crypt32: Trace method used to find an issuer.
[wine/multimedia.git] / dlls / crypt32 / chain.c
blob6344e67f441bbc9024a39c771c374adff4c15aed
1 /*
2 * Copyright 2006 Juan Lang
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.
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.
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
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"
30 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
31 WINE_DECLARE_DEBUG_CHANNEL(chain);
33 #define DEFAULT_CYCLE_MODULUS 7
35 static HCERTCHAINENGINE CRYPT_defaultChainEngine;
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.
42 typedef struct _CertificateChainEngine
44 LONG ref;
45 HCERTSTORE hRoot;
46 HCERTSTORE hWorld;
47 DWORD dwFlags;
48 DWORD dwUrlRetrievalTimeout;
49 DWORD MaximumCachedCertificates;
50 DWORD CycleDetectionModulus;
51 } CertificateChainEngine, *PCertificateChainEngine;
53 static inline void CRYPT_AddStoresToCollection(HCERTSTORE collection,
54 DWORD cStores, HCERTSTORE *stores)
56 DWORD i;
58 for (i = 0; i < cStores; i++)
59 CertAddStoreToCollection(collection, stores[i], 0, 0);
62 static inline void CRYPT_CloseStores(DWORD cStores, HCERTSTORE *stores)
64 DWORD i;
66 for (i = 0; i < cStores; i++)
67 CertCloseStore(stores[i], 0);
70 static const WCHAR rootW[] = { 'R','o','o','t',0 };
72 /* Finds cert in store by comparing the cert's hashes. */
73 static PCCERT_CONTEXT CRYPT_FindCertInStore(HCERTSTORE store,
74 PCCERT_CONTEXT cert)
76 PCCERT_CONTEXT matching = NULL;
77 BYTE hash[20];
78 DWORD size = sizeof(hash);
80 if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID, hash, &size))
82 CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
84 matching = CertFindCertificateInStore(store, cert->dwCertEncodingType,
85 0, CERT_FIND_SHA1_HASH, &blob, NULL);
87 return matching;
90 static BOOL CRYPT_CheckRestrictedRoot(HCERTSTORE store)
92 BOOL ret = TRUE;
94 if (store)
96 HCERTSTORE rootStore = CertOpenSystemStoreW(0, rootW);
97 PCCERT_CONTEXT cert = NULL, check;
99 do {
100 cert = CertEnumCertificatesInStore(store, cert);
101 if (cert)
103 if (!(check = CRYPT_FindCertInStore(rootStore, cert)))
104 ret = FALSE;
105 else
106 CertFreeCertificateContext(check);
108 } while (ret && cert);
109 if (cert)
110 CertFreeCertificateContext(cert);
111 CertCloseStore(rootStore, 0);
113 return ret;
116 HCERTCHAINENGINE CRYPT_CreateChainEngine(HCERTSTORE root,
117 PCERT_CHAIN_ENGINE_CONFIG pConfig)
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));
125 if (engine)
127 HCERTSTORE worldStores[4];
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;
152 return engine;
155 BOOL WINAPI CertCreateCertificateChainEngine(PCERT_CHAIN_ENGINE_CONFIG pConfig,
156 HCERTCHAINENGINE *phChainEngine)
158 BOOL ret;
160 TRACE("(%p, %p)\n", pConfig, phChainEngine);
162 if (pConfig->cbSize != sizeof(*pConfig))
164 SetLastError(E_INVALIDARG);
165 return FALSE;
167 *phChainEngine = NULL;
168 ret = CRYPT_CheckRestrictedRoot(pConfig->hRestrictedRoot);
169 if (ret)
171 HCERTSTORE root;
172 HCERTCHAINENGINE engine;
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)
181 *phChainEngine = engine;
182 ret = TRUE;
184 else
185 ret = FALSE;
187 return ret;
190 VOID WINAPI CertFreeCertificateChainEngine(HCERTCHAINENGINE hChainEngine)
192 PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
194 TRACE("(%p)\n", hChainEngine);
196 if (engine && InterlockedDecrement(&engine->ref) == 0)
198 CertCloseStore(engine->hWorld, 0);
199 CertCloseStore(engine->hRoot, 0);
200 CryptMemFree(engine);
204 static HCERTCHAINENGINE CRYPT_GetDefaultChainEngine(void)
206 if (!CRYPT_defaultChainEngine)
208 CERT_CHAIN_ENGINE_CONFIG config = { 0 };
209 HCERTCHAINENGINE engine;
211 config.cbSize = sizeof(config);
212 CertCreateCertificateChainEngine(&config, &engine);
213 InterlockedCompareExchangePointer(&CRYPT_defaultChainEngine, engine,
214 NULL);
215 if (CRYPT_defaultChainEngine != engine)
216 CertFreeCertificateChainEngine(engine);
218 return CRYPT_defaultChainEngine;
221 void default_chain_engine_free(void)
223 CertFreeCertificateChainEngine(CRYPT_defaultChainEngine);
226 typedef struct _CertificateChain
228 CERT_CHAIN_CONTEXT context;
229 HCERTSTORE world;
230 LONG ref;
231 } CertificateChain, *PCertificateChain;
233 static inline BOOL CRYPT_IsCertificateSelfSigned(PCCERT_CONTEXT cert)
235 return CertCompareCertificateName(cert->dwCertEncodingType,
236 &cert->pCertInfo->Subject, &cert->pCertInfo->Issuer);
239 static void CRYPT_FreeChainElement(PCERT_CHAIN_ELEMENT element)
241 CertFreeCertificateContext(element->pCertContext);
242 CryptMemFree(element);
245 static void CRYPT_CheckSimpleChainForCycles(PCERT_SIMPLE_CHAIN chain)
247 DWORD i, j, cyclicCertIndex = 0;
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)
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;
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)
271 if (chain->cElement)
272 return chain->rgpElement[chain->cElement - 1]->TrustStatus.dwErrorStatus
273 & CERT_TRUST_IS_CYCLIC;
274 else
275 return FALSE;
278 static inline void CRYPT_CombineTrustStatus(CERT_TRUST_STATUS *chainStatus,
279 const CERT_TRUST_STATUS *elementStatus)
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.
286 chainStatus->dwInfoStatus |= (elementStatus->dwInfoStatus & 0xfffffff0);
289 static BOOL CRYPT_AddCertToSimpleChain(const CertificateChainEngine *engine,
290 PCERT_SIMPLE_CHAIN chain, PCCERT_CONTEXT cert, DWORD subjectInfoStatus)
292 BOOL ret = FALSE;
293 PCERT_CHAIN_ELEMENT element = CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
295 if (element)
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)
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))
314 CRYPT_CheckSimpleChainForCycles(chain);
315 /* Reinitialize the element pointer in case the chain is
316 * cyclic, in which case the chain is truncated.
318 element = chain->rgpElement[chain->cElement - 1];
320 CRYPT_CombineTrustStatus(&chain->TrustStatus,
321 &element->TrustStatus);
322 ret = TRUE;
324 else
325 CryptMemFree(element);
327 return ret;
330 static void CRYPT_FreeSimpleChain(PCERT_SIMPLE_CHAIN chain)
332 DWORD i;
334 for (i = 0; i < chain->cElement; i++)
335 CRYPT_FreeChainElement(chain->rgpElement[i]);
336 CryptMemFree(chain->rgpElement);
337 CryptMemFree(chain);
340 static void CRYPT_CheckTrustedStatus(HCERTSTORE hRoot,
341 PCERT_CHAIN_ELEMENT rootElement)
343 PCCERT_CONTEXT trustedRoot = CRYPT_FindCertInStore(hRoot,
344 rootElement->pCertContext);
346 if (!trustedRoot)
347 rootElement->TrustStatus.dwErrorStatus |=
348 CERT_TRUST_IS_UNTRUSTED_ROOT;
349 else
350 CertFreeCertificateContext(trustedRoot);
353 static void CRYPT_CheckRootCert(HCERTCHAINENGINE hRoot,
354 PCERT_CHAIN_ELEMENT rootElement)
356 PCCERT_CONTEXT root = rootElement->pCertContext;
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))
362 TRACE_(chain)("Last certificate's signature is invalid\n");
363 rootElement->TrustStatus.dwErrorStatus |=
364 CERT_TRUST_IS_NOT_SIGNATURE_VALID;
366 CRYPT_CheckTrustedStatus(hRoot, rootElement);
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.
375 static BOOL CRYPT_DecodeBasicConstraints(PCCERT_CONTEXT cert,
376 CERT_BASIC_CONSTRAINTS2_INFO *constraints, BOOL defaultIfNotSpecified)
378 BOOL ret = TRUE;
379 PCERT_EXTENSION ext = CertFindExtension(szOID_BASIC_CONSTRAINTS,
380 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
382 constraints->fPathLenConstraint = FALSE;
383 if (ext)
385 CERT_BASIC_CONSTRAINTS_INFO *info;
386 DWORD size = 0;
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)
393 if (info->SubjectType.cbData == 1)
394 constraints->fCA =
395 info->SubjectType.pbData[0] & CERT_CA_SUBJECT_FLAG;
396 LocalFree(info);
399 else
401 ext = CertFindExtension(szOID_BASIC_CONSTRAINTS2,
402 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
403 if (ext)
405 DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
407 ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
408 szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
409 0, NULL, constraints, &size);
411 else
412 constraints->fCA = defaultIfNotSpecified;
414 return ret;
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.
442 static BOOL CRYPT_CheckBasicConstraintsForCA(PCertificateChainEngine engine,
443 PCCERT_CONTEXT cert, CERT_BASIC_CONSTRAINTS2_INFO *chainConstraints,
444 DWORD remainingCAs, BOOL isRoot, BOOL *pathLengthConstraintViolated)
446 BOOL validBasicConstraints, implicitCA = FALSE;
447 CERT_BASIC_CONSTRAINTS2_INFO constraints;
449 if (isRoot)
450 implicitCA = TRUE;
451 else if (cert->pCertInfo->dwVersion == CERT_V1 ||
452 cert->pCertInfo->dwVersion == CERT_V2)
454 BYTE hash[20];
455 DWORD size = sizeof(hash);
457 if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID,
458 hash, &size))
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);
465 if (localCert)
467 CertFreeCertificateContext(localCert);
468 implicitCA = TRUE;
472 if ((validBasicConstraints = CRYPT_DecodeBasicConstraints(cert,
473 &constraints, implicitCA)))
475 chainConstraints->fCA = constraints.fCA;
476 if (!constraints.fCA)
478 TRACE_(chain)("chain element %d can't be a CA\n", remainingCAs + 1);
479 validBasicConstraints = FALSE;
481 else if (constraints.fPathLenConstraint)
483 /* If the element has path length constraints, they apply to the
484 * entire remaining chain.
486 if (!chainConstraints->fPathLenConstraint ||
487 constraints.dwPathLenConstraint <
488 chainConstraints->dwPathLenConstraint)
490 TRACE_(chain)("setting path length constraint to %d\n",
491 chainConstraints->dwPathLenConstraint);
492 chainConstraints->fPathLenConstraint = TRUE;
493 chainConstraints->dwPathLenConstraint =
494 constraints.dwPathLenConstraint;
498 if (chainConstraints->fPathLenConstraint &&
499 remainingCAs > chainConstraints->dwPathLenConstraint)
501 TRACE_(chain)("remaining CAs %d exceed max path length %d\n",
502 remainingCAs, chainConstraints->dwPathLenConstraint);
503 validBasicConstraints = FALSE;
504 *pathLengthConstraintViolated = TRUE;
506 return validBasicConstraints;
509 static BOOL url_matches(LPCWSTR constraint, LPCWSTR name,
510 DWORD *trustErrorStatus)
512 BOOL match = FALSE;
514 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
516 if (!constraint)
517 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
518 else if (!name)
519 ; /* no match */
520 else if (constraint[0] == '.')
522 if (lstrlenW(name) > lstrlenW(constraint))
523 match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
524 constraint);
526 else
527 match = !lstrcmpiW(constraint, name);
528 return match;
531 static BOOL rfc822_name_matches(LPCWSTR constraint, LPCWSTR name,
532 DWORD *trustErrorStatus)
534 BOOL match = FALSE;
535 LPCWSTR at;
537 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
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
547 if ((at = strchrW(name, '@')))
548 match = url_matches(constraint, at + 1, trustErrorStatus);
549 else
550 match = !lstrcmpiW(constraint, name);
552 return match;
555 static BOOL dns_name_matches(LPCWSTR constraint, LPCWSTR name,
556 DWORD *trustErrorStatus)
558 BOOL match = FALSE;
560 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
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 */
571 return match;
574 static BOOL ip_address_matches(const CRYPT_DATA_BLOB *constraint,
575 const CRYPT_DATA_BLOB *name, DWORD *trustErrorStatus)
577 BOOL match = FALSE;
579 TRACE("(%d, %p), (%d, %p)\n", constraint->cbData, constraint->pbData,
580 name->cbData, name->pbData);
582 /* RFC5280, section 4.2.1.10, iPAddress syntax: either 8 or 32 bytes, for
583 * IPv4 or IPv6 addresses, respectively.
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)
590 DWORD subnet, mask, addr;
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
598 match = (subnet & mask) == (addr & mask);
600 else if (name->cbData == 16 && constraint->cbData == 32)
602 const BYTE *subnet, *mask, *addr;
603 DWORD i;
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;
613 /* else: name is wrong size, no match */
615 return match;
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)
622 DWORD i;
623 BOOL match = FALSE;
625 for (i = 0; i < subjectName->cAltEntry; i++)
627 if (subjectName->rgAltEntry[i].dwAltNameChoice ==
628 constraint->dwAltNameChoice)
630 switch (constraint->dwAltNameChoice)
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;
657 *trustErrorStatus |= match ? errorIfFound : errorIfNotFound;
660 static inline PCERT_EXTENSION get_subject_alt_name_ext(const CERT_INFO *cert)
662 PCERT_EXTENSION ext;
664 ext = CertFindExtension(szOID_SUBJECT_ALT_NAME2,
665 cert->cExtension, cert->rgExtension);
666 if (!ext)
667 ext = CertFindExtension(szOID_SUBJECT_ALT_NAME,
668 cert->cExtension, cert->rgExtension);
669 return ext;
672 static void CRYPT_CheckNameConstraints(
673 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, const CERT_INFO *cert,
674 DWORD *trustErrorStatus)
676 /* If there aren't any existing constraints, don't bother checking */
677 if (nameConstraints->cPermittedSubtree || nameConstraints->cExcludedSubtree)
679 CERT_EXTENSION *ext = get_subject_alt_name_ext(cert);
681 if (ext)
683 CERT_ALT_NAME_INFO *subjectName;
684 DWORD size;
686 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
687 ext->Value.pbData, ext->Value.cbData,
688 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
689 &subjectName, &size))
691 DWORD i;
693 for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
694 CRYPT_FindMatchingNameEntry(
695 &nameConstraints->rgExcludedSubtree[i].Base, subjectName,
696 trustErrorStatus,
697 CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT, 0);
698 for (i = 0; i < nameConstraints->cPermittedSubtree; i++)
699 CRYPT_FindMatchingNameEntry(
700 &nameConstraints->rgPermittedSubtree[i].Base, subjectName,
701 trustErrorStatus, 0,
702 CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT);
703 LocalFree(subjectName);
705 else
706 *trustErrorStatus |=
707 CERT_TRUST_INVALID_EXTENSION |
708 CERT_TRUST_INVALID_NAME_CONSTRAINTS;
710 else
712 if (nameConstraints->cPermittedSubtree)
713 *trustErrorStatus |=
714 CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT |
715 CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
716 if (nameConstraints->cExcludedSubtree)
717 *trustErrorStatus |=
718 CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
723 /* Gets cert's name constraints, if any. Free with LocalFree. */
724 static CERT_NAME_CONSTRAINTS_INFO *CRYPT_GetNameConstraints(CERT_INFO *cert)
726 CERT_NAME_CONSTRAINTS_INFO *info = NULL;
728 CERT_EXTENSION *ext;
730 if ((ext = CertFindExtension(szOID_NAME_CONSTRAINTS, cert->cExtension,
731 cert->rgExtension)))
733 DWORD size;
735 CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
736 ext->Value.pbData, ext->Value.cbData,
737 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &info,
738 &size);
740 return info;
743 static BOOL CRYPT_IsValidNameConstraint(const CERT_NAME_CONSTRAINTS_INFO *info)
745 DWORD i;
746 BOOL ret = TRUE;
748 /* Check that none of the constraints specifies a minimum or a maximum.
749 * See RFC 5280, section 4.2.1.10:
750 * "Within this profile, the minimum and maximum fields are not used with
751 * any name forms, thus, the minimum MUST be zero, and maximum MUST be
752 * absent. However, if an application encounters a critical name
753 * constraints extension that specifies other values for minimum or
754 * maximum for a name form that appears in a subsequent certificate, the
755 * application MUST either process these fields or reject the
756 * certificate."
757 * Since it gives no guidance as to how to process these fields, we
758 * reject any name constraint that contains them.
760 for (i = 0; ret && i < info->cPermittedSubtree; i++)
761 if (info->rgPermittedSubtree[i].dwMinimum ||
762 info->rgPermittedSubtree[i].fMaximum)
764 TRACE_(chain)("found a minimum or maximum in permitted subtrees\n");
765 ret = FALSE;
767 for (i = 0; ret && i < info->cExcludedSubtree; i++)
768 if (info->rgExcludedSubtree[i].dwMinimum ||
769 info->rgExcludedSubtree[i].fMaximum)
771 TRACE_(chain)("found a minimum or maximum in excluded subtrees\n");
772 ret = FALSE;
774 return ret;
777 static void CRYPT_CheckChainNameConstraints(PCERT_SIMPLE_CHAIN chain)
779 int i, j;
781 /* Microsoft's implementation appears to violate RFC 3280: according to
782 * MSDN, the various CERT_TRUST_*_NAME_CONSTRAINT errors are set if a CA's
783 * name constraint is violated in the end cert. According to RFC 3280,
784 * the constraints should be checked against every subsequent certificate
785 * in the chain, not just the end cert.
786 * Microsoft's implementation also sets the name constraint errors on the
787 * certs whose constraints were violated, not on the certs that violated
788 * them.
789 * In order to be error-compatible with Microsoft's implementation, while
790 * still adhering to RFC 3280, I use a O(n ^ 2) algorithm to check name
791 * constraints.
793 for (i = chain->cElement - 1; i > 0; i--)
795 CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
797 if ((nameConstraints = CRYPT_GetNameConstraints(
798 chain->rgpElement[i]->pCertContext->pCertInfo)))
800 if (!CRYPT_IsValidNameConstraint(nameConstraints))
801 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
802 CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
803 else
805 for (j = i - 1; j >= 0; j--)
807 DWORD errorStatus = 0;
809 /* According to RFC 3280, self-signed certs don't have name
810 * constraints checked unless they're the end cert.
812 if (j == 0 || !CRYPT_IsCertificateSelfSigned(
813 chain->rgpElement[j]->pCertContext))
815 CRYPT_CheckNameConstraints(nameConstraints,
816 chain->rgpElement[j]->pCertContext->pCertInfo,
817 &errorStatus);
818 if (errorStatus)
819 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
820 errorStatus;
821 else
822 chain->rgpElement[i]->TrustStatus.dwInfoStatus |=
823 CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS;
827 LocalFree(nameConstraints);
832 static LPWSTR name_value_to_str(const CERT_NAME_BLOB *name)
834 DWORD len = cert_name_to_str_with_indent(X509_ASN_ENCODING, 0, name,
835 CERT_SIMPLE_NAME_STR, NULL, 0);
836 LPWSTR str = NULL;
838 if (len)
840 str = CryptMemAlloc(len * sizeof(WCHAR));
841 if (str)
842 cert_name_to_str_with_indent(X509_ASN_ENCODING, 0, name,
843 CERT_SIMPLE_NAME_STR, str, len);
845 return str;
848 static void dump_alt_name_entry(const CERT_ALT_NAME_ENTRY *entry)
850 LPWSTR str;
852 switch (entry->dwAltNameChoice)
854 case CERT_ALT_NAME_OTHER_NAME:
855 TRACE_(chain)("CERT_ALT_NAME_OTHER_NAME, oid = %s\n",
856 debugstr_a(entry->u.pOtherName->pszObjId));
857 break;
858 case CERT_ALT_NAME_RFC822_NAME:
859 TRACE_(chain)("CERT_ALT_NAME_RFC822_NAME: %s\n",
860 debugstr_w(entry->u.pwszRfc822Name));
861 break;
862 case CERT_ALT_NAME_DNS_NAME:
863 TRACE_(chain)("CERT_ALT_NAME_DNS_NAME: %s\n",
864 debugstr_w(entry->u.pwszDNSName));
865 break;
866 case CERT_ALT_NAME_DIRECTORY_NAME:
867 str = name_value_to_str(&entry->u.DirectoryName);
868 TRACE_(chain)("CERT_ALT_NAME_DIRECTORY_NAME: %s\n", debugstr_w(str));
869 CryptMemFree(str);
870 break;
871 case CERT_ALT_NAME_URL:
872 TRACE_(chain)("CERT_ALT_NAME_URL: %s\n", debugstr_w(entry->u.pwszURL));
873 break;
874 case CERT_ALT_NAME_IP_ADDRESS:
875 TRACE_(chain)("CERT_ALT_NAME_IP_ADDRESS: %d bytes\n",
876 entry->u.IPAddress.cbData);
877 break;
878 case CERT_ALT_NAME_REGISTERED_ID:
879 TRACE_(chain)("CERT_ALT_NAME_REGISTERED_ID: %s\n",
880 debugstr_a(entry->u.pszRegisteredID));
881 break;
882 default:
883 TRACE_(chain)("dwAltNameChoice = %d\n", entry->dwAltNameChoice);
887 static void dump_alt_name(LPCSTR type, const CERT_EXTENSION *ext)
889 CERT_ALT_NAME_INFO *name;
890 DWORD size;
892 TRACE_(chain)("%s:\n", type);
893 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
894 ext->Value.pbData, ext->Value.cbData,
895 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &name, &size))
897 DWORD i;
899 TRACE_(chain)("%d alt name entries:\n", name->cAltEntry);
900 for (i = 0; i < name->cAltEntry; i++)
901 dump_alt_name_entry(&name->rgAltEntry[i]);
902 LocalFree(name);
906 static void dump_basic_constraints(const CERT_EXTENSION *ext)
908 CERT_BASIC_CONSTRAINTS_INFO *info;
909 DWORD size = 0;
911 if (CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
912 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
913 NULL, &info, &size))
915 TRACE_(chain)("SubjectType: %02x\n", info->SubjectType.pbData[0]);
916 TRACE_(chain)("%s path length constraint\n",
917 info->fPathLenConstraint ? "has" : "doesn't have");
918 TRACE_(chain)("path length=%d\n", info->dwPathLenConstraint);
919 LocalFree(info);
923 static void dump_basic_constraints2(const CERT_EXTENSION *ext)
925 CERT_BASIC_CONSTRAINTS2_INFO constraints;
926 DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
928 if (CryptDecodeObjectEx(X509_ASN_ENCODING,
929 szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
930 0, NULL, &constraints, &size))
932 TRACE_(chain)("basic constraints:\n");
933 TRACE_(chain)("can%s be a CA\n", constraints.fCA ? "" : "not");
934 TRACE_(chain)("%s path length constraint\n",
935 constraints.fPathLenConstraint ? "has" : "doesn't have");
936 TRACE_(chain)("path length=%d\n", constraints.dwPathLenConstraint);
940 static void dump_key_usage(const CERT_EXTENSION *ext)
942 CRYPT_BIT_BLOB usage;
943 DWORD size = sizeof(usage);
945 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
946 ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
948 #define trace_usage_bit(bits, bit) \
949 if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
950 if (usage.cbData)
952 trace_usage_bit(usage.pbData[0], CERT_DIGITAL_SIGNATURE_KEY_USAGE);
953 trace_usage_bit(usage.pbData[0], CERT_NON_REPUDIATION_KEY_USAGE);
954 trace_usage_bit(usage.pbData[0], CERT_KEY_ENCIPHERMENT_KEY_USAGE);
955 trace_usage_bit(usage.pbData[0], CERT_DATA_ENCIPHERMENT_KEY_USAGE);
956 trace_usage_bit(usage.pbData[0], CERT_KEY_AGREEMENT_KEY_USAGE);
957 trace_usage_bit(usage.pbData[0], CERT_KEY_CERT_SIGN_KEY_USAGE);
958 trace_usage_bit(usage.pbData[0], CERT_CRL_SIGN_KEY_USAGE);
959 trace_usage_bit(usage.pbData[0], CERT_ENCIPHER_ONLY_KEY_USAGE);
961 #undef trace_usage_bit
962 if (usage.cbData > 1 && usage.pbData[1] & CERT_DECIPHER_ONLY_KEY_USAGE)
963 TRACE_(chain)("CERT_DECIPHER_ONLY_KEY_USAGE\n");
967 static void dump_general_subtree(const CERT_GENERAL_SUBTREE *subtree)
969 dump_alt_name_entry(&subtree->Base);
970 TRACE_(chain)("dwMinimum = %d, fMaximum = %d, dwMaximum = %d\n",
971 subtree->dwMinimum, subtree->fMaximum, subtree->dwMaximum);
974 static void dump_name_constraints(const CERT_EXTENSION *ext)
976 CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
977 DWORD size;
979 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
980 ext->Value.pbData, ext->Value.cbData,
981 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &nameConstraints,
982 &size))
984 DWORD i;
986 TRACE_(chain)("%d permitted subtrees:\n",
987 nameConstraints->cPermittedSubtree);
988 for (i = 0; i < nameConstraints->cPermittedSubtree; i++)
989 dump_general_subtree(&nameConstraints->rgPermittedSubtree[i]);
990 TRACE_(chain)("%d excluded subtrees:\n",
991 nameConstraints->cExcludedSubtree);
992 for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
993 dump_general_subtree(&nameConstraints->rgExcludedSubtree[i]);
994 LocalFree(nameConstraints);
998 static void dump_cert_policies(const CERT_EXTENSION *ext)
1000 CERT_POLICIES_INFO *policies;
1001 DWORD size;
1003 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_CERT_POLICIES,
1004 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1005 &policies, &size))
1007 DWORD i, j;
1009 TRACE_(chain)("%d policies:\n", policies->cPolicyInfo);
1010 for (i = 0; i < policies->cPolicyInfo; i++)
1012 TRACE_(chain)("policy identifier: %s\n",
1013 debugstr_a(policies->rgPolicyInfo[i].pszPolicyIdentifier));
1014 TRACE_(chain)("%d policy qualifiers:\n",
1015 policies->rgPolicyInfo[i].cPolicyQualifier);
1016 for (j = 0; j < policies->rgPolicyInfo[i].cPolicyQualifier; j++)
1017 TRACE_(chain)("%s\n", debugstr_a(
1018 policies->rgPolicyInfo[i].rgPolicyQualifier[j].
1019 pszPolicyQualifierId));
1021 LocalFree(policies);
1025 static void dump_enhanced_key_usage(const CERT_EXTENSION *ext)
1027 CERT_ENHKEY_USAGE *usage;
1028 DWORD size;
1030 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ENHANCED_KEY_USAGE,
1031 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1032 &usage, &size))
1034 DWORD i;
1036 TRACE_(chain)("%d usages:\n", usage->cUsageIdentifier);
1037 for (i = 0; i < usage->cUsageIdentifier; i++)
1038 TRACE_(chain)("%s\n", usage->rgpszUsageIdentifier[i]);
1039 LocalFree(usage);
1043 static void dump_netscape_cert_type(const CERT_EXTENSION *ext)
1045 CRYPT_BIT_BLOB usage;
1046 DWORD size = sizeof(usage);
1048 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
1049 ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
1051 #define trace_cert_type_bit(bits, bit) \
1052 if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
1053 if (usage.cbData)
1055 trace_cert_type_bit(usage.pbData[0],
1056 NETSCAPE_SSL_CLIENT_AUTH_CERT_TYPE);
1057 trace_cert_type_bit(usage.pbData[0],
1058 NETSCAPE_SSL_SERVER_AUTH_CERT_TYPE);
1059 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SMIME_CERT_TYPE);
1060 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SIGN_CERT_TYPE);
1061 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SSL_CA_CERT_TYPE);
1062 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SMIME_CA_CERT_TYPE);
1063 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SIGN_CA_CERT_TYPE);
1065 #undef trace_cert_type_bit
1069 static void dump_extension(const CERT_EXTENSION *ext)
1071 TRACE_(chain)("%s (%scritical)\n", debugstr_a(ext->pszObjId),
1072 ext->fCritical ? "" : "not ");
1073 if (!strcmp(ext->pszObjId, szOID_SUBJECT_ALT_NAME))
1074 dump_alt_name("subject alt name", ext);
1075 else if (!strcmp(ext->pszObjId, szOID_ISSUER_ALT_NAME))
1076 dump_alt_name("issuer alt name", ext);
1077 else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS))
1078 dump_basic_constraints(ext);
1079 else if (!strcmp(ext->pszObjId, szOID_KEY_USAGE))
1080 dump_key_usage(ext);
1081 else if (!strcmp(ext->pszObjId, szOID_SUBJECT_ALT_NAME2))
1082 dump_alt_name("subject alt name 2", ext);
1083 else if (!strcmp(ext->pszObjId, szOID_ISSUER_ALT_NAME2))
1084 dump_alt_name("issuer alt name 2", ext);
1085 else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS2))
1086 dump_basic_constraints2(ext);
1087 else if (!strcmp(ext->pszObjId, szOID_NAME_CONSTRAINTS))
1088 dump_name_constraints(ext);
1089 else if (!strcmp(ext->pszObjId, szOID_CERT_POLICIES))
1090 dump_cert_policies(ext);
1091 else if (!strcmp(ext->pszObjId, szOID_ENHANCED_KEY_USAGE))
1092 dump_enhanced_key_usage(ext);
1093 else if (!strcmp(ext->pszObjId, szOID_NETSCAPE_CERT_TYPE))
1094 dump_netscape_cert_type(ext);
1097 static LPCWSTR filetime_to_str(const FILETIME *time)
1099 static WCHAR date[80];
1100 WCHAR dateFmt[80]; /* sufficient for all versions of LOCALE_SSHORTDATE */
1101 SYSTEMTIME sysTime;
1103 if (!time) return NULL;
1105 GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, dateFmt,
1106 sizeof(dateFmt) / sizeof(dateFmt[0]));
1107 FileTimeToSystemTime(time, &sysTime);
1108 GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, date,
1109 sizeof(date) / sizeof(date[0]));
1110 return date;
1113 static void dump_element(PCCERT_CONTEXT cert)
1115 LPWSTR name = NULL;
1116 DWORD len, i;
1118 TRACE_(chain)("%p: version %d\n", cert, cert->pCertInfo->dwVersion);
1119 len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
1120 CERT_NAME_ISSUER_FLAG, NULL, NULL, 0);
1121 name = CryptMemAlloc(len * sizeof(WCHAR));
1122 if (name)
1124 CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
1125 CERT_NAME_ISSUER_FLAG, NULL, name, len);
1126 TRACE_(chain)("issued by %s\n", debugstr_w(name));
1127 CryptMemFree(name);
1129 len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
1130 NULL, 0);
1131 name = CryptMemAlloc(len * sizeof(WCHAR));
1132 if (name)
1134 CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
1135 name, len);
1136 TRACE_(chain)("issued to %s\n", debugstr_w(name));
1137 CryptMemFree(name);
1139 TRACE_(chain)("valid from %s to %s\n",
1140 debugstr_w(filetime_to_str(&cert->pCertInfo->NotBefore)),
1141 debugstr_w(filetime_to_str(&cert->pCertInfo->NotAfter)));
1142 TRACE_(chain)("%d extensions\n", cert->pCertInfo->cExtension);
1143 for (i = 0; i < cert->pCertInfo->cExtension; i++)
1144 dump_extension(&cert->pCertInfo->rgExtension[i]);
1147 static BOOL CRYPT_KeyUsageValid(PCertificateChainEngine engine,
1148 PCCERT_CONTEXT cert, BOOL isRoot, BOOL isCA, DWORD index)
1150 PCERT_EXTENSION ext;
1151 BOOL ret;
1152 BYTE usageBits = 0;
1154 ext = CertFindExtension(szOID_KEY_USAGE, cert->pCertInfo->cExtension,
1155 cert->pCertInfo->rgExtension);
1156 if (ext)
1158 CRYPT_BIT_BLOB usage;
1159 DWORD size = sizeof(usage);
1161 ret = CryptDecodeObjectEx(cert->dwCertEncodingType, X509_BITS,
1162 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL,
1163 &usage, &size);
1164 if (!ret)
1165 return FALSE;
1166 else if (usage.cbData > 2)
1168 /* The key usage extension only defines 9 bits => no more than 2
1169 * bytes are needed to encode all known usages.
1171 return FALSE;
1173 else
1175 /* The only bit relevant to chain validation is the keyCertSign
1176 * bit, which is always in the least significant byte of the
1177 * key usage bits.
1179 usageBits = usage.pbData[usage.cbData - 1];
1182 if (isCA)
1184 if (!ext)
1186 /* MS appears to violate RFC 5280, section 4.2.1.3 (Key Usage)
1187 * here. Quoting the RFC:
1188 * "This [key usage] extension MUST appear in certificates that
1189 * contain public keys that are used to validate digital signatures
1190 * on other public key certificates or CRLs."
1191 * MS appears to accept certs that do not contain key usage
1192 * extensions as CA certs. V1 and V2 certificates did not have
1193 * extensions, and many root certificates are V1 certificates, so
1194 * perhaps this is prudent. On the other hand, MS also accepts V3
1195 * certs without key usage extensions. We are more restrictive:
1196 * we accept locally installed V1 or V2 certs as CA certs.
1197 * We also accept a lack of key usage extension on root certs,
1198 * which is implied in RFC 5280, section 6.1: the trust anchor's
1199 * only requirement is that it was used to issue the next
1200 * certificate in the chain.
1202 if (isRoot)
1203 ret = TRUE;
1204 else if (cert->pCertInfo->dwVersion == CERT_V1 ||
1205 cert->pCertInfo->dwVersion == CERT_V2)
1207 PCCERT_CONTEXT localCert = CRYPT_FindCertInStore(
1208 engine->hWorld, cert);
1210 ret = localCert != NULL;
1211 CertFreeCertificateContext(localCert);
1213 else
1214 ret = FALSE;
1215 if (!ret)
1216 WARN_(chain)("no key usage extension on a CA cert\n");
1218 else
1220 if (!(usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
1222 WARN_(chain)("keyCertSign not asserted on a CA cert\n");
1223 ret = FALSE;
1225 else
1226 ret = TRUE;
1229 else
1231 if (ext && (usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
1233 WARN_(chain)("keyCertSign asserted on a non-CA cert\n");
1234 ret = FALSE;
1236 else
1237 ret = TRUE;
1239 return ret;
1242 static BOOL CRYPT_ExtendedKeyUsageValidForCA(PCCERT_CONTEXT cert)
1244 PCERT_EXTENSION ext;
1245 BOOL ret;
1247 /* RFC 5280, section 4.2.1.12: "In general, this extension will only
1248 * appear in end entity certificates." And, "If a certificate contains
1249 * both a key usage extension and an extended key usage extension, then
1250 * both extensions MUST be processed independently and the certificate MUST
1251 * only be used for a purpose consistent with both extensions." This seems
1252 * to imply that it should be checked if present, and ignored if not.
1253 * Unfortunately some CAs, e.g. the Thawte SGC CA, don't include the code
1254 * signing extended key usage, whereas they do include the keyCertSign
1255 * key usage. Thus, when checking for a CA, we only require the
1256 * code signing extended key usage if the extended key usage is critical.
1258 ext = CertFindExtension(szOID_ENHANCED_KEY_USAGE,
1259 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
1260 if (ext && ext->fCritical)
1262 CERT_ENHKEY_USAGE *usage;
1263 DWORD size;
1265 ret = CryptDecodeObjectEx(cert->dwCertEncodingType,
1266 X509_ENHANCED_KEY_USAGE, ext->Value.pbData, ext->Value.cbData,
1267 CRYPT_DECODE_ALLOC_FLAG, NULL, &usage, &size);
1268 if (ret)
1270 DWORD i;
1272 /* Explicitly require the code signing extended key usage for a CA
1273 * with an extended key usage extension. That is, don't assume
1274 * a cert is allowed to be a CA if it specifies the
1275 * anyExtendedKeyUsage usage oid. See again RFC 5280, section
1276 * 4.2.1.12: "Applications that require the presence of a
1277 * particular purpose MAY reject certificates that include the
1278 * anyExtendedKeyUsage OID but not the particular OID expected for
1279 * the application."
1281 ret = FALSE;
1282 for (i = 0; !ret && i < usage->cUsageIdentifier; i++)
1283 if (!strcmp(usage->rgpszUsageIdentifier[i],
1284 szOID_PKIX_KP_CODE_SIGNING))
1285 ret = TRUE;
1286 LocalFree(usage);
1289 else
1290 ret = TRUE;
1291 return ret;
1294 static BOOL CRYPT_CriticalExtensionsSupported(PCCERT_CONTEXT cert)
1296 BOOL ret = TRUE;
1297 DWORD i;
1299 for (i = 0; ret && i < cert->pCertInfo->cExtension; i++)
1301 if (cert->pCertInfo->rgExtension[i].fCritical)
1303 LPCSTR oid = cert->pCertInfo->rgExtension[i].pszObjId;
1305 if (!strcmp(oid, szOID_BASIC_CONSTRAINTS))
1306 ret = TRUE;
1307 else if (!strcmp(oid, szOID_BASIC_CONSTRAINTS2))
1308 ret = TRUE;
1309 else if (!strcmp(oid, szOID_NAME_CONSTRAINTS))
1310 ret = TRUE;
1311 else if (!strcmp(oid, szOID_KEY_USAGE))
1312 ret = TRUE;
1313 else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME))
1314 ret = TRUE;
1315 else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME2))
1316 ret = TRUE;
1317 else if (!strcmp(oid, szOID_ENHANCED_KEY_USAGE))
1318 ret = TRUE;
1319 else
1321 FIXME("unsupported critical extension %s\n",
1322 debugstr_a(oid));
1323 ret = FALSE;
1327 return ret;
1330 static BOOL CRYPT_IsCertVersionValid(PCCERT_CONTEXT cert)
1332 BOOL ret = TRUE;
1334 /* Checks whether the contents of the cert match the cert's version. */
1335 switch (cert->pCertInfo->dwVersion)
1337 case CERT_V1:
1338 /* A V1 cert may not contain unique identifiers. See RFC 5280,
1339 * section 4.1.2.8:
1340 * "These fields MUST only appear if the version is 2 or 3 (Section
1341 * 4.1.2.1). These fields MUST NOT appear if the version is 1."
1343 if (cert->pCertInfo->IssuerUniqueId.cbData ||
1344 cert->pCertInfo->SubjectUniqueId.cbData)
1345 ret = FALSE;
1346 /* A V1 cert may not contain extensions. See RFC 5280, section 4.1.2.9:
1347 * "This field MUST only appear if the version is 3 (Section 4.1.2.1)."
1349 if (cert->pCertInfo->cExtension)
1350 ret = FALSE;
1351 break;
1352 case CERT_V2:
1353 /* A V2 cert may not contain extensions. See RFC 5280, section 4.1.2.9:
1354 * "This field MUST only appear if the version is 3 (Section 4.1.2.1)."
1356 if (cert->pCertInfo->cExtension)
1357 ret = FALSE;
1358 break;
1359 case CERT_V3:
1360 /* Do nothing, all fields are allowed for V3 certs */
1361 break;
1362 default:
1363 WARN_(chain)("invalid cert version %d\n", cert->pCertInfo->dwVersion);
1364 ret = FALSE;
1366 return ret;
1369 static void CRYPT_CheckSimpleChain(PCertificateChainEngine engine,
1370 PCERT_SIMPLE_CHAIN chain, LPFILETIME time)
1372 PCERT_CHAIN_ELEMENT rootElement = chain->rgpElement[chain->cElement - 1];
1373 int i;
1374 BOOL pathLengthConstraintViolated = FALSE;
1375 CERT_BASIC_CONSTRAINTS2_INFO constraints = { FALSE, FALSE, 0 };
1377 TRACE_(chain)("checking chain with %d elements for time %s\n",
1378 chain->cElement, debugstr_w(filetime_to_str(time)));
1379 for (i = chain->cElement - 1; i >= 0; i--)
1381 BOOL isRoot;
1383 if (TRACE_ON(chain))
1384 dump_element(chain->rgpElement[i]->pCertContext);
1385 if (i == chain->cElement - 1)
1386 isRoot = CRYPT_IsCertificateSelfSigned(
1387 chain->rgpElement[i]->pCertContext);
1388 else
1389 isRoot = FALSE;
1390 if (!CRYPT_IsCertVersionValid(chain->rgpElement[i]->pCertContext))
1392 /* MS appears to accept certs whose versions don't match their
1393 * contents, so there isn't an appropriate error code.
1395 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1396 CERT_TRUST_INVALID_EXTENSION;
1398 if (CertVerifyTimeValidity(time,
1399 chain->rgpElement[i]->pCertContext->pCertInfo) != 0)
1400 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1401 CERT_TRUST_IS_NOT_TIME_VALID;
1402 if (i != 0)
1404 /* Check the signature of the cert this issued */
1405 if (!CryptVerifyCertificateSignatureEx(0, X509_ASN_ENCODING,
1406 CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT,
1407 (void *)chain->rgpElement[i - 1]->pCertContext,
1408 CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT,
1409 (void *)chain->rgpElement[i]->pCertContext, 0, NULL))
1410 chain->rgpElement[i - 1]->TrustStatus.dwErrorStatus |=
1411 CERT_TRUST_IS_NOT_SIGNATURE_VALID;
1412 /* Once a path length constraint has been violated, every remaining
1413 * CA cert's basic constraints is considered invalid.
1415 if (pathLengthConstraintViolated)
1416 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1417 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1418 else if (!CRYPT_CheckBasicConstraintsForCA(engine,
1419 chain->rgpElement[i]->pCertContext, &constraints, i - 1, isRoot,
1420 &pathLengthConstraintViolated))
1421 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1422 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1423 else if (constraints.fPathLenConstraint &&
1424 constraints.dwPathLenConstraint)
1426 /* This one's valid - decrement max length */
1427 constraints.dwPathLenConstraint--;
1430 else
1432 /* Check whether end cert has a basic constraints extension */
1433 if (!CRYPT_DecodeBasicConstraints(
1434 chain->rgpElement[i]->pCertContext, &constraints, FALSE))
1435 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1436 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1438 if (!CRYPT_KeyUsageValid(engine, chain->rgpElement[i]->pCertContext,
1439 isRoot, constraints.fCA, i))
1440 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1441 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
1442 if (i != 0)
1443 if (!CRYPT_ExtendedKeyUsageValidForCA(
1444 chain->rgpElement[i]->pCertContext))
1445 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1446 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
1447 if (CRYPT_IsSimpleChainCyclic(chain))
1449 /* If the chain is cyclic, then the path length constraints
1450 * are violated, because the chain is infinitely long.
1452 pathLengthConstraintViolated = TRUE;
1453 chain->TrustStatus.dwErrorStatus |=
1454 CERT_TRUST_IS_PARTIAL_CHAIN |
1455 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1457 /* Check whether every critical extension is supported */
1458 if (!CRYPT_CriticalExtensionsSupported(
1459 chain->rgpElement[i]->pCertContext))
1460 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1461 CERT_TRUST_INVALID_EXTENSION;
1462 CRYPT_CombineTrustStatus(&chain->TrustStatus,
1463 &chain->rgpElement[i]->TrustStatus);
1465 CRYPT_CheckChainNameConstraints(chain);
1466 if (CRYPT_IsCertificateSelfSigned(rootElement->pCertContext))
1468 rootElement->TrustStatus.dwInfoStatus |=
1469 CERT_TRUST_IS_SELF_SIGNED | CERT_TRUST_HAS_NAME_MATCH_ISSUER;
1470 CRYPT_CheckRootCert(engine->hRoot, rootElement);
1472 CRYPT_CombineTrustStatus(&chain->TrustStatus, &rootElement->TrustStatus);
1475 static PCCERT_CONTEXT CRYPT_GetIssuer(HCERTSTORE store, PCCERT_CONTEXT subject,
1476 PCCERT_CONTEXT prevIssuer, DWORD *infoStatus)
1478 PCCERT_CONTEXT issuer = NULL;
1479 PCERT_EXTENSION ext;
1480 DWORD size;
1482 *infoStatus = 0;
1483 if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
1484 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1486 CERT_AUTHORITY_KEY_ID_INFO *info;
1487 BOOL ret;
1489 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1490 X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
1491 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1492 &info, &size);
1493 if (ret)
1495 CERT_ID id;
1497 if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
1499 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1500 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
1501 sizeof(CERT_NAME_BLOB));
1502 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1503 &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
1504 issuer = CertFindCertificateInStore(store,
1505 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1506 prevIssuer);
1507 if (issuer)
1509 TRACE_(chain)("issuer found by issuer/serial number\n");
1510 *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
1513 else if (info->KeyId.cbData)
1515 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1516 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1517 issuer = CertFindCertificateInStore(store,
1518 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1519 prevIssuer);
1520 if (issuer)
1522 TRACE_(chain)("issuer found by key id\n");
1523 *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
1526 LocalFree(info);
1529 else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
1530 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1532 CERT_AUTHORITY_KEY_ID2_INFO *info;
1533 BOOL ret;
1535 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1536 X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
1537 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1538 &info, &size);
1539 if (ret)
1541 CERT_ID id;
1543 if (info->AuthorityCertIssuer.cAltEntry &&
1544 info->AuthorityCertSerialNumber.cbData)
1546 PCERT_ALT_NAME_ENTRY directoryName = NULL;
1547 DWORD i;
1549 for (i = 0; !directoryName &&
1550 i < info->AuthorityCertIssuer.cAltEntry; i++)
1551 if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
1552 == CERT_ALT_NAME_DIRECTORY_NAME)
1553 directoryName =
1554 &info->AuthorityCertIssuer.rgAltEntry[i];
1555 if (directoryName)
1557 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1558 memcpy(&id.u.IssuerSerialNumber.Issuer,
1559 &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
1560 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1561 &info->AuthorityCertSerialNumber,
1562 sizeof(CRYPT_INTEGER_BLOB));
1563 issuer = CertFindCertificateInStore(store,
1564 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1565 prevIssuer);
1566 if (issuer)
1568 TRACE_(chain)("issuer found by directory name\n");
1569 *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
1572 else
1573 FIXME("no supported name type in authority key id2\n");
1575 else if (info->KeyId.cbData)
1577 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1578 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1579 issuer = CertFindCertificateInStore(store,
1580 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1581 prevIssuer);
1582 if (issuer)
1584 TRACE_(chain)("issuer found by key id\n");
1585 *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
1588 LocalFree(info);
1591 else
1593 issuer = CertFindCertificateInStore(store,
1594 subject->dwCertEncodingType, 0, CERT_FIND_SUBJECT_NAME,
1595 &subject->pCertInfo->Issuer, prevIssuer);
1596 TRACE_(chain)("issuer found by name\n");
1597 *infoStatus = CERT_TRUST_HAS_NAME_MATCH_ISSUER;
1599 return issuer;
1602 /* Builds a simple chain by finding an issuer for the last cert in the chain,
1603 * until reaching a self-signed cert, or until no issuer can be found.
1605 static BOOL CRYPT_BuildSimpleChain(const CertificateChainEngine *engine,
1606 HCERTSTORE world, PCERT_SIMPLE_CHAIN chain)
1608 BOOL ret = TRUE;
1609 PCCERT_CONTEXT cert = chain->rgpElement[chain->cElement - 1]->pCertContext;
1611 while (ret && !CRYPT_IsSimpleChainCyclic(chain) &&
1612 !CRYPT_IsCertificateSelfSigned(cert))
1614 PCCERT_CONTEXT issuer = CRYPT_GetIssuer(world, cert, NULL,
1615 &chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
1617 if (issuer)
1619 ret = CRYPT_AddCertToSimpleChain(engine, chain, issuer,
1620 chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
1621 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it to
1622 * close the enumeration that found it
1624 CertFreeCertificateContext(issuer);
1625 cert = issuer;
1627 else
1629 TRACE_(chain)("Couldn't find issuer, halting chain creation\n");
1630 chain->TrustStatus.dwErrorStatus |= CERT_TRUST_IS_PARTIAL_CHAIN;
1631 break;
1634 return ret;
1637 static BOOL CRYPT_GetSimpleChainForCert(PCertificateChainEngine engine,
1638 HCERTSTORE world, PCCERT_CONTEXT cert, LPFILETIME pTime,
1639 PCERT_SIMPLE_CHAIN *ppChain)
1641 BOOL ret = FALSE;
1642 PCERT_SIMPLE_CHAIN chain;
1644 TRACE("(%p, %p, %p, %p)\n", engine, world, cert, pTime);
1646 chain = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
1647 if (chain)
1649 memset(chain, 0, sizeof(CERT_SIMPLE_CHAIN));
1650 chain->cbSize = sizeof(CERT_SIMPLE_CHAIN);
1651 ret = CRYPT_AddCertToSimpleChain(engine, chain, cert, 0);
1652 if (ret)
1654 ret = CRYPT_BuildSimpleChain(engine, world, chain);
1655 if (ret)
1656 CRYPT_CheckSimpleChain(engine, chain, pTime);
1658 if (!ret)
1660 CRYPT_FreeSimpleChain(chain);
1661 chain = NULL;
1663 *ppChain = chain;
1665 return ret;
1668 static BOOL CRYPT_BuildCandidateChainFromCert(HCERTCHAINENGINE hChainEngine,
1669 PCCERT_CONTEXT cert, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1670 PCertificateChain *ppChain)
1672 PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
1673 PCERT_SIMPLE_CHAIN simpleChain = NULL;
1674 HCERTSTORE world;
1675 BOOL ret;
1677 world = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
1678 CERT_STORE_CREATE_NEW_FLAG, NULL);
1679 CertAddStoreToCollection(world, engine->hWorld, 0, 0);
1680 if (hAdditionalStore)
1681 CertAddStoreToCollection(world, hAdditionalStore, 0, 0);
1682 /* FIXME: only simple chains are supported for now, as CTLs aren't
1683 * supported yet.
1685 if ((ret = CRYPT_GetSimpleChainForCert(engine, world, cert, pTime,
1686 &simpleChain)))
1688 PCertificateChain chain = CryptMemAlloc(sizeof(CertificateChain));
1690 if (chain)
1692 chain->ref = 1;
1693 chain->world = world;
1694 chain->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
1695 chain->context.TrustStatus = simpleChain->TrustStatus;
1696 chain->context.cChain = 1;
1697 chain->context.rgpChain = CryptMemAlloc(sizeof(PCERT_SIMPLE_CHAIN));
1698 chain->context.rgpChain[0] = simpleChain;
1699 chain->context.cLowerQualityChainContext = 0;
1700 chain->context.rgpLowerQualityChainContext = NULL;
1701 chain->context.fHasRevocationFreshnessTime = FALSE;
1702 chain->context.dwRevocationFreshnessTime = 0;
1704 else
1705 ret = FALSE;
1706 *ppChain = chain;
1708 return ret;
1711 /* Makes and returns a copy of chain, up to and including element iElement. */
1712 static PCERT_SIMPLE_CHAIN CRYPT_CopySimpleChainToElement(
1713 const CERT_SIMPLE_CHAIN *chain, DWORD iElement)
1715 PCERT_SIMPLE_CHAIN copy = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
1717 if (copy)
1719 memset(copy, 0, sizeof(CERT_SIMPLE_CHAIN));
1720 copy->cbSize = sizeof(CERT_SIMPLE_CHAIN);
1721 copy->rgpElement =
1722 CryptMemAlloc((iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
1723 if (copy->rgpElement)
1725 DWORD i;
1726 BOOL ret = TRUE;
1728 memset(copy->rgpElement, 0,
1729 (iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
1730 for (i = 0; ret && i <= iElement; i++)
1732 PCERT_CHAIN_ELEMENT element =
1733 CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
1735 if (element)
1737 *element = *chain->rgpElement[i];
1738 element->pCertContext = CertDuplicateCertificateContext(
1739 chain->rgpElement[i]->pCertContext);
1740 /* Reset the trust status of the copied element, it'll get
1741 * rechecked after the new chain is done.
1743 memset(&element->TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
1744 copy->rgpElement[copy->cElement++] = element;
1746 else
1747 ret = FALSE;
1749 if (!ret)
1751 for (i = 0; i <= iElement; i++)
1752 CryptMemFree(copy->rgpElement[i]);
1753 CryptMemFree(copy->rgpElement);
1754 CryptMemFree(copy);
1755 copy = NULL;
1758 else
1760 CryptMemFree(copy);
1761 copy = NULL;
1764 return copy;
1767 static void CRYPT_FreeLowerQualityChains(PCertificateChain chain)
1769 DWORD i;
1771 for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
1772 CertFreeCertificateChain(chain->context.rgpLowerQualityChainContext[i]);
1773 CryptMemFree(chain->context.rgpLowerQualityChainContext);
1774 chain->context.cLowerQualityChainContext = 0;
1775 chain->context.rgpLowerQualityChainContext = NULL;
1778 static void CRYPT_FreeChainContext(PCertificateChain chain)
1780 DWORD i;
1782 CRYPT_FreeLowerQualityChains(chain);
1783 for (i = 0; i < chain->context.cChain; i++)
1784 CRYPT_FreeSimpleChain(chain->context.rgpChain[i]);
1785 CryptMemFree(chain->context.rgpChain);
1786 CertCloseStore(chain->world, 0);
1787 CryptMemFree(chain);
1790 /* Makes and returns a copy of chain, up to and including element iElement of
1791 * simple chain iChain.
1793 static PCertificateChain CRYPT_CopyChainToElement(PCertificateChain chain,
1794 DWORD iChain, DWORD iElement)
1796 PCertificateChain copy = CryptMemAlloc(sizeof(CertificateChain));
1798 if (copy)
1800 copy->ref = 1;
1801 copy->world = CertDuplicateStore(chain->world);
1802 copy->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
1803 /* Leave the trust status of the copied chain unset, it'll get
1804 * rechecked after the new chain is done.
1806 memset(&copy->context.TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
1807 copy->context.cLowerQualityChainContext = 0;
1808 copy->context.rgpLowerQualityChainContext = NULL;
1809 copy->context.fHasRevocationFreshnessTime = FALSE;
1810 copy->context.dwRevocationFreshnessTime = 0;
1811 copy->context.rgpChain = CryptMemAlloc(
1812 (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
1813 if (copy->context.rgpChain)
1815 BOOL ret = TRUE;
1816 DWORD i;
1818 memset(copy->context.rgpChain, 0,
1819 (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
1820 if (iChain)
1822 for (i = 0; ret && iChain && i < iChain - 1; i++)
1824 copy->context.rgpChain[i] =
1825 CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
1826 chain->context.rgpChain[i]->cElement - 1);
1827 if (!copy->context.rgpChain[i])
1828 ret = FALSE;
1831 else
1832 i = 0;
1833 if (ret)
1835 copy->context.rgpChain[i] =
1836 CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
1837 iElement);
1838 if (!copy->context.rgpChain[i])
1839 ret = FALSE;
1841 if (!ret)
1843 CRYPT_FreeChainContext(copy);
1844 copy = NULL;
1846 else
1847 copy->context.cChain = iChain + 1;
1849 else
1851 CryptMemFree(copy);
1852 copy = NULL;
1855 return copy;
1858 static PCertificateChain CRYPT_BuildAlternateContextFromChain(
1859 HCERTCHAINENGINE hChainEngine, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1860 PCertificateChain chain)
1862 PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
1863 PCertificateChain alternate;
1865 TRACE("(%p, %p, %p, %p)\n", hChainEngine, pTime, hAdditionalStore, chain);
1867 /* Always start with the last "lower quality" chain to ensure a consistent
1868 * order of alternate creation:
1870 if (chain->context.cLowerQualityChainContext)
1871 chain = (PCertificateChain)chain->context.rgpLowerQualityChainContext[
1872 chain->context.cLowerQualityChainContext - 1];
1873 /* A chain with only one element can't have any alternates */
1874 if (chain->context.cChain <= 1 && chain->context.rgpChain[0]->cElement <= 1)
1875 alternate = NULL;
1876 else
1878 DWORD i, j, infoStatus;
1879 PCCERT_CONTEXT alternateIssuer = NULL;
1881 alternate = NULL;
1882 for (i = 0; !alternateIssuer && i < chain->context.cChain; i++)
1883 for (j = 0; !alternateIssuer &&
1884 j < chain->context.rgpChain[i]->cElement - 1; j++)
1886 PCCERT_CONTEXT subject =
1887 chain->context.rgpChain[i]->rgpElement[j]->pCertContext;
1888 PCCERT_CONTEXT prevIssuer = CertDuplicateCertificateContext(
1889 chain->context.rgpChain[i]->rgpElement[j + 1]->pCertContext);
1891 alternateIssuer = CRYPT_GetIssuer(prevIssuer->hCertStore,
1892 subject, prevIssuer, &infoStatus);
1894 if (alternateIssuer)
1896 i--;
1897 j--;
1898 alternate = CRYPT_CopyChainToElement(chain, i, j);
1899 if (alternate)
1901 BOOL ret = CRYPT_AddCertToSimpleChain(engine,
1902 alternate->context.rgpChain[i], alternateIssuer, infoStatus);
1904 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it
1905 * to close the enumeration that found it
1907 CertFreeCertificateContext(alternateIssuer);
1908 if (ret)
1910 ret = CRYPT_BuildSimpleChain(engine, alternate->world,
1911 alternate->context.rgpChain[i]);
1912 if (ret)
1913 CRYPT_CheckSimpleChain(engine,
1914 alternate->context.rgpChain[i], pTime);
1915 CRYPT_CombineTrustStatus(&alternate->context.TrustStatus,
1916 &alternate->context.rgpChain[i]->TrustStatus);
1918 if (!ret)
1920 CRYPT_FreeChainContext(alternate);
1921 alternate = NULL;
1926 TRACE("%p\n", alternate);
1927 return alternate;
1930 #define CHAIN_QUALITY_SIGNATURE_VALID 0x16
1931 #define CHAIN_QUALITY_TIME_VALID 8
1932 #define CHAIN_QUALITY_COMPLETE_CHAIN 4
1933 #define CHAIN_QUALITY_BASIC_CONSTRAINTS 2
1934 #define CHAIN_QUALITY_TRUSTED_ROOT 1
1936 #define CHAIN_QUALITY_HIGHEST \
1937 CHAIN_QUALITY_SIGNATURE_VALID | CHAIN_QUALITY_TIME_VALID | \
1938 CHAIN_QUALITY_COMPLETE_CHAIN | CHAIN_QUALITY_BASIC_CONSTRAINTS | \
1939 CHAIN_QUALITY_TRUSTED_ROOT
1941 #define IS_TRUST_ERROR_SET(TrustStatus, bits) \
1942 (TrustStatus)->dwErrorStatus & (bits)
1944 static DWORD CRYPT_ChainQuality(const CertificateChain *chain)
1946 DWORD quality = CHAIN_QUALITY_HIGHEST;
1948 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1949 CERT_TRUST_IS_UNTRUSTED_ROOT))
1950 quality &= ~CHAIN_QUALITY_TRUSTED_ROOT;
1951 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1952 CERT_TRUST_INVALID_BASIC_CONSTRAINTS))
1953 quality &= ~CHAIN_QUALITY_BASIC_CONSTRAINTS;
1954 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1955 CERT_TRUST_IS_PARTIAL_CHAIN))
1956 quality &= ~CHAIN_QUALITY_COMPLETE_CHAIN;
1957 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1958 CERT_TRUST_IS_NOT_TIME_VALID | CERT_TRUST_IS_NOT_TIME_NESTED))
1959 quality &= ~CHAIN_QUALITY_TIME_VALID;
1960 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1961 CERT_TRUST_IS_NOT_SIGNATURE_VALID))
1962 quality &= ~CHAIN_QUALITY_SIGNATURE_VALID;
1963 return quality;
1966 /* Chooses the highest quality chain among chain and its "lower quality"
1967 * alternate chains. Returns the highest quality chain, with all other
1968 * chains as lower quality chains of it.
1970 static PCertificateChain CRYPT_ChooseHighestQualityChain(
1971 PCertificateChain chain)
1973 DWORD i;
1975 /* There are always only two chains being considered: chain, and an
1976 * alternate at chain->rgpLowerQualityChainContext[i]. If the alternate
1977 * has a higher quality than chain, the alternate gets assigned the lower
1978 * quality contexts, with chain taking the alternate's place among the
1979 * lower quality contexts.
1981 for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
1983 PCertificateChain alternate =
1984 (PCertificateChain)chain->context.rgpLowerQualityChainContext[i];
1986 if (CRYPT_ChainQuality(alternate) > CRYPT_ChainQuality(chain))
1988 alternate->context.cLowerQualityChainContext =
1989 chain->context.cLowerQualityChainContext;
1990 alternate->context.rgpLowerQualityChainContext =
1991 chain->context.rgpLowerQualityChainContext;
1992 alternate->context.rgpLowerQualityChainContext[i] =
1993 (PCCERT_CHAIN_CONTEXT)chain;
1994 chain->context.cLowerQualityChainContext = 0;
1995 chain->context.rgpLowerQualityChainContext = NULL;
1996 chain = alternate;
1999 return chain;
2002 static BOOL CRYPT_AddAlternateChainToChain(PCertificateChain chain,
2003 const CertificateChain *alternate)
2005 BOOL ret;
2007 if (chain->context.cLowerQualityChainContext)
2008 chain->context.rgpLowerQualityChainContext =
2009 CryptMemRealloc(chain->context.rgpLowerQualityChainContext,
2010 (chain->context.cLowerQualityChainContext + 1) *
2011 sizeof(PCCERT_CHAIN_CONTEXT));
2012 else
2013 chain->context.rgpLowerQualityChainContext =
2014 CryptMemAlloc(sizeof(PCCERT_CHAIN_CONTEXT));
2015 if (chain->context.rgpLowerQualityChainContext)
2017 chain->context.rgpLowerQualityChainContext[
2018 chain->context.cLowerQualityChainContext++] =
2019 (PCCERT_CHAIN_CONTEXT)alternate;
2020 ret = TRUE;
2022 else
2023 ret = FALSE;
2024 return ret;
2027 static PCERT_CHAIN_ELEMENT CRYPT_FindIthElementInChain(
2028 const CERT_CHAIN_CONTEXT *chain, DWORD i)
2030 DWORD j, iElement;
2031 PCERT_CHAIN_ELEMENT element = NULL;
2033 for (j = 0, iElement = 0; !element && j < chain->cChain; j++)
2035 if (iElement + chain->rgpChain[j]->cElement < i)
2036 iElement += chain->rgpChain[j]->cElement;
2037 else
2038 element = chain->rgpChain[j]->rgpElement[i - iElement];
2040 return element;
2043 typedef struct _CERT_CHAIN_PARA_NO_EXTRA_FIELDS {
2044 DWORD cbSize;
2045 CERT_USAGE_MATCH RequestedUsage;
2046 } CERT_CHAIN_PARA_NO_EXTRA_FIELDS, *PCERT_CHAIN_PARA_NO_EXTRA_FIELDS;
2048 static void CRYPT_VerifyChainRevocation(PCERT_CHAIN_CONTEXT chain,
2049 LPFILETIME pTime, const CERT_CHAIN_PARA *pChainPara, DWORD chainFlags)
2051 DWORD cContext;
2053 if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_END_CERT)
2054 cContext = 1;
2055 else if ((chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN) ||
2056 (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT))
2058 DWORD i;
2060 for (i = 0, cContext = 0; i < chain->cChain; i++)
2062 if (i < chain->cChain - 1 ||
2063 chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN)
2064 cContext += chain->rgpChain[i]->cElement;
2065 else
2066 cContext += chain->rgpChain[i]->cElement - 1;
2069 else
2070 cContext = 0;
2071 if (cContext)
2073 PCCERT_CONTEXT *contexts =
2074 CryptMemAlloc(cContext * sizeof(PCCERT_CONTEXT *));
2076 if (contexts)
2078 DWORD i, j, iContext, revocationFlags;
2079 CERT_REVOCATION_PARA revocationPara = { sizeof(revocationPara), 0 };
2080 CERT_REVOCATION_STATUS revocationStatus =
2081 { sizeof(revocationStatus), 0 };
2082 BOOL ret;
2084 for (i = 0, iContext = 0; iContext < cContext && i < chain->cChain;
2085 i++)
2087 for (j = 0; iContext < cContext &&
2088 j < chain->rgpChain[i]->cElement; j++)
2089 contexts[iContext++] =
2090 chain->rgpChain[i]->rgpElement[j]->pCertContext;
2092 revocationFlags = CERT_VERIFY_REV_CHAIN_FLAG;
2093 if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY)
2094 revocationFlags |= CERT_VERIFY_CACHE_ONLY_BASED_REVOCATION;
2095 if (chainFlags & CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT)
2096 revocationFlags |= CERT_VERIFY_REV_ACCUMULATIVE_TIMEOUT_FLAG;
2097 revocationPara.pftTimeToUse = pTime;
2098 if (pChainPara->cbSize == sizeof(CERT_CHAIN_PARA))
2100 revocationPara.dwUrlRetrievalTimeout =
2101 pChainPara->dwUrlRetrievalTimeout;
2102 revocationPara.fCheckFreshnessTime =
2103 pChainPara->fCheckRevocationFreshnessTime;
2104 revocationPara.dwFreshnessTime =
2105 pChainPara->dwRevocationFreshnessTime;
2107 ret = CertVerifyRevocation(X509_ASN_ENCODING,
2108 CERT_CONTEXT_REVOCATION_TYPE, cContext, (void **)contexts,
2109 revocationFlags, &revocationPara, &revocationStatus);
2110 if (!ret)
2112 PCERT_CHAIN_ELEMENT element =
2113 CRYPT_FindIthElementInChain(chain, revocationStatus.dwIndex);
2114 DWORD error;
2116 switch (revocationStatus.dwError)
2118 case CRYPT_E_NO_REVOCATION_CHECK:
2119 case CRYPT_E_NO_REVOCATION_DLL:
2120 case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
2121 error = CERT_TRUST_REVOCATION_STATUS_UNKNOWN;
2122 break;
2123 case CRYPT_E_REVOCATION_OFFLINE:
2124 error = CERT_TRUST_IS_OFFLINE_REVOCATION;
2125 break;
2126 case CRYPT_E_REVOKED:
2127 error = CERT_TRUST_IS_REVOKED;
2128 break;
2129 default:
2130 WARN("unmapped error %08x\n", revocationStatus.dwError);
2131 error = 0;
2133 if (element)
2135 /* FIXME: set element's pRevocationInfo member */
2136 element->TrustStatus.dwErrorStatus |= error;
2138 chain->TrustStatus.dwErrorStatus |= error;
2140 CryptMemFree(contexts);
2145 static void dump_usage_match(LPCSTR name, const CERT_USAGE_MATCH *usageMatch)
2147 DWORD i;
2149 TRACE_(chain)("%s: %s\n", name,
2150 usageMatch->dwType == USAGE_MATCH_TYPE_AND ? "AND" : "OR");
2151 for (i = 0; i < usageMatch->Usage.cUsageIdentifier; i++)
2152 TRACE_(chain)("%s\n", usageMatch->Usage.rgpszUsageIdentifier[i]);
2155 static void dump_chain_para(const CERT_CHAIN_PARA *pChainPara)
2157 TRACE_(chain)("%d\n", pChainPara->cbSize);
2158 if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA_NO_EXTRA_FIELDS))
2159 dump_usage_match("RequestedUsage", &pChainPara->RequestedUsage);
2160 if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA))
2162 dump_usage_match("RequestedIssuancePolicy",
2163 &pChainPara->RequestedIssuancePolicy);
2164 TRACE_(chain)("%d\n", pChainPara->dwUrlRetrievalTimeout);
2165 TRACE_(chain)("%d\n", pChainPara->fCheckRevocationFreshnessTime);
2166 TRACE_(chain)("%d\n", pChainPara->dwRevocationFreshnessTime);
2170 BOOL WINAPI CertGetCertificateChain(HCERTCHAINENGINE hChainEngine,
2171 PCCERT_CONTEXT pCertContext, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
2172 PCERT_CHAIN_PARA pChainPara, DWORD dwFlags, LPVOID pvReserved,
2173 PCCERT_CHAIN_CONTEXT* ppChainContext)
2175 BOOL ret;
2176 PCertificateChain chain = NULL;
2178 TRACE("(%p, %p, %p, %p, %p, %08x, %p, %p)\n", hChainEngine, pCertContext,
2179 pTime, hAdditionalStore, pChainPara, dwFlags, pvReserved, ppChainContext);
2181 if (ppChainContext)
2182 *ppChainContext = NULL;
2183 if (!pChainPara)
2185 SetLastError(E_INVALIDARG);
2186 return FALSE;
2188 if (!pCertContext->pCertInfo->SignatureAlgorithm.pszObjId)
2190 SetLastError(ERROR_INVALID_DATA);
2191 return FALSE;
2194 if (!hChainEngine)
2195 hChainEngine = CRYPT_GetDefaultChainEngine();
2196 if (TRACE_ON(chain))
2197 dump_chain_para(pChainPara);
2198 /* FIXME: what about HCCE_LOCAL_MACHINE? */
2199 ret = CRYPT_BuildCandidateChainFromCert(hChainEngine, pCertContext, pTime,
2200 hAdditionalStore, &chain);
2201 if (ret)
2203 PCertificateChain alternate = NULL;
2204 PCERT_CHAIN_CONTEXT pChain;
2206 do {
2207 alternate = CRYPT_BuildAlternateContextFromChain(hChainEngine,
2208 pTime, hAdditionalStore, chain);
2210 /* Alternate contexts are added as "lower quality" contexts of
2211 * chain, to avoid loops in alternate chain creation.
2212 * The highest-quality chain is chosen at the end.
2214 if (alternate)
2215 ret = CRYPT_AddAlternateChainToChain(chain, alternate);
2216 } while (ret && alternate);
2217 chain = CRYPT_ChooseHighestQualityChain(chain);
2218 if (!(dwFlags & CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS))
2219 CRYPT_FreeLowerQualityChains(chain);
2220 pChain = (PCERT_CHAIN_CONTEXT)chain;
2221 CRYPT_VerifyChainRevocation(pChain, pTime, pChainPara, dwFlags);
2222 if (ppChainContext)
2223 *ppChainContext = pChain;
2224 else
2225 CertFreeCertificateChain(pChain);
2227 TRACE("returning %d\n", ret);
2228 return ret;
2231 PCCERT_CHAIN_CONTEXT WINAPI CertDuplicateCertificateChain(
2232 PCCERT_CHAIN_CONTEXT pChainContext)
2234 PCertificateChain chain = (PCertificateChain)pChainContext;
2236 TRACE("(%p)\n", pChainContext);
2238 if (chain)
2239 InterlockedIncrement(&chain->ref);
2240 return pChainContext;
2243 VOID WINAPI CertFreeCertificateChain(PCCERT_CHAIN_CONTEXT pChainContext)
2245 PCertificateChain chain = (PCertificateChain)pChainContext;
2247 TRACE("(%p)\n", pChainContext);
2249 if (chain)
2251 if (InterlockedDecrement(&chain->ref) == 0)
2252 CRYPT_FreeChainContext(chain);
2256 static void find_element_with_error(PCCERT_CHAIN_CONTEXT chain, DWORD error,
2257 LONG *iChain, LONG *iElement)
2259 DWORD i, j;
2261 for (i = 0; i < chain->cChain; i++)
2262 for (j = 0; j < chain->rgpChain[i]->cElement; j++)
2263 if (chain->rgpChain[i]->rgpElement[j]->TrustStatus.dwErrorStatus &
2264 error)
2266 *iChain = i;
2267 *iElement = j;
2268 return;
2272 static BOOL WINAPI verify_base_policy(LPCSTR szPolicyOID,
2273 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2274 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2276 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2277 if (pChainContext->TrustStatus.dwErrorStatus &
2278 CERT_TRUST_IS_NOT_SIGNATURE_VALID)
2280 pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
2281 find_element_with_error(pChainContext,
2282 CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
2283 &pPolicyStatus->lElementIndex);
2285 else if (pChainContext->TrustStatus.dwErrorStatus &
2286 CERT_TRUST_IS_UNTRUSTED_ROOT)
2288 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
2289 find_element_with_error(pChainContext,
2290 CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
2291 &pPolicyStatus->lElementIndex);
2293 else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
2295 pPolicyStatus->dwError = CERT_E_CHAINING;
2296 find_element_with_error(pChainContext, CERT_TRUST_IS_CYCLIC,
2297 &pPolicyStatus->lChainIndex, &pPolicyStatus->lElementIndex);
2298 /* For a cyclic chain, which element is a cycle isn't meaningful */
2299 pPolicyStatus->lElementIndex = -1;
2301 else
2302 pPolicyStatus->dwError = NO_ERROR;
2303 return TRUE;
2306 static BYTE msTestPubKey1[] = {
2307 0x30,0x47,0x02,0x40,0x81,0x55,0x22,0xb9,0x8a,0xa4,0x6f,0xed,0xd6,0xe7,0xd9,
2308 0x66,0x0f,0x55,0xbc,0xd7,0xcd,0xd5,0xbc,0x4e,0x40,0x02,0x21,0xa2,0xb1,0xf7,
2309 0x87,0x30,0x85,0x5e,0xd2,0xf2,0x44,0xb9,0xdc,0x9b,0x75,0xb6,0xfb,0x46,0x5f,
2310 0x42,0xb6,0x9d,0x23,0x36,0x0b,0xde,0x54,0x0f,0xcd,0xbd,0x1f,0x99,0x2a,0x10,
2311 0x58,0x11,0xcb,0x40,0xcb,0xb5,0xa7,0x41,0x02,0x03,0x01,0x00,0x01 };
2312 static BYTE msTestPubKey2[] = {
2313 0x30,0x47,0x02,0x40,0x9c,0x50,0x05,0x1d,0xe2,0x0e,0x4c,0x53,0xd8,0xd9,0xb5,
2314 0xe5,0xfd,0xe9,0xe3,0xad,0x83,0x4b,0x80,0x08,0xd9,0xdc,0xe8,0xe8,0x35,0xf8,
2315 0x11,0xf1,0xe9,0x9b,0x03,0x7a,0x65,0x64,0x76,0x35,0xce,0x38,0x2c,0xf2,0xb6,
2316 0x71,0x9e,0x06,0xd9,0xbf,0xbb,0x31,0x69,0xa3,0xf6,0x30,0xa0,0x78,0x7b,0x18,
2317 0xdd,0x50,0x4d,0x79,0x1e,0xeb,0x61,0xc1,0x02,0x03,0x01,0x00,0x01 };
2319 static BOOL WINAPI verify_authenticode_policy(LPCSTR szPolicyOID,
2320 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2321 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2323 BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
2324 pPolicyStatus);
2326 if (ret && pPolicyStatus->dwError == CERT_E_UNTRUSTEDROOT)
2328 CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
2329 BOOL isMSTestRoot = FALSE;
2330 PCCERT_CONTEXT failingCert =
2331 pChainContext->rgpChain[pPolicyStatus->lChainIndex]->
2332 rgpElement[pPolicyStatus->lElementIndex]->pCertContext;
2333 DWORD i;
2334 CRYPT_DATA_BLOB keyBlobs[] = {
2335 { sizeof(msTestPubKey1), msTestPubKey1 },
2336 { sizeof(msTestPubKey2), msTestPubKey2 },
2339 /* Check whether the root is an MS test root */
2340 for (i = 0; !isMSTestRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
2341 i++)
2343 msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
2344 msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
2345 if (CertComparePublicKeyInfo(
2346 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
2347 &failingCert->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
2348 isMSTestRoot = TRUE;
2350 if (isMSTestRoot)
2351 pPolicyStatus->dwError = CERT_E_UNTRUSTEDTESTROOT;
2353 return ret;
2356 static BOOL WINAPI verify_basic_constraints_policy(LPCSTR szPolicyOID,
2357 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2358 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2360 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2361 if (pChainContext->TrustStatus.dwErrorStatus &
2362 CERT_TRUST_INVALID_BASIC_CONSTRAINTS)
2364 pPolicyStatus->dwError = TRUST_E_BASIC_CONSTRAINTS;
2365 find_element_with_error(pChainContext,
2366 CERT_TRUST_INVALID_BASIC_CONSTRAINTS, &pPolicyStatus->lChainIndex,
2367 &pPolicyStatus->lElementIndex);
2369 else
2370 pPolicyStatus->dwError = NO_ERROR;
2371 return TRUE;
2374 static BOOL match_dns_to_subject_alt_name(PCERT_EXTENSION ext,
2375 LPCWSTR server_name)
2377 BOOL matches = FALSE;
2378 CERT_ALT_NAME_INFO *subjectName;
2379 DWORD size;
2381 TRACE_(chain)("%s\n", debugstr_w(server_name));
2382 /* This could be spoofed by the embedded NULL vulnerability, since the
2383 * returned CERT_ALT_NAME_INFO doesn't have a way to indicate the
2384 * encoded length of a name. Fortunately CryptDecodeObjectEx fails if
2385 * the encoded form of the name contains a NULL.
2387 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
2388 ext->Value.pbData, ext->Value.cbData,
2389 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2390 &subjectName, &size))
2392 DWORD i;
2394 /* RFC 5280 states that multiple instances of each name type may exist,
2395 * in section 4.2.1.6:
2396 * "Multiple name forms, and multiple instances of each name form,
2397 * MAY be included."
2398 * It doesn't specify the behavior in such cases, but both RFC 2818
2399 * and RFC 2595 explicitly accept a certificate if any name matches.
2401 for (i = 0; !matches && i < subjectName->cAltEntry; i++)
2403 if (subjectName->rgAltEntry[i].dwAltNameChoice ==
2404 CERT_ALT_NAME_DNS_NAME)
2406 TRACE_(chain)("dNSName: %s\n", debugstr_w(
2407 subjectName->rgAltEntry[i].u.pwszDNSName));
2408 if (!strcmpiW(server_name,
2409 subjectName->rgAltEntry[i].u.pwszDNSName))
2410 matches = TRUE;
2413 LocalFree(subjectName);
2415 return matches;
2418 static BOOL find_matching_domain_component(CERT_NAME_INFO *name,
2419 LPCWSTR component)
2421 BOOL matches = FALSE;
2422 DWORD i, j;
2424 for (i = 0; !matches && i < name->cRDN; i++)
2425 for (j = 0; j < name->rgRDN[i].cRDNAttr; j++)
2426 if (!strcmp(szOID_DOMAIN_COMPONENT,
2427 name->rgRDN[i].rgRDNAttr[j].pszObjId))
2429 PCERT_RDN_ATTR attr;
2431 attr = &name->rgRDN[i].rgRDNAttr[j];
2432 /* Compare with memicmpW rather than strcmpiW in order to avoid
2433 * a match with a string with an embedded NULL. The component
2434 * must match one domain component attribute's entire string
2435 * value with a case-insensitive match.
2437 matches = !memicmpW(component, (LPWSTR)attr->Value.pbData,
2438 attr->Value.cbData / sizeof(WCHAR));
2440 return matches;
2443 static BOOL match_domain_component(LPCWSTR allowed_component, DWORD allowed_len,
2444 LPCWSTR server_component, DWORD server_len, BOOL allow_wildcards,
2445 BOOL *see_wildcard)
2447 LPCWSTR allowed_ptr, server_ptr;
2448 BOOL matches = TRUE;
2450 *see_wildcard = FALSE;
2451 if (server_len < allowed_len)
2453 WARN_(chain)("domain component %s too short for %s\n",
2454 debugstr_wn(server_component, server_len),
2455 debugstr_wn(allowed_component, allowed_len));
2456 /* A domain component can't contain a wildcard character, so a domain
2457 * component shorter than the allowed string can't produce a match.
2459 return FALSE;
2461 for (allowed_ptr = allowed_component, server_ptr = server_component;
2462 matches && allowed_ptr - allowed_component < allowed_len;
2463 allowed_ptr++, server_ptr++)
2465 if (*allowed_ptr == '*')
2467 if (allowed_ptr - allowed_component < allowed_len - 1)
2469 WARN_(chain)("non-wildcard characters after wildcard not supported\n");
2470 matches = FALSE;
2472 else if (!allow_wildcards)
2474 WARN_(chain)("wildcard after non-wildcard component\n");
2475 matches = FALSE;
2477 else
2479 /* the preceding characters must have matched, so the rest of
2480 * the component also matches.
2482 *see_wildcard = TRUE;
2483 break;
2486 matches = tolowerW(*allowed_ptr) == tolowerW(*server_ptr);
2488 if (matches && server_ptr - server_component < server_len)
2490 /* If there are unmatched characters in the server domain component,
2491 * the server domain only matches if the allowed string ended in a '*'.
2493 matches = *allowed_ptr == '*';
2495 return matches;
2498 static BOOL match_common_name(LPCWSTR server_name, PCERT_RDN_ATTR nameAttr)
2500 LPCWSTR allowed = (LPCWSTR)nameAttr->Value.pbData;
2501 LPCWSTR allowed_component = allowed;
2502 DWORD allowed_len = nameAttr->Value.cbData / sizeof(WCHAR);
2503 LPCWSTR server_component = server_name;
2504 DWORD server_len = strlenW(server_name);
2505 BOOL matches = TRUE, allow_wildcards = TRUE;
2507 TRACE_(chain)("CN = %s\n", debugstr_wn(allowed_component, allowed_len));
2509 /* From RFC 2818 (HTTP over TLS), section 3.1:
2510 * "Names may contain the wildcard character * which is considered to match
2511 * any single domain name component or component fragment. E.g.,
2512 * *.a.com matches foo.a.com but not bar.foo.a.com. f*.com matches foo.com
2513 * but not bar.com."
2515 * And from RFC 2595 (Using TLS with IMAP, POP3 and ACAP), section 2.4:
2516 * "A "*" wildcard character MAY be used as the left-most name component in
2517 * the certificate. For example, *.example.com would match a.example.com,
2518 * foo.example.com, etc. but would not match example.com."
2520 * There are other protocols which use TLS, and none of them is
2521 * authoritative. This accepts certificates in common usage, e.g.
2522 * *.domain.com matches www.domain.com but not domain.com, and
2523 * www*.domain.com matches www1.domain.com but not mail.domain.com.
2525 do {
2526 LPCWSTR allowed_dot, server_dot;
2528 allowed_dot = memchrW(allowed_component, '.',
2529 allowed_len - (allowed_component - allowed));
2530 server_dot = memchrW(server_component, '.',
2531 server_len - (server_component - server_name));
2532 /* The number of components must match */
2533 if ((!allowed_dot && server_dot) || (allowed_dot && !server_dot))
2535 if (!allowed_dot)
2536 WARN_(chain)("%s: too many components for CN=%s\n",
2537 debugstr_w(server_name), debugstr_wn(allowed, allowed_len));
2538 else
2539 WARN_(chain)("%s: not enough components for CN=%s\n",
2540 debugstr_w(server_name), debugstr_wn(allowed, allowed_len));
2541 matches = FALSE;
2543 else
2545 LPCWSTR allowed_end, server_end;
2546 BOOL has_wildcard;
2548 allowed_end = allowed_dot ? allowed_dot : allowed + allowed_len;
2549 server_end = server_dot ? server_dot : server_name + server_len;
2550 matches = match_domain_component(allowed_component,
2551 allowed_end - allowed_component, server_component,
2552 server_end - server_component, allow_wildcards, &has_wildcard);
2553 /* Once a non-wildcard component is seen, no wildcard components
2554 * may follow
2556 if (!has_wildcard)
2557 allow_wildcards = FALSE;
2558 if (matches)
2560 allowed_component = allowed_dot ? allowed_dot + 1 : allowed_end;
2561 server_component = server_dot ? server_dot + 1 : server_end;
2564 } while (matches && allowed_component &&
2565 allowed_component - allowed < allowed_len &&
2566 server_component && server_component - server_name < server_len);
2567 TRACE_(chain)("returning %d\n", matches);
2568 return matches;
2571 static BOOL match_dns_to_subject_dn(PCCERT_CONTEXT cert, LPCWSTR server_name)
2573 BOOL matches = FALSE;
2574 CERT_NAME_INFO *name;
2575 DWORD size;
2577 TRACE_(chain)("%s\n", debugstr_w(server_name));
2578 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_UNICODE_NAME,
2579 cert->pCertInfo->Subject.pbData, cert->pCertInfo->Subject.cbData,
2580 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2581 &name, &size))
2583 /* If the subject distinguished name contains any name components,
2584 * make sure all of them are present.
2586 if (CertFindRDNAttr(szOID_DOMAIN_COMPONENT, name))
2588 LPCWSTR ptr = server_name;
2590 matches = TRUE;
2591 do {
2592 LPCWSTR dot = strchrW(ptr, '.'), end;
2593 /* 254 is the maximum DNS label length, see RFC 1035 */
2594 WCHAR component[255];
2595 DWORD len;
2597 end = dot ? dot : ptr + strlenW(ptr);
2598 len = end - ptr;
2599 if (len >= sizeof(component) / sizeof(component[0]))
2601 WARN_(chain)("domain component %s too long\n",
2602 debugstr_wn(ptr, len));
2603 matches = FALSE;
2605 else
2607 memcpy(component, ptr, len * sizeof(WCHAR));
2608 component[len] = 0;
2609 matches = find_matching_domain_component(name, component);
2611 ptr = dot ? dot + 1 : end;
2612 } while (matches && ptr && *ptr);
2614 else
2616 PCERT_RDN_ATTR attr;
2618 /* If the certificate isn't using a DN attribute in the name, make
2619 * make sure the common name matches.
2621 if ((attr = CertFindRDNAttr(szOID_COMMON_NAME, name)))
2622 matches = match_common_name(server_name, attr);
2624 LocalFree(name);
2626 return matches;
2629 static BOOL WINAPI verify_ssl_policy(LPCSTR szPolicyOID,
2630 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2631 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2633 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2634 if (pChainContext->TrustStatus.dwErrorStatus &
2635 CERT_TRUST_IS_NOT_SIGNATURE_VALID)
2637 pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
2638 find_element_with_error(pChainContext,
2639 CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
2640 &pPolicyStatus->lElementIndex);
2642 else if (pChainContext->TrustStatus.dwErrorStatus &
2643 CERT_TRUST_IS_UNTRUSTED_ROOT)
2645 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
2646 find_element_with_error(pChainContext,
2647 CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
2648 &pPolicyStatus->lElementIndex);
2650 else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
2652 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
2653 find_element_with_error(pChainContext,
2654 CERT_TRUST_IS_CYCLIC, &pPolicyStatus->lChainIndex,
2655 &pPolicyStatus->lElementIndex);
2656 /* For a cyclic chain, which element is a cycle isn't meaningful */
2657 pPolicyStatus->lElementIndex = -1;
2659 else if (pChainContext->TrustStatus.dwErrorStatus &
2660 CERT_TRUST_IS_NOT_TIME_VALID)
2662 pPolicyStatus->dwError = CERT_E_EXPIRED;
2663 find_element_with_error(pChainContext,
2664 CERT_TRUST_IS_NOT_TIME_VALID, &pPolicyStatus->lChainIndex,
2665 &pPolicyStatus->lElementIndex);
2667 else
2668 pPolicyStatus->dwError = NO_ERROR;
2669 /* We only need bother checking whether the name in the end certificate
2670 * matches if the chain is otherwise okay.
2672 if (!pPolicyStatus->dwError && pPolicyPara &&
2673 pPolicyPara->cbSize >= sizeof(CERT_CHAIN_POLICY_PARA))
2675 HTTPSPolicyCallbackData *sslPara = pPolicyPara->pvExtraPolicyPara;
2677 if (sslPara && sslPara->u.cbSize >= sizeof(HTTPSPolicyCallbackData))
2679 if (sslPara->dwAuthType == AUTHTYPE_SERVER &&
2680 sslPara->pwszServerName)
2682 PCCERT_CONTEXT cert;
2683 PCERT_EXTENSION altNameExt;
2684 BOOL matches;
2686 cert = pChainContext->rgpChain[0]->rgpElement[0]->pCertContext;
2687 altNameExt = get_subject_alt_name_ext(cert->pCertInfo);
2688 /* If the alternate name extension exists, the name it contains
2689 * is bound to the certificate, so make sure the name matches
2690 * it. Otherwise, look for the server name in the subject
2691 * distinguished name. RFC5280, section 4.2.1.6:
2692 * "Whenever such identities are to be bound into a
2693 * certificate, the subject alternative name (or issuer
2694 * alternative name) extension MUST be used; however, a DNS
2695 * name MAY also be represented in the subject field using the
2696 * domainComponent attribute."
2698 if (altNameExt)
2699 matches = match_dns_to_subject_alt_name(altNameExt,
2700 sslPara->pwszServerName);
2701 else
2702 matches = match_dns_to_subject_dn(cert,
2703 sslPara->pwszServerName);
2704 if (!matches)
2706 pPolicyStatus->dwError = CERT_E_CN_NO_MATCH;
2707 pPolicyStatus->lChainIndex = 0;
2708 pPolicyStatus->lElementIndex = 0;
2713 return TRUE;
2716 static BYTE msPubKey1[] = {
2717 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xdf,0x08,0xba,0xe3,0x3f,0x6e,
2718 0x64,0x9b,0xf5,0x89,0xaf,0x28,0x96,0x4a,0x07,0x8f,0x1b,0x2e,0x8b,0x3e,0x1d,
2719 0xfc,0xb8,0x80,0x69,0xa3,0xa1,0xce,0xdb,0xdf,0xb0,0x8e,0x6c,0x89,0x76,0x29,
2720 0x4f,0xca,0x60,0x35,0x39,0xad,0x72,0x32,0xe0,0x0b,0xae,0x29,0x3d,0x4c,0x16,
2721 0xd9,0x4b,0x3c,0x9d,0xda,0xc5,0xd3,0xd1,0x09,0xc9,0x2c,0x6f,0xa6,0xc2,0x60,
2722 0x53,0x45,0xdd,0x4b,0xd1,0x55,0xcd,0x03,0x1c,0xd2,0x59,0x56,0x24,0xf3,0xe5,
2723 0x78,0xd8,0x07,0xcc,0xd8,0xb3,0x1f,0x90,0x3f,0xc0,0x1a,0x71,0x50,0x1d,0x2d,
2724 0xa7,0x12,0x08,0x6d,0x7c,0xb0,0x86,0x6c,0xc7,0xba,0x85,0x32,0x07,0xe1,0x61,
2725 0x6f,0xaf,0x03,0xc5,0x6d,0xe5,0xd6,0xa1,0x8f,0x36,0xf6,0xc1,0x0b,0xd1,0x3e,
2726 0x69,0x97,0x48,0x72,0xc9,0x7f,0xa4,0xc8,0xc2,0x4a,0x4c,0x7e,0xa1,0xd1,0x94,
2727 0xa6,0xd7,0xdc,0xeb,0x05,0x46,0x2e,0xb8,0x18,0xb4,0x57,0x1d,0x86,0x49,0xdb,
2728 0x69,0x4a,0x2c,0x21,0xf5,0x5e,0x0f,0x54,0x2d,0x5a,0x43,0xa9,0x7a,0x7e,0x6a,
2729 0x8e,0x50,0x4d,0x25,0x57,0xa1,0xbf,0x1b,0x15,0x05,0x43,0x7b,0x2c,0x05,0x8d,
2730 0xbd,0x3d,0x03,0x8c,0x93,0x22,0x7d,0x63,0xea,0x0a,0x57,0x05,0x06,0x0a,0xdb,
2731 0x61,0x98,0x65,0x2d,0x47,0x49,0xa8,0xe7,0xe6,0x56,0x75,0x5c,0xb8,0x64,0x08,
2732 0x63,0xa9,0x30,0x40,0x66,0xb2,0xf9,0xb6,0xe3,0x34,0xe8,0x67,0x30,0xe1,0x43,
2733 0x0b,0x87,0xff,0xc9,0xbe,0x72,0x10,0x5e,0x23,0xf0,0x9b,0xa7,0x48,0x65,0xbf,
2734 0x09,0x88,0x7b,0xcd,0x72,0xbc,0x2e,0x79,0x9b,0x7b,0x02,0x03,0x01,0x00,0x01 };
2735 static BYTE msPubKey2[] = {
2736 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xa9,0x02,0xbd,0xc1,0x70,0xe6,
2737 0x3b,0xf2,0x4e,0x1b,0x28,0x9f,0x97,0x78,0x5e,0x30,0xea,0xa2,0xa9,0x8d,0x25,
2738 0x5f,0xf8,0xfe,0x95,0x4c,0xa3,0xb7,0xfe,0x9d,0xa2,0x20,0x3e,0x7c,0x51,0xa2,
2739 0x9b,0xa2,0x8f,0x60,0x32,0x6b,0xd1,0x42,0x64,0x79,0xee,0xac,0x76,0xc9,0x54,
2740 0xda,0xf2,0xeb,0x9c,0x86,0x1c,0x8f,0x9f,0x84,0x66,0xb3,0xc5,0x6b,0x7a,0x62,
2741 0x23,0xd6,0x1d,0x3c,0xde,0x0f,0x01,0x92,0xe8,0x96,0xc4,0xbf,0x2d,0x66,0x9a,
2742 0x9a,0x68,0x26,0x99,0xd0,0x3a,0x2c,0xbf,0x0c,0xb5,0x58,0x26,0xc1,0x46,0xe7,
2743 0x0a,0x3e,0x38,0x96,0x2c,0xa9,0x28,0x39,0xa8,0xec,0x49,0x83,0x42,0xe3,0x84,
2744 0x0f,0xbb,0x9a,0x6c,0x55,0x61,0xac,0x82,0x7c,0xa1,0x60,0x2d,0x77,0x4c,0xe9,
2745 0x99,0xb4,0x64,0x3b,0x9a,0x50,0x1c,0x31,0x08,0x24,0x14,0x9f,0xa9,0xe7,0x91,
2746 0x2b,0x18,0xe6,0x3d,0x98,0x63,0x14,0x60,0x58,0x05,0x65,0x9f,0x1d,0x37,0x52,
2747 0x87,0xf7,0xa7,0xef,0x94,0x02,0xc6,0x1b,0xd3,0xbf,0x55,0x45,0xb3,0x89,0x80,
2748 0xbf,0x3a,0xec,0x54,0x94,0x4e,0xae,0xfd,0xa7,0x7a,0x6d,0x74,0x4e,0xaf,0x18,
2749 0xcc,0x96,0x09,0x28,0x21,0x00,0x57,0x90,0x60,0x69,0x37,0xbb,0x4b,0x12,0x07,
2750 0x3c,0x56,0xff,0x5b,0xfb,0xa4,0x66,0x0a,0x08,0xa6,0xd2,0x81,0x56,0x57,0xef,
2751 0xb6,0x3b,0x5e,0x16,0x81,0x77,0x04,0xda,0xf6,0xbe,0xae,0x80,0x95,0xfe,0xb0,
2752 0xcd,0x7f,0xd6,0xa7,0x1a,0x72,0x5c,0x3c,0xca,0xbc,0xf0,0x08,0xa3,0x22,0x30,
2753 0xb3,0x06,0x85,0xc9,0xb3,0x20,0x77,0x13,0x85,0xdf,0x02,0x03,0x01,0x00,0x01 };
2754 static BYTE msPubKey3[] = {
2755 0x30,0x82,0x02,0x0a,0x02,0x82,0x02,0x01,0x00,0xf3,0x5d,0xfa,0x80,0x67,0xd4,
2756 0x5a,0xa7,0xa9,0x0c,0x2c,0x90,0x20,0xd0,0x35,0x08,0x3c,0x75,0x84,0xcd,0xb7,
2757 0x07,0x89,0x9c,0x89,0xda,0xde,0xce,0xc3,0x60,0xfa,0x91,0x68,0x5a,0x9e,0x94,
2758 0x71,0x29,0x18,0x76,0x7c,0xc2,0xe0,0xc8,0x25,0x76,0x94,0x0e,0x58,0xfa,0x04,
2759 0x34,0x36,0xe6,0xdf,0xaf,0xf7,0x80,0xba,0xe9,0x58,0x0b,0x2b,0x93,0xe5,0x9d,
2760 0x05,0xe3,0x77,0x22,0x91,0xf7,0x34,0x64,0x3c,0x22,0x91,0x1d,0x5e,0xe1,0x09,
2761 0x90,0xbc,0x14,0xfe,0xfc,0x75,0x58,0x19,0xe1,0x79,0xb7,0x07,0x92,0xa3,0xae,
2762 0x88,0x59,0x08,0xd8,0x9f,0x07,0xca,0x03,0x58,0xfc,0x68,0x29,0x6d,0x32,0xd7,
2763 0xd2,0xa8,0xcb,0x4b,0xfc,0xe1,0x0b,0x48,0x32,0x4f,0xe6,0xeb,0xb8,0xad,0x4f,
2764 0xe4,0x5c,0x6f,0x13,0x94,0x99,0xdb,0x95,0xd5,0x75,0xdb,0xa8,0x1a,0xb7,0x94,
2765 0x91,0xb4,0x77,0x5b,0xf5,0x48,0x0c,0x8f,0x6a,0x79,0x7d,0x14,0x70,0x04,0x7d,
2766 0x6d,0xaf,0x90,0xf5,0xda,0x70,0xd8,0x47,0xb7,0xbf,0x9b,0x2f,0x6c,0xe7,0x05,
2767 0xb7,0xe1,0x11,0x60,0xac,0x79,0x91,0x14,0x7c,0xc5,0xd6,0xa6,0xe4,0xe1,0x7e,
2768 0xd5,0xc3,0x7e,0xe5,0x92,0xd2,0x3c,0x00,0xb5,0x36,0x82,0xde,0x79,0xe1,0x6d,
2769 0xf3,0xb5,0x6e,0xf8,0x9f,0x33,0xc9,0xcb,0x52,0x7d,0x73,0x98,0x36,0xdb,0x8b,
2770 0xa1,0x6b,0xa2,0x95,0x97,0x9b,0xa3,0xde,0xc2,0x4d,0x26,0xff,0x06,0x96,0x67,
2771 0x25,0x06,0xc8,0xe7,0xac,0xe4,0xee,0x12,0x33,0x95,0x31,0x99,0xc8,0x35,0x08,
2772 0x4e,0x34,0xca,0x79,0x53,0xd5,0xb5,0xbe,0x63,0x32,0x59,0x40,0x36,0xc0,0xa5,
2773 0x4e,0x04,0x4d,0x3d,0xdb,0x5b,0x07,0x33,0xe4,0x58,0xbf,0xef,0x3f,0x53,0x64,
2774 0xd8,0x42,0x59,0x35,0x57,0xfd,0x0f,0x45,0x7c,0x24,0x04,0x4d,0x9e,0xd6,0x38,
2775 0x74,0x11,0x97,0x22,0x90,0xce,0x68,0x44,0x74,0x92,0x6f,0xd5,0x4b,0x6f,0xb0,
2776 0x86,0xe3,0xc7,0x36,0x42,0xa0,0xd0,0xfc,0xc1,0xc0,0x5a,0xf9,0xa3,0x61,0xb9,
2777 0x30,0x47,0x71,0x96,0x0a,0x16,0xb0,0x91,0xc0,0x42,0x95,0xef,0x10,0x7f,0x28,
2778 0x6a,0xe3,0x2a,0x1f,0xb1,0xe4,0xcd,0x03,0x3f,0x77,0x71,0x04,0xc7,0x20,0xfc,
2779 0x49,0x0f,0x1d,0x45,0x88,0xa4,0xd7,0xcb,0x7e,0x88,0xad,0x8e,0x2d,0xec,0x45,
2780 0xdb,0xc4,0x51,0x04,0xc9,0x2a,0xfc,0xec,0x86,0x9e,0x9a,0x11,0x97,0x5b,0xde,
2781 0xce,0x53,0x88,0xe6,0xe2,0xb7,0xfd,0xac,0x95,0xc2,0x28,0x40,0xdb,0xef,0x04,
2782 0x90,0xdf,0x81,0x33,0x39,0xd9,0xb2,0x45,0xa5,0x23,0x87,0x06,0xa5,0x55,0x89,
2783 0x31,0xbb,0x06,0x2d,0x60,0x0e,0x41,0x18,0x7d,0x1f,0x2e,0xb5,0x97,0xcb,0x11,
2784 0xeb,0x15,0xd5,0x24,0xa5,0x94,0xef,0x15,0x14,0x89,0xfd,0x4b,0x73,0xfa,0x32,
2785 0x5b,0xfc,0xd1,0x33,0x00,0xf9,0x59,0x62,0x70,0x07,0x32,0xea,0x2e,0xab,0x40,
2786 0x2d,0x7b,0xca,0xdd,0x21,0x67,0x1b,0x30,0x99,0x8f,0x16,0xaa,0x23,0xa8,0x41,
2787 0xd1,0xb0,0x6e,0x11,0x9b,0x36,0xc4,0xde,0x40,0x74,0x9c,0xe1,0x58,0x65,0xc1,
2788 0x60,0x1e,0x7a,0x5b,0x38,0xc8,0x8f,0xbb,0x04,0x26,0x7c,0xd4,0x16,0x40,0xe5,
2789 0xb6,0x6b,0x6c,0xaa,0x86,0xfd,0x00,0xbf,0xce,0xc1,0x35,0x02,0x03,0x01,0x00,
2790 0x01 };
2792 static BOOL WINAPI verify_ms_root_policy(LPCSTR szPolicyOID,
2793 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2794 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2796 BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
2797 pPolicyStatus);
2799 if (ret && !pPolicyStatus->dwError)
2801 CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
2802 BOOL isMSRoot = FALSE;
2803 DWORD i;
2804 CRYPT_DATA_BLOB keyBlobs[] = {
2805 { sizeof(msPubKey1), msPubKey1 },
2806 { sizeof(msPubKey2), msPubKey2 },
2807 { sizeof(msPubKey3), msPubKey3 },
2809 PCERT_SIMPLE_CHAIN rootChain =
2810 pChainContext->rgpChain[pChainContext->cChain -1 ];
2811 PCCERT_CONTEXT root =
2812 rootChain->rgpElement[rootChain->cElement - 1]->pCertContext;
2814 for (i = 0; !isMSRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
2815 i++)
2817 msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
2818 msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
2819 if (CertComparePublicKeyInfo(
2820 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
2821 &root->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
2822 isMSRoot = TRUE;
2824 if (isMSRoot)
2825 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = 0;
2827 return ret;
2830 typedef BOOL (WINAPI *CertVerifyCertificateChainPolicyFunc)(LPCSTR szPolicyOID,
2831 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2832 PCERT_CHAIN_POLICY_STATUS pPolicyStatus);
2834 BOOL WINAPI CertVerifyCertificateChainPolicy(LPCSTR szPolicyOID,
2835 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2836 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2838 static HCRYPTOIDFUNCSET set = NULL;
2839 BOOL ret = FALSE;
2840 CertVerifyCertificateChainPolicyFunc verifyPolicy = NULL;
2841 HCRYPTOIDFUNCADDR hFunc = NULL;
2843 TRACE("(%s, %p, %p, %p)\n", debugstr_a(szPolicyOID), pChainContext,
2844 pPolicyPara, pPolicyStatus);
2846 if (!HIWORD(szPolicyOID))
2848 switch (LOWORD(szPolicyOID))
2850 case LOWORD(CERT_CHAIN_POLICY_BASE):
2851 verifyPolicy = verify_base_policy;
2852 break;
2853 case LOWORD(CERT_CHAIN_POLICY_AUTHENTICODE):
2854 verifyPolicy = verify_authenticode_policy;
2855 break;
2856 case LOWORD(CERT_CHAIN_POLICY_SSL):
2857 verifyPolicy = verify_ssl_policy;
2858 break;
2859 case LOWORD(CERT_CHAIN_POLICY_BASIC_CONSTRAINTS):
2860 verifyPolicy = verify_basic_constraints_policy;
2861 break;
2862 case LOWORD(CERT_CHAIN_POLICY_MICROSOFT_ROOT):
2863 verifyPolicy = verify_ms_root_policy;
2864 break;
2865 default:
2866 FIXME("unimplemented for %d\n", LOWORD(szPolicyOID));
2869 if (!verifyPolicy)
2871 if (!set)
2872 set = CryptInitOIDFunctionSet(
2873 CRYPT_OID_VERIFY_CERTIFICATE_CHAIN_POLICY_FUNC, 0);
2874 CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING, szPolicyOID, 0,
2875 (void **)&verifyPolicy, &hFunc);
2877 if (verifyPolicy)
2878 ret = verifyPolicy(szPolicyOID, pChainContext, pPolicyPara,
2879 pPolicyStatus);
2880 if (hFunc)
2881 CryptFreeOIDFunctionAddress(hFunc, 0);
2882 TRACE("returning %d (%08x)\n", ret, pPolicyStatus->dwError);
2883 return ret;