winmm: Fix a failing mixer test on 98 and ME.
[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
32 #define DEFAULT_CYCLE_MODULUS 7
33
34 static HCERTCHAINENGINE CRYPT_defaultChainEngine;
35
36 /* This represents a subset of a certificate chain engine:  it doesn't include
37  * the "hOther" store described by MSDN, because I'm not sure how that's used.
38  * It also doesn't include the "hTrust" store, because I don't yet implement
39  * CTLs or complex certificate chains.
40  */
41 typedef struct _CertificateChainEngine
42 {
43     LONG       ref;
44     HCERTSTORE hRoot;
45     HCERTSTORE hWorld;
46     DWORD      dwFlags;
47     DWORD      dwUrlRetrievalTimeout;
48     DWORD      MaximumCachedCertificates;
49     DWORD      CycleDetectionModulus;
50 } CertificateChainEngine, *PCertificateChainEngine;
51
52 static inline void CRYPT_AddStoresToCollection(HCERTSTORE collection,
53  DWORD cStores, HCERTSTORE *stores)
54 {
55     DWORD i;
56
57     for (i = 0; i < cStores; i++)
58         CertAddStoreToCollection(collection, stores[i], 0, 0);
59 }
60
61 static inline void CRYPT_CloseStores(DWORD cStores, HCERTSTORE *stores)
62 {
63     DWORD i;
64
65     for (i = 0; i < cStores; i++)
66         CertCloseStore(stores[i], 0);
67 }
68
69 static const WCHAR rootW[] = { 'R','o','o','t',0 };
70
71 static BOOL CRYPT_CheckRestrictedRoot(HCERTSTORE store)
72 {
73     BOOL ret = TRUE;
74
75     if (store)
76     {
77         HCERTSTORE rootStore = CertOpenSystemStoreW(0, rootW);
78         PCCERT_CONTEXT cert = NULL, check;
79         BYTE hash[20];
80         DWORD size;
81
82         do {
83             cert = CertEnumCertificatesInStore(store, cert);
84             if (cert)
85             {
86                 size = sizeof(hash);
87
88                 ret = CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID,
89                  hash, &size);
90                 if (ret)
91                 {
92                     CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
93
94                     check = CertFindCertificateInStore(rootStore,
95                      cert->dwCertEncodingType, 0, CERT_FIND_SHA1_HASH, &blob,
96                      NULL);
97                     if (!check)
98                         ret = FALSE;
99                     else
100                         CertFreeCertificateContext(check);
101                 }
102             }
103         } while (ret && cert);
104         if (cert)
105             CertFreeCertificateContext(cert);
106         CertCloseStore(rootStore, 0);
107     }
108     return ret;
109 }
110
111 HCERTCHAINENGINE CRYPT_CreateChainEngine(HCERTSTORE root,
112  PCERT_CHAIN_ENGINE_CONFIG pConfig)
113 {
114     static const WCHAR caW[] = { 'C','A',0 };
115     static const WCHAR myW[] = { 'M','y',0 };
116     static const WCHAR trustW[] = { 'T','r','u','s','t',0 };
117     PCertificateChainEngine engine =
118      CryptMemAlloc(sizeof(CertificateChainEngine));
119
120     if (engine)
121     {
122         HCERTSTORE worldStores[4];
123
124         engine->ref = 1;
125         engine->hRoot = root;
126         engine->hWorld = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
127          CERT_STORE_CREATE_NEW_FLAG, NULL);
128         worldStores[0] = CertDuplicateStore(engine->hRoot);
129         worldStores[1] = CertOpenSystemStoreW(0, caW);
130         worldStores[2] = CertOpenSystemStoreW(0, myW);
131         worldStores[3] = CertOpenSystemStoreW(0, trustW);
132         CRYPT_AddStoresToCollection(engine->hWorld,
133          sizeof(worldStores) / sizeof(worldStores[0]), worldStores);
134         CRYPT_AddStoresToCollection(engine->hWorld,
135          pConfig->cAdditionalStore, pConfig->rghAdditionalStore);
136         CRYPT_CloseStores(sizeof(worldStores) / sizeof(worldStores[0]),
137          worldStores);
138         engine->dwFlags = pConfig->dwFlags;
139         engine->dwUrlRetrievalTimeout = pConfig->dwUrlRetrievalTimeout;
140         engine->MaximumCachedCertificates =
141          pConfig->MaximumCachedCertificates;
142         if (pConfig->CycleDetectionModulus)
143             engine->CycleDetectionModulus = pConfig->CycleDetectionModulus;
144         else
145             engine->CycleDetectionModulus = DEFAULT_CYCLE_MODULUS;
146     }
147     return (HCERTCHAINENGINE)engine;
148 }
149
150 BOOL WINAPI CertCreateCertificateChainEngine(PCERT_CHAIN_ENGINE_CONFIG pConfig,
151  HCERTCHAINENGINE *phChainEngine)
152 {
153     BOOL ret;
154
155     TRACE("(%p, %p)\n", pConfig, phChainEngine);
156
157     if (pConfig->cbSize != sizeof(*pConfig))
158     {
159         SetLastError(E_INVALIDARG);
160         return FALSE;
161     }
162     *phChainEngine = NULL;
163     ret = CRYPT_CheckRestrictedRoot(pConfig->hRestrictedRoot);
164     if (ret)
165     {
166         HCERTSTORE root;
167         HCERTCHAINENGINE engine;
168
169         if (pConfig->hRestrictedRoot)
170             root = CertDuplicateStore(pConfig->hRestrictedRoot);
171         else
172             root = CertOpenSystemStoreW(0, rootW);
173         engine = CRYPT_CreateChainEngine(root, pConfig);
174         if (engine)
175         {
176             *phChainEngine = engine;
177             ret = TRUE;
178         }
179         else
180             ret = FALSE;
181     }
182     return ret;
183 }
184
185 VOID WINAPI CertFreeCertificateChainEngine(HCERTCHAINENGINE hChainEngine)
186 {
187     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
188
189     TRACE("(%p)\n", hChainEngine);
190
191     if (engine && InterlockedDecrement(&engine->ref) == 0)
192     {
193         CertCloseStore(engine->hWorld, 0);
194         CertCloseStore(engine->hRoot, 0);
195         CryptMemFree(engine);
196     }
197 }
198
199 static HCERTCHAINENGINE CRYPT_GetDefaultChainEngine(void)
200 {
201     if (!CRYPT_defaultChainEngine)
202     {
203         CERT_CHAIN_ENGINE_CONFIG config = { 0 };
204         HCERTCHAINENGINE engine;
205
206         config.cbSize = sizeof(config);
207         CertCreateCertificateChainEngine(&config, &engine);
208         InterlockedCompareExchangePointer(&CRYPT_defaultChainEngine, engine,
209          NULL);
210         if (CRYPT_defaultChainEngine != engine)
211             CertFreeCertificateChainEngine(engine);
212     }
213     return CRYPT_defaultChainEngine;
214 }
215
216 void default_chain_engine_free(void)
217 {
218     CertFreeCertificateChainEngine(CRYPT_defaultChainEngine);
219 }
220
221 typedef struct _CertificateChain
222 {
223     CERT_CHAIN_CONTEXT context;
224     HCERTSTORE world;
225     LONG ref;
226 } CertificateChain, *PCertificateChain;
227
228 static inline BOOL CRYPT_IsCertificateSelfSigned(PCCERT_CONTEXT cert)
229 {
230     return CertCompareCertificateName(cert->dwCertEncodingType,
231      &cert->pCertInfo->Subject, &cert->pCertInfo->Issuer);
232 }
233
234 static void CRYPT_FreeChainElement(PCERT_CHAIN_ELEMENT element)
235 {
236     CertFreeCertificateContext(element->pCertContext);
237     CryptMemFree(element);
238 }
239
240 static void CRYPT_CheckSimpleChainForCycles(PCERT_SIMPLE_CHAIN chain)
241 {
242     DWORD i, j, cyclicCertIndex = 0;
243
244     /* O(n^2) - I don't think there's a faster way */
245     for (i = 0; !cyclicCertIndex && i < chain->cElement; i++)
246         for (j = i + 1; !cyclicCertIndex && j < chain->cElement; j++)
247             if (CertCompareCertificate(X509_ASN_ENCODING,
248              chain->rgpElement[i]->pCertContext->pCertInfo,
249              chain->rgpElement[j]->pCertContext->pCertInfo))
250                 cyclicCertIndex = j;
251     if (cyclicCertIndex)
252     {
253         chain->rgpElement[cyclicCertIndex]->TrustStatus.dwErrorStatus
254          |= CERT_TRUST_IS_CYCLIC | CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
255         /* Release remaining certs */
256         for (i = cyclicCertIndex + 1; i < chain->cElement; i++)
257             CRYPT_FreeChainElement(chain->rgpElement[i]);
258         /* Truncate chain */
259         chain->cElement = cyclicCertIndex + 1;
260     }
261 }
262
263 /* Checks whether the chain is cyclic by examining the last element's status */
264 static inline BOOL CRYPT_IsSimpleChainCyclic(PCERT_SIMPLE_CHAIN chain)
265 {
266     if (chain->cElement)
267         return chain->rgpElement[chain->cElement - 1]->TrustStatus.dwErrorStatus
268          & CERT_TRUST_IS_CYCLIC;
269     else
270         return FALSE;
271 }
272
273 static inline void CRYPT_CombineTrustStatus(CERT_TRUST_STATUS *chainStatus,
274  CERT_TRUST_STATUS *elementStatus)
275 {
276     /* Any error that applies to an element also applies to a chain.. */
277     chainStatus->dwErrorStatus |= elementStatus->dwErrorStatus;
278     /* but the bottom nibble of an element's info status doesn't apply to the
279      * chain.
280      */
281     chainStatus->dwInfoStatus |= (elementStatus->dwInfoStatus & 0xfffffff0);
282 }
283
284 static BOOL CRYPT_AddCertToSimpleChain(PCertificateChainEngine engine,
285  PCERT_SIMPLE_CHAIN chain, PCCERT_CONTEXT cert, DWORD subjectInfoStatus)
286 {
287     BOOL ret = FALSE;
288     PCERT_CHAIN_ELEMENT element = CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
289
290     if (element)
291     {
292         if (!chain->cElement)
293             chain->rgpElement = CryptMemAlloc(sizeof(PCERT_CHAIN_ELEMENT));
294         else
295             chain->rgpElement = CryptMemRealloc(chain->rgpElement,
296              (chain->cElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
297         if (chain->rgpElement)
298         {
299             chain->rgpElement[chain->cElement++] = element;
300             memset(element, 0, sizeof(CERT_CHAIN_ELEMENT));
301             element->cbSize = sizeof(CERT_CHAIN_ELEMENT);
302             element->pCertContext = CertDuplicateCertificateContext(cert);
303             if (chain->cElement > 1)
304                 chain->rgpElement[chain->cElement - 2]->TrustStatus.dwInfoStatus
305                  = subjectInfoStatus;
306             /* FIXME: initialize the rest of element */
307             if (chain->cElement % engine->CycleDetectionModulus)
308                 CRYPT_CheckSimpleChainForCycles(chain);
309             CRYPT_CombineTrustStatus(&chain->TrustStatus,
310              &element->TrustStatus);
311             ret = TRUE;
312         }
313         else
314             CryptMemFree(element);
315     }
316     return ret;
317 }
318
319 static void CRYPT_FreeSimpleChain(PCERT_SIMPLE_CHAIN chain)
320 {
321     DWORD i;
322
323     for (i = 0; i < chain->cElement; i++)
324         CRYPT_FreeChainElement(chain->rgpElement[i]);
325     CryptMemFree(chain->rgpElement);
326     CryptMemFree(chain);
327 }
328
329 static void CRYPT_CheckTrustedStatus(HCERTSTORE hRoot,
330  PCERT_CHAIN_ELEMENT rootElement)
331 {
332     BYTE hash[20];
333     DWORD size = sizeof(hash);
334     CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
335     PCCERT_CONTEXT trustedRoot;
336
337     CertGetCertificateContextProperty(rootElement->pCertContext,
338      CERT_HASH_PROP_ID, hash, &size);
339     trustedRoot = CertFindCertificateInStore(hRoot,
340      rootElement->pCertContext->dwCertEncodingType, 0, CERT_FIND_SHA1_HASH,
341      &blob, NULL);
342     if (!trustedRoot)
343         rootElement->TrustStatus.dwErrorStatus |=
344          CERT_TRUST_IS_UNTRUSTED_ROOT;
345     else
346         CertFreeCertificateContext(trustedRoot);
347 }
348
349 static void CRYPT_CheckRootCert(HCERTCHAINENGINE hRoot,
350  PCERT_CHAIN_ELEMENT rootElement)
351 {
352     PCCERT_CONTEXT root = rootElement->pCertContext;
353
354     if (!CryptVerifyCertificateSignatureEx(0, root->dwCertEncodingType,
355      CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, (void *)root,
356      CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, (void *)root, 0, NULL))
357     {
358         TRACE("Last certificate's signature is invalid\n");
359         rootElement->TrustStatus.dwErrorStatus |=
360          CERT_TRUST_IS_NOT_SIGNATURE_VALID;
361     }
362     CRYPT_CheckTrustedStatus(hRoot, rootElement);
363 }
364
365 /* Decodes a cert's basic constraints extension (either szOID_BASIC_CONSTRAINTS
366  * or szOID_BASIC_CONSTRAINTS2, whichever is present) into a
367  * CERT_BASIC_CONSTRAINTS2_INFO.  If it neither extension is present, sets
368  * constraints->fCA to defaultIfNotSpecified.
369  * Returns FALSE if the extension is present but couldn't be decoded.
370  */
371 static BOOL CRYPT_DecodeBasicConstraints(PCCERT_CONTEXT cert,
372  CERT_BASIC_CONSTRAINTS2_INFO *constraints, BOOL defaultIfNotSpecified)
373 {
374     BOOL ret = TRUE;
375     PCERT_EXTENSION ext = CertFindExtension(szOID_BASIC_CONSTRAINTS,
376      cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
377
378     constraints->fPathLenConstraint = FALSE;
379     if (ext)
380     {
381         CERT_BASIC_CONSTRAINTS_INFO *info;
382         DWORD size = 0;
383
384         ret = CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
385          ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
386          NULL, (LPBYTE)&info, &size);
387         if (ret)
388         {
389             if (info->SubjectType.cbData == 1)
390                 constraints->fCA =
391                  info->SubjectType.pbData[0] & CERT_CA_SUBJECT_FLAG;
392             LocalFree(info);
393         }
394     }
395     else
396     {
397         ext = CertFindExtension(szOID_BASIC_CONSTRAINTS2,
398          cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
399         if (ext)
400         {
401             DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
402
403             ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
404              szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
405              0, NULL, constraints, &size);
406         }
407         else
408             constraints->fCA = defaultIfNotSpecified;
409     }
410     return ret;
411 }
412
413 /* Checks element's basic constraints to see if it can act as a CA, with
414  * remainingCAs CAs left in this chain.  Updates chainConstraints with the
415  * element's constraints, if:
416  * 1. chainConstraints doesn't have a path length constraint, or
417  * 2. element's path length constraint is smaller than chainConstraints's
418  * Sets *pathLengthConstraintViolated to TRUE if a path length violation
419  * occurs.
420  * Returns TRUE if the element can be a CA, and the length of the remaining
421  * chain is valid.
422  */
423 static BOOL CRYPT_CheckBasicConstraintsForCA(PCCERT_CONTEXT cert,
424  CERT_BASIC_CONSTRAINTS2_INFO *chainConstraints, DWORD remainingCAs,
425  BOOL *pathLengthConstraintViolated)
426 {
427     BOOL validBasicConstraints;
428     CERT_BASIC_CONSTRAINTS2_INFO constraints;
429
430     if ((validBasicConstraints = CRYPT_DecodeBasicConstraints(cert,
431      &constraints, TRUE)))
432     {
433         if (!constraints.fCA)
434         {
435             TRACE("chain element %d can't be a CA\n", remainingCAs + 1);
436             validBasicConstraints = FALSE;
437         }
438         else if (constraints.fPathLenConstraint)
439         {
440             /* If the element has path length constraints, they apply to the
441              * entire remaining chain.
442              */
443             if (!chainConstraints->fPathLenConstraint ||
444              constraints.dwPathLenConstraint <
445              chainConstraints->dwPathLenConstraint)
446             {
447                 TRACE("setting path length constraint to %d\n",
448                  chainConstraints->dwPathLenConstraint);
449                 chainConstraints->fPathLenConstraint = TRUE;
450                 chainConstraints->dwPathLenConstraint =
451                  constraints.dwPathLenConstraint;
452             }
453         }
454     }
455     if (chainConstraints->fPathLenConstraint &&
456      remainingCAs > chainConstraints->dwPathLenConstraint)
457     {
458         TRACE("remaining CAs %d exceed max path length %d\n", remainingCAs,
459          chainConstraints->dwPathLenConstraint);
460         validBasicConstraints = FALSE;
461         *pathLengthConstraintViolated = TRUE;
462     }
463     return validBasicConstraints;
464 }
465
466 static BOOL url_matches(LPCWSTR constraint, LPCWSTR name,
467  DWORD *trustErrorStatus)
468 {
469     BOOL match = FALSE;
470
471     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
472
473     if (!constraint)
474         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
475     else if (!name)
476         ; /* no match */
477     else if (constraint[0] == '.')
478     {
479         if (lstrlenW(name) > lstrlenW(constraint))
480             match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
481              constraint);
482     }
483     else
484         match = !lstrcmpiW(constraint, name);
485     return match;
486 }
487
488 static BOOL rfc822_name_matches(LPCWSTR constraint, LPCWSTR name,
489  DWORD *trustErrorStatus)
490 {
491     BOOL match = FALSE;
492     LPCWSTR at;
493
494     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
495
496     if (!constraint)
497         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
498     else if (!name)
499         ; /* no match */
500     else if ((at = strchrW(constraint, '@')))
501         match = !lstrcmpiW(constraint, name);
502     else
503     {
504         if ((at = strchrW(name, '@')))
505             match = url_matches(constraint, at + 1, trustErrorStatus);
506         else
507             match = !lstrcmpiW(constraint, name);
508     }
509     return match;
510 }
511
512 static BOOL dns_name_matches(LPCWSTR constraint, LPCWSTR name,
513  DWORD *trustErrorStatus)
514 {
515     BOOL match = FALSE;
516
517     TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
518
519     if (!constraint)
520         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
521     else if (!name)
522         ; /* no match */
523     else if (lstrlenW(name) >= lstrlenW(constraint))
524         match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
525          constraint);
526     /* else:  name is too short, no match */
527
528     return match;
529 }
530
531 static BOOL ip_address_matches(const CRYPT_DATA_BLOB *constraint,
532  const CRYPT_DATA_BLOB *name, DWORD *trustErrorStatus)
533 {
534     BOOL match = FALSE;
535
536     TRACE("(%d, %p), (%d, %p)\n", constraint->cbData, constraint->pbData,
537      name->cbData, name->pbData);
538
539     if (constraint->cbData != sizeof(DWORD) * 2)
540         *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
541     else if (name->cbData == sizeof(DWORD))
542     {
543         DWORD subnet, mask, addr;
544
545         memcpy(&subnet, constraint->pbData, sizeof(subnet));
546         memcpy(&mask, constraint->pbData + sizeof(subnet), sizeof(mask));
547         memcpy(&addr, name->pbData, sizeof(addr));
548         /* These are really in big-endian order, but for equality matching we
549          * don't need to swap to host order
550          */
551         match = (subnet & mask) == (addr & mask);
552     }
553     /* else: name is wrong size, no match */
554
555     return match;
556 }
557
558 static void CRYPT_FindMatchingNameEntry(const CERT_ALT_NAME_ENTRY *constraint,
559  const CERT_ALT_NAME_INFO *subjectName, DWORD *trustErrorStatus,
560  DWORD errorIfFound, DWORD errorIfNotFound)
561 {
562     DWORD i;
563     BOOL defined = FALSE, match = FALSE;
564
565     for (i = 0; i < subjectName->cAltEntry; i++)
566     {
567         if (subjectName->rgAltEntry[i].dwAltNameChoice ==
568          constraint->dwAltNameChoice)
569         {
570             defined = TRUE;
571             switch (constraint->dwAltNameChoice)
572             {
573             case CERT_ALT_NAME_RFC822_NAME:
574                 match = rfc822_name_matches(constraint->u.pwszURL,
575                  subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
576                 break;
577             case CERT_ALT_NAME_DNS_NAME:
578                 match = dns_name_matches(constraint->u.pwszURL,
579                  subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
580                 break;
581             case CERT_ALT_NAME_URL:
582                 match = url_matches(constraint->u.pwszURL,
583                  subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
584                 break;
585             case CERT_ALT_NAME_IP_ADDRESS:
586                 match = ip_address_matches(&constraint->u.IPAddress,
587                  &subjectName->rgAltEntry[i].u.IPAddress, trustErrorStatus);
588                 break;
589             case CERT_ALT_NAME_DIRECTORY_NAME:
590             default:
591                 ERR("name choice %d unsupported in this context\n",
592                  constraint->dwAltNameChoice);
593                 *trustErrorStatus |=
594                  CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
595             }
596         }
597     }
598     /* Microsoft's implementation of name constraint checking appears at odds
599      * with RFC 3280:
600      * According to MSDN, CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT is set
601      * when a name constraint is present, but that name form is not defined in
602      * the end certificate.  According to RFC 3280, "if no name of the type is
603      * in the certificate, the name is acceptable."
604      * I follow Microsoft here.
605      */
606     if (!defined)
607         *trustErrorStatus |= CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT;
608     *trustErrorStatus |= match ? errorIfFound : errorIfNotFound;
609 }
610
611 static void CRYPT_CheckNameConstraints(
612  const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, const CERT_INFO *cert,
613  DWORD *trustErrorStatus)
614 {
615     /* If there aren't any existing constraints, don't bother checking */
616     if (nameConstraints->cPermittedSubtree || nameConstraints->cExcludedSubtree)
617     {
618         CERT_EXTENSION *ext;
619
620         if ((ext = CertFindExtension(szOID_SUBJECT_ALT_NAME, cert->cExtension,
621          cert->rgExtension)))
622         {
623             CERT_ALT_NAME_INFO *subjectName;
624             DWORD size;
625
626             if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
627              ext->Value.pbData, ext->Value.cbData,
628              CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
629              &subjectName, &size))
630             {
631                 DWORD i;
632
633                 for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
634                     CRYPT_FindMatchingNameEntry(
635                      &nameConstraints->rgExcludedSubtree[i].Base, subjectName,
636                      trustErrorStatus,
637                      CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT, 0);
638                 for (i = 0; i < nameConstraints->cPermittedSubtree; i++)
639                     CRYPT_FindMatchingNameEntry(
640                      &nameConstraints->rgPermittedSubtree[i].Base, subjectName,
641                      trustErrorStatus,
642                      0, CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT);
643                 LocalFree(subjectName);
644             }
645         }
646         else
647         {
648             /* See above comment on CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT.
649              * I match Microsoft's implementation here as well.
650              */
651             *trustErrorStatus |= CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT;
652             if (nameConstraints->cPermittedSubtree)
653                 *trustErrorStatus |=
654                  CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
655             if (nameConstraints->cExcludedSubtree)
656                 *trustErrorStatus |=
657                  CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
658         }
659     }
660 }
661
662 /* Gets cert's name constraints, if any.  Free with LocalFree. */
663 static CERT_NAME_CONSTRAINTS_INFO *CRYPT_GetNameConstraints(CERT_INFO *cert)
664 {
665     CERT_NAME_CONSTRAINTS_INFO *info = NULL;
666
667     CERT_EXTENSION *ext;
668
669     if ((ext = CertFindExtension(szOID_NAME_CONSTRAINTS, cert->cExtension,
670      cert->rgExtension)))
671     {
672         DWORD size;
673
674         CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
675          ext->Value.pbData, ext->Value.cbData,
676          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &info,
677          &size);
678     }
679     return info;
680 }
681
682 static void CRYPT_CheckChainNameConstraints(PCERT_SIMPLE_CHAIN chain)
683 {
684     int i, j;
685
686     /* Microsoft's implementation appears to violate RFC 3280:  according to
687      * MSDN, the various CERT_TRUST_*_NAME_CONSTRAINT errors are set if a CA's
688      * name constraint is violated in the end cert.  According to RFC 3280,
689      * the constraints should be checked against every subsequent certificate
690      * in the chain, not just the end cert.
691      * Microsoft's implementation also sets the name constraint errors on the
692      * certs whose constraints were violated, not on the certs that violated
693      * them.
694      * In order to be error-compatible with Microsoft's implementation, while
695      * still adhering to RFC 3280, I use a O(n ^ 2) algorithm to check name
696      * constraints.
697      */
698     for (i = chain->cElement - 1; i > 0; i--)
699     {
700         CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
701
702         if ((nameConstraints = CRYPT_GetNameConstraints(
703          chain->rgpElement[i]->pCertContext->pCertInfo)))
704         {
705             for (j = i - 1; j >= 0; j--)
706             {
707                 DWORD errorStatus = 0;
708
709                 /* According to RFC 3280, self-signed certs don't have name
710                  * constraints checked unless they're the end cert.
711                  */
712                 if (j == 0 || !CRYPT_IsCertificateSelfSigned(
713                  chain->rgpElement[j]->pCertContext))
714                 {
715                     CRYPT_CheckNameConstraints(nameConstraints,
716                      chain->rgpElement[i]->pCertContext->pCertInfo,
717                      &errorStatus);
718                     chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
719                      errorStatus;
720                 }
721             }
722             LocalFree(nameConstraints);
723         }
724     }
725 }
726
727 static void CRYPT_CheckSimpleChain(PCertificateChainEngine engine,
728  PCERT_SIMPLE_CHAIN chain, LPFILETIME time)
729 {
730     PCERT_CHAIN_ELEMENT rootElement = chain->rgpElement[chain->cElement - 1];
731     int i;
732     BOOL pathLengthConstraintViolated = FALSE;
733     CERT_BASIC_CONSTRAINTS2_INFO constraints = { TRUE, FALSE, 0 };
734
735     for (i = chain->cElement - 1; i >= 0; i--)
736     {
737         if (CertVerifyTimeValidity(time,
738          chain->rgpElement[i]->pCertContext->pCertInfo) != 0)
739             chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
740              CERT_TRUST_IS_NOT_TIME_VALID;
741         if (i != 0)
742         {
743             /* Check the signature of the cert this issued */
744             if (!CryptVerifyCertificateSignatureEx(0, X509_ASN_ENCODING,
745              CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT,
746              (void *)chain->rgpElement[i - 1]->pCertContext,
747              CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT,
748              (void *)chain->rgpElement[i]->pCertContext, 0, NULL))
749                 chain->rgpElement[i - 1]->TrustStatus.dwErrorStatus |=
750                  CERT_TRUST_IS_NOT_SIGNATURE_VALID;
751             /* Once a path length constraint has been violated, every remaining
752              * CA cert's basic constraints is considered invalid.
753              */
754             if (pathLengthConstraintViolated)
755                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
756                  CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
757             else if (!CRYPT_CheckBasicConstraintsForCA(
758              chain->rgpElement[i]->pCertContext, &constraints, i - 1,
759              &pathLengthConstraintViolated))
760                 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
761                  CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
762             else if (constraints.fPathLenConstraint &&
763              constraints.dwPathLenConstraint)
764             {
765                 /* This one's valid - decrement max length */
766                 constraints.dwPathLenConstraint--;
767             }
768         }
769         if (CRYPT_IsSimpleChainCyclic(chain))
770         {
771             /* If the chain is cyclic, then the path length constraints
772              * are violated, because the chain is infinitely long.
773              */
774             pathLengthConstraintViolated = TRUE;
775             chain->TrustStatus.dwErrorStatus |=
776              CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
777         }
778         /* FIXME: check valid usages */
779         CRYPT_CombineTrustStatus(&chain->TrustStatus,
780          &chain->rgpElement[i]->TrustStatus);
781     }
782     CRYPT_CheckChainNameConstraints(chain);
783     if (CRYPT_IsCertificateSelfSigned(rootElement->pCertContext))
784     {
785         rootElement->TrustStatus.dwInfoStatus |=
786          CERT_TRUST_IS_SELF_SIGNED | CERT_TRUST_HAS_NAME_MATCH_ISSUER;
787         CRYPT_CheckRootCert(engine->hRoot, rootElement);
788     }
789     CRYPT_CombineTrustStatus(&chain->TrustStatus, &rootElement->TrustStatus);
790 }
791
792 static PCCERT_CONTEXT CRYPT_GetIssuer(HCERTSTORE store, PCCERT_CONTEXT subject,
793  PCCERT_CONTEXT prevIssuer, DWORD *infoStatus)
794 {
795     PCCERT_CONTEXT issuer = NULL;
796     PCERT_EXTENSION ext;
797     DWORD size;
798
799     *infoStatus = 0;
800     if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
801      subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
802     {
803         CERT_AUTHORITY_KEY_ID_INFO *info;
804         BOOL ret;
805
806         ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
807          X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
808          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
809          &info, &size);
810         if (ret)
811         {
812             CERT_ID id;
813
814             if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
815             {
816                 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
817                 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
818                  sizeof(CERT_NAME_BLOB));
819                 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
820                  &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
821                 issuer = CertFindCertificateInStore(store,
822                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
823                  prevIssuer);
824                 if (issuer)
825                     *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
826             }
827             else if (info->KeyId.cbData)
828             {
829                 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
830                 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
831                 issuer = CertFindCertificateInStore(store,
832                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
833                  prevIssuer);
834                 if (issuer)
835                     *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
836             }
837             LocalFree(info);
838         }
839     }
840     else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
841      subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
842     {
843         CERT_AUTHORITY_KEY_ID2_INFO *info;
844         BOOL ret;
845
846         ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
847          X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
848          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
849          &info, &size);
850         if (ret)
851         {
852             CERT_ID id;
853
854             if (info->AuthorityCertIssuer.cAltEntry &&
855              info->AuthorityCertSerialNumber.cbData)
856             {
857                 PCERT_ALT_NAME_ENTRY directoryName = NULL;
858                 DWORD i;
859
860                 for (i = 0; !directoryName &&
861                  i < info->AuthorityCertIssuer.cAltEntry; i++)
862                     if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
863                      == CERT_ALT_NAME_DIRECTORY_NAME)
864                         directoryName =
865                          &info->AuthorityCertIssuer.rgAltEntry[i];
866                 if (directoryName)
867                 {
868                     id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
869                     memcpy(&id.u.IssuerSerialNumber.Issuer,
870                      &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
871                     memcpy(&id.u.IssuerSerialNumber.SerialNumber,
872                      &info->AuthorityCertSerialNumber,
873                      sizeof(CRYPT_INTEGER_BLOB));
874                     issuer = CertFindCertificateInStore(store,
875                      subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
876                      prevIssuer);
877                     if (issuer)
878                         *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
879                 }
880                 else
881                     FIXME("no supported name type in authority key id2\n");
882             }
883             else if (info->KeyId.cbData)
884             {
885                 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
886                 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
887                 issuer = CertFindCertificateInStore(store,
888                  subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
889                  prevIssuer);
890                 if (issuer)
891                     *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
892             }
893             LocalFree(info);
894         }
895     }
896     else
897     {
898         issuer = CertFindCertificateInStore(store,
899          subject->dwCertEncodingType, 0, CERT_FIND_SUBJECT_NAME,
900          &subject->pCertInfo->Issuer, prevIssuer);
901         if (issuer)
902             *infoStatus = CERT_TRUST_HAS_NAME_MATCH_ISSUER;
903     }
904     return issuer;
905 }
906
907 /* Builds a simple chain by finding an issuer for the last cert in the chain,
908  * until reaching a self-signed cert, or until no issuer can be found.
909  */
910 static BOOL CRYPT_BuildSimpleChain(PCertificateChainEngine engine,
911  HCERTSTORE world, PCERT_SIMPLE_CHAIN chain)
912 {
913     BOOL ret = TRUE;
914     PCCERT_CONTEXT cert = chain->rgpElement[chain->cElement - 1]->pCertContext;
915
916     while (ret && !CRYPT_IsSimpleChainCyclic(chain) &&
917      !CRYPT_IsCertificateSelfSigned(cert))
918     {
919         DWORD infoStatus;
920         PCCERT_CONTEXT issuer = CRYPT_GetIssuer(world, cert, NULL, &infoStatus);
921
922         if (issuer)
923         {
924             ret = CRYPT_AddCertToSimpleChain(engine, chain, issuer, infoStatus);
925             /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it to
926              * close the enumeration that found it
927              */
928             CertFreeCertificateContext(issuer);
929             cert = issuer;
930         }
931         else
932         {
933             TRACE("Couldn't find issuer, halting chain creation\n");
934             break;
935         }
936     }
937     return ret;
938 }
939
940 static BOOL CRYPT_GetSimpleChainForCert(PCertificateChainEngine engine,
941  HCERTSTORE world, PCCERT_CONTEXT cert, LPFILETIME pTime,
942  PCERT_SIMPLE_CHAIN *ppChain)
943 {
944     BOOL ret = FALSE;
945     PCERT_SIMPLE_CHAIN chain;
946
947     TRACE("(%p, %p, %p, %p)\n", engine, world, cert, pTime);
948
949     chain = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
950     if (chain)
951     {
952         memset(chain, 0, sizeof(CERT_SIMPLE_CHAIN));
953         chain->cbSize = sizeof(CERT_SIMPLE_CHAIN);
954         ret = CRYPT_AddCertToSimpleChain(engine, chain, cert, 0);
955         if (ret)
956         {
957             ret = CRYPT_BuildSimpleChain(engine, world, chain);
958             if (ret)
959                 CRYPT_CheckSimpleChain(engine, chain, pTime);
960         }
961         if (!ret)
962         {
963             CRYPT_FreeSimpleChain(chain);
964             chain = NULL;
965         }
966         *ppChain = chain;
967     }
968     return ret;
969 }
970
971 static BOOL CRYPT_BuildCandidateChainFromCert(HCERTCHAINENGINE hChainEngine,
972  PCCERT_CONTEXT cert, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
973  PCertificateChain *ppChain)
974 {
975     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
976     PCERT_SIMPLE_CHAIN simpleChain = NULL;
977     HCERTSTORE world;
978     BOOL ret;
979
980     world = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
981      CERT_STORE_CREATE_NEW_FLAG, NULL);
982     CertAddStoreToCollection(world, engine->hWorld, 0, 0);
983     if (hAdditionalStore)
984         CertAddStoreToCollection(world, hAdditionalStore, 0, 0);
985     /* FIXME: only simple chains are supported for now, as CTLs aren't
986      * supported yet.
987      */
988     if ((ret = CRYPT_GetSimpleChainForCert(engine, world, cert, pTime,
989      &simpleChain)))
990     {
991         PCertificateChain chain = CryptMemAlloc(sizeof(CertificateChain));
992
993         if (chain)
994         {
995             chain->ref = 1;
996             chain->world = world;
997             chain->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
998             chain->context.TrustStatus = simpleChain->TrustStatus;
999             chain->context.cChain = 1;
1000             chain->context.rgpChain = CryptMemAlloc(sizeof(PCERT_SIMPLE_CHAIN));
1001             chain->context.rgpChain[0] = simpleChain;
1002             chain->context.cLowerQualityChainContext = 0;
1003             chain->context.rgpLowerQualityChainContext = NULL;
1004             chain->context.fHasRevocationFreshnessTime = FALSE;
1005             chain->context.dwRevocationFreshnessTime = 0;
1006         }
1007         else
1008             ret = FALSE;
1009         *ppChain = chain;
1010     }
1011     return ret;
1012 }
1013
1014 /* Makes and returns a copy of chain, up to and including element iElement. */
1015 static PCERT_SIMPLE_CHAIN CRYPT_CopySimpleChainToElement(
1016  PCERT_SIMPLE_CHAIN chain, DWORD iElement)
1017 {
1018     PCERT_SIMPLE_CHAIN copy = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
1019
1020     if (copy)
1021     {
1022         memset(copy, 0, sizeof(CERT_SIMPLE_CHAIN));
1023         copy->cbSize = sizeof(CERT_SIMPLE_CHAIN);
1024         copy->rgpElement =
1025          CryptMemAlloc((iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
1026         if (copy->rgpElement)
1027         {
1028             DWORD i;
1029             BOOL ret = TRUE;
1030
1031             memset(copy->rgpElement, 0,
1032              (iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
1033             for (i = 0; ret && i <= iElement; i++)
1034             {
1035                 PCERT_CHAIN_ELEMENT element =
1036                  CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
1037
1038                 if (element)
1039                 {
1040                     *element = *chain->rgpElement[i];
1041                     element->pCertContext = CertDuplicateCertificateContext(
1042                      chain->rgpElement[i]->pCertContext);
1043                     /* Reset the trust status of the copied element, it'll get
1044                      * rechecked after the new chain is done.
1045                      */
1046                     memset(&element->TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
1047                     copy->rgpElement[copy->cElement++] = element;
1048                 }
1049                 else
1050                     ret = FALSE;
1051             }
1052             if (!ret)
1053             {
1054                 for (i = 0; i <= iElement; i++)
1055                     CryptMemFree(copy->rgpElement[i]);
1056                 CryptMemFree(copy->rgpElement);
1057                 CryptMemFree(copy);
1058                 copy = NULL;
1059             }
1060         }
1061         else
1062         {
1063             CryptMemFree(copy);
1064             copy = NULL;
1065         }
1066     }
1067     return copy;
1068 }
1069
1070 static void CRYPT_FreeLowerQualityChains(PCertificateChain chain)
1071 {
1072     DWORD i;
1073
1074     for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
1075         CertFreeCertificateChain(chain->context.rgpLowerQualityChainContext[i]);
1076     CryptMemFree(chain->context.rgpLowerQualityChainContext);
1077     chain->context.cLowerQualityChainContext = 0;
1078     chain->context.rgpLowerQualityChainContext = NULL;
1079 }
1080
1081 static void CRYPT_FreeChainContext(PCertificateChain chain)
1082 {
1083     DWORD i;
1084
1085     CRYPT_FreeLowerQualityChains(chain);
1086     for (i = 0; i < chain->context.cChain; i++)
1087         CRYPT_FreeSimpleChain(chain->context.rgpChain[i]);
1088     CryptMemFree(chain->context.rgpChain);
1089     CertCloseStore(chain->world, 0);
1090     CryptMemFree(chain);
1091 }
1092
1093 /* Makes and returns a copy of chain, up to and including element iElement of
1094  * simple chain iChain.
1095  */
1096 static PCertificateChain CRYPT_CopyChainToElement(PCertificateChain chain,
1097  DWORD iChain, DWORD iElement)
1098 {
1099     PCertificateChain copy = CryptMemAlloc(sizeof(CertificateChain));
1100
1101     if (copy)
1102     {
1103         copy->ref = 1;
1104         copy->world = CertDuplicateStore(chain->world);
1105         copy->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
1106         /* Leave the trust status of the copied chain unset, it'll get
1107          * rechecked after the new chain is done.
1108          */
1109         memset(&copy->context.TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
1110         copy->context.cLowerQualityChainContext = 0;
1111         copy->context.rgpLowerQualityChainContext = NULL;
1112         copy->context.fHasRevocationFreshnessTime = FALSE;
1113         copy->context.dwRevocationFreshnessTime = 0;
1114         copy->context.rgpChain = CryptMemAlloc(
1115          (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
1116         if (copy->context.rgpChain)
1117         {
1118             BOOL ret = TRUE;
1119             DWORD i;
1120
1121             memset(copy->context.rgpChain, 0,
1122              (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
1123             if (iChain)
1124             {
1125                 for (i = 0; ret && iChain && i < iChain - 1; i++)
1126                 {
1127                     copy->context.rgpChain[i] =
1128                      CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
1129                      chain->context.rgpChain[i]->cElement - 1);
1130                     if (!copy->context.rgpChain[i])
1131                         ret = FALSE;
1132                 }
1133             }
1134             else
1135                 i = 0;
1136             if (ret)
1137             {
1138                 copy->context.rgpChain[i] =
1139                  CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
1140                  iElement);
1141                 if (!copy->context.rgpChain[i])
1142                     ret = FALSE;
1143             }
1144             if (!ret)
1145             {
1146                 CRYPT_FreeChainContext(copy);
1147                 copy = NULL;
1148             }
1149             else
1150                 copy->context.cChain = iChain + 1;
1151         }
1152         else
1153         {
1154             CryptMemFree(copy);
1155             copy = NULL;
1156         }
1157     }
1158     return copy;
1159 }
1160
1161 static PCertificateChain CRYPT_BuildAlternateContextFromChain(
1162  HCERTCHAINENGINE hChainEngine, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1163  PCertificateChain chain)
1164 {
1165     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
1166     PCertificateChain alternate;
1167
1168     TRACE("(%p, %p, %p, %p)\n", hChainEngine, pTime, hAdditionalStore, chain);
1169
1170     /* Always start with the last "lower quality" chain to ensure a consistent
1171      * order of alternate creation:
1172      */
1173     if (chain->context.cLowerQualityChainContext)
1174         chain = (PCertificateChain)chain->context.rgpLowerQualityChainContext[
1175          chain->context.cLowerQualityChainContext - 1];
1176     /* A chain with only one element can't have any alternates */
1177     if (chain->context.cChain <= 1 && chain->context.rgpChain[0]->cElement <= 1)
1178         alternate = NULL;
1179     else
1180     {
1181         DWORD i, j, infoStatus;
1182         PCCERT_CONTEXT alternateIssuer = NULL;
1183
1184         alternate = NULL;
1185         for (i = 0; !alternateIssuer && i < chain->context.cChain; i++)
1186             for (j = 0; !alternateIssuer &&
1187              j < chain->context.rgpChain[i]->cElement - 1; j++)
1188             {
1189                 PCCERT_CONTEXT subject =
1190                  chain->context.rgpChain[i]->rgpElement[j]->pCertContext;
1191                 PCCERT_CONTEXT prevIssuer = CertDuplicateCertificateContext(
1192                  chain->context.rgpChain[i]->rgpElement[j + 1]->pCertContext);
1193
1194                 alternateIssuer = CRYPT_GetIssuer(prevIssuer->hCertStore,
1195                  subject, prevIssuer, &infoStatus);
1196             }
1197         if (alternateIssuer)
1198         {
1199             i--;
1200             j--;
1201             alternate = CRYPT_CopyChainToElement(chain, i, j);
1202             if (alternate)
1203             {
1204                 BOOL ret = CRYPT_AddCertToSimpleChain(engine,
1205                  alternate->context.rgpChain[i], alternateIssuer, infoStatus);
1206
1207                 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it
1208                  * to close the enumeration that found it
1209                  */
1210                 CertFreeCertificateContext(alternateIssuer);
1211                 if (ret)
1212                 {
1213                     ret = CRYPT_BuildSimpleChain(engine, alternate->world,
1214                      alternate->context.rgpChain[i]);
1215                     if (ret)
1216                         CRYPT_CheckSimpleChain(engine,
1217                          alternate->context.rgpChain[i], pTime);
1218                     CRYPT_CombineTrustStatus(&alternate->context.TrustStatus,
1219                      &alternate->context.rgpChain[i]->TrustStatus);
1220                 }
1221                 if (!ret)
1222                 {
1223                     CRYPT_FreeChainContext(alternate);
1224                     alternate = NULL;
1225                 }
1226             }
1227         }
1228     }
1229     TRACE("%p\n", alternate);
1230     return alternate;
1231 }
1232
1233 #define CHAIN_QUALITY_SIGNATURE_VALID 8
1234 #define CHAIN_QUALITY_TIME_VALID      4
1235 #define CHAIN_QUALITY_COMPLETE_CHAIN  2
1236 #define CHAIN_QUALITY_TRUSTED_ROOT    1
1237
1238 #define CHAIN_QUALITY_HIGHEST \
1239  CHAIN_QUALITY_SIGNATURE_VALID | CHAIN_QUALITY_TIME_VALID | \
1240  CHAIN_QUALITY_COMPLETE_CHAIN | CHAIN_QUALITY_TRUSTED_ROOT
1241
1242 #define IS_TRUST_ERROR_SET(TrustStatus, bits) \
1243  (TrustStatus)->dwErrorStatus & (bits)
1244
1245 static DWORD CRYPT_ChainQuality(PCertificateChain chain)
1246 {
1247     DWORD quality = CHAIN_QUALITY_HIGHEST;
1248
1249     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1250      CERT_TRUST_IS_UNTRUSTED_ROOT))
1251         quality &= ~CHAIN_QUALITY_TRUSTED_ROOT;
1252     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1253      CERT_TRUST_IS_PARTIAL_CHAIN))
1254     if (chain->context.TrustStatus.dwErrorStatus & CERT_TRUST_IS_PARTIAL_CHAIN)
1255         quality &= ~CHAIN_QUALITY_COMPLETE_CHAIN;
1256     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1257      CERT_TRUST_IS_NOT_TIME_VALID | CERT_TRUST_IS_NOT_TIME_NESTED))
1258         quality &= ~CHAIN_QUALITY_TIME_VALID;
1259     if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1260      CERT_TRUST_IS_NOT_SIGNATURE_VALID))
1261         quality &= ~CHAIN_QUALITY_SIGNATURE_VALID;
1262     return quality;
1263 }
1264
1265 /* Chooses the highest quality chain among chain and its "lower quality"
1266  * alternate chains.  Returns the highest quality chain, with all other
1267  * chains as lower quality chains of it.
1268  */
1269 static PCertificateChain CRYPT_ChooseHighestQualityChain(
1270  PCertificateChain chain)
1271 {
1272     DWORD i;
1273
1274     /* There are always only two chains being considered:  chain, and an
1275      * alternate at chain->rgpLowerQualityChainContext[i].  If the alternate
1276      * has a higher quality than chain, the alternate gets assigned the lower
1277      * quality contexts, with chain taking the alternate's place among the
1278      * lower quality contexts.
1279      */
1280     for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
1281     {
1282         PCertificateChain alternate =
1283          (PCertificateChain)chain->context.rgpLowerQualityChainContext[i];
1284
1285         if (CRYPT_ChainQuality(alternate) > CRYPT_ChainQuality(chain))
1286         {
1287             alternate->context.cLowerQualityChainContext =
1288              chain->context.cLowerQualityChainContext;
1289             alternate->context.rgpLowerQualityChainContext =
1290              chain->context.rgpLowerQualityChainContext;
1291             alternate->context.rgpLowerQualityChainContext[i] =
1292              (PCCERT_CHAIN_CONTEXT)chain;
1293             chain->context.cLowerQualityChainContext = 0;
1294             chain->context.rgpLowerQualityChainContext = NULL;
1295             chain = alternate;
1296         }
1297     }
1298     return chain;
1299 }
1300
1301 static BOOL CRYPT_AddAlternateChainToChain(PCertificateChain chain,
1302  PCertificateChain alternate)
1303 {
1304     BOOL ret;
1305
1306     if (chain->context.cLowerQualityChainContext)
1307         chain->context.rgpLowerQualityChainContext =
1308          CryptMemRealloc(chain->context.rgpLowerQualityChainContext,
1309          (chain->context.cLowerQualityChainContext + 1) *
1310          sizeof(PCCERT_CHAIN_CONTEXT));
1311     else
1312         chain->context.rgpLowerQualityChainContext =
1313          CryptMemAlloc(sizeof(PCCERT_CHAIN_CONTEXT));
1314     if (chain->context.rgpLowerQualityChainContext)
1315     {
1316         chain->context.rgpLowerQualityChainContext[
1317          chain->context.cLowerQualityChainContext++] =
1318          (PCCERT_CHAIN_CONTEXT)alternate;
1319         ret = TRUE;
1320     }
1321     else
1322         ret = FALSE;
1323     return ret;
1324 }
1325
1326 static PCERT_CHAIN_ELEMENT CRYPT_FindIthElementInChain(
1327  PCERT_CHAIN_CONTEXT chain, DWORD i)
1328 {
1329     DWORD j, iElement;
1330     PCERT_CHAIN_ELEMENT element = NULL;
1331
1332     for (j = 0, iElement = 0; !element && j < chain->cChain; j++)
1333     {
1334         if (iElement + chain->rgpChain[j]->cElement < i)
1335             iElement += chain->rgpChain[j]->cElement;
1336         else
1337             element = chain->rgpChain[j]->rgpElement[i - iElement];
1338     }
1339     return element;
1340 }
1341
1342 typedef struct _CERT_CHAIN_PARA_NO_EXTRA_FIELDS {
1343     DWORD            cbSize;
1344     CERT_USAGE_MATCH RequestedUsage;
1345 } CERT_CHAIN_PARA_NO_EXTRA_FIELDS, *PCERT_CHAIN_PARA_NO_EXTRA_FIELDS;
1346
1347 static void CRYPT_VerifyChainRevocation(PCERT_CHAIN_CONTEXT chain,
1348  LPFILETIME pTime, PCERT_CHAIN_PARA pChainPara, DWORD chainFlags)
1349 {
1350     DWORD cContext;
1351
1352     if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_END_CERT)
1353         cContext = 1;
1354     else if ((chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN) ||
1355      (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT))
1356     {
1357         DWORD i;
1358
1359         for (i = 0, cContext = 0; i < chain->cChain; i++)
1360         {
1361             if (i < chain->cChain - 1 ||
1362              chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN)
1363                 cContext += chain->rgpChain[i]->cElement;
1364             else
1365                 cContext += chain->rgpChain[i]->cElement - 1;
1366         }
1367     }
1368     else
1369         cContext = 0;
1370     if (cContext)
1371     {
1372         PCCERT_CONTEXT *contexts =
1373          CryptMemAlloc(cContext * sizeof(PCCERT_CONTEXT *));
1374
1375         if (contexts)
1376         {
1377             DWORD i, j, iContext, revocationFlags;
1378             CERT_REVOCATION_PARA revocationPara = { sizeof(revocationPara), 0 };
1379             CERT_REVOCATION_STATUS revocationStatus =
1380              { sizeof(revocationStatus), 0 };
1381             BOOL ret;
1382
1383             for (i = 0, iContext = 0; iContext < cContext && i < chain->cChain;
1384              i++)
1385             {
1386                 for (j = 0; iContext < cContext &&
1387                  j < chain->rgpChain[i]->cElement; j++)
1388                     contexts[iContext++] =
1389                      chain->rgpChain[i]->rgpElement[j]->pCertContext;
1390             }
1391             revocationFlags = CERT_VERIFY_REV_CHAIN_FLAG;
1392             if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY)
1393                 revocationFlags |= CERT_VERIFY_CACHE_ONLY_BASED_REVOCATION;
1394             if (chainFlags & CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT)
1395                 revocationFlags |= CERT_VERIFY_REV_ACCUMULATIVE_TIMEOUT_FLAG;
1396             revocationPara.pftTimeToUse = pTime;
1397             if (pChainPara->cbSize == sizeof(CERT_CHAIN_PARA))
1398             {
1399                 revocationPara.dwUrlRetrievalTimeout =
1400                  pChainPara->dwUrlRetrievalTimeout;
1401                 revocationPara.fCheckFreshnessTime =
1402                  pChainPara->fCheckRevocationFreshnessTime;
1403                 revocationPara.dwFreshnessTime =
1404                  pChainPara->dwRevocationFreshnessTime;
1405             }
1406             ret = CertVerifyRevocation(X509_ASN_ENCODING,
1407              CERT_CONTEXT_REVOCATION_TYPE, cContext, (void **)contexts,
1408              revocationFlags, &revocationPara, &revocationStatus);
1409             if (!ret)
1410             {
1411                 PCERT_CHAIN_ELEMENT element =
1412                  CRYPT_FindIthElementInChain(chain, revocationStatus.dwIndex);
1413                 DWORD error;
1414
1415                 switch (revocationStatus.dwError)
1416                 {
1417                 case CRYPT_E_NO_REVOCATION_CHECK:
1418                 case CRYPT_E_NO_REVOCATION_DLL:
1419                 case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
1420                     error = CERT_TRUST_REVOCATION_STATUS_UNKNOWN;
1421                     break;
1422                 case CRYPT_E_REVOCATION_OFFLINE:
1423                     error = CERT_TRUST_IS_OFFLINE_REVOCATION;
1424                     break;
1425                 case CRYPT_E_REVOKED:
1426                     error = CERT_TRUST_IS_REVOKED;
1427                     break;
1428                 default:
1429                     WARN("unmapped error %08x\n", revocationStatus.dwError);
1430                     error = 0;
1431                 }
1432                 if (element)
1433                 {
1434                     /* FIXME: set element's pRevocationInfo member */
1435                     element->TrustStatus.dwErrorStatus |= error;
1436                 }
1437                 chain->TrustStatus.dwErrorStatus |= error;
1438             }
1439             CryptMemFree(contexts);
1440         }
1441     }
1442 }
1443
1444 BOOL WINAPI CertGetCertificateChain(HCERTCHAINENGINE hChainEngine,
1445  PCCERT_CONTEXT pCertContext, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1446  PCERT_CHAIN_PARA pChainPara, DWORD dwFlags, LPVOID pvReserved,
1447  PCCERT_CHAIN_CONTEXT* ppChainContext)
1448 {
1449     BOOL ret;
1450     PCertificateChain chain = NULL;
1451
1452     TRACE("(%p, %p, %p, %p, %p, %08x, %p, %p)\n", hChainEngine, pCertContext,
1453      pTime, hAdditionalStore, pChainPara, dwFlags, pvReserved, ppChainContext);
1454
1455     if (ppChainContext)
1456         *ppChainContext = NULL;
1457     if (!pChainPara)
1458     {
1459         SetLastError(E_INVALIDARG);
1460         return FALSE;
1461     }
1462     if (!pCertContext->pCertInfo->SignatureAlgorithm.pszObjId)
1463     {
1464         SetLastError(ERROR_INVALID_DATA);
1465         return FALSE;
1466     }
1467     if (pChainPara->cbSize != sizeof(CERT_CHAIN_PARA_NO_EXTRA_FIELDS) &&
1468      pChainPara->cbSize != sizeof(CERT_CHAIN_PARA))
1469     {
1470         SetLastError(E_INVALIDARG);
1471         return FALSE;
1472     }
1473     if (!hChainEngine)
1474         hChainEngine = CRYPT_GetDefaultChainEngine();
1475     /* FIXME: what about HCCE_LOCAL_MACHINE? */
1476     ret = CRYPT_BuildCandidateChainFromCert(hChainEngine, pCertContext, pTime,
1477      hAdditionalStore, &chain);
1478     if (ret)
1479     {
1480         PCertificateChain alternate = NULL;
1481         PCERT_CHAIN_CONTEXT pChain;
1482
1483         do {
1484             alternate = CRYPT_BuildAlternateContextFromChain(hChainEngine,
1485              pTime, hAdditionalStore, chain);
1486
1487             /* Alternate contexts are added as "lower quality" contexts of
1488              * chain, to avoid loops in alternate chain creation.
1489              * The highest-quality chain is chosen at the end.
1490              */
1491             if (alternate)
1492                 ret = CRYPT_AddAlternateChainToChain(chain, alternate);
1493         } while (ret && alternate);
1494         chain = CRYPT_ChooseHighestQualityChain(chain);
1495         if (!(dwFlags & CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS))
1496             CRYPT_FreeLowerQualityChains(chain);
1497         pChain = (PCERT_CHAIN_CONTEXT)chain;
1498         CRYPT_VerifyChainRevocation(pChain, pTime, pChainPara, dwFlags);
1499         if (ppChainContext)
1500             *ppChainContext = pChain;
1501         else
1502             CertFreeCertificateChain(pChain);
1503     }
1504     TRACE("returning %d\n", ret);
1505     return ret;
1506 }
1507
1508 PCCERT_CHAIN_CONTEXT WINAPI CertDuplicateCertificateChain(
1509  PCCERT_CHAIN_CONTEXT pChainContext)
1510 {
1511     PCertificateChain chain = (PCertificateChain)pChainContext;
1512
1513     TRACE("(%p)\n", pChainContext);
1514
1515     if (chain)
1516         InterlockedIncrement(&chain->ref);
1517     return pChainContext;
1518 }
1519
1520 VOID WINAPI CertFreeCertificateChain(PCCERT_CHAIN_CONTEXT pChainContext)
1521 {
1522     PCertificateChain chain = (PCertificateChain)pChainContext;
1523
1524     TRACE("(%p)\n", pChainContext);
1525
1526     if (chain)
1527     {
1528         if (InterlockedDecrement(&chain->ref) == 0)
1529             CRYPT_FreeChainContext(chain);
1530     }
1531 }
1532
1533 static void find_element_with_error(PCCERT_CHAIN_CONTEXT chain, DWORD error,
1534  LONG *iChain, LONG *iElement)
1535 {
1536     DWORD i, j;
1537
1538     for (i = 0; i < chain->cChain; i++)
1539         for (j = 0; j < chain->rgpChain[i]->cElement; j++)
1540             if (chain->rgpChain[i]->rgpElement[j]->TrustStatus.dwErrorStatus &
1541              error)
1542             {
1543                 *iChain = i;
1544                 *iElement = j;
1545                 return;
1546             }
1547 }
1548
1549 static BOOL WINAPI verify_base_policy(LPCSTR szPolicyOID,
1550  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1551  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
1552 {
1553     pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
1554     if (pChainContext->TrustStatus.dwErrorStatus &
1555      CERT_TRUST_IS_NOT_SIGNATURE_VALID)
1556     {
1557         pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
1558         find_element_with_error(pChainContext,
1559          CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
1560          &pPolicyStatus->lElementIndex);
1561     }
1562     else if (pChainContext->TrustStatus.dwErrorStatus &
1563      CERT_TRUST_IS_UNTRUSTED_ROOT)
1564     {
1565         pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
1566         find_element_with_error(pChainContext,
1567          CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
1568          &pPolicyStatus->lElementIndex);
1569     }
1570     else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
1571     {
1572         pPolicyStatus->dwError = CERT_E_CHAINING;
1573         find_element_with_error(pChainContext, CERT_TRUST_IS_CYCLIC,
1574          &pPolicyStatus->lChainIndex, &pPolicyStatus->lElementIndex);
1575         /* For a cyclic chain, which element is a cycle isn't meaningful */
1576         pPolicyStatus->lElementIndex = -1;
1577     }
1578     else
1579         pPolicyStatus->dwError = NO_ERROR;
1580     return TRUE;
1581 }
1582
1583 static BYTE msTestPubKey1[] = {
1584 0x30,0x47,0x02,0x40,0x81,0x55,0x22,0xb9,0x8a,0xa4,0x6f,0xed,0xd6,0xe7,0xd9,
1585 0x66,0x0f,0x55,0xbc,0xd7,0xcd,0xd5,0xbc,0x4e,0x40,0x02,0x21,0xa2,0xb1,0xf7,
1586 0x87,0x30,0x85,0x5e,0xd2,0xf2,0x44,0xb9,0xdc,0x9b,0x75,0xb6,0xfb,0x46,0x5f,
1587 0x42,0xb6,0x9d,0x23,0x36,0x0b,0xde,0x54,0x0f,0xcd,0xbd,0x1f,0x99,0x2a,0x10,
1588 0x58,0x11,0xcb,0x40,0xcb,0xb5,0xa7,0x41,0x02,0x03,0x01,0x00,0x01 };
1589 static BYTE msTestPubKey2[] = {
1590 0x30,0x47,0x02,0x40,0x9c,0x50,0x05,0x1d,0xe2,0x0e,0x4c,0x53,0xd8,0xd9,0xb5,
1591 0xe5,0xfd,0xe9,0xe3,0xad,0x83,0x4b,0x80,0x08,0xd9,0xdc,0xe8,0xe8,0x35,0xf8,
1592 0x11,0xf1,0xe9,0x9b,0x03,0x7a,0x65,0x64,0x76,0x35,0xce,0x38,0x2c,0xf2,0xb6,
1593 0x71,0x9e,0x06,0xd9,0xbf,0xbb,0x31,0x69,0xa3,0xf6,0x30,0xa0,0x78,0x7b,0x18,
1594 0xdd,0x50,0x4d,0x79,0x1e,0xeb,0x61,0xc1,0x02,0x03,0x01,0x00,0x01 };
1595
1596 static BOOL WINAPI verify_authenticode_policy(LPCSTR szPolicyOID,
1597  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1598  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
1599 {
1600     BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
1601      pPolicyStatus);
1602
1603     if (ret && pPolicyStatus->dwError == CERT_E_UNTRUSTEDROOT)
1604     {
1605         CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
1606         BOOL isMSTestRoot = FALSE;
1607         PCCERT_CONTEXT failingCert =
1608          pChainContext->rgpChain[pPolicyStatus->lChainIndex]->
1609          rgpElement[pPolicyStatus->lElementIndex]->pCertContext;
1610         DWORD i;
1611         CRYPT_DATA_BLOB keyBlobs[] = {
1612          { sizeof(msTestPubKey1), msTestPubKey1 },
1613          { sizeof(msTestPubKey2), msTestPubKey2 },
1614         };
1615
1616         /* Check whether the root is an MS test root */
1617         for (i = 0; !isMSTestRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
1618          i++)
1619         {
1620             msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
1621             msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
1622             if (CertComparePublicKeyInfo(
1623              X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1624              &failingCert->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
1625                 isMSTestRoot = TRUE;
1626         }
1627         if (isMSTestRoot)
1628             pPolicyStatus->dwError = CERT_E_UNTRUSTEDTESTROOT;
1629     }
1630     return ret;
1631 }
1632
1633 static BOOL WINAPI verify_basic_constraints_policy(LPCSTR szPolicyOID,
1634  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1635  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
1636 {
1637     pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
1638     if (pChainContext->TrustStatus.dwErrorStatus &
1639      CERT_TRUST_INVALID_BASIC_CONSTRAINTS)
1640     {
1641         pPolicyStatus->dwError = TRUST_E_BASIC_CONSTRAINTS;
1642         find_element_with_error(pChainContext,
1643          CERT_TRUST_INVALID_BASIC_CONSTRAINTS, &pPolicyStatus->lChainIndex,
1644          &pPolicyStatus->lElementIndex);
1645     }
1646     else
1647         pPolicyStatus->dwError = NO_ERROR;
1648     return TRUE;
1649 }
1650
1651 static BYTE msPubKey1[] = {
1652 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xdf,0x08,0xba,0xe3,0x3f,0x6e,
1653 0x64,0x9b,0xf5,0x89,0xaf,0x28,0x96,0x4a,0x07,0x8f,0x1b,0x2e,0x8b,0x3e,0x1d,
1654 0xfc,0xb8,0x80,0x69,0xa3,0xa1,0xce,0xdb,0xdf,0xb0,0x8e,0x6c,0x89,0x76,0x29,
1655 0x4f,0xca,0x60,0x35,0x39,0xad,0x72,0x32,0xe0,0x0b,0xae,0x29,0x3d,0x4c,0x16,
1656 0xd9,0x4b,0x3c,0x9d,0xda,0xc5,0xd3,0xd1,0x09,0xc9,0x2c,0x6f,0xa6,0xc2,0x60,
1657 0x53,0x45,0xdd,0x4b,0xd1,0x55,0xcd,0x03,0x1c,0xd2,0x59,0x56,0x24,0xf3,0xe5,
1658 0x78,0xd8,0x07,0xcc,0xd8,0xb3,0x1f,0x90,0x3f,0xc0,0x1a,0x71,0x50,0x1d,0x2d,
1659 0xa7,0x12,0x08,0x6d,0x7c,0xb0,0x86,0x6c,0xc7,0xba,0x85,0x32,0x07,0xe1,0x61,
1660 0x6f,0xaf,0x03,0xc5,0x6d,0xe5,0xd6,0xa1,0x8f,0x36,0xf6,0xc1,0x0b,0xd1,0x3e,
1661 0x69,0x97,0x48,0x72,0xc9,0x7f,0xa4,0xc8,0xc2,0x4a,0x4c,0x7e,0xa1,0xd1,0x94,
1662 0xa6,0xd7,0xdc,0xeb,0x05,0x46,0x2e,0xb8,0x18,0xb4,0x57,0x1d,0x86,0x49,0xdb,
1663 0x69,0x4a,0x2c,0x21,0xf5,0x5e,0x0f,0x54,0x2d,0x5a,0x43,0xa9,0x7a,0x7e,0x6a,
1664 0x8e,0x50,0x4d,0x25,0x57,0xa1,0xbf,0x1b,0x15,0x05,0x43,0x7b,0x2c,0x05,0x8d,
1665 0xbd,0x3d,0x03,0x8c,0x93,0x22,0x7d,0x63,0xea,0x0a,0x57,0x05,0x06,0x0a,0xdb,
1666 0x61,0x98,0x65,0x2d,0x47,0x49,0xa8,0xe7,0xe6,0x56,0x75,0x5c,0xb8,0x64,0x08,
1667 0x63,0xa9,0x30,0x40,0x66,0xb2,0xf9,0xb6,0xe3,0x34,0xe8,0x67,0x30,0xe1,0x43,
1668 0x0b,0x87,0xff,0xc9,0xbe,0x72,0x10,0x5e,0x23,0xf0,0x9b,0xa7,0x48,0x65,0xbf,
1669 0x09,0x88,0x7b,0xcd,0x72,0xbc,0x2e,0x79,0x9b,0x7b,0x02,0x03,0x01,0x00,0x01 };
1670 static BYTE msPubKey2[] = {
1671 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xa9,0x02,0xbd,0xc1,0x70,0xe6,
1672 0x3b,0xf2,0x4e,0x1b,0x28,0x9f,0x97,0x78,0x5e,0x30,0xea,0xa2,0xa9,0x8d,0x25,
1673 0x5f,0xf8,0xfe,0x95,0x4c,0xa3,0xb7,0xfe,0x9d,0xa2,0x20,0x3e,0x7c,0x51,0xa2,
1674 0x9b,0xa2,0x8f,0x60,0x32,0x6b,0xd1,0x42,0x64,0x79,0xee,0xac,0x76,0xc9,0x54,
1675 0xda,0xf2,0xeb,0x9c,0x86,0x1c,0x8f,0x9f,0x84,0x66,0xb3,0xc5,0x6b,0x7a,0x62,
1676 0x23,0xd6,0x1d,0x3c,0xde,0x0f,0x01,0x92,0xe8,0x96,0xc4,0xbf,0x2d,0x66,0x9a,
1677 0x9a,0x68,0x26,0x99,0xd0,0x3a,0x2c,0xbf,0x0c,0xb5,0x58,0x26,0xc1,0x46,0xe7,
1678 0x0a,0x3e,0x38,0x96,0x2c,0xa9,0x28,0x39,0xa8,0xec,0x49,0x83,0x42,0xe3,0x84,
1679 0x0f,0xbb,0x9a,0x6c,0x55,0x61,0xac,0x82,0x7c,0xa1,0x60,0x2d,0x77,0x4c,0xe9,
1680 0x99,0xb4,0x64,0x3b,0x9a,0x50,0x1c,0x31,0x08,0x24,0x14,0x9f,0xa9,0xe7,0x91,
1681 0x2b,0x18,0xe6,0x3d,0x98,0x63,0x14,0x60,0x58,0x05,0x65,0x9f,0x1d,0x37,0x52,
1682 0x87,0xf7,0xa7,0xef,0x94,0x02,0xc6,0x1b,0xd3,0xbf,0x55,0x45,0xb3,0x89,0x80,
1683 0xbf,0x3a,0xec,0x54,0x94,0x4e,0xae,0xfd,0xa7,0x7a,0x6d,0x74,0x4e,0xaf,0x18,
1684 0xcc,0x96,0x09,0x28,0x21,0x00,0x57,0x90,0x60,0x69,0x37,0xbb,0x4b,0x12,0x07,
1685 0x3c,0x56,0xff,0x5b,0xfb,0xa4,0x66,0x0a,0x08,0xa6,0xd2,0x81,0x56,0x57,0xef,
1686 0xb6,0x3b,0x5e,0x16,0x81,0x77,0x04,0xda,0xf6,0xbe,0xae,0x80,0x95,0xfe,0xb0,
1687 0xcd,0x7f,0xd6,0xa7,0x1a,0x72,0x5c,0x3c,0xca,0xbc,0xf0,0x08,0xa3,0x22,0x30,
1688 0xb3,0x06,0x85,0xc9,0xb3,0x20,0x77,0x13,0x85,0xdf,0x02,0x03,0x01,0x00,0x01 };
1689 static BYTE msPubKey3[] = {
1690 0x30,0x82,0x02,0x0a,0x02,0x82,0x02,0x01,0x00,0xf3,0x5d,0xfa,0x80,0x67,0xd4,
1691 0x5a,0xa7,0xa9,0x0c,0x2c,0x90,0x20,0xd0,0x35,0x08,0x3c,0x75,0x84,0xcd,0xb7,
1692 0x07,0x89,0x9c,0x89,0xda,0xde,0xce,0xc3,0x60,0xfa,0x91,0x68,0x5a,0x9e,0x94,
1693 0x71,0x29,0x18,0x76,0x7c,0xc2,0xe0,0xc8,0x25,0x76,0x94,0x0e,0x58,0xfa,0x04,
1694 0x34,0x36,0xe6,0xdf,0xaf,0xf7,0x80,0xba,0xe9,0x58,0x0b,0x2b,0x93,0xe5,0x9d,
1695 0x05,0xe3,0x77,0x22,0x91,0xf7,0x34,0x64,0x3c,0x22,0x91,0x1d,0x5e,0xe1,0x09,
1696 0x90,0xbc,0x14,0xfe,0xfc,0x75,0x58,0x19,0xe1,0x79,0xb7,0x07,0x92,0xa3,0xae,
1697 0x88,0x59,0x08,0xd8,0x9f,0x07,0xca,0x03,0x58,0xfc,0x68,0x29,0x6d,0x32,0xd7,
1698 0xd2,0xa8,0xcb,0x4b,0xfc,0xe1,0x0b,0x48,0x32,0x4f,0xe6,0xeb,0xb8,0xad,0x4f,
1699 0xe4,0x5c,0x6f,0x13,0x94,0x99,0xdb,0x95,0xd5,0x75,0xdb,0xa8,0x1a,0xb7,0x94,
1700 0x91,0xb4,0x77,0x5b,0xf5,0x48,0x0c,0x8f,0x6a,0x79,0x7d,0x14,0x70,0x04,0x7d,
1701 0x6d,0xaf,0x90,0xf5,0xda,0x70,0xd8,0x47,0xb7,0xbf,0x9b,0x2f,0x6c,0xe7,0x05,
1702 0xb7,0xe1,0x11,0x60,0xac,0x79,0x91,0x14,0x7c,0xc5,0xd6,0xa6,0xe4,0xe1,0x7e,
1703 0xd5,0xc3,0x7e,0xe5,0x92,0xd2,0x3c,0x00,0xb5,0x36,0x82,0xde,0x79,0xe1,0x6d,
1704 0xf3,0xb5,0x6e,0xf8,0x9f,0x33,0xc9,0xcb,0x52,0x7d,0x73,0x98,0x36,0xdb,0x8b,
1705 0xa1,0x6b,0xa2,0x95,0x97,0x9b,0xa3,0xde,0xc2,0x4d,0x26,0xff,0x06,0x96,0x67,
1706 0x25,0x06,0xc8,0xe7,0xac,0xe4,0xee,0x12,0x33,0x95,0x31,0x99,0xc8,0x35,0x08,
1707 0x4e,0x34,0xca,0x79,0x53,0xd5,0xb5,0xbe,0x63,0x32,0x59,0x40,0x36,0xc0,0xa5,
1708 0x4e,0x04,0x4d,0x3d,0xdb,0x5b,0x07,0x33,0xe4,0x58,0xbf,0xef,0x3f,0x53,0x64,
1709 0xd8,0x42,0x59,0x35,0x57,0xfd,0x0f,0x45,0x7c,0x24,0x04,0x4d,0x9e,0xd6,0x38,
1710 0x74,0x11,0x97,0x22,0x90,0xce,0x68,0x44,0x74,0x92,0x6f,0xd5,0x4b,0x6f,0xb0,
1711 0x86,0xe3,0xc7,0x36,0x42,0xa0,0xd0,0xfc,0xc1,0xc0,0x5a,0xf9,0xa3,0x61,0xb9,
1712 0x30,0x47,0x71,0x96,0x0a,0x16,0xb0,0x91,0xc0,0x42,0x95,0xef,0x10,0x7f,0x28,
1713 0x6a,0xe3,0x2a,0x1f,0xb1,0xe4,0xcd,0x03,0x3f,0x77,0x71,0x04,0xc7,0x20,0xfc,
1714 0x49,0x0f,0x1d,0x45,0x88,0xa4,0xd7,0xcb,0x7e,0x88,0xad,0x8e,0x2d,0xec,0x45,
1715 0xdb,0xc4,0x51,0x04,0xc9,0x2a,0xfc,0xec,0x86,0x9e,0x9a,0x11,0x97,0x5b,0xde,
1716 0xce,0x53,0x88,0xe6,0xe2,0xb7,0xfd,0xac,0x95,0xc2,0x28,0x40,0xdb,0xef,0x04,
1717 0x90,0xdf,0x81,0x33,0x39,0xd9,0xb2,0x45,0xa5,0x23,0x87,0x06,0xa5,0x55,0x89,
1718 0x31,0xbb,0x06,0x2d,0x60,0x0e,0x41,0x18,0x7d,0x1f,0x2e,0xb5,0x97,0xcb,0x11,
1719 0xeb,0x15,0xd5,0x24,0xa5,0x94,0xef,0x15,0x14,0x89,0xfd,0x4b,0x73,0xfa,0x32,
1720 0x5b,0xfc,0xd1,0x33,0x00,0xf9,0x59,0x62,0x70,0x07,0x32,0xea,0x2e,0xab,0x40,
1721 0x2d,0x7b,0xca,0xdd,0x21,0x67,0x1b,0x30,0x99,0x8f,0x16,0xaa,0x23,0xa8,0x41,
1722 0xd1,0xb0,0x6e,0x11,0x9b,0x36,0xc4,0xde,0x40,0x74,0x9c,0xe1,0x58,0x65,0xc1,
1723 0x60,0x1e,0x7a,0x5b,0x38,0xc8,0x8f,0xbb,0x04,0x26,0x7c,0xd4,0x16,0x40,0xe5,
1724 0xb6,0x6b,0x6c,0xaa,0x86,0xfd,0x00,0xbf,0xce,0xc1,0x35,0x02,0x03,0x01,0x00,
1725 0x01 };
1726
1727 static BOOL WINAPI verify_ms_root_policy(LPCSTR szPolicyOID,
1728  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1729  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
1730 {
1731     BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
1732      pPolicyStatus);
1733
1734     if (ret && !pPolicyStatus->dwError)
1735     {
1736         CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
1737         BOOL isMSRoot = FALSE;
1738         DWORD i;
1739         CRYPT_DATA_BLOB keyBlobs[] = {
1740          { sizeof(msPubKey1), msPubKey1 },
1741          { sizeof(msPubKey2), msPubKey2 },
1742          { sizeof(msPubKey3), msPubKey3 },
1743         };
1744         PCERT_SIMPLE_CHAIN rootChain =
1745          pChainContext->rgpChain[pChainContext->cChain -1 ];
1746         PCCERT_CONTEXT root =
1747          rootChain->rgpElement[rootChain->cElement - 1]->pCertContext;
1748
1749         for (i = 0; !isMSRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
1750          i++)
1751         {
1752             msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
1753             msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
1754             if (CertComparePublicKeyInfo(
1755              X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1756              &root->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
1757                 isMSRoot = TRUE;
1758         }
1759         if (isMSRoot)
1760             pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = 0;
1761     }
1762     return ret;
1763 }
1764
1765 typedef BOOL (WINAPI *CertVerifyCertificateChainPolicyFunc)(LPCSTR szPolicyOID,
1766  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1767  PCERT_CHAIN_POLICY_STATUS pPolicyStatus);
1768
1769 BOOL WINAPI CertVerifyCertificateChainPolicy(LPCSTR szPolicyOID,
1770  PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
1771  PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
1772 {
1773     static HCRYPTOIDFUNCSET set = NULL;
1774     BOOL ret = FALSE;
1775     CertVerifyCertificateChainPolicyFunc verifyPolicy = NULL;
1776     HCRYPTOIDFUNCADDR hFunc = NULL;
1777
1778     TRACE("(%s, %p, %p, %p)\n", debugstr_a(szPolicyOID), pChainContext,
1779      pPolicyPara, pPolicyStatus);
1780
1781     if (!HIWORD(szPolicyOID))
1782     {
1783         switch (LOWORD(szPolicyOID))
1784         {
1785         case LOWORD(CERT_CHAIN_POLICY_BASE):
1786             verifyPolicy = verify_base_policy;
1787             break;
1788         case LOWORD(CERT_CHAIN_POLICY_AUTHENTICODE):
1789             verifyPolicy = verify_authenticode_policy;
1790             break;
1791         case LOWORD(CERT_CHAIN_POLICY_BASIC_CONSTRAINTS):
1792             verifyPolicy = verify_basic_constraints_policy;
1793             break;
1794         case LOWORD(CERT_CHAIN_POLICY_MICROSOFT_ROOT):
1795             verifyPolicy = verify_ms_root_policy;
1796             break;
1797         default:
1798             FIXME("unimplemented for %d\n", LOWORD(szPolicyOID));
1799         }
1800     }
1801     if (!verifyPolicy)
1802     {
1803         if (!set)
1804             set = CryptInitOIDFunctionSet(
1805              CRYPT_OID_VERIFY_CERTIFICATE_CHAIN_POLICY_FUNC, 0);
1806         CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING, szPolicyOID, 0,
1807          (void **)&verifyPolicy, &hFunc);
1808     }
1809     if (verifyPolicy)
1810         ret = verifyPolicy(szPolicyOID, pChainContext, pPolicyPara,
1811          pPolicyStatus);
1812     if (hFunc)
1813         CryptFreeOIDFunctionAddress(hFunc, 0);
1814     return ret;
1815 }