crypt32: Add tests for encoding/decoding cert policy constraints.
[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 url_matches(LPCWSTR constraint, LPCWSTR name,
510  DWORD *trustErrorStatus)
511 {
512     BOOL match = FALSE;
513
514     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
515
516     if (!constraint)
517         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
518     else if (!name)
519         ; /* no match */
520     else if (constraint[0] == '.')
521     {
522         if (lstrlenW(name) > lstrlenW(constraint))
523             match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
524              constraint);
525     }
526     else
527         match = !lstrcmpiW(constraint, name);
528     return match;
529 }
530
531 static BOOL rfc822_name_matches(LPCWSTR constraint, LPCWSTR name,
532  DWORD *trustErrorStatus)
533 {
534     BOOL match = FALSE;
535     LPCWSTR at;
536
537     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
538
539     if (!constraint)
540         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
541     else if (!name)
542         ; /* no match */
543     else if ((at = strchrW(constraint, '@')))
544         match = !lstrcmpiW(constraint, name);
545     else
546     {
547         if ((at = strchrW(name, '@')))
548             match = url_matches(constraint, at + 1, trustErrorStatus);
549         else
550             match = !lstrcmpiW(constraint, name);
551     }
552     return match;
553 }
554
555 static BOOL dns_name_matches(LPCWSTR constraint, LPCWSTR name,
556  DWORD *trustErrorStatus)
557 {
558     BOOL match = FALSE;
559
560     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
561
562     if (!constraint)
563         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
564     else if (!name)
565         ; /* no match */
566     else if (lstrlenW(name) >= lstrlenW(constraint))
567         match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
568          constraint);
569     /* else:  name is too short, no match */
570
571     return match;
572 }
573
574 static BOOL ip_address_matches(const CRYPT_DATA_BLOB *constraint,
575  const CRYPT_DATA_BLOB *name, DWORD *trustErrorStatus)
576 {
577     BOOL match = FALSE;
578
579     TRACE("(%d, %p), (%d, %p)\n", constraint->cbData, constraint->pbData,
580      name->cbData, name->pbData);
581
582     /* RFC5280, section 4.2.1.10, iPAddress syntax: either 8 or 32 bytes, for
583      * IPv4 or IPv6 addresses, respectively.
584      */
585     if (constraint->cbData != sizeof(DWORD) * 2 && constraint->cbData != 32)
586         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
587     else if (name->cbData == sizeof(DWORD) &&
588      constraint->cbData == sizeof(DWORD) * 2)
589     {
590         DWORD subnet, mask, addr;
591
592         memcpy(&subnet, constraint->pbData, sizeof(subnet));
593         memcpy(&mask, constraint->pbData + sizeof(subnet), sizeof(mask));
594         memcpy(&addr, name->pbData, sizeof(addr));
595         /* These are really in big-endian order, but for equality matching we
596          * don't need to swap to host order
597          */
598         match = (subnet & mask) == (addr & mask);
599     }
600     else if (name->cbData == 16 && constraint->cbData == 32)
601     {
602         const BYTE *subnet, *mask, *addr;
603         DWORD i;
604
605         subnet = constraint->pbData;
606         mask = constraint->pbData + 16;
607         addr = name->pbData;
608         match = TRUE;
609         for (i = 0; match && i < 16; i++)
610             if ((subnet[i] & mask[i]) != (addr[i] & mask[i]))
611                 match = FALSE;
612     }
613     /* else: name is wrong size, no match */
614
615     return match;
616 }
617
618 static void CRYPT_FindMatchingNameEntry(const CERT_ALT_NAME_ENTRY *constraint,
619  const CERT_ALT_NAME_INFO *subjectName, DWORD *trustErrorStatus,
620  DWORD errorIfFound, DWORD errorIfNotFound)
621 {
622     DWORD i;
623     BOOL match = FALSE;
624
625     for (i = 0; i < subjectName->cAltEntry; i++)
626     {
627         if (subjectName->rgAltEntry[i].dwAltNameChoice ==
628          constraint->dwAltNameChoice)
629         {
630             switch (constraint->dwAltNameChoice)
631             {
632             case CERT_ALT_NAME_RFC822_NAME:
633                 match = rfc822_name_matches(constraint->u.pwszURL,
634                  subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
635                 break;
636             case CERT_ALT_NAME_DNS_NAME:
637                 match = dns_name_matches(constraint->u.pwszURL,
638                  subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
639                 break;
640             case CERT_ALT_NAME_URL:
641                 match = url_matches(constraint->u.pwszURL,
642                  subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
643                 break;
644             case CERT_ALT_NAME_IP_ADDRESS:
645                 match = ip_address_matches(&constraint->u.IPAddress,
646                  &subjectName->rgAltEntry[i].u.IPAddress, trustErrorStatus);
647                 break;
648             case CERT_ALT_NAME_DIRECTORY_NAME:
649             default:
650                 ERR("name choice %d unsupported in this context\n",
651                  constraint->dwAltNameChoice);
652                 *trustErrorStatus |=
653                  CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
654             }
655         }
656     }
657     *trustErrorStatus |= match ? errorIfFound : errorIfNotFound;
658 }
659
660 static void CRYPT_CheckNameConstraints(
661  const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, const CERT_INFO *cert,
662  DWORD *trustErrorStatus)
663 {
664     /* If there aren't any existing constraints, don't bother checking */
665     if (nameConstraints->cPermittedSubtree || nameConstraints->cExcludedSubtree)
666     {
667         CERT_EXTENSION *ext;
668
669         ext = CertFindExtension(szOID_SUBJECT_ALT_NAME2, cert->cExtension,
670          cert->rgExtension);
671         if (!ext)
672             ext = CertFindExtension(szOID_SUBJECT_ALT_NAME, cert->cExtension,
673              cert->rgExtension);
674         if (ext)
675         {
676             CERT_ALT_NAME_INFO *subjectName;
677             DWORD size;
678
679             if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
680              ext->Value.pbData, ext->Value.cbData,
681              CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
682              &subjectName, &size))
683             {
684                 DWORD i;
685
686                 for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
687                     CRYPT_FindMatchingNameEntry(
688                      &nameConstraints->rgExcludedSubtree[i].Base, subjectName,
689                      trustErrorStatus,
690                      CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT, 0);
691                 for (i = 0; i < nameConstraints->cPermittedSubtree; i++)
692                     CRYPT_FindMatchingNameEntry(
693                      &nameConstraints->rgPermittedSubtree[i].Base, subjectName,
694                      trustErrorStatus,
695                      0, CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT);
696                 LocalFree(subjectName);
697             }
698         }
699         else
700         {
701             if (nameConstraints->cPermittedSubtree)
702                 *trustErrorStatus |=
703                  CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
704             if (nameConstraints->cExcludedSubtree)
705                 *trustErrorStatus |=
706                  CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
707         }
708     }
709 }
710
711 /* Gets cert's name constraints, if any.  Free with LocalFree. */
712 static CERT_NAME_CONSTRAINTS_INFO *CRYPT_GetNameConstraints(CERT_INFO *cert)
713 {
714     CERT_NAME_CONSTRAINTS_INFO *info = NULL;
715
716     CERT_EXTENSION *ext;
717
718     if ((ext = CertFindExtension(szOID_NAME_CONSTRAINTS, cert->cExtension,
719      cert->rgExtension)))
720     {
721         DWORD size;
722
723         CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
724          ext->Value.pbData, ext->Value.cbData,
725          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &info,
726          &size);
727     }
728     return info;
729 }
730
731 static void CRYPT_CheckChainNameConstraints(PCERT_SIMPLE_CHAIN chain)
732 {
733     int i, j;
734
735     /* Microsoft's implementation appears to violate RFC 3280:  according to
736      * MSDN, the various CERT_TRUST_*_NAME_CONSTRAINT errors are set if a CA's
737      * name constraint is violated in the end cert.  According to RFC 3280,
738      * the constraints should be checked against every subsequent certificate
739      * in the chain, not just the end cert.
740      * Microsoft's implementation also sets the name constraint errors on the
741      * certs whose constraints were violated, not on the certs that violated
742      * them.
743      * In order to be error-compatible with Microsoft's implementation, while
744      * still adhering to RFC 3280, I use a O(n ^ 2) algorithm to check name
745      * constraints.
746      */
747     for (i = chain->cElement - 1; i > 0; i--)
748     {
749         CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
750
751         if ((nameConstraints = CRYPT_GetNameConstraints(
752          chain->rgpElement[i]->pCertContext->pCertInfo)))
753         {
754             for (j = i - 1; j >= 0; j--)
755             {
756                 DWORD errorStatus = 0;
757
758                 /* According to RFC 3280, self-signed certs don't have name
759                  * constraints checked unless they're the end cert.
760                  */
761                 if (j == 0 || !CRYPT_IsCertificateSelfSigned(
762                  chain->rgpElement[j]->pCertContext))
763                 {
764                     CRYPT_CheckNameConstraints(nameConstraints,
765                      chain->rgpElement[i]->pCertContext->pCertInfo,
766                      &errorStatus);
767                     chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
768                      errorStatus;
769                 }
770             }
771             LocalFree(nameConstraints);
772         }
773     }
774 }
775
776 static LPWSTR name_value_to_str(const CERT_NAME_BLOB *name)
777 {
778     DWORD len = cert_name_to_str_with_indent(X509_ASN_ENCODING, 0, name,
779      CERT_SIMPLE_NAME_STR, NULL, 0);
780     LPWSTR str = NULL;
781
782     if (len)
783     {
784         str = CryptMemAlloc(len * sizeof(WCHAR));
785         if (str)
786             cert_name_to_str_with_indent(X509_ASN_ENCODING, 0, name,
787              CERT_SIMPLE_NAME_STR, str, len);
788     }
789     return str;
790 }
791
792 static void dump_alt_name_entry(const CERT_ALT_NAME_ENTRY *entry)
793 {
794     LPWSTR str;
795
796     switch (entry->dwAltNameChoice)
797     {
798     case CERT_ALT_NAME_OTHER_NAME:
799         TRACE_(chain)("CERT_ALT_NAME_OTHER_NAME, oid = %s\n",
800          debugstr_a(entry->u.pOtherName->pszObjId));
801          break;
802     case CERT_ALT_NAME_RFC822_NAME:
803         TRACE_(chain)("CERT_ALT_NAME_RFC822_NAME: %s\n",
804          debugstr_w(entry->u.pwszRfc822Name));
805         break;
806     case CERT_ALT_NAME_DNS_NAME:
807         TRACE_(chain)("CERT_ALT_NAME_DNS_NAME: %s\n",
808          debugstr_w(entry->u.pwszDNSName));
809         break;
810     case CERT_ALT_NAME_DIRECTORY_NAME:
811         str = name_value_to_str(&entry->u.DirectoryName);
812         TRACE_(chain)("CERT_ALT_NAME_DIRECTORY_NAME: %s\n", debugstr_w(str));
813         CryptMemFree(str);
814         break;
815     case CERT_ALT_NAME_URL:
816         TRACE_(chain)("CERT_ALT_NAME_URL: %s\n", debugstr_w(entry->u.pwszURL));
817         break;
818     case CERT_ALT_NAME_IP_ADDRESS:
819         TRACE_(chain)("CERT_ALT_NAME_IP_ADDRESS: %d bytes\n",
820          entry->u.IPAddress.cbData);
821         break;
822     case CERT_ALT_NAME_REGISTERED_ID:
823         TRACE_(chain)("CERT_ALT_NAME_REGISTERED_ID: %s\n",
824          debugstr_a(entry->u.pszRegisteredID));
825         break;
826     default:
827         TRACE_(chain)("dwAltNameChoice = %d\n", entry->dwAltNameChoice);
828     }
829 }
830
831 static void dump_alt_name(LPCSTR type, const CERT_EXTENSION *ext)
832 {
833     CERT_ALT_NAME_INFO *name;
834     DWORD size;
835
836     TRACE_(chain)("%s:\n", type);
837     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
838      ext->Value.pbData, ext->Value.cbData,
839      CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &name, &size))
840     {
841         DWORD i;
842
843         TRACE_(chain)("%d alt name entries:\n", name->cAltEntry);
844         for (i = 0; i < name->cAltEntry; i++)
845             dump_alt_name_entry(&name->rgAltEntry[i]);
846         LocalFree(name);
847     }
848 }
849
850 static void dump_basic_constraints(const CERT_EXTENSION *ext)
851 {
852     CERT_BASIC_CONSTRAINTS_INFO *info;
853     DWORD size = 0;
854
855     if (CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
856      ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
857      NULL, &info, &size))
858     {
859         TRACE_(chain)("SubjectType: %02x\n", info->SubjectType.pbData[0]);
860         TRACE_(chain)("%s path length constraint\n",
861          info->fPathLenConstraint ? "has" : "doesn't have");
862         TRACE_(chain)("path length=%d\n", info->dwPathLenConstraint);
863         LocalFree(info);
864     }
865 }
866
867 static void dump_basic_constraints2(const CERT_EXTENSION *ext)
868 {
869     CERT_BASIC_CONSTRAINTS2_INFO constraints;
870     DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
871
872     if (CryptDecodeObjectEx(X509_ASN_ENCODING,
873      szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
874      0, NULL, &constraints, &size))
875     {
876         TRACE_(chain)("basic constraints:\n");
877         TRACE_(chain)("can%s be a CA\n", constraints.fCA ? "" : "not");
878         TRACE_(chain)("%s path length constraint\n",
879          constraints.fPathLenConstraint ? "has" : "doesn't have");
880         TRACE_(chain)("path length=%d\n", constraints.dwPathLenConstraint);
881     }
882 }
883
884 static void dump_key_usage(const CERT_EXTENSION *ext)
885 {
886     CRYPT_BIT_BLOB usage;
887     DWORD size = sizeof(usage);
888
889     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
890      ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
891     {
892 #define trace_usage_bit(bits, bit) \
893  if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
894         if (usage.cbData)
895         {
896             trace_usage_bit(usage.pbData[0], CERT_DIGITAL_SIGNATURE_KEY_USAGE);
897             trace_usage_bit(usage.pbData[0], CERT_NON_REPUDIATION_KEY_USAGE);
898             trace_usage_bit(usage.pbData[0], CERT_KEY_ENCIPHERMENT_KEY_USAGE);
899             trace_usage_bit(usage.pbData[0], CERT_DATA_ENCIPHERMENT_KEY_USAGE);
900             trace_usage_bit(usage.pbData[0], CERT_KEY_AGREEMENT_KEY_USAGE);
901             trace_usage_bit(usage.pbData[0], CERT_KEY_CERT_SIGN_KEY_USAGE);
902             trace_usage_bit(usage.pbData[0], CERT_CRL_SIGN_KEY_USAGE);
903             trace_usage_bit(usage.pbData[0], CERT_ENCIPHER_ONLY_KEY_USAGE);
904         }
905 #undef trace_usage_bit
906         if (usage.cbData > 1 && usage.pbData[1] & CERT_DECIPHER_ONLY_KEY_USAGE)
907             TRACE_(chain)("CERT_DECIPHER_ONLY_KEY_USAGE\n");
908     }
909 }
910
911 static void dump_general_subtree(const CERT_GENERAL_SUBTREE *subtree)
912 {
913     dump_alt_name_entry(&subtree->Base);
914     TRACE_(chain)("dwMinimum = %d, fMaximum = %d, dwMaximum = %d\n",
915      subtree->dwMinimum, subtree->fMaximum, subtree->dwMaximum);
916 }
917
918 static void dump_name_constraints(const CERT_EXTENSION *ext)
919 {
920     CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
921     DWORD size;
922
923     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
924      ext->Value.pbData, ext->Value.cbData,
925      CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &nameConstraints,
926      &size))
927     {
928         DWORD i;
929
930         TRACE_(chain)("%d permitted subtrees:\n",
931          nameConstraints->cPermittedSubtree);
932         for (i = 0; i < nameConstraints->cPermittedSubtree; i++)
933             dump_general_subtree(&nameConstraints->rgPermittedSubtree[i]);
934         TRACE_(chain)("%d excluded subtrees:\n",
935          nameConstraints->cExcludedSubtree);
936         for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
937             dump_general_subtree(&nameConstraints->rgExcludedSubtree[i]);
938         LocalFree(nameConstraints);
939     }
940 }
941
942 static void dump_cert_policies(const CERT_EXTENSION *ext)
943 {
944     CERT_POLICIES_INFO *policies;
945     DWORD size;
946
947     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_CERT_POLICIES,
948      ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
949      &policies, &size))
950     {
951         DWORD i, j;
952
953         TRACE_(chain)("%d policies:\n", policies->cPolicyInfo);
954         for (i = 0; i < policies->cPolicyInfo; i++)
955         {
956             TRACE_(chain)("policy identifier: %s\n",
957              debugstr_a(policies->rgPolicyInfo[i].pszPolicyIdentifier));
958             TRACE_(chain)("%d policy qualifiers:\n",
959              policies->rgPolicyInfo[i].cPolicyQualifier);
960             for (j = 0; j < policies->rgPolicyInfo[i].cPolicyQualifier; j++)
961                 TRACE_(chain)("%s\n", debugstr_a(
962                  policies->rgPolicyInfo[i].rgPolicyQualifier[j].
963                  pszPolicyQualifierId));
964         }
965         LocalFree(policies);
966     }
967 }
968
969 static void dump_enhanced_key_usage(const CERT_EXTENSION *ext)
970 {
971     CERT_ENHKEY_USAGE *usage;
972     DWORD size;
973
974     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ENHANCED_KEY_USAGE,
975      ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
976      &usage, &size))
977     {
978         DWORD i;
979
980         TRACE_(chain)("%d usages:\n", usage->cUsageIdentifier);
981         for (i = 0; i < usage->cUsageIdentifier; i++)
982             TRACE_(chain)("%s\n", usage->rgpszUsageIdentifier[i]);
983         LocalFree(usage);
984     }
985 }
986
987 static void dump_netscape_cert_type(const CERT_EXTENSION *ext)
988 {
989     CRYPT_BIT_BLOB usage;
990     DWORD size = sizeof(usage);
991
992     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
993      ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
994     {
995 #define trace_cert_type_bit(bits, bit) \
996  if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
997         if (usage.cbData)
998         {
999             trace_cert_type_bit(usage.pbData[0],
1000              NETSCAPE_SSL_CLIENT_AUTH_CERT_TYPE);
1001             trace_cert_type_bit(usage.pbData[0],
1002              NETSCAPE_SSL_SERVER_AUTH_CERT_TYPE);
1003             trace_cert_type_bit(usage.pbData[0], NETSCAPE_SMIME_CERT_TYPE);
1004             trace_cert_type_bit(usage.pbData[0], NETSCAPE_SIGN_CERT_TYPE);
1005             trace_cert_type_bit(usage.pbData[0], NETSCAPE_SSL_CA_CERT_TYPE);
1006             trace_cert_type_bit(usage.pbData[0], NETSCAPE_SMIME_CA_CERT_TYPE);
1007             trace_cert_type_bit(usage.pbData[0], NETSCAPE_SIGN_CA_CERT_TYPE);
1008         }
1009 #undef trace_cert_type_bit
1010     }
1011 }
1012
1013 static void dump_extension(const CERT_EXTENSION *ext)
1014 {
1015     TRACE_(chain)("%s (%scritical)\n", debugstr_a(ext->pszObjId),
1016      ext->fCritical ? "" : "not ");
1017     if (!strcmp(ext->pszObjId, szOID_SUBJECT_ALT_NAME))
1018         dump_alt_name("subject alt name", ext);
1019     else  if (!strcmp(ext->pszObjId, szOID_ISSUER_ALT_NAME))
1020         dump_alt_name("issuer alt name", ext);
1021     else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS))
1022         dump_basic_constraints(ext);
1023     else if (!strcmp(ext->pszObjId, szOID_KEY_USAGE))
1024         dump_key_usage(ext);
1025     else if (!strcmp(ext->pszObjId, szOID_SUBJECT_ALT_NAME2))
1026         dump_alt_name("subject alt name 2", ext);
1027     else if (!strcmp(ext->pszObjId, szOID_ISSUER_ALT_NAME2))
1028         dump_alt_name("issuer alt name 2", ext);
1029     else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS2))
1030         dump_basic_constraints2(ext);
1031     else if (!strcmp(ext->pszObjId, szOID_NAME_CONSTRAINTS))
1032         dump_name_constraints(ext);
1033     else if (!strcmp(ext->pszObjId, szOID_CERT_POLICIES))
1034         dump_cert_policies(ext);
1035     else if (!strcmp(ext->pszObjId, szOID_ENHANCED_KEY_USAGE))
1036         dump_enhanced_key_usage(ext);
1037     else if (!strcmp(ext->pszObjId, szOID_NETSCAPE_CERT_TYPE))
1038         dump_netscape_cert_type(ext);
1039 }
1040
1041 static LPCWSTR filetime_to_str(const FILETIME *time)
1042 {
1043     static WCHAR date[80];
1044     WCHAR dateFmt[80]; /* sufficient for all versions of LOCALE_SSHORTDATE */
1045     SYSTEMTIME sysTime;
1046
1047     if (!time) return NULL;
1048
1049     GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, dateFmt,
1050      sizeof(dateFmt) / sizeof(dateFmt[0]));
1051     FileTimeToSystemTime(time, &sysTime);
1052     GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, date,
1053      sizeof(date) / sizeof(date[0]));
1054     return date;
1055 }
1056
1057 static void dump_element(PCCERT_CONTEXT cert)
1058 {
1059     LPWSTR name = NULL;
1060     DWORD len, i;
1061
1062     TRACE_(chain)("%p\n", cert);
1063     len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
1064      CERT_NAME_ISSUER_FLAG, NULL, NULL, 0);
1065     name = CryptMemAlloc(len * sizeof(WCHAR));
1066     if (name)
1067     {
1068         CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
1069          CERT_NAME_ISSUER_FLAG, NULL, name, len);
1070         TRACE_(chain)("issued by %s\n", debugstr_w(name));
1071         CryptMemFree(name);
1072     }
1073     len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
1074      NULL, 0);
1075     name = CryptMemAlloc(len * sizeof(WCHAR));
1076     if (name)
1077     {
1078         CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
1079          name, len);
1080         TRACE_(chain)("issued to %s\n", debugstr_w(name));
1081         CryptMemFree(name);
1082     }
1083     TRACE_(chain)("valid from %s to %s\n",
1084      debugstr_w(filetime_to_str(&cert->pCertInfo->NotBefore)),
1085      debugstr_w(filetime_to_str(&cert->pCertInfo->NotAfter)));
1086     TRACE_(chain)("%d extensions\n", cert->pCertInfo->cExtension);
1087     for (i = 0; i < cert->pCertInfo->cExtension; i++)
1088         dump_extension(&cert->pCertInfo->rgExtension[i]);
1089 }
1090
1091 static BOOL CRYPT_KeyUsageValid(PCertificateChainEngine engine,
1092  PCCERT_CONTEXT cert, BOOL isRoot, BOOL isCA, DWORD index)
1093 {
1094     PCERT_EXTENSION ext;
1095     BOOL ret;
1096     BYTE usageBits = 0;
1097
1098     ext = CertFindExtension(szOID_KEY_USAGE, cert->pCertInfo->cExtension,
1099      cert->pCertInfo->rgExtension);
1100     if (ext)
1101     {
1102         CRYPT_BIT_BLOB usage;
1103         DWORD size = sizeof(usage);
1104
1105         ret = CryptDecodeObjectEx(cert->dwCertEncodingType, X509_BITS,
1106          ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL,
1107          &usage, &size);
1108         if (!ret)
1109             return FALSE;
1110         else if (usage.cbData > 2)
1111         {
1112             /* The key usage extension only defines 9 bits => no more than 2
1113              * bytes are needed to encode all known usages.
1114              */
1115             return FALSE;
1116         }
1117         else
1118         {
1119             /* The only bit relevant to chain validation is the keyCertSign
1120              * bit, which is always in the least significant byte of the
1121              * key usage bits.
1122              */
1123             usageBits = usage.pbData[usage.cbData - 1];
1124         }
1125     }
1126     if (isCA)
1127     {
1128         if (!ext)
1129         {
1130             /* MS appears to violate RFC 5280, section 4.2.1.3 (Key Usage)
1131              * here.  Quoting the RFC:
1132              * "This [key usage] extension MUST appear in certificates that
1133              * contain public keys that are used to validate digital signatures
1134              * on other public key certificates or CRLs."
1135              * MS appears to accept certs that do not contain key usage
1136              * extensions as CA certs.  V1 and V2 certificates did not have
1137              * extensions, and many root certificates are V1 certificates, so
1138              * perhaps this is prudent.  On the other hand, MS also accepts V3
1139              * certs without key usage extensions.  We are more restrictive:
1140              * we accept locally installed V1 or V2 certs as CA certs.
1141              * We also accept a lack of key usage extension on root certs,
1142              * which is implied in RFC 5280, section 6.1:  the trust anchor's
1143              * only requirement is that it was used to issue the next
1144              * certificate in the chain.
1145              */
1146             if (isRoot)
1147                 ret = TRUE;
1148             else if (cert->pCertInfo->dwVersion == CERT_V1 ||
1149              cert->pCertInfo->dwVersion == CERT_V2)
1150             {
1151                 PCCERT_CONTEXT localCert = CRYPT_FindCertInStore(
1152                  engine->hWorld, cert);
1153
1154                 ret = localCert != NULL;
1155                 CertFreeCertificateContext(localCert);
1156             }
1157             else
1158                 ret = FALSE;
1159             if (!ret)
1160                 WARN_(chain)("no key usage extension on a CA cert\n");
1161         }
1162         else
1163         {
1164             if (!(usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
1165             {
1166                 WARN_(chain)("keyCertSign not asserted on a CA cert\n");
1167                 ret = FALSE;
1168             }
1169             else
1170                 ret = TRUE;
1171         }
1172     }
1173     else
1174     {
1175         if (ext && (usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
1176         {
1177             WARN_(chain)("keyCertSign asserted on a non-CA cert\n");
1178             ret = FALSE;
1179         }
1180         else
1181             ret = TRUE;
1182     }
1183     return ret;
1184 }
1185
1186 static BOOL CRYPT_ExtendedKeyUsageValidForCA(PCCERT_CONTEXT cert)
1187 {
1188     PCERT_EXTENSION ext;
1189     BOOL ret;
1190
1191     /* RFC 5280, section 4.2.1.12:  "In general, this extension will only
1192      * appear in end entity certificates."  And, "If a certificate contains
1193      * both a key usage extension and an extended key usage extension, then
1194      * both extensions MUST be processed independently and the certificate MUST
1195      * only be used for a purpose consistent with both extensions."  This seems
1196      * to imply that it should be checked if present, and ignored if not.
1197      * Unfortunately some CAs, e.g. the Thawte SGC CA, don't include the code
1198      * signing extended key usage, whereas they do include the keyCertSign
1199      * key usage.  Thus, when checking for a CA, we only require the
1200      * code signing extended key usage if the extended key usage is critical.
1201      */
1202     ext = CertFindExtension(szOID_ENHANCED_KEY_USAGE,
1203      cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
1204     if (ext && ext->fCritical)
1205     {
1206         CERT_ENHKEY_USAGE *usage;
1207         DWORD size;
1208
1209         ret = CryptDecodeObjectEx(cert->dwCertEncodingType,
1210          X509_ENHANCED_KEY_USAGE, ext->Value.pbData, ext->Value.cbData,
1211          CRYPT_DECODE_ALLOC_FLAG, NULL, &usage, &size);
1212         if (ret)
1213         {
1214             DWORD i;
1215
1216             /* Explicitly require the code signing extended key usage for a CA
1217              * with an extended key usage extension.  That is, don't assume
1218              * a cert is allowed to be a CA if it specifies the
1219              * anyExtendedKeyUsage usage oid.  See again RFC 5280, section
1220              * 4.2.1.12: "Applications that require the presence of a
1221              * particular purpose MAY reject certificates that include the
1222              * anyExtendedKeyUsage OID but not the particular OID expected for
1223              * the application."
1224              */
1225             ret = FALSE;
1226             for (i = 0; !ret && i < usage->cUsageIdentifier; i++)
1227                 if (!strcmp(usage->rgpszUsageIdentifier[i],
1228                  szOID_PKIX_KP_CODE_SIGNING))
1229                     ret = TRUE;
1230             LocalFree(usage);
1231         }
1232     }
1233     else
1234         ret = TRUE;
1235     return ret;
1236 }
1237
1238 static BOOL CRYPT_CriticalExtensionsSupported(PCCERT_CONTEXT cert)
1239 {
1240     BOOL ret = TRUE;
1241     DWORD i;
1242
1243     for (i = 0; ret && i < cert->pCertInfo->cExtension; i++)
1244     {
1245         if (cert->pCertInfo->rgExtension[i].fCritical)
1246         {
1247             LPCSTR oid = cert->pCertInfo->rgExtension[i].pszObjId;
1248
1249             if (!strcmp(oid, szOID_BASIC_CONSTRAINTS))
1250                 ret = TRUE;
1251             else if (!strcmp(oid, szOID_BASIC_CONSTRAINTS2))
1252                 ret = TRUE;
1253             else if (!strcmp(oid, szOID_NAME_CONSTRAINTS))
1254                 ret = TRUE;
1255             else if (!strcmp(oid, szOID_KEY_USAGE))
1256                 ret = TRUE;
1257             else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME))
1258                 ret = TRUE;
1259             else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME2))
1260                 ret = TRUE;
1261             else if (!strcmp(oid, szOID_ENHANCED_KEY_USAGE))
1262                 ret = TRUE;
1263             else
1264             {
1265                 FIXME("unsupported critical extension %s\n",
1266                  debugstr_a(oid));
1267                 ret = FALSE;
1268             }
1269         }
1270     }
1271     return ret;
1272 }
1273
1274 static void CRYPT_CheckSimpleChain(PCertificateChainEngine engine,
1275  PCERT_SIMPLE_CHAIN chain, LPFILETIME time)
1276 {
1277     PCERT_CHAIN_ELEMENT rootElement = chain->rgpElement[chain->cElement - 1];
1278     int i;
1279     BOOL pathLengthConstraintViolated = FALSE;
1280     CERT_BASIC_CONSTRAINTS2_INFO constraints = { FALSE, FALSE, 0 };
1281
1282     TRACE_(chain)("checking chain with %d elements for time %s\n",
1283      chain->cElement, debugstr_w(filetime_to_str(time)));
1284     for (i = chain->cElement - 1; i >= 0; i--)
1285     {
1286         BOOL isRoot;
1287
1288         if (TRACE_ON(chain))
1289             dump_element(chain->rgpElement[i]->pCertContext);
1290         if (i == chain->cElement - 1)
1291             isRoot = CRYPT_IsCertificateSelfSigned(
1292              chain->rgpElement[i]->pCertContext);
1293         else
1294             isRoot = FALSE;
1295         if (CertVerifyTimeValidity(time,
1296          chain->rgpElement[i]->pCertContext->pCertInfo) != 0)
1297             chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1298              CERT_TRUST_IS_NOT_TIME_VALID;
1299         if (i != 0)
1300         {
1301             /* Check the signature of the cert this issued */
1302             if (!CryptVerifyCertificateSignatureEx(0, X509_ASN_ENCODING,
1303              CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT,
1304              (void *)chain->rgpElement[i - 1]->pCertContext,
1305              CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT,
1306              (void *)chain->rgpElement[i]->pCertContext, 0, NULL))
1307                 chain->rgpElement[i - 1]->TrustStatus.dwErrorStatus |=
1308                  CERT_TRUST_IS_NOT_SIGNATURE_VALID;
1309             /* Once a path length constraint has been violated, every remaining
1310              * CA cert's basic constraints is considered invalid.
1311              */
1312             if (pathLengthConstraintViolated)
1313                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1314                  CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1315             else if (!CRYPT_CheckBasicConstraintsForCA(engine,
1316              chain->rgpElement[i]->pCertContext, &constraints, i - 1, isRoot,
1317              &pathLengthConstraintViolated))
1318                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1319                  CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1320             else if (constraints.fPathLenConstraint &&
1321              constraints.dwPathLenConstraint)
1322             {
1323                 /* This one's valid - decrement max length */
1324                 constraints.dwPathLenConstraint--;
1325             }
1326         }
1327         else
1328         {
1329             /* Check whether end cert has a basic constraints extension */
1330             if (!CRYPT_DecodeBasicConstraints(
1331              chain->rgpElement[i]->pCertContext, &constraints, FALSE))
1332                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1333                  CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1334         }
1335         if (!CRYPT_KeyUsageValid(engine, chain->rgpElement[i]->pCertContext,
1336          isRoot, constraints.fCA, i))
1337             chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1338              CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
1339         if (i != 0)
1340             if (!CRYPT_ExtendedKeyUsageValidForCA(
1341              chain->rgpElement[i]->pCertContext))
1342                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1343                  CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
1344         if (CRYPT_IsSimpleChainCyclic(chain))
1345         {
1346             /* If the chain is cyclic, then the path length constraints
1347              * are violated, because the chain is infinitely long.
1348              */
1349             pathLengthConstraintViolated = TRUE;
1350             chain->TrustStatus.dwErrorStatus |=
1351              CERT_TRUST_IS_PARTIAL_CHAIN |
1352              CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1353         }
1354         /* Check whether every critical extension is supported */
1355         if (!CRYPT_CriticalExtensionsSupported(
1356          chain->rgpElement[i]->pCertContext))
1357             chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1358              CERT_TRUST_INVALID_EXTENSION;
1359         CRYPT_CombineTrustStatus(&chain->TrustStatus,
1360          &chain->rgpElement[i]->TrustStatus);
1361     }
1362     CRYPT_CheckChainNameConstraints(chain);
1363     if (CRYPT_IsCertificateSelfSigned(rootElement->pCertContext))
1364     {
1365         rootElement->TrustStatus.dwInfoStatus |=
1366          CERT_TRUST_IS_SELF_SIGNED | CERT_TRUST_HAS_NAME_MATCH_ISSUER;
1367         CRYPT_CheckRootCert(engine->hRoot, rootElement);
1368     }
1369     CRYPT_CombineTrustStatus(&chain->TrustStatus, &rootElement->TrustStatus);
1370 }
1371
1372 static PCCERT_CONTEXT CRYPT_GetIssuer(HCERTSTORE store, PCCERT_CONTEXT subject,
1373  PCCERT_CONTEXT prevIssuer, DWORD *infoStatus)
1374 {
1375     PCCERT_CONTEXT issuer = NULL;
1376     PCERT_EXTENSION ext;
1377     DWORD size;
1378
1379     *infoStatus = 0;
1380     if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
1381      subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1382     {
1383         CERT_AUTHORITY_KEY_ID_INFO *info;
1384         BOOL ret;
1385
1386         ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1387          X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
1388          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1389          &info, &size);
1390         if (ret)
1391         {
1392             CERT_ID id;
1393
1394             if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
1395             {
1396                 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1397                 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
1398                  sizeof(CERT_NAME_BLOB));
1399                 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1400                  &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
1401                 issuer = CertFindCertificateInStore(store,
1402                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1403                  prevIssuer);
1404                 if (issuer)
1405                     *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
1406             }
1407             else if (info->KeyId.cbData)
1408             {
1409                 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1410                 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1411                 issuer = CertFindCertificateInStore(store,
1412                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1413                  prevIssuer);
1414                 if (issuer)
1415                     *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
1416             }
1417             LocalFree(info);
1418         }
1419     }
1420     else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
1421      subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1422     {
1423         CERT_AUTHORITY_KEY_ID2_INFO *info;
1424         BOOL ret;
1425
1426         ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1427          X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
1428          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1429          &info, &size);
1430         if (ret)
1431         {
1432             CERT_ID id;
1433
1434             if (info->AuthorityCertIssuer.cAltEntry &&
1435              info->AuthorityCertSerialNumber.cbData)
1436             {
1437                 PCERT_ALT_NAME_ENTRY directoryName = NULL;
1438                 DWORD i;
1439
1440                 for (i = 0; !directoryName &&
1441                  i < info->AuthorityCertIssuer.cAltEntry; i++)
1442                     if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
1443                      == CERT_ALT_NAME_DIRECTORY_NAME)
1444                         directoryName =
1445                          &info->AuthorityCertIssuer.rgAltEntry[i];
1446                 if (directoryName)
1447                 {
1448                     id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1449                     memcpy(&id.u.IssuerSerialNumber.Issuer,
1450                      &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
1451                     memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1452                      &info->AuthorityCertSerialNumber,
1453                      sizeof(CRYPT_INTEGER_BLOB));
1454                     issuer = CertFindCertificateInStore(store,
1455                      subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1456                      prevIssuer);
1457                     if (issuer)
1458                         *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
1459                 }
1460                 else
1461                     FIXME("no supported name type in authority key id2\n");
1462             }
1463             else if (info->KeyId.cbData)
1464             {
1465                 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1466                 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1467                 issuer = CertFindCertificateInStore(store,
1468                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1469                  prevIssuer);
1470                 if (issuer)
1471                     *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
1472             }
1473             LocalFree(info);
1474         }
1475     }
1476     else
1477     {
1478         issuer = CertFindCertificateInStore(store,
1479          subject->dwCertEncodingType, 0, CERT_FIND_SUBJECT_NAME,
1480          &subject->pCertInfo->Issuer, prevIssuer);
1481         *infoStatus = CERT_TRUST_HAS_NAME_MATCH_ISSUER;
1482     }
1483     return issuer;
1484 }
1485
1486 /* Builds a simple chain by finding an issuer for the last cert in the chain,
1487  * until reaching a self-signed cert, or until no issuer can be found.
1488  */
1489 static BOOL CRYPT_BuildSimpleChain(const CertificateChainEngine *engine,
1490  HCERTSTORE world, PCERT_SIMPLE_CHAIN chain)
1491 {
1492     BOOL ret = TRUE;
1493     PCCERT_CONTEXT cert = chain->rgpElement[chain->cElement - 1]->pCertContext;
1494
1495     while (ret && !CRYPT_IsSimpleChainCyclic(chain) &&
1496      !CRYPT_IsCertificateSelfSigned(cert))
1497     {
1498         PCCERT_CONTEXT issuer = CRYPT_GetIssuer(world, cert, NULL,
1499          &chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
1500
1501         if (issuer)
1502         {
1503             ret = CRYPT_AddCertToSimpleChain(engine, chain, issuer,
1504              chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
1505             /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it to
1506              * close the enumeration that found it
1507              */
1508             CertFreeCertificateContext(issuer);
1509             cert = issuer;
1510         }
1511         else
1512         {
1513             TRACE_(chain)("Couldn't find issuer, halting chain creation\n");
1514             chain->TrustStatus.dwErrorStatus |= CERT_TRUST_IS_PARTIAL_CHAIN;
1515             break;
1516         }
1517     }
1518     return ret;
1519 }
1520
1521 static BOOL CRYPT_GetSimpleChainForCert(PCertificateChainEngine engine,
1522  HCERTSTORE world, PCCERT_CONTEXT cert, LPFILETIME pTime,
1523  PCERT_SIMPLE_CHAIN *ppChain)
1524 {
1525     BOOL ret = FALSE;
1526     PCERT_SIMPLE_CHAIN chain;
1527
1528     TRACE("(%p, %p, %p, %p)\n", engine, world, cert, pTime);
1529
1530     chain = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
1531     if (chain)
1532     {
1533         memset(chain, 0, sizeof(CERT_SIMPLE_CHAIN));
1534         chain->cbSize = sizeof(CERT_SIMPLE_CHAIN);
1535         ret = CRYPT_AddCertToSimpleChain(engine, chain, cert, 0);
1536         if (ret)
1537         {
1538             ret = CRYPT_BuildSimpleChain(engine, world, chain);
1539             if (ret)
1540                 CRYPT_CheckSimpleChain(engine, chain, pTime);
1541         }
1542         if (!ret)
1543         {
1544             CRYPT_FreeSimpleChain(chain);
1545             chain = NULL;
1546         }
1547         *ppChain = chain;
1548     }
1549     return ret;
1550 }
1551
1552 static BOOL CRYPT_BuildCandidateChainFromCert(HCERTCHAINENGINE hChainEngine,
1553  PCCERT_CONTEXT cert, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1554  PCertificateChain *ppChain)
1555 {
1556     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
1557     PCERT_SIMPLE_CHAIN simpleChain = NULL;
1558     HCERTSTORE world;
1559     BOOL ret;
1560
1561     world = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
1562      CERT_STORE_CREATE_NEW_FLAG, NULL);
1563     CertAddStoreToCollection(world, engine->hWorld, 0, 0);
1564     if (hAdditionalStore)
1565         CertAddStoreToCollection(world, hAdditionalStore, 0, 0);
1566     /* FIXME: only simple chains are supported for now, as CTLs aren't
1567      * supported yet.
1568      */
1569     if ((ret = CRYPT_GetSimpleChainForCert(engine, world, cert, pTime,
1570      &simpleChain)))
1571     {
1572         PCertificateChain chain = CryptMemAlloc(sizeof(CertificateChain));
1573
1574         if (chain)
1575         {
1576             chain->ref = 1;
1577             chain->world = world;
1578             chain->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
1579             chain->context.TrustStatus = simpleChain->TrustStatus;
1580             chain->context.cChain = 1;
1581             chain->context.rgpChain = CryptMemAlloc(sizeof(PCERT_SIMPLE_CHAIN));
1582             chain->context.rgpChain[0] = simpleChain;
1583             chain->context.cLowerQualityChainContext = 0;
1584             chain->context.rgpLowerQualityChainContext = NULL;
1585             chain->context.fHasRevocationFreshnessTime = FALSE;
1586             chain->context.dwRevocationFreshnessTime = 0;
1587         }
1588         else
1589             ret = FALSE;
1590         *ppChain = chain;
1591     }
1592     return ret;
1593 }
1594
1595 /* Makes and returns a copy of chain, up to and including element iElement. */
1596 static PCERT_SIMPLE_CHAIN CRYPT_CopySimpleChainToElement(
1597  const CERT_SIMPLE_CHAIN *chain, DWORD iElement)
1598 {
1599     PCERT_SIMPLE_CHAIN copy = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
1600
1601     if (copy)
1602     {
1603         memset(copy, 0, sizeof(CERT_SIMPLE_CHAIN));
1604         copy->cbSize = sizeof(CERT_SIMPLE_CHAIN);
1605         copy->rgpElement =
1606          CryptMemAlloc((iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
1607         if (copy->rgpElement)
1608         {
1609             DWORD i;
1610             BOOL ret = TRUE;
1611
1612             memset(copy->rgpElement, 0,
1613              (iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
1614             for (i = 0; ret && i <= iElement; i++)
1615             {
1616                 PCERT_CHAIN_ELEMENT element =
1617                  CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
1618
1619                 if (element)
1620                 {
1621                     *element = *chain->rgpElement[i];
1622                     element->pCertContext = CertDuplicateCertificateContext(
1623                      chain->rgpElement[i]->pCertContext);
1624                     /* Reset the trust status of the copied element, it'll get
1625                      * rechecked after the new chain is done.
1626                      */
1627                     memset(&element->TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
1628                     copy->rgpElement[copy->cElement++] = element;
1629                 }
1630                 else
1631                     ret = FALSE;
1632             }
1633             if (!ret)
1634             {
1635                 for (i = 0; i <= iElement; i++)
1636                     CryptMemFree(copy->rgpElement[i]);
1637                 CryptMemFree(copy->rgpElement);
1638                 CryptMemFree(copy);
1639                 copy = NULL;
1640             }
1641         }
1642         else
1643         {
1644             CryptMemFree(copy);
1645             copy = NULL;
1646         }
1647     }
1648     return copy;
1649 }
1650
1651 static void CRYPT_FreeLowerQualityChains(PCertificateChain chain)
1652 {
1653     DWORD i;
1654
1655     for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
1656         CertFreeCertificateChain(chain->context.rgpLowerQualityChainContext[i]);
1657     CryptMemFree(chain->context.rgpLowerQualityChainContext);
1658     chain->context.cLowerQualityChainContext = 0;
1659     chain->context.rgpLowerQualityChainContext = NULL;
1660 }
1661
1662 static void CRYPT_FreeChainContext(PCertificateChain chain)
1663 {
1664     DWORD i;
1665
1666     CRYPT_FreeLowerQualityChains(chain);
1667     for (i = 0; i < chain->context.cChain; i++)
1668         CRYPT_FreeSimpleChain(chain->context.rgpChain[i]);
1669     CryptMemFree(chain->context.rgpChain);
1670     CertCloseStore(chain->world, 0);
1671     CryptMemFree(chain);
1672 }
1673
1674 /* Makes and returns a copy of chain, up to and including element iElement of
1675  * simple chain iChain.
1676  */
1677 static PCertificateChain CRYPT_CopyChainToElement(PCertificateChain chain,
1678  DWORD iChain, DWORD iElement)
1679 {
1680     PCertificateChain copy = CryptMemAlloc(sizeof(CertificateChain));
1681
1682     if (copy)
1683     {
1684         copy->ref = 1;
1685         copy->world = CertDuplicateStore(chain->world);
1686         copy->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
1687         /* Leave the trust status of the copied chain unset, it'll get
1688          * rechecked after the new chain is done.
1689          */
1690         memset(&copy->context.TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
1691         copy->context.cLowerQualityChainContext = 0;
1692         copy->context.rgpLowerQualityChainContext = NULL;
1693         copy->context.fHasRevocationFreshnessTime = FALSE;
1694         copy->context.dwRevocationFreshnessTime = 0;
1695         copy->context.rgpChain = CryptMemAlloc(
1696          (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
1697         if (copy->context.rgpChain)
1698         {
1699             BOOL ret = TRUE;
1700             DWORD i;
1701
1702             memset(copy->context.rgpChain, 0,
1703              (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
1704             if (iChain)
1705             {
1706                 for (i = 0; ret && iChain && i < iChain - 1; i++)
1707                 {
1708                     copy->context.rgpChain[i] =
1709                      CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
1710                      chain->context.rgpChain[i]->cElement - 1);
1711                     if (!copy->context.rgpChain[i])
1712                         ret = FALSE;
1713                 }
1714             }
1715             else
1716                 i = 0;
1717             if (ret)
1718             {
1719                 copy->context.rgpChain[i] =
1720                  CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
1721                  iElement);
1722                 if (!copy->context.rgpChain[i])
1723                     ret = FALSE;
1724             }
1725             if (!ret)
1726             {
1727                 CRYPT_FreeChainContext(copy);
1728                 copy = NULL;
1729             }
1730             else
1731                 copy->context.cChain = iChain + 1;
1732         }
1733         else
1734         {
1735             CryptMemFree(copy);
1736             copy = NULL;
1737         }
1738     }
1739     return copy;
1740 }
1741
1742 static PCertificateChain CRYPT_BuildAlternateContextFromChain(
1743  HCERTCHAINENGINE hChainEngine, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1744  PCertificateChain chain)
1745 {
1746     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
1747     PCertificateChain alternate;
1748
1749     TRACE("(%p, %p, %p, %p)\n", hChainEngine, pTime, hAdditionalStore, chain);
1750
1751     /* Always start with the last "lower quality" chain to ensure a consistent
1752      * order of alternate creation:
1753      */
1754     if (chain->context.cLowerQualityChainContext)
1755         chain = (PCertificateChain)chain->context.rgpLowerQualityChainContext[
1756          chain->context.cLowerQualityChainContext - 1];
1757     /* A chain with only one element can't have any alternates */
1758     if (chain->context.cChain <= 1 && chain->context.rgpChain[0]->cElement <= 1)
1759         alternate = NULL;
1760     else
1761     {
1762         DWORD i, j, infoStatus;
1763         PCCERT_CONTEXT alternateIssuer = NULL;
1764
1765         alternate = NULL;
1766         for (i = 0; !alternateIssuer && i < chain->context.cChain; i++)
1767             for (j = 0; !alternateIssuer &&
1768              j < chain->context.rgpChain[i]->cElement - 1; j++)
1769             {
1770                 PCCERT_CONTEXT subject =
1771                  chain->context.rgpChain[i]->rgpElement[j]->pCertContext;
1772                 PCCERT_CONTEXT prevIssuer = CertDuplicateCertificateContext(
1773                  chain->context.rgpChain[i]->rgpElement[j + 1]->pCertContext);
1774
1775                 alternateIssuer = CRYPT_GetIssuer(prevIssuer->hCertStore,
1776                  subject, prevIssuer, &infoStatus);
1777             }
1778         if (alternateIssuer)
1779         {
1780             i--;
1781             j--;
1782             alternate = CRYPT_CopyChainToElement(chain, i, j);
1783             if (alternate)
1784             {
1785                 BOOL ret = CRYPT_AddCertToSimpleChain(engine,
1786                  alternate->context.rgpChain[i], alternateIssuer, infoStatus);
1787
1788                 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it
1789                  * to close the enumeration that found it
1790                  */
1791                 CertFreeCertificateContext(alternateIssuer);
1792                 if (ret)
1793                 {
1794                     ret = CRYPT_BuildSimpleChain(engine, alternate->world,
1795                      alternate->context.rgpChain[i]);
1796                     if (ret)
1797                         CRYPT_CheckSimpleChain(engine,
1798                          alternate->context.rgpChain[i], pTime);
1799                     CRYPT_CombineTrustStatus(&alternate->context.TrustStatus,
1800                      &alternate->context.rgpChain[i]->TrustStatus);
1801                 }
1802                 if (!ret)
1803                 {
1804                     CRYPT_FreeChainContext(alternate);
1805                     alternate = NULL;
1806                 }
1807             }
1808         }
1809     }
1810     TRACE("%p\n", alternate);
1811     return alternate;
1812 }
1813
1814 #define CHAIN_QUALITY_SIGNATURE_VALID   0x16
1815 #define CHAIN_QUALITY_TIME_VALID        8
1816 #define CHAIN_QUALITY_COMPLETE_CHAIN    4
1817 #define CHAIN_QUALITY_BASIC_CONSTRAINTS 2
1818 #define CHAIN_QUALITY_TRUSTED_ROOT      1
1819
1820 #define CHAIN_QUALITY_HIGHEST \
1821  CHAIN_QUALITY_SIGNATURE_VALID | CHAIN_QUALITY_TIME_VALID | \
1822  CHAIN_QUALITY_COMPLETE_CHAIN | CHAIN_QUALITY_BASIC_CONSTRAINTS | \
1823  CHAIN_QUALITY_TRUSTED_ROOT
1824
1825 #define IS_TRUST_ERROR_SET(TrustStatus, bits) \
1826  (TrustStatus)->dwErrorStatus & (bits)
1827
1828 static DWORD CRYPT_ChainQuality(const CertificateChain *chain)
1829 {
1830     DWORD quality = CHAIN_QUALITY_HIGHEST;
1831
1832     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1833      CERT_TRUST_IS_UNTRUSTED_ROOT))
1834         quality &= ~CHAIN_QUALITY_TRUSTED_ROOT;
1835     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1836      CERT_TRUST_INVALID_BASIC_CONSTRAINTS))
1837         quality &= ~CHAIN_QUALITY_BASIC_CONSTRAINTS;
1838     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1839      CERT_TRUST_IS_PARTIAL_CHAIN))
1840         quality &= ~CHAIN_QUALITY_COMPLETE_CHAIN;
1841     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1842      CERT_TRUST_IS_NOT_TIME_VALID | CERT_TRUST_IS_NOT_TIME_NESTED))
1843         quality &= ~CHAIN_QUALITY_TIME_VALID;
1844     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1845      CERT_TRUST_IS_NOT_SIGNATURE_VALID))
1846         quality &= ~CHAIN_QUALITY_SIGNATURE_VALID;
1847     return quality;
1848 }
1849
1850 /* Chooses the highest quality chain among chain and its "lower quality"
1851  * alternate chains.  Returns the highest quality chain, with all other
1852  * chains as lower quality chains of it.
1853  */
1854 static PCertificateChain CRYPT_ChooseHighestQualityChain(
1855  PCertificateChain chain)
1856 {
1857     DWORD i;
1858
1859     /* There are always only two chains being considered:  chain, and an
1860      * alternate at chain->rgpLowerQualityChainContext[i].  If the alternate
1861      * has a higher quality than chain, the alternate gets assigned the lower
1862      * quality contexts, with chain taking the alternate's place among the
1863      * lower quality contexts.
1864      */
1865     for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
1866     {
1867         PCertificateChain alternate =
1868          (PCertificateChain)chain->context.rgpLowerQualityChainContext[i];
1869
1870         if (CRYPT_ChainQuality(alternate) > CRYPT_ChainQuality(chain))
1871         {
1872             alternate->context.cLowerQualityChainContext =
1873              chain->context.cLowerQualityChainContext;
1874             alternate->context.rgpLowerQualityChainContext =
1875              chain->context.rgpLowerQualityChainContext;
1876             alternate->context.rgpLowerQualityChainContext[i] =
1877              (PCCERT_CHAIN_CONTEXT)chain;
1878             chain->context.cLowerQualityChainContext = 0;
1879             chain->context.rgpLowerQualityChainContext = NULL;
1880             chain = alternate;
1881         }
1882     }
1883     return chain;
1884 }
1885
1886 static BOOL CRYPT_AddAlternateChainToChain(PCertificateChain chain,
1887  const CertificateChain *alternate)
1888 {
1889     BOOL ret;
1890
1891     if (chain->context.cLowerQualityChainContext)
1892         chain->context.rgpLowerQualityChainContext =
1893          CryptMemRealloc(chain->context.rgpLowerQualityChainContext,
1894          (chain->context.cLowerQualityChainContext + 1) *
1895          sizeof(PCCERT_CHAIN_CONTEXT));
1896     else
1897         chain->context.rgpLowerQualityChainContext =
1898          CryptMemAlloc(sizeof(PCCERT_CHAIN_CONTEXT));
1899     if (chain->context.rgpLowerQualityChainContext)
1900     {
1901         chain->context.rgpLowerQualityChainContext[
1902          chain->context.cLowerQualityChainContext++] =
1903          (PCCERT_CHAIN_CONTEXT)alternate;
1904         ret = TRUE;
1905     }
1906     else
1907         ret = FALSE;
1908     return ret;
1909 }
1910
1911 static PCERT_CHAIN_ELEMENT CRYPT_FindIthElementInChain(
1912  const CERT_CHAIN_CONTEXT *chain, DWORD i)
1913 {
1914     DWORD j, iElement;
1915     PCERT_CHAIN_ELEMENT element = NULL;
1916
1917     for (j = 0, iElement = 0; !element && j < chain->cChain; j++)
1918     {
1919         if (iElement + chain->rgpChain[j]->cElement < i)
1920             iElement += chain->rgpChain[j]->cElement;
1921         else
1922             element = chain->rgpChain[j]->rgpElement[i - iElement];
1923     }
1924     return element;
1925 }
1926
1927 typedef struct _CERT_CHAIN_PARA_NO_EXTRA_FIELDS {
1928     DWORD            cbSize;
1929     CERT_USAGE_MATCH RequestedUsage;
1930 } CERT_CHAIN_PARA_NO_EXTRA_FIELDS, *PCERT_CHAIN_PARA_NO_EXTRA_FIELDS;
1931
1932 static void CRYPT_VerifyChainRevocation(PCERT_CHAIN_CONTEXT chain,
1933  LPFILETIME pTime, const CERT_CHAIN_PARA *pChainPara, DWORD chainFlags)
1934 {
1935     DWORD cContext;
1936
1937     if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_END_CERT)
1938         cContext = 1;
1939     else if ((chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN) ||
1940      (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT))
1941     {
1942         DWORD i;
1943
1944         for (i = 0, cContext = 0; i < chain->cChain; i++)
1945         {
1946             if (i < chain->cChain - 1 ||
1947              chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN)
1948                 cContext += chain->rgpChain[i]->cElement;
1949             else
1950                 cContext += chain->rgpChain[i]->cElement - 1;
1951         }
1952     }
1953     else
1954         cContext = 0;
1955     if (cContext)
1956     {
1957         PCCERT_CONTEXT *contexts =
1958          CryptMemAlloc(cContext * sizeof(PCCERT_CONTEXT *));
1959
1960         if (contexts)
1961         {
1962             DWORD i, j, iContext, revocationFlags;
1963             CERT_REVOCATION_PARA revocationPara = { sizeof(revocationPara), 0 };
1964             CERT_REVOCATION_STATUS revocationStatus =
1965              { sizeof(revocationStatus), 0 };
1966             BOOL ret;
1967
1968             for (i = 0, iContext = 0; iContext < cContext && i < chain->cChain;
1969              i++)
1970             {
1971                 for (j = 0; iContext < cContext &&
1972                  j < chain->rgpChain[i]->cElement; j++)
1973                     contexts[iContext++] =
1974                      chain->rgpChain[i]->rgpElement[j]->pCertContext;
1975             }
1976             revocationFlags = CERT_VERIFY_REV_CHAIN_FLAG;
1977             if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY)
1978                 revocationFlags |= CERT_VERIFY_CACHE_ONLY_BASED_REVOCATION;
1979             if (chainFlags & CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT)
1980                 revocationFlags |= CERT_VERIFY_REV_ACCUMULATIVE_TIMEOUT_FLAG;
1981             revocationPara.pftTimeToUse = pTime;
1982             if (pChainPara->cbSize == sizeof(CERT_CHAIN_PARA))
1983             {
1984                 revocationPara.dwUrlRetrievalTimeout =
1985                  pChainPara->dwUrlRetrievalTimeout;
1986                 revocationPara.fCheckFreshnessTime =
1987                  pChainPara->fCheckRevocationFreshnessTime;
1988                 revocationPara.dwFreshnessTime =
1989                  pChainPara->dwRevocationFreshnessTime;
1990             }
1991             ret = CertVerifyRevocation(X509_ASN_ENCODING,
1992              CERT_CONTEXT_REVOCATION_TYPE, cContext, (void **)contexts,
1993              revocationFlags, &revocationPara, &revocationStatus);
1994             if (!ret)
1995             {
1996                 PCERT_CHAIN_ELEMENT element =
1997                  CRYPT_FindIthElementInChain(chain, revocationStatus.dwIndex);
1998                 DWORD error;
1999
2000                 switch (revocationStatus.dwError)
2001                 {
2002                 case CRYPT_E_NO_REVOCATION_CHECK:
2003                 case CRYPT_E_NO_REVOCATION_DLL:
2004                 case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
2005                     error = CERT_TRUST_REVOCATION_STATUS_UNKNOWN;
2006                     break;
2007                 case CRYPT_E_REVOCATION_OFFLINE:
2008                     error = CERT_TRUST_IS_OFFLINE_REVOCATION;
2009                     break;
2010                 case CRYPT_E_REVOKED:
2011                     error = CERT_TRUST_IS_REVOKED;
2012                     break;
2013                 default:
2014                     WARN("unmapped error %08x\n", revocationStatus.dwError);
2015                     error = 0;
2016                 }
2017                 if (element)
2018                 {
2019                     /* FIXME: set element's pRevocationInfo member */
2020                     element->TrustStatus.dwErrorStatus |= error;
2021                 }
2022                 chain->TrustStatus.dwErrorStatus |= error;
2023             }
2024             CryptMemFree(contexts);
2025         }
2026     }
2027 }
2028
2029 static void dump_usage_match(LPCSTR name, const CERT_USAGE_MATCH *usageMatch)
2030 {
2031     DWORD i;
2032
2033     TRACE_(chain)("%s: %s\n", name,
2034      usageMatch->dwType == USAGE_MATCH_TYPE_AND ? "AND" : "OR");
2035     for (i = 0; i < usageMatch->Usage.cUsageIdentifier; i++)
2036         TRACE_(chain)("%s\n", usageMatch->Usage.rgpszUsageIdentifier[i]);
2037 }
2038
2039 static void dump_chain_para(const CERT_CHAIN_PARA *pChainPara)
2040 {
2041     TRACE_(chain)("%d\n", pChainPara->cbSize);
2042     if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA_NO_EXTRA_FIELDS))
2043         dump_usage_match("RequestedUsage", &pChainPara->RequestedUsage);
2044     if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA))
2045     {
2046         dump_usage_match("RequestedIssuancePolicy",
2047          &pChainPara->RequestedIssuancePolicy);
2048         TRACE_(chain)("%d\n", pChainPara->dwUrlRetrievalTimeout);
2049         TRACE_(chain)("%d\n", pChainPara->fCheckRevocationFreshnessTime);
2050         TRACE_(chain)("%d\n", pChainPara->dwRevocationFreshnessTime);
2051     }
2052 }
2053
2054 BOOL WINAPI CertGetCertificateChain(HCERTCHAINENGINE hChainEngine,
2055  PCCERT_CONTEXT pCertContext, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
2056  PCERT_CHAIN_PARA pChainPara, DWORD dwFlags, LPVOID pvReserved,
2057  PCCERT_CHAIN_CONTEXT* ppChainContext)
2058 {
2059     BOOL ret;
2060     PCertificateChain chain = NULL;
2061
2062     TRACE("(%p, %p, %p, %p, %p, %08x, %p, %p)\n", hChainEngine, pCertContext,
2063      pTime, hAdditionalStore, pChainPara, dwFlags, pvReserved, ppChainContext);
2064
2065     if (ppChainContext)
2066         *ppChainContext = NULL;
2067     if (!pChainPara)
2068     {
2069         SetLastError(E_INVALIDARG);
2070         return FALSE;
2071     }
2072     if (!pCertContext->pCertInfo->SignatureAlgorithm.pszObjId)
2073     {
2074         SetLastError(ERROR_INVALID_DATA);
2075         return FALSE;
2076     }
2077
2078     if (!hChainEngine)
2079         hChainEngine = CRYPT_GetDefaultChainEngine();
2080     if (TRACE_ON(chain))
2081         dump_chain_para(pChainPara);
2082     /* FIXME: what about HCCE_LOCAL_MACHINE? */
2083     ret = CRYPT_BuildCandidateChainFromCert(hChainEngine, pCertContext, pTime,
2084      hAdditionalStore, &chain);
2085     if (ret)
2086     {
2087         PCertificateChain alternate = NULL;
2088         PCERT_CHAIN_CONTEXT pChain;
2089
2090         do {
2091             alternate = CRYPT_BuildAlternateContextFromChain(hChainEngine,
2092              pTime, hAdditionalStore, chain);
2093
2094             /* Alternate contexts are added as "lower quality" contexts of
2095              * chain, to avoid loops in alternate chain creation.
2096              * The highest-quality chain is chosen at the end.
2097              */
2098             if (alternate)
2099                 ret = CRYPT_AddAlternateChainToChain(chain, alternate);
2100         } while (ret && alternate);
2101         chain = CRYPT_ChooseHighestQualityChain(chain);
2102         if (!(dwFlags & CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS))
2103             CRYPT_FreeLowerQualityChains(chain);
2104         pChain = (PCERT_CHAIN_CONTEXT)chain;
2105         CRYPT_VerifyChainRevocation(pChain, pTime, pChainPara, dwFlags);
2106         if (ppChainContext)
2107             *ppChainContext = pChain;
2108         else
2109             CertFreeCertificateChain(pChain);
2110     }
2111     TRACE("returning %d\n", ret);
2112     return ret;
2113 }
2114
2115 PCCERT_CHAIN_CONTEXT WINAPI CertDuplicateCertificateChain(
2116  PCCERT_CHAIN_CONTEXT pChainContext)
2117 {
2118     PCertificateChain chain = (PCertificateChain)pChainContext;
2119
2120     TRACE("(%p)\n", pChainContext);
2121
2122     if (chain)
2123         InterlockedIncrement(&chain->ref);
2124     return pChainContext;
2125 }
2126
2127 VOID WINAPI CertFreeCertificateChain(PCCERT_CHAIN_CONTEXT pChainContext)
2128 {
2129     PCertificateChain chain = (PCertificateChain)pChainContext;
2130
2131     TRACE("(%p)\n", pChainContext);
2132
2133     if (chain)
2134     {
2135         if (InterlockedDecrement(&chain->ref) == 0)
2136             CRYPT_FreeChainContext(chain);
2137     }
2138 }
2139
2140 static void find_element_with_error(PCCERT_CHAIN_CONTEXT chain, DWORD error,
2141  LONG *iChain, LONG *iElement)
2142 {
2143     DWORD i, j;
2144
2145     for (i = 0; i < chain->cChain; i++)
2146         for (j = 0; j < chain->rgpChain[i]->cElement; j++)
2147             if (chain->rgpChain[i]->rgpElement[j]->TrustStatus.dwErrorStatus &
2148              error)
2149             {
2150                 *iChain = i;
2151                 *iElement = j;
2152                 return;
2153             }
2154 }
2155
2156 static BOOL WINAPI verify_base_policy(LPCSTR szPolicyOID,
2157  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2158  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2159 {
2160     pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2161     if (pChainContext->TrustStatus.dwErrorStatus &
2162      CERT_TRUST_IS_NOT_SIGNATURE_VALID)
2163     {
2164         pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
2165         find_element_with_error(pChainContext,
2166          CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
2167          &pPolicyStatus->lElementIndex);
2168     }
2169     else if (pChainContext->TrustStatus.dwErrorStatus &
2170      CERT_TRUST_IS_UNTRUSTED_ROOT)
2171     {
2172         pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
2173         find_element_with_error(pChainContext,
2174          CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
2175          &pPolicyStatus->lElementIndex);
2176     }
2177     else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
2178     {
2179         pPolicyStatus->dwError = CERT_E_CHAINING;
2180         find_element_with_error(pChainContext, CERT_TRUST_IS_CYCLIC,
2181          &pPolicyStatus->lChainIndex, &pPolicyStatus->lElementIndex);
2182         /* For a cyclic chain, which element is a cycle isn't meaningful */
2183         pPolicyStatus->lElementIndex = -1;
2184     }
2185     else
2186         pPolicyStatus->dwError = NO_ERROR;
2187     return TRUE;
2188 }
2189
2190 static BYTE msTestPubKey1[] = {
2191 0x30,0x47,0x02,0x40,0x81,0x55,0x22,0xb9,0x8a,0xa4,0x6f,0xed,0xd6,0xe7,0xd9,
2192 0x66,0x0f,0x55,0xbc,0xd7,0xcd,0xd5,0xbc,0x4e,0x40,0x02,0x21,0xa2,0xb1,0xf7,
2193 0x87,0x30,0x85,0x5e,0xd2,0xf2,0x44,0xb9,0xdc,0x9b,0x75,0xb6,0xfb,0x46,0x5f,
2194 0x42,0xb6,0x9d,0x23,0x36,0x0b,0xde,0x54,0x0f,0xcd,0xbd,0x1f,0x99,0x2a,0x10,
2195 0x58,0x11,0xcb,0x40,0xcb,0xb5,0xa7,0x41,0x02,0x03,0x01,0x00,0x01 };
2196 static BYTE msTestPubKey2[] = {
2197 0x30,0x47,0x02,0x40,0x9c,0x50,0x05,0x1d,0xe2,0x0e,0x4c,0x53,0xd8,0xd9,0xb5,
2198 0xe5,0xfd,0xe9,0xe3,0xad,0x83,0x4b,0x80,0x08,0xd9,0xdc,0xe8,0xe8,0x35,0xf8,
2199 0x11,0xf1,0xe9,0x9b,0x03,0x7a,0x65,0x64,0x76,0x35,0xce,0x38,0x2c,0xf2,0xb6,
2200 0x71,0x9e,0x06,0xd9,0xbf,0xbb,0x31,0x69,0xa3,0xf6,0x30,0xa0,0x78,0x7b,0x18,
2201 0xdd,0x50,0x4d,0x79,0x1e,0xeb,0x61,0xc1,0x02,0x03,0x01,0x00,0x01 };
2202
2203 static BOOL WINAPI verify_authenticode_policy(LPCSTR szPolicyOID,
2204  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2205  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2206 {
2207     BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
2208      pPolicyStatus);
2209
2210     if (ret && pPolicyStatus->dwError == CERT_E_UNTRUSTEDROOT)
2211     {
2212         CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
2213         BOOL isMSTestRoot = FALSE;
2214         PCCERT_CONTEXT failingCert =
2215          pChainContext->rgpChain[pPolicyStatus->lChainIndex]->
2216          rgpElement[pPolicyStatus->lElementIndex]->pCertContext;
2217         DWORD i;
2218         CRYPT_DATA_BLOB keyBlobs[] = {
2219          { sizeof(msTestPubKey1), msTestPubKey1 },
2220          { sizeof(msTestPubKey2), msTestPubKey2 },
2221         };
2222
2223         /* Check whether the root is an MS test root */
2224         for (i = 0; !isMSTestRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
2225          i++)
2226         {
2227             msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
2228             msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
2229             if (CertComparePublicKeyInfo(
2230              X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
2231              &failingCert->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
2232                 isMSTestRoot = TRUE;
2233         }
2234         if (isMSTestRoot)
2235             pPolicyStatus->dwError = CERT_E_UNTRUSTEDTESTROOT;
2236     }
2237     return ret;
2238 }
2239
2240 static BOOL WINAPI verify_basic_constraints_policy(LPCSTR szPolicyOID,
2241  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2242  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2243 {
2244     pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2245     if (pChainContext->TrustStatus.dwErrorStatus &
2246      CERT_TRUST_INVALID_BASIC_CONSTRAINTS)
2247     {
2248         pPolicyStatus->dwError = TRUST_E_BASIC_CONSTRAINTS;
2249         find_element_with_error(pChainContext,
2250          CERT_TRUST_INVALID_BASIC_CONSTRAINTS, &pPolicyStatus->lChainIndex,
2251          &pPolicyStatus->lElementIndex);
2252     }
2253     else
2254         pPolicyStatus->dwError = NO_ERROR;
2255     return TRUE;
2256 }
2257
2258 static inline PCERT_EXTENSION get_subject_alt_name_ext(PCCERT_CONTEXT cert)
2259 {
2260     PCERT_EXTENSION ext;
2261
2262     ext = CertFindExtension(szOID_SUBJECT_ALT_NAME2,
2263      cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
2264     if (!ext)
2265         ext = CertFindExtension(szOID_SUBJECT_ALT_NAME,
2266          cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
2267     return ext;
2268 }
2269
2270 static BOOL match_dns_to_subject_alt_name(PCERT_EXTENSION ext,
2271  LPCWSTR server_name)
2272 {
2273     BOOL matches = FALSE;
2274     CERT_ALT_NAME_INFO *subjectName;
2275     DWORD size;
2276
2277     TRACE_(chain)("%s\n", debugstr_w(server_name));
2278     /* FIXME: This can be spoofed by the embedded NULL vulnerability.  The
2279      * returned CERT_ALT_NAME_INFO doesn't have a way to indicate the
2280      * encoded length of a name, so a certificate issued to
2281      * winehq.org\0badsite.com will get treated as having been issued to
2282      * winehq.org.
2283      */
2284     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
2285      ext->Value.pbData, ext->Value.cbData,
2286      CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2287      &subjectName, &size))
2288     {
2289         DWORD i;
2290         BOOL found = FALSE;
2291
2292         for (i = 0; !found && i < subjectName->cAltEntry; i++)
2293         {
2294             if (subjectName->rgAltEntry[i].dwAltNameChoice ==
2295              CERT_ALT_NAME_DNS_NAME)
2296             {
2297                 TRACE_(chain)("dNSName: %s\n", debugstr_w(
2298                  subjectName->rgAltEntry[i].u.pwszDNSName));
2299                 found = TRUE;
2300                 if (!strcmpiW(server_name,
2301                  subjectName->rgAltEntry[i].u.pwszDNSName))
2302                     matches = TRUE;
2303             }
2304         }
2305         LocalFree(subjectName);
2306     }
2307     return matches;
2308 }
2309
2310 static BOOL find_matching_domain_component(CERT_NAME_INFO *name,
2311  LPCWSTR component)
2312 {
2313     BOOL matches = FALSE;
2314     DWORD i, j;
2315
2316     for (i = 0; !matches && i < name->cRDN; i++)
2317         for (j = 0; j < name->rgRDN[i].cRDNAttr; j++)
2318             if (!strcmp(szOID_DOMAIN_COMPONENT,
2319              name->rgRDN[i].rgRDNAttr[j].pszObjId))
2320             {
2321                 PCERT_RDN_ATTR attr;
2322
2323                 attr = &name->rgRDN[i].rgRDNAttr[j];
2324                 /* Compare with memicmpW rather than strcmpiW in order to avoid
2325                  * a match with a string with an embedded NULL.  The component
2326                  * must match one domain component attribute's entire string
2327                  * value with a case-insensitive match.
2328                  */
2329                 matches = !memicmpW(component, (LPWSTR)attr->Value.pbData,
2330                  attr->Value.cbData / sizeof(WCHAR));
2331             }
2332     return matches;
2333 }
2334
2335 static BOOL match_dns_to_subject_dn(PCCERT_CONTEXT cert, LPCWSTR server_name)
2336 {
2337     BOOL matches = FALSE;
2338     CERT_NAME_INFO *name;
2339     DWORD size;
2340
2341     TRACE_(chain)("%s\n", debugstr_w(server_name));
2342     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_UNICODE_NAME,
2343      cert->pCertInfo->Subject.pbData, cert->pCertInfo->Subject.cbData,
2344      CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2345      &name, &size))
2346     {
2347         /* If the subject distinguished name contains any name components,
2348          * make sure all of them are present.
2349          */
2350         if (CertFindRDNAttr(szOID_DOMAIN_COMPONENT, name))
2351         {
2352             LPCWSTR ptr = server_name;
2353
2354             matches = TRUE;
2355             do {
2356                 LPCWSTR dot = strchrW(ptr, '.'), end;
2357                 /* 254 is the maximum DNS label length, see RFC 1035 */
2358                 WCHAR component[255];
2359                 DWORD len;
2360
2361                 end = dot ? dot : ptr + strlenW(ptr);
2362                 len = end - ptr;
2363                 if (len >= sizeof(component) / sizeof(component[0]))
2364                 {
2365                     WARN_(chain)("domain component %s too long\n",
2366                      debugstr_wn(ptr, len));
2367                     matches = FALSE;
2368                 }
2369                 else
2370                 {
2371                     memcpy(component, ptr, len * sizeof(WCHAR));
2372                     component[len] = 0;
2373                     matches = find_matching_domain_component(name, component);
2374                 }
2375                 ptr = dot ? dot + 1 : end;
2376             } while (matches && ptr && *ptr);
2377         }
2378         else
2379         {
2380             PCERT_RDN_ATTR attr;
2381
2382             /* If the certificate isn't using a DN attribute in the name, make
2383              * make sure the common name matches.  Again, use memicmpW rather
2384              * than strcmpiW in order to avoid being fooled by an embedded NULL.
2385              */
2386             if ((attr = CertFindRDNAttr(szOID_COMMON_NAME, name)))
2387             {
2388                 TRACE_(chain)("CN = %s\n", debugstr_w(
2389                  (LPWSTR)attr->Value.pbData));
2390                 matches = !memicmpW(server_name, (LPWSTR)attr->Value.pbData,
2391                  attr->Value.cbData / sizeof(WCHAR));
2392             }
2393         }
2394         LocalFree(name);
2395     }
2396     return matches;
2397 }
2398
2399 static BOOL WINAPI verify_ssl_policy(LPCSTR szPolicyOID,
2400  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2401  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2402 {
2403     pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2404     if (pChainContext->TrustStatus.dwErrorStatus &
2405      CERT_TRUST_IS_NOT_SIGNATURE_VALID)
2406     {
2407         pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
2408         find_element_with_error(pChainContext,
2409          CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
2410          &pPolicyStatus->lElementIndex);
2411     }
2412     else if (pChainContext->TrustStatus.dwErrorStatus &
2413      CERT_TRUST_IS_UNTRUSTED_ROOT)
2414     {
2415         pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
2416         find_element_with_error(pChainContext,
2417          CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
2418          &pPolicyStatus->lElementIndex);
2419     }
2420     else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
2421     {
2422         pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
2423         find_element_with_error(pChainContext,
2424          CERT_TRUST_IS_CYCLIC, &pPolicyStatus->lChainIndex,
2425          &pPolicyStatus->lElementIndex);
2426         /* For a cyclic chain, which element is a cycle isn't meaningful */
2427         pPolicyStatus->lElementIndex = -1;
2428     }
2429     else if (pChainContext->TrustStatus.dwErrorStatus &
2430      CERT_TRUST_IS_NOT_TIME_VALID)
2431     {
2432         pPolicyStatus->dwError = CERT_E_EXPIRED;
2433         find_element_with_error(pChainContext,
2434          CERT_TRUST_IS_NOT_TIME_VALID, &pPolicyStatus->lChainIndex,
2435          &pPolicyStatus->lElementIndex);
2436     }
2437     else
2438         pPolicyStatus->dwError = NO_ERROR;
2439     /* We only need bother checking whether the name in the end certificate
2440      * matches if the chain is otherwise okay.
2441      */
2442     if (!pPolicyStatus->dwError && pPolicyPara &&
2443      pPolicyPara->cbSize >= sizeof(CERT_CHAIN_POLICY_PARA))
2444     {
2445         HTTPSPolicyCallbackData *sslPara = pPolicyPara->pvExtraPolicyPara;
2446
2447         if (sslPara && sslPara->u.cbSize >= sizeof(HTTPSPolicyCallbackData))
2448         {
2449             if (sslPara->dwAuthType == AUTHTYPE_SERVER &&
2450              sslPara->pwszServerName)
2451             {
2452                 PCCERT_CONTEXT cert;
2453                 PCERT_EXTENSION altNameExt;
2454                 BOOL matches;
2455
2456                 cert = pChainContext->rgpChain[0]->rgpElement[0]->pCertContext;
2457                 altNameExt = get_subject_alt_name_ext(cert);
2458                 /* If the alternate name extension exists, the name it contains
2459                  * is bound to the certificate, so make sure the name matches
2460                  * it.  Otherwise, look for the server name in the subject
2461                  * distinguished name.  RFC5280, section 4.2.1.6:
2462                  * "Whenever such identities are to be bound into a
2463                  *  certificate, the subject alternative name (or issuer
2464                  *  alternative name) extension MUST be used; however, a DNS
2465                  *  name MAY also be represented in the subject field using the
2466                  *  domainComponent attribute."
2467                  */
2468                 if (altNameExt)
2469                     matches = match_dns_to_subject_alt_name(altNameExt,
2470                      sslPara->pwszServerName);
2471                 else
2472                     matches = match_dns_to_subject_dn(cert,
2473                      sslPara->pwszServerName);
2474                 if (!matches)
2475                 {
2476                     pPolicyStatus->dwError = CERT_E_CN_NO_MATCH;
2477                     pPolicyStatus->lChainIndex = 0;
2478                     pPolicyStatus->lElementIndex = 0;
2479                 }
2480             }
2481         }
2482     }
2483     return TRUE;
2484 }
2485
2486 static BYTE msPubKey1[] = {
2487 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xdf,0x08,0xba,0xe3,0x3f,0x6e,
2488 0x64,0x9b,0xf5,0x89,0xaf,0x28,0x96,0x4a,0x07,0x8f,0x1b,0x2e,0x8b,0x3e,0x1d,
2489 0xfc,0xb8,0x80,0x69,0xa3,0xa1,0xce,0xdb,0xdf,0xb0,0x8e,0x6c,0x89,0x76,0x29,
2490 0x4f,0xca,0x60,0x35,0x39,0xad,0x72,0x32,0xe0,0x0b,0xae,0x29,0x3d,0x4c,0x16,
2491 0xd9,0x4b,0x3c,0x9d,0xda,0xc5,0xd3,0xd1,0x09,0xc9,0x2c,0x6f,0xa6,0xc2,0x60,
2492 0x53,0x45,0xdd,0x4b,0xd1,0x55,0xcd,0x03,0x1c,0xd2,0x59,0x56,0x24,0xf3,0xe5,
2493 0x78,0xd8,0x07,0xcc,0xd8,0xb3,0x1f,0x90,0x3f,0xc0,0x1a,0x71,0x50,0x1d,0x2d,
2494 0xa7,0x12,0x08,0x6d,0x7c,0xb0,0x86,0x6c,0xc7,0xba,0x85,0x32,0x07,0xe1,0x61,
2495 0x6f,0xaf,0x03,0xc5,0x6d,0xe5,0xd6,0xa1,0x8f,0x36,0xf6,0xc1,0x0b,0xd1,0x3e,
2496 0x69,0x97,0x48,0x72,0xc9,0x7f,0xa4,0xc8,0xc2,0x4a,0x4c,0x7e,0xa1,0xd1,0x94,
2497 0xa6,0xd7,0xdc,0xeb,0x05,0x46,0x2e,0xb8,0x18,0xb4,0x57,0x1d,0x86,0x49,0xdb,
2498 0x69,0x4a,0x2c,0x21,0xf5,0x5e,0x0f,0x54,0x2d,0x5a,0x43,0xa9,0x7a,0x7e,0x6a,
2499 0x8e,0x50,0x4d,0x25,0x57,0xa1,0xbf,0x1b,0x15,0x05,0x43,0x7b,0x2c,0x05,0x8d,
2500 0xbd,0x3d,0x03,0x8c,0x93,0x22,0x7d,0x63,0xea,0x0a,0x57,0x05,0x06,0x0a,0xdb,
2501 0x61,0x98,0x65,0x2d,0x47,0x49,0xa8,0xe7,0xe6,0x56,0x75,0x5c,0xb8,0x64,0x08,
2502 0x63,0xa9,0x30,0x40,0x66,0xb2,0xf9,0xb6,0xe3,0x34,0xe8,0x67,0x30,0xe1,0x43,
2503 0x0b,0x87,0xff,0xc9,0xbe,0x72,0x10,0x5e,0x23,0xf0,0x9b,0xa7,0x48,0x65,0xbf,
2504 0x09,0x88,0x7b,0xcd,0x72,0xbc,0x2e,0x79,0x9b,0x7b,0x02,0x03,0x01,0x00,0x01 };
2505 static BYTE msPubKey2[] = {
2506 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xa9,0x02,0xbd,0xc1,0x70,0xe6,
2507 0x3b,0xf2,0x4e,0x1b,0x28,0x9f,0x97,0x78,0x5e,0x30,0xea,0xa2,0xa9,0x8d,0x25,
2508 0x5f,0xf8,0xfe,0x95,0x4c,0xa3,0xb7,0xfe,0x9d,0xa2,0x20,0x3e,0x7c,0x51,0xa2,
2509 0x9b,0xa2,0x8f,0x60,0x32,0x6b,0xd1,0x42,0x64,0x79,0xee,0xac,0x76,0xc9,0x54,
2510 0xda,0xf2,0xeb,0x9c,0x86,0x1c,0x8f,0x9f,0x84,0x66,0xb3,0xc5,0x6b,0x7a,0x62,
2511 0x23,0xd6,0x1d,0x3c,0xde,0x0f,0x01,0x92,0xe8,0x96,0xc4,0xbf,0x2d,0x66,0x9a,
2512 0x9a,0x68,0x26,0x99,0xd0,0x3a,0x2c,0xbf,0x0c,0xb5,0x58,0x26,0xc1,0x46,0xe7,
2513 0x0a,0x3e,0x38,0x96,0x2c,0xa9,0x28,0x39,0xa8,0xec,0x49,0x83,0x42,0xe3,0x84,
2514 0x0f,0xbb,0x9a,0x6c,0x55,0x61,0xac,0x82,0x7c,0xa1,0x60,0x2d,0x77,0x4c,0xe9,
2515 0x99,0xb4,0x64,0x3b,0x9a,0x50,0x1c,0x31,0x08,0x24,0x14,0x9f,0xa9,0xe7,0x91,
2516 0x2b,0x18,0xe6,0x3d,0x98,0x63,0x14,0x60,0x58,0x05,0x65,0x9f,0x1d,0x37,0x52,
2517 0x87,0xf7,0xa7,0xef,0x94,0x02,0xc6,0x1b,0xd3,0xbf,0x55,0x45,0xb3,0x89,0x80,
2518 0xbf,0x3a,0xec,0x54,0x94,0x4e,0xae,0xfd,0xa7,0x7a,0x6d,0x74,0x4e,0xaf,0x18,
2519 0xcc,0x96,0x09,0x28,0x21,0x00,0x57,0x90,0x60,0x69,0x37,0xbb,0x4b,0x12,0x07,
2520 0x3c,0x56,0xff,0x5b,0xfb,0xa4,0x66,0x0a,0x08,0xa6,0xd2,0x81,0x56,0x57,0xef,
2521 0xb6,0x3b,0x5e,0x16,0x81,0x77,0x04,0xda,0xf6,0xbe,0xae,0x80,0x95,0xfe,0xb0,
2522 0xcd,0x7f,0xd6,0xa7,0x1a,0x72,0x5c,0x3c,0xca,0xbc,0xf0,0x08,0xa3,0x22,0x30,
2523 0xb3,0x06,0x85,0xc9,0xb3,0x20,0x77,0x13,0x85,0xdf,0x02,0x03,0x01,0x00,0x01 };
2524 static BYTE msPubKey3[] = {
2525 0x30,0x82,0x02,0x0a,0x02,0x82,0x02,0x01,0x00,0xf3,0x5d,0xfa,0x80,0x67,0xd4,
2526 0x5a,0xa7,0xa9,0x0c,0x2c,0x90,0x20,0xd0,0x35,0x08,0x3c,0x75,0x84,0xcd,0xb7,
2527 0x07,0x89,0x9c,0x89,0xda,0xde,0xce,0xc3,0x60,0xfa,0x91,0x68,0x5a,0x9e,0x94,
2528 0x71,0x29,0x18,0x76,0x7c,0xc2,0xe0,0xc8,0x25,0x76,0x94,0x0e,0x58,0xfa,0x04,
2529 0x34,0x36,0xe6,0xdf,0xaf,0xf7,0x80,0xba,0xe9,0x58,0x0b,0x2b,0x93,0xe5,0x9d,
2530 0x05,0xe3,0x77,0x22,0x91,0xf7,0x34,0x64,0x3c,0x22,0x91,0x1d,0x5e,0xe1,0x09,
2531 0x90,0xbc,0x14,0xfe,0xfc,0x75,0x58,0x19,0xe1,0x79,0xb7,0x07,0x92,0xa3,0xae,
2532 0x88,0x59,0x08,0xd8,0x9f,0x07,0xca,0x03,0x58,0xfc,0x68,0x29,0x6d,0x32,0xd7,
2533 0xd2,0xa8,0xcb,0x4b,0xfc,0xe1,0x0b,0x48,0x32,0x4f,0xe6,0xeb,0xb8,0xad,0x4f,
2534 0xe4,0x5c,0x6f,0x13,0x94,0x99,0xdb,0x95,0xd5,0x75,0xdb,0xa8,0x1a,0xb7,0x94,
2535 0x91,0xb4,0x77,0x5b,0xf5,0x48,0x0c,0x8f,0x6a,0x79,0x7d,0x14,0x70,0x04,0x7d,
2536 0x6d,0xaf,0x90,0xf5,0xda,0x70,0xd8,0x47,0xb7,0xbf,0x9b,0x2f,0x6c,0xe7,0x05,
2537 0xb7,0xe1,0x11,0x60,0xac,0x79,0x91,0x14,0x7c,0xc5,0xd6,0xa6,0xe4,0xe1,0x7e,
2538 0xd5,0xc3,0x7e,0xe5,0x92,0xd2,0x3c,0x00,0xb5,0x36,0x82,0xde,0x79,0xe1,0x6d,
2539 0xf3,0xb5,0x6e,0xf8,0x9f,0x33,0xc9,0xcb,0x52,0x7d,0x73,0x98,0x36,0xdb,0x8b,
2540 0xa1,0x6b,0xa2,0x95,0x97,0x9b,0xa3,0xde,0xc2,0x4d,0x26,0xff,0x06,0x96,0x67,
2541 0x25,0x06,0xc8,0xe7,0xac,0xe4,0xee,0x12,0x33,0x95,0x31,0x99,0xc8,0x35,0x08,
2542 0x4e,0x34,0xca,0x79,0x53,0xd5,0xb5,0xbe,0x63,0x32,0x59,0x40,0x36,0xc0,0xa5,
2543 0x4e,0x04,0x4d,0x3d,0xdb,0x5b,0x07,0x33,0xe4,0x58,0xbf,0xef,0x3f,0x53,0x64,
2544 0xd8,0x42,0x59,0x35,0x57,0xfd,0x0f,0x45,0x7c,0x24,0x04,0x4d,0x9e,0xd6,0x38,
2545 0x74,0x11,0x97,0x22,0x90,0xce,0x68,0x44,0x74,0x92,0x6f,0xd5,0x4b,0x6f,0xb0,
2546 0x86,0xe3,0xc7,0x36,0x42,0xa0,0xd0,0xfc,0xc1,0xc0,0x5a,0xf9,0xa3,0x61,0xb9,
2547 0x30,0x47,0x71,0x96,0x0a,0x16,0xb0,0x91,0xc0,0x42,0x95,0xef,0x10,0x7f,0x28,
2548 0x6a,0xe3,0x2a,0x1f,0xb1,0xe4,0xcd,0x03,0x3f,0x77,0x71,0x04,0xc7,0x20,0xfc,
2549 0x49,0x0f,0x1d,0x45,0x88,0xa4,0xd7,0xcb,0x7e,0x88,0xad,0x8e,0x2d,0xec,0x45,
2550 0xdb,0xc4,0x51,0x04,0xc9,0x2a,0xfc,0xec,0x86,0x9e,0x9a,0x11,0x97,0x5b,0xde,
2551 0xce,0x53,0x88,0xe6,0xe2,0xb7,0xfd,0xac,0x95,0xc2,0x28,0x40,0xdb,0xef,0x04,
2552 0x90,0xdf,0x81,0x33,0x39,0xd9,0xb2,0x45,0xa5,0x23,0x87,0x06,0xa5,0x55,0x89,
2553 0x31,0xbb,0x06,0x2d,0x60,0x0e,0x41,0x18,0x7d,0x1f,0x2e,0xb5,0x97,0xcb,0x11,
2554 0xeb,0x15,0xd5,0x24,0xa5,0x94,0xef,0x15,0x14,0x89,0xfd,0x4b,0x73,0xfa,0x32,
2555 0x5b,0xfc,0xd1,0x33,0x00,0xf9,0x59,0x62,0x70,0x07,0x32,0xea,0x2e,0xab,0x40,
2556 0x2d,0x7b,0xca,0xdd,0x21,0x67,0x1b,0x30,0x99,0x8f,0x16,0xaa,0x23,0xa8,0x41,
2557 0xd1,0xb0,0x6e,0x11,0x9b,0x36,0xc4,0xde,0x40,0x74,0x9c,0xe1,0x58,0x65,0xc1,
2558 0x60,0x1e,0x7a,0x5b,0x38,0xc8,0x8f,0xbb,0x04,0x26,0x7c,0xd4,0x16,0x40,0xe5,
2559 0xb6,0x6b,0x6c,0xaa,0x86,0xfd,0x00,0xbf,0xce,0xc1,0x35,0x02,0x03,0x01,0x00,
2560 0x01 };
2561
2562 static BOOL WINAPI verify_ms_root_policy(LPCSTR szPolicyOID,
2563  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2564  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2565 {
2566     BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
2567      pPolicyStatus);
2568
2569     if (ret && !pPolicyStatus->dwError)
2570     {
2571         CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
2572         BOOL isMSRoot = FALSE;
2573         DWORD i;
2574         CRYPT_DATA_BLOB keyBlobs[] = {
2575          { sizeof(msPubKey1), msPubKey1 },
2576          { sizeof(msPubKey2), msPubKey2 },
2577          { sizeof(msPubKey3), msPubKey3 },
2578         };
2579         PCERT_SIMPLE_CHAIN rootChain =
2580          pChainContext->rgpChain[pChainContext->cChain -1 ];
2581         PCCERT_CONTEXT root =
2582          rootChain->rgpElement[rootChain->cElement - 1]->pCertContext;
2583
2584         for (i = 0; !isMSRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
2585          i++)
2586         {
2587             msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
2588             msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
2589             if (CertComparePublicKeyInfo(
2590              X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
2591              &root->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
2592                 isMSRoot = TRUE;
2593         }
2594         if (isMSRoot)
2595             pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = 0;
2596     }
2597     return ret;
2598 }
2599
2600 typedef BOOL (WINAPI *CertVerifyCertificateChainPolicyFunc)(LPCSTR szPolicyOID,
2601  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2602  PCERT_CHAIN_POLICY_STATUS pPolicyStatus);
2603
2604 BOOL WINAPI CertVerifyCertificateChainPolicy(LPCSTR szPolicyOID,
2605  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2606  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2607 {
2608     static HCRYPTOIDFUNCSET set = NULL;
2609     BOOL ret = FALSE;
2610     CertVerifyCertificateChainPolicyFunc verifyPolicy = NULL;
2611     HCRYPTOIDFUNCADDR hFunc = NULL;
2612
2613     TRACE("(%s, %p, %p, %p)\n", debugstr_a(szPolicyOID), pChainContext,
2614      pPolicyPara, pPolicyStatus);
2615
2616     if (!HIWORD(szPolicyOID))
2617     {
2618         switch (LOWORD(szPolicyOID))
2619         {
2620         case LOWORD(CERT_CHAIN_POLICY_BASE):
2621             verifyPolicy = verify_base_policy;
2622             break;
2623         case LOWORD(CERT_CHAIN_POLICY_AUTHENTICODE):
2624             verifyPolicy = verify_authenticode_policy;
2625             break;
2626         case LOWORD(CERT_CHAIN_POLICY_SSL):
2627             verifyPolicy = verify_ssl_policy;
2628             break;
2629         case LOWORD(CERT_CHAIN_POLICY_BASIC_CONSTRAINTS):
2630             verifyPolicy = verify_basic_constraints_policy;
2631             break;
2632         case LOWORD(CERT_CHAIN_POLICY_MICROSOFT_ROOT):
2633             verifyPolicy = verify_ms_root_policy;
2634             break;
2635         default:
2636             FIXME("unimplemented for %d\n", LOWORD(szPolicyOID));
2637         }
2638     }
2639     if (!verifyPolicy)
2640     {
2641         if (!set)
2642             set = CryptInitOIDFunctionSet(
2643              CRYPT_OID_VERIFY_CERTIFICATE_CHAIN_POLICY_FUNC, 0);
2644         CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING, szPolicyOID, 0,
2645          (void **)&verifyPolicy, &hFunc);
2646     }
2647     if (verifyPolicy)
2648         ret = verifyPolicy(szPolicyOID, pChainContext, pPolicyPara,
2649          pPolicyStatus);
2650     if (hFunc)
2651         CryptFreeOIDFunctionAddress(hFunc, 0);
2652     TRACE("returning %d (%08x)\n", ret, pPolicyStatus->dwError);
2653     return ret;
2654 }