winex11.drv: Quiet a noisy FIXME.
[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 "wininet.h"
27 #include "wine/debug.h"
28 #include "wine/unicode.h"
29 #include "crypt32_private.h"
30
31 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
32 WINE_DECLARE_DEBUG_CHANNEL(chain);
33
34 #define DEFAULT_CYCLE_MODULUS 7
35
36 static HCERTCHAINENGINE CRYPT_defaultChainEngine;
37
38 /* This represents a subset of a certificate chain engine:  it doesn't include
39  * the "hOther" store described by MSDN, because I'm not sure how that's used.
40  * It also doesn't include the "hTrust" store, because I don't yet implement
41  * CTLs or complex certificate chains.
42  */
43 typedef struct _CertificateChainEngine
44 {
45     LONG       ref;
46     HCERTSTORE hRoot;
47     HCERTSTORE hWorld;
48     DWORD      dwFlags;
49     DWORD      dwUrlRetrievalTimeout;
50     DWORD      MaximumCachedCertificates;
51     DWORD      CycleDetectionModulus;
52 } CertificateChainEngine, *PCertificateChainEngine;
53
54 static inline void CRYPT_AddStoresToCollection(HCERTSTORE collection,
55  DWORD cStores, HCERTSTORE *stores)
56 {
57     DWORD i;
58
59     for (i = 0; i < cStores; i++)
60         CertAddStoreToCollection(collection, stores[i], 0, 0);
61 }
62
63 static inline void CRYPT_CloseStores(DWORD cStores, HCERTSTORE *stores)
64 {
65     DWORD i;
66
67     for (i = 0; i < cStores; i++)
68         CertCloseStore(stores[i], 0);
69 }
70
71 static const WCHAR rootW[] = { 'R','o','o','t',0 };
72
73 /* Finds cert in store by comparing the cert's hashes. */
74 static PCCERT_CONTEXT CRYPT_FindCertInStore(HCERTSTORE store,
75  PCCERT_CONTEXT cert)
76 {
77     PCCERT_CONTEXT matching = NULL;
78     BYTE hash[20];
79     DWORD size = sizeof(hash);
80
81     if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID, hash, &size))
82     {
83         CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
84
85         matching = CertFindCertificateInStore(store, cert->dwCertEncodingType,
86          0, CERT_FIND_SHA1_HASH, &blob, NULL);
87     }
88     return matching;
89 }
90
91 static BOOL CRYPT_CheckRestrictedRoot(HCERTSTORE store)
92 {
93     BOOL ret = TRUE;
94
95     if (store)
96     {
97         HCERTSTORE rootStore = CertOpenSystemStoreW(0, rootW);
98         PCCERT_CONTEXT cert = NULL, check;
99
100         do {
101             cert = CertEnumCertificatesInStore(store, cert);
102             if (cert)
103             {
104                 if (!(check = CRYPT_FindCertInStore(rootStore, cert)))
105                     ret = FALSE;
106                 else
107                     CertFreeCertificateContext(check);
108             }
109         } while (ret && cert);
110         if (cert)
111             CertFreeCertificateContext(cert);
112         CertCloseStore(rootStore, 0);
113     }
114     return ret;
115 }
116
117 HCERTCHAINENGINE CRYPT_CreateChainEngine(HCERTSTORE root,
118  PCERT_CHAIN_ENGINE_CONFIG pConfig)
119 {
120     static const WCHAR caW[] = { 'C','A',0 };
121     static const WCHAR myW[] = { 'M','y',0 };
122     static const WCHAR trustW[] = { 'T','r','u','s','t',0 };
123     PCertificateChainEngine engine =
124      CryptMemAlloc(sizeof(CertificateChainEngine));
125
126     if (engine)
127     {
128         HCERTSTORE worldStores[4];
129
130         engine->ref = 1;
131         engine->hRoot = root;
132         engine->hWorld = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
133          CERT_STORE_CREATE_NEW_FLAG, NULL);
134         worldStores[0] = CertDuplicateStore(engine->hRoot);
135         worldStores[1] = CertOpenSystemStoreW(0, caW);
136         worldStores[2] = CertOpenSystemStoreW(0, myW);
137         worldStores[3] = CertOpenSystemStoreW(0, trustW);
138         CRYPT_AddStoresToCollection(engine->hWorld,
139          sizeof(worldStores) / sizeof(worldStores[0]), worldStores);
140         CRYPT_AddStoresToCollection(engine->hWorld,
141          pConfig->cAdditionalStore, pConfig->rghAdditionalStore);
142         CRYPT_CloseStores(sizeof(worldStores) / sizeof(worldStores[0]),
143          worldStores);
144         engine->dwFlags = pConfig->dwFlags;
145         engine->dwUrlRetrievalTimeout = pConfig->dwUrlRetrievalTimeout;
146         engine->MaximumCachedCertificates =
147          pConfig->MaximumCachedCertificates;
148         if (pConfig->CycleDetectionModulus)
149             engine->CycleDetectionModulus = pConfig->CycleDetectionModulus;
150         else
151             engine->CycleDetectionModulus = DEFAULT_CYCLE_MODULUS;
152     }
153     return engine;
154 }
155
156 typedef struct _CERT_CHAIN_ENGINE_CONFIG_NO_EXCLUSIVE_ROOT
157 {
158     DWORD       cbSize;
159     HCERTSTORE  hRestrictedRoot;
160     HCERTSTORE  hRestrictedTrust;
161     HCERTSTORE  hRestrictedOther;
162     DWORD       cAdditionalStore;
163     HCERTSTORE *rghAdditionalStore;
164     DWORD       dwFlags;
165     DWORD       dwUrlRetrievalTimeout;
166     DWORD       MaximumCachedCertificates;
167     DWORD       CycleDetectionModulus;
168 } CERT_CHAIN_ENGINE_CONFIG_NO_EXCLUSIVE_ROOT;
169
170 BOOL WINAPI CertCreateCertificateChainEngine(PCERT_CHAIN_ENGINE_CONFIG pConfig,
171  HCERTCHAINENGINE *phChainEngine)
172 {
173     BOOL ret;
174
175     TRACE("(%p, %p)\n", pConfig, phChainEngine);
176
177     if (pConfig->cbSize != sizeof(CERT_CHAIN_ENGINE_CONFIG_NO_EXCLUSIVE_ROOT)
178      && pConfig->cbSize != sizeof(CERT_CHAIN_ENGINE_CONFIG))
179     {
180         SetLastError(E_INVALIDARG);
181         return FALSE;
182     }
183     *phChainEngine = NULL;
184     ret = CRYPT_CheckRestrictedRoot(pConfig->hRestrictedRoot);
185     if (ret)
186     {
187         HCERTSTORE root;
188         HCERTCHAINENGINE engine;
189
190         if (pConfig->cbSize >= sizeof(CERT_CHAIN_ENGINE_CONFIG) &&
191          pConfig->hExclusiveRoot)
192             root = CertDuplicateStore(pConfig->hExclusiveRoot);
193         else if (pConfig->hRestrictedRoot)
194             root = CertDuplicateStore(pConfig->hRestrictedRoot);
195         else
196             root = CertOpenSystemStoreW(0, rootW);
197         engine = CRYPT_CreateChainEngine(root, pConfig);
198         if (engine)
199         {
200             *phChainEngine = engine;
201             ret = TRUE;
202         }
203         else
204             ret = FALSE;
205     }
206     return ret;
207 }
208
209 VOID WINAPI CertFreeCertificateChainEngine(HCERTCHAINENGINE hChainEngine)
210 {
211     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
212
213     TRACE("(%p)\n", hChainEngine);
214
215     if (engine && InterlockedDecrement(&engine->ref) == 0)
216     {
217         CertCloseStore(engine->hWorld, 0);
218         CertCloseStore(engine->hRoot, 0);
219         CryptMemFree(engine);
220     }
221 }
222
223 static HCERTCHAINENGINE CRYPT_GetDefaultChainEngine(void)
224 {
225     if (!CRYPT_defaultChainEngine)
226     {
227         CERT_CHAIN_ENGINE_CONFIG config = { 0 };
228         HCERTCHAINENGINE engine;
229
230         config.cbSize = sizeof(config);
231         CertCreateCertificateChainEngine(&config, &engine);
232         InterlockedCompareExchangePointer(&CRYPT_defaultChainEngine, engine,
233          NULL);
234         if (CRYPT_defaultChainEngine != engine)
235             CertFreeCertificateChainEngine(engine);
236     }
237     return CRYPT_defaultChainEngine;
238 }
239
240 void default_chain_engine_free(void)
241 {
242     CertFreeCertificateChainEngine(CRYPT_defaultChainEngine);
243 }
244
245 typedef struct _CertificateChain
246 {
247     CERT_CHAIN_CONTEXT context;
248     HCERTSTORE world;
249     LONG ref;
250 } CertificateChain, *PCertificateChain;
251
252 static BOOL CRYPT_IsCertificateSelfSigned(PCCERT_CONTEXT cert)
253 {
254     PCERT_EXTENSION ext;
255     DWORD size;
256     BOOL ret;
257
258     if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
259      cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension)))
260     {
261         CERT_AUTHORITY_KEY_ID2_INFO *info;
262
263         ret = CryptDecodeObjectEx(cert->dwCertEncodingType,
264          X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
265          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
266          &info, &size);
267         if (ret)
268         {
269             if (info->AuthorityCertIssuer.cAltEntry &&
270              info->AuthorityCertSerialNumber.cbData)
271             {
272                 PCERT_ALT_NAME_ENTRY directoryName = NULL;
273                 DWORD i;
274
275                 for (i = 0; !directoryName &&
276                  i < info->AuthorityCertIssuer.cAltEntry; i++)
277                     if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
278                      == CERT_ALT_NAME_DIRECTORY_NAME)
279                         directoryName =
280                          &info->AuthorityCertIssuer.rgAltEntry[i];
281                 if (directoryName)
282                 {
283                     ret = CertCompareCertificateName(cert->dwCertEncodingType,
284                      &directoryName->u.DirectoryName, &cert->pCertInfo->Issuer)
285                      && CertCompareIntegerBlob(&info->AuthorityCertSerialNumber,
286                      &cert->pCertInfo->SerialNumber);
287                 }
288                 else
289                 {
290                     FIXME("no supported name type in authority key id2\n");
291                     ret = FALSE;
292                 }
293             }
294             else if (info->KeyId.cbData)
295             {
296                 ret = CertGetCertificateContextProperty(cert,
297                  CERT_KEY_IDENTIFIER_PROP_ID, NULL, &size);
298                 if (ret && size == info->KeyId.cbData)
299                 {
300                     LPBYTE buf = CryptMemAlloc(size);
301
302                     if (buf)
303                     {
304                         CertGetCertificateContextProperty(cert,
305                          CERT_KEY_IDENTIFIER_PROP_ID, buf, &size);
306                         ret = !memcmp(buf, info->KeyId.pbData, size);
307                         CryptMemFree(buf);
308                     }
309                 }
310                 else
311                     ret = FALSE;
312             }
313             LocalFree(info);
314         }
315     }
316     else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
317      cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension)))
318     {
319         CERT_AUTHORITY_KEY_ID_INFO *info;
320
321         ret = CryptDecodeObjectEx(cert->dwCertEncodingType,
322          X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
323          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
324          &info, &size);
325         if (ret)
326         {
327             if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
328             {
329                 ret = CertCompareCertificateName(cert->dwCertEncodingType,
330                  &info->CertIssuer, &cert->pCertInfo->Issuer) &&
331                  CertCompareIntegerBlob(&info->CertSerialNumber,
332                  &cert->pCertInfo->SerialNumber);
333             }
334             else if (info->KeyId.cbData)
335             {
336                 ret = CertGetCertificateContextProperty(cert,
337                  CERT_KEY_IDENTIFIER_PROP_ID, NULL, &size);
338                 if (ret && size == info->KeyId.cbData)
339                 {
340                     LPBYTE buf = CryptMemAlloc(size);
341
342                     if (buf)
343                     {
344                         CertGetCertificateContextProperty(cert,
345                          CERT_KEY_IDENTIFIER_PROP_ID, buf, &size);
346                         ret = !memcmp(buf, info->KeyId.pbData, size);
347                         CryptMemFree(buf);
348                     }
349                     else
350                         ret = FALSE;
351                 }
352                 else
353                     ret = FALSE;
354             }
355             else
356                 ret = FALSE;
357             LocalFree(info);
358         }
359     }
360     else
361         ret = CertCompareCertificateName(cert->dwCertEncodingType,
362          &cert->pCertInfo->Subject, &cert->pCertInfo->Issuer);
363     return ret;
364 }
365
366 static void CRYPT_FreeChainElement(PCERT_CHAIN_ELEMENT element)
367 {
368     CertFreeCertificateContext(element->pCertContext);
369     CryptMemFree(element);
370 }
371
372 static void CRYPT_CheckSimpleChainForCycles(PCERT_SIMPLE_CHAIN chain)
373 {
374     DWORD i, j, cyclicCertIndex = 0;
375
376     /* O(n^2) - I don't think there's a faster way */
377     for (i = 0; !cyclicCertIndex && i < chain->cElement; i++)
378         for (j = i + 1; !cyclicCertIndex && j < chain->cElement; j++)
379             if (CertCompareCertificate(X509_ASN_ENCODING,
380              chain->rgpElement[i]->pCertContext->pCertInfo,
381              chain->rgpElement[j]->pCertContext->pCertInfo))
382                 cyclicCertIndex = j;
383     if (cyclicCertIndex)
384     {
385         chain->rgpElement[cyclicCertIndex]->TrustStatus.dwErrorStatus
386          |= CERT_TRUST_IS_CYCLIC | CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
387         /* Release remaining certs */
388         for (i = cyclicCertIndex + 1; i < chain->cElement; i++)
389             CRYPT_FreeChainElement(chain->rgpElement[i]);
390         /* Truncate chain */
391         chain->cElement = cyclicCertIndex + 1;
392     }
393 }
394
395 /* Checks whether the chain is cyclic by examining the last element's status */
396 static inline BOOL CRYPT_IsSimpleChainCyclic(const CERT_SIMPLE_CHAIN *chain)
397 {
398     if (chain->cElement)
399         return chain->rgpElement[chain->cElement - 1]->TrustStatus.dwErrorStatus
400          & CERT_TRUST_IS_CYCLIC;
401     else
402         return FALSE;
403 }
404
405 static inline void CRYPT_CombineTrustStatus(CERT_TRUST_STATUS *chainStatus,
406  const CERT_TRUST_STATUS *elementStatus)
407 {
408     /* Any error that applies to an element also applies to a chain.. */
409     chainStatus->dwErrorStatus |= elementStatus->dwErrorStatus;
410     /* but the bottom nibble of an element's info status doesn't apply to the
411      * chain.
412      */
413     chainStatus->dwInfoStatus |= (elementStatus->dwInfoStatus & 0xfffffff0);
414 }
415
416 static BOOL CRYPT_AddCertToSimpleChain(const CertificateChainEngine *engine,
417  PCERT_SIMPLE_CHAIN chain, PCCERT_CONTEXT cert, DWORD subjectInfoStatus)
418 {
419     BOOL ret = FALSE;
420     PCERT_CHAIN_ELEMENT element = CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
421
422     if (element)
423     {
424         if (!chain->cElement)
425             chain->rgpElement = CryptMemAlloc(sizeof(PCERT_CHAIN_ELEMENT));
426         else
427             chain->rgpElement = CryptMemRealloc(chain->rgpElement,
428              (chain->cElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
429         if (chain->rgpElement)
430         {
431             chain->rgpElement[chain->cElement++] = element;
432             memset(element, 0, sizeof(CERT_CHAIN_ELEMENT));
433             element->cbSize = sizeof(CERT_CHAIN_ELEMENT);
434             element->pCertContext = CertDuplicateCertificateContext(cert);
435             if (chain->cElement > 1)
436                 chain->rgpElement[chain->cElement - 2]->TrustStatus.dwInfoStatus
437                  = subjectInfoStatus;
438             /* FIXME: initialize the rest of element */
439             if (!(chain->cElement % engine->CycleDetectionModulus))
440             {
441                 CRYPT_CheckSimpleChainForCycles(chain);
442                 /* Reinitialize the element pointer in case the chain is
443                  * cyclic, in which case the chain is truncated.
444                  */
445                 element = chain->rgpElement[chain->cElement - 1];
446             }
447             CRYPT_CombineTrustStatus(&chain->TrustStatus,
448              &element->TrustStatus);
449             ret = TRUE;
450         }
451         else
452             CryptMemFree(element);
453     }
454     return ret;
455 }
456
457 static void CRYPT_FreeSimpleChain(PCERT_SIMPLE_CHAIN chain)
458 {
459     DWORD i;
460
461     for (i = 0; i < chain->cElement; i++)
462         CRYPT_FreeChainElement(chain->rgpElement[i]);
463     CryptMemFree(chain->rgpElement);
464     CryptMemFree(chain);
465 }
466
467 static void CRYPT_CheckTrustedStatus(HCERTSTORE hRoot,
468  PCERT_CHAIN_ELEMENT rootElement)
469 {
470     PCCERT_CONTEXT trustedRoot = CRYPT_FindCertInStore(hRoot,
471      rootElement->pCertContext);
472
473     if (!trustedRoot)
474         rootElement->TrustStatus.dwErrorStatus |=
475          CERT_TRUST_IS_UNTRUSTED_ROOT;
476     else
477         CertFreeCertificateContext(trustedRoot);
478 }
479
480 static void CRYPT_CheckRootCert(HCERTCHAINENGINE hRoot,
481  PCERT_CHAIN_ELEMENT rootElement)
482 {
483     PCCERT_CONTEXT root = rootElement->pCertContext;
484
485     if (!CryptVerifyCertificateSignatureEx(0, root->dwCertEncodingType,
486      CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, (void *)root,
487      CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, (void *)root, 0, NULL))
488     {
489         TRACE_(chain)("Last certificate's signature is invalid\n");
490         rootElement->TrustStatus.dwErrorStatus |=
491          CERT_TRUST_IS_NOT_SIGNATURE_VALID;
492     }
493     CRYPT_CheckTrustedStatus(hRoot, rootElement);
494 }
495
496 /* Decodes a cert's basic constraints extension (either szOID_BASIC_CONSTRAINTS
497  * or szOID_BASIC_CONSTRAINTS2, whichever is present) into a
498  * CERT_BASIC_CONSTRAINTS2_INFO.  If it neither extension is present, sets
499  * constraints->fCA to defaultIfNotSpecified.
500  * Returns FALSE if the extension is present but couldn't be decoded.
501  */
502 static BOOL CRYPT_DecodeBasicConstraints(PCCERT_CONTEXT cert,
503  CERT_BASIC_CONSTRAINTS2_INFO *constraints, BOOL defaultIfNotSpecified)
504 {
505     BOOL ret = TRUE;
506     PCERT_EXTENSION ext = CertFindExtension(szOID_BASIC_CONSTRAINTS,
507      cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
508
509     constraints->fPathLenConstraint = FALSE;
510     if (ext)
511     {
512         CERT_BASIC_CONSTRAINTS_INFO *info;
513         DWORD size = 0;
514
515         ret = CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
516          ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
517          NULL, &info, &size);
518         if (ret)
519         {
520             if (info->SubjectType.cbData == 1)
521                 constraints->fCA =
522                  info->SubjectType.pbData[0] & CERT_CA_SUBJECT_FLAG;
523             LocalFree(info);
524         }
525     }
526     else
527     {
528         ext = CertFindExtension(szOID_BASIC_CONSTRAINTS2,
529          cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
530         if (ext)
531         {
532             DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
533
534             ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
535              szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
536              0, NULL, constraints, &size);
537         }
538         else
539             constraints->fCA = defaultIfNotSpecified;
540     }
541     return ret;
542 }
543
544 /* Checks element's basic constraints to see if it can act as a CA, with
545  * remainingCAs CAs left in this chain.  In general, a cert must include the
546  * basic constraints extension, with the CA flag asserted, in order to be
547  * allowed to be a CA.  A V1 or V2 cert, which has no extensions, is also
548  * allowed to be a CA if it's installed locally (in the engine's world store.)
549  * This matches the expected usage in RFC 5280, section 4.2.1.9:  a conforming
550  * CA MUST include the basic constraints extension in all certificates that are
551  * used to validate digital signatures on certificates.  It also matches
552  * section 6.1.4(k): "If a certificate is a v1 or v2 certificate, then the
553  * application MUST either verify that the certificate is a CA certificate
554  * through out-of-band means or reject the certificate." Rejecting the
555  * certificate prohibits a large number of commonly used certificates, so
556  * accepting locally installed ones is a compromise.
557  * Root certificates are also allowed to be CAs even without a basic
558  * constraints extension.  This is implied by RFC 5280, section 6.1:  the
559  * root of a certificate chain's only requirement is that it was used to issue
560  * the next certificate in the chain.
561  * Updates chainConstraints with the element's constraints, if:
562  * 1. chainConstraints doesn't have a path length constraint, or
563  * 2. element's path length constraint is smaller than chainConstraints's
564  * Sets *pathLengthConstraintViolated to TRUE if a path length violation
565  * occurs.
566  * Returns TRUE if the element can be a CA, and the length of the remaining
567  * chain is valid.
568  */
569 static BOOL CRYPT_CheckBasicConstraintsForCA(PCertificateChainEngine engine,
570  PCCERT_CONTEXT cert, CERT_BASIC_CONSTRAINTS2_INFO *chainConstraints,
571  DWORD remainingCAs, BOOL isRoot, BOOL *pathLengthConstraintViolated)
572 {
573     BOOL validBasicConstraints, implicitCA = FALSE;
574     CERT_BASIC_CONSTRAINTS2_INFO constraints;
575
576     if (isRoot)
577         implicitCA = TRUE;
578     else if (cert->pCertInfo->dwVersion == CERT_V1 ||
579      cert->pCertInfo->dwVersion == CERT_V2)
580     {
581         BYTE hash[20];
582         DWORD size = sizeof(hash);
583
584         if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID,
585          hash, &size))
586         {
587             CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
588             PCCERT_CONTEXT localCert = CertFindCertificateInStore(
589              engine->hWorld, cert->dwCertEncodingType, 0, CERT_FIND_SHA1_HASH,
590              &blob, NULL);
591
592             if (localCert)
593             {
594                 CertFreeCertificateContext(localCert);
595                 implicitCA = TRUE;
596             }
597         }
598     }
599     if ((validBasicConstraints = CRYPT_DecodeBasicConstraints(cert,
600      &constraints, implicitCA)))
601     {
602         chainConstraints->fCA = constraints.fCA;
603         if (!constraints.fCA)
604         {
605             TRACE_(chain)("chain element %d can't be a CA\n", remainingCAs + 1);
606             validBasicConstraints = FALSE;
607         }
608         else if (constraints.fPathLenConstraint)
609         {
610             /* If the element has path length constraints, they apply to the
611              * entire remaining chain.
612              */
613             if (!chainConstraints->fPathLenConstraint ||
614              constraints.dwPathLenConstraint <
615              chainConstraints->dwPathLenConstraint)
616             {
617                 TRACE_(chain)("setting path length constraint to %d\n",
618                  chainConstraints->dwPathLenConstraint);
619                 chainConstraints->fPathLenConstraint = TRUE;
620                 chainConstraints->dwPathLenConstraint =
621                  constraints.dwPathLenConstraint;
622             }
623         }
624     }
625     if (chainConstraints->fPathLenConstraint &&
626      remainingCAs > chainConstraints->dwPathLenConstraint)
627     {
628         TRACE_(chain)("remaining CAs %d exceed max path length %d\n",
629          remainingCAs, chainConstraints->dwPathLenConstraint);
630         validBasicConstraints = FALSE;
631         *pathLengthConstraintViolated = TRUE;
632     }
633     return validBasicConstraints;
634 }
635
636 static BOOL domain_name_matches(LPCWSTR constraint, LPCWSTR name)
637 {
638     BOOL match;
639
640     /* RFC 5280, section 4.2.1.10:
641      * "For URIs, the constraint applies to the host part of the name...
642      *  When the constraint begins with a period, it MAY be expanded with one
643      *  or more labels.  That is, the constraint ".example.com" is satisfied by
644      *  both host.example.com and my.host.example.com.  However, the constraint
645      *  ".example.com" is not satisfied by "example.com".  When the constraint
646      *  does not begin with a period, it specifies a host."
647      * and for email addresses,
648      * "To indicate all Internet mail addresses on a particular host, the
649      *  constraint is specified as the host name.  For example, the constraint
650      *  "example.com" is satisfied by any mail address at the host
651      *  "example.com".  To specify any address within a domain, the constraint
652      *  is specified with a leading period (as with URIs)."
653      */
654     if (constraint[0] == '.')
655     {
656         /* Must be strictly greater than, a name can't begin with '.' */
657         if (lstrlenW(name) > lstrlenW(constraint))
658             match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
659              constraint);
660         else
661         {
662             /* name is too short, no match */
663             match = FALSE;
664         }
665     }
666     else
667         match = !lstrcmpiW(name, constraint);
668      return match;
669 }
670
671 static BOOL url_matches(LPCWSTR constraint, LPCWSTR name,
672  DWORD *trustErrorStatus)
673 {
674     BOOL match = FALSE;
675
676     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
677
678     if (!constraint)
679         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
680     else if (!name)
681         ; /* no match */
682     else
683     {
684         LPCWSTR colon, authority_end, at, hostname = NULL;
685         /* The maximum length for a hostname is 254 in the DNS, see RFC 1034 */
686         WCHAR hostname_buf[255];
687
688         /* RFC 5280: only the hostname portion of the URL is compared.  From
689          * section 4.2.1.10:
690          * "For URIs, the constraint applies to the host part of the name.
691          *  The constraint MUST be specified as a fully qualified domain name
692          *  and MAY specify a host or a domain."
693          * The format for URIs is in RFC 2396.
694          *
695          * First, remove any scheme that's present. */
696         colon = strchrW(name, ':');
697         if (colon && *(colon + 1) == '/' && *(colon + 2) == '/')
698             name = colon + 3;
699         /* Next, find the end of the authority component.  (The authority is
700          * generally just the hostname, but it may contain a username or a port.
701          * Those are removed next.)
702          */
703         authority_end = strchrW(name, '/');
704         if (!authority_end)
705             authority_end = strchrW(name, '?');
706         if (!authority_end)
707             authority_end = name + strlenW(name);
708         /* Remove any port number from the authority.  The userinfo portion
709          * of an authority may contain a colon, so stop if a userinfo portion
710          * is found (indicated by '@').
711          */
712         for (colon = authority_end; colon >= name && *colon != ':' &&
713          *colon != '@'; colon--)
714             ;
715         if (*colon == ':')
716             authority_end = colon;
717         /* Remove any username from the authority */
718         if ((at = strchrW(name, '@')))
719             name = at;
720         /* Ignore any path or query portion of the URL. */
721         if (*authority_end)
722         {
723             if (authority_end - name < sizeof(hostname_buf) /
724              sizeof(hostname_buf[0]))
725             {
726                 memcpy(hostname_buf, name,
727                  (authority_end - name) * sizeof(WCHAR));
728                 hostname_buf[authority_end - name] = 0;
729                 hostname = hostname_buf;
730             }
731             /* else: Hostname is too long, not a match */
732         }
733         else
734             hostname = name;
735         if (hostname)
736             match = domain_name_matches(constraint, hostname);
737     }
738     return match;
739 }
740
741 static BOOL rfc822_name_matches(LPCWSTR constraint, LPCWSTR name,
742  DWORD *trustErrorStatus)
743 {
744     BOOL match = FALSE;
745     LPCWSTR at;
746
747     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
748
749     if (!constraint)
750         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
751     else if (!name)
752         ; /* no match */
753     else if (strchrW(constraint, '@'))
754         match = !lstrcmpiW(constraint, name);
755     else
756     {
757         if ((at = strchrW(name, '@')))
758             match = domain_name_matches(constraint, at + 1);
759         else
760             match = !lstrcmpiW(constraint, name);
761     }
762     return match;
763 }
764
765 static BOOL dns_name_matches(LPCWSTR constraint, LPCWSTR name,
766  DWORD *trustErrorStatus)
767 {
768     BOOL match = FALSE;
769
770     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
771
772     if (!constraint)
773         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
774     else if (!name)
775         ; /* no match */
776     /* RFC 5280, section 4.2.1.10:
777      * "DNS name restrictions are expressed as host.example.com.  Any DNS name
778      *  that can be constructed by simply adding zero or more labels to the
779      *  left-hand side of the name satisfies the name constraint.  For example,
780      *  www.host.example.com would satisfy the constraint but host1.example.com
781      *  would not."
782      */
783     else if (lstrlenW(name) == lstrlenW(constraint))
784         match = !lstrcmpiW(name, constraint);
785     else if (lstrlenW(name) > lstrlenW(constraint))
786     {
787         match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
788          constraint);
789         if (match)
790         {
791             BOOL dot = FALSE;
792             LPCWSTR ptr;
793
794             /* This only matches if name is a subdomain of constraint, i.e.
795              * there's a '.' between the beginning of the name and the
796              * matching portion of the name.
797              */
798             for (ptr = name + lstrlenW(name) - lstrlenW(constraint);
799              !dot && ptr >= name; ptr--)
800                 if (*ptr == '.')
801                     dot = TRUE;
802             match = dot;
803         }
804     }
805     /* else:  name is too short, no match */
806
807     return match;
808 }
809
810 static BOOL ip_address_matches(const CRYPT_DATA_BLOB *constraint,
811  const CRYPT_DATA_BLOB *name, DWORD *trustErrorStatus)
812 {
813     BOOL match = FALSE;
814
815     TRACE("(%d, %p), (%d, %p)\n", constraint->cbData, constraint->pbData,
816      name->cbData, name->pbData);
817
818     /* RFC5280, section 4.2.1.10, iPAddress syntax: either 8 or 32 bytes, for
819      * IPv4 or IPv6 addresses, respectively.
820      */
821     if (constraint->cbData != sizeof(DWORD) * 2 && constraint->cbData != 32)
822         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
823     else if (name->cbData == sizeof(DWORD) &&
824      constraint->cbData == sizeof(DWORD) * 2)
825     {
826         DWORD subnet, mask, addr;
827
828         memcpy(&subnet, constraint->pbData, sizeof(subnet));
829         memcpy(&mask, constraint->pbData + sizeof(subnet), sizeof(mask));
830         memcpy(&addr, name->pbData, sizeof(addr));
831         /* These are really in big-endian order, but for equality matching we
832          * don't need to swap to host order
833          */
834         match = (subnet & mask) == (addr & mask);
835     }
836     else if (name->cbData == 16 && constraint->cbData == 32)
837     {
838         const BYTE *subnet, *mask, *addr;
839         DWORD i;
840
841         subnet = constraint->pbData;
842         mask = constraint->pbData + 16;
843         addr = name->pbData;
844         match = TRUE;
845         for (i = 0; match && i < 16; i++)
846             if ((subnet[i] & mask[i]) != (addr[i] & mask[i]))
847                 match = FALSE;
848     }
849     /* else: name is wrong size, no match */
850
851     return match;
852 }
853
854 static BOOL directory_name_matches(const CERT_NAME_BLOB *constraint,
855  const CERT_NAME_BLOB *name)
856 {
857     CERT_NAME_INFO *constraintName;
858     DWORD size;
859     BOOL match = FALSE;
860
861     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME, constraint->pbData,
862      constraint->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &constraintName, &size))
863     {
864         DWORD i;
865
866         match = TRUE;
867         for (i = 0; match && i < constraintName->cRDN; i++)
868             match = CertIsRDNAttrsInCertificateName(X509_ASN_ENCODING,
869              CERT_CASE_INSENSITIVE_IS_RDN_ATTRS_FLAG,
870              (CERT_NAME_BLOB *)name, &constraintName->rgRDN[i]);
871         LocalFree(constraintName);
872     }
873     return match;
874 }
875
876 static BOOL alt_name_matches(const CERT_ALT_NAME_ENTRY *name,
877  const CERT_ALT_NAME_ENTRY *constraint, DWORD *trustErrorStatus, BOOL *present)
878 {
879     BOOL match = FALSE;
880
881     if (name->dwAltNameChoice == constraint->dwAltNameChoice)
882     {
883         if (present)
884             *present = TRUE;
885         switch (constraint->dwAltNameChoice)
886         {
887         case CERT_ALT_NAME_RFC822_NAME:
888             match = rfc822_name_matches(constraint->u.pwszURL,
889              name->u.pwszURL, trustErrorStatus);
890             break;
891         case CERT_ALT_NAME_DNS_NAME:
892             match = dns_name_matches(constraint->u.pwszURL,
893              name->u.pwszURL, trustErrorStatus);
894             break;
895         case CERT_ALT_NAME_URL:
896             match = url_matches(constraint->u.pwszURL,
897              name->u.pwszURL, trustErrorStatus);
898             break;
899         case CERT_ALT_NAME_IP_ADDRESS:
900             match = ip_address_matches(&constraint->u.IPAddress,
901              &name->u.IPAddress, trustErrorStatus);
902             break;
903         case CERT_ALT_NAME_DIRECTORY_NAME:
904             match = directory_name_matches(&constraint->u.DirectoryName,
905              &name->u.DirectoryName);
906             break;
907         default:
908             ERR("name choice %d unsupported in this context\n",
909              constraint->dwAltNameChoice);
910             *trustErrorStatus |=
911              CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
912         }
913     }
914     else if (present)
915         *present = FALSE;
916     return match;
917 }
918
919 static BOOL alt_name_matches_excluded_name(const CERT_ALT_NAME_ENTRY *name,
920  const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
921 {
922     DWORD i;
923     BOOL match = FALSE;
924
925     for (i = 0; !match && i < nameConstraints->cExcludedSubtree; i++)
926         match = alt_name_matches(name,
927          &nameConstraints->rgExcludedSubtree[i].Base, trustErrorStatus, NULL);
928     return match;
929 }
930
931 static BOOL alt_name_matches_permitted_name(const CERT_ALT_NAME_ENTRY *name,
932  const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus,
933  BOOL *present)
934 {
935     DWORD i;
936     BOOL match = FALSE;
937
938     for (i = 0; !match && i < nameConstraints->cPermittedSubtree; i++)
939         match = alt_name_matches(name,
940          &nameConstraints->rgPermittedSubtree[i].Base, trustErrorStatus,
941          present);
942     return match;
943 }
944
945 static inline PCERT_EXTENSION get_subject_alt_name_ext(const CERT_INFO *cert)
946 {
947     PCERT_EXTENSION ext;
948
949     ext = CertFindExtension(szOID_SUBJECT_ALT_NAME2,
950      cert->cExtension, cert->rgExtension);
951     if (!ext)
952         ext = CertFindExtension(szOID_SUBJECT_ALT_NAME,
953          cert->cExtension, cert->rgExtension);
954     return ext;
955 }
956
957 static void compare_alt_name_with_constraints(const CERT_EXTENSION *altNameExt,
958  const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
959 {
960     CERT_ALT_NAME_INFO *subjectAltName;
961     DWORD size;
962
963     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
964      altNameExt->Value.pbData, altNameExt->Value.cbData,
965      CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
966      &subjectAltName, &size))
967     {
968         DWORD i;
969
970         for (i = 0; i < subjectAltName->cAltEntry; i++)
971         {
972              BOOL nameFormPresent;
973
974              /* A name constraint only applies if the name form is present.
975               * From RFC 5280, section 4.2.1.10:
976               * "Restrictions apply only when the specified name form is
977               *  present.  If no name of the type is in the certificate,
978               *  the certificate is acceptable."
979               */
980             if (alt_name_matches_excluded_name(
981              &subjectAltName->rgAltEntry[i], nameConstraints,
982              trustErrorStatus))
983             {
984                 TRACE_(chain)("subject alternate name form %d excluded\n",
985                  subjectAltName->rgAltEntry[i].dwAltNameChoice);
986                 *trustErrorStatus |=
987                  CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
988             }
989             nameFormPresent = FALSE;
990             if (!alt_name_matches_permitted_name(
991              &subjectAltName->rgAltEntry[i], nameConstraints,
992              trustErrorStatus, &nameFormPresent) && nameFormPresent)
993             {
994                 TRACE_(chain)("subject alternate name form %d not permitted\n",
995                  subjectAltName->rgAltEntry[i].dwAltNameChoice);
996                 *trustErrorStatus |=
997                  CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
998             }
999         }
1000         LocalFree(subjectAltName);
1001     }
1002     else
1003         *trustErrorStatus |=
1004          CERT_TRUST_INVALID_EXTENSION | CERT_TRUST_INVALID_NAME_CONSTRAINTS;
1005 }
1006
1007 static BOOL rfc822_attr_matches_excluded_name(const CERT_RDN_ATTR *attr,
1008  const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
1009 {
1010     DWORD i;
1011     BOOL match = FALSE;
1012
1013     for (i = 0; !match && i < nameConstraints->cExcludedSubtree; i++)
1014     {
1015         const CERT_ALT_NAME_ENTRY *constraint =
1016          &nameConstraints->rgExcludedSubtree[i].Base;
1017
1018         if (constraint->dwAltNameChoice == CERT_ALT_NAME_RFC822_NAME)
1019             match = rfc822_name_matches(constraint->u.pwszRfc822Name,
1020              (LPCWSTR)attr->Value.pbData, trustErrorStatus);
1021     }
1022     return match;
1023 }
1024
1025 static BOOL rfc822_attr_matches_permitted_name(const CERT_RDN_ATTR *attr,
1026  const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus,
1027  BOOL *present)
1028 {
1029     DWORD i;
1030     BOOL match = FALSE;
1031
1032     for (i = 0; !match && i < nameConstraints->cPermittedSubtree; i++)
1033     {
1034         const CERT_ALT_NAME_ENTRY *constraint =
1035          &nameConstraints->rgPermittedSubtree[i].Base;
1036
1037         if (constraint->dwAltNameChoice == CERT_ALT_NAME_RFC822_NAME)
1038         {
1039             *present = TRUE;
1040             match = rfc822_name_matches(constraint->u.pwszRfc822Name,
1041              (LPCWSTR)attr->Value.pbData, trustErrorStatus);
1042         }
1043     }
1044     return match;
1045 }
1046
1047 static void compare_subject_with_email_constraints(
1048  const CERT_NAME_BLOB *subjectName,
1049  const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
1050 {
1051     CERT_NAME_INFO *name;
1052     DWORD size;
1053
1054     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_UNICODE_NAME,
1055      subjectName->pbData, subjectName->cbData,
1056      CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &name, &size))
1057     {
1058         DWORD i, j;
1059
1060         for (i = 0; i < name->cRDN; i++)
1061             for (j = 0; j < name->rgRDN[i].cRDNAttr; j++)
1062                 if (!strcmp(name->rgRDN[i].rgRDNAttr[j].pszObjId,
1063                  szOID_RSA_emailAddr))
1064                 {
1065                     BOOL nameFormPresent;
1066
1067                     /* A name constraint only applies if the name form is
1068                      * present.  From RFC 5280, section 4.2.1.10:
1069                      * "Restrictions apply only when the specified name form is
1070                      *  present.  If no name of the type is in the certificate,
1071                      *  the certificate is acceptable."
1072                      */
1073                     if (rfc822_attr_matches_excluded_name(
1074                      &name->rgRDN[i].rgRDNAttr[j], nameConstraints,
1075                      trustErrorStatus))
1076                     {
1077                         TRACE_(chain)(
1078                          "email address in subject name is excluded\n");
1079                         *trustErrorStatus |=
1080                          CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
1081                     }
1082                     nameFormPresent = FALSE;
1083                     if (!rfc822_attr_matches_permitted_name(
1084                      &name->rgRDN[i].rgRDNAttr[j], nameConstraints,
1085                      trustErrorStatus, &nameFormPresent) && nameFormPresent)
1086                     {
1087                         TRACE_(chain)(
1088                          "email address in subject name is not permitted\n");
1089                         *trustErrorStatus |=
1090                          CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
1091                     }
1092                 }
1093         LocalFree(name);
1094     }
1095     else
1096         *trustErrorStatus |=
1097          CERT_TRUST_INVALID_EXTENSION | CERT_TRUST_INVALID_NAME_CONSTRAINTS;
1098 }
1099
1100 static BOOL CRYPT_IsEmptyName(const CERT_NAME_BLOB *name)
1101 {
1102     BOOL empty;
1103
1104     if (!name->cbData)
1105         empty = TRUE;
1106     else if (name->cbData == 2 && name->pbData[1] == 0)
1107     {
1108         /* An empty sequence is also empty */
1109         empty = TRUE;
1110     }
1111     else
1112         empty = FALSE;
1113     return empty;
1114 }
1115
1116 static void compare_subject_with_constraints(const CERT_NAME_BLOB *subjectName,
1117  const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
1118 {
1119     BOOL hasEmailConstraint = FALSE;
1120     DWORD i;
1121
1122     /* In general, a subject distinguished name only matches a directory name
1123      * constraint.  However, an exception exists for email addresses.
1124      * From RFC 5280, section 4.2.1.6:
1125      * "Legacy implementations exist where an electronic mail address is
1126      *  embedded in the subject distinguished name as an emailAddress
1127      *  attribute [RFC2985]."
1128      * If an email address constraint exists, check that constraint separately.
1129      */
1130     for (i = 0; !hasEmailConstraint && i < nameConstraints->cExcludedSubtree;
1131      i++)
1132         if (nameConstraints->rgExcludedSubtree[i].Base.dwAltNameChoice ==
1133          CERT_ALT_NAME_RFC822_NAME)
1134             hasEmailConstraint = TRUE;
1135     for (i = 0; !hasEmailConstraint && i < nameConstraints->cPermittedSubtree;
1136      i++)
1137         if (nameConstraints->rgPermittedSubtree[i].Base.dwAltNameChoice ==
1138          CERT_ALT_NAME_RFC822_NAME)
1139             hasEmailConstraint = TRUE;
1140     if (hasEmailConstraint)
1141         compare_subject_with_email_constraints(subjectName, nameConstraints,
1142          trustErrorStatus);
1143     for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
1144     {
1145         CERT_ALT_NAME_ENTRY *constraint =
1146          &nameConstraints->rgExcludedSubtree[i].Base;
1147
1148         if (constraint->dwAltNameChoice == CERT_ALT_NAME_DIRECTORY_NAME &&
1149          directory_name_matches(&constraint->u.DirectoryName, subjectName))
1150         {
1151             TRACE_(chain)("subject name is excluded\n");
1152             *trustErrorStatus |=
1153              CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
1154         }
1155     }
1156     /* RFC 5280, section 4.2.1.10:
1157      * "Restrictions apply only when the specified name form is present.
1158      *  If no name of the type is in the certificate, the certificate is
1159      *  acceptable."
1160      * An empty name can't have the name form present, so don't check it.
1161      */
1162     if (nameConstraints->cPermittedSubtree && !CRYPT_IsEmptyName(subjectName))
1163     {
1164         BOOL match = FALSE, hasDirectoryConstraint = FALSE;
1165
1166         for (i = 0; !match && i < nameConstraints->cPermittedSubtree; i++)
1167         {
1168             CERT_ALT_NAME_ENTRY *constraint =
1169              &nameConstraints->rgPermittedSubtree[i].Base;
1170
1171             if (constraint->dwAltNameChoice == CERT_ALT_NAME_DIRECTORY_NAME)
1172             {
1173                 hasDirectoryConstraint = TRUE;
1174                 match = directory_name_matches(&constraint->u.DirectoryName,
1175                  subjectName);
1176             }
1177         }
1178         if (hasDirectoryConstraint && !match)
1179         {
1180             TRACE_(chain)("subject name is not permitted\n");
1181             *trustErrorStatus |= CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
1182         }
1183     }
1184 }
1185
1186 static void CRYPT_CheckNameConstraints(
1187  const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, const CERT_INFO *cert,
1188  DWORD *trustErrorStatus)
1189 {
1190     CERT_EXTENSION *ext = get_subject_alt_name_ext(cert);
1191
1192     if (ext)
1193         compare_alt_name_with_constraints(ext, nameConstraints,
1194          trustErrorStatus);
1195     /* Name constraints apply to the subject alternative name as well as the
1196      * subject name.  From RFC 5280, section 4.2.1.10:
1197      * "Restrictions apply to the subject distinguished name and apply to
1198      *  subject alternative names."
1199      */
1200     compare_subject_with_constraints(&cert->Subject, nameConstraints,
1201      trustErrorStatus);
1202 }
1203
1204 /* Gets cert's name constraints, if any.  Free with LocalFree. */
1205 static CERT_NAME_CONSTRAINTS_INFO *CRYPT_GetNameConstraints(CERT_INFO *cert)
1206 {
1207     CERT_NAME_CONSTRAINTS_INFO *info = NULL;
1208
1209     CERT_EXTENSION *ext;
1210
1211     if ((ext = CertFindExtension(szOID_NAME_CONSTRAINTS, cert->cExtension,
1212      cert->rgExtension)))
1213     {
1214         DWORD size;
1215
1216         CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
1217          ext->Value.pbData, ext->Value.cbData,
1218          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &info,
1219          &size);
1220     }
1221     return info;
1222 }
1223
1224 static BOOL CRYPT_IsValidNameConstraint(const CERT_NAME_CONSTRAINTS_INFO *info)
1225 {
1226     DWORD i;
1227     BOOL ret = TRUE;
1228
1229     /* Make sure at least one permitted or excluded subtree is present.  From
1230      * RFC 5280, section 4.2.1.10:
1231      * "Conforming CAs MUST NOT issue certificates where name constraints is an
1232      *  empty sequence.  That is, either the permittedSubtrees field or the
1233      *  excludedSubtrees MUST be present."
1234      */
1235     if (!info->cPermittedSubtree && !info->cExcludedSubtree)
1236     {
1237         WARN_(chain)("constraints contain no permitted nor excluded subtree\n");
1238         ret = FALSE;
1239     }
1240     /* Check that none of the constraints specifies a minimum or a maximum.
1241      * See RFC 5280, section 4.2.1.10:
1242      * "Within this profile, the minimum and maximum fields are not used with
1243      *  any name forms, thus, the minimum MUST be zero, and maximum MUST be
1244      *  absent.  However, if an application encounters a critical name
1245      *  constraints extension that specifies other values for minimum or
1246      *  maximum for a name form that appears in a subsequent certificate, the
1247      *  application MUST either process these fields or reject the
1248      *  certificate."
1249      * Since it gives no guidance as to how to process these fields, we
1250      * reject any name constraint that contains them.
1251      */
1252     for (i = 0; ret && i < info->cPermittedSubtree; i++)
1253         if (info->rgPermittedSubtree[i].dwMinimum ||
1254          info->rgPermittedSubtree[i].fMaximum)
1255         {
1256             TRACE_(chain)("found a minimum or maximum in permitted subtrees\n");
1257             ret = FALSE;
1258         }
1259     for (i = 0; ret && i < info->cExcludedSubtree; i++)
1260         if (info->rgExcludedSubtree[i].dwMinimum ||
1261          info->rgExcludedSubtree[i].fMaximum)
1262         {
1263             TRACE_(chain)("found a minimum or maximum in excluded subtrees\n");
1264             ret = FALSE;
1265         }
1266     return ret;
1267 }
1268
1269 static void CRYPT_CheckChainNameConstraints(PCERT_SIMPLE_CHAIN chain)
1270 {
1271     int i, j;
1272
1273     /* Microsoft's implementation appears to violate RFC 3280:  according to
1274      * MSDN, the various CERT_TRUST_*_NAME_CONSTRAINT errors are set if a CA's
1275      * name constraint is violated in the end cert.  According to RFC 3280,
1276      * the constraints should be checked against every subsequent certificate
1277      * in the chain, not just the end cert.
1278      * Microsoft's implementation also sets the name constraint errors on the
1279      * certs whose constraints were violated, not on the certs that violated
1280      * them.
1281      * In order to be error-compatible with Microsoft's implementation, while
1282      * still adhering to RFC 3280, I use a O(n ^ 2) algorithm to check name
1283      * constraints.
1284      */
1285     for (i = chain->cElement - 1; i > 0; i--)
1286     {
1287         CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
1288
1289         if ((nameConstraints = CRYPT_GetNameConstraints(
1290          chain->rgpElement[i]->pCertContext->pCertInfo)))
1291         {
1292             if (!CRYPT_IsValidNameConstraint(nameConstraints))
1293                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1294                  CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
1295             else
1296             {
1297                 for (j = i - 1; j >= 0; j--)
1298                 {
1299                     DWORD errorStatus = 0;
1300
1301                     /* According to RFC 3280, self-signed certs don't have name
1302                      * constraints checked unless they're the end cert.
1303                      */
1304                     if (j == 0 || !CRYPT_IsCertificateSelfSigned(
1305                      chain->rgpElement[j]->pCertContext))
1306                     {
1307                         CRYPT_CheckNameConstraints(nameConstraints,
1308                          chain->rgpElement[j]->pCertContext->pCertInfo,
1309                          &errorStatus);
1310                         if (errorStatus)
1311                         {
1312                             chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1313                              errorStatus;
1314                             CRYPT_CombineTrustStatus(&chain->TrustStatus,
1315                              &chain->rgpElement[i]->TrustStatus);
1316                         }
1317                         else
1318                             chain->rgpElement[i]->TrustStatus.dwInfoStatus |=
1319                              CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS;
1320                     }
1321                 }
1322             }
1323             LocalFree(nameConstraints);
1324         }
1325     }
1326 }
1327
1328 /* Gets cert's policies info, if any.  Free with LocalFree. */
1329 static CERT_POLICIES_INFO *CRYPT_GetPolicies(PCCERT_CONTEXT cert)
1330 {
1331     PCERT_EXTENSION ext;
1332     CERT_POLICIES_INFO *policies = NULL;
1333
1334     ext = CertFindExtension(szOID_KEY_USAGE, cert->pCertInfo->cExtension,
1335      cert->pCertInfo->rgExtension);
1336     if (ext)
1337     {
1338         DWORD size;
1339
1340         CryptDecodeObjectEx(X509_ASN_ENCODING, X509_CERT_POLICIES,
1341          ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1342          &policies, &size);
1343     }
1344     return policies;
1345 }
1346
1347 static void CRYPT_CheckPolicies(const CERT_POLICIES_INFO *policies, CERT_INFO *cert,
1348  DWORD *errorStatus)
1349 {
1350     DWORD i;
1351
1352     for (i = 0; i < policies->cPolicyInfo; i++)
1353     {
1354         /* For now, the only accepted policy identifier is the anyPolicy
1355          * identifier.
1356          * FIXME: the policy identifiers should be compared against the
1357          * cert's certificate policies extension, subject to the policy
1358          * mappings extension, and the policy constraints extension.
1359          * See RFC 5280, sections 4.2.1.4, 4.2.1.5, and 4.2.1.11.
1360          */
1361         if (strcmp(policies->rgPolicyInfo[i].pszPolicyIdentifier,
1362          szOID_ANY_CERT_POLICY))
1363         {
1364             FIXME("unsupported policy %s\n",
1365              policies->rgPolicyInfo[i].pszPolicyIdentifier);
1366             *errorStatus |= CERT_TRUST_INVALID_POLICY_CONSTRAINTS;
1367         }
1368     }
1369 }
1370
1371 static void CRYPT_CheckChainPolicies(PCERT_SIMPLE_CHAIN chain)
1372 {
1373     int i, j;
1374
1375     for (i = chain->cElement - 1; i > 0; i--)
1376     {
1377         CERT_POLICIES_INFO *policies;
1378
1379         if ((policies = CRYPT_GetPolicies(chain->rgpElement[i]->pCertContext)))
1380         {
1381             for (j = i - 1; j >= 0; j--)
1382             {
1383                 DWORD errorStatus = 0;
1384
1385                 CRYPT_CheckPolicies(policies,
1386                  chain->rgpElement[j]->pCertContext->pCertInfo, &errorStatus);
1387                 if (errorStatus)
1388                 {
1389                     chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1390                      errorStatus;
1391                     CRYPT_CombineTrustStatus(&chain->TrustStatus,
1392                      &chain->rgpElement[i]->TrustStatus);
1393                 }
1394             }
1395             LocalFree(policies);
1396         }
1397     }
1398 }
1399
1400 static LPWSTR name_value_to_str(const CERT_NAME_BLOB *name)
1401 {
1402     DWORD len = cert_name_to_str_with_indent(X509_ASN_ENCODING, 0, name,
1403      CERT_SIMPLE_NAME_STR, NULL, 0);
1404     LPWSTR str = NULL;
1405
1406     if (len)
1407     {
1408         str = CryptMemAlloc(len * sizeof(WCHAR));
1409         if (str)
1410             cert_name_to_str_with_indent(X509_ASN_ENCODING, 0, name,
1411              CERT_SIMPLE_NAME_STR, str, len);
1412     }
1413     return str;
1414 }
1415
1416 static void dump_alt_name_entry(const CERT_ALT_NAME_ENTRY *entry)
1417 {
1418     LPWSTR str;
1419
1420     switch (entry->dwAltNameChoice)
1421     {
1422     case CERT_ALT_NAME_OTHER_NAME:
1423         TRACE_(chain)("CERT_ALT_NAME_OTHER_NAME, oid = %s\n",
1424          debugstr_a(entry->u.pOtherName->pszObjId));
1425          break;
1426     case CERT_ALT_NAME_RFC822_NAME:
1427         TRACE_(chain)("CERT_ALT_NAME_RFC822_NAME: %s\n",
1428          debugstr_w(entry->u.pwszRfc822Name));
1429         break;
1430     case CERT_ALT_NAME_DNS_NAME:
1431         TRACE_(chain)("CERT_ALT_NAME_DNS_NAME: %s\n",
1432          debugstr_w(entry->u.pwszDNSName));
1433         break;
1434     case CERT_ALT_NAME_DIRECTORY_NAME:
1435         str = name_value_to_str(&entry->u.DirectoryName);
1436         TRACE_(chain)("CERT_ALT_NAME_DIRECTORY_NAME: %s\n", debugstr_w(str));
1437         CryptMemFree(str);
1438         break;
1439     case CERT_ALT_NAME_URL:
1440         TRACE_(chain)("CERT_ALT_NAME_URL: %s\n", debugstr_w(entry->u.pwszURL));
1441         break;
1442     case CERT_ALT_NAME_IP_ADDRESS:
1443         TRACE_(chain)("CERT_ALT_NAME_IP_ADDRESS: %d bytes\n",
1444          entry->u.IPAddress.cbData);
1445         break;
1446     case CERT_ALT_NAME_REGISTERED_ID:
1447         TRACE_(chain)("CERT_ALT_NAME_REGISTERED_ID: %s\n",
1448          debugstr_a(entry->u.pszRegisteredID));
1449         break;
1450     default:
1451         TRACE_(chain)("dwAltNameChoice = %d\n", entry->dwAltNameChoice);
1452     }
1453 }
1454
1455 static void dump_alt_name(LPCSTR type, const CERT_EXTENSION *ext)
1456 {
1457     CERT_ALT_NAME_INFO *name;
1458     DWORD size;
1459
1460     TRACE_(chain)("%s:\n", type);
1461     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
1462      ext->Value.pbData, ext->Value.cbData,
1463      CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &name, &size))
1464     {
1465         DWORD i;
1466
1467         TRACE_(chain)("%d alt name entries:\n", name->cAltEntry);
1468         for (i = 0; i < name->cAltEntry; i++)
1469             dump_alt_name_entry(&name->rgAltEntry[i]);
1470         LocalFree(name);
1471     }
1472 }
1473
1474 static void dump_basic_constraints(const CERT_EXTENSION *ext)
1475 {
1476     CERT_BASIC_CONSTRAINTS_INFO *info;
1477     DWORD size = 0;
1478
1479     if (CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
1480      ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
1481      NULL, &info, &size))
1482     {
1483         TRACE_(chain)("SubjectType: %02x\n", info->SubjectType.pbData[0]);
1484         TRACE_(chain)("%s path length constraint\n",
1485          info->fPathLenConstraint ? "has" : "doesn't have");
1486         TRACE_(chain)("path length=%d\n", info->dwPathLenConstraint);
1487         LocalFree(info);
1488     }
1489 }
1490
1491 static void dump_basic_constraints2(const CERT_EXTENSION *ext)
1492 {
1493     CERT_BASIC_CONSTRAINTS2_INFO constraints;
1494     DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
1495
1496     if (CryptDecodeObjectEx(X509_ASN_ENCODING,
1497      szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
1498      0, NULL, &constraints, &size))
1499     {
1500         TRACE_(chain)("basic constraints:\n");
1501         TRACE_(chain)("can%s be a CA\n", constraints.fCA ? "" : "not");
1502         TRACE_(chain)("%s path length constraint\n",
1503          constraints.fPathLenConstraint ? "has" : "doesn't have");
1504         TRACE_(chain)("path length=%d\n", constraints.dwPathLenConstraint);
1505     }
1506 }
1507
1508 static void dump_key_usage(const CERT_EXTENSION *ext)
1509 {
1510     CRYPT_BIT_BLOB usage;
1511     DWORD size = sizeof(usage);
1512
1513     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
1514      ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
1515     {
1516 #define trace_usage_bit(bits, bit) \
1517  if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
1518         if (usage.cbData)
1519         {
1520             trace_usage_bit(usage.pbData[0], CERT_DIGITAL_SIGNATURE_KEY_USAGE);
1521             trace_usage_bit(usage.pbData[0], CERT_NON_REPUDIATION_KEY_USAGE);
1522             trace_usage_bit(usage.pbData[0], CERT_KEY_ENCIPHERMENT_KEY_USAGE);
1523             trace_usage_bit(usage.pbData[0], CERT_DATA_ENCIPHERMENT_KEY_USAGE);
1524             trace_usage_bit(usage.pbData[0], CERT_KEY_AGREEMENT_KEY_USAGE);
1525             trace_usage_bit(usage.pbData[0], CERT_KEY_CERT_SIGN_KEY_USAGE);
1526             trace_usage_bit(usage.pbData[0], CERT_CRL_SIGN_KEY_USAGE);
1527             trace_usage_bit(usage.pbData[0], CERT_ENCIPHER_ONLY_KEY_USAGE);
1528         }
1529 #undef trace_usage_bit
1530         if (usage.cbData > 1 && usage.pbData[1] & CERT_DECIPHER_ONLY_KEY_USAGE)
1531             TRACE_(chain)("CERT_DECIPHER_ONLY_KEY_USAGE\n");
1532     }
1533 }
1534
1535 static void dump_general_subtree(const CERT_GENERAL_SUBTREE *subtree)
1536 {
1537     dump_alt_name_entry(&subtree->Base);
1538     TRACE_(chain)("dwMinimum = %d, fMaximum = %d, dwMaximum = %d\n",
1539      subtree->dwMinimum, subtree->fMaximum, subtree->dwMaximum);
1540 }
1541
1542 static void dump_name_constraints(const CERT_EXTENSION *ext)
1543 {
1544     CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
1545     DWORD size;
1546
1547     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
1548      ext->Value.pbData, ext->Value.cbData,
1549      CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &nameConstraints,
1550      &size))
1551     {
1552         DWORD i;
1553
1554         TRACE_(chain)("%d permitted subtrees:\n",
1555          nameConstraints->cPermittedSubtree);
1556         for (i = 0; i < nameConstraints->cPermittedSubtree; i++)
1557             dump_general_subtree(&nameConstraints->rgPermittedSubtree[i]);
1558         TRACE_(chain)("%d excluded subtrees:\n",
1559          nameConstraints->cExcludedSubtree);
1560         for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
1561             dump_general_subtree(&nameConstraints->rgExcludedSubtree[i]);
1562         LocalFree(nameConstraints);
1563     }
1564 }
1565
1566 static void dump_cert_policies(const CERT_EXTENSION *ext)
1567 {
1568     CERT_POLICIES_INFO *policies;
1569     DWORD size;
1570
1571     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_CERT_POLICIES,
1572      ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1573      &policies, &size))
1574     {
1575         DWORD i, j;
1576
1577         TRACE_(chain)("%d policies:\n", policies->cPolicyInfo);
1578         for (i = 0; i < policies->cPolicyInfo; i++)
1579         {
1580             TRACE_(chain)("policy identifier: %s\n",
1581              debugstr_a(policies->rgPolicyInfo[i].pszPolicyIdentifier));
1582             TRACE_(chain)("%d policy qualifiers:\n",
1583              policies->rgPolicyInfo[i].cPolicyQualifier);
1584             for (j = 0; j < policies->rgPolicyInfo[i].cPolicyQualifier; j++)
1585                 TRACE_(chain)("%s\n", debugstr_a(
1586                  policies->rgPolicyInfo[i].rgPolicyQualifier[j].
1587                  pszPolicyQualifierId));
1588         }
1589         LocalFree(policies);
1590     }
1591 }
1592
1593 static void dump_enhanced_key_usage(const CERT_EXTENSION *ext)
1594 {
1595     CERT_ENHKEY_USAGE *usage;
1596     DWORD size;
1597
1598     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ENHANCED_KEY_USAGE,
1599      ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1600      &usage, &size))
1601     {
1602         DWORD i;
1603
1604         TRACE_(chain)("%d usages:\n", usage->cUsageIdentifier);
1605         for (i = 0; i < usage->cUsageIdentifier; i++)
1606             TRACE_(chain)("%s\n", usage->rgpszUsageIdentifier[i]);
1607         LocalFree(usage);
1608     }
1609 }
1610
1611 static void dump_netscape_cert_type(const CERT_EXTENSION *ext)
1612 {
1613     CRYPT_BIT_BLOB usage;
1614     DWORD size = sizeof(usage);
1615
1616     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
1617      ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
1618     {
1619 #define trace_cert_type_bit(bits, bit) \
1620  if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
1621         if (usage.cbData)
1622         {
1623             trace_cert_type_bit(usage.pbData[0],
1624              NETSCAPE_SSL_CLIENT_AUTH_CERT_TYPE);
1625             trace_cert_type_bit(usage.pbData[0],
1626              NETSCAPE_SSL_SERVER_AUTH_CERT_TYPE);
1627             trace_cert_type_bit(usage.pbData[0], NETSCAPE_SMIME_CERT_TYPE);
1628             trace_cert_type_bit(usage.pbData[0], NETSCAPE_SIGN_CERT_TYPE);
1629             trace_cert_type_bit(usage.pbData[0], NETSCAPE_SSL_CA_CERT_TYPE);
1630             trace_cert_type_bit(usage.pbData[0], NETSCAPE_SMIME_CA_CERT_TYPE);
1631             trace_cert_type_bit(usage.pbData[0], NETSCAPE_SIGN_CA_CERT_TYPE);
1632         }
1633 #undef trace_cert_type_bit
1634     }
1635 }
1636
1637 static void dump_extension(const CERT_EXTENSION *ext)
1638 {
1639     TRACE_(chain)("%s (%scritical)\n", debugstr_a(ext->pszObjId),
1640      ext->fCritical ? "" : "not ");
1641     if (!strcmp(ext->pszObjId, szOID_SUBJECT_ALT_NAME))
1642         dump_alt_name("subject alt name", ext);
1643     else  if (!strcmp(ext->pszObjId, szOID_ISSUER_ALT_NAME))
1644         dump_alt_name("issuer alt name", ext);
1645     else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS))
1646         dump_basic_constraints(ext);
1647     else if (!strcmp(ext->pszObjId, szOID_KEY_USAGE))
1648         dump_key_usage(ext);
1649     else if (!strcmp(ext->pszObjId, szOID_SUBJECT_ALT_NAME2))
1650         dump_alt_name("subject alt name 2", ext);
1651     else if (!strcmp(ext->pszObjId, szOID_ISSUER_ALT_NAME2))
1652         dump_alt_name("issuer alt name 2", ext);
1653     else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS2))
1654         dump_basic_constraints2(ext);
1655     else if (!strcmp(ext->pszObjId, szOID_NAME_CONSTRAINTS))
1656         dump_name_constraints(ext);
1657     else if (!strcmp(ext->pszObjId, szOID_CERT_POLICIES))
1658         dump_cert_policies(ext);
1659     else if (!strcmp(ext->pszObjId, szOID_ENHANCED_KEY_USAGE))
1660         dump_enhanced_key_usage(ext);
1661     else if (!strcmp(ext->pszObjId, szOID_NETSCAPE_CERT_TYPE))
1662         dump_netscape_cert_type(ext);
1663 }
1664
1665 static LPCSTR filetime_to_str(const FILETIME *time)
1666 {
1667     static char date[80];
1668     char dateFmt[80]; /* sufficient for all versions of LOCALE_SSHORTDATE */
1669     SYSTEMTIME sysTime;
1670
1671     if (!time) return NULL;
1672
1673     GetLocaleInfoA(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, dateFmt,
1674      sizeof(dateFmt) / sizeof(dateFmt[0]));
1675     FileTimeToSystemTime(time, &sysTime);
1676     GetDateFormatA(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, date,
1677      sizeof(date) / sizeof(date[0]));
1678     return date;
1679 }
1680
1681 static void dump_element(PCCERT_CONTEXT cert)
1682 {
1683     LPWSTR name = NULL;
1684     DWORD len, i;
1685
1686     TRACE_(chain)("%p: version %d\n", cert, cert->pCertInfo->dwVersion);
1687     len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
1688      CERT_NAME_ISSUER_FLAG, NULL, NULL, 0);
1689     name = CryptMemAlloc(len * sizeof(WCHAR));
1690     if (name)
1691     {
1692         CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
1693          CERT_NAME_ISSUER_FLAG, NULL, name, len);
1694         TRACE_(chain)("issued by %s\n", debugstr_w(name));
1695         CryptMemFree(name);
1696     }
1697     len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
1698      NULL, 0);
1699     name = CryptMemAlloc(len * sizeof(WCHAR));
1700     if (name)
1701     {
1702         CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
1703          name, len);
1704         TRACE_(chain)("issued to %s\n", debugstr_w(name));
1705         CryptMemFree(name);
1706     }
1707     TRACE_(chain)("valid from %s to %s\n",
1708      filetime_to_str(&cert->pCertInfo->NotBefore),
1709      filetime_to_str(&cert->pCertInfo->NotAfter));
1710     TRACE_(chain)("%d extensions\n", cert->pCertInfo->cExtension);
1711     for (i = 0; i < cert->pCertInfo->cExtension; i++)
1712         dump_extension(&cert->pCertInfo->rgExtension[i]);
1713 }
1714
1715 static BOOL CRYPT_KeyUsageValid(PCertificateChainEngine engine,
1716  PCCERT_CONTEXT cert, BOOL isRoot, BOOL isCA, DWORD index)
1717 {
1718     PCERT_EXTENSION ext;
1719     BOOL ret;
1720     BYTE usageBits = 0;
1721
1722     ext = CertFindExtension(szOID_KEY_USAGE, cert->pCertInfo->cExtension,
1723      cert->pCertInfo->rgExtension);
1724     if (ext)
1725     {
1726         CRYPT_BIT_BLOB usage;
1727         DWORD size = sizeof(usage);
1728
1729         ret = CryptDecodeObjectEx(cert->dwCertEncodingType, X509_BITS,
1730          ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL,
1731          &usage, &size);
1732         if (!ret)
1733             return FALSE;
1734         else if (usage.cbData > 2)
1735         {
1736             /* The key usage extension only defines 9 bits => no more than 2
1737              * bytes are needed to encode all known usages.
1738              */
1739             return FALSE;
1740         }
1741         else
1742         {
1743             /* The only bit relevant to chain validation is the keyCertSign
1744              * bit, which is always in the least significant byte of the
1745              * key usage bits.
1746              */
1747             usageBits = usage.pbData[usage.cbData - 1];
1748         }
1749     }
1750     if (isCA)
1751     {
1752         if (!ext)
1753         {
1754             /* MS appears to violate RFC 5280, section 4.2.1.3 (Key Usage)
1755              * here.  Quoting the RFC:
1756              * "This [key usage] extension MUST appear in certificates that
1757              * contain public keys that are used to validate digital signatures
1758              * on other public key certificates or CRLs."
1759              * MS appears to accept certs that do not contain key usage
1760              * extensions as CA certs.  V1 and V2 certificates did not have
1761              * extensions, and many root certificates are V1 certificates, so
1762              * perhaps this is prudent.  On the other hand, MS also accepts V3
1763              * certs without key usage extensions.  We are more restrictive:
1764              * we accept locally installed V1 or V2 certs as CA certs.
1765              * We also accept a lack of key usage extension on root certs,
1766              * which is implied in RFC 5280, section 6.1:  the trust anchor's
1767              * only requirement is that it was used to issue the next
1768              * certificate in the chain.
1769              */
1770             if (isRoot)
1771                 ret = TRUE;
1772             else if (cert->pCertInfo->dwVersion == CERT_V1 ||
1773              cert->pCertInfo->dwVersion == CERT_V2)
1774             {
1775                 PCCERT_CONTEXT localCert = CRYPT_FindCertInStore(
1776                  engine->hWorld, cert);
1777
1778                 ret = localCert != NULL;
1779                 CertFreeCertificateContext(localCert);
1780             }
1781             else
1782                 ret = FALSE;
1783             if (!ret)
1784                 WARN_(chain)("no key usage extension on a CA cert\n");
1785         }
1786         else
1787         {
1788             if (!(usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
1789             {
1790                 WARN_(chain)("keyCertSign not asserted on a CA cert\n");
1791                 ret = FALSE;
1792             }
1793             else
1794                 ret = TRUE;
1795         }
1796     }
1797     else
1798     {
1799         if (ext && (usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
1800         {
1801             WARN_(chain)("keyCertSign asserted on a non-CA cert\n");
1802             ret = FALSE;
1803         }
1804         else
1805             ret = TRUE;
1806     }
1807     return ret;
1808 }
1809
1810 static BOOL CRYPT_CriticalExtensionsSupported(PCCERT_CONTEXT cert)
1811 {
1812     BOOL ret = TRUE;
1813     DWORD i;
1814
1815     for (i = 0; ret && i < cert->pCertInfo->cExtension; i++)
1816     {
1817         if (cert->pCertInfo->rgExtension[i].fCritical)
1818         {
1819             LPCSTR oid = cert->pCertInfo->rgExtension[i].pszObjId;
1820
1821             if (!strcmp(oid, szOID_BASIC_CONSTRAINTS))
1822                 ret = TRUE;
1823             else if (!strcmp(oid, szOID_BASIC_CONSTRAINTS2))
1824                 ret = TRUE;
1825             else if (!strcmp(oid, szOID_NAME_CONSTRAINTS))
1826                 ret = TRUE;
1827             else if (!strcmp(oid, szOID_KEY_USAGE))
1828                 ret = TRUE;
1829             else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME))
1830                 ret = TRUE;
1831             else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME2))
1832                 ret = TRUE;
1833             else if (!strcmp(oid, szOID_CERT_POLICIES))
1834                 ret = TRUE;
1835             else if (!strcmp(oid, szOID_ENHANCED_KEY_USAGE))
1836                 ret = TRUE;
1837             else
1838             {
1839                 FIXME("unsupported critical extension %s\n",
1840                  debugstr_a(oid));
1841                 ret = FALSE;
1842             }
1843         }
1844     }
1845     return ret;
1846 }
1847
1848 static BOOL CRYPT_IsCertVersionValid(PCCERT_CONTEXT cert)
1849 {
1850     BOOL ret = TRUE;
1851
1852     /* Checks whether the contents of the cert match the cert's version. */
1853     switch (cert->pCertInfo->dwVersion)
1854     {
1855     case CERT_V1:
1856         /* A V1 cert may not contain unique identifiers.  See RFC 5280,
1857          * section 4.1.2.8:
1858          * "These fields MUST only appear if the version is 2 or 3 (Section
1859          *  4.1.2.1).  These fields MUST NOT appear if the version is 1."
1860          */
1861         if (cert->pCertInfo->IssuerUniqueId.cbData ||
1862          cert->pCertInfo->SubjectUniqueId.cbData)
1863             ret = FALSE;
1864         /* A V1 cert may not contain extensions.  See RFC 5280, section 4.1.2.9:
1865          * "This field MUST only appear if the version is 3 (Section 4.1.2.1)."
1866          */
1867         if (cert->pCertInfo->cExtension)
1868             ret = FALSE;
1869         break;
1870     case CERT_V2:
1871         /* A V2 cert may not contain extensions.  See RFC 5280, section 4.1.2.9:
1872          * "This field MUST only appear if the version is 3 (Section 4.1.2.1)."
1873          */
1874         if (cert->pCertInfo->cExtension)
1875             ret = FALSE;
1876         break;
1877     case CERT_V3:
1878         /* Do nothing, all fields are allowed for V3 certs */
1879         break;
1880     default:
1881         WARN_(chain)("invalid cert version %d\n", cert->pCertInfo->dwVersion);
1882         ret = FALSE;
1883     }
1884     return ret;
1885 }
1886
1887 static void CRYPT_CheckSimpleChain(PCertificateChainEngine engine,
1888  PCERT_SIMPLE_CHAIN chain, LPFILETIME time)
1889 {
1890     PCERT_CHAIN_ELEMENT rootElement = chain->rgpElement[chain->cElement - 1];
1891     int i;
1892     BOOL pathLengthConstraintViolated = FALSE;
1893     CERT_BASIC_CONSTRAINTS2_INFO constraints = { FALSE, FALSE, 0 };
1894
1895     TRACE_(chain)("checking chain with %d elements for time %s\n",
1896      chain->cElement, filetime_to_str(time));
1897     for (i = chain->cElement - 1; i >= 0; i--)
1898     {
1899         BOOL isRoot;
1900
1901         if (TRACE_ON(chain))
1902             dump_element(chain->rgpElement[i]->pCertContext);
1903         if (i == chain->cElement - 1)
1904             isRoot = CRYPT_IsCertificateSelfSigned(
1905              chain->rgpElement[i]->pCertContext);
1906         else
1907             isRoot = FALSE;
1908         if (!CRYPT_IsCertVersionValid(chain->rgpElement[i]->pCertContext))
1909         {
1910             /* MS appears to accept certs whose versions don't match their
1911              * contents, so there isn't an appropriate error code.
1912              */
1913             chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1914              CERT_TRUST_INVALID_EXTENSION;
1915         }
1916         if (CertVerifyTimeValidity(time,
1917          chain->rgpElement[i]->pCertContext->pCertInfo) != 0)
1918             chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1919              CERT_TRUST_IS_NOT_TIME_VALID;
1920         if (i != 0)
1921         {
1922             /* Check the signature of the cert this issued */
1923             if (!CryptVerifyCertificateSignatureEx(0, X509_ASN_ENCODING,
1924              CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT,
1925              (void *)chain->rgpElement[i - 1]->pCertContext,
1926              CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT,
1927              (void *)chain->rgpElement[i]->pCertContext, 0, NULL))
1928                 chain->rgpElement[i - 1]->TrustStatus.dwErrorStatus |=
1929                  CERT_TRUST_IS_NOT_SIGNATURE_VALID;
1930             /* Once a path length constraint has been violated, every remaining
1931              * CA cert's basic constraints is considered invalid.
1932              */
1933             if (pathLengthConstraintViolated)
1934                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1935                  CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1936             else if (!CRYPT_CheckBasicConstraintsForCA(engine,
1937              chain->rgpElement[i]->pCertContext, &constraints, i - 1, isRoot,
1938              &pathLengthConstraintViolated))
1939                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1940                  CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1941             else if (constraints.fPathLenConstraint &&
1942              constraints.dwPathLenConstraint)
1943             {
1944                 /* This one's valid - decrement max length */
1945                 constraints.dwPathLenConstraint--;
1946             }
1947         }
1948         else
1949         {
1950             /* Check whether end cert has a basic constraints extension */
1951             if (!CRYPT_DecodeBasicConstraints(
1952              chain->rgpElement[i]->pCertContext, &constraints, FALSE))
1953                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1954                  CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1955         }
1956         if (!CRYPT_KeyUsageValid(engine, chain->rgpElement[i]->pCertContext,
1957          isRoot, constraints.fCA, i))
1958             chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1959              CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
1960         if (CRYPT_IsSimpleChainCyclic(chain))
1961         {
1962             /* If the chain is cyclic, then the path length constraints
1963              * are violated, because the chain is infinitely long.
1964              */
1965             pathLengthConstraintViolated = TRUE;
1966             chain->TrustStatus.dwErrorStatus |=
1967              CERT_TRUST_IS_PARTIAL_CHAIN |
1968              CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1969         }
1970         /* Check whether every critical extension is supported */
1971         if (!CRYPT_CriticalExtensionsSupported(
1972          chain->rgpElement[i]->pCertContext))
1973             chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1974              CERT_TRUST_INVALID_EXTENSION |
1975              CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT;
1976         CRYPT_CombineTrustStatus(&chain->TrustStatus,
1977          &chain->rgpElement[i]->TrustStatus);
1978     }
1979     CRYPT_CheckChainNameConstraints(chain);
1980     CRYPT_CheckChainPolicies(chain);
1981     if (CRYPT_IsCertificateSelfSigned(rootElement->pCertContext))
1982     {
1983         rootElement->TrustStatus.dwInfoStatus |=
1984          CERT_TRUST_IS_SELF_SIGNED | CERT_TRUST_HAS_NAME_MATCH_ISSUER;
1985         CRYPT_CheckRootCert(engine->hRoot, rootElement);
1986     }
1987     CRYPT_CombineTrustStatus(&chain->TrustStatus, &rootElement->TrustStatus);
1988 }
1989
1990 static PCCERT_CONTEXT CRYPT_GetIssuer(HCERTSTORE store, PCCERT_CONTEXT subject,
1991  PCCERT_CONTEXT prevIssuer, DWORD *infoStatus)
1992 {
1993     PCCERT_CONTEXT issuer = NULL;
1994     PCERT_EXTENSION ext;
1995     DWORD size;
1996
1997     *infoStatus = 0;
1998     if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
1999      subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
2000     {
2001         CERT_AUTHORITY_KEY_ID_INFO *info;
2002         BOOL ret;
2003
2004         ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
2005          X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
2006          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2007          &info, &size);
2008         if (ret)
2009         {
2010             CERT_ID id;
2011
2012             if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
2013             {
2014                 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
2015                 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
2016                  sizeof(CERT_NAME_BLOB));
2017                 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
2018                  &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
2019                 issuer = CertFindCertificateInStore(store,
2020                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
2021                  prevIssuer);
2022                 if (issuer)
2023                 {
2024                     TRACE_(chain)("issuer found by issuer/serial number\n");
2025                     *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
2026                 }
2027             }
2028             else if (info->KeyId.cbData)
2029             {
2030                 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
2031                 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
2032                 issuer = CertFindCertificateInStore(store,
2033                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
2034                  prevIssuer);
2035                 if (issuer)
2036                 {
2037                     TRACE_(chain)("issuer found by key id\n");
2038                     *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
2039                 }
2040             }
2041             LocalFree(info);
2042         }
2043     }
2044     else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
2045      subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
2046     {
2047         CERT_AUTHORITY_KEY_ID2_INFO *info;
2048         BOOL ret;
2049
2050         ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
2051          X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
2052          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2053          &info, &size);
2054         if (ret)
2055         {
2056             CERT_ID id;
2057
2058             if (info->AuthorityCertIssuer.cAltEntry &&
2059              info->AuthorityCertSerialNumber.cbData)
2060             {
2061                 PCERT_ALT_NAME_ENTRY directoryName = NULL;
2062                 DWORD i;
2063
2064                 for (i = 0; !directoryName &&
2065                  i < info->AuthorityCertIssuer.cAltEntry; i++)
2066                     if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
2067                      == CERT_ALT_NAME_DIRECTORY_NAME)
2068                         directoryName =
2069                          &info->AuthorityCertIssuer.rgAltEntry[i];
2070                 if (directoryName)
2071                 {
2072                     id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
2073                     memcpy(&id.u.IssuerSerialNumber.Issuer,
2074                      &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
2075                     memcpy(&id.u.IssuerSerialNumber.SerialNumber,
2076                      &info->AuthorityCertSerialNumber,
2077                      sizeof(CRYPT_INTEGER_BLOB));
2078                     issuer = CertFindCertificateInStore(store,
2079                      subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
2080                      prevIssuer);
2081                     if (issuer)
2082                     {
2083                         TRACE_(chain)("issuer found by directory name\n");
2084                         *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
2085                     }
2086                 }
2087                 else
2088                     FIXME("no supported name type in authority key id2\n");
2089             }
2090             else if (info->KeyId.cbData)
2091             {
2092                 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
2093                 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
2094                 issuer = CertFindCertificateInStore(store,
2095                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
2096                  prevIssuer);
2097                 if (issuer)
2098                 {
2099                     TRACE_(chain)("issuer found by key id\n");
2100                     *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
2101                 }
2102             }
2103             LocalFree(info);
2104         }
2105     }
2106     else
2107     {
2108         issuer = CertFindCertificateInStore(store,
2109          subject->dwCertEncodingType, 0, CERT_FIND_SUBJECT_NAME,
2110          &subject->pCertInfo->Issuer, prevIssuer);
2111         TRACE_(chain)("issuer found by name\n");
2112         *infoStatus = CERT_TRUST_HAS_NAME_MATCH_ISSUER;
2113     }
2114     return issuer;
2115 }
2116
2117 /* Builds a simple chain by finding an issuer for the last cert in the chain,
2118  * until reaching a self-signed cert, or until no issuer can be found.
2119  */
2120 static BOOL CRYPT_BuildSimpleChain(const CertificateChainEngine *engine,
2121  HCERTSTORE world, PCERT_SIMPLE_CHAIN chain)
2122 {
2123     BOOL ret = TRUE;
2124     PCCERT_CONTEXT cert = chain->rgpElement[chain->cElement - 1]->pCertContext;
2125
2126     while (ret && !CRYPT_IsSimpleChainCyclic(chain) &&
2127      !CRYPT_IsCertificateSelfSigned(cert))
2128     {
2129         PCCERT_CONTEXT issuer = CRYPT_GetIssuer(world, cert, NULL,
2130          &chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
2131
2132         if (issuer)
2133         {
2134             ret = CRYPT_AddCertToSimpleChain(engine, chain, issuer,
2135              chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
2136             /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it to
2137              * close the enumeration that found it
2138              */
2139             CertFreeCertificateContext(issuer);
2140             cert = issuer;
2141         }
2142         else
2143         {
2144             TRACE_(chain)("Couldn't find issuer, halting chain creation\n");
2145             chain->TrustStatus.dwErrorStatus |= CERT_TRUST_IS_PARTIAL_CHAIN;
2146             break;
2147         }
2148     }
2149     return ret;
2150 }
2151
2152 static LPCSTR debugstr_filetime(LPFILETIME pTime)
2153 {
2154     if (!pTime)
2155         return "(nil)";
2156     return wine_dbg_sprintf("%p (%s)", pTime, filetime_to_str(pTime));
2157 }
2158
2159 static BOOL CRYPT_GetSimpleChainForCert(PCertificateChainEngine engine,
2160  HCERTSTORE world, PCCERT_CONTEXT cert, LPFILETIME pTime,
2161  PCERT_SIMPLE_CHAIN *ppChain)
2162 {
2163     BOOL ret = FALSE;
2164     PCERT_SIMPLE_CHAIN chain;
2165
2166     TRACE("(%p, %p, %p, %s)\n", engine, world, cert, debugstr_filetime(pTime));
2167
2168     chain = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
2169     if (chain)
2170     {
2171         memset(chain, 0, sizeof(CERT_SIMPLE_CHAIN));
2172         chain->cbSize = sizeof(CERT_SIMPLE_CHAIN);
2173         ret = CRYPT_AddCertToSimpleChain(engine, chain, cert, 0);
2174         if (ret)
2175         {
2176             ret = CRYPT_BuildSimpleChain(engine, world, chain);
2177             if (ret)
2178                 CRYPT_CheckSimpleChain(engine, chain, pTime);
2179         }
2180         if (!ret)
2181         {
2182             CRYPT_FreeSimpleChain(chain);
2183             chain = NULL;
2184         }
2185         *ppChain = chain;
2186     }
2187     return ret;
2188 }
2189
2190 static BOOL CRYPT_BuildCandidateChainFromCert(HCERTCHAINENGINE hChainEngine,
2191  PCCERT_CONTEXT cert, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
2192  PCertificateChain *ppChain)
2193 {
2194     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
2195     PCERT_SIMPLE_CHAIN simpleChain = NULL;
2196     HCERTSTORE world;
2197     BOOL ret;
2198
2199     world = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
2200      CERT_STORE_CREATE_NEW_FLAG, NULL);
2201     CertAddStoreToCollection(world, engine->hWorld, 0, 0);
2202     if (hAdditionalStore)
2203         CertAddStoreToCollection(world, hAdditionalStore, 0, 0);
2204     /* FIXME: only simple chains are supported for now, as CTLs aren't
2205      * supported yet.
2206      */
2207     if ((ret = CRYPT_GetSimpleChainForCert(engine, world, cert, pTime,
2208      &simpleChain)))
2209     {
2210         PCertificateChain chain = CryptMemAlloc(sizeof(CertificateChain));
2211
2212         if (chain)
2213         {
2214             chain->ref = 1;
2215             chain->world = world;
2216             chain->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
2217             chain->context.TrustStatus = simpleChain->TrustStatus;
2218             chain->context.cChain = 1;
2219             chain->context.rgpChain = CryptMemAlloc(sizeof(PCERT_SIMPLE_CHAIN));
2220             chain->context.rgpChain[0] = simpleChain;
2221             chain->context.cLowerQualityChainContext = 0;
2222             chain->context.rgpLowerQualityChainContext = NULL;
2223             chain->context.fHasRevocationFreshnessTime = FALSE;
2224             chain->context.dwRevocationFreshnessTime = 0;
2225         }
2226         else
2227             ret = FALSE;
2228         *ppChain = chain;
2229     }
2230     return ret;
2231 }
2232
2233 /* Makes and returns a copy of chain, up to and including element iElement. */
2234 static PCERT_SIMPLE_CHAIN CRYPT_CopySimpleChainToElement(
2235  const CERT_SIMPLE_CHAIN *chain, DWORD iElement)
2236 {
2237     PCERT_SIMPLE_CHAIN copy = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
2238
2239     if (copy)
2240     {
2241         memset(copy, 0, sizeof(CERT_SIMPLE_CHAIN));
2242         copy->cbSize = sizeof(CERT_SIMPLE_CHAIN);
2243         copy->rgpElement =
2244          CryptMemAlloc((iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
2245         if (copy->rgpElement)
2246         {
2247             DWORD i;
2248             BOOL ret = TRUE;
2249
2250             memset(copy->rgpElement, 0,
2251              (iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
2252             for (i = 0; ret && i <= iElement; i++)
2253             {
2254                 PCERT_CHAIN_ELEMENT element =
2255                  CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
2256
2257                 if (element)
2258                 {
2259                     *element = *chain->rgpElement[i];
2260                     element->pCertContext = CertDuplicateCertificateContext(
2261                      chain->rgpElement[i]->pCertContext);
2262                     /* Reset the trust status of the copied element, it'll get
2263                      * rechecked after the new chain is done.
2264                      */
2265                     memset(&element->TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
2266                     copy->rgpElement[copy->cElement++] = element;
2267                 }
2268                 else
2269                     ret = FALSE;
2270             }
2271             if (!ret)
2272             {
2273                 for (i = 0; i <= iElement; i++)
2274                     CryptMemFree(copy->rgpElement[i]);
2275                 CryptMemFree(copy->rgpElement);
2276                 CryptMemFree(copy);
2277                 copy = NULL;
2278             }
2279         }
2280         else
2281         {
2282             CryptMemFree(copy);
2283             copy = NULL;
2284         }
2285     }
2286     return copy;
2287 }
2288
2289 static void CRYPT_FreeLowerQualityChains(PCertificateChain chain)
2290 {
2291     DWORD i;
2292
2293     for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
2294         CertFreeCertificateChain(chain->context.rgpLowerQualityChainContext[i]);
2295     CryptMemFree(chain->context.rgpLowerQualityChainContext);
2296     chain->context.cLowerQualityChainContext = 0;
2297     chain->context.rgpLowerQualityChainContext = NULL;
2298 }
2299
2300 static void CRYPT_FreeChainContext(PCertificateChain chain)
2301 {
2302     DWORD i;
2303
2304     CRYPT_FreeLowerQualityChains(chain);
2305     for (i = 0; i < chain->context.cChain; i++)
2306         CRYPT_FreeSimpleChain(chain->context.rgpChain[i]);
2307     CryptMemFree(chain->context.rgpChain);
2308     CertCloseStore(chain->world, 0);
2309     CryptMemFree(chain);
2310 }
2311
2312 /* Makes and returns a copy of chain, up to and including element iElement of
2313  * simple chain iChain.
2314  */
2315 static PCertificateChain CRYPT_CopyChainToElement(PCertificateChain chain,
2316  DWORD iChain, DWORD iElement)
2317 {
2318     PCertificateChain copy = CryptMemAlloc(sizeof(CertificateChain));
2319
2320     if (copy)
2321     {
2322         copy->ref = 1;
2323         copy->world = CertDuplicateStore(chain->world);
2324         copy->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
2325         /* Leave the trust status of the copied chain unset, it'll get
2326          * rechecked after the new chain is done.
2327          */
2328         memset(&copy->context.TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
2329         copy->context.cLowerQualityChainContext = 0;
2330         copy->context.rgpLowerQualityChainContext = NULL;
2331         copy->context.fHasRevocationFreshnessTime = FALSE;
2332         copy->context.dwRevocationFreshnessTime = 0;
2333         copy->context.rgpChain = CryptMemAlloc(
2334          (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
2335         if (copy->context.rgpChain)
2336         {
2337             BOOL ret = TRUE;
2338             DWORD i;
2339
2340             memset(copy->context.rgpChain, 0,
2341              (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
2342             if (iChain)
2343             {
2344                 for (i = 0; ret && iChain && i < iChain - 1; i++)
2345                 {
2346                     copy->context.rgpChain[i] =
2347                      CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
2348                      chain->context.rgpChain[i]->cElement - 1);
2349                     if (!copy->context.rgpChain[i])
2350                         ret = FALSE;
2351                 }
2352             }
2353             else
2354                 i = 0;
2355             if (ret)
2356             {
2357                 copy->context.rgpChain[i] =
2358                  CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
2359                  iElement);
2360                 if (!copy->context.rgpChain[i])
2361                     ret = FALSE;
2362             }
2363             if (!ret)
2364             {
2365                 CRYPT_FreeChainContext(copy);
2366                 copy = NULL;
2367             }
2368             else
2369                 copy->context.cChain = iChain + 1;
2370         }
2371         else
2372         {
2373             CryptMemFree(copy);
2374             copy = NULL;
2375         }
2376     }
2377     return copy;
2378 }
2379
2380 static PCertificateChain CRYPT_BuildAlternateContextFromChain(
2381  HCERTCHAINENGINE hChainEngine, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
2382  PCertificateChain chain)
2383 {
2384     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
2385     PCertificateChain alternate;
2386
2387     TRACE("(%p, %s, %p, %p)\n", hChainEngine, debugstr_filetime(pTime),
2388      hAdditionalStore, chain);
2389
2390     /* Always start with the last "lower quality" chain to ensure a consistent
2391      * order of alternate creation:
2392      */
2393     if (chain->context.cLowerQualityChainContext)
2394         chain = (PCertificateChain)chain->context.rgpLowerQualityChainContext[
2395          chain->context.cLowerQualityChainContext - 1];
2396     /* A chain with only one element can't have any alternates */
2397     if (chain->context.cChain <= 1 && chain->context.rgpChain[0]->cElement <= 1)
2398         alternate = NULL;
2399     else
2400     {
2401         DWORD i, j, infoStatus;
2402         PCCERT_CONTEXT alternateIssuer = NULL;
2403
2404         alternate = NULL;
2405         for (i = 0; !alternateIssuer && i < chain->context.cChain; i++)
2406             for (j = 0; !alternateIssuer &&
2407              j < chain->context.rgpChain[i]->cElement - 1; j++)
2408             {
2409                 PCCERT_CONTEXT subject =
2410                  chain->context.rgpChain[i]->rgpElement[j]->pCertContext;
2411                 PCCERT_CONTEXT prevIssuer = CertDuplicateCertificateContext(
2412                  chain->context.rgpChain[i]->rgpElement[j + 1]->pCertContext);
2413
2414                 alternateIssuer = CRYPT_GetIssuer(prevIssuer->hCertStore,
2415                  subject, prevIssuer, &infoStatus);
2416             }
2417         if (alternateIssuer)
2418         {
2419             i--;
2420             j--;
2421             alternate = CRYPT_CopyChainToElement(chain, i, j);
2422             if (alternate)
2423             {
2424                 BOOL ret = CRYPT_AddCertToSimpleChain(engine,
2425                  alternate->context.rgpChain[i], alternateIssuer, infoStatus);
2426
2427                 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it
2428                  * to close the enumeration that found it
2429                  */
2430                 CertFreeCertificateContext(alternateIssuer);
2431                 if (ret)
2432                 {
2433                     ret = CRYPT_BuildSimpleChain(engine, alternate->world,
2434                      alternate->context.rgpChain[i]);
2435                     if (ret)
2436                         CRYPT_CheckSimpleChain(engine,
2437                          alternate->context.rgpChain[i], pTime);
2438                     CRYPT_CombineTrustStatus(&alternate->context.TrustStatus,
2439                      &alternate->context.rgpChain[i]->TrustStatus);
2440                 }
2441                 if (!ret)
2442                 {
2443                     CRYPT_FreeChainContext(alternate);
2444                     alternate = NULL;
2445                 }
2446             }
2447         }
2448     }
2449     TRACE("%p\n", alternate);
2450     return alternate;
2451 }
2452
2453 #define CHAIN_QUALITY_SIGNATURE_VALID   0x16
2454 #define CHAIN_QUALITY_TIME_VALID        8
2455 #define CHAIN_QUALITY_COMPLETE_CHAIN    4
2456 #define CHAIN_QUALITY_BASIC_CONSTRAINTS 2
2457 #define CHAIN_QUALITY_TRUSTED_ROOT      1
2458
2459 #define CHAIN_QUALITY_HIGHEST \
2460  CHAIN_QUALITY_SIGNATURE_VALID | CHAIN_QUALITY_TIME_VALID | \
2461  CHAIN_QUALITY_COMPLETE_CHAIN | CHAIN_QUALITY_BASIC_CONSTRAINTS | \
2462  CHAIN_QUALITY_TRUSTED_ROOT
2463
2464 #define IS_TRUST_ERROR_SET(TrustStatus, bits) \
2465  (TrustStatus)->dwErrorStatus & (bits)
2466
2467 static DWORD CRYPT_ChainQuality(const CertificateChain *chain)
2468 {
2469     DWORD quality = CHAIN_QUALITY_HIGHEST;
2470
2471     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2472      CERT_TRUST_IS_UNTRUSTED_ROOT))
2473         quality &= ~CHAIN_QUALITY_TRUSTED_ROOT;
2474     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2475      CERT_TRUST_INVALID_BASIC_CONSTRAINTS))
2476         quality &= ~CHAIN_QUALITY_BASIC_CONSTRAINTS;
2477     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2478      CERT_TRUST_IS_PARTIAL_CHAIN))
2479         quality &= ~CHAIN_QUALITY_COMPLETE_CHAIN;
2480     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2481      CERT_TRUST_IS_NOT_TIME_VALID | CERT_TRUST_IS_NOT_TIME_NESTED))
2482         quality &= ~CHAIN_QUALITY_TIME_VALID;
2483     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2484      CERT_TRUST_IS_NOT_SIGNATURE_VALID))
2485         quality &= ~CHAIN_QUALITY_SIGNATURE_VALID;
2486     return quality;
2487 }
2488
2489 /* Chooses the highest quality chain among chain and its "lower quality"
2490  * alternate chains.  Returns the highest quality chain, with all other
2491  * chains as lower quality chains of it.
2492  */
2493 static PCertificateChain CRYPT_ChooseHighestQualityChain(
2494  PCertificateChain chain)
2495 {
2496     DWORD i;
2497
2498     /* There are always only two chains being considered:  chain, and an
2499      * alternate at chain->rgpLowerQualityChainContext[i].  If the alternate
2500      * has a higher quality than chain, the alternate gets assigned the lower
2501      * quality contexts, with chain taking the alternate's place among the
2502      * lower quality contexts.
2503      */
2504     for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
2505     {
2506         PCertificateChain alternate =
2507          (PCertificateChain)chain->context.rgpLowerQualityChainContext[i];
2508
2509         if (CRYPT_ChainQuality(alternate) > CRYPT_ChainQuality(chain))
2510         {
2511             alternate->context.cLowerQualityChainContext =
2512              chain->context.cLowerQualityChainContext;
2513             alternate->context.rgpLowerQualityChainContext =
2514              chain->context.rgpLowerQualityChainContext;
2515             alternate->context.rgpLowerQualityChainContext[i] =
2516              (PCCERT_CHAIN_CONTEXT)chain;
2517             chain->context.cLowerQualityChainContext = 0;
2518             chain->context.rgpLowerQualityChainContext = NULL;
2519             chain = alternate;
2520         }
2521     }
2522     return chain;
2523 }
2524
2525 static BOOL CRYPT_AddAlternateChainToChain(PCertificateChain chain,
2526  const CertificateChain *alternate)
2527 {
2528     BOOL ret;
2529
2530     if (chain->context.cLowerQualityChainContext)
2531         chain->context.rgpLowerQualityChainContext =
2532          CryptMemRealloc(chain->context.rgpLowerQualityChainContext,
2533          (chain->context.cLowerQualityChainContext + 1) *
2534          sizeof(PCCERT_CHAIN_CONTEXT));
2535     else
2536         chain->context.rgpLowerQualityChainContext =
2537          CryptMemAlloc(sizeof(PCCERT_CHAIN_CONTEXT));
2538     if (chain->context.rgpLowerQualityChainContext)
2539     {
2540         chain->context.rgpLowerQualityChainContext[
2541          chain->context.cLowerQualityChainContext++] =
2542          (PCCERT_CHAIN_CONTEXT)alternate;
2543         ret = TRUE;
2544     }
2545     else
2546         ret = FALSE;
2547     return ret;
2548 }
2549
2550 static PCERT_CHAIN_ELEMENT CRYPT_FindIthElementInChain(
2551  const CERT_CHAIN_CONTEXT *chain, DWORD i)
2552 {
2553     DWORD j, iElement;
2554     PCERT_CHAIN_ELEMENT element = NULL;
2555
2556     for (j = 0, iElement = 0; !element && j < chain->cChain; j++)
2557     {
2558         if (iElement + chain->rgpChain[j]->cElement < i)
2559             iElement += chain->rgpChain[j]->cElement;
2560         else
2561             element = chain->rgpChain[j]->rgpElement[i - iElement];
2562     }
2563     return element;
2564 }
2565
2566 typedef struct _CERT_CHAIN_PARA_NO_EXTRA_FIELDS {
2567     DWORD            cbSize;
2568     CERT_USAGE_MATCH RequestedUsage;
2569 } CERT_CHAIN_PARA_NO_EXTRA_FIELDS, *PCERT_CHAIN_PARA_NO_EXTRA_FIELDS;
2570
2571 static void CRYPT_VerifyChainRevocation(PCERT_CHAIN_CONTEXT chain,
2572  LPFILETIME pTime, HCERTSTORE hAdditionalStore,
2573  const CERT_CHAIN_PARA *pChainPara, DWORD chainFlags)
2574 {
2575     DWORD cContext;
2576
2577     if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_END_CERT)
2578         cContext = 1;
2579     else if ((chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN) ||
2580      (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT))
2581     {
2582         DWORD i;
2583
2584         for (i = 0, cContext = 0; i < chain->cChain; i++)
2585         {
2586             if (i < chain->cChain - 1 ||
2587              chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN)
2588                 cContext += chain->rgpChain[i]->cElement;
2589             else
2590                 cContext += chain->rgpChain[i]->cElement - 1;
2591         }
2592     }
2593     else
2594         cContext = 0;
2595     if (cContext)
2596     {
2597         DWORD i, j, iContext, revocationFlags;
2598         CERT_REVOCATION_PARA revocationPara = { sizeof(revocationPara), 0 };
2599         CERT_REVOCATION_STATUS revocationStatus =
2600          { sizeof(revocationStatus), 0 };
2601         BOOL ret;
2602
2603         revocationFlags = CERT_VERIFY_REV_CHAIN_FLAG;
2604         if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY)
2605             revocationFlags |= CERT_VERIFY_CACHE_ONLY_BASED_REVOCATION;
2606         if (chainFlags & CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT)
2607             revocationFlags |= CERT_VERIFY_REV_ACCUMULATIVE_TIMEOUT_FLAG;
2608         revocationPara.pftTimeToUse = pTime;
2609         if (hAdditionalStore)
2610         {
2611             revocationPara.cCertStore = 1;
2612             revocationPara.rgCertStore = &hAdditionalStore;
2613             revocationPara.hCrlStore = hAdditionalStore;
2614         }
2615         if (pChainPara->cbSize == sizeof(CERT_CHAIN_PARA))
2616         {
2617             revocationPara.dwUrlRetrievalTimeout =
2618              pChainPara->dwUrlRetrievalTimeout;
2619             revocationPara.fCheckFreshnessTime =
2620              pChainPara->fCheckRevocationFreshnessTime;
2621             revocationPara.dwFreshnessTime =
2622              pChainPara->dwRevocationFreshnessTime;
2623         }
2624         for (i = 0, iContext = 0; iContext < cContext && i < chain->cChain; i++)
2625         {
2626             for (j = 0; iContext < cContext &&
2627              j < chain->rgpChain[i]->cElement; j++, iContext++)
2628             {
2629                 PCCERT_CONTEXT certToCheck =
2630                  chain->rgpChain[i]->rgpElement[j]->pCertContext;
2631
2632                 if (j < chain->rgpChain[i]->cElement - 1)
2633                     revocationPara.pIssuerCert =
2634                      chain->rgpChain[i]->rgpElement[j + 1]->pCertContext;
2635                 else
2636                     revocationPara.pIssuerCert = NULL;
2637                 ret = CertVerifyRevocation(X509_ASN_ENCODING,
2638                  CERT_CONTEXT_REVOCATION_TYPE, 1, (void **)&certToCheck,
2639                  revocationFlags, &revocationPara, &revocationStatus);
2640                 if (!ret)
2641                 {
2642                     PCERT_CHAIN_ELEMENT element = CRYPT_FindIthElementInChain(
2643                      chain, iContext);
2644                     DWORD error;
2645
2646                     switch (revocationStatus.dwError)
2647                     {
2648                     case CRYPT_E_NO_REVOCATION_CHECK:
2649                     case CRYPT_E_NO_REVOCATION_DLL:
2650                     case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
2651                         /* If the revocation status is unknown, it's assumed
2652                          * to be offline too.
2653                          */
2654                         error = CERT_TRUST_REVOCATION_STATUS_UNKNOWN |
2655                          CERT_TRUST_IS_OFFLINE_REVOCATION;
2656                         break;
2657                     case CRYPT_E_REVOCATION_OFFLINE:
2658                         error = CERT_TRUST_IS_OFFLINE_REVOCATION;
2659                         break;
2660                     case CRYPT_E_REVOKED:
2661                         error = CERT_TRUST_IS_REVOKED;
2662                         break;
2663                     default:
2664                         WARN("unmapped error %08x\n", revocationStatus.dwError);
2665                         error = 0;
2666                     }
2667                     if (element)
2668                     {
2669                         /* FIXME: set element's pRevocationInfo member */
2670                         element->TrustStatus.dwErrorStatus |= error;
2671                     }
2672                     chain->TrustStatus.dwErrorStatus |= error;
2673                 }
2674             }
2675         }
2676     }
2677 }
2678
2679 static void CRYPT_CheckUsages(PCERT_CHAIN_CONTEXT chain,
2680  const CERT_CHAIN_PARA *pChainPara)
2681 {
2682     if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA_NO_EXTRA_FIELDS) &&
2683      pChainPara->RequestedUsage.Usage.cUsageIdentifier)
2684     {
2685         PCCERT_CONTEXT endCert;
2686         PCERT_EXTENSION ext;
2687         BOOL validForUsage;
2688
2689         /* A chain, if created, always includes the end certificate */
2690         endCert = chain->rgpChain[0]->rgpElement[0]->pCertContext;
2691         /* The extended key usage extension specifies how a certificate's
2692          * public key may be used.  From RFC 5280, section 4.2.1.12:
2693          * "This extension indicates one or more purposes for which the
2694          *  certified public key may be used, in addition to or in place of the
2695          *  basic purposes indicated in the key usage extension."
2696          * If the extension is present, it only satisfies the requested usage
2697          * if that usage is included in the extension:
2698          * "If the extension is present, then the certificate MUST only be used
2699          *  for one of the purposes indicated."
2700          * There is also the special anyExtendedKeyUsage OID, but it doesn't
2701          * have to be respected:
2702          * "Applications that require the presence of a particular purpose
2703          *  MAY reject certificates that include the anyExtendedKeyUsage OID
2704          *  but not the particular OID expected for the application."
2705          * For now, I'm being more conservative and ignoring the presence of
2706          * the anyExtendedKeyUsage OID.
2707          */
2708         if ((ext = CertFindExtension(szOID_ENHANCED_KEY_USAGE,
2709          endCert->pCertInfo->cExtension, endCert->pCertInfo->rgExtension)))
2710         {
2711             const CERT_ENHKEY_USAGE *requestedUsage =
2712              &pChainPara->RequestedUsage.Usage;
2713             CERT_ENHKEY_USAGE *usage;
2714             DWORD size;
2715
2716             if (CryptDecodeObjectEx(X509_ASN_ENCODING,
2717              X509_ENHANCED_KEY_USAGE, ext->Value.pbData, ext->Value.cbData,
2718              CRYPT_DECODE_ALLOC_FLAG, NULL, &usage, &size))
2719             {
2720                 if (pChainPara->RequestedUsage.dwType == USAGE_MATCH_TYPE_AND)
2721                 {
2722                     DWORD i, j;
2723
2724                     /* For AND matches, all usages must be present */
2725                     validForUsage = TRUE;
2726                     for (i = 0; validForUsage &&
2727                      i < requestedUsage->cUsageIdentifier; i++)
2728                     {
2729                         BOOL match = FALSE;
2730
2731                         for (j = 0; !match && j < usage->cUsageIdentifier; j++)
2732                             match = !strcmp(usage->rgpszUsageIdentifier[j],
2733                              requestedUsage->rgpszUsageIdentifier[i]);
2734                         if (!match)
2735                             validForUsage = FALSE;
2736                     }
2737                 }
2738                 else
2739                 {
2740                     DWORD i, j;
2741
2742                     /* For OR matches, any matching usage suffices */
2743                     validForUsage = FALSE;
2744                     for (i = 0; !validForUsage &&
2745                      i < requestedUsage->cUsageIdentifier; i++)
2746                     {
2747                         for (j = 0; !validForUsage &&
2748                          j < usage->cUsageIdentifier; j++)
2749                             validForUsage =
2750                              !strcmp(usage->rgpszUsageIdentifier[j],
2751                              requestedUsage->rgpszUsageIdentifier[i]);
2752                     }
2753                 }
2754                 LocalFree(usage);
2755             }
2756             else
2757                 validForUsage = FALSE;
2758         }
2759         else
2760         {
2761             /* If the extension isn't present, any interpretation is valid:
2762              * "Certificate using applications MAY require that the extended
2763              *  key usage extension be present and that a particular purpose
2764              *  be indicated in order for the certificate to be acceptable to
2765              *  that application."
2766              * Not all web sites include the extended key usage extension, so
2767              * accept chains without it.
2768              */
2769             TRACE_(chain)("requested usage from certificate with no usages\n");
2770             validForUsage = TRUE;
2771         }
2772         if (!validForUsage)
2773         {
2774             chain->TrustStatus.dwErrorStatus |=
2775              CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
2776             chain->rgpChain[0]->rgpElement[0]->TrustStatus.dwErrorStatus |=
2777              CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
2778         }
2779     }
2780     if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA) &&
2781      pChainPara->RequestedIssuancePolicy.Usage.cUsageIdentifier)
2782         FIXME("unimplemented for RequestedIssuancePolicy\n");
2783 }
2784
2785 static void dump_usage_match(LPCSTR name, const CERT_USAGE_MATCH *usageMatch)
2786 {
2787     if (usageMatch->Usage.cUsageIdentifier)
2788     {
2789         DWORD i;
2790
2791         TRACE_(chain)("%s: %s\n", name,
2792          usageMatch->dwType == USAGE_MATCH_TYPE_AND ? "AND" : "OR");
2793         for (i = 0; i < usageMatch->Usage.cUsageIdentifier; i++)
2794             TRACE_(chain)("%s\n", usageMatch->Usage.rgpszUsageIdentifier[i]);
2795     }
2796 }
2797
2798 static void dump_chain_para(const CERT_CHAIN_PARA *pChainPara)
2799 {
2800     TRACE_(chain)("%d\n", pChainPara->cbSize);
2801     if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA_NO_EXTRA_FIELDS))
2802         dump_usage_match("RequestedUsage", &pChainPara->RequestedUsage);
2803     if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA))
2804     {
2805         dump_usage_match("RequestedIssuancePolicy",
2806          &pChainPara->RequestedIssuancePolicy);
2807         TRACE_(chain)("%d\n", pChainPara->dwUrlRetrievalTimeout);
2808         TRACE_(chain)("%d\n", pChainPara->fCheckRevocationFreshnessTime);
2809         TRACE_(chain)("%d\n", pChainPara->dwRevocationFreshnessTime);
2810     }
2811 }
2812
2813 BOOL WINAPI CertGetCertificateChain(HCERTCHAINENGINE hChainEngine,
2814  PCCERT_CONTEXT pCertContext, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
2815  PCERT_CHAIN_PARA pChainPara, DWORD dwFlags, LPVOID pvReserved,
2816  PCCERT_CHAIN_CONTEXT* ppChainContext)
2817 {
2818     BOOL ret;
2819     PCertificateChain chain = NULL;
2820
2821     TRACE("(%p, %p, %s, %p, %p, %08x, %p, %p)\n", hChainEngine, pCertContext,
2822      debugstr_filetime(pTime), hAdditionalStore, pChainPara, dwFlags,
2823      pvReserved, ppChainContext);
2824
2825     if (ppChainContext)
2826         *ppChainContext = NULL;
2827     if (!pChainPara)
2828     {
2829         SetLastError(E_INVALIDARG);
2830         return FALSE;
2831     }
2832     if (!pCertContext->pCertInfo->SignatureAlgorithm.pszObjId)
2833     {
2834         SetLastError(ERROR_INVALID_DATA);
2835         return FALSE;
2836     }
2837
2838     if (!hChainEngine)
2839         hChainEngine = CRYPT_GetDefaultChainEngine();
2840     if (TRACE_ON(chain))
2841         dump_chain_para(pChainPara);
2842     /* FIXME: what about HCCE_LOCAL_MACHINE? */
2843     ret = CRYPT_BuildCandidateChainFromCert(hChainEngine, pCertContext, pTime,
2844      hAdditionalStore, &chain);
2845     if (ret)
2846     {
2847         PCertificateChain alternate = NULL;
2848         PCERT_CHAIN_CONTEXT pChain;
2849
2850         do {
2851             alternate = CRYPT_BuildAlternateContextFromChain(hChainEngine,
2852              pTime, hAdditionalStore, chain);
2853
2854             /* Alternate contexts are added as "lower quality" contexts of
2855              * chain, to avoid loops in alternate chain creation.
2856              * The highest-quality chain is chosen at the end.
2857              */
2858             if (alternate)
2859                 ret = CRYPT_AddAlternateChainToChain(chain, alternate);
2860         } while (ret && alternate);
2861         chain = CRYPT_ChooseHighestQualityChain(chain);
2862         if (!(dwFlags & CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS))
2863             CRYPT_FreeLowerQualityChains(chain);
2864         pChain = (PCERT_CHAIN_CONTEXT)chain;
2865         CRYPT_VerifyChainRevocation(pChain, pTime, hAdditionalStore,
2866          pChainPara, dwFlags);
2867         CRYPT_CheckUsages(pChain, pChainPara);
2868         TRACE_(chain)("error status: %08x\n",
2869          pChain->TrustStatus.dwErrorStatus);
2870         if (ppChainContext)
2871             *ppChainContext = pChain;
2872         else
2873             CertFreeCertificateChain(pChain);
2874     }
2875     TRACE("returning %d\n", ret);
2876     return ret;
2877 }
2878
2879 PCCERT_CHAIN_CONTEXT WINAPI CertDuplicateCertificateChain(
2880  PCCERT_CHAIN_CONTEXT pChainContext)
2881 {
2882     PCertificateChain chain = (PCertificateChain)pChainContext;
2883
2884     TRACE("(%p)\n", pChainContext);
2885
2886     if (chain)
2887         InterlockedIncrement(&chain->ref);
2888     return pChainContext;
2889 }
2890
2891 VOID WINAPI CertFreeCertificateChain(PCCERT_CHAIN_CONTEXT pChainContext)
2892 {
2893     PCertificateChain chain = (PCertificateChain)pChainContext;
2894
2895     TRACE("(%p)\n", pChainContext);
2896
2897     if (chain)
2898     {
2899         if (InterlockedDecrement(&chain->ref) == 0)
2900             CRYPT_FreeChainContext(chain);
2901     }
2902 }
2903
2904 PCCERT_CHAIN_CONTEXT WINAPI CertFindChainInStore(HCERTSTORE store,
2905  DWORD certEncodingType, DWORD findFlags, DWORD findType,
2906  const void *findPara, PCCERT_CHAIN_CONTEXT prevChainContext)
2907 {
2908     FIXME("(%p, %08x, %08x, %d, %p, %p): stub\n", store, certEncodingType,
2909      findFlags, findType, findPara, prevChainContext);
2910     return NULL;
2911 }
2912
2913 static void find_element_with_error(PCCERT_CHAIN_CONTEXT chain, DWORD error,
2914  LONG *iChain, LONG *iElement)
2915 {
2916     DWORD i, j;
2917
2918     for (i = 0; i < chain->cChain; i++)
2919         for (j = 0; j < chain->rgpChain[i]->cElement; j++)
2920             if (chain->rgpChain[i]->rgpElement[j]->TrustStatus.dwErrorStatus &
2921              error)
2922             {
2923                 *iChain = i;
2924                 *iElement = j;
2925                 return;
2926             }
2927 }
2928
2929 static BOOL WINAPI verify_base_policy(LPCSTR szPolicyOID,
2930  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2931  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2932 {
2933     DWORD checks = 0;
2934
2935     if (pPolicyPara)
2936         checks = pPolicyPara->dwFlags;
2937     pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2938     pPolicyStatus->dwError = NO_ERROR;
2939     if (pChainContext->TrustStatus.dwErrorStatus &
2940      CERT_TRUST_IS_NOT_SIGNATURE_VALID)
2941     {
2942         pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
2943         find_element_with_error(pChainContext,
2944          CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
2945          &pPolicyStatus->lElementIndex);
2946     }
2947     else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
2948     {
2949         pPolicyStatus->dwError = CERT_E_CHAINING;
2950         find_element_with_error(pChainContext, CERT_TRUST_IS_CYCLIC,
2951          &pPolicyStatus->lChainIndex, &pPolicyStatus->lElementIndex);
2952         /* For a cyclic chain, which element is a cycle isn't meaningful */
2953         pPolicyStatus->lElementIndex = -1;
2954     }
2955     if (!pPolicyStatus->dwError &&
2956      pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_UNTRUSTED_ROOT &&
2957      !(checks & CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG))
2958     {
2959         pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
2960         find_element_with_error(pChainContext,
2961          CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
2962          &pPolicyStatus->lElementIndex);
2963     }
2964     if (!pPolicyStatus->dwError &&
2965      pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
2966     {
2967         pPolicyStatus->dwError = CERT_E_EXPIRED;
2968         find_element_with_error(pChainContext,
2969          CERT_TRUST_IS_NOT_TIME_VALID, &pPolicyStatus->lChainIndex,
2970          &pPolicyStatus->lElementIndex);
2971     }
2972     if (!pPolicyStatus->dwError &&
2973      pChainContext->TrustStatus.dwErrorStatus &
2974      CERT_TRUST_IS_NOT_VALID_FOR_USAGE &&
2975      !(checks & CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG))
2976     {
2977         pPolicyStatus->dwError = CERT_E_WRONG_USAGE;
2978         find_element_with_error(pChainContext,
2979          CERT_TRUST_IS_NOT_VALID_FOR_USAGE, &pPolicyStatus->lChainIndex,
2980          &pPolicyStatus->lElementIndex);
2981     }
2982     if (!pPolicyStatus->dwError &&
2983      pChainContext->TrustStatus.dwErrorStatus &
2984      CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT &&
2985      !(checks & CERT_CHAIN_POLICY_IGNORE_NOT_SUPPORTED_CRITICAL_EXT_FLAG))
2986     {
2987         pPolicyStatus->dwError = CERT_E_CRITICAL;
2988         find_element_with_error(pChainContext,
2989          CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT, &pPolicyStatus->lChainIndex,
2990          &pPolicyStatus->lElementIndex);
2991     }
2992     return TRUE;
2993 }
2994
2995 static BYTE msTestPubKey1[] = {
2996 0x30,0x47,0x02,0x40,0x81,0x55,0x22,0xb9,0x8a,0xa4,0x6f,0xed,0xd6,0xe7,0xd9,
2997 0x66,0x0f,0x55,0xbc,0xd7,0xcd,0xd5,0xbc,0x4e,0x40,0x02,0x21,0xa2,0xb1,0xf7,
2998 0x87,0x30,0x85,0x5e,0xd2,0xf2,0x44,0xb9,0xdc,0x9b,0x75,0xb6,0xfb,0x46,0x5f,
2999 0x42,0xb6,0x9d,0x23,0x36,0x0b,0xde,0x54,0x0f,0xcd,0xbd,0x1f,0x99,0x2a,0x10,
3000 0x58,0x11,0xcb,0x40,0xcb,0xb5,0xa7,0x41,0x02,0x03,0x01,0x00,0x01 };
3001 static BYTE msTestPubKey2[] = {
3002 0x30,0x47,0x02,0x40,0x9c,0x50,0x05,0x1d,0xe2,0x0e,0x4c,0x53,0xd8,0xd9,0xb5,
3003 0xe5,0xfd,0xe9,0xe3,0xad,0x83,0x4b,0x80,0x08,0xd9,0xdc,0xe8,0xe8,0x35,0xf8,
3004 0x11,0xf1,0xe9,0x9b,0x03,0x7a,0x65,0x64,0x76,0x35,0xce,0x38,0x2c,0xf2,0xb6,
3005 0x71,0x9e,0x06,0xd9,0xbf,0xbb,0x31,0x69,0xa3,0xf6,0x30,0xa0,0x78,0x7b,0x18,
3006 0xdd,0x50,0x4d,0x79,0x1e,0xeb,0x61,0xc1,0x02,0x03,0x01,0x00,0x01 };
3007
3008 static void dump_authenticode_extra_chain_policy_para(
3009  AUTHENTICODE_EXTRA_CERT_CHAIN_POLICY_PARA *extraPara)
3010 {
3011     if (extraPara)
3012     {
3013         TRACE_(chain)("cbSize = %d\n", extraPara->cbSize);
3014         TRACE_(chain)("dwRegPolicySettings = %08x\n",
3015          extraPara->dwRegPolicySettings);
3016         TRACE_(chain)("pSignerInfo = %p\n", extraPara->pSignerInfo);
3017     }
3018 }
3019
3020 static BOOL WINAPI verify_authenticode_policy(LPCSTR szPolicyOID,
3021  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3022  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
3023 {
3024     BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
3025      pPolicyStatus);
3026     AUTHENTICODE_EXTRA_CERT_CHAIN_POLICY_PARA *extraPara = NULL;
3027
3028     if (pPolicyPara)
3029         extraPara = pPolicyPara->pvExtraPolicyPara;
3030     if (TRACE_ON(chain))
3031         dump_authenticode_extra_chain_policy_para(extraPara);
3032     if (ret && pPolicyStatus->dwError == CERT_E_UNTRUSTEDROOT)
3033     {
3034         CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
3035         BOOL isMSTestRoot = FALSE;
3036         PCCERT_CONTEXT failingCert =
3037          pChainContext->rgpChain[pPolicyStatus->lChainIndex]->
3038          rgpElement[pPolicyStatus->lElementIndex]->pCertContext;
3039         DWORD i;
3040         CRYPT_DATA_BLOB keyBlobs[] = {
3041          { sizeof(msTestPubKey1), msTestPubKey1 },
3042          { sizeof(msTestPubKey2), msTestPubKey2 },
3043         };
3044
3045         /* Check whether the root is an MS test root */
3046         for (i = 0; !isMSTestRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
3047          i++)
3048         {
3049             msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
3050             msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
3051             if (CertComparePublicKeyInfo(
3052              X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
3053              &failingCert->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
3054                 isMSTestRoot = TRUE;
3055         }
3056         if (isMSTestRoot)
3057             pPolicyStatus->dwError = CERT_E_UNTRUSTEDTESTROOT;
3058     }
3059     return ret;
3060 }
3061
3062 static BOOL WINAPI verify_basic_constraints_policy(LPCSTR szPolicyOID,
3063  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3064  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
3065 {
3066     pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
3067     if (pChainContext->TrustStatus.dwErrorStatus &
3068      CERT_TRUST_INVALID_BASIC_CONSTRAINTS)
3069     {
3070         pPolicyStatus->dwError = TRUST_E_BASIC_CONSTRAINTS;
3071         find_element_with_error(pChainContext,
3072          CERT_TRUST_INVALID_BASIC_CONSTRAINTS, &pPolicyStatus->lChainIndex,
3073          &pPolicyStatus->lElementIndex);
3074     }
3075     else
3076         pPolicyStatus->dwError = NO_ERROR;
3077     return TRUE;
3078 }
3079
3080 static BOOL match_dns_to_subject_alt_name(const CERT_EXTENSION *ext,
3081  LPCWSTR server_name)
3082 {
3083     BOOL matches = FALSE;
3084     CERT_ALT_NAME_INFO *subjectName;
3085     DWORD size;
3086
3087     TRACE_(chain)("%s\n", debugstr_w(server_name));
3088     /* This could be spoofed by the embedded NULL vulnerability, since the
3089      * returned CERT_ALT_NAME_INFO doesn't have a way to indicate the
3090      * encoded length of a name.  Fortunately CryptDecodeObjectEx fails if
3091      * the encoded form of the name contains a NULL.
3092      */
3093     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
3094      ext->Value.pbData, ext->Value.cbData,
3095      CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
3096      &subjectName, &size))
3097     {
3098         DWORD i;
3099
3100         /* RFC 5280 states that multiple instances of each name type may exist,
3101          * in section 4.2.1.6:
3102          * "Multiple name forms, and multiple instances of each name form,
3103          *  MAY be included."
3104          * It doesn't specify the behavior in such cases, but both RFC 2818
3105          * and RFC 2595 explicitly accept a certificate if any name matches.
3106          */
3107         for (i = 0; !matches && i < subjectName->cAltEntry; i++)
3108         {
3109             if (subjectName->rgAltEntry[i].dwAltNameChoice ==
3110              CERT_ALT_NAME_DNS_NAME)
3111             {
3112                 TRACE_(chain)("dNSName: %s\n", debugstr_w(
3113                  subjectName->rgAltEntry[i].u.pwszDNSName));
3114                 if (subjectName->rgAltEntry[i].u.pwszDNSName[0] == '*')
3115                 {
3116                     LPCWSTR server_name_dot;
3117
3118                     /* Matching a wildcard: a wildcard matches a single name
3119                      * component, which is terminated by a dot.  RFC 1034
3120                      * doesn't define whether multiple wildcards are allowed,
3121                      * but I will assume that they are not until proven
3122                      * otherwise.  RFC 1034 also states that 'the "*" label
3123                      * always matches at least one whole label and sometimes
3124                      * more, but always whole labels.'  Native crypt32 does not
3125                      * match more than one label with a wildcard, so I do the
3126                      * same here.  Thus, a wildcard only accepts the first
3127                      * label, then requires an exact match of the remaining
3128                      * string.
3129                      */
3130                     server_name_dot = strchrW(server_name, '.');
3131                     if (server_name_dot)
3132                     {
3133                         if (!strcmpiW(server_name_dot,
3134                          subjectName->rgAltEntry[i].u.pwszDNSName + 1))
3135                             matches = TRUE;
3136                     }
3137                 }
3138                 else if (!strcmpiW(server_name,
3139                  subjectName->rgAltEntry[i].u.pwszDNSName))
3140                     matches = TRUE;
3141             }
3142         }
3143         LocalFree(subjectName);
3144     }
3145     return matches;
3146 }
3147
3148 static BOOL find_matching_domain_component(const CERT_NAME_INFO *name,
3149  LPCWSTR component)
3150 {
3151     BOOL matches = FALSE;
3152     DWORD i, j;
3153
3154     for (i = 0; !matches && i < name->cRDN; i++)
3155         for (j = 0; j < name->rgRDN[i].cRDNAttr; j++)
3156             if (!strcmp(szOID_DOMAIN_COMPONENT,
3157              name->rgRDN[i].rgRDNAttr[j].pszObjId))
3158             {
3159                 const CERT_RDN_ATTR *attr;
3160
3161                 attr = &name->rgRDN[i].rgRDNAttr[j];
3162                 /* Compare with memicmpW rather than strcmpiW in order to avoid
3163                  * a match with a string with an embedded NULL.  The component
3164                  * must match one domain component attribute's entire string
3165                  * value with a case-insensitive match.
3166                  */
3167                 matches = !memicmpW(component, (LPCWSTR)attr->Value.pbData,
3168                  attr->Value.cbData / sizeof(WCHAR));
3169             }
3170     return matches;
3171 }
3172
3173 static BOOL match_domain_component(LPCWSTR allowed_component, DWORD allowed_len,
3174  LPCWSTR server_component, DWORD server_len, BOOL allow_wildcards,
3175  BOOL *see_wildcard)
3176 {
3177     LPCWSTR allowed_ptr, server_ptr;
3178     BOOL matches = TRUE;
3179
3180     *see_wildcard = FALSE;
3181     if (server_len < allowed_len)
3182     {
3183         WARN_(chain)("domain component %s too short for %s\n",
3184          debugstr_wn(server_component, server_len),
3185          debugstr_wn(allowed_component, allowed_len));
3186         /* A domain component can't contain a wildcard character, so a domain
3187          * component shorter than the allowed string can't produce a match.
3188          */
3189         return FALSE;
3190     }
3191     for (allowed_ptr = allowed_component, server_ptr = server_component;
3192          matches && allowed_ptr - allowed_component < allowed_len;
3193          allowed_ptr++, server_ptr++)
3194     {
3195         if (*allowed_ptr == '*')
3196         {
3197             if (allowed_ptr - allowed_component < allowed_len - 1)
3198             {
3199                 WARN_(chain)("non-wildcard characters after wildcard not supported\n");
3200                 matches = FALSE;
3201             }
3202             else if (!allow_wildcards)
3203             {
3204                 WARN_(chain)("wildcard after non-wildcard component\n");
3205                 matches = FALSE;
3206             }
3207             else
3208             {
3209                 /* the preceding characters must have matched, so the rest of
3210                  * the component also matches.
3211                  */
3212                 *see_wildcard = TRUE;
3213                 break;
3214             }
3215         }
3216         if (matches)
3217             matches = tolowerW(*allowed_ptr) == tolowerW(*server_ptr);
3218     }
3219     if (matches && server_ptr - server_component < server_len)
3220     {
3221         /* If there are unmatched characters in the server domain component,
3222          * the server domain only matches if the allowed string ended in a '*'.
3223          */
3224         matches = *allowed_ptr == '*';
3225     }
3226     return matches;
3227 }
3228
3229 static BOOL match_common_name(LPCWSTR server_name, const CERT_RDN_ATTR *nameAttr)
3230 {
3231     LPCWSTR allowed = (LPCWSTR)nameAttr->Value.pbData;
3232     LPCWSTR allowed_component = allowed;
3233     DWORD allowed_len = nameAttr->Value.cbData / sizeof(WCHAR);
3234     LPCWSTR server_component = server_name;
3235     DWORD server_len = strlenW(server_name);
3236     BOOL matches = TRUE, allow_wildcards = TRUE;
3237
3238     TRACE_(chain)("CN = %s\n", debugstr_wn(allowed_component, allowed_len));
3239
3240     /* From RFC 2818 (HTTP over TLS), section 3.1:
3241      * "Names may contain the wildcard character * which is considered to match
3242      *  any single domain name component or component fragment. E.g.,
3243      *  *.a.com matches foo.a.com but not bar.foo.a.com. f*.com matches foo.com
3244      *  but not bar.com."
3245      *
3246      * And from RFC 2595 (Using TLS with IMAP, POP3 and ACAP), section 2.4:
3247      * "A "*" wildcard character MAY be used as the left-most name component in
3248      *  the certificate.  For example, *.example.com would match a.example.com,
3249      *  foo.example.com, etc. but would not match example.com."
3250      *
3251      * There are other protocols which use TLS, and none of them is
3252      * authoritative.  This accepts certificates in common usage, e.g.
3253      * *.domain.com matches www.domain.com but not domain.com, and
3254      * www*.domain.com matches www1.domain.com but not mail.domain.com.
3255      */
3256     do {
3257         LPCWSTR allowed_dot, server_dot;
3258
3259         allowed_dot = memchrW(allowed_component, '.',
3260          allowed_len - (allowed_component - allowed));
3261         server_dot = memchrW(server_component, '.',
3262          server_len - (server_component - server_name));
3263         /* The number of components must match */
3264         if ((!allowed_dot && server_dot) || (allowed_dot && !server_dot))
3265         {
3266             if (!allowed_dot)
3267                 WARN_(chain)("%s: too many components for CN=%s\n",
3268                  debugstr_w(server_name), debugstr_wn(allowed, allowed_len));
3269             else
3270                 WARN_(chain)("%s: not enough components for CN=%s\n",
3271                  debugstr_w(server_name), debugstr_wn(allowed, allowed_len));
3272             matches = FALSE;
3273         }
3274         else
3275         {
3276             LPCWSTR allowed_end, server_end;
3277             BOOL has_wildcard;
3278
3279             allowed_end = allowed_dot ? allowed_dot : allowed + allowed_len;
3280             server_end = server_dot ? server_dot : server_name + server_len;
3281             matches = match_domain_component(allowed_component,
3282              allowed_end - allowed_component, server_component,
3283              server_end - server_component, allow_wildcards, &has_wildcard);
3284             /* Once a non-wildcard component is seen, no wildcard components
3285              * may follow
3286              */
3287             if (!has_wildcard)
3288                 allow_wildcards = FALSE;
3289             if (matches)
3290             {
3291                 allowed_component = allowed_dot ? allowed_dot + 1 : allowed_end;
3292                 server_component = server_dot ? server_dot + 1 : server_end;
3293             }
3294         }
3295     } while (matches && allowed_component &&
3296      allowed_component - allowed < allowed_len &&
3297      server_component && server_component - server_name < server_len);
3298     TRACE_(chain)("returning %d\n", matches);
3299     return matches;
3300 }
3301
3302 static BOOL match_dns_to_subject_dn(PCCERT_CONTEXT cert, LPCWSTR server_name)
3303 {
3304     BOOL matches = FALSE;
3305     CERT_NAME_INFO *name;
3306     DWORD size;
3307
3308     TRACE_(chain)("%s\n", debugstr_w(server_name));
3309     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_UNICODE_NAME,
3310      cert->pCertInfo->Subject.pbData, cert->pCertInfo->Subject.cbData,
3311      CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
3312      &name, &size))
3313     {
3314         /* If the subject distinguished name contains any name components,
3315          * make sure all of them are present.
3316          */
3317         if (CertFindRDNAttr(szOID_DOMAIN_COMPONENT, name))
3318         {
3319             LPCWSTR ptr = server_name;
3320
3321             matches = TRUE;
3322             do {
3323                 LPCWSTR dot = strchrW(ptr, '.'), end;
3324                 /* 254 is the maximum DNS label length, see RFC 1035 */
3325                 WCHAR component[255];
3326                 DWORD len;
3327
3328                 end = dot ? dot : ptr + strlenW(ptr);
3329                 len = end - ptr;
3330                 if (len >= sizeof(component) / sizeof(component[0]))
3331                 {
3332                     WARN_(chain)("domain component %s too long\n",
3333                      debugstr_wn(ptr, len));
3334                     matches = FALSE;
3335                 }
3336                 else
3337                 {
3338                     memcpy(component, ptr, len * sizeof(WCHAR));
3339                     component[len] = 0;
3340                     matches = find_matching_domain_component(name, component);
3341                 }
3342                 ptr = dot ? dot + 1 : end;
3343             } while (matches && ptr && *ptr);
3344         }
3345         else
3346         {
3347             DWORD i, j;
3348
3349             /* If the certificate isn't using a DN attribute in the name, make
3350              * make sure at least one common name matches.  From RFC 2818,
3351              * section 3.1:
3352              * "If more than one identity of a given type is present in the
3353              * certificate (e.g., more than one dNSName name, a match in any
3354              * one of the set is considered acceptable.)"
3355              */
3356             for (i = 0; !matches && i < name->cRDN; i++)
3357                 for (j = 0; !matches && j < name->rgRDN[i].cRDNAttr; j++)
3358                 {
3359                     PCERT_RDN_ATTR attr = &name->rgRDN[i].rgRDNAttr[j];
3360
3361                     if (attr->pszObjId && !strcmp(szOID_COMMON_NAME,
3362                      attr->pszObjId))
3363                         matches = match_common_name(server_name, attr);
3364                 }
3365         }
3366         LocalFree(name);
3367     }
3368     return matches;
3369 }
3370
3371 static void dump_ssl_extra_chain_policy_para(HTTPSPolicyCallbackData *sslPara)
3372 {
3373     if (sslPara)
3374     {
3375         TRACE_(chain)("cbSize = %d\n", sslPara->u.cbSize);
3376         TRACE_(chain)("dwAuthType = %d\n", sslPara->dwAuthType);
3377         TRACE_(chain)("fdwChecks = %08x\n", sslPara->fdwChecks);
3378         TRACE_(chain)("pwszServerName = %s\n",
3379          debugstr_w(sslPara->pwszServerName));
3380     }
3381 }
3382
3383 static BOOL WINAPI verify_ssl_policy(LPCSTR szPolicyOID,
3384  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3385  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
3386 {
3387     HTTPSPolicyCallbackData *sslPara = NULL;
3388     DWORD checks = 0;
3389
3390     if (pPolicyPara)
3391         sslPara = pPolicyPara->pvExtraPolicyPara;
3392     if (TRACE_ON(chain))
3393         dump_ssl_extra_chain_policy_para(sslPara);
3394     if (sslPara && sslPara->u.cbSize >= sizeof(HTTPSPolicyCallbackData))
3395         checks = sslPara->fdwChecks;
3396     pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
3397     if (pChainContext->TrustStatus.dwErrorStatus &
3398      CERT_TRUST_IS_NOT_SIGNATURE_VALID)
3399     {
3400         pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
3401         find_element_with_error(pChainContext,
3402          CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
3403          &pPolicyStatus->lElementIndex);
3404     }
3405     else if (pChainContext->TrustStatus.dwErrorStatus &
3406      CERT_TRUST_IS_UNTRUSTED_ROOT &&
3407      !(checks & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
3408     {
3409         pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
3410         find_element_with_error(pChainContext,
3411          CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
3412          &pPolicyStatus->lElementIndex);
3413     }
3414     else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
3415     {
3416         pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
3417         find_element_with_error(pChainContext,
3418          CERT_TRUST_IS_CYCLIC, &pPolicyStatus->lChainIndex,
3419          &pPolicyStatus->lElementIndex);
3420         /* For a cyclic chain, which element is a cycle isn't meaningful */
3421         pPolicyStatus->lElementIndex = -1;
3422     }
3423     else if (pChainContext->TrustStatus.dwErrorStatus &
3424      CERT_TRUST_IS_NOT_TIME_VALID &&
3425      !(checks & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
3426     {
3427         pPolicyStatus->dwError = CERT_E_EXPIRED;
3428         find_element_with_error(pChainContext,
3429          CERT_TRUST_IS_NOT_TIME_VALID, &pPolicyStatus->lChainIndex,
3430          &pPolicyStatus->lElementIndex);
3431     }
3432     else if (pChainContext->TrustStatus.dwErrorStatus &
3433      CERT_TRUST_IS_NOT_VALID_FOR_USAGE &&
3434      !(checks & SECURITY_FLAG_IGNORE_WRONG_USAGE))
3435     {
3436         pPolicyStatus->dwError = CERT_E_WRONG_USAGE;
3437         find_element_with_error(pChainContext,
3438          CERT_TRUST_IS_NOT_VALID_FOR_USAGE, &pPolicyStatus->lChainIndex,
3439          &pPolicyStatus->lElementIndex);
3440     }
3441     else if (pChainContext->TrustStatus.dwErrorStatus &
3442      CERT_TRUST_IS_REVOKED && !(checks & SECURITY_FLAG_IGNORE_REVOCATION))
3443     {
3444         pPolicyStatus->dwError = CERT_E_REVOKED;
3445         find_element_with_error(pChainContext,
3446          CERT_TRUST_IS_REVOKED, &pPolicyStatus->lChainIndex,
3447          &pPolicyStatus->lElementIndex);
3448     }
3449     else if (pChainContext->TrustStatus.dwErrorStatus &
3450      CERT_TRUST_IS_OFFLINE_REVOCATION &&
3451      !(checks & SECURITY_FLAG_IGNORE_REVOCATION))
3452     {
3453         pPolicyStatus->dwError = CERT_E_REVOCATION_FAILURE;
3454         find_element_with_error(pChainContext,
3455          CERT_TRUST_IS_OFFLINE_REVOCATION, &pPolicyStatus->lChainIndex,
3456          &pPolicyStatus->lElementIndex);
3457     }
3458     else if (pChainContext->TrustStatus.dwErrorStatus &
3459      CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT)
3460     {
3461         pPolicyStatus->dwError = CERT_E_CRITICAL;
3462         find_element_with_error(pChainContext,
3463          CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT, &pPolicyStatus->lChainIndex,
3464          &pPolicyStatus->lElementIndex);
3465     }
3466     else
3467         pPolicyStatus->dwError = NO_ERROR;
3468     /* We only need bother checking whether the name in the end certificate
3469      * matches if the chain is otherwise okay.
3470      */
3471     if (!pPolicyStatus->dwError && pPolicyPara &&
3472      pPolicyPara->cbSize >= sizeof(CERT_CHAIN_POLICY_PARA))
3473     {
3474         if (sslPara && sslPara->u.cbSize >= sizeof(HTTPSPolicyCallbackData))
3475         {
3476             if (sslPara->dwAuthType == AUTHTYPE_SERVER &&
3477              sslPara->pwszServerName &&
3478              !(checks & SECURITY_FLAG_IGNORE_CERT_CN_INVALID))
3479             {
3480                 PCCERT_CONTEXT cert;
3481                 PCERT_EXTENSION altNameExt;
3482                 BOOL matches;
3483
3484                 cert = pChainContext->rgpChain[0]->rgpElement[0]->pCertContext;
3485                 altNameExt = get_subject_alt_name_ext(cert->pCertInfo);
3486                 /* If the alternate name extension exists, the name it contains
3487                  * is bound to the certificate, so make sure the name matches
3488                  * it.  Otherwise, look for the server name in the subject
3489                  * distinguished name.  RFC5280, section 4.2.1.6:
3490                  * "Whenever such identities are to be bound into a
3491                  *  certificate, the subject alternative name (or issuer
3492                  *  alternative name) extension MUST be used; however, a DNS
3493                  *  name MAY also be represented in the subject field using the
3494                  *  domainComponent attribute."
3495                  */
3496                 if (altNameExt)
3497                     matches = match_dns_to_subject_alt_name(altNameExt,
3498                      sslPara->pwszServerName);
3499                 else
3500                     matches = match_dns_to_subject_dn(cert,
3501                      sslPara->pwszServerName);
3502                 if (!matches)
3503                 {
3504                     pPolicyStatus->dwError = CERT_E_CN_NO_MATCH;
3505                     pPolicyStatus->lChainIndex = 0;
3506                     pPolicyStatus->lElementIndex = 0;
3507                 }
3508             }
3509         }
3510     }
3511     return TRUE;
3512 }
3513
3514 static BYTE msPubKey1[] = {
3515 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xdf,0x08,0xba,0xe3,0x3f,0x6e,
3516 0x64,0x9b,0xf5,0x89,0xaf,0x28,0x96,0x4a,0x07,0x8f,0x1b,0x2e,0x8b,0x3e,0x1d,
3517 0xfc,0xb8,0x80,0x69,0xa3,0xa1,0xce,0xdb,0xdf,0xb0,0x8e,0x6c,0x89,0x76,0x29,
3518 0x4f,0xca,0x60,0x35,0x39,0xad,0x72,0x32,0xe0,0x0b,0xae,0x29,0x3d,0x4c,0x16,
3519 0xd9,0x4b,0x3c,0x9d,0xda,0xc5,0xd3,0xd1,0x09,0xc9,0x2c,0x6f,0xa6,0xc2,0x60,
3520 0x53,0x45,0xdd,0x4b,0xd1,0x55,0xcd,0x03,0x1c,0xd2,0x59,0x56,0x24,0xf3,0xe5,
3521 0x78,0xd8,0x07,0xcc,0xd8,0xb3,0x1f,0x90,0x3f,0xc0,0x1a,0x71,0x50,0x1d,0x2d,
3522 0xa7,0x12,0x08,0x6d,0x7c,0xb0,0x86,0x6c,0xc7,0xba,0x85,0x32,0x07,0xe1,0x61,
3523 0x6f,0xaf,0x03,0xc5,0x6d,0xe5,0xd6,0xa1,0x8f,0x36,0xf6,0xc1,0x0b,0xd1,0x3e,
3524 0x69,0x97,0x48,0x72,0xc9,0x7f,0xa4,0xc8,0xc2,0x4a,0x4c,0x7e,0xa1,0xd1,0x94,
3525 0xa6,0xd7,0xdc,0xeb,0x05,0x46,0x2e,0xb8,0x18,0xb4,0x57,0x1d,0x86,0x49,0xdb,
3526 0x69,0x4a,0x2c,0x21,0xf5,0x5e,0x0f,0x54,0x2d,0x5a,0x43,0xa9,0x7a,0x7e,0x6a,
3527 0x8e,0x50,0x4d,0x25,0x57,0xa1,0xbf,0x1b,0x15,0x05,0x43,0x7b,0x2c,0x05,0x8d,
3528 0xbd,0x3d,0x03,0x8c,0x93,0x22,0x7d,0x63,0xea,0x0a,0x57,0x05,0x06,0x0a,0xdb,
3529 0x61,0x98,0x65,0x2d,0x47,0x49,0xa8,0xe7,0xe6,0x56,0x75,0x5c,0xb8,0x64,0x08,
3530 0x63,0xa9,0x30,0x40,0x66,0xb2,0xf9,0xb6,0xe3,0x34,0xe8,0x67,0x30,0xe1,0x43,
3531 0x0b,0x87,0xff,0xc9,0xbe,0x72,0x10,0x5e,0x23,0xf0,0x9b,0xa7,0x48,0x65,0xbf,
3532 0x09,0x88,0x7b,0xcd,0x72,0xbc,0x2e,0x79,0x9b,0x7b,0x02,0x03,0x01,0x00,0x01 };
3533 static BYTE msPubKey2[] = {
3534 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xa9,0x02,0xbd,0xc1,0x70,0xe6,
3535 0x3b,0xf2,0x4e,0x1b,0x28,0x9f,0x97,0x78,0x5e,0x30,0xea,0xa2,0xa9,0x8d,0x25,
3536 0x5f,0xf8,0xfe,0x95,0x4c,0xa3,0xb7,0xfe,0x9d,0xa2,0x20,0x3e,0x7c,0x51,0xa2,
3537 0x9b,0xa2,0x8f,0x60,0x32,0x6b,0xd1,0x42,0x64,0x79,0xee,0xac,0x76,0xc9,0x54,
3538 0xda,0xf2,0xeb,0x9c,0x86,0x1c,0x8f,0x9f,0x84,0x66,0xb3,0xc5,0x6b,0x7a,0x62,
3539 0x23,0xd6,0x1d,0x3c,0xde,0x0f,0x01,0x92,0xe8,0x96,0xc4,0xbf,0x2d,0x66,0x9a,
3540 0x9a,0x68,0x26,0x99,0xd0,0x3a,0x2c,0xbf,0x0c,0xb5,0x58,0x26,0xc1,0x46,0xe7,
3541 0x0a,0x3e,0x38,0x96,0x2c,0xa9,0x28,0x39,0xa8,0xec,0x49,0x83,0x42,0xe3,0x84,
3542 0x0f,0xbb,0x9a,0x6c,0x55,0x61,0xac,0x82,0x7c,0xa1,0x60,0x2d,0x77,0x4c,0xe9,
3543 0x99,0xb4,0x64,0x3b,0x9a,0x50,0x1c,0x31,0x08,0x24,0x14,0x9f,0xa9,0xe7,0x91,
3544 0x2b,0x18,0xe6,0x3d,0x98,0x63,0x14,0x60,0x58,0x05,0x65,0x9f,0x1d,0x37,0x52,
3545 0x87,0xf7,0xa7,0xef,0x94,0x02,0xc6,0x1b,0xd3,0xbf,0x55,0x45,0xb3,0x89,0x80,
3546 0xbf,0x3a,0xec,0x54,0x94,0x4e,0xae,0xfd,0xa7,0x7a,0x6d,0x74,0x4e,0xaf,0x18,
3547 0xcc,0x96,0x09,0x28,0x21,0x00,0x57,0x90,0x60,0x69,0x37,0xbb,0x4b,0x12,0x07,
3548 0x3c,0x56,0xff,0x5b,0xfb,0xa4,0x66,0x0a,0x08,0xa6,0xd2,0x81,0x56,0x57,0xef,
3549 0xb6,0x3b,0x5e,0x16,0x81,0x77,0x04,0xda,0xf6,0xbe,0xae,0x80,0x95,0xfe,0xb0,
3550 0xcd,0x7f,0xd6,0xa7,0x1a,0x72,0x5c,0x3c,0xca,0xbc,0xf0,0x08,0xa3,0x22,0x30,
3551 0xb3,0x06,0x85,0xc9,0xb3,0x20,0x77,0x13,0x85,0xdf,0x02,0x03,0x01,0x00,0x01 };
3552 static BYTE msPubKey3[] = {
3553 0x30,0x82,0x02,0x0a,0x02,0x82,0x02,0x01,0x00,0xf3,0x5d,0xfa,0x80,0x67,0xd4,
3554 0x5a,0xa7,0xa9,0x0c,0x2c,0x90,0x20,0xd0,0x35,0x08,0x3c,0x75,0x84,0xcd,0xb7,
3555 0x07,0x89,0x9c,0x89,0xda,0xde,0xce,0xc3,0x60,0xfa,0x91,0x68,0x5a,0x9e,0x94,
3556 0x71,0x29,0x18,0x76,0x7c,0xc2,0xe0,0xc8,0x25,0x76,0x94,0x0e,0x58,0xfa,0x04,
3557 0x34,0x36,0xe6,0xdf,0xaf,0xf7,0x80,0xba,0xe9,0x58,0x0b,0x2b,0x93,0xe5,0x9d,
3558 0x05,0xe3,0x77,0x22,0x91,0xf7,0x34,0x64,0x3c,0x22,0x91,0x1d,0x5e,0xe1,0x09,
3559 0x90,0xbc,0x14,0xfe,0xfc,0x75,0x58,0x19,0xe1,0x79,0xb7,0x07,0x92,0xa3,0xae,
3560 0x88,0x59,0x08,0xd8,0x9f,0x07,0xca,0x03,0x58,0xfc,0x68,0x29,0x6d,0x32,0xd7,
3561 0xd2,0xa8,0xcb,0x4b,0xfc,0xe1,0x0b,0x48,0x32,0x4f,0xe6,0xeb,0xb8,0xad,0x4f,
3562 0xe4,0x5c,0x6f,0x13,0x94,0x99,0xdb,0x95,0xd5,0x75,0xdb,0xa8,0x1a,0xb7,0x94,
3563 0x91,0xb4,0x77,0x5b,0xf5,0x48,0x0c,0x8f,0x6a,0x79,0x7d,0x14,0x70,0x04,0x7d,
3564 0x6d,0xaf,0x90,0xf5,0xda,0x70,0xd8,0x47,0xb7,0xbf,0x9b,0x2f,0x6c,0xe7,0x05,
3565 0xb7,0xe1,0x11,0x60,0xac,0x79,0x91,0x14,0x7c,0xc5,0xd6,0xa6,0xe4,0xe1,0x7e,
3566 0xd5,0xc3,0x7e,0xe5,0x92,0xd2,0x3c,0x00,0xb5,0x36,0x82,0xde,0x79,0xe1,0x6d,
3567 0xf3,0xb5,0x6e,0xf8,0x9f,0x33,0xc9,0xcb,0x52,0x7d,0x73,0x98,0x36,0xdb,0x8b,
3568 0xa1,0x6b,0xa2,0x95,0x97,0x9b,0xa3,0xde,0xc2,0x4d,0x26,0xff,0x06,0x96,0x67,
3569 0x25,0x06,0xc8,0xe7,0xac,0xe4,0xee,0x12,0x33,0x95,0x31,0x99,0xc8,0x35,0x08,
3570 0x4e,0x34,0xca,0x79,0x53,0xd5,0xb5,0xbe,0x63,0x32,0x59,0x40,0x36,0xc0,0xa5,
3571 0x4e,0x04,0x4d,0x3d,0xdb,0x5b,0x07,0x33,0xe4,0x58,0xbf,0xef,0x3f,0x53,0x64,
3572 0xd8,0x42,0x59,0x35,0x57,0xfd,0x0f,0x45,0x7c,0x24,0x04,0x4d,0x9e,0xd6,0x38,
3573 0x74,0x11,0x97,0x22,0x90,0xce,0x68,0x44,0x74,0x92,0x6f,0xd5,0x4b,0x6f,0xb0,
3574 0x86,0xe3,0xc7,0x36,0x42,0xa0,0xd0,0xfc,0xc1,0xc0,0x5a,0xf9,0xa3,0x61,0xb9,
3575 0x30,0x47,0x71,0x96,0x0a,0x16,0xb0,0x91,0xc0,0x42,0x95,0xef,0x10,0x7f,0x28,
3576 0x6a,0xe3,0x2a,0x1f,0xb1,0xe4,0xcd,0x03,0x3f,0x77,0x71,0x04,0xc7,0x20,0xfc,
3577 0x49,0x0f,0x1d,0x45,0x88,0xa4,0xd7,0xcb,0x7e,0x88,0xad,0x8e,0x2d,0xec,0x45,
3578 0xdb,0xc4,0x51,0x04,0xc9,0x2a,0xfc,0xec,0x86,0x9e,0x9a,0x11,0x97,0x5b,0xde,
3579 0xce,0x53,0x88,0xe6,0xe2,0xb7,0xfd,0xac,0x95,0xc2,0x28,0x40,0xdb,0xef,0x04,
3580 0x90,0xdf,0x81,0x33,0x39,0xd9,0xb2,0x45,0xa5,0x23,0x87,0x06,0xa5,0x55,0x89,
3581 0x31,0xbb,0x06,0x2d,0x60,0x0e,0x41,0x18,0x7d,0x1f,0x2e,0xb5,0x97,0xcb,0x11,
3582 0xeb,0x15,0xd5,0x24,0xa5,0x94,0xef,0x15,0x14,0x89,0xfd,0x4b,0x73,0xfa,0x32,
3583 0x5b,0xfc,0xd1,0x33,0x00,0xf9,0x59,0x62,0x70,0x07,0x32,0xea,0x2e,0xab,0x40,
3584 0x2d,0x7b,0xca,0xdd,0x21,0x67,0x1b,0x30,0x99,0x8f,0x16,0xaa,0x23,0xa8,0x41,
3585 0xd1,0xb0,0x6e,0x11,0x9b,0x36,0xc4,0xde,0x40,0x74,0x9c,0xe1,0x58,0x65,0xc1,
3586 0x60,0x1e,0x7a,0x5b,0x38,0xc8,0x8f,0xbb,0x04,0x26,0x7c,0xd4,0x16,0x40,0xe5,
3587 0xb6,0x6b,0x6c,0xaa,0x86,0xfd,0x00,0xbf,0xce,0xc1,0x35,0x02,0x03,0x01,0x00,
3588 0x01 };
3589
3590 static BOOL WINAPI verify_ms_root_policy(LPCSTR szPolicyOID,
3591  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3592  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
3593 {
3594     BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
3595      pPolicyStatus);
3596
3597     if (ret && !pPolicyStatus->dwError)
3598     {
3599         CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
3600         BOOL isMSRoot = FALSE;
3601         DWORD i;
3602         CRYPT_DATA_BLOB keyBlobs[] = {
3603          { sizeof(msPubKey1), msPubKey1 },
3604          { sizeof(msPubKey2), msPubKey2 },
3605          { sizeof(msPubKey3), msPubKey3 },
3606         };
3607         PCERT_SIMPLE_CHAIN rootChain =
3608          pChainContext->rgpChain[pChainContext->cChain -1 ];
3609         PCCERT_CONTEXT root =
3610          rootChain->rgpElement[rootChain->cElement - 1]->pCertContext;
3611
3612         for (i = 0; !isMSRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
3613          i++)
3614         {
3615             msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
3616             msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
3617             if (CertComparePublicKeyInfo(
3618              X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
3619              &root->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
3620                 isMSRoot = TRUE;
3621         }
3622         if (isMSRoot)
3623             pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = 0;
3624     }
3625     return ret;
3626 }
3627
3628 typedef BOOL (WINAPI *CertVerifyCertificateChainPolicyFunc)(LPCSTR szPolicyOID,
3629  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3630  PCERT_CHAIN_POLICY_STATUS pPolicyStatus);
3631
3632 static void dump_policy_para(PCERT_CHAIN_POLICY_PARA para)
3633 {
3634     if (para)
3635     {
3636         TRACE_(chain)("cbSize = %d\n", para->cbSize);
3637         TRACE_(chain)("dwFlags = %08x\n", para->dwFlags);
3638         TRACE_(chain)("pvExtraPolicyPara = %p\n", para->pvExtraPolicyPara);
3639     }
3640 }
3641
3642 BOOL WINAPI CertVerifyCertificateChainPolicy(LPCSTR szPolicyOID,
3643  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3644  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
3645 {
3646     static HCRYPTOIDFUNCSET set = NULL;
3647     BOOL ret = FALSE;
3648     CertVerifyCertificateChainPolicyFunc verifyPolicy = NULL;
3649     HCRYPTOIDFUNCADDR hFunc = NULL;
3650
3651     TRACE("(%s, %p, %p, %p)\n", debugstr_a(szPolicyOID), pChainContext,
3652      pPolicyPara, pPolicyStatus);
3653     if (TRACE_ON(chain))
3654         dump_policy_para(pPolicyPara);
3655
3656     if (IS_INTOID(szPolicyOID))
3657     {
3658         switch (LOWORD(szPolicyOID))
3659         {
3660         case LOWORD(CERT_CHAIN_POLICY_BASE):
3661             verifyPolicy = verify_base_policy;
3662             break;
3663         case LOWORD(CERT_CHAIN_POLICY_AUTHENTICODE):
3664             verifyPolicy = verify_authenticode_policy;
3665             break;
3666         case LOWORD(CERT_CHAIN_POLICY_SSL):
3667             verifyPolicy = verify_ssl_policy;
3668             break;
3669         case LOWORD(CERT_CHAIN_POLICY_BASIC_CONSTRAINTS):
3670             verifyPolicy = verify_basic_constraints_policy;
3671             break;
3672         case LOWORD(CERT_CHAIN_POLICY_MICROSOFT_ROOT):
3673             verifyPolicy = verify_ms_root_policy;
3674             break;
3675         default:
3676             FIXME("unimplemented for %d\n", LOWORD(szPolicyOID));
3677         }
3678     }
3679     if (!verifyPolicy)
3680     {
3681         if (!set)
3682             set = CryptInitOIDFunctionSet(
3683              CRYPT_OID_VERIFY_CERTIFICATE_CHAIN_POLICY_FUNC, 0);
3684         CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING, szPolicyOID, 0,
3685          (void **)&verifyPolicy, &hFunc);
3686     }
3687     if (verifyPolicy)
3688         ret = verifyPolicy(szPolicyOID, pChainContext, pPolicyPara,
3689          pPolicyStatus);
3690     if (hFunc)
3691         CryptFreeOIDFunctionAddress(hFunc, 0);
3692     TRACE("returning %d (%08x)\n", ret, pPolicyStatus->dwError);
3693     return ret;
3694 }