kernel32: Add a structure to store all the information about an executable.
[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         chainConstraints->fCA = constraints.fCA;
445         if (!constraints.fCA)
446         {
447             TRACE_(chain)("chain element %d can't be a CA\n", remainingCAs + 1);
448             validBasicConstraints = FALSE;
449         }
450         else if (constraints.fPathLenConstraint)
451         {
452             /* If the element has path length constraints, they apply to the
453              * entire remaining chain.
454              */
455             if (!chainConstraints->fPathLenConstraint ||
456              constraints.dwPathLenConstraint <
457              chainConstraints->dwPathLenConstraint)
458             {
459                 TRACE_(chain)("setting path length constraint to %d\n",
460                  chainConstraints->dwPathLenConstraint);
461                 chainConstraints->fPathLenConstraint = TRUE;
462                 chainConstraints->dwPathLenConstraint =
463                  constraints.dwPathLenConstraint;
464             }
465         }
466     }
467     if (chainConstraints->fPathLenConstraint &&
468      remainingCAs > chainConstraints->dwPathLenConstraint)
469     {
470         TRACE_(chain)("remaining CAs %d exceed max path length %d\n",
471          remainingCAs, chainConstraints->dwPathLenConstraint);
472         validBasicConstraints = FALSE;
473         *pathLengthConstraintViolated = TRUE;
474     }
475     return validBasicConstraints;
476 }
477
478 static BOOL url_matches(LPCWSTR constraint, LPCWSTR name,
479  DWORD *trustErrorStatus)
480 {
481     BOOL match = FALSE;
482
483     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
484
485     if (!constraint)
486         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
487     else if (!name)
488         ; /* no match */
489     else if (constraint[0] == '.')
490     {
491         if (lstrlenW(name) > lstrlenW(constraint))
492             match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
493              constraint);
494     }
495     else
496         match = !lstrcmpiW(constraint, name);
497     return match;
498 }
499
500 static BOOL rfc822_name_matches(LPCWSTR constraint, LPCWSTR name,
501  DWORD *trustErrorStatus)
502 {
503     BOOL match = FALSE;
504     LPCWSTR at;
505
506     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
507
508     if (!constraint)
509         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
510     else if (!name)
511         ; /* no match */
512     else if ((at = strchrW(constraint, '@')))
513         match = !lstrcmpiW(constraint, name);
514     else
515     {
516         if ((at = strchrW(name, '@')))
517             match = url_matches(constraint, at + 1, trustErrorStatus);
518         else
519             match = !lstrcmpiW(constraint, name);
520     }
521     return match;
522 }
523
524 static BOOL dns_name_matches(LPCWSTR constraint, LPCWSTR name,
525  DWORD *trustErrorStatus)
526 {
527     BOOL match = FALSE;
528
529     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
530
531     if (!constraint)
532         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
533     else if (!name)
534         ; /* no match */
535     else if (lstrlenW(name) >= lstrlenW(constraint))
536         match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
537          constraint);
538     /* else:  name is too short, no match */
539
540     return match;
541 }
542
543 static BOOL ip_address_matches(const CRYPT_DATA_BLOB *constraint,
544  const CRYPT_DATA_BLOB *name, DWORD *trustErrorStatus)
545 {
546     BOOL match = FALSE;
547
548     TRACE("(%d, %p), (%d, %p)\n", constraint->cbData, constraint->pbData,
549      name->cbData, name->pbData);
550
551     if (constraint->cbData != sizeof(DWORD) * 2)
552         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
553     else if (name->cbData == sizeof(DWORD))
554     {
555         DWORD subnet, mask, addr;
556
557         memcpy(&subnet, constraint->pbData, sizeof(subnet));
558         memcpy(&mask, constraint->pbData + sizeof(subnet), sizeof(mask));
559         memcpy(&addr, name->pbData, sizeof(addr));
560         /* These are really in big-endian order, but for equality matching we
561          * don't need to swap to host order
562          */
563         match = (subnet & mask) == (addr & mask);
564     }
565     /* else: name is wrong size, no match */
566
567     return match;
568 }
569
570 static void CRYPT_FindMatchingNameEntry(const CERT_ALT_NAME_ENTRY *constraint,
571  const CERT_ALT_NAME_INFO *subjectName, DWORD *trustErrorStatus,
572  DWORD errorIfFound, DWORD errorIfNotFound)
573 {
574     DWORD i;
575     BOOL match = FALSE;
576
577     for (i = 0; i < subjectName->cAltEntry; i++)
578     {
579         if (subjectName->rgAltEntry[i].dwAltNameChoice ==
580          constraint->dwAltNameChoice)
581         {
582             switch (constraint->dwAltNameChoice)
583             {
584             case CERT_ALT_NAME_RFC822_NAME:
585                 match = rfc822_name_matches(constraint->u.pwszURL,
586                  subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
587                 break;
588             case CERT_ALT_NAME_DNS_NAME:
589                 match = dns_name_matches(constraint->u.pwszURL,
590                  subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
591                 break;
592             case CERT_ALT_NAME_URL:
593                 match = url_matches(constraint->u.pwszURL,
594                  subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
595                 break;
596             case CERT_ALT_NAME_IP_ADDRESS:
597                 match = ip_address_matches(&constraint->u.IPAddress,
598                  &subjectName->rgAltEntry[i].u.IPAddress, trustErrorStatus);
599                 break;
600             case CERT_ALT_NAME_DIRECTORY_NAME:
601             default:
602                 ERR("name choice %d unsupported in this context\n",
603                  constraint->dwAltNameChoice);
604                 *trustErrorStatus |=
605                  CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
606             }
607         }
608     }
609     *trustErrorStatus |= match ? errorIfFound : errorIfNotFound;
610 }
611
612 static void CRYPT_CheckNameConstraints(
613  const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, const CERT_INFO *cert,
614  DWORD *trustErrorStatus)
615 {
616     /* If there aren't any existing constraints, don't bother checking */
617     if (nameConstraints->cPermittedSubtree || nameConstraints->cExcludedSubtree)
618     {
619         CERT_EXTENSION *ext;
620
621         if ((ext = CertFindExtension(szOID_SUBJECT_ALT_NAME, cert->cExtension,
622          cert->rgExtension)))
623         {
624             CERT_ALT_NAME_INFO *subjectName;
625             DWORD size;
626
627             if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
628              ext->Value.pbData, ext->Value.cbData,
629              CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
630              &subjectName, &size))
631             {
632                 DWORD i;
633
634                 for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
635                     CRYPT_FindMatchingNameEntry(
636                      &nameConstraints->rgExcludedSubtree[i].Base, subjectName,
637                      trustErrorStatus,
638                      CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT, 0);
639                 for (i = 0; i < nameConstraints->cPermittedSubtree; i++)
640                     CRYPT_FindMatchingNameEntry(
641                      &nameConstraints->rgPermittedSubtree[i].Base, subjectName,
642                      trustErrorStatus,
643                      0, CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT);
644                 LocalFree(subjectName);
645             }
646         }
647         else
648         {
649             if (nameConstraints->cPermittedSubtree)
650                 *trustErrorStatus |=
651                  CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
652             if (nameConstraints->cExcludedSubtree)
653                 *trustErrorStatus |=
654                  CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
655         }
656     }
657 }
658
659 /* Gets cert's name constraints, if any.  Free with LocalFree. */
660 static CERT_NAME_CONSTRAINTS_INFO *CRYPT_GetNameConstraints(CERT_INFO *cert)
661 {
662     CERT_NAME_CONSTRAINTS_INFO *info = NULL;
663
664     CERT_EXTENSION *ext;
665
666     if ((ext = CertFindExtension(szOID_NAME_CONSTRAINTS, cert->cExtension,
667      cert->rgExtension)))
668     {
669         DWORD size;
670
671         CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
672          ext->Value.pbData, ext->Value.cbData,
673          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &info,
674          &size);
675     }
676     return info;
677 }
678
679 static void CRYPT_CheckChainNameConstraints(PCERT_SIMPLE_CHAIN chain)
680 {
681     int i, j;
682
683     /* Microsoft's implementation appears to violate RFC 3280:  according to
684      * MSDN, the various CERT_TRUST_*_NAME_CONSTRAINT errors are set if a CA's
685      * name constraint is violated in the end cert.  According to RFC 3280,
686      * the constraints should be checked against every subsequent certificate
687      * in the chain, not just the end cert.
688      * Microsoft's implementation also sets the name constraint errors on the
689      * certs whose constraints were violated, not on the certs that violated
690      * them.
691      * In order to be error-compatible with Microsoft's implementation, while
692      * still adhering to RFC 3280, I use a O(n ^ 2) algorithm to check name
693      * constraints.
694      */
695     for (i = chain->cElement - 1; i > 0; i--)
696     {
697         CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
698
699         if ((nameConstraints = CRYPT_GetNameConstraints(
700          chain->rgpElement[i]->pCertContext->pCertInfo)))
701         {
702             for (j = i - 1; j >= 0; j--)
703             {
704                 DWORD errorStatus = 0;
705
706                 /* According to RFC 3280, self-signed certs don't have name
707                  * constraints checked unless they're the end cert.
708                  */
709                 if (j == 0 || !CRYPT_IsCertificateSelfSigned(
710                  chain->rgpElement[j]->pCertContext))
711                 {
712                     CRYPT_CheckNameConstraints(nameConstraints,
713                      chain->rgpElement[i]->pCertContext->pCertInfo,
714                      &errorStatus);
715                     chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
716                      errorStatus;
717                 }
718             }
719             LocalFree(nameConstraints);
720         }
721     }
722 }
723
724 static void dump_basic_constraints(const CERT_EXTENSION *ext)
725 {
726     CERT_BASIC_CONSTRAINTS_INFO *info;
727     DWORD size = 0;
728
729     if (CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
730      ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
731      NULL, &info, &size))
732     {
733         TRACE_(chain)("SubjectType: %02x\n", info->SubjectType.pbData[0]);
734         TRACE_(chain)("%s path length constraint\n",
735          info->fPathLenConstraint ? "has" : "doesn't have");
736         TRACE_(chain)("path length=%d\n", info->dwPathLenConstraint);
737         LocalFree(info);
738     }
739 }
740
741 static void dump_basic_constraints2(const CERT_EXTENSION *ext)
742 {
743     CERT_BASIC_CONSTRAINTS2_INFO constraints;
744     DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
745
746     if (CryptDecodeObjectEx(X509_ASN_ENCODING,
747      szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
748      0, NULL, &constraints, &size))
749     {
750         TRACE_(chain)("basic constraints:\n");
751         TRACE_(chain)("can%s be a CA\n", constraints.fCA ? "" : "not");
752         TRACE_(chain)("%s path length constraint\n",
753          constraints.fPathLenConstraint ? "has" : "doesn't have");
754         TRACE_(chain)("path length=%d\n", constraints.dwPathLenConstraint);
755     }
756 }
757
758 static void dump_key_usage(const CERT_EXTENSION *ext)
759 {
760     CRYPT_BIT_BLOB usage;
761     DWORD size = sizeof(usage);
762
763     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
764      ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
765     {
766 #define trace_usage_bit(bits, bit) \
767  if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
768         if (usage.cbData)
769         {
770             trace_usage_bit(usage.pbData[0], CERT_DIGITAL_SIGNATURE_KEY_USAGE);
771             trace_usage_bit(usage.pbData[0], CERT_NON_REPUDIATION_KEY_USAGE);
772             trace_usage_bit(usage.pbData[0], CERT_KEY_ENCIPHERMENT_KEY_USAGE);
773             trace_usage_bit(usage.pbData[0], CERT_DATA_ENCIPHERMENT_KEY_USAGE);
774             trace_usage_bit(usage.pbData[0], CERT_KEY_AGREEMENT_KEY_USAGE);
775             trace_usage_bit(usage.pbData[0], CERT_KEY_CERT_SIGN_KEY_USAGE);
776             trace_usage_bit(usage.pbData[0], CERT_CRL_SIGN_KEY_USAGE);
777             trace_usage_bit(usage.pbData[0], CERT_ENCIPHER_ONLY_KEY_USAGE);
778         }
779 #undef trace_usage_bit
780         if (usage.cbData > 1 && usage.pbData[1] & CERT_DECIPHER_ONLY_KEY_USAGE)
781             TRACE_(chain)("CERT_DECIPHER_ONLY_KEY_USAGE\n");
782     }
783 }
784
785 static void dump_extension(const CERT_EXTENSION *ext)
786 {
787     TRACE_(chain)("%s (%scritical)\n", debugstr_a(ext->pszObjId),
788      ext->fCritical ? "" : "not ");
789     if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS))
790         dump_basic_constraints(ext);
791     else if (!strcmp(ext->pszObjId, szOID_KEY_USAGE))
792         dump_key_usage(ext);
793     else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS2))
794         dump_basic_constraints2(ext);
795 }
796
797 static LPCWSTR filetime_to_str(const FILETIME *time)
798 {
799     static WCHAR date[80];
800     WCHAR dateFmt[80]; /* sufficient for all versions of LOCALE_SSHORTDATE */
801     SYSTEMTIME sysTime;
802
803     if (!time) return NULL;
804
805     GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, dateFmt,
806      sizeof(dateFmt) / sizeof(dateFmt[0]));
807     FileTimeToSystemTime(time, &sysTime);
808     GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, date,
809      sizeof(date) / sizeof(date[0]));
810     return date;
811 }
812
813 static void dump_element(PCCERT_CONTEXT cert)
814 {
815     LPWSTR name = NULL;
816     DWORD len, i;
817
818     TRACE_(chain)("%p\n", cert);
819     len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
820      CERT_NAME_ISSUER_FLAG, NULL, NULL, 0);
821     name = CryptMemAlloc(len * sizeof(WCHAR));
822     if (name)
823     {
824         CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
825          CERT_NAME_ISSUER_FLAG, NULL, name, len);
826         TRACE_(chain)("issued by %s\n", debugstr_w(name));
827         CryptMemFree(name);
828     }
829     len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
830      NULL, 0);
831     name = CryptMemAlloc(len * sizeof(WCHAR));
832     if (name)
833     {
834         CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
835          name, len);
836         TRACE_(chain)("issued to %s\n", debugstr_w(name));
837         CryptMemFree(name);
838     }
839     TRACE_(chain)("valid from %s to %s\n",
840      debugstr_w(filetime_to_str(&cert->pCertInfo->NotBefore)),
841      debugstr_w(filetime_to_str(&cert->pCertInfo->NotAfter)));
842     TRACE_(chain)("%d extensions\n", cert->pCertInfo->cExtension);
843     for (i = 0; i < cert->pCertInfo->cExtension; i++)
844         dump_extension(&cert->pCertInfo->rgExtension[i]);
845 }
846
847 static BOOL CRYPT_KeyUsageValid(PCCERT_CONTEXT cert, BOOL isRoot, BOOL isCA,
848  DWORD index)
849 {
850     PCERT_EXTENSION ext;
851     BOOL ret;
852     BYTE usageBits = 0;
853
854     ext = CertFindExtension(szOID_KEY_USAGE, cert->pCertInfo->cExtension,
855      cert->pCertInfo->rgExtension);
856     if (ext)
857     {
858         CRYPT_BIT_BLOB usage;
859         DWORD size = sizeof(usage);
860
861         ret = CryptDecodeObjectEx(cert->dwCertEncodingType, X509_BITS,
862          ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL,
863          &usage, &size);
864         if (!ret)
865             return FALSE;
866         else if (usage.cbData > 2)
867         {
868             /* The key usage extension only defines 9 bits => no more than 2
869              * bytes are needed to encode all known usages.
870              */
871             return FALSE;
872         }
873         else
874         {
875             /* The only bit relevant to chain validation is the keyCertSign
876              * bit, which is always in the least significant byte of the
877              * key usage bits.
878              */
879             usageBits = usage.pbData[usage.cbData - 1];
880         }
881     }
882     if (isCA)
883     {
884         if (!ext)
885         {
886             /* MS appears to violate RFC 3280, section 4.2.1.3 (Key Usage)
887              * here.  Quoting the RFC:
888              * "This [key usage] extension MUST appear in certificates that
889              * contain public keys that are used to validate digital signatures
890              * on other public key certificates or CRLs."
891              * Most of the test chains' certs do not contain key usage
892              * extensions, yet are allowed to be CA certs.  This appears to
893              * be common usage too:  the root CA in a chain often does not have
894              * the key usage extension.  We are a little more restrictive:
895              * root certs, which commonly do not have any extensions, are
896              * allowed to sign certificates without the key usage extension.
897              */
898             WARN_(chain)("no key usage extension on a CA cert\n");
899             ret = isRoot;
900         }
901         else
902         {
903             if (!(usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
904             {
905                 WARN_(chain)("keyCertSign not asserted on a CA cert\n");
906                 ret = FALSE;
907             }
908             else
909                 ret = TRUE;
910         }
911     }
912     else
913     {
914         if (ext && (usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
915         {
916             WARN_(chain)("keyCertSign asserted on a non-CA cert\n");
917             ret = FALSE;
918         }
919         else
920             ret = TRUE;
921     }
922     return ret;
923 }
924
925 static BOOL CRYPT_CriticalExtensionsSupported(PCCERT_CONTEXT cert)
926 {
927     BOOL ret = TRUE;
928     DWORD i;
929
930     for (i = 0; ret && i < cert->pCertInfo->cExtension; i++)
931     {
932         if (cert->pCertInfo->rgExtension[i].fCritical)
933         {
934             LPCSTR oid = cert->pCertInfo->rgExtension[i].pszObjId;
935
936             if (!strcmp(oid, szOID_BASIC_CONSTRAINTS))
937                 ret = TRUE;
938             else if (!strcmp(oid, szOID_BASIC_CONSTRAINTS2))
939                 ret = TRUE;
940             else if (!strcmp(oid, szOID_NAME_CONSTRAINTS))
941                 ret = TRUE;
942             else if (!strcmp(oid, szOID_KEY_USAGE))
943                 ret = TRUE;
944             else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME))
945                 ret = TRUE;
946             else
947             {
948                 FIXME("unsupported critical extension %s\n",
949                  debugstr_a(oid));
950                 ret = FALSE;
951             }
952         }
953     }
954     return ret;
955 }
956
957 static void CRYPT_CheckSimpleChain(PCertificateChainEngine engine,
958  PCERT_SIMPLE_CHAIN chain, LPFILETIME time)
959 {
960     PCERT_CHAIN_ELEMENT rootElement = chain->rgpElement[chain->cElement - 1];
961     int i;
962     BOOL pathLengthConstraintViolated = FALSE;
963     CERT_BASIC_CONSTRAINTS2_INFO constraints = { FALSE, FALSE, 0 };
964
965     TRACE_(chain)("checking chain with %d elements for time %s\n",
966      chain->cElement, debugstr_w(filetime_to_str(time)));
967     for (i = chain->cElement - 1; i >= 0; i--)
968     {
969         BOOL isRoot;
970
971         if (TRACE_ON(chain))
972             dump_element(chain->rgpElement[i]->pCertContext);
973         if (CertVerifyTimeValidity(time,
974          chain->rgpElement[i]->pCertContext->pCertInfo) != 0)
975             chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
976              CERT_TRUST_IS_NOT_TIME_VALID;
977         if (i == chain->cElement - 1)
978             isRoot = CRYPT_IsCertificateSelfSigned(
979              chain->rgpElement[i]->pCertContext);
980         else
981             isRoot = FALSE;
982         if (i != 0)
983         {
984             /* Check the signature of the cert this issued */
985             if (!CryptVerifyCertificateSignatureEx(0, X509_ASN_ENCODING,
986              CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT,
987              (void *)chain->rgpElement[i - 1]->pCertContext,
988              CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT,
989              (void *)chain->rgpElement[i]->pCertContext, 0, NULL))
990                 chain->rgpElement[i - 1]->TrustStatus.dwErrorStatus |=
991                  CERT_TRUST_IS_NOT_SIGNATURE_VALID;
992             /* Once a path length constraint has been violated, every remaining
993              * CA cert's basic constraints is considered invalid.
994              */
995             if (pathLengthConstraintViolated)
996                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
997                  CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
998             else if (!CRYPT_CheckBasicConstraintsForCA(
999              chain->rgpElement[i]->pCertContext, &constraints, i - 1,
1000              isRoot, &pathLengthConstraintViolated))
1001                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1002                  CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1003             else if (constraints.fPathLenConstraint &&
1004              constraints.dwPathLenConstraint)
1005             {
1006                 /* This one's valid - decrement max length */
1007                 constraints.dwPathLenConstraint--;
1008             }
1009         }
1010         else
1011         {
1012             /* Check whether end cert has a basic constraints extension */
1013             if (!CRYPT_DecodeBasicConstraints(
1014              chain->rgpElement[i]->pCertContext, &constraints, FALSE))
1015                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1016                  CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1017         }
1018         if (!CRYPT_KeyUsageValid(chain->rgpElement[i]->pCertContext, isRoot,
1019          constraints.fCA, i))
1020             chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1021              CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
1022         if (CRYPT_IsSimpleChainCyclic(chain))
1023         {
1024             /* If the chain is cyclic, then the path length constraints
1025              * are violated, because the chain is infinitely long.
1026              */
1027             pathLengthConstraintViolated = TRUE;
1028             chain->TrustStatus.dwErrorStatus |=
1029              CERT_TRUST_IS_PARTIAL_CHAIN |
1030              CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1031         }
1032         /* Check whether every critical extension is supported */
1033         if (!CRYPT_CriticalExtensionsSupported(
1034          chain->rgpElement[i]->pCertContext))
1035             chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1036              CERT_TRUST_INVALID_EXTENSION;
1037         CRYPT_CombineTrustStatus(&chain->TrustStatus,
1038          &chain->rgpElement[i]->TrustStatus);
1039     }
1040     CRYPT_CheckChainNameConstraints(chain);
1041     if (CRYPT_IsCertificateSelfSigned(rootElement->pCertContext))
1042     {
1043         rootElement->TrustStatus.dwInfoStatus |=
1044          CERT_TRUST_IS_SELF_SIGNED | CERT_TRUST_HAS_NAME_MATCH_ISSUER;
1045         CRYPT_CheckRootCert(engine->hRoot, rootElement);
1046     }
1047     CRYPT_CombineTrustStatus(&chain->TrustStatus, &rootElement->TrustStatus);
1048 }
1049
1050 static PCCERT_CONTEXT CRYPT_GetIssuer(HCERTSTORE store, PCCERT_CONTEXT subject,
1051  PCCERT_CONTEXT prevIssuer, DWORD *infoStatus)
1052 {
1053     PCCERT_CONTEXT issuer = NULL;
1054     PCERT_EXTENSION ext;
1055     DWORD size;
1056
1057     *infoStatus = 0;
1058     if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
1059      subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1060     {
1061         CERT_AUTHORITY_KEY_ID_INFO *info;
1062         BOOL ret;
1063
1064         ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1065          X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
1066          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1067          &info, &size);
1068         if (ret)
1069         {
1070             CERT_ID id;
1071
1072             if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
1073             {
1074                 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1075                 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
1076                  sizeof(CERT_NAME_BLOB));
1077                 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1078                  &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
1079                 issuer = CertFindCertificateInStore(store,
1080                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1081                  prevIssuer);
1082                 if (issuer)
1083                     *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
1084             }
1085             else if (info->KeyId.cbData)
1086             {
1087                 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1088                 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1089                 issuer = CertFindCertificateInStore(store,
1090                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1091                  prevIssuer);
1092                 if (issuer)
1093                     *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
1094             }
1095             LocalFree(info);
1096         }
1097     }
1098     else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
1099      subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1100     {
1101         CERT_AUTHORITY_KEY_ID2_INFO *info;
1102         BOOL ret;
1103
1104         ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1105          X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
1106          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1107          &info, &size);
1108         if (ret)
1109         {
1110             CERT_ID id;
1111
1112             if (info->AuthorityCertIssuer.cAltEntry &&
1113              info->AuthorityCertSerialNumber.cbData)
1114             {
1115                 PCERT_ALT_NAME_ENTRY directoryName = NULL;
1116                 DWORD i;
1117
1118                 for (i = 0; !directoryName &&
1119                  i < info->AuthorityCertIssuer.cAltEntry; i++)
1120                     if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
1121                      == CERT_ALT_NAME_DIRECTORY_NAME)
1122                         directoryName =
1123                          &info->AuthorityCertIssuer.rgAltEntry[i];
1124                 if (directoryName)
1125                 {
1126                     id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1127                     memcpy(&id.u.IssuerSerialNumber.Issuer,
1128                      &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
1129                     memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1130                      &info->AuthorityCertSerialNumber,
1131                      sizeof(CRYPT_INTEGER_BLOB));
1132                     issuer = CertFindCertificateInStore(store,
1133                      subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1134                      prevIssuer);
1135                     if (issuer)
1136                         *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
1137                 }
1138                 else
1139                     FIXME("no supported name type in authority key id2\n");
1140             }
1141             else if (info->KeyId.cbData)
1142             {
1143                 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1144                 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1145                 issuer = CertFindCertificateInStore(store,
1146                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1147                  prevIssuer);
1148                 if (issuer)
1149                     *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
1150             }
1151             LocalFree(info);
1152         }
1153     }
1154     else
1155     {
1156         issuer = CertFindCertificateInStore(store,
1157          subject->dwCertEncodingType, 0, CERT_FIND_SUBJECT_NAME,
1158          &subject->pCertInfo->Issuer, prevIssuer);
1159         *infoStatus = CERT_TRUST_HAS_NAME_MATCH_ISSUER;
1160     }
1161     return issuer;
1162 }
1163
1164 /* Builds a simple chain by finding an issuer for the last cert in the chain,
1165  * until reaching a self-signed cert, or until no issuer can be found.
1166  */
1167 static BOOL CRYPT_BuildSimpleChain(const CertificateChainEngine *engine,
1168  HCERTSTORE world, PCERT_SIMPLE_CHAIN chain)
1169 {
1170     BOOL ret = TRUE;
1171     PCCERT_CONTEXT cert = chain->rgpElement[chain->cElement - 1]->pCertContext;
1172
1173     while (ret && !CRYPT_IsSimpleChainCyclic(chain) &&
1174      !CRYPT_IsCertificateSelfSigned(cert))
1175     {
1176         PCCERT_CONTEXT issuer = CRYPT_GetIssuer(world, cert, NULL,
1177          &chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
1178
1179         if (issuer)
1180         {
1181             ret = CRYPT_AddCertToSimpleChain(engine, chain, issuer,
1182              chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
1183             /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it to
1184              * close the enumeration that found it
1185              */
1186             CertFreeCertificateContext(issuer);
1187             cert = issuer;
1188         }
1189         else
1190         {
1191             TRACE_(chain)("Couldn't find issuer, halting chain creation\n");
1192             chain->TrustStatus.dwErrorStatus |= CERT_TRUST_IS_PARTIAL_CHAIN;
1193             break;
1194         }
1195     }
1196     return ret;
1197 }
1198
1199 static BOOL CRYPT_GetSimpleChainForCert(PCertificateChainEngine engine,
1200  HCERTSTORE world, PCCERT_CONTEXT cert, LPFILETIME pTime,
1201  PCERT_SIMPLE_CHAIN *ppChain)
1202 {
1203     BOOL ret = FALSE;
1204     PCERT_SIMPLE_CHAIN chain;
1205
1206     TRACE("(%p, %p, %p, %p)\n", engine, world, cert, pTime);
1207
1208     chain = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
1209     if (chain)
1210     {
1211         memset(chain, 0, sizeof(CERT_SIMPLE_CHAIN));
1212         chain->cbSize = sizeof(CERT_SIMPLE_CHAIN);
1213         ret = CRYPT_AddCertToSimpleChain(engine, chain, cert, 0);
1214         if (ret)
1215         {
1216             ret = CRYPT_BuildSimpleChain(engine, world, chain);
1217             if (ret)
1218                 CRYPT_CheckSimpleChain(engine, chain, pTime);
1219         }
1220         if (!ret)
1221         {
1222             CRYPT_FreeSimpleChain(chain);
1223             chain = NULL;
1224         }
1225         *ppChain = chain;
1226     }
1227     return ret;
1228 }
1229
1230 static BOOL CRYPT_BuildCandidateChainFromCert(HCERTCHAINENGINE hChainEngine,
1231  PCCERT_CONTEXT cert, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1232  PCertificateChain *ppChain)
1233 {
1234     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
1235     PCERT_SIMPLE_CHAIN simpleChain = NULL;
1236     HCERTSTORE world;
1237     BOOL ret;
1238
1239     world = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
1240      CERT_STORE_CREATE_NEW_FLAG, NULL);
1241     CertAddStoreToCollection(world, engine->hWorld, 0, 0);
1242     if (hAdditionalStore)
1243         CertAddStoreToCollection(world, hAdditionalStore, 0, 0);
1244     /* FIXME: only simple chains are supported for now, as CTLs aren't
1245      * supported yet.
1246      */
1247     if ((ret = CRYPT_GetSimpleChainForCert(engine, world, cert, pTime,
1248      &simpleChain)))
1249     {
1250         PCertificateChain chain = CryptMemAlloc(sizeof(CertificateChain));
1251
1252         if (chain)
1253         {
1254             chain->ref = 1;
1255             chain->world = world;
1256             chain->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
1257             chain->context.TrustStatus = simpleChain->TrustStatus;
1258             chain->context.cChain = 1;
1259             chain->context.rgpChain = CryptMemAlloc(sizeof(PCERT_SIMPLE_CHAIN));
1260             chain->context.rgpChain[0] = simpleChain;
1261             chain->context.cLowerQualityChainContext = 0;
1262             chain->context.rgpLowerQualityChainContext = NULL;
1263             chain->context.fHasRevocationFreshnessTime = FALSE;
1264             chain->context.dwRevocationFreshnessTime = 0;
1265         }
1266         else
1267             ret = FALSE;
1268         *ppChain = chain;
1269     }
1270     return ret;
1271 }
1272
1273 /* Makes and returns a copy of chain, up to and including element iElement. */
1274 static PCERT_SIMPLE_CHAIN CRYPT_CopySimpleChainToElement(
1275  const CERT_SIMPLE_CHAIN *chain, DWORD iElement)
1276 {
1277     PCERT_SIMPLE_CHAIN copy = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
1278
1279     if (copy)
1280     {
1281         memset(copy, 0, sizeof(CERT_SIMPLE_CHAIN));
1282         copy->cbSize = sizeof(CERT_SIMPLE_CHAIN);
1283         copy->rgpElement =
1284          CryptMemAlloc((iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
1285         if (copy->rgpElement)
1286         {
1287             DWORD i;
1288             BOOL ret = TRUE;
1289
1290             memset(copy->rgpElement, 0,
1291              (iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
1292             for (i = 0; ret && i <= iElement; i++)
1293             {
1294                 PCERT_CHAIN_ELEMENT element =
1295                  CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
1296
1297                 if (element)
1298                 {
1299                     *element = *chain->rgpElement[i];
1300                     element->pCertContext = CertDuplicateCertificateContext(
1301                      chain->rgpElement[i]->pCertContext);
1302                     /* Reset the trust status of the copied element, it'll get
1303                      * rechecked after the new chain is done.
1304                      */
1305                     memset(&element->TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
1306                     copy->rgpElement[copy->cElement++] = element;
1307                 }
1308                 else
1309                     ret = FALSE;
1310             }
1311             if (!ret)
1312             {
1313                 for (i = 0; i <= iElement; i++)
1314                     CryptMemFree(copy->rgpElement[i]);
1315                 CryptMemFree(copy->rgpElement);
1316                 CryptMemFree(copy);
1317                 copy = NULL;
1318             }
1319         }
1320         else
1321         {
1322             CryptMemFree(copy);
1323             copy = NULL;
1324         }
1325     }
1326     return copy;
1327 }
1328
1329 static void CRYPT_FreeLowerQualityChains(PCertificateChain chain)
1330 {
1331     DWORD i;
1332
1333     for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
1334         CertFreeCertificateChain(chain->context.rgpLowerQualityChainContext[i]);
1335     CryptMemFree(chain->context.rgpLowerQualityChainContext);
1336     chain->context.cLowerQualityChainContext = 0;
1337     chain->context.rgpLowerQualityChainContext = NULL;
1338 }
1339
1340 static void CRYPT_FreeChainContext(PCertificateChain chain)
1341 {
1342     DWORD i;
1343
1344     CRYPT_FreeLowerQualityChains(chain);
1345     for (i = 0; i < chain->context.cChain; i++)
1346         CRYPT_FreeSimpleChain(chain->context.rgpChain[i]);
1347     CryptMemFree(chain->context.rgpChain);
1348     CertCloseStore(chain->world, 0);
1349     CryptMemFree(chain);
1350 }
1351
1352 /* Makes and returns a copy of chain, up to and including element iElement of
1353  * simple chain iChain.
1354  */
1355 static PCertificateChain CRYPT_CopyChainToElement(PCertificateChain chain,
1356  DWORD iChain, DWORD iElement)
1357 {
1358     PCertificateChain copy = CryptMemAlloc(sizeof(CertificateChain));
1359
1360     if (copy)
1361     {
1362         copy->ref = 1;
1363         copy->world = CertDuplicateStore(chain->world);
1364         copy->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
1365         /* Leave the trust status of the copied chain unset, it'll get
1366          * rechecked after the new chain is done.
1367          */
1368         memset(&copy->context.TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
1369         copy->context.cLowerQualityChainContext = 0;
1370         copy->context.rgpLowerQualityChainContext = NULL;
1371         copy->context.fHasRevocationFreshnessTime = FALSE;
1372         copy->context.dwRevocationFreshnessTime = 0;
1373         copy->context.rgpChain = CryptMemAlloc(
1374          (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
1375         if (copy->context.rgpChain)
1376         {
1377             BOOL ret = TRUE;
1378             DWORD i;
1379
1380             memset(copy->context.rgpChain, 0,
1381              (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
1382             if (iChain)
1383             {
1384                 for (i = 0; ret && iChain && i < iChain - 1; i++)
1385                 {
1386                     copy->context.rgpChain[i] =
1387                      CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
1388                      chain->context.rgpChain[i]->cElement - 1);
1389                     if (!copy->context.rgpChain[i])
1390                         ret = FALSE;
1391                 }
1392             }
1393             else
1394                 i = 0;
1395             if (ret)
1396             {
1397                 copy->context.rgpChain[i] =
1398                  CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
1399                  iElement);
1400                 if (!copy->context.rgpChain[i])
1401                     ret = FALSE;
1402             }
1403             if (!ret)
1404             {
1405                 CRYPT_FreeChainContext(copy);
1406                 copy = NULL;
1407             }
1408             else
1409                 copy->context.cChain = iChain + 1;
1410         }
1411         else
1412         {
1413             CryptMemFree(copy);
1414             copy = NULL;
1415         }
1416     }
1417     return copy;
1418 }
1419
1420 static PCertificateChain CRYPT_BuildAlternateContextFromChain(
1421  HCERTCHAINENGINE hChainEngine, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1422  PCertificateChain chain)
1423 {
1424     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
1425     PCertificateChain alternate;
1426
1427     TRACE("(%p, %p, %p, %p)\n", hChainEngine, pTime, hAdditionalStore, chain);
1428
1429     /* Always start with the last "lower quality" chain to ensure a consistent
1430      * order of alternate creation:
1431      */
1432     if (chain->context.cLowerQualityChainContext)
1433         chain = (PCertificateChain)chain->context.rgpLowerQualityChainContext[
1434          chain->context.cLowerQualityChainContext - 1];
1435     /* A chain with only one element can't have any alternates */
1436     if (chain->context.cChain <= 1 && chain->context.rgpChain[0]->cElement <= 1)
1437         alternate = NULL;
1438     else
1439     {
1440         DWORD i, j, infoStatus;
1441         PCCERT_CONTEXT alternateIssuer = NULL;
1442
1443         alternate = NULL;
1444         for (i = 0; !alternateIssuer && i < chain->context.cChain; i++)
1445             for (j = 0; !alternateIssuer &&
1446              j < chain->context.rgpChain[i]->cElement - 1; j++)
1447             {
1448                 PCCERT_CONTEXT subject =
1449                  chain->context.rgpChain[i]->rgpElement[j]->pCertContext;
1450                 PCCERT_CONTEXT prevIssuer = CertDuplicateCertificateContext(
1451                  chain->context.rgpChain[i]->rgpElement[j + 1]->pCertContext);
1452
1453                 alternateIssuer = CRYPT_GetIssuer(prevIssuer->hCertStore,
1454                  subject, prevIssuer, &infoStatus);
1455             }
1456         if (alternateIssuer)
1457         {
1458             i--;
1459             j--;
1460             alternate = CRYPT_CopyChainToElement(chain, i, j);
1461             if (alternate)
1462             {
1463                 BOOL ret = CRYPT_AddCertToSimpleChain(engine,
1464                  alternate->context.rgpChain[i], alternateIssuer, infoStatus);
1465
1466                 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it
1467                  * to close the enumeration that found it
1468                  */
1469                 CertFreeCertificateContext(alternateIssuer);
1470                 if (ret)
1471                 {
1472                     ret = CRYPT_BuildSimpleChain(engine, alternate->world,
1473                      alternate->context.rgpChain[i]);
1474                     if (ret)
1475                         CRYPT_CheckSimpleChain(engine,
1476                          alternate->context.rgpChain[i], pTime);
1477                     CRYPT_CombineTrustStatus(&alternate->context.TrustStatus,
1478                      &alternate->context.rgpChain[i]->TrustStatus);
1479                 }
1480                 if (!ret)
1481                 {
1482                     CRYPT_FreeChainContext(alternate);
1483                     alternate = NULL;
1484                 }
1485             }
1486         }
1487     }
1488     TRACE("%p\n", alternate);
1489     return alternate;
1490 }
1491
1492 #define CHAIN_QUALITY_SIGNATURE_VALID 8
1493 #define CHAIN_QUALITY_TIME_VALID      4
1494 #define CHAIN_QUALITY_COMPLETE_CHAIN  2
1495 #define CHAIN_QUALITY_TRUSTED_ROOT    1
1496
1497 #define CHAIN_QUALITY_HIGHEST \
1498  CHAIN_QUALITY_SIGNATURE_VALID | CHAIN_QUALITY_TIME_VALID | \
1499  CHAIN_QUALITY_COMPLETE_CHAIN | CHAIN_QUALITY_TRUSTED_ROOT
1500
1501 #define IS_TRUST_ERROR_SET(TrustStatus, bits) \
1502  (TrustStatus)->dwErrorStatus & (bits)
1503
1504 static DWORD CRYPT_ChainQuality(const CertificateChain *chain)
1505 {
1506     DWORD quality = CHAIN_QUALITY_HIGHEST;
1507
1508     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1509      CERT_TRUST_IS_UNTRUSTED_ROOT))
1510         quality &= ~CHAIN_QUALITY_TRUSTED_ROOT;
1511     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1512      CERT_TRUST_IS_PARTIAL_CHAIN))
1513     if (chain->context.TrustStatus.dwErrorStatus & CERT_TRUST_IS_PARTIAL_CHAIN)
1514         quality &= ~CHAIN_QUALITY_COMPLETE_CHAIN;
1515     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1516      CERT_TRUST_IS_NOT_TIME_VALID | CERT_TRUST_IS_NOT_TIME_NESTED))
1517         quality &= ~CHAIN_QUALITY_TIME_VALID;
1518     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1519      CERT_TRUST_IS_NOT_SIGNATURE_VALID))
1520         quality &= ~CHAIN_QUALITY_SIGNATURE_VALID;
1521     return quality;
1522 }
1523
1524 /* Chooses the highest quality chain among chain and its "lower quality"
1525  * alternate chains.  Returns the highest quality chain, with all other
1526  * chains as lower quality chains of it.
1527  */
1528 static PCertificateChain CRYPT_ChooseHighestQualityChain(
1529  PCertificateChain chain)
1530 {
1531     DWORD i;
1532
1533     /* There are always only two chains being considered:  chain, and an
1534      * alternate at chain->rgpLowerQualityChainContext[i].  If the alternate
1535      * has a higher quality than chain, the alternate gets assigned the lower
1536      * quality contexts, with chain taking the alternate's place among the
1537      * lower quality contexts.
1538      */
1539     for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
1540     {
1541         PCertificateChain alternate =
1542          (PCertificateChain)chain->context.rgpLowerQualityChainContext[i];
1543
1544         if (CRYPT_ChainQuality(alternate) > CRYPT_ChainQuality(chain))
1545         {
1546             alternate->context.cLowerQualityChainContext =
1547              chain->context.cLowerQualityChainContext;
1548             alternate->context.rgpLowerQualityChainContext =
1549              chain->context.rgpLowerQualityChainContext;
1550             alternate->context.rgpLowerQualityChainContext[i] =
1551              (PCCERT_CHAIN_CONTEXT)chain;
1552             chain->context.cLowerQualityChainContext = 0;
1553             chain->context.rgpLowerQualityChainContext = NULL;
1554             chain = alternate;
1555         }
1556     }
1557     return chain;
1558 }
1559
1560 static BOOL CRYPT_AddAlternateChainToChain(PCertificateChain chain,
1561  const CertificateChain *alternate)
1562 {
1563     BOOL ret;
1564
1565     if (chain->context.cLowerQualityChainContext)
1566         chain->context.rgpLowerQualityChainContext =
1567          CryptMemRealloc(chain->context.rgpLowerQualityChainContext,
1568          (chain->context.cLowerQualityChainContext + 1) *
1569          sizeof(PCCERT_CHAIN_CONTEXT));
1570     else
1571         chain->context.rgpLowerQualityChainContext =
1572          CryptMemAlloc(sizeof(PCCERT_CHAIN_CONTEXT));
1573     if (chain->context.rgpLowerQualityChainContext)
1574     {
1575         chain->context.rgpLowerQualityChainContext[
1576          chain->context.cLowerQualityChainContext++] =
1577          (PCCERT_CHAIN_CONTEXT)alternate;
1578         ret = TRUE;
1579     }
1580     else
1581         ret = FALSE;
1582     return ret;
1583 }
1584
1585 static PCERT_CHAIN_ELEMENT CRYPT_FindIthElementInChain(
1586  const CERT_CHAIN_CONTEXT *chain, DWORD i)
1587 {
1588     DWORD j, iElement;
1589     PCERT_CHAIN_ELEMENT element = NULL;
1590
1591     for (j = 0, iElement = 0; !element && j < chain->cChain; j++)
1592     {
1593         if (iElement + chain->rgpChain[j]->cElement < i)
1594             iElement += chain->rgpChain[j]->cElement;
1595         else
1596             element = chain->rgpChain[j]->rgpElement[i - iElement];
1597     }
1598     return element;
1599 }
1600
1601 typedef struct _CERT_CHAIN_PARA_NO_EXTRA_FIELDS {
1602     DWORD            cbSize;
1603     CERT_USAGE_MATCH RequestedUsage;
1604 } CERT_CHAIN_PARA_NO_EXTRA_FIELDS, *PCERT_CHAIN_PARA_NO_EXTRA_FIELDS;
1605
1606 static void CRYPT_VerifyChainRevocation(PCERT_CHAIN_CONTEXT chain,
1607  LPFILETIME pTime, const CERT_CHAIN_PARA *pChainPara, DWORD chainFlags)
1608 {
1609     DWORD cContext;
1610
1611     if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_END_CERT)
1612         cContext = 1;
1613     else if ((chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN) ||
1614      (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT))
1615     {
1616         DWORD i;
1617
1618         for (i = 0, cContext = 0; i < chain->cChain; i++)
1619         {
1620             if (i < chain->cChain - 1 ||
1621              chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN)
1622                 cContext += chain->rgpChain[i]->cElement;
1623             else
1624                 cContext += chain->rgpChain[i]->cElement - 1;
1625         }
1626     }
1627     else
1628         cContext = 0;
1629     if (cContext)
1630     {
1631         PCCERT_CONTEXT *contexts =
1632          CryptMemAlloc(cContext * sizeof(PCCERT_CONTEXT *));
1633
1634         if (contexts)
1635         {
1636             DWORD i, j, iContext, revocationFlags;
1637             CERT_REVOCATION_PARA revocationPara = { sizeof(revocationPara), 0 };
1638             CERT_REVOCATION_STATUS revocationStatus =
1639              { sizeof(revocationStatus), 0 };
1640             BOOL ret;
1641
1642             for (i = 0, iContext = 0; iContext < cContext && i < chain->cChain;
1643              i++)
1644             {
1645                 for (j = 0; iContext < cContext &&
1646                  j < chain->rgpChain[i]->cElement; j++)
1647                     contexts[iContext++] =
1648                      chain->rgpChain[i]->rgpElement[j]->pCertContext;
1649             }
1650             revocationFlags = CERT_VERIFY_REV_CHAIN_FLAG;
1651             if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY)
1652                 revocationFlags |= CERT_VERIFY_CACHE_ONLY_BASED_REVOCATION;
1653             if (chainFlags & CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT)
1654                 revocationFlags |= CERT_VERIFY_REV_ACCUMULATIVE_TIMEOUT_FLAG;
1655             revocationPara.pftTimeToUse = pTime;
1656             if (pChainPara->cbSize == sizeof(CERT_CHAIN_PARA))
1657             {
1658                 revocationPara.dwUrlRetrievalTimeout =
1659                  pChainPara->dwUrlRetrievalTimeout;
1660                 revocationPara.fCheckFreshnessTime =
1661                  pChainPara->fCheckRevocationFreshnessTime;
1662                 revocationPara.dwFreshnessTime =
1663                  pChainPara->dwRevocationFreshnessTime;
1664             }
1665             ret = CertVerifyRevocation(X509_ASN_ENCODING,
1666              CERT_CONTEXT_REVOCATION_TYPE, cContext, (void **)contexts,
1667              revocationFlags, &revocationPara, &revocationStatus);
1668             if (!ret)
1669             {
1670                 PCERT_CHAIN_ELEMENT element =
1671                  CRYPT_FindIthElementInChain(chain, revocationStatus.dwIndex);
1672                 DWORD error;
1673
1674                 switch (revocationStatus.dwError)
1675                 {
1676                 case CRYPT_E_NO_REVOCATION_CHECK:
1677                 case CRYPT_E_NO_REVOCATION_DLL:
1678                 case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
1679                     error = CERT_TRUST_REVOCATION_STATUS_UNKNOWN;
1680                     break;
1681                 case CRYPT_E_REVOCATION_OFFLINE:
1682                     error = CERT_TRUST_IS_OFFLINE_REVOCATION;
1683                     break;
1684                 case CRYPT_E_REVOKED:
1685                     error = CERT_TRUST_IS_REVOKED;
1686                     break;
1687                 default:
1688                     WARN("unmapped error %08x\n", revocationStatus.dwError);
1689                     error = 0;
1690                 }
1691                 if (element)
1692                 {
1693                     /* FIXME: set element's pRevocationInfo member */
1694                     element->TrustStatus.dwErrorStatus |= error;
1695                 }
1696                 chain->TrustStatus.dwErrorStatus |= error;
1697             }
1698             CryptMemFree(contexts);
1699         }
1700     }
1701 }
1702
1703 BOOL WINAPI CertGetCertificateChain(HCERTCHAINENGINE hChainEngine,
1704  PCCERT_CONTEXT pCertContext, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1705  PCERT_CHAIN_PARA pChainPara, DWORD dwFlags, LPVOID pvReserved,
1706  PCCERT_CHAIN_CONTEXT* ppChainContext)
1707 {
1708     BOOL ret;
1709     PCertificateChain chain = NULL;
1710
1711     TRACE("(%p, %p, %p, %p, %p, %08x, %p, %p)\n", hChainEngine, pCertContext,
1712      pTime, hAdditionalStore, pChainPara, dwFlags, pvReserved, ppChainContext);
1713
1714     if (ppChainContext)
1715         *ppChainContext = NULL;
1716     if (!pChainPara)
1717     {
1718         SetLastError(E_INVALIDARG);
1719         return FALSE;
1720     }
1721     if (!pCertContext->pCertInfo->SignatureAlgorithm.pszObjId)
1722     {
1723         SetLastError(ERROR_INVALID_DATA);
1724         return FALSE;
1725     }
1726
1727     if (!hChainEngine)
1728         hChainEngine = CRYPT_GetDefaultChainEngine();
1729     /* FIXME: what about HCCE_LOCAL_MACHINE? */
1730     ret = CRYPT_BuildCandidateChainFromCert(hChainEngine, pCertContext, pTime,
1731      hAdditionalStore, &chain);
1732     if (ret)
1733     {
1734         PCertificateChain alternate = NULL;
1735         PCERT_CHAIN_CONTEXT pChain;
1736
1737         do {
1738             alternate = CRYPT_BuildAlternateContextFromChain(hChainEngine,
1739              pTime, hAdditionalStore, chain);
1740
1741             /* Alternate contexts are added as "lower quality" contexts of
1742              * chain, to avoid loops in alternate chain creation.
1743              * The highest-quality chain is chosen at the end.
1744              */
1745             if (alternate)
1746                 ret = CRYPT_AddAlternateChainToChain(chain, alternate);
1747         } while (ret && alternate);
1748         chain = CRYPT_ChooseHighestQualityChain(chain);
1749         if (!(dwFlags & CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS))
1750             CRYPT_FreeLowerQualityChains(chain);
1751         pChain = (PCERT_CHAIN_CONTEXT)chain;
1752         CRYPT_VerifyChainRevocation(pChain, pTime, pChainPara, dwFlags);
1753         if (ppChainContext)
1754             *ppChainContext = pChain;
1755         else
1756             CertFreeCertificateChain(pChain);
1757     }
1758     TRACE("returning %d\n", ret);
1759     return ret;
1760 }
1761
1762 PCCERT_CHAIN_CONTEXT WINAPI CertDuplicateCertificateChain(
1763  PCCERT_CHAIN_CONTEXT pChainContext)
1764 {
1765     PCertificateChain chain = (PCertificateChain)pChainContext;
1766
1767     TRACE("(%p)\n", pChainContext);
1768
1769     if (chain)
1770         InterlockedIncrement(&chain->ref);
1771     return pChainContext;
1772 }
1773
1774 VOID WINAPI CertFreeCertificateChain(PCCERT_CHAIN_CONTEXT pChainContext)
1775 {
1776     PCertificateChain chain = (PCertificateChain)pChainContext;
1777
1778     TRACE("(%p)\n", pChainContext);
1779
1780     if (chain)
1781     {
1782         if (InterlockedDecrement(&chain->ref) == 0)
1783             CRYPT_FreeChainContext(chain);
1784     }
1785 }
1786
1787 static void find_element_with_error(PCCERT_CHAIN_CONTEXT chain, DWORD error,
1788  LONG *iChain, LONG *iElement)
1789 {
1790     DWORD i, j;
1791
1792     for (i = 0; i < chain->cChain; i++)
1793         for (j = 0; j < chain->rgpChain[i]->cElement; j++)
1794             if (chain->rgpChain[i]->rgpElement[j]->TrustStatus.dwErrorStatus &
1795              error)
1796             {
1797                 *iChain = i;
1798                 *iElement = j;
1799                 return;
1800             }
1801 }
1802
1803 static BOOL WINAPI verify_base_policy(LPCSTR szPolicyOID,
1804  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1805  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
1806 {
1807     pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
1808     if (pChainContext->TrustStatus.dwErrorStatus &
1809      CERT_TRUST_IS_NOT_SIGNATURE_VALID)
1810     {
1811         pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
1812         find_element_with_error(pChainContext,
1813          CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
1814          &pPolicyStatus->lElementIndex);
1815     }
1816     else if (pChainContext->TrustStatus.dwErrorStatus &
1817      CERT_TRUST_IS_UNTRUSTED_ROOT)
1818     {
1819         pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
1820         find_element_with_error(pChainContext,
1821          CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
1822          &pPolicyStatus->lElementIndex);
1823     }
1824     else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
1825     {
1826         pPolicyStatus->dwError = CERT_E_CHAINING;
1827         find_element_with_error(pChainContext, CERT_TRUST_IS_CYCLIC,
1828          &pPolicyStatus->lChainIndex, &pPolicyStatus->lElementIndex);
1829         /* For a cyclic chain, which element is a cycle isn't meaningful */
1830         pPolicyStatus->lElementIndex = -1;
1831     }
1832     else
1833         pPolicyStatus->dwError = NO_ERROR;
1834     return TRUE;
1835 }
1836
1837 static BYTE msTestPubKey1[] = {
1838 0x30,0x47,0x02,0x40,0x81,0x55,0x22,0xb9,0x8a,0xa4,0x6f,0xed,0xd6,0xe7,0xd9,
1839 0x66,0x0f,0x55,0xbc,0xd7,0xcd,0xd5,0xbc,0x4e,0x40,0x02,0x21,0xa2,0xb1,0xf7,
1840 0x87,0x30,0x85,0x5e,0xd2,0xf2,0x44,0xb9,0xdc,0x9b,0x75,0xb6,0xfb,0x46,0x5f,
1841 0x42,0xb6,0x9d,0x23,0x36,0x0b,0xde,0x54,0x0f,0xcd,0xbd,0x1f,0x99,0x2a,0x10,
1842 0x58,0x11,0xcb,0x40,0xcb,0xb5,0xa7,0x41,0x02,0x03,0x01,0x00,0x01 };
1843 static BYTE msTestPubKey2[] = {
1844 0x30,0x47,0x02,0x40,0x9c,0x50,0x05,0x1d,0xe2,0x0e,0x4c,0x53,0xd8,0xd9,0xb5,
1845 0xe5,0xfd,0xe9,0xe3,0xad,0x83,0x4b,0x80,0x08,0xd9,0xdc,0xe8,0xe8,0x35,0xf8,
1846 0x11,0xf1,0xe9,0x9b,0x03,0x7a,0x65,0x64,0x76,0x35,0xce,0x38,0x2c,0xf2,0xb6,
1847 0x71,0x9e,0x06,0xd9,0xbf,0xbb,0x31,0x69,0xa3,0xf6,0x30,0xa0,0x78,0x7b,0x18,
1848 0xdd,0x50,0x4d,0x79,0x1e,0xeb,0x61,0xc1,0x02,0x03,0x01,0x00,0x01 };
1849
1850 static BOOL WINAPI verify_authenticode_policy(LPCSTR szPolicyOID,
1851  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1852  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
1853 {
1854     BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
1855      pPolicyStatus);
1856
1857     if (ret && pPolicyStatus->dwError == CERT_E_UNTRUSTEDROOT)
1858     {
1859         CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
1860         BOOL isMSTestRoot = FALSE;
1861         PCCERT_CONTEXT failingCert =
1862          pChainContext->rgpChain[pPolicyStatus->lChainIndex]->
1863          rgpElement[pPolicyStatus->lElementIndex]->pCertContext;
1864         DWORD i;
1865         CRYPT_DATA_BLOB keyBlobs[] = {
1866          { sizeof(msTestPubKey1), msTestPubKey1 },
1867          { sizeof(msTestPubKey2), msTestPubKey2 },
1868         };
1869
1870         /* Check whether the root is an MS test root */
1871         for (i = 0; !isMSTestRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
1872          i++)
1873         {
1874             msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
1875             msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
1876             if (CertComparePublicKeyInfo(
1877              X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1878              &failingCert->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
1879                 isMSTestRoot = TRUE;
1880         }
1881         if (isMSTestRoot)
1882             pPolicyStatus->dwError = CERT_E_UNTRUSTEDTESTROOT;
1883     }
1884     return ret;
1885 }
1886
1887 static BOOL WINAPI verify_basic_constraints_policy(LPCSTR szPolicyOID,
1888  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1889  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
1890 {
1891     pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
1892     if (pChainContext->TrustStatus.dwErrorStatus &
1893      CERT_TRUST_INVALID_BASIC_CONSTRAINTS)
1894     {
1895         pPolicyStatus->dwError = TRUST_E_BASIC_CONSTRAINTS;
1896         find_element_with_error(pChainContext,
1897          CERT_TRUST_INVALID_BASIC_CONSTRAINTS, &pPolicyStatus->lChainIndex,
1898          &pPolicyStatus->lElementIndex);
1899     }
1900     else
1901         pPolicyStatus->dwError = NO_ERROR;
1902     return TRUE;
1903 }
1904
1905 static BYTE msPubKey1[] = {
1906 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xdf,0x08,0xba,0xe3,0x3f,0x6e,
1907 0x64,0x9b,0xf5,0x89,0xaf,0x28,0x96,0x4a,0x07,0x8f,0x1b,0x2e,0x8b,0x3e,0x1d,
1908 0xfc,0xb8,0x80,0x69,0xa3,0xa1,0xce,0xdb,0xdf,0xb0,0x8e,0x6c,0x89,0x76,0x29,
1909 0x4f,0xca,0x60,0x35,0x39,0xad,0x72,0x32,0xe0,0x0b,0xae,0x29,0x3d,0x4c,0x16,
1910 0xd9,0x4b,0x3c,0x9d,0xda,0xc5,0xd3,0xd1,0x09,0xc9,0x2c,0x6f,0xa6,0xc2,0x60,
1911 0x53,0x45,0xdd,0x4b,0xd1,0x55,0xcd,0x03,0x1c,0xd2,0x59,0x56,0x24,0xf3,0xe5,
1912 0x78,0xd8,0x07,0xcc,0xd8,0xb3,0x1f,0x90,0x3f,0xc0,0x1a,0x71,0x50,0x1d,0x2d,
1913 0xa7,0x12,0x08,0x6d,0x7c,0xb0,0x86,0x6c,0xc7,0xba,0x85,0x32,0x07,0xe1,0x61,
1914 0x6f,0xaf,0x03,0xc5,0x6d,0xe5,0xd6,0xa1,0x8f,0x36,0xf6,0xc1,0x0b,0xd1,0x3e,
1915 0x69,0x97,0x48,0x72,0xc9,0x7f,0xa4,0xc8,0xc2,0x4a,0x4c,0x7e,0xa1,0xd1,0x94,
1916 0xa6,0xd7,0xdc,0xeb,0x05,0x46,0x2e,0xb8,0x18,0xb4,0x57,0x1d,0x86,0x49,0xdb,
1917 0x69,0x4a,0x2c,0x21,0xf5,0x5e,0x0f,0x54,0x2d,0x5a,0x43,0xa9,0x7a,0x7e,0x6a,
1918 0x8e,0x50,0x4d,0x25,0x57,0xa1,0xbf,0x1b,0x15,0x05,0x43,0x7b,0x2c,0x05,0x8d,
1919 0xbd,0x3d,0x03,0x8c,0x93,0x22,0x7d,0x63,0xea,0x0a,0x57,0x05,0x06,0x0a,0xdb,
1920 0x61,0x98,0x65,0x2d,0x47,0x49,0xa8,0xe7,0xe6,0x56,0x75,0x5c,0xb8,0x64,0x08,
1921 0x63,0xa9,0x30,0x40,0x66,0xb2,0xf9,0xb6,0xe3,0x34,0xe8,0x67,0x30,0xe1,0x43,
1922 0x0b,0x87,0xff,0xc9,0xbe,0x72,0x10,0x5e,0x23,0xf0,0x9b,0xa7,0x48,0x65,0xbf,
1923 0x09,0x88,0x7b,0xcd,0x72,0xbc,0x2e,0x79,0x9b,0x7b,0x02,0x03,0x01,0x00,0x01 };
1924 static BYTE msPubKey2[] = {
1925 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xa9,0x02,0xbd,0xc1,0x70,0xe6,
1926 0x3b,0xf2,0x4e,0x1b,0x28,0x9f,0x97,0x78,0x5e,0x30,0xea,0xa2,0xa9,0x8d,0x25,
1927 0x5f,0xf8,0xfe,0x95,0x4c,0xa3,0xb7,0xfe,0x9d,0xa2,0x20,0x3e,0x7c,0x51,0xa2,
1928 0x9b,0xa2,0x8f,0x60,0x32,0x6b,0xd1,0x42,0x64,0x79,0xee,0xac,0x76,0xc9,0x54,
1929 0xda,0xf2,0xeb,0x9c,0x86,0x1c,0x8f,0x9f,0x84,0x66,0xb3,0xc5,0x6b,0x7a,0x62,
1930 0x23,0xd6,0x1d,0x3c,0xde,0x0f,0x01,0x92,0xe8,0x96,0xc4,0xbf,0x2d,0x66,0x9a,
1931 0x9a,0x68,0x26,0x99,0xd0,0x3a,0x2c,0xbf,0x0c,0xb5,0x58,0x26,0xc1,0x46,0xe7,
1932 0x0a,0x3e,0x38,0x96,0x2c,0xa9,0x28,0x39,0xa8,0xec,0x49,0x83,0x42,0xe3,0x84,
1933 0x0f,0xbb,0x9a,0x6c,0x55,0x61,0xac,0x82,0x7c,0xa1,0x60,0x2d,0x77,0x4c,0xe9,
1934 0x99,0xb4,0x64,0x3b,0x9a,0x50,0x1c,0x31,0x08,0x24,0x14,0x9f,0xa9,0xe7,0x91,
1935 0x2b,0x18,0xe6,0x3d,0x98,0x63,0x14,0x60,0x58,0x05,0x65,0x9f,0x1d,0x37,0x52,
1936 0x87,0xf7,0xa7,0xef,0x94,0x02,0xc6,0x1b,0xd3,0xbf,0x55,0x45,0xb3,0x89,0x80,
1937 0xbf,0x3a,0xec,0x54,0x94,0x4e,0xae,0xfd,0xa7,0x7a,0x6d,0x74,0x4e,0xaf,0x18,
1938 0xcc,0x96,0x09,0x28,0x21,0x00,0x57,0x90,0x60,0x69,0x37,0xbb,0x4b,0x12,0x07,
1939 0x3c,0x56,0xff,0x5b,0xfb,0xa4,0x66,0x0a,0x08,0xa6,0xd2,0x81,0x56,0x57,0xef,
1940 0xb6,0x3b,0x5e,0x16,0x81,0x77,0x04,0xda,0xf6,0xbe,0xae,0x80,0x95,0xfe,0xb0,
1941 0xcd,0x7f,0xd6,0xa7,0x1a,0x72,0x5c,0x3c,0xca,0xbc,0xf0,0x08,0xa3,0x22,0x30,
1942 0xb3,0x06,0x85,0xc9,0xb3,0x20,0x77,0x13,0x85,0xdf,0x02,0x03,0x01,0x00,0x01 };
1943 static BYTE msPubKey3[] = {
1944 0x30,0x82,0x02,0x0a,0x02,0x82,0x02,0x01,0x00,0xf3,0x5d,0xfa,0x80,0x67,0xd4,
1945 0x5a,0xa7,0xa9,0x0c,0x2c,0x90,0x20,0xd0,0x35,0x08,0x3c,0x75,0x84,0xcd,0xb7,
1946 0x07,0x89,0x9c,0x89,0xda,0xde,0xce,0xc3,0x60,0xfa,0x91,0x68,0x5a,0x9e,0x94,
1947 0x71,0x29,0x18,0x76,0x7c,0xc2,0xe0,0xc8,0x25,0x76,0x94,0x0e,0x58,0xfa,0x04,
1948 0x34,0x36,0xe6,0xdf,0xaf,0xf7,0x80,0xba,0xe9,0x58,0x0b,0x2b,0x93,0xe5,0x9d,
1949 0x05,0xe3,0x77,0x22,0x91,0xf7,0x34,0x64,0x3c,0x22,0x91,0x1d,0x5e,0xe1,0x09,
1950 0x90,0xbc,0x14,0xfe,0xfc,0x75,0x58,0x19,0xe1,0x79,0xb7,0x07,0x92,0xa3,0xae,
1951 0x88,0x59,0x08,0xd8,0x9f,0x07,0xca,0x03,0x58,0xfc,0x68,0x29,0x6d,0x32,0xd7,
1952 0xd2,0xa8,0xcb,0x4b,0xfc,0xe1,0x0b,0x48,0x32,0x4f,0xe6,0xeb,0xb8,0xad,0x4f,
1953 0xe4,0x5c,0x6f,0x13,0x94,0x99,0xdb,0x95,0xd5,0x75,0xdb,0xa8,0x1a,0xb7,0x94,
1954 0x91,0xb4,0x77,0x5b,0xf5,0x48,0x0c,0x8f,0x6a,0x79,0x7d,0x14,0x70,0x04,0x7d,
1955 0x6d,0xaf,0x90,0xf5,0xda,0x70,0xd8,0x47,0xb7,0xbf,0x9b,0x2f,0x6c,0xe7,0x05,
1956 0xb7,0xe1,0x11,0x60,0xac,0x79,0x91,0x14,0x7c,0xc5,0xd6,0xa6,0xe4,0xe1,0x7e,
1957 0xd5,0xc3,0x7e,0xe5,0x92,0xd2,0x3c,0x00,0xb5,0x36,0x82,0xde,0x79,0xe1,0x6d,
1958 0xf3,0xb5,0x6e,0xf8,0x9f,0x33,0xc9,0xcb,0x52,0x7d,0x73,0x98,0x36,0xdb,0x8b,
1959 0xa1,0x6b,0xa2,0x95,0x97,0x9b,0xa3,0xde,0xc2,0x4d,0x26,0xff,0x06,0x96,0x67,
1960 0x25,0x06,0xc8,0xe7,0xac,0xe4,0xee,0x12,0x33,0x95,0x31,0x99,0xc8,0x35,0x08,
1961 0x4e,0x34,0xca,0x79,0x53,0xd5,0xb5,0xbe,0x63,0x32,0x59,0x40,0x36,0xc0,0xa5,
1962 0x4e,0x04,0x4d,0x3d,0xdb,0x5b,0x07,0x33,0xe4,0x58,0xbf,0xef,0x3f,0x53,0x64,
1963 0xd8,0x42,0x59,0x35,0x57,0xfd,0x0f,0x45,0x7c,0x24,0x04,0x4d,0x9e,0xd6,0x38,
1964 0x74,0x11,0x97,0x22,0x90,0xce,0x68,0x44,0x74,0x92,0x6f,0xd5,0x4b,0x6f,0xb0,
1965 0x86,0xe3,0xc7,0x36,0x42,0xa0,0xd0,0xfc,0xc1,0xc0,0x5a,0xf9,0xa3,0x61,0xb9,
1966 0x30,0x47,0x71,0x96,0x0a,0x16,0xb0,0x91,0xc0,0x42,0x95,0xef,0x10,0x7f,0x28,
1967 0x6a,0xe3,0x2a,0x1f,0xb1,0xe4,0xcd,0x03,0x3f,0x77,0x71,0x04,0xc7,0x20,0xfc,
1968 0x49,0x0f,0x1d,0x45,0x88,0xa4,0xd7,0xcb,0x7e,0x88,0xad,0x8e,0x2d,0xec,0x45,
1969 0xdb,0xc4,0x51,0x04,0xc9,0x2a,0xfc,0xec,0x86,0x9e,0x9a,0x11,0x97,0x5b,0xde,
1970 0xce,0x53,0x88,0xe6,0xe2,0xb7,0xfd,0xac,0x95,0xc2,0x28,0x40,0xdb,0xef,0x04,
1971 0x90,0xdf,0x81,0x33,0x39,0xd9,0xb2,0x45,0xa5,0x23,0x87,0x06,0xa5,0x55,0x89,
1972 0x31,0xbb,0x06,0x2d,0x60,0x0e,0x41,0x18,0x7d,0x1f,0x2e,0xb5,0x97,0xcb,0x11,
1973 0xeb,0x15,0xd5,0x24,0xa5,0x94,0xef,0x15,0x14,0x89,0xfd,0x4b,0x73,0xfa,0x32,
1974 0x5b,0xfc,0xd1,0x33,0x00,0xf9,0x59,0x62,0x70,0x07,0x32,0xea,0x2e,0xab,0x40,
1975 0x2d,0x7b,0xca,0xdd,0x21,0x67,0x1b,0x30,0x99,0x8f,0x16,0xaa,0x23,0xa8,0x41,
1976 0xd1,0xb0,0x6e,0x11,0x9b,0x36,0xc4,0xde,0x40,0x74,0x9c,0xe1,0x58,0x65,0xc1,
1977 0x60,0x1e,0x7a,0x5b,0x38,0xc8,0x8f,0xbb,0x04,0x26,0x7c,0xd4,0x16,0x40,0xe5,
1978 0xb6,0x6b,0x6c,0xaa,0x86,0xfd,0x00,0xbf,0xce,0xc1,0x35,0x02,0x03,0x01,0x00,
1979 0x01 };
1980
1981 static BOOL WINAPI verify_ms_root_policy(LPCSTR szPolicyOID,
1982  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1983  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
1984 {
1985     BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
1986      pPolicyStatus);
1987
1988     if (ret && !pPolicyStatus->dwError)
1989     {
1990         CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
1991         BOOL isMSRoot = FALSE;
1992         DWORD i;
1993         CRYPT_DATA_BLOB keyBlobs[] = {
1994          { sizeof(msPubKey1), msPubKey1 },
1995          { sizeof(msPubKey2), msPubKey2 },
1996          { sizeof(msPubKey3), msPubKey3 },
1997         };
1998         PCERT_SIMPLE_CHAIN rootChain =
1999          pChainContext->rgpChain[pChainContext->cChain -1 ];
2000         PCCERT_CONTEXT root =
2001          rootChain->rgpElement[rootChain->cElement - 1]->pCertContext;
2002
2003         for (i = 0; !isMSRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
2004          i++)
2005         {
2006             msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
2007             msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
2008             if (CertComparePublicKeyInfo(
2009              X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
2010              &root->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
2011                 isMSRoot = TRUE;
2012         }
2013         if (isMSRoot)
2014             pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = 0;
2015     }
2016     return ret;
2017 }
2018
2019 typedef BOOL (WINAPI *CertVerifyCertificateChainPolicyFunc)(LPCSTR szPolicyOID,
2020  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2021  PCERT_CHAIN_POLICY_STATUS pPolicyStatus);
2022
2023 BOOL WINAPI CertVerifyCertificateChainPolicy(LPCSTR szPolicyOID,
2024  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2025  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2026 {
2027     static HCRYPTOIDFUNCSET set = NULL;
2028     BOOL ret = FALSE;
2029     CertVerifyCertificateChainPolicyFunc verifyPolicy = NULL;
2030     HCRYPTOIDFUNCADDR hFunc = NULL;
2031
2032     TRACE("(%s, %p, %p, %p)\n", debugstr_a(szPolicyOID), pChainContext,
2033      pPolicyPara, pPolicyStatus);
2034
2035     if (!HIWORD(szPolicyOID))
2036     {
2037         switch (LOWORD(szPolicyOID))
2038         {
2039         case LOWORD(CERT_CHAIN_POLICY_BASE):
2040             verifyPolicy = verify_base_policy;
2041             break;
2042         case LOWORD(CERT_CHAIN_POLICY_AUTHENTICODE):
2043             verifyPolicy = verify_authenticode_policy;
2044             break;
2045         case LOWORD(CERT_CHAIN_POLICY_BASIC_CONSTRAINTS):
2046             verifyPolicy = verify_basic_constraints_policy;
2047             break;
2048         case LOWORD(CERT_CHAIN_POLICY_MICROSOFT_ROOT):
2049             verifyPolicy = verify_ms_root_policy;
2050             break;
2051         default:
2052             FIXME("unimplemented for %d\n", LOWORD(szPolicyOID));
2053         }
2054     }
2055     if (!verifyPolicy)
2056     {
2057         if (!set)
2058             set = CryptInitOIDFunctionSet(
2059              CRYPT_OID_VERIFY_CERTIFICATE_CHAIN_POLICY_FUNC, 0);
2060         CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING, szPolicyOID, 0,
2061          (void **)&verifyPolicy, &hFunc);
2062     }
2063     if (verifyPolicy)
2064         ret = verifyPolicy(szPolicyOID, pChainContext, pPolicyPara,
2065          pPolicyStatus);
2066     if (hFunc)
2067         CryptFreeOIDFunctionAddress(hFunc, 0);
2068     return ret;
2069 }