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