crypt32: Set an output parameter on the success path.
[wine] / dlls / crypt32 / chain.c
1 /*
2  * Copyright 2006 Juan Lang
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  *
18  */
19 #include <stdarg.h>
20 #define NONAMELESSUNION
21 #include "windef.h"
22 #include "winbase.h"
23 #define CERT_CHAIN_PARA_HAS_EXTRA_FIELDS
24 #define CERT_REVOCATION_PARA_HAS_EXTRA_FIELDS
25 #include "wincrypt.h"
26 #include "wine/debug.h"
27 #include "wine/unicode.h"
28 #include "crypt32_private.h"
29
30 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
31 WINE_DECLARE_DEBUG_CHANNEL(chain);
32
33 #define DEFAULT_CYCLE_MODULUS 7
34
35 static HCERTCHAINENGINE CRYPT_defaultChainEngine;
36
37 /* This represents a subset of a certificate chain engine:  it doesn't include
38  * the "hOther" store described by MSDN, because I'm not sure how that's used.
39  * It also doesn't include the "hTrust" store, because I don't yet implement
40  * CTLs or complex certificate chains.
41  */
42 typedef struct _CertificateChainEngine
43 {
44     LONG       ref;
45     HCERTSTORE hRoot;
46     HCERTSTORE hWorld;
47     DWORD      dwFlags;
48     DWORD      dwUrlRetrievalTimeout;
49     DWORD      MaximumCachedCertificates;
50     DWORD      CycleDetectionModulus;
51 } CertificateChainEngine, *PCertificateChainEngine;
52
53 static inline void CRYPT_AddStoresToCollection(HCERTSTORE collection,
54  DWORD cStores, HCERTSTORE *stores)
55 {
56     DWORD i;
57
58     for (i = 0; i < cStores; i++)
59         CertAddStoreToCollection(collection, stores[i], 0, 0);
60 }
61
62 static inline void CRYPT_CloseStores(DWORD cStores, HCERTSTORE *stores)
63 {
64     DWORD i;
65
66     for (i = 0; i < cStores; i++)
67         CertCloseStore(stores[i], 0);
68 }
69
70 static const WCHAR rootW[] = { 'R','o','o','t',0 };
71
72 static BOOL CRYPT_CheckRestrictedRoot(HCERTSTORE store)
73 {
74     BOOL ret = TRUE;
75
76     if (store)
77     {
78         HCERTSTORE rootStore = CertOpenSystemStoreW(0, rootW);
79         PCCERT_CONTEXT cert = NULL, check;
80         BYTE hash[20];
81         DWORD size;
82
83         do {
84             cert = CertEnumCertificatesInStore(store, cert);
85             if (cert)
86             {
87                 size = sizeof(hash);
88
89                 ret = CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID,
90                  hash, &size);
91                 if (ret)
92                 {
93                     CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
94
95                     check = CertFindCertificateInStore(rootStore,
96                      cert->dwCertEncodingType, 0, CERT_FIND_SHA1_HASH, &blob,
97                      NULL);
98                     if (!check)
99                         ret = FALSE;
100                     else
101                         CertFreeCertificateContext(check);
102                 }
103             }
104         } while (ret && cert);
105         if (cert)
106             CertFreeCertificateContext(cert);
107         CertCloseStore(rootStore, 0);
108     }
109     return ret;
110 }
111
112 HCERTCHAINENGINE CRYPT_CreateChainEngine(HCERTSTORE root,
113  PCERT_CHAIN_ENGINE_CONFIG pConfig)
114 {
115     static const WCHAR caW[] = { 'C','A',0 };
116     static const WCHAR myW[] = { 'M','y',0 };
117     static const WCHAR trustW[] = { 'T','r','u','s','t',0 };
118     PCertificateChainEngine engine =
119      CryptMemAlloc(sizeof(CertificateChainEngine));
120
121     if (engine)
122     {
123         HCERTSTORE worldStores[4];
124
125         engine->ref = 1;
126         engine->hRoot = root;
127         engine->hWorld = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
128          CERT_STORE_CREATE_NEW_FLAG, NULL);
129         worldStores[0] = CertDuplicateStore(engine->hRoot);
130         worldStores[1] = CertOpenSystemStoreW(0, caW);
131         worldStores[2] = CertOpenSystemStoreW(0, myW);
132         worldStores[3] = CertOpenSystemStoreW(0, trustW);
133         CRYPT_AddStoresToCollection(engine->hWorld,
134          sizeof(worldStores) / sizeof(worldStores[0]), worldStores);
135         CRYPT_AddStoresToCollection(engine->hWorld,
136          pConfig->cAdditionalStore, pConfig->rghAdditionalStore);
137         CRYPT_CloseStores(sizeof(worldStores) / sizeof(worldStores[0]),
138          worldStores);
139         engine->dwFlags = pConfig->dwFlags;
140         engine->dwUrlRetrievalTimeout = pConfig->dwUrlRetrievalTimeout;
141         engine->MaximumCachedCertificates =
142          pConfig->MaximumCachedCertificates;
143         if (pConfig->CycleDetectionModulus)
144             engine->CycleDetectionModulus = pConfig->CycleDetectionModulus;
145         else
146             engine->CycleDetectionModulus = DEFAULT_CYCLE_MODULUS;
147     }
148     return engine;
149 }
150
151 BOOL WINAPI CertCreateCertificateChainEngine(PCERT_CHAIN_ENGINE_CONFIG pConfig,
152  HCERTCHAINENGINE *phChainEngine)
153 {
154     BOOL ret;
155
156     TRACE("(%p, %p)\n", pConfig, phChainEngine);
157
158     if (pConfig->cbSize != sizeof(*pConfig))
159     {
160         SetLastError(E_INVALIDARG);
161         return FALSE;
162     }
163     *phChainEngine = NULL;
164     ret = CRYPT_CheckRestrictedRoot(pConfig->hRestrictedRoot);
165     if (ret)
166     {
167         HCERTSTORE root;
168         HCERTCHAINENGINE engine;
169
170         if (pConfig->hRestrictedRoot)
171             root = CertDuplicateStore(pConfig->hRestrictedRoot);
172         else
173             root = CertOpenSystemStoreW(0, rootW);
174         engine = CRYPT_CreateChainEngine(root, pConfig);
175         if (engine)
176         {
177             *phChainEngine = engine;
178             ret = TRUE;
179         }
180         else
181             ret = FALSE;
182     }
183     return ret;
184 }
185
186 VOID WINAPI CertFreeCertificateChainEngine(HCERTCHAINENGINE hChainEngine)
187 {
188     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
189
190     TRACE("(%p)\n", hChainEngine);
191
192     if (engine && InterlockedDecrement(&engine->ref) == 0)
193     {
194         CertCloseStore(engine->hWorld, 0);
195         CertCloseStore(engine->hRoot, 0);
196         CryptMemFree(engine);
197     }
198 }
199
200 static HCERTCHAINENGINE CRYPT_GetDefaultChainEngine(void)
201 {
202     if (!CRYPT_defaultChainEngine)
203     {
204         CERT_CHAIN_ENGINE_CONFIG config = { 0 };
205         HCERTCHAINENGINE engine;
206
207         config.cbSize = sizeof(config);
208         CertCreateCertificateChainEngine(&config, &engine);
209         InterlockedCompareExchangePointer(&CRYPT_defaultChainEngine, engine,
210          NULL);
211         if (CRYPT_defaultChainEngine != engine)
212             CertFreeCertificateChainEngine(engine);
213     }
214     return CRYPT_defaultChainEngine;
215 }
216
217 void default_chain_engine_free(void)
218 {
219     CertFreeCertificateChainEngine(CRYPT_defaultChainEngine);
220 }
221
222 typedef struct _CertificateChain
223 {
224     CERT_CHAIN_CONTEXT context;
225     HCERTSTORE world;
226     LONG ref;
227 } CertificateChain, *PCertificateChain;
228
229 static inline BOOL CRYPT_IsCertificateSelfSigned(PCCERT_CONTEXT cert)
230 {
231     return CertCompareCertificateName(cert->dwCertEncodingType,
232      &cert->pCertInfo->Subject, &cert->pCertInfo->Issuer);
233 }
234
235 static void CRYPT_FreeChainElement(PCERT_CHAIN_ELEMENT element)
236 {
237     CertFreeCertificateContext(element->pCertContext);
238     CryptMemFree(element);
239 }
240
241 static void CRYPT_CheckSimpleChainForCycles(PCERT_SIMPLE_CHAIN chain)
242 {
243     DWORD i, j, cyclicCertIndex = 0;
244
245     /* O(n^2) - I don't think there's a faster way */
246     for (i = 0; !cyclicCertIndex && i < chain->cElement; i++)
247         for (j = i + 1; !cyclicCertIndex && j < chain->cElement; j++)
248             if (CertCompareCertificate(X509_ASN_ENCODING,
249              chain->rgpElement[i]->pCertContext->pCertInfo,
250              chain->rgpElement[j]->pCertContext->pCertInfo))
251                 cyclicCertIndex = j;
252     if (cyclicCertIndex)
253     {
254         chain->rgpElement[cyclicCertIndex]->TrustStatus.dwErrorStatus
255          |= CERT_TRUST_IS_CYCLIC | CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
256         /* Release remaining certs */
257         for (i = cyclicCertIndex + 1; i < chain->cElement; i++)
258             CRYPT_FreeChainElement(chain->rgpElement[i]);
259         /* Truncate chain */
260         chain->cElement = cyclicCertIndex + 1;
261     }
262 }
263
264 /* Checks whether the chain is cyclic by examining the last element's status */
265 static inline BOOL CRYPT_IsSimpleChainCyclic(const CERT_SIMPLE_CHAIN *chain)
266 {
267     if (chain->cElement)
268         return chain->rgpElement[chain->cElement - 1]->TrustStatus.dwErrorStatus
269          & CERT_TRUST_IS_CYCLIC;
270     else
271         return FALSE;
272 }
273
274 static inline void CRYPT_CombineTrustStatus(CERT_TRUST_STATUS *chainStatus,
275  const CERT_TRUST_STATUS *elementStatus)
276 {
277     /* Any error that applies to an element also applies to a chain.. */
278     chainStatus->dwErrorStatus |= elementStatus->dwErrorStatus;
279     /* but the bottom nibble of an element's info status doesn't apply to the
280      * chain.
281      */
282     chainStatus->dwInfoStatus |= (elementStatus->dwInfoStatus & 0xfffffff0);
283 }
284
285 static BOOL CRYPT_AddCertToSimpleChain(const CertificateChainEngine *engine,
286  PCERT_SIMPLE_CHAIN chain, PCCERT_CONTEXT cert, DWORD subjectInfoStatus)
287 {
288     BOOL ret = FALSE;
289     PCERT_CHAIN_ELEMENT element = CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
290
291     if (element)
292     {
293         if (!chain->cElement)
294             chain->rgpElement = CryptMemAlloc(sizeof(PCERT_CHAIN_ELEMENT));
295         else
296             chain->rgpElement = CryptMemRealloc(chain->rgpElement,
297              (chain->cElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
298         if (chain->rgpElement)
299         {
300             chain->rgpElement[chain->cElement++] = element;
301             memset(element, 0, sizeof(CERT_CHAIN_ELEMENT));
302             element->cbSize = sizeof(CERT_CHAIN_ELEMENT);
303             element->pCertContext = CertDuplicateCertificateContext(cert);
304             if (chain->cElement > 1)
305                 chain->rgpElement[chain->cElement - 2]->TrustStatus.dwInfoStatus
306                  = subjectInfoStatus;
307             /* FIXME: initialize the rest of element */
308             if (!(chain->cElement % engine->CycleDetectionModulus))
309             {
310                 CRYPT_CheckSimpleChainForCycles(chain);
311                 /* Reinitialize the element pointer in case the chain is
312                  * cyclic, in which case the chain is truncated.
313                  */
314                 element = chain->rgpElement[chain->cElement - 1];
315             }
316             CRYPT_CombineTrustStatus(&chain->TrustStatus,
317              &element->TrustStatus);
318             ret = TRUE;
319         }
320         else
321             CryptMemFree(element);
322     }
323     return ret;
324 }
325
326 static void CRYPT_FreeSimpleChain(PCERT_SIMPLE_CHAIN chain)
327 {
328     DWORD i;
329
330     for (i = 0; i < chain->cElement; i++)
331         CRYPT_FreeChainElement(chain->rgpElement[i]);
332     CryptMemFree(chain->rgpElement);
333     CryptMemFree(chain);
334 }
335
336 static void CRYPT_CheckTrustedStatus(HCERTSTORE hRoot,
337  PCERT_CHAIN_ELEMENT rootElement)
338 {
339     BYTE hash[20];
340     DWORD size = sizeof(hash);
341     CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
342     PCCERT_CONTEXT trustedRoot;
343
344     CertGetCertificateContextProperty(rootElement->pCertContext,
345      CERT_HASH_PROP_ID, hash, &size);
346     trustedRoot = CertFindCertificateInStore(hRoot,
347      rootElement->pCertContext->dwCertEncodingType, 0, CERT_FIND_SHA1_HASH,
348      &blob, NULL);
349     if (!trustedRoot)
350         rootElement->TrustStatus.dwErrorStatus |=
351          CERT_TRUST_IS_UNTRUSTED_ROOT;
352     else
353         CertFreeCertificateContext(trustedRoot);
354 }
355
356 static void CRYPT_CheckRootCert(HCERTCHAINENGINE hRoot,
357  PCERT_CHAIN_ELEMENT rootElement)
358 {
359     PCCERT_CONTEXT root = rootElement->pCertContext;
360
361     if (!CryptVerifyCertificateSignatureEx(0, root->dwCertEncodingType,
362      CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, (void *)root,
363      CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, (void *)root, 0, NULL))
364     {
365         TRACE_(chain)("Last certificate's signature is invalid\n");
366         rootElement->TrustStatus.dwErrorStatus |=
367          CERT_TRUST_IS_NOT_SIGNATURE_VALID;
368     }
369     CRYPT_CheckTrustedStatus(hRoot, rootElement);
370 }
371
372 /* Decodes a cert's basic constraints extension (either szOID_BASIC_CONSTRAINTS
373  * or szOID_BASIC_CONSTRAINTS2, whichever is present) into a
374  * CERT_BASIC_CONSTRAINTS2_INFO.  If it neither extension is present, sets
375  * constraints->fCA to defaultIfNotSpecified.
376  * Returns FALSE if the extension is present but couldn't be decoded.
377  */
378 static BOOL CRYPT_DecodeBasicConstraints(PCCERT_CONTEXT cert,
379  CERT_BASIC_CONSTRAINTS2_INFO *constraints, BOOL defaultIfNotSpecified)
380 {
381     BOOL ret = TRUE;
382     PCERT_EXTENSION ext = CertFindExtension(szOID_BASIC_CONSTRAINTS,
383      cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
384
385     constraints->fPathLenConstraint = FALSE;
386     if (ext)
387     {
388         CERT_BASIC_CONSTRAINTS_INFO *info;
389         DWORD size = 0;
390
391         ret = CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
392          ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
393          NULL, &info, &size);
394         if (ret)
395         {
396             if (info->SubjectType.cbData == 1)
397                 constraints->fCA =
398                  info->SubjectType.pbData[0] & CERT_CA_SUBJECT_FLAG;
399             LocalFree(info);
400         }
401     }
402     else
403     {
404         ext = CertFindExtension(szOID_BASIC_CONSTRAINTS2,
405          cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
406         if (ext)
407         {
408             DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
409
410             ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
411              szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
412              0, NULL, constraints, &size);
413         }
414         else
415             constraints->fCA = defaultIfNotSpecified;
416     }
417     return ret;
418 }
419
420 /* Checks element's basic constraints to see if it can act as a CA, with
421  * remainingCAs CAs left in this chain.  A root certificate is assumed to be
422  * allowed to be a CA whether or not the basic constraints extension is present,
423  * whereas an intermediate CA cert is not.  This matches the expected usage in
424  * RFC 3280:  a conforming intermediate CA MUST contain the basic constraints
425  * extension.  It also appears to match Microsoft's implementation.
426  * Updates chainConstraints with the element's constraints, if:
427  * 1. chainConstraints doesn't have a path length constraint, or
428  * 2. element's path length constraint is smaller than chainConstraints's
429  * Sets *pathLengthConstraintViolated to TRUE if a path length violation
430  * occurs.
431  * Returns TRUE if the element can be a CA, and the length of the remaining
432  * chain is valid.
433  */
434 static BOOL CRYPT_CheckBasicConstraintsForCA(PCCERT_CONTEXT cert,
435  CERT_BASIC_CONSTRAINTS2_INFO *chainConstraints, DWORD remainingCAs,
436  BOOL isRoot, BOOL *pathLengthConstraintViolated)
437 {
438     BOOL validBasicConstraints;
439     CERT_BASIC_CONSTRAINTS2_INFO constraints;
440
441     if ((validBasicConstraints = CRYPT_DecodeBasicConstraints(cert,
442      &constraints, isRoot)))
443     {
444         if (!constraints.fCA)
445         {
446             TRACE_(chain)("chain element %d can't be a CA\n", remainingCAs + 1);
447             validBasicConstraints = FALSE;
448         }
449         else if (constraints.fPathLenConstraint)
450         {
451             /* If the element has path length constraints, they apply to the
452              * entire remaining chain.
453              */
454             if (!chainConstraints->fPathLenConstraint ||
455              constraints.dwPathLenConstraint <
456              chainConstraints->dwPathLenConstraint)
457             {
458                 TRACE_(chain)("setting path length constraint to %d\n",
459                  chainConstraints->dwPathLenConstraint);
460                 chainConstraints->fPathLenConstraint = TRUE;
461                 chainConstraints->dwPathLenConstraint =
462                  constraints.dwPathLenConstraint;
463             }
464         }
465     }
466     if (chainConstraints->fPathLenConstraint &&
467      remainingCAs > chainConstraints->dwPathLenConstraint)
468     {
469         TRACE_(chain)("remaining CAs %d exceed max path length %d\n",
470          remainingCAs, chainConstraints->dwPathLenConstraint);
471         validBasicConstraints = FALSE;
472         *pathLengthConstraintViolated = TRUE;
473     }
474     return validBasicConstraints;
475 }
476
477 static BOOL url_matches(LPCWSTR constraint, LPCWSTR name,
478  DWORD *trustErrorStatus)
479 {
480     BOOL match = FALSE;
481
482     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
483
484     if (!constraint)
485         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
486     else if (!name)
487         ; /* no match */
488     else if (constraint[0] == '.')
489     {
490         if (lstrlenW(name) > lstrlenW(constraint))
491             match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
492              constraint);
493     }
494     else
495         match = !lstrcmpiW(constraint, name);
496     return match;
497 }
498
499 static BOOL rfc822_name_matches(LPCWSTR constraint, LPCWSTR name,
500  DWORD *trustErrorStatus)
501 {
502     BOOL match = FALSE;
503     LPCWSTR at;
504
505     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
506
507     if (!constraint)
508         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
509     else if (!name)
510         ; /* no match */
511     else if ((at = strchrW(constraint, '@')))
512         match = !lstrcmpiW(constraint, name);
513     else
514     {
515         if ((at = strchrW(name, '@')))
516             match = url_matches(constraint, at + 1, trustErrorStatus);
517         else
518             match = !lstrcmpiW(constraint, name);
519     }
520     return match;
521 }
522
523 static BOOL dns_name_matches(LPCWSTR constraint, LPCWSTR name,
524  DWORD *trustErrorStatus)
525 {
526     BOOL match = FALSE;
527
528     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
529
530     if (!constraint)
531         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
532     else if (!name)
533         ; /* no match */
534     else if (lstrlenW(name) >= lstrlenW(constraint))
535         match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
536          constraint);
537     /* else:  name is too short, no match */
538
539     return match;
540 }
541
542 static BOOL ip_address_matches(const CRYPT_DATA_BLOB *constraint,
543  const CRYPT_DATA_BLOB *name, DWORD *trustErrorStatus)
544 {
545     BOOL match = FALSE;
546
547     TRACE("(%d, %p), (%d, %p)\n", constraint->cbData, constraint->pbData,
548      name->cbData, name->pbData);
549
550     if (constraint->cbData != sizeof(DWORD) * 2)
551         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
552     else if (name->cbData == sizeof(DWORD))
553     {
554         DWORD subnet, mask, addr;
555
556         memcpy(&subnet, constraint->pbData, sizeof(subnet));
557         memcpy(&mask, constraint->pbData + sizeof(subnet), sizeof(mask));
558         memcpy(&addr, name->pbData, sizeof(addr));
559         /* These are really in big-endian order, but for equality matching we
560          * don't need to swap to host order
561          */
562         match = (subnet & mask) == (addr & mask);
563     }
564     /* else: name is wrong size, no match */
565
566     return match;
567 }
568
569 static void CRYPT_FindMatchingNameEntry(const CERT_ALT_NAME_ENTRY *constraint,
570  const CERT_ALT_NAME_INFO *subjectName, DWORD *trustErrorStatus,
571  DWORD errorIfFound, DWORD errorIfNotFound)
572 {
573     DWORD i;
574     BOOL match = FALSE;
575
576     for (i = 0; i < subjectName->cAltEntry; i++)
577     {
578         if (subjectName->rgAltEntry[i].dwAltNameChoice ==
579          constraint->dwAltNameChoice)
580         {
581             switch (constraint->dwAltNameChoice)
582             {
583             case CERT_ALT_NAME_RFC822_NAME:
584                 match = rfc822_name_matches(constraint->u.pwszURL,
585                  subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
586                 break;
587             case CERT_ALT_NAME_DNS_NAME:
588                 match = dns_name_matches(constraint->u.pwszURL,
589                  subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
590                 break;
591             case CERT_ALT_NAME_URL:
592                 match = url_matches(constraint->u.pwszURL,
593                  subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
594                 break;
595             case CERT_ALT_NAME_IP_ADDRESS:
596                 match = ip_address_matches(&constraint->u.IPAddress,
597                  &subjectName->rgAltEntry[i].u.IPAddress, trustErrorStatus);
598                 break;
599             case CERT_ALT_NAME_DIRECTORY_NAME:
600             default:
601                 ERR("name choice %d unsupported in this context\n",
602                  constraint->dwAltNameChoice);
603                 *trustErrorStatus |=
604                  CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
605             }
606         }
607     }
608     *trustErrorStatus |= match ? errorIfFound : errorIfNotFound;
609 }
610
611 static void CRYPT_CheckNameConstraints(
612  const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, const CERT_INFO *cert,
613  DWORD *trustErrorStatus)
614 {
615     /* If there aren't any existing constraints, don't bother checking */
616     if (nameConstraints->cPermittedSubtree || nameConstraints->cExcludedSubtree)
617     {
618         CERT_EXTENSION *ext;
619
620         if ((ext = CertFindExtension(szOID_SUBJECT_ALT_NAME, cert->cExtension,
621          cert->rgExtension)))
622         {
623             CERT_ALT_NAME_INFO *subjectName;
624             DWORD size;
625
626             if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
627              ext->Value.pbData, ext->Value.cbData,
628              CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
629              &subjectName, &size))
630             {
631                 DWORD i;
632
633                 for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
634                     CRYPT_FindMatchingNameEntry(
635                      &nameConstraints->rgExcludedSubtree[i].Base, subjectName,
636                      trustErrorStatus,
637                      CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT, 0);
638                 for (i = 0; i < nameConstraints->cPermittedSubtree; i++)
639                     CRYPT_FindMatchingNameEntry(
640                      &nameConstraints->rgPermittedSubtree[i].Base, subjectName,
641                      trustErrorStatus,
642                      0, CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT);
643                 LocalFree(subjectName);
644             }
645         }
646         else
647         {
648             if (nameConstraints->cPermittedSubtree)
649                 *trustErrorStatus |=
650                  CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
651             if (nameConstraints->cExcludedSubtree)
652                 *trustErrorStatus |=
653                  CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
654         }
655     }
656 }
657
658 /* Gets cert's name constraints, if any.  Free with LocalFree. */
659 static CERT_NAME_CONSTRAINTS_INFO *CRYPT_GetNameConstraints(CERT_INFO *cert)
660 {
661     CERT_NAME_CONSTRAINTS_INFO *info = NULL;
662
663     CERT_EXTENSION *ext;
664
665     if ((ext = CertFindExtension(szOID_NAME_CONSTRAINTS, cert->cExtension,
666      cert->rgExtension)))
667     {
668         DWORD size;
669
670         CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
671          ext->Value.pbData, ext->Value.cbData,
672          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &info,
673          &size);
674     }
675     return info;
676 }
677
678 static void CRYPT_CheckChainNameConstraints(PCERT_SIMPLE_CHAIN chain)
679 {
680     int i, j;
681
682     /* Microsoft's implementation appears to violate RFC 3280:  according to
683      * MSDN, the various CERT_TRUST_*_NAME_CONSTRAINT errors are set if a CA's
684      * name constraint is violated in the end cert.  According to RFC 3280,
685      * the constraints should be checked against every subsequent certificate
686      * in the chain, not just the end cert.
687      * Microsoft's implementation also sets the name constraint errors on the
688      * certs whose constraints were violated, not on the certs that violated
689      * them.
690      * In order to be error-compatible with Microsoft's implementation, while
691      * still adhering to RFC 3280, I use a O(n ^ 2) algorithm to check name
692      * constraints.
693      */
694     for (i = chain->cElement - 1; i > 0; i--)
695     {
696         CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
697
698         if ((nameConstraints = CRYPT_GetNameConstraints(
699          chain->rgpElement[i]->pCertContext->pCertInfo)))
700         {
701             for (j = i - 1; j >= 0; j--)
702             {
703                 DWORD errorStatus = 0;
704
705                 /* According to RFC 3280, self-signed certs don't have name
706                  * constraints checked unless they're the end cert.
707                  */
708                 if (j == 0 || !CRYPT_IsCertificateSelfSigned(
709                  chain->rgpElement[j]->pCertContext))
710                 {
711                     CRYPT_CheckNameConstraints(nameConstraints,
712                      chain->rgpElement[i]->pCertContext->pCertInfo,
713                      &errorStatus);
714                     chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
715                      errorStatus;
716                 }
717             }
718             LocalFree(nameConstraints);
719         }
720     }
721 }
722
723 static void dump_basic_constraints(const CERT_EXTENSION *ext)
724 {
725     CERT_BASIC_CONSTRAINTS_INFO *info;
726     DWORD size = 0;
727
728     if (CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
729      ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
730      NULL, &info, &size))
731     {
732         TRACE_(chain)("SubjectType: %02x\n", info->SubjectType.pbData[0]);
733         TRACE_(chain)("%s path length constraint\n",
734          info->fPathLenConstraint ? "has" : "doesn't have");
735         TRACE_(chain)("path length=%d\n", info->dwPathLenConstraint);
736         LocalFree(info);
737     }
738 }
739
740 static void dump_basic_constraints2(const CERT_EXTENSION *ext)
741 {
742     CERT_BASIC_CONSTRAINTS2_INFO constraints;
743     DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
744
745     if (CryptDecodeObjectEx(X509_ASN_ENCODING,
746      szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
747      0, NULL, &constraints, &size))
748     {
749         TRACE_(chain)("basic constraints:\n");
750         TRACE_(chain)("can%s be a CA\n", constraints.fCA ? "" : "not");
751         TRACE_(chain)("%s path length constraint\n",
752          constraints.fPathLenConstraint ? "has" : "doesn't have");
753         TRACE_(chain)("path length=%d\n", constraints.dwPathLenConstraint);
754     }
755 }
756
757 static void dump_extension(const CERT_EXTENSION *ext)
758 {
759     TRACE_(chain)("%s (%scritical)\n", debugstr_a(ext->pszObjId),
760      ext->fCritical ? "" : "not ");
761     if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS))
762         dump_basic_constraints(ext);
763     else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS2))
764         dump_basic_constraints2(ext);
765 }
766
767 static LPCWSTR filetime_to_str(const FILETIME *time)
768 {
769     static WCHAR date[80];
770     WCHAR dateFmt[80]; /* sufficient for all versions of LOCALE_SSHORTDATE */
771     SYSTEMTIME sysTime;
772
773     if (!time) return NULL;
774
775     GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, dateFmt,
776      sizeof(dateFmt) / sizeof(dateFmt[0]));
777     FileTimeToSystemTime(time, &sysTime);
778     GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, date,
779      sizeof(date) / sizeof(date[0]));
780     return date;
781 }
782
783 static void dump_element(PCCERT_CONTEXT cert)
784 {
785     LPWSTR name = NULL;
786     DWORD len, i;
787
788     TRACE_(chain)("%p\n", cert);
789     len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
790      CERT_NAME_ISSUER_FLAG, NULL, NULL, 0);
791     name = CryptMemAlloc(len * sizeof(WCHAR));
792     if (name)
793     {
794         CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
795          CERT_NAME_ISSUER_FLAG, NULL, name, len);
796         TRACE_(chain)("issued by %s\n", debugstr_w(name));
797         CryptMemFree(name);
798     }
799     len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
800      NULL, 0);
801     name = CryptMemAlloc(len * sizeof(WCHAR));
802     if (name)
803     {
804         CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
805          name, len);
806         TRACE_(chain)("issued to %s\n", debugstr_w(name));
807         CryptMemFree(name);
808     }
809     TRACE_(chain)("valid from %s to %s\n",
810      debugstr_w(filetime_to_str(&cert->pCertInfo->NotBefore)),
811      debugstr_w(filetime_to_str(&cert->pCertInfo->NotAfter)));
812     TRACE_(chain)("%d extensions\n", cert->pCertInfo->cExtension);
813     for (i = 0; i < cert->pCertInfo->cExtension; i++)
814         dump_extension(&cert->pCertInfo->rgExtension[i]);
815 }
816
817 static BOOL CRYPT_CriticalExtensionsSupported(PCCERT_CONTEXT cert)
818 {
819     BOOL ret = TRUE;
820     DWORD i;
821
822     for (i = 0; ret && i < cert->pCertInfo->cExtension; i++)
823     {
824         if (cert->pCertInfo->rgExtension[i].fCritical)
825         {
826             LPCSTR oid = cert->pCertInfo->rgExtension[i].pszObjId;
827
828             if (!strcmp(oid, szOID_BASIC_CONSTRAINTS))
829                 ret = TRUE;
830             else if (!strcmp(oid, szOID_BASIC_CONSTRAINTS2))
831                 ret = TRUE;
832             else if (!strcmp(oid, szOID_NAME_CONSTRAINTS))
833                 ret = TRUE;
834             else if (!strcmp(oid, szOID_KEY_USAGE))
835             {
836                 static int warned;
837
838                 if (!warned++)
839                     FIXME("key usage extension unsupported, ignoring\n");
840                 ret = TRUE;
841             }
842             else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME))
843                 ret = TRUE;
844             else
845             {
846                 FIXME("unsupported critical extension %s\n",
847                  debugstr_a(oid));
848                 ret = FALSE;
849             }
850         }
851     }
852     return ret;
853 }
854
855 static void CRYPT_CheckSimpleChain(PCertificateChainEngine engine,
856  PCERT_SIMPLE_CHAIN chain, LPFILETIME time)
857 {
858     PCERT_CHAIN_ELEMENT rootElement = chain->rgpElement[chain->cElement - 1];
859     int i;
860     BOOL pathLengthConstraintViolated = FALSE;
861     CERT_BASIC_CONSTRAINTS2_INFO constraints = { TRUE, FALSE, 0 };
862
863     TRACE_(chain)("checking chain with %d elements for time %s\n",
864      chain->cElement, debugstr_w(filetime_to_str(time)));
865     for (i = chain->cElement - 1; i >= 0; i--)
866     {
867         if (TRACE_ON(chain))
868             dump_element(chain->rgpElement[i]->pCertContext);
869         if (CertVerifyTimeValidity(time,
870          chain->rgpElement[i]->pCertContext->pCertInfo) != 0)
871             chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
872              CERT_TRUST_IS_NOT_TIME_VALID;
873         if (i != 0)
874         {
875             BOOL isRoot;
876
877             if (i == chain->cElement - 1)
878                 isRoot = CRYPT_IsCertificateSelfSigned(
879                  chain->rgpElement[i]->pCertContext);
880             else
881                 isRoot = FALSE;
882             /* Check the signature of the cert this issued */
883             if (!CryptVerifyCertificateSignatureEx(0, X509_ASN_ENCODING,
884              CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT,
885              (void *)chain->rgpElement[i - 1]->pCertContext,
886              CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT,
887              (void *)chain->rgpElement[i]->pCertContext, 0, NULL))
888                 chain->rgpElement[i - 1]->TrustStatus.dwErrorStatus |=
889                  CERT_TRUST_IS_NOT_SIGNATURE_VALID;
890             /* Once a path length constraint has been violated, every remaining
891              * CA cert's basic constraints is considered invalid.
892              */
893             if (pathLengthConstraintViolated)
894                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
895                  CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
896             else if (!CRYPT_CheckBasicConstraintsForCA(
897              chain->rgpElement[i]->pCertContext, &constraints, i - 1,
898              isRoot, &pathLengthConstraintViolated))
899                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
900                  CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
901             else if (constraints.fPathLenConstraint &&
902              constraints.dwPathLenConstraint)
903             {
904                 /* This one's valid - decrement max length */
905                 constraints.dwPathLenConstraint--;
906             }
907         }
908         if (CRYPT_IsSimpleChainCyclic(chain))
909         {
910             /* If the chain is cyclic, then the path length constraints
911              * are violated, because the chain is infinitely long.
912              */
913             pathLengthConstraintViolated = TRUE;
914             chain->TrustStatus.dwErrorStatus |=
915              CERT_TRUST_IS_PARTIAL_CHAIN |
916              CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
917         }
918         /* FIXME: check valid usages */
919         /* Check whether every critical extension is supported */
920         if (!CRYPT_CriticalExtensionsSupported(
921          chain->rgpElement[i]->pCertContext))
922             chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
923              CERT_TRUST_INVALID_EXTENSION;
924         CRYPT_CombineTrustStatus(&chain->TrustStatus,
925          &chain->rgpElement[i]->TrustStatus);
926     }
927     CRYPT_CheckChainNameConstraints(chain);
928     if (CRYPT_IsCertificateSelfSigned(rootElement->pCertContext))
929     {
930         rootElement->TrustStatus.dwInfoStatus |=
931          CERT_TRUST_IS_SELF_SIGNED | CERT_TRUST_HAS_NAME_MATCH_ISSUER;
932         CRYPT_CheckRootCert(engine->hRoot, rootElement);
933     }
934     CRYPT_CombineTrustStatus(&chain->TrustStatus, &rootElement->TrustStatus);
935 }
936
937 static PCCERT_CONTEXT CRYPT_GetIssuer(HCERTSTORE store, PCCERT_CONTEXT subject,
938  PCCERT_CONTEXT prevIssuer, DWORD *infoStatus)
939 {
940     PCCERT_CONTEXT issuer = NULL;
941     PCERT_EXTENSION ext;
942     DWORD size;
943
944     *infoStatus = 0;
945     if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
946      subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
947     {
948         CERT_AUTHORITY_KEY_ID_INFO *info;
949         BOOL ret;
950
951         ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
952          X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
953          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
954          &info, &size);
955         if (ret)
956         {
957             CERT_ID id;
958
959             if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
960             {
961                 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
962                 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
963                  sizeof(CERT_NAME_BLOB));
964                 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
965                  &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
966                 issuer = CertFindCertificateInStore(store,
967                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
968                  prevIssuer);
969                 if (issuer)
970                     *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
971             }
972             else if (info->KeyId.cbData)
973             {
974                 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
975                 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
976                 issuer = CertFindCertificateInStore(store,
977                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
978                  prevIssuer);
979                 if (issuer)
980                     *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
981             }
982             LocalFree(info);
983         }
984     }
985     else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
986      subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
987     {
988         CERT_AUTHORITY_KEY_ID2_INFO *info;
989         BOOL ret;
990
991         ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
992          X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
993          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
994          &info, &size);
995         if (ret)
996         {
997             CERT_ID id;
998
999             if (info->AuthorityCertIssuer.cAltEntry &&
1000              info->AuthorityCertSerialNumber.cbData)
1001             {
1002                 PCERT_ALT_NAME_ENTRY directoryName = NULL;
1003                 DWORD i;
1004
1005                 for (i = 0; !directoryName &&
1006                  i < info->AuthorityCertIssuer.cAltEntry; i++)
1007                     if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
1008                      == CERT_ALT_NAME_DIRECTORY_NAME)
1009                         directoryName =
1010                          &info->AuthorityCertIssuer.rgAltEntry[i];
1011                 if (directoryName)
1012                 {
1013                     id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1014                     memcpy(&id.u.IssuerSerialNumber.Issuer,
1015                      &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
1016                     memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1017                      &info->AuthorityCertSerialNumber,
1018                      sizeof(CRYPT_INTEGER_BLOB));
1019                     issuer = CertFindCertificateInStore(store,
1020                      subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1021                      prevIssuer);
1022                     if (issuer)
1023                         *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
1024                 }
1025                 else
1026                     FIXME("no supported name type in authority key id2\n");
1027             }
1028             else if (info->KeyId.cbData)
1029             {
1030                 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1031                 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1032                 issuer = CertFindCertificateInStore(store,
1033                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1034                  prevIssuer);
1035                 if (issuer)
1036                     *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
1037             }
1038             LocalFree(info);
1039         }
1040     }
1041     else
1042     {
1043         issuer = CertFindCertificateInStore(store,
1044          subject->dwCertEncodingType, 0, CERT_FIND_SUBJECT_NAME,
1045          &subject->pCertInfo->Issuer, prevIssuer);
1046         *infoStatus = CERT_TRUST_HAS_NAME_MATCH_ISSUER;
1047     }
1048     return issuer;
1049 }
1050
1051 /* Builds a simple chain by finding an issuer for the last cert in the chain,
1052  * until reaching a self-signed cert, or until no issuer can be found.
1053  */
1054 static BOOL CRYPT_BuildSimpleChain(const CertificateChainEngine *engine,
1055  HCERTSTORE world, PCERT_SIMPLE_CHAIN chain)
1056 {
1057     BOOL ret = TRUE;
1058     PCCERT_CONTEXT cert = chain->rgpElement[chain->cElement - 1]->pCertContext;
1059
1060     while (ret && !CRYPT_IsSimpleChainCyclic(chain) &&
1061      !CRYPT_IsCertificateSelfSigned(cert))
1062     {
1063         PCCERT_CONTEXT issuer = CRYPT_GetIssuer(world, cert, NULL,
1064          &chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
1065
1066         if (issuer)
1067         {
1068             ret = CRYPT_AddCertToSimpleChain(engine, chain, issuer,
1069              chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
1070             /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it to
1071              * close the enumeration that found it
1072              */
1073             CertFreeCertificateContext(issuer);
1074             cert = issuer;
1075         }
1076         else
1077         {
1078             TRACE_(chain)("Couldn't find issuer, halting chain creation\n");
1079             chain->TrustStatus.dwErrorStatus |= CERT_TRUST_IS_PARTIAL_CHAIN;
1080             break;
1081         }
1082     }
1083     return ret;
1084 }
1085
1086 static BOOL CRYPT_GetSimpleChainForCert(PCertificateChainEngine engine,
1087  HCERTSTORE world, PCCERT_CONTEXT cert, LPFILETIME pTime,
1088  PCERT_SIMPLE_CHAIN *ppChain)
1089 {
1090     BOOL ret = FALSE;
1091     PCERT_SIMPLE_CHAIN chain;
1092
1093     TRACE("(%p, %p, %p, %p)\n", engine, world, cert, pTime);
1094
1095     chain = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
1096     if (chain)
1097     {
1098         memset(chain, 0, sizeof(CERT_SIMPLE_CHAIN));
1099         chain->cbSize = sizeof(CERT_SIMPLE_CHAIN);
1100         ret = CRYPT_AddCertToSimpleChain(engine, chain, cert, 0);
1101         if (ret)
1102         {
1103             ret = CRYPT_BuildSimpleChain(engine, world, chain);
1104             if (ret)
1105                 CRYPT_CheckSimpleChain(engine, chain, pTime);
1106         }
1107         if (!ret)
1108         {
1109             CRYPT_FreeSimpleChain(chain);
1110             chain = NULL;
1111         }
1112         *ppChain = chain;
1113     }
1114     return ret;
1115 }
1116
1117 static BOOL CRYPT_BuildCandidateChainFromCert(HCERTCHAINENGINE hChainEngine,
1118  PCCERT_CONTEXT cert, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1119  PCertificateChain *ppChain)
1120 {
1121     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
1122     PCERT_SIMPLE_CHAIN simpleChain = NULL;
1123     HCERTSTORE world;
1124     BOOL ret;
1125
1126     world = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
1127      CERT_STORE_CREATE_NEW_FLAG, NULL);
1128     CertAddStoreToCollection(world, engine->hWorld, 0, 0);
1129     if (hAdditionalStore)
1130         CertAddStoreToCollection(world, hAdditionalStore, 0, 0);
1131     /* FIXME: only simple chains are supported for now, as CTLs aren't
1132      * supported yet.
1133      */
1134     if ((ret = CRYPT_GetSimpleChainForCert(engine, world, cert, pTime,
1135      &simpleChain)))
1136     {
1137         PCertificateChain chain = CryptMemAlloc(sizeof(CertificateChain));
1138
1139         if (chain)
1140         {
1141             chain->ref = 1;
1142             chain->world = world;
1143             chain->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
1144             chain->context.TrustStatus = simpleChain->TrustStatus;
1145             chain->context.cChain = 1;
1146             chain->context.rgpChain = CryptMemAlloc(sizeof(PCERT_SIMPLE_CHAIN));
1147             chain->context.rgpChain[0] = simpleChain;
1148             chain->context.cLowerQualityChainContext = 0;
1149             chain->context.rgpLowerQualityChainContext = NULL;
1150             chain->context.fHasRevocationFreshnessTime = FALSE;
1151             chain->context.dwRevocationFreshnessTime = 0;
1152         }
1153         else
1154             ret = FALSE;
1155         *ppChain = chain;
1156     }
1157     return ret;
1158 }
1159
1160 /* Makes and returns a copy of chain, up to and including element iElement. */
1161 static PCERT_SIMPLE_CHAIN CRYPT_CopySimpleChainToElement(
1162  const CERT_SIMPLE_CHAIN *chain, DWORD iElement)
1163 {
1164     PCERT_SIMPLE_CHAIN copy = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
1165
1166     if (copy)
1167     {
1168         memset(copy, 0, sizeof(CERT_SIMPLE_CHAIN));
1169         copy->cbSize = sizeof(CERT_SIMPLE_CHAIN);
1170         copy->rgpElement =
1171          CryptMemAlloc((iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
1172         if (copy->rgpElement)
1173         {
1174             DWORD i;
1175             BOOL ret = TRUE;
1176
1177             memset(copy->rgpElement, 0,
1178              (iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
1179             for (i = 0; ret && i <= iElement; i++)
1180             {
1181                 PCERT_CHAIN_ELEMENT element =
1182                  CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
1183
1184                 if (element)
1185                 {
1186                     *element = *chain->rgpElement[i];
1187                     element->pCertContext = CertDuplicateCertificateContext(
1188                      chain->rgpElement[i]->pCertContext);
1189                     /* Reset the trust status of the copied element, it'll get
1190                      * rechecked after the new chain is done.
1191                      */
1192                     memset(&element->TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
1193                     copy->rgpElement[copy->cElement++] = element;
1194                 }
1195                 else
1196                     ret = FALSE;
1197             }
1198             if (!ret)
1199             {
1200                 for (i = 0; i <= iElement; i++)
1201                     CryptMemFree(copy->rgpElement[i]);
1202                 CryptMemFree(copy->rgpElement);
1203                 CryptMemFree(copy);
1204                 copy = NULL;
1205             }
1206         }
1207         else
1208         {
1209             CryptMemFree(copy);
1210             copy = NULL;
1211         }
1212     }
1213     return copy;
1214 }
1215
1216 static void CRYPT_FreeLowerQualityChains(PCertificateChain chain)
1217 {
1218     DWORD i;
1219
1220     for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
1221         CertFreeCertificateChain(chain->context.rgpLowerQualityChainContext[i]);
1222     CryptMemFree(chain->context.rgpLowerQualityChainContext);
1223     chain->context.cLowerQualityChainContext = 0;
1224     chain->context.rgpLowerQualityChainContext = NULL;
1225 }
1226
1227 static void CRYPT_FreeChainContext(PCertificateChain chain)
1228 {
1229     DWORD i;
1230
1231     CRYPT_FreeLowerQualityChains(chain);
1232     for (i = 0; i < chain->context.cChain; i++)
1233         CRYPT_FreeSimpleChain(chain->context.rgpChain[i]);
1234     CryptMemFree(chain->context.rgpChain);
1235     CertCloseStore(chain->world, 0);
1236     CryptMemFree(chain);
1237 }
1238
1239 /* Makes and returns a copy of chain, up to and including element iElement of
1240  * simple chain iChain.
1241  */
1242 static PCertificateChain CRYPT_CopyChainToElement(PCertificateChain chain,
1243  DWORD iChain, DWORD iElement)
1244 {
1245     PCertificateChain copy = CryptMemAlloc(sizeof(CertificateChain));
1246
1247     if (copy)
1248     {
1249         copy->ref = 1;
1250         copy->world = CertDuplicateStore(chain->world);
1251         copy->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
1252         /* Leave the trust status of the copied chain unset, it'll get
1253          * rechecked after the new chain is done.
1254          */
1255         memset(&copy->context.TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
1256         copy->context.cLowerQualityChainContext = 0;
1257         copy->context.rgpLowerQualityChainContext = NULL;
1258         copy->context.fHasRevocationFreshnessTime = FALSE;
1259         copy->context.dwRevocationFreshnessTime = 0;
1260         copy->context.rgpChain = CryptMemAlloc(
1261          (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
1262         if (copy->context.rgpChain)
1263         {
1264             BOOL ret = TRUE;
1265             DWORD i;
1266
1267             memset(copy->context.rgpChain, 0,
1268              (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
1269             if (iChain)
1270             {
1271                 for (i = 0; ret && iChain && i < iChain - 1; i++)
1272                 {
1273                     copy->context.rgpChain[i] =
1274                      CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
1275                      chain->context.rgpChain[i]->cElement - 1);
1276                     if (!copy->context.rgpChain[i])
1277                         ret = FALSE;
1278                 }
1279             }
1280             else
1281                 i = 0;
1282             if (ret)
1283             {
1284                 copy->context.rgpChain[i] =
1285                  CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
1286                  iElement);
1287                 if (!copy->context.rgpChain[i])
1288                     ret = FALSE;
1289             }
1290             if (!ret)
1291             {
1292                 CRYPT_FreeChainContext(copy);
1293                 copy = NULL;
1294             }
1295             else
1296                 copy->context.cChain = iChain + 1;
1297         }
1298         else
1299         {
1300             CryptMemFree(copy);
1301             copy = NULL;
1302         }
1303     }
1304     return copy;
1305 }
1306
1307 static PCertificateChain CRYPT_BuildAlternateContextFromChain(
1308  HCERTCHAINENGINE hChainEngine, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1309  PCertificateChain chain)
1310 {
1311     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
1312     PCertificateChain alternate;
1313
1314     TRACE("(%p, %p, %p, %p)\n", hChainEngine, pTime, hAdditionalStore, chain);
1315
1316     /* Always start with the last "lower quality" chain to ensure a consistent
1317      * order of alternate creation:
1318      */
1319     if (chain->context.cLowerQualityChainContext)
1320         chain = (PCertificateChain)chain->context.rgpLowerQualityChainContext[
1321          chain->context.cLowerQualityChainContext - 1];
1322     /* A chain with only one element can't have any alternates */
1323     if (chain->context.cChain <= 1 && chain->context.rgpChain[0]->cElement <= 1)
1324         alternate = NULL;
1325     else
1326     {
1327         DWORD i, j, infoStatus;
1328         PCCERT_CONTEXT alternateIssuer = NULL;
1329
1330         alternate = NULL;
1331         for (i = 0; !alternateIssuer && i < chain->context.cChain; i++)
1332             for (j = 0; !alternateIssuer &&
1333              j < chain->context.rgpChain[i]->cElement - 1; j++)
1334             {
1335                 PCCERT_CONTEXT subject =
1336                  chain->context.rgpChain[i]->rgpElement[j]->pCertContext;
1337                 PCCERT_CONTEXT prevIssuer = CertDuplicateCertificateContext(
1338                  chain->context.rgpChain[i]->rgpElement[j + 1]->pCertContext);
1339
1340                 alternateIssuer = CRYPT_GetIssuer(prevIssuer->hCertStore,
1341                  subject, prevIssuer, &infoStatus);
1342             }
1343         if (alternateIssuer)
1344         {
1345             i--;
1346             j--;
1347             alternate = CRYPT_CopyChainToElement(chain, i, j);
1348             if (alternate)
1349             {
1350                 BOOL ret = CRYPT_AddCertToSimpleChain(engine,
1351                  alternate->context.rgpChain[i], alternateIssuer, infoStatus);
1352
1353                 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it
1354                  * to close the enumeration that found it
1355                  */
1356                 CertFreeCertificateContext(alternateIssuer);
1357                 if (ret)
1358                 {
1359                     ret = CRYPT_BuildSimpleChain(engine, alternate->world,
1360                      alternate->context.rgpChain[i]);
1361                     if (ret)
1362                         CRYPT_CheckSimpleChain(engine,
1363                          alternate->context.rgpChain[i], pTime);
1364                     CRYPT_CombineTrustStatus(&alternate->context.TrustStatus,
1365                      &alternate->context.rgpChain[i]->TrustStatus);
1366                 }
1367                 if (!ret)
1368                 {
1369                     CRYPT_FreeChainContext(alternate);
1370                     alternate = NULL;
1371                 }
1372             }
1373         }
1374     }
1375     TRACE("%p\n", alternate);
1376     return alternate;
1377 }
1378
1379 #define CHAIN_QUALITY_SIGNATURE_VALID 8
1380 #define CHAIN_QUALITY_TIME_VALID      4
1381 #define CHAIN_QUALITY_COMPLETE_CHAIN  2
1382 #define CHAIN_QUALITY_TRUSTED_ROOT    1
1383
1384 #define CHAIN_QUALITY_HIGHEST \
1385  CHAIN_QUALITY_SIGNATURE_VALID | CHAIN_QUALITY_TIME_VALID | \
1386  CHAIN_QUALITY_COMPLETE_CHAIN | CHAIN_QUALITY_TRUSTED_ROOT
1387
1388 #define IS_TRUST_ERROR_SET(TrustStatus, bits) \
1389  (TrustStatus)->dwErrorStatus & (bits)
1390
1391 static DWORD CRYPT_ChainQuality(const CertificateChain *chain)
1392 {
1393     DWORD quality = CHAIN_QUALITY_HIGHEST;
1394
1395     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1396      CERT_TRUST_IS_UNTRUSTED_ROOT))
1397         quality &= ~CHAIN_QUALITY_TRUSTED_ROOT;
1398     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1399      CERT_TRUST_IS_PARTIAL_CHAIN))
1400     if (chain->context.TrustStatus.dwErrorStatus & CERT_TRUST_IS_PARTIAL_CHAIN)
1401         quality &= ~CHAIN_QUALITY_COMPLETE_CHAIN;
1402     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1403      CERT_TRUST_IS_NOT_TIME_VALID | CERT_TRUST_IS_NOT_TIME_NESTED))
1404         quality &= ~CHAIN_QUALITY_TIME_VALID;
1405     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1406      CERT_TRUST_IS_NOT_SIGNATURE_VALID))
1407         quality &= ~CHAIN_QUALITY_SIGNATURE_VALID;
1408     return quality;
1409 }
1410
1411 /* Chooses the highest quality chain among chain and its "lower quality"
1412  * alternate chains.  Returns the highest quality chain, with all other
1413  * chains as lower quality chains of it.
1414  */
1415 static PCertificateChain CRYPT_ChooseHighestQualityChain(
1416  PCertificateChain chain)
1417 {
1418     DWORD i;
1419
1420     /* There are always only two chains being considered:  chain, and an
1421      * alternate at chain->rgpLowerQualityChainContext[i].  If the alternate
1422      * has a higher quality than chain, the alternate gets assigned the lower
1423      * quality contexts, with chain taking the alternate's place among the
1424      * lower quality contexts.
1425      */
1426     for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
1427     {
1428         PCertificateChain alternate =
1429          (PCertificateChain)chain->context.rgpLowerQualityChainContext[i];
1430
1431         if (CRYPT_ChainQuality(alternate) > CRYPT_ChainQuality(chain))
1432         {
1433             alternate->context.cLowerQualityChainContext =
1434              chain->context.cLowerQualityChainContext;
1435             alternate->context.rgpLowerQualityChainContext =
1436              chain->context.rgpLowerQualityChainContext;
1437             alternate->context.rgpLowerQualityChainContext[i] =
1438              (PCCERT_CHAIN_CONTEXT)chain;
1439             chain->context.cLowerQualityChainContext = 0;
1440             chain->context.rgpLowerQualityChainContext = NULL;
1441             chain = alternate;
1442         }
1443     }
1444     return chain;
1445 }
1446
1447 static BOOL CRYPT_AddAlternateChainToChain(PCertificateChain chain,
1448  const CertificateChain *alternate)
1449 {
1450     BOOL ret;
1451
1452     if (chain->context.cLowerQualityChainContext)
1453         chain->context.rgpLowerQualityChainContext =
1454          CryptMemRealloc(chain->context.rgpLowerQualityChainContext,
1455          (chain->context.cLowerQualityChainContext + 1) *
1456          sizeof(PCCERT_CHAIN_CONTEXT));
1457     else
1458         chain->context.rgpLowerQualityChainContext =
1459          CryptMemAlloc(sizeof(PCCERT_CHAIN_CONTEXT));
1460     if (chain->context.rgpLowerQualityChainContext)
1461     {
1462         chain->context.rgpLowerQualityChainContext[
1463          chain->context.cLowerQualityChainContext++] =
1464          (PCCERT_CHAIN_CONTEXT)alternate;
1465         ret = TRUE;
1466     }
1467     else
1468         ret = FALSE;
1469     return ret;
1470 }
1471
1472 static PCERT_CHAIN_ELEMENT CRYPT_FindIthElementInChain(
1473  const CERT_CHAIN_CONTEXT *chain, DWORD i)
1474 {
1475     DWORD j, iElement;
1476     PCERT_CHAIN_ELEMENT element = NULL;
1477
1478     for (j = 0, iElement = 0; !element && j < chain->cChain; j++)
1479     {
1480         if (iElement + chain->rgpChain[j]->cElement < i)
1481             iElement += chain->rgpChain[j]->cElement;
1482         else
1483             element = chain->rgpChain[j]->rgpElement[i - iElement];
1484     }
1485     return element;
1486 }
1487
1488 typedef struct _CERT_CHAIN_PARA_NO_EXTRA_FIELDS {
1489     DWORD            cbSize;
1490     CERT_USAGE_MATCH RequestedUsage;
1491 } CERT_CHAIN_PARA_NO_EXTRA_FIELDS, *PCERT_CHAIN_PARA_NO_EXTRA_FIELDS;
1492
1493 static void CRYPT_VerifyChainRevocation(PCERT_CHAIN_CONTEXT chain,
1494  LPFILETIME pTime, const CERT_CHAIN_PARA *pChainPara, DWORD chainFlags)
1495 {
1496     DWORD cContext;
1497
1498     if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_END_CERT)
1499         cContext = 1;
1500     else if ((chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN) ||
1501      (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT))
1502     {
1503         DWORD i;
1504
1505         for (i = 0, cContext = 0; i < chain->cChain; i++)
1506         {
1507             if (i < chain->cChain - 1 ||
1508              chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN)
1509                 cContext += chain->rgpChain[i]->cElement;
1510             else
1511                 cContext += chain->rgpChain[i]->cElement - 1;
1512         }
1513     }
1514     else
1515         cContext = 0;
1516     if (cContext)
1517     {
1518         PCCERT_CONTEXT *contexts =
1519          CryptMemAlloc(cContext * sizeof(PCCERT_CONTEXT *));
1520
1521         if (contexts)
1522         {
1523             DWORD i, j, iContext, revocationFlags;
1524             CERT_REVOCATION_PARA revocationPara = { sizeof(revocationPara), 0 };
1525             CERT_REVOCATION_STATUS revocationStatus =
1526              { sizeof(revocationStatus), 0 };
1527             BOOL ret;
1528
1529             for (i = 0, iContext = 0; iContext < cContext && i < chain->cChain;
1530              i++)
1531             {
1532                 for (j = 0; iContext < cContext &&
1533                  j < chain->rgpChain[i]->cElement; j++)
1534                     contexts[iContext++] =
1535                      chain->rgpChain[i]->rgpElement[j]->pCertContext;
1536             }
1537             revocationFlags = CERT_VERIFY_REV_CHAIN_FLAG;
1538             if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY)
1539                 revocationFlags |= CERT_VERIFY_CACHE_ONLY_BASED_REVOCATION;
1540             if (chainFlags & CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT)
1541                 revocationFlags |= CERT_VERIFY_REV_ACCUMULATIVE_TIMEOUT_FLAG;
1542             revocationPara.pftTimeToUse = pTime;
1543             if (pChainPara->cbSize == sizeof(CERT_CHAIN_PARA))
1544             {
1545                 revocationPara.dwUrlRetrievalTimeout =
1546                  pChainPara->dwUrlRetrievalTimeout;
1547                 revocationPara.fCheckFreshnessTime =
1548                  pChainPara->fCheckRevocationFreshnessTime;
1549                 revocationPara.dwFreshnessTime =
1550                  pChainPara->dwRevocationFreshnessTime;
1551             }
1552             ret = CertVerifyRevocation(X509_ASN_ENCODING,
1553              CERT_CONTEXT_REVOCATION_TYPE, cContext, (void **)contexts,
1554              revocationFlags, &revocationPara, &revocationStatus);
1555             if (!ret)
1556             {
1557                 PCERT_CHAIN_ELEMENT element =
1558                  CRYPT_FindIthElementInChain(chain, revocationStatus.dwIndex);
1559                 DWORD error;
1560
1561                 switch (revocationStatus.dwError)
1562                 {
1563                 case CRYPT_E_NO_REVOCATION_CHECK:
1564                 case CRYPT_E_NO_REVOCATION_DLL:
1565                 case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
1566                     error = CERT_TRUST_REVOCATION_STATUS_UNKNOWN;
1567                     break;
1568                 case CRYPT_E_REVOCATION_OFFLINE:
1569                     error = CERT_TRUST_IS_OFFLINE_REVOCATION;
1570                     break;
1571                 case CRYPT_E_REVOKED:
1572                     error = CERT_TRUST_IS_REVOKED;
1573                     break;
1574                 default:
1575                     WARN("unmapped error %08x\n", revocationStatus.dwError);
1576                     error = 0;
1577                 }
1578                 if (element)
1579                 {
1580                     /* FIXME: set element's pRevocationInfo member */
1581                     element->TrustStatus.dwErrorStatus |= error;
1582                 }
1583                 chain->TrustStatus.dwErrorStatus |= error;
1584             }
1585             CryptMemFree(contexts);
1586         }
1587     }
1588 }
1589
1590 BOOL WINAPI CertGetCertificateChain(HCERTCHAINENGINE hChainEngine,
1591  PCCERT_CONTEXT pCertContext, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1592  PCERT_CHAIN_PARA pChainPara, DWORD dwFlags, LPVOID pvReserved,
1593  PCCERT_CHAIN_CONTEXT* ppChainContext)
1594 {
1595     BOOL ret;
1596     PCertificateChain chain = NULL;
1597
1598     TRACE("(%p, %p, %p, %p, %p, %08x, %p, %p)\n", hChainEngine, pCertContext,
1599      pTime, hAdditionalStore, pChainPara, dwFlags, pvReserved, ppChainContext);
1600
1601     if (ppChainContext)
1602         *ppChainContext = NULL;
1603     if (!pChainPara)
1604     {
1605         SetLastError(E_INVALIDARG);
1606         return FALSE;
1607     }
1608     if (!pCertContext->pCertInfo->SignatureAlgorithm.pszObjId)
1609     {
1610         SetLastError(ERROR_INVALID_DATA);
1611         return FALSE;
1612     }
1613
1614     if (!hChainEngine)
1615         hChainEngine = CRYPT_GetDefaultChainEngine();
1616     /* FIXME: what about HCCE_LOCAL_MACHINE? */
1617     ret = CRYPT_BuildCandidateChainFromCert(hChainEngine, pCertContext, pTime,
1618      hAdditionalStore, &chain);
1619     if (ret)
1620     {
1621         PCertificateChain alternate = NULL;
1622         PCERT_CHAIN_CONTEXT pChain;
1623
1624         do {
1625             alternate = CRYPT_BuildAlternateContextFromChain(hChainEngine,
1626              pTime, hAdditionalStore, chain);
1627
1628             /* Alternate contexts are added as "lower quality" contexts of
1629              * chain, to avoid loops in alternate chain creation.
1630              * The highest-quality chain is chosen at the end.
1631              */
1632             if (alternate)
1633                 ret = CRYPT_AddAlternateChainToChain(chain, alternate);
1634         } while (ret && alternate);
1635         chain = CRYPT_ChooseHighestQualityChain(chain);
1636         if (!(dwFlags & CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS))
1637             CRYPT_FreeLowerQualityChains(chain);
1638         pChain = (PCERT_CHAIN_CONTEXT)chain;
1639         CRYPT_VerifyChainRevocation(pChain, pTime, pChainPara, dwFlags);
1640         if (ppChainContext)
1641             *ppChainContext = pChain;
1642         else
1643             CertFreeCertificateChain(pChain);
1644     }
1645     TRACE("returning %d\n", ret);
1646     return ret;
1647 }
1648
1649 PCCERT_CHAIN_CONTEXT WINAPI CertDuplicateCertificateChain(
1650  PCCERT_CHAIN_CONTEXT pChainContext)
1651 {
1652     PCertificateChain chain = (PCertificateChain)pChainContext;
1653
1654     TRACE("(%p)\n", pChainContext);
1655
1656     if (chain)
1657         InterlockedIncrement(&chain->ref);
1658     return pChainContext;
1659 }
1660
1661 VOID WINAPI CertFreeCertificateChain(PCCERT_CHAIN_CONTEXT pChainContext)
1662 {
1663     PCertificateChain chain = (PCertificateChain)pChainContext;
1664
1665     TRACE("(%p)\n", pChainContext);
1666
1667     if (chain)
1668     {
1669         if (InterlockedDecrement(&chain->ref) == 0)
1670             CRYPT_FreeChainContext(chain);
1671     }
1672 }
1673
1674 static void find_element_with_error(PCCERT_CHAIN_CONTEXT chain, DWORD error,
1675  LONG *iChain, LONG *iElement)
1676 {
1677     DWORD i, j;
1678
1679     for (i = 0; i < chain->cChain; i++)
1680         for (j = 0; j < chain->rgpChain[i]->cElement; j++)
1681             if (chain->rgpChain[i]->rgpElement[j]->TrustStatus.dwErrorStatus &
1682              error)
1683             {
1684                 *iChain = i;
1685                 *iElement = j;
1686                 return;
1687             }
1688 }
1689
1690 static BOOL WINAPI verify_base_policy(LPCSTR szPolicyOID,
1691  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1692  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
1693 {
1694     pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
1695     if (pChainContext->TrustStatus.dwErrorStatus &
1696      CERT_TRUST_IS_NOT_SIGNATURE_VALID)
1697     {
1698         pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
1699         find_element_with_error(pChainContext,
1700          CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
1701          &pPolicyStatus->lElementIndex);
1702     }
1703     else if (pChainContext->TrustStatus.dwErrorStatus &
1704      CERT_TRUST_IS_UNTRUSTED_ROOT)
1705     {
1706         pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
1707         find_element_with_error(pChainContext,
1708          CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
1709          &pPolicyStatus->lElementIndex);
1710     }
1711     else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
1712     {
1713         pPolicyStatus->dwError = CERT_E_CHAINING;
1714         find_element_with_error(pChainContext, CERT_TRUST_IS_CYCLIC,
1715          &pPolicyStatus->lChainIndex, &pPolicyStatus->lElementIndex);
1716         /* For a cyclic chain, which element is a cycle isn't meaningful */
1717         pPolicyStatus->lElementIndex = -1;
1718     }
1719     else
1720         pPolicyStatus->dwError = NO_ERROR;
1721     return TRUE;
1722 }
1723
1724 static BYTE msTestPubKey1[] = {
1725 0x30,0x47,0x02,0x40,0x81,0x55,0x22,0xb9,0x8a,0xa4,0x6f,0xed,0xd6,0xe7,0xd9,
1726 0x66,0x0f,0x55,0xbc,0xd7,0xcd,0xd5,0xbc,0x4e,0x40,0x02,0x21,0xa2,0xb1,0xf7,
1727 0x87,0x30,0x85,0x5e,0xd2,0xf2,0x44,0xb9,0xdc,0x9b,0x75,0xb6,0xfb,0x46,0x5f,
1728 0x42,0xb6,0x9d,0x23,0x36,0x0b,0xde,0x54,0x0f,0xcd,0xbd,0x1f,0x99,0x2a,0x10,
1729 0x58,0x11,0xcb,0x40,0xcb,0xb5,0xa7,0x41,0x02,0x03,0x01,0x00,0x01 };
1730 static BYTE msTestPubKey2[] = {
1731 0x30,0x47,0x02,0x40,0x9c,0x50,0x05,0x1d,0xe2,0x0e,0x4c,0x53,0xd8,0xd9,0xb5,
1732 0xe5,0xfd,0xe9,0xe3,0xad,0x83,0x4b,0x80,0x08,0xd9,0xdc,0xe8,0xe8,0x35,0xf8,
1733 0x11,0xf1,0xe9,0x9b,0x03,0x7a,0x65,0x64,0x76,0x35,0xce,0x38,0x2c,0xf2,0xb6,
1734 0x71,0x9e,0x06,0xd9,0xbf,0xbb,0x31,0x69,0xa3,0xf6,0x30,0xa0,0x78,0x7b,0x18,
1735 0xdd,0x50,0x4d,0x79,0x1e,0xeb,0x61,0xc1,0x02,0x03,0x01,0x00,0x01 };
1736
1737 static BOOL WINAPI verify_authenticode_policy(LPCSTR szPolicyOID,
1738  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1739  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
1740 {
1741     BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
1742      pPolicyStatus);
1743
1744     if (ret && pPolicyStatus->dwError == CERT_E_UNTRUSTEDROOT)
1745     {
1746         CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
1747         BOOL isMSTestRoot = FALSE;
1748         PCCERT_CONTEXT failingCert =
1749          pChainContext->rgpChain[pPolicyStatus->lChainIndex]->
1750          rgpElement[pPolicyStatus->lElementIndex]->pCertContext;
1751         DWORD i;
1752         CRYPT_DATA_BLOB keyBlobs[] = {
1753          { sizeof(msTestPubKey1), msTestPubKey1 },
1754          { sizeof(msTestPubKey2), msTestPubKey2 },
1755         };
1756
1757         /* Check whether the root is an MS test root */
1758         for (i = 0; !isMSTestRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
1759          i++)
1760         {
1761             msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
1762             msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
1763             if (CertComparePublicKeyInfo(
1764              X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1765              &failingCert->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
1766                 isMSTestRoot = TRUE;
1767         }
1768         if (isMSTestRoot)
1769             pPolicyStatus->dwError = CERT_E_UNTRUSTEDTESTROOT;
1770     }
1771     return ret;
1772 }
1773
1774 static BOOL WINAPI verify_basic_constraints_policy(LPCSTR szPolicyOID,
1775  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1776  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
1777 {
1778     pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
1779     if (pChainContext->TrustStatus.dwErrorStatus &
1780      CERT_TRUST_INVALID_BASIC_CONSTRAINTS)
1781     {
1782         pPolicyStatus->dwError = TRUST_E_BASIC_CONSTRAINTS;
1783         find_element_with_error(pChainContext,
1784          CERT_TRUST_INVALID_BASIC_CONSTRAINTS, &pPolicyStatus->lChainIndex,
1785          &pPolicyStatus->lElementIndex);
1786     }
1787     else
1788         pPolicyStatus->dwError = NO_ERROR;
1789     return TRUE;
1790 }
1791
1792 static BYTE msPubKey1[] = {
1793 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xdf,0x08,0xba,0xe3,0x3f,0x6e,
1794 0x64,0x9b,0xf5,0x89,0xaf,0x28,0x96,0x4a,0x07,0x8f,0x1b,0x2e,0x8b,0x3e,0x1d,
1795 0xfc,0xb8,0x80,0x69,0xa3,0xa1,0xce,0xdb,0xdf,0xb0,0x8e,0x6c,0x89,0x76,0x29,
1796 0x4f,0xca,0x60,0x35,0x39,0xad,0x72,0x32,0xe0,0x0b,0xae,0x29,0x3d,0x4c,0x16,
1797 0xd9,0x4b,0x3c,0x9d,0xda,0xc5,0xd3,0xd1,0x09,0xc9,0x2c,0x6f,0xa6,0xc2,0x60,
1798 0x53,0x45,0xdd,0x4b,0xd1,0x55,0xcd,0x03,0x1c,0xd2,0x59,0x56,0x24,0xf3,0xe5,
1799 0x78,0xd8,0x07,0xcc,0xd8,0xb3,0x1f,0x90,0x3f,0xc0,0x1a,0x71,0x50,0x1d,0x2d,
1800 0xa7,0x12,0x08,0x6d,0x7c,0xb0,0x86,0x6c,0xc7,0xba,0x85,0x32,0x07,0xe1,0x61,
1801 0x6f,0xaf,0x03,0xc5,0x6d,0xe5,0xd6,0xa1,0x8f,0x36,0xf6,0xc1,0x0b,0xd1,0x3e,
1802 0x69,0x97,0x48,0x72,0xc9,0x7f,0xa4,0xc8,0xc2,0x4a,0x4c,0x7e,0xa1,0xd1,0x94,
1803 0xa6,0xd7,0xdc,0xeb,0x05,0x46,0x2e,0xb8,0x18,0xb4,0x57,0x1d,0x86,0x49,0xdb,
1804 0x69,0x4a,0x2c,0x21,0xf5,0x5e,0x0f,0x54,0x2d,0x5a,0x43,0xa9,0x7a,0x7e,0x6a,
1805 0x8e,0x50,0x4d,0x25,0x57,0xa1,0xbf,0x1b,0x15,0x05,0x43,0x7b,0x2c,0x05,0x8d,
1806 0xbd,0x3d,0x03,0x8c,0x93,0x22,0x7d,0x63,0xea,0x0a,0x57,0x05,0x06,0x0a,0xdb,
1807 0x61,0x98,0x65,0x2d,0x47,0x49,0xa8,0xe7,0xe6,0x56,0x75,0x5c,0xb8,0x64,0x08,
1808 0x63,0xa9,0x30,0x40,0x66,0xb2,0xf9,0xb6,0xe3,0x34,0xe8,0x67,0x30,0xe1,0x43,
1809 0x0b,0x87,0xff,0xc9,0xbe,0x72,0x10,0x5e,0x23,0xf0,0x9b,0xa7,0x48,0x65,0xbf,
1810 0x09,0x88,0x7b,0xcd,0x72,0xbc,0x2e,0x79,0x9b,0x7b,0x02,0x03,0x01,0x00,0x01 };
1811 static BYTE msPubKey2[] = {
1812 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xa9,0x02,0xbd,0xc1,0x70,0xe6,
1813 0x3b,0xf2,0x4e,0x1b,0x28,0x9f,0x97,0x78,0x5e,0x30,0xea,0xa2,0xa9,0x8d,0x25,
1814 0x5f,0xf8,0xfe,0x95,0x4c,0xa3,0xb7,0xfe,0x9d,0xa2,0x20,0x3e,0x7c,0x51,0xa2,
1815 0x9b,0xa2,0x8f,0x60,0x32,0x6b,0xd1,0x42,0x64,0x79,0xee,0xac,0x76,0xc9,0x54,
1816 0xda,0xf2,0xeb,0x9c,0x86,0x1c,0x8f,0x9f,0x84,0x66,0xb3,0xc5,0x6b,0x7a,0x62,
1817 0x23,0xd6,0x1d,0x3c,0xde,0x0f,0x01,0x92,0xe8,0x96,0xc4,0xbf,0x2d,0x66,0x9a,
1818 0x9a,0x68,0x26,0x99,0xd0,0x3a,0x2c,0xbf,0x0c,0xb5,0x58,0x26,0xc1,0x46,0xe7,
1819 0x0a,0x3e,0x38,0x96,0x2c,0xa9,0x28,0x39,0xa8,0xec,0x49,0x83,0x42,0xe3,0x84,
1820 0x0f,0xbb,0x9a,0x6c,0x55,0x61,0xac,0x82,0x7c,0xa1,0x60,0x2d,0x77,0x4c,0xe9,
1821 0x99,0xb4,0x64,0x3b,0x9a,0x50,0x1c,0x31,0x08,0x24,0x14,0x9f,0xa9,0xe7,0x91,
1822 0x2b,0x18,0xe6,0x3d,0x98,0x63,0x14,0x60,0x58,0x05,0x65,0x9f,0x1d,0x37,0x52,
1823 0x87,0xf7,0xa7,0xef,0x94,0x02,0xc6,0x1b,0xd3,0xbf,0x55,0x45,0xb3,0x89,0x80,
1824 0xbf,0x3a,0xec,0x54,0x94,0x4e,0xae,0xfd,0xa7,0x7a,0x6d,0x74,0x4e,0xaf,0x18,
1825 0xcc,0x96,0x09,0x28,0x21,0x00,0x57,0x90,0x60,0x69,0x37,0xbb,0x4b,0x12,0x07,
1826 0x3c,0x56,0xff,0x5b,0xfb,0xa4,0x66,0x0a,0x08,0xa6,0xd2,0x81,0x56,0x57,0xef,
1827 0xb6,0x3b,0x5e,0x16,0x81,0x77,0x04,0xda,0xf6,0xbe,0xae,0x80,0x95,0xfe,0xb0,
1828 0xcd,0x7f,0xd6,0xa7,0x1a,0x72,0x5c,0x3c,0xca,0xbc,0xf0,0x08,0xa3,0x22,0x30,
1829 0xb3,0x06,0x85,0xc9,0xb3,0x20,0x77,0x13,0x85,0xdf,0x02,0x03,0x01,0x00,0x01 };
1830 static BYTE msPubKey3[] = {
1831 0x30,0x82,0x02,0x0a,0x02,0x82,0x02,0x01,0x00,0xf3,0x5d,0xfa,0x80,0x67,0xd4,
1832 0x5a,0xa7,0xa9,0x0c,0x2c,0x90,0x20,0xd0,0x35,0x08,0x3c,0x75,0x84,0xcd,0xb7,
1833 0x07,0x89,0x9c,0x89,0xda,0xde,0xce,0xc3,0x60,0xfa,0x91,0x68,0x5a,0x9e,0x94,
1834 0x71,0x29,0x18,0x76,0x7c,0xc2,0xe0,0xc8,0x25,0x76,0x94,0x0e,0x58,0xfa,0x04,
1835 0x34,0x36,0xe6,0xdf,0xaf,0xf7,0x80,0xba,0xe9,0x58,0x0b,0x2b,0x93,0xe5,0x9d,
1836 0x05,0xe3,0x77,0x22,0x91,0xf7,0x34,0x64,0x3c,0x22,0x91,0x1d,0x5e,0xe1,0x09,
1837 0x90,0xbc,0x14,0xfe,0xfc,0x75,0x58,0x19,0xe1,0x79,0xb7,0x07,0x92,0xa3,0xae,
1838 0x88,0x59,0x08,0xd8,0x9f,0x07,0xca,0x03,0x58,0xfc,0x68,0x29,0x6d,0x32,0xd7,
1839 0xd2,0xa8,0xcb,0x4b,0xfc,0xe1,0x0b,0x48,0x32,0x4f,0xe6,0xeb,0xb8,0xad,0x4f,
1840 0xe4,0x5c,0x6f,0x13,0x94,0x99,0xdb,0x95,0xd5,0x75,0xdb,0xa8,0x1a,0xb7,0x94,
1841 0x91,0xb4,0x77,0x5b,0xf5,0x48,0x0c,0x8f,0x6a,0x79,0x7d,0x14,0x70,0x04,0x7d,
1842 0x6d,0xaf,0x90,0xf5,0xda,0x70,0xd8,0x47,0xb7,0xbf,0x9b,0x2f,0x6c,0xe7,0x05,
1843 0xb7,0xe1,0x11,0x60,0xac,0x79,0x91,0x14,0x7c,0xc5,0xd6,0xa6,0xe4,0xe1,0x7e,
1844 0xd5,0xc3,0x7e,0xe5,0x92,0xd2,0x3c,0x00,0xb5,0x36,0x82,0xde,0x79,0xe1,0x6d,
1845 0xf3,0xb5,0x6e,0xf8,0x9f,0x33,0xc9,0xcb,0x52,0x7d,0x73,0x98,0x36,0xdb,0x8b,
1846 0xa1,0x6b,0xa2,0x95,0x97,0x9b,0xa3,0xde,0xc2,0x4d,0x26,0xff,0x06,0x96,0x67,
1847 0x25,0x06,0xc8,0xe7,0xac,0xe4,0xee,0x12,0x33,0x95,0x31,0x99,0xc8,0x35,0x08,
1848 0x4e,0x34,0xca,0x79,0x53,0xd5,0xb5,0xbe,0x63,0x32,0x59,0x40,0x36,0xc0,0xa5,
1849 0x4e,0x04,0x4d,0x3d,0xdb,0x5b,0x07,0x33,0xe4,0x58,0xbf,0xef,0x3f,0x53,0x64,
1850 0xd8,0x42,0x59,0x35,0x57,0xfd,0x0f,0x45,0x7c,0x24,0x04,0x4d,0x9e,0xd6,0x38,
1851 0x74,0x11,0x97,0x22,0x90,0xce,0x68,0x44,0x74,0x92,0x6f,0xd5,0x4b,0x6f,0xb0,
1852 0x86,0xe3,0xc7,0x36,0x42,0xa0,0xd0,0xfc,0xc1,0xc0,0x5a,0xf9,0xa3,0x61,0xb9,
1853 0x30,0x47,0x71,0x96,0x0a,0x16,0xb0,0x91,0xc0,0x42,0x95,0xef,0x10,0x7f,0x28,
1854 0x6a,0xe3,0x2a,0x1f,0xb1,0xe4,0xcd,0x03,0x3f,0x77,0x71,0x04,0xc7,0x20,0xfc,
1855 0x49,0x0f,0x1d,0x45,0x88,0xa4,0xd7,0xcb,0x7e,0x88,0xad,0x8e,0x2d,0xec,0x45,
1856 0xdb,0xc4,0x51,0x04,0xc9,0x2a,0xfc,0xec,0x86,0x9e,0x9a,0x11,0x97,0x5b,0xde,
1857 0xce,0x53,0x88,0xe6,0xe2,0xb7,0xfd,0xac,0x95,0xc2,0x28,0x40,0xdb,0xef,0x04,
1858 0x90,0xdf,0x81,0x33,0x39,0xd9,0xb2,0x45,0xa5,0x23,0x87,0x06,0xa5,0x55,0x89,
1859 0x31,0xbb,0x06,0x2d,0x60,0x0e,0x41,0x18,0x7d,0x1f,0x2e,0xb5,0x97,0xcb,0x11,
1860 0xeb,0x15,0xd5,0x24,0xa5,0x94,0xef,0x15,0x14,0x89,0xfd,0x4b,0x73,0xfa,0x32,
1861 0x5b,0xfc,0xd1,0x33,0x00,0xf9,0x59,0x62,0x70,0x07,0x32,0xea,0x2e,0xab,0x40,
1862 0x2d,0x7b,0xca,0xdd,0x21,0x67,0x1b,0x30,0x99,0x8f,0x16,0xaa,0x23,0xa8,0x41,
1863 0xd1,0xb0,0x6e,0x11,0x9b,0x36,0xc4,0xde,0x40,0x74,0x9c,0xe1,0x58,0x65,0xc1,
1864 0x60,0x1e,0x7a,0x5b,0x38,0xc8,0x8f,0xbb,0x04,0x26,0x7c,0xd4,0x16,0x40,0xe5,
1865 0xb6,0x6b,0x6c,0xaa,0x86,0xfd,0x00,0xbf,0xce,0xc1,0x35,0x02,0x03,0x01,0x00,
1866 0x01 };
1867
1868 static BOOL WINAPI verify_ms_root_policy(LPCSTR szPolicyOID,
1869  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1870  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
1871 {
1872     BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
1873      pPolicyStatus);
1874
1875     if (ret && !pPolicyStatus->dwError)
1876     {
1877         CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
1878         BOOL isMSRoot = FALSE;
1879         DWORD i;
1880         CRYPT_DATA_BLOB keyBlobs[] = {
1881          { sizeof(msPubKey1), msPubKey1 },
1882          { sizeof(msPubKey2), msPubKey2 },
1883          { sizeof(msPubKey3), msPubKey3 },
1884         };
1885         PCERT_SIMPLE_CHAIN rootChain =
1886          pChainContext->rgpChain[pChainContext->cChain -1 ];
1887         PCCERT_CONTEXT root =
1888          rootChain->rgpElement[rootChain->cElement - 1]->pCertContext;
1889
1890         for (i = 0; !isMSRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
1891          i++)
1892         {
1893             msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
1894             msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
1895             if (CertComparePublicKeyInfo(
1896              X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1897              &root->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
1898                 isMSRoot = TRUE;
1899         }
1900         if (isMSRoot)
1901             pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = 0;
1902     }
1903     return ret;
1904 }
1905
1906 typedef BOOL (WINAPI *CertVerifyCertificateChainPolicyFunc)(LPCSTR szPolicyOID,
1907  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1908  PCERT_CHAIN_POLICY_STATUS pPolicyStatus);
1909
1910 BOOL WINAPI CertVerifyCertificateChainPolicy(LPCSTR szPolicyOID,
1911  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1912  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
1913 {
1914     static HCRYPTOIDFUNCSET set = NULL;
1915     BOOL ret = FALSE;
1916     CertVerifyCertificateChainPolicyFunc verifyPolicy = NULL;
1917     HCRYPTOIDFUNCADDR hFunc = NULL;
1918
1919     TRACE("(%s, %p, %p, %p)\n", debugstr_a(szPolicyOID), pChainContext,
1920      pPolicyPara, pPolicyStatus);
1921
1922     if (!HIWORD(szPolicyOID))
1923     {
1924         switch (LOWORD(szPolicyOID))
1925         {
1926         case LOWORD(CERT_CHAIN_POLICY_BASE):
1927             verifyPolicy = verify_base_policy;
1928             break;
1929         case LOWORD(CERT_CHAIN_POLICY_AUTHENTICODE):
1930             verifyPolicy = verify_authenticode_policy;
1931             break;
1932         case LOWORD(CERT_CHAIN_POLICY_BASIC_CONSTRAINTS):
1933             verifyPolicy = verify_basic_constraints_policy;
1934             break;
1935         case LOWORD(CERT_CHAIN_POLICY_MICROSOFT_ROOT):
1936             verifyPolicy = verify_ms_root_policy;
1937             break;
1938         default:
1939             FIXME("unimplemented for %d\n", LOWORD(szPolicyOID));
1940         }
1941     }
1942     if (!verifyPolicy)
1943     {
1944         if (!set)
1945             set = CryptInitOIDFunctionSet(
1946              CRYPT_OID_VERIFY_CERTIFICATE_CHAIN_POLICY_FUNC, 0);
1947         CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING, szPolicyOID, 0,
1948          (void **)&verifyPolicy, &hFunc);
1949     }
1950     if (verifyPolicy)
1951         ret = verifyPolicy(szPolicyOID, pChainContext, pPolicyPara,
1952          pPolicyStatus);
1953     if (hFunc)
1954         CryptFreeOIDFunctionAddress(hFunc, 0);
1955     return ret;
1956 }