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