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
20 #define NONAMELESSUNION
23 #define CERT_CHAIN_PARA_HAS_EXTRA_FIELDS
24 #define CERT_REVOCATION_PARA_HAS_EXTRA_FIELDS
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
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)
58 for (i = 0; i < cStores; i++)
59 CertAddStoreToCollection(collection, stores[i], 0, 0);
62 static inline void CRYPT_CloseStores(DWORD cStores, HCERTSTORE *stores)
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,
76 PCCERT_CONTEXT matching = NULL;
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);
90 static BOOL CRYPT_CheckRestrictedRoot(HCERTSTORE store)
96 HCERTSTORE rootStore = CertOpenSystemStoreW(0, rootW);
97 PCCERT_CONTEXT cert = NULL, check;
100 cert = CertEnumCertificatesInStore(store, cert);
103 if (!(check = CRYPT_FindCertInStore(rootStore, cert)))
106 CertFreeCertificateContext(check);
108 } while (ret && cert);
110 CertFreeCertificateContext(cert);
111 CertCloseStore(rootStore, 0);
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));
127 HCERTSTORE worldStores[4];
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]),
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;
150 engine->CycleDetectionModulus = DEFAULT_CYCLE_MODULUS;
155 BOOL WINAPI CertCreateCertificateChainEngine(PCERT_CHAIN_ENGINE_CONFIG pConfig,
156 HCERTCHAINENGINE *phChainEngine)
160 TRACE("(%p, %p)\n", pConfig, phChainEngine);
162 if (pConfig->cbSize != sizeof(*pConfig))
164 SetLastError(E_INVALIDARG);
167 *phChainEngine = NULL;
168 ret = CRYPT_CheckRestrictedRoot(pConfig->hRestrictedRoot);
172 HCERTCHAINENGINE engine;
174 if (pConfig->hRestrictedRoot)
175 root = CertDuplicateStore(pConfig->hRestrictedRoot);
177 root = CertOpenSystemStoreW(0, rootW);
178 engine = CRYPT_CreateChainEngine(root, pConfig);
181 *phChainEngine = engine;
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,
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;
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))
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]);
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)
272 return chain->rgpElement[chain->cElement - 1]->TrustStatus.dwErrorStatus
273 & CERT_TRUST_IS_CYCLIC;
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
286 chainStatus->dwInfoStatus |= (elementStatus->dwInfoStatus & 0xfffffff0);
289 static BOOL CRYPT_AddCertToSimpleChain(const CertificateChainEngine *engine,
290 PCERT_SIMPLE_CHAIN chain, PCCERT_CONTEXT cert, DWORD subjectInfoStatus)
293 PCERT_CHAIN_ELEMENT element = CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
297 if (!chain->cElement)
298 chain->rgpElement = CryptMemAlloc(sizeof(PCERT_CHAIN_ELEMENT));
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
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);
325 CryptMemFree(element);
330 static void CRYPT_FreeSimpleChain(PCERT_SIMPLE_CHAIN chain)
334 for (i = 0; i < chain->cElement; i++)
335 CRYPT_FreeChainElement(chain->rgpElement[i]);
336 CryptMemFree(chain->rgpElement);
340 static void CRYPT_CheckTrustedStatus(HCERTSTORE hRoot,
341 PCERT_CHAIN_ELEMENT rootElement)
343 PCCERT_CONTEXT trustedRoot = CRYPT_FindCertInStore(hRoot,
344 rootElement->pCertContext);
347 rootElement->TrustStatus.dwErrorStatus |=
348 CERT_TRUST_IS_UNTRUSTED_ROOT;
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)
379 PCERT_EXTENSION ext = CertFindExtension(szOID_BASIC_CONSTRAINTS,
380 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
382 constraints->fPathLenConstraint = FALSE;
385 CERT_BASIC_CONSTRAINTS_INFO *info;
388 ret = CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
389 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
393 if (info->SubjectType.cbData == 1)
395 info->SubjectType.pbData[0] & CERT_CA_SUBJECT_FLAG;
401 ext = CertFindExtension(szOID_BASIC_CONSTRAINTS2,
402 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
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);
412 constraints->fCA = defaultIfNotSpecified;
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
439 * Returns TRUE if the element can be a CA, and the length of the remaining
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;
451 else if (cert->pCertInfo->dwVersion == CERT_V1 ||
452 cert->pCertInfo->dwVersion == CERT_V2)
455 DWORD size = sizeof(hash);
457 if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID,
460 CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
461 PCCERT_CONTEXT localCert = CertFindCertificateInStore(
462 engine->hWorld, cert->dwCertEncodingType, 0, CERT_FIND_SHA1_HASH,
467 CertFreeCertificateContext(localCert);
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)
514 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
517 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
520 else if (constraint[0] == '.')
522 if (lstrlenW(name) > lstrlenW(constraint))
523 match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
527 match = !lstrcmpiW(constraint, name);
531 static BOOL rfc822_name_matches(LPCWSTR constraint, LPCWSTR name,
532 DWORD *trustErrorStatus)
537 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
540 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
543 else if ((at = strchrW(constraint, '@')))
544 match = !lstrcmpiW(constraint, name);
547 if ((at = strchrW(name, '@')))
548 match = url_matches(constraint, at + 1, trustErrorStatus);
550 match = !lstrcmpiW(constraint, name);
555 static BOOL dns_name_matches(LPCWSTR constraint, LPCWSTR name,
556 DWORD *trustErrorStatus)
560 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
563 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
566 else if (lstrlenW(name) >= lstrlenW(constraint))
567 match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
569 /* else: name is too short, no match */
574 static BOOL ip_address_matches(const CRYPT_DATA_BLOB *constraint,
575 const CRYPT_DATA_BLOB *name, DWORD *trustErrorStatus)
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;
605 subnet = constraint->pbData;
606 mask = constraint->pbData + 16;
609 for (i = 0; match && i < 16; i++)
610 if ((subnet[i] & mask[i]) != (addr[i] & mask[i]))
613 /* else: name is wrong size, no 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)
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);
636 case CERT_ALT_NAME_DNS_NAME:
637 match = dns_name_matches(constraint->u.pwszURL,
638 subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
640 case CERT_ALT_NAME_URL:
641 match = url_matches(constraint->u.pwszURL,
642 subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
644 case CERT_ALT_NAME_IP_ADDRESS:
645 match = ip_address_matches(&constraint->u.IPAddress,
646 &subjectName->rgAltEntry[i].u.IPAddress, trustErrorStatus);
648 case CERT_ALT_NAME_DIRECTORY_NAME:
650 ERR("name choice %d unsupported in this context\n",
651 constraint->dwAltNameChoice);
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)
664 ext = CertFindExtension(szOID_SUBJECT_ALT_NAME2,
665 cert->cExtension, cert->rgExtension);
667 ext = CertFindExtension(szOID_SUBJECT_ALT_NAME,
668 cert->cExtension, cert->rgExtension);
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);
683 CERT_ALT_NAME_INFO *subjectName;
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))
693 for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
694 CRYPT_FindMatchingNameEntry(
695 &nameConstraints->rgExcludedSubtree[i].Base, subjectName,
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,
702 CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT,
703 CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT);
704 LocalFree(subjectName);
708 CERT_TRUST_INVALID_EXTENSION |
709 CERT_TRUST_INVALID_NAME_CONSTRAINTS;
713 if (nameConstraints->cPermittedSubtree)
715 CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT |
716 CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
717 if (nameConstraints->cExcludedSubtree)
719 CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
724 /* Gets cert's name constraints, if any. Free with LocalFree. */
725 static CERT_NAME_CONSTRAINTS_INFO *CRYPT_GetNameConstraints(CERT_INFO *cert)
727 CERT_NAME_CONSTRAINTS_INFO *info = NULL;
731 if ((ext = CertFindExtension(szOID_NAME_CONSTRAINTS, cert->cExtension,
736 CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
737 ext->Value.pbData, ext->Value.cbData,
738 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &info,
744 static BOOL CRYPT_IsValidNameConstraint(const CERT_NAME_CONSTRAINTS_INFO *info)
749 /* Check that none of the constraints specifies a minimum or a maximum.
750 * See RFC 5280, section 4.2.1.10:
751 * "Within this profile, the minimum and maximum fields are not used with
752 * any name forms, thus, the minimum MUST be zero, and maximum MUST be
753 * absent. However, if an application encounters a critical name
754 * constraints extension that specifies other values for minimum or
755 * maximum for a name form that appears in a subsequent certificate, the
756 * application MUST either process these fields or reject the
758 * Since it gives no guidance as to how to process these fields, we
759 * reject any name constraint that contains them.
761 for (i = 0; ret && i < info->cPermittedSubtree; i++)
762 if (info->rgPermittedSubtree[i].dwMinimum ||
763 info->rgPermittedSubtree[i].fMaximum)
765 TRACE_(chain)("found a minimum or maximum in permitted subtrees\n");
768 for (i = 0; ret && i < info->cExcludedSubtree; i++)
769 if (info->rgExcludedSubtree[i].dwMinimum ||
770 info->rgExcludedSubtree[i].fMaximum)
772 TRACE_(chain)("found a minimum or maximum in excluded subtrees\n");
778 static void CRYPT_CheckChainNameConstraints(PCERT_SIMPLE_CHAIN chain)
782 /* Microsoft's implementation appears to violate RFC 3280: according to
783 * MSDN, the various CERT_TRUST_*_NAME_CONSTRAINT errors are set if a CA's
784 * name constraint is violated in the end cert. According to RFC 3280,
785 * the constraints should be checked against every subsequent certificate
786 * in the chain, not just the end cert.
787 * Microsoft's implementation also sets the name constraint errors on the
788 * certs whose constraints were violated, not on the certs that violated
790 * In order to be error-compatible with Microsoft's implementation, while
791 * still adhering to RFC 3280, I use a O(n ^ 2) algorithm to check name
794 for (i = chain->cElement - 1; i > 0; i--)
796 CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
798 if ((nameConstraints = CRYPT_GetNameConstraints(
799 chain->rgpElement[i]->pCertContext->pCertInfo)))
801 if (!CRYPT_IsValidNameConstraint(nameConstraints))
802 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
803 CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
806 for (j = i - 1; j >= 0; j--)
808 DWORD errorStatus = 0;
810 /* According to RFC 3280, self-signed certs don't have name
811 * constraints checked unless they're the end cert.
813 if (j == 0 || !CRYPT_IsCertificateSelfSigned(
814 chain->rgpElement[j]->pCertContext))
816 CRYPT_CheckNameConstraints(nameConstraints,
817 chain->rgpElement[j]->pCertContext->pCertInfo,
819 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
824 LocalFree(nameConstraints);
829 static LPWSTR name_value_to_str(const CERT_NAME_BLOB *name)
831 DWORD len = cert_name_to_str_with_indent(X509_ASN_ENCODING, 0, name,
832 CERT_SIMPLE_NAME_STR, NULL, 0);
837 str = CryptMemAlloc(len * sizeof(WCHAR));
839 cert_name_to_str_with_indent(X509_ASN_ENCODING, 0, name,
840 CERT_SIMPLE_NAME_STR, str, len);
845 static void dump_alt_name_entry(const CERT_ALT_NAME_ENTRY *entry)
849 switch (entry->dwAltNameChoice)
851 case CERT_ALT_NAME_OTHER_NAME:
852 TRACE_(chain)("CERT_ALT_NAME_OTHER_NAME, oid = %s\n",
853 debugstr_a(entry->u.pOtherName->pszObjId));
855 case CERT_ALT_NAME_RFC822_NAME:
856 TRACE_(chain)("CERT_ALT_NAME_RFC822_NAME: %s\n",
857 debugstr_w(entry->u.pwszRfc822Name));
859 case CERT_ALT_NAME_DNS_NAME:
860 TRACE_(chain)("CERT_ALT_NAME_DNS_NAME: %s\n",
861 debugstr_w(entry->u.pwszDNSName));
863 case CERT_ALT_NAME_DIRECTORY_NAME:
864 str = name_value_to_str(&entry->u.DirectoryName);
865 TRACE_(chain)("CERT_ALT_NAME_DIRECTORY_NAME: %s\n", debugstr_w(str));
868 case CERT_ALT_NAME_URL:
869 TRACE_(chain)("CERT_ALT_NAME_URL: %s\n", debugstr_w(entry->u.pwszURL));
871 case CERT_ALT_NAME_IP_ADDRESS:
872 TRACE_(chain)("CERT_ALT_NAME_IP_ADDRESS: %d bytes\n",
873 entry->u.IPAddress.cbData);
875 case CERT_ALT_NAME_REGISTERED_ID:
876 TRACE_(chain)("CERT_ALT_NAME_REGISTERED_ID: %s\n",
877 debugstr_a(entry->u.pszRegisteredID));
880 TRACE_(chain)("dwAltNameChoice = %d\n", entry->dwAltNameChoice);
884 static void dump_alt_name(LPCSTR type, const CERT_EXTENSION *ext)
886 CERT_ALT_NAME_INFO *name;
889 TRACE_(chain)("%s:\n", type);
890 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
891 ext->Value.pbData, ext->Value.cbData,
892 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &name, &size))
896 TRACE_(chain)("%d alt name entries:\n", name->cAltEntry);
897 for (i = 0; i < name->cAltEntry; i++)
898 dump_alt_name_entry(&name->rgAltEntry[i]);
903 static void dump_basic_constraints(const CERT_EXTENSION *ext)
905 CERT_BASIC_CONSTRAINTS_INFO *info;
908 if (CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
909 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
912 TRACE_(chain)("SubjectType: %02x\n", info->SubjectType.pbData[0]);
913 TRACE_(chain)("%s path length constraint\n",
914 info->fPathLenConstraint ? "has" : "doesn't have");
915 TRACE_(chain)("path length=%d\n", info->dwPathLenConstraint);
920 static void dump_basic_constraints2(const CERT_EXTENSION *ext)
922 CERT_BASIC_CONSTRAINTS2_INFO constraints;
923 DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
925 if (CryptDecodeObjectEx(X509_ASN_ENCODING,
926 szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
927 0, NULL, &constraints, &size))
929 TRACE_(chain)("basic constraints:\n");
930 TRACE_(chain)("can%s be a CA\n", constraints.fCA ? "" : "not");
931 TRACE_(chain)("%s path length constraint\n",
932 constraints.fPathLenConstraint ? "has" : "doesn't have");
933 TRACE_(chain)("path length=%d\n", constraints.dwPathLenConstraint);
937 static void dump_key_usage(const CERT_EXTENSION *ext)
939 CRYPT_BIT_BLOB usage;
940 DWORD size = sizeof(usage);
942 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
943 ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
945 #define trace_usage_bit(bits, bit) \
946 if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
949 trace_usage_bit(usage.pbData[0], CERT_DIGITAL_SIGNATURE_KEY_USAGE);
950 trace_usage_bit(usage.pbData[0], CERT_NON_REPUDIATION_KEY_USAGE);
951 trace_usage_bit(usage.pbData[0], CERT_KEY_ENCIPHERMENT_KEY_USAGE);
952 trace_usage_bit(usage.pbData[0], CERT_DATA_ENCIPHERMENT_KEY_USAGE);
953 trace_usage_bit(usage.pbData[0], CERT_KEY_AGREEMENT_KEY_USAGE);
954 trace_usage_bit(usage.pbData[0], CERT_KEY_CERT_SIGN_KEY_USAGE);
955 trace_usage_bit(usage.pbData[0], CERT_CRL_SIGN_KEY_USAGE);
956 trace_usage_bit(usage.pbData[0], CERT_ENCIPHER_ONLY_KEY_USAGE);
958 #undef trace_usage_bit
959 if (usage.cbData > 1 && usage.pbData[1] & CERT_DECIPHER_ONLY_KEY_USAGE)
960 TRACE_(chain)("CERT_DECIPHER_ONLY_KEY_USAGE\n");
964 static void dump_general_subtree(const CERT_GENERAL_SUBTREE *subtree)
966 dump_alt_name_entry(&subtree->Base);
967 TRACE_(chain)("dwMinimum = %d, fMaximum = %d, dwMaximum = %d\n",
968 subtree->dwMinimum, subtree->fMaximum, subtree->dwMaximum);
971 static void dump_name_constraints(const CERT_EXTENSION *ext)
973 CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
976 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
977 ext->Value.pbData, ext->Value.cbData,
978 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &nameConstraints,
983 TRACE_(chain)("%d permitted subtrees:\n",
984 nameConstraints->cPermittedSubtree);
985 for (i = 0; i < nameConstraints->cPermittedSubtree; i++)
986 dump_general_subtree(&nameConstraints->rgPermittedSubtree[i]);
987 TRACE_(chain)("%d excluded subtrees:\n",
988 nameConstraints->cExcludedSubtree);
989 for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
990 dump_general_subtree(&nameConstraints->rgExcludedSubtree[i]);
991 LocalFree(nameConstraints);
995 static void dump_cert_policies(const CERT_EXTENSION *ext)
997 CERT_POLICIES_INFO *policies;
1000 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_CERT_POLICIES,
1001 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1006 TRACE_(chain)("%d policies:\n", policies->cPolicyInfo);
1007 for (i = 0; i < policies->cPolicyInfo; i++)
1009 TRACE_(chain)("policy identifier: %s\n",
1010 debugstr_a(policies->rgPolicyInfo[i].pszPolicyIdentifier));
1011 TRACE_(chain)("%d policy qualifiers:\n",
1012 policies->rgPolicyInfo[i].cPolicyQualifier);
1013 for (j = 0; j < policies->rgPolicyInfo[i].cPolicyQualifier; j++)
1014 TRACE_(chain)("%s\n", debugstr_a(
1015 policies->rgPolicyInfo[i].rgPolicyQualifier[j].
1016 pszPolicyQualifierId));
1018 LocalFree(policies);
1022 static void dump_enhanced_key_usage(const CERT_EXTENSION *ext)
1024 CERT_ENHKEY_USAGE *usage;
1027 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ENHANCED_KEY_USAGE,
1028 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1033 TRACE_(chain)("%d usages:\n", usage->cUsageIdentifier);
1034 for (i = 0; i < usage->cUsageIdentifier; i++)
1035 TRACE_(chain)("%s\n", usage->rgpszUsageIdentifier[i]);
1040 static void dump_netscape_cert_type(const CERT_EXTENSION *ext)
1042 CRYPT_BIT_BLOB usage;
1043 DWORD size = sizeof(usage);
1045 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
1046 ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
1048 #define trace_cert_type_bit(bits, bit) \
1049 if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
1052 trace_cert_type_bit(usage.pbData[0],
1053 NETSCAPE_SSL_CLIENT_AUTH_CERT_TYPE);
1054 trace_cert_type_bit(usage.pbData[0],
1055 NETSCAPE_SSL_SERVER_AUTH_CERT_TYPE);
1056 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SMIME_CERT_TYPE);
1057 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SIGN_CERT_TYPE);
1058 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SSL_CA_CERT_TYPE);
1059 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SMIME_CA_CERT_TYPE);
1060 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SIGN_CA_CERT_TYPE);
1062 #undef trace_cert_type_bit
1066 static void dump_extension(const CERT_EXTENSION *ext)
1068 TRACE_(chain)("%s (%scritical)\n", debugstr_a(ext->pszObjId),
1069 ext->fCritical ? "" : "not ");
1070 if (!strcmp(ext->pszObjId, szOID_SUBJECT_ALT_NAME))
1071 dump_alt_name("subject alt name", ext);
1072 else if (!strcmp(ext->pszObjId, szOID_ISSUER_ALT_NAME))
1073 dump_alt_name("issuer alt name", ext);
1074 else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS))
1075 dump_basic_constraints(ext);
1076 else if (!strcmp(ext->pszObjId, szOID_KEY_USAGE))
1077 dump_key_usage(ext);
1078 else if (!strcmp(ext->pszObjId, szOID_SUBJECT_ALT_NAME2))
1079 dump_alt_name("subject alt name 2", ext);
1080 else if (!strcmp(ext->pszObjId, szOID_ISSUER_ALT_NAME2))
1081 dump_alt_name("issuer alt name 2", ext);
1082 else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS2))
1083 dump_basic_constraints2(ext);
1084 else if (!strcmp(ext->pszObjId, szOID_NAME_CONSTRAINTS))
1085 dump_name_constraints(ext);
1086 else if (!strcmp(ext->pszObjId, szOID_CERT_POLICIES))
1087 dump_cert_policies(ext);
1088 else if (!strcmp(ext->pszObjId, szOID_ENHANCED_KEY_USAGE))
1089 dump_enhanced_key_usage(ext);
1090 else if (!strcmp(ext->pszObjId, szOID_NETSCAPE_CERT_TYPE))
1091 dump_netscape_cert_type(ext);
1094 static LPCWSTR filetime_to_str(const FILETIME *time)
1096 static WCHAR date[80];
1097 WCHAR dateFmt[80]; /* sufficient for all versions of LOCALE_SSHORTDATE */
1100 if (!time) return NULL;
1102 GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, dateFmt,
1103 sizeof(dateFmt) / sizeof(dateFmt[0]));
1104 FileTimeToSystemTime(time, &sysTime);
1105 GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, date,
1106 sizeof(date) / sizeof(date[0]));
1110 static void dump_element(PCCERT_CONTEXT cert)
1115 TRACE_(chain)("%p\n", cert);
1116 len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
1117 CERT_NAME_ISSUER_FLAG, NULL, NULL, 0);
1118 name = CryptMemAlloc(len * sizeof(WCHAR));
1121 CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
1122 CERT_NAME_ISSUER_FLAG, NULL, name, len);
1123 TRACE_(chain)("issued by %s\n", debugstr_w(name));
1126 len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
1128 name = CryptMemAlloc(len * sizeof(WCHAR));
1131 CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
1133 TRACE_(chain)("issued to %s\n", debugstr_w(name));
1136 TRACE_(chain)("valid from %s to %s\n",
1137 debugstr_w(filetime_to_str(&cert->pCertInfo->NotBefore)),
1138 debugstr_w(filetime_to_str(&cert->pCertInfo->NotAfter)));
1139 TRACE_(chain)("%d extensions\n", cert->pCertInfo->cExtension);
1140 for (i = 0; i < cert->pCertInfo->cExtension; i++)
1141 dump_extension(&cert->pCertInfo->rgExtension[i]);
1144 static BOOL CRYPT_KeyUsageValid(PCertificateChainEngine engine,
1145 PCCERT_CONTEXT cert, BOOL isRoot, BOOL isCA, DWORD index)
1147 PCERT_EXTENSION ext;
1151 ext = CertFindExtension(szOID_KEY_USAGE, cert->pCertInfo->cExtension,
1152 cert->pCertInfo->rgExtension);
1155 CRYPT_BIT_BLOB usage;
1156 DWORD size = sizeof(usage);
1158 ret = CryptDecodeObjectEx(cert->dwCertEncodingType, X509_BITS,
1159 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL,
1163 else if (usage.cbData > 2)
1165 /* The key usage extension only defines 9 bits => no more than 2
1166 * bytes are needed to encode all known usages.
1172 /* The only bit relevant to chain validation is the keyCertSign
1173 * bit, which is always in the least significant byte of the
1176 usageBits = usage.pbData[usage.cbData - 1];
1183 /* MS appears to violate RFC 5280, section 4.2.1.3 (Key Usage)
1184 * here. Quoting the RFC:
1185 * "This [key usage] extension MUST appear in certificates that
1186 * contain public keys that are used to validate digital signatures
1187 * on other public key certificates or CRLs."
1188 * MS appears to accept certs that do not contain key usage
1189 * extensions as CA certs. V1 and V2 certificates did not have
1190 * extensions, and many root certificates are V1 certificates, so
1191 * perhaps this is prudent. On the other hand, MS also accepts V3
1192 * certs without key usage extensions. We are more restrictive:
1193 * we accept locally installed V1 or V2 certs as CA certs.
1194 * We also accept a lack of key usage extension on root certs,
1195 * which is implied in RFC 5280, section 6.1: the trust anchor's
1196 * only requirement is that it was used to issue the next
1197 * certificate in the chain.
1201 else if (cert->pCertInfo->dwVersion == CERT_V1 ||
1202 cert->pCertInfo->dwVersion == CERT_V2)
1204 PCCERT_CONTEXT localCert = CRYPT_FindCertInStore(
1205 engine->hWorld, cert);
1207 ret = localCert != NULL;
1208 CertFreeCertificateContext(localCert);
1213 WARN_(chain)("no key usage extension on a CA cert\n");
1217 if (!(usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
1219 WARN_(chain)("keyCertSign not asserted on a CA cert\n");
1228 if (ext && (usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
1230 WARN_(chain)("keyCertSign asserted on a non-CA cert\n");
1239 static BOOL CRYPT_ExtendedKeyUsageValidForCA(PCCERT_CONTEXT cert)
1241 PCERT_EXTENSION ext;
1244 /* RFC 5280, section 4.2.1.12: "In general, this extension will only
1245 * appear in end entity certificates." And, "If a certificate contains
1246 * both a key usage extension and an extended key usage extension, then
1247 * both extensions MUST be processed independently and the certificate MUST
1248 * only be used for a purpose consistent with both extensions." This seems
1249 * to imply that it should be checked if present, and ignored if not.
1250 * Unfortunately some CAs, e.g. the Thawte SGC CA, don't include the code
1251 * signing extended key usage, whereas they do include the keyCertSign
1252 * key usage. Thus, when checking for a CA, we only require the
1253 * code signing extended key usage if the extended key usage is critical.
1255 ext = CertFindExtension(szOID_ENHANCED_KEY_USAGE,
1256 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
1257 if (ext && ext->fCritical)
1259 CERT_ENHKEY_USAGE *usage;
1262 ret = CryptDecodeObjectEx(cert->dwCertEncodingType,
1263 X509_ENHANCED_KEY_USAGE, ext->Value.pbData, ext->Value.cbData,
1264 CRYPT_DECODE_ALLOC_FLAG, NULL, &usage, &size);
1269 /* Explicitly require the code signing extended key usage for a CA
1270 * with an extended key usage extension. That is, don't assume
1271 * a cert is allowed to be a CA if it specifies the
1272 * anyExtendedKeyUsage usage oid. See again RFC 5280, section
1273 * 4.2.1.12: "Applications that require the presence of a
1274 * particular purpose MAY reject certificates that include the
1275 * anyExtendedKeyUsage OID but not the particular OID expected for
1279 for (i = 0; !ret && i < usage->cUsageIdentifier; i++)
1280 if (!strcmp(usage->rgpszUsageIdentifier[i],
1281 szOID_PKIX_KP_CODE_SIGNING))
1291 static BOOL CRYPT_CriticalExtensionsSupported(PCCERT_CONTEXT cert)
1296 for (i = 0; ret && i < cert->pCertInfo->cExtension; i++)
1298 if (cert->pCertInfo->rgExtension[i].fCritical)
1300 LPCSTR oid = cert->pCertInfo->rgExtension[i].pszObjId;
1302 if (!strcmp(oid, szOID_BASIC_CONSTRAINTS))
1304 else if (!strcmp(oid, szOID_BASIC_CONSTRAINTS2))
1306 else if (!strcmp(oid, szOID_NAME_CONSTRAINTS))
1308 else if (!strcmp(oid, szOID_KEY_USAGE))
1310 else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME))
1312 else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME2))
1314 else if (!strcmp(oid, szOID_ENHANCED_KEY_USAGE))
1318 FIXME("unsupported critical extension %s\n",
1327 static BOOL CRYPT_IsCertVersionValid(PCCERT_CONTEXT cert)
1331 /* Checks whether the contents of the cert match the cert's version. */
1332 switch (cert->pCertInfo->dwVersion)
1335 /* A V1 cert may not contain unique identifiers. See RFC 5280,
1337 * "These fields MUST only appear if the version is 2 or 3 (Section
1338 * 4.1.2.1). These fields MUST NOT appear if the version is 1."
1340 if (cert->pCertInfo->IssuerUniqueId.cbData ||
1341 cert->pCertInfo->SubjectUniqueId.cbData)
1343 /* A V1 cert may not contain extensions. See RFC 5280, section 4.1.2.9:
1344 * "This field MUST only appear if the version is 3 (Section 4.1.2.1)."
1346 if (cert->pCertInfo->cExtension)
1350 /* A V2 cert may not contain extensions. See RFC 5280, section 4.1.2.9:
1351 * "This field MUST only appear if the version is 3 (Section 4.1.2.1)."
1353 if (cert->pCertInfo->cExtension)
1357 /* Do nothing, all fields are allowed for V3 certs */
1360 WARN_(chain)("invalid cert version %d\n", cert->pCertInfo->dwVersion);
1366 static void CRYPT_CheckSimpleChain(PCertificateChainEngine engine,
1367 PCERT_SIMPLE_CHAIN chain, LPFILETIME time)
1369 PCERT_CHAIN_ELEMENT rootElement = chain->rgpElement[chain->cElement - 1];
1371 BOOL pathLengthConstraintViolated = FALSE;
1372 CERT_BASIC_CONSTRAINTS2_INFO constraints = { FALSE, FALSE, 0 };
1374 TRACE_(chain)("checking chain with %d elements for time %s\n",
1375 chain->cElement, debugstr_w(filetime_to_str(time)));
1376 for (i = chain->cElement - 1; i >= 0; i--)
1380 if (TRACE_ON(chain))
1381 dump_element(chain->rgpElement[i]->pCertContext);
1382 if (i == chain->cElement - 1)
1383 isRoot = CRYPT_IsCertificateSelfSigned(
1384 chain->rgpElement[i]->pCertContext);
1387 if (!CRYPT_IsCertVersionValid(chain->rgpElement[i]->pCertContext))
1389 /* MS appears to accept certs whose versions don't match their
1390 * contents, so there isn't an appropriate error code.
1392 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1393 CERT_TRUST_INVALID_EXTENSION;
1395 if (CertVerifyTimeValidity(time,
1396 chain->rgpElement[i]->pCertContext->pCertInfo) != 0)
1397 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1398 CERT_TRUST_IS_NOT_TIME_VALID;
1401 /* Check the signature of the cert this issued */
1402 if (!CryptVerifyCertificateSignatureEx(0, X509_ASN_ENCODING,
1403 CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT,
1404 (void *)chain->rgpElement[i - 1]->pCertContext,
1405 CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT,
1406 (void *)chain->rgpElement[i]->pCertContext, 0, NULL))
1407 chain->rgpElement[i - 1]->TrustStatus.dwErrorStatus |=
1408 CERT_TRUST_IS_NOT_SIGNATURE_VALID;
1409 /* Once a path length constraint has been violated, every remaining
1410 * CA cert's basic constraints is considered invalid.
1412 if (pathLengthConstraintViolated)
1413 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1414 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1415 else if (!CRYPT_CheckBasicConstraintsForCA(engine,
1416 chain->rgpElement[i]->pCertContext, &constraints, i - 1, isRoot,
1417 &pathLengthConstraintViolated))
1418 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1419 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1420 else if (constraints.fPathLenConstraint &&
1421 constraints.dwPathLenConstraint)
1423 /* This one's valid - decrement max length */
1424 constraints.dwPathLenConstraint--;
1429 /* Check whether end cert has a basic constraints extension */
1430 if (!CRYPT_DecodeBasicConstraints(
1431 chain->rgpElement[i]->pCertContext, &constraints, FALSE))
1432 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1433 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1435 if (!CRYPT_KeyUsageValid(engine, chain->rgpElement[i]->pCertContext,
1436 isRoot, constraints.fCA, i))
1437 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1438 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
1440 if (!CRYPT_ExtendedKeyUsageValidForCA(
1441 chain->rgpElement[i]->pCertContext))
1442 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1443 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
1444 if (CRYPT_IsSimpleChainCyclic(chain))
1446 /* If the chain is cyclic, then the path length constraints
1447 * are violated, because the chain is infinitely long.
1449 pathLengthConstraintViolated = TRUE;
1450 chain->TrustStatus.dwErrorStatus |=
1451 CERT_TRUST_IS_PARTIAL_CHAIN |
1452 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1454 /* Check whether every critical extension is supported */
1455 if (!CRYPT_CriticalExtensionsSupported(
1456 chain->rgpElement[i]->pCertContext))
1457 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1458 CERT_TRUST_INVALID_EXTENSION;
1459 CRYPT_CombineTrustStatus(&chain->TrustStatus,
1460 &chain->rgpElement[i]->TrustStatus);
1462 CRYPT_CheckChainNameConstraints(chain);
1463 if (CRYPT_IsCertificateSelfSigned(rootElement->pCertContext))
1465 rootElement->TrustStatus.dwInfoStatus |=
1466 CERT_TRUST_IS_SELF_SIGNED | CERT_TRUST_HAS_NAME_MATCH_ISSUER;
1467 CRYPT_CheckRootCert(engine->hRoot, rootElement);
1469 CRYPT_CombineTrustStatus(&chain->TrustStatus, &rootElement->TrustStatus);
1472 static PCCERT_CONTEXT CRYPT_GetIssuer(HCERTSTORE store, PCCERT_CONTEXT subject,
1473 PCCERT_CONTEXT prevIssuer, DWORD *infoStatus)
1475 PCCERT_CONTEXT issuer = NULL;
1476 PCERT_EXTENSION ext;
1480 if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
1481 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1483 CERT_AUTHORITY_KEY_ID_INFO *info;
1486 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1487 X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
1488 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1494 if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
1496 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1497 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
1498 sizeof(CERT_NAME_BLOB));
1499 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1500 &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
1501 issuer = CertFindCertificateInStore(store,
1502 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1505 *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
1507 else if (info->KeyId.cbData)
1509 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1510 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1511 issuer = CertFindCertificateInStore(store,
1512 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1515 *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
1520 else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
1521 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1523 CERT_AUTHORITY_KEY_ID2_INFO *info;
1526 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1527 X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
1528 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1534 if (info->AuthorityCertIssuer.cAltEntry &&
1535 info->AuthorityCertSerialNumber.cbData)
1537 PCERT_ALT_NAME_ENTRY directoryName = NULL;
1540 for (i = 0; !directoryName &&
1541 i < info->AuthorityCertIssuer.cAltEntry; i++)
1542 if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
1543 == CERT_ALT_NAME_DIRECTORY_NAME)
1545 &info->AuthorityCertIssuer.rgAltEntry[i];
1548 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1549 memcpy(&id.u.IssuerSerialNumber.Issuer,
1550 &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
1551 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1552 &info->AuthorityCertSerialNumber,
1553 sizeof(CRYPT_INTEGER_BLOB));
1554 issuer = CertFindCertificateInStore(store,
1555 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1558 *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
1561 FIXME("no supported name type in authority key id2\n");
1563 else if (info->KeyId.cbData)
1565 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1566 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1567 issuer = CertFindCertificateInStore(store,
1568 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1571 *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
1578 issuer = CertFindCertificateInStore(store,
1579 subject->dwCertEncodingType, 0, CERT_FIND_SUBJECT_NAME,
1580 &subject->pCertInfo->Issuer, prevIssuer);
1581 *infoStatus = CERT_TRUST_HAS_NAME_MATCH_ISSUER;
1586 /* Builds a simple chain by finding an issuer for the last cert in the chain,
1587 * until reaching a self-signed cert, or until no issuer can be found.
1589 static BOOL CRYPT_BuildSimpleChain(const CertificateChainEngine *engine,
1590 HCERTSTORE world, PCERT_SIMPLE_CHAIN chain)
1593 PCCERT_CONTEXT cert = chain->rgpElement[chain->cElement - 1]->pCertContext;
1595 while (ret && !CRYPT_IsSimpleChainCyclic(chain) &&
1596 !CRYPT_IsCertificateSelfSigned(cert))
1598 PCCERT_CONTEXT issuer = CRYPT_GetIssuer(world, cert, NULL,
1599 &chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
1603 ret = CRYPT_AddCertToSimpleChain(engine, chain, issuer,
1604 chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
1605 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it to
1606 * close the enumeration that found it
1608 CertFreeCertificateContext(issuer);
1613 TRACE_(chain)("Couldn't find issuer, halting chain creation\n");
1614 chain->TrustStatus.dwErrorStatus |= CERT_TRUST_IS_PARTIAL_CHAIN;
1621 static BOOL CRYPT_GetSimpleChainForCert(PCertificateChainEngine engine,
1622 HCERTSTORE world, PCCERT_CONTEXT cert, LPFILETIME pTime,
1623 PCERT_SIMPLE_CHAIN *ppChain)
1626 PCERT_SIMPLE_CHAIN chain;
1628 TRACE("(%p, %p, %p, %p)\n", engine, world, cert, pTime);
1630 chain = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
1633 memset(chain, 0, sizeof(CERT_SIMPLE_CHAIN));
1634 chain->cbSize = sizeof(CERT_SIMPLE_CHAIN);
1635 ret = CRYPT_AddCertToSimpleChain(engine, chain, cert, 0);
1638 ret = CRYPT_BuildSimpleChain(engine, world, chain);
1640 CRYPT_CheckSimpleChain(engine, chain, pTime);
1644 CRYPT_FreeSimpleChain(chain);
1652 static BOOL CRYPT_BuildCandidateChainFromCert(HCERTCHAINENGINE hChainEngine,
1653 PCCERT_CONTEXT cert, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1654 PCertificateChain *ppChain)
1656 PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
1657 PCERT_SIMPLE_CHAIN simpleChain = NULL;
1661 world = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
1662 CERT_STORE_CREATE_NEW_FLAG, NULL);
1663 CertAddStoreToCollection(world, engine->hWorld, 0, 0);
1664 if (hAdditionalStore)
1665 CertAddStoreToCollection(world, hAdditionalStore, 0, 0);
1666 /* FIXME: only simple chains are supported for now, as CTLs aren't
1669 if ((ret = CRYPT_GetSimpleChainForCert(engine, world, cert, pTime,
1672 PCertificateChain chain = CryptMemAlloc(sizeof(CertificateChain));
1677 chain->world = world;
1678 chain->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
1679 chain->context.TrustStatus = simpleChain->TrustStatus;
1680 chain->context.cChain = 1;
1681 chain->context.rgpChain = CryptMemAlloc(sizeof(PCERT_SIMPLE_CHAIN));
1682 chain->context.rgpChain[0] = simpleChain;
1683 chain->context.cLowerQualityChainContext = 0;
1684 chain->context.rgpLowerQualityChainContext = NULL;
1685 chain->context.fHasRevocationFreshnessTime = FALSE;
1686 chain->context.dwRevocationFreshnessTime = 0;
1695 /* Makes and returns a copy of chain, up to and including element iElement. */
1696 static PCERT_SIMPLE_CHAIN CRYPT_CopySimpleChainToElement(
1697 const CERT_SIMPLE_CHAIN *chain, DWORD iElement)
1699 PCERT_SIMPLE_CHAIN copy = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
1703 memset(copy, 0, sizeof(CERT_SIMPLE_CHAIN));
1704 copy->cbSize = sizeof(CERT_SIMPLE_CHAIN);
1706 CryptMemAlloc((iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
1707 if (copy->rgpElement)
1712 memset(copy->rgpElement, 0,
1713 (iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
1714 for (i = 0; ret && i <= iElement; i++)
1716 PCERT_CHAIN_ELEMENT element =
1717 CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
1721 *element = *chain->rgpElement[i];
1722 element->pCertContext = CertDuplicateCertificateContext(
1723 chain->rgpElement[i]->pCertContext);
1724 /* Reset the trust status of the copied element, it'll get
1725 * rechecked after the new chain is done.
1727 memset(&element->TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
1728 copy->rgpElement[copy->cElement++] = element;
1735 for (i = 0; i <= iElement; i++)
1736 CryptMemFree(copy->rgpElement[i]);
1737 CryptMemFree(copy->rgpElement);
1751 static void CRYPT_FreeLowerQualityChains(PCertificateChain chain)
1755 for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
1756 CertFreeCertificateChain(chain->context.rgpLowerQualityChainContext[i]);
1757 CryptMemFree(chain->context.rgpLowerQualityChainContext);
1758 chain->context.cLowerQualityChainContext = 0;
1759 chain->context.rgpLowerQualityChainContext = NULL;
1762 static void CRYPT_FreeChainContext(PCertificateChain chain)
1766 CRYPT_FreeLowerQualityChains(chain);
1767 for (i = 0; i < chain->context.cChain; i++)
1768 CRYPT_FreeSimpleChain(chain->context.rgpChain[i]);
1769 CryptMemFree(chain->context.rgpChain);
1770 CertCloseStore(chain->world, 0);
1771 CryptMemFree(chain);
1774 /* Makes and returns a copy of chain, up to and including element iElement of
1775 * simple chain iChain.
1777 static PCertificateChain CRYPT_CopyChainToElement(PCertificateChain chain,
1778 DWORD iChain, DWORD iElement)
1780 PCertificateChain copy = CryptMemAlloc(sizeof(CertificateChain));
1785 copy->world = CertDuplicateStore(chain->world);
1786 copy->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
1787 /* Leave the trust status of the copied chain unset, it'll get
1788 * rechecked after the new chain is done.
1790 memset(©->context.TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
1791 copy->context.cLowerQualityChainContext = 0;
1792 copy->context.rgpLowerQualityChainContext = NULL;
1793 copy->context.fHasRevocationFreshnessTime = FALSE;
1794 copy->context.dwRevocationFreshnessTime = 0;
1795 copy->context.rgpChain = CryptMemAlloc(
1796 (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
1797 if (copy->context.rgpChain)
1802 memset(copy->context.rgpChain, 0,
1803 (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
1806 for (i = 0; ret && iChain && i < iChain - 1; i++)
1808 copy->context.rgpChain[i] =
1809 CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
1810 chain->context.rgpChain[i]->cElement - 1);
1811 if (!copy->context.rgpChain[i])
1819 copy->context.rgpChain[i] =
1820 CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
1822 if (!copy->context.rgpChain[i])
1827 CRYPT_FreeChainContext(copy);
1831 copy->context.cChain = iChain + 1;
1842 static PCertificateChain CRYPT_BuildAlternateContextFromChain(
1843 HCERTCHAINENGINE hChainEngine, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1844 PCertificateChain chain)
1846 PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
1847 PCertificateChain alternate;
1849 TRACE("(%p, %p, %p, %p)\n", hChainEngine, pTime, hAdditionalStore, chain);
1851 /* Always start with the last "lower quality" chain to ensure a consistent
1852 * order of alternate creation:
1854 if (chain->context.cLowerQualityChainContext)
1855 chain = (PCertificateChain)chain->context.rgpLowerQualityChainContext[
1856 chain->context.cLowerQualityChainContext - 1];
1857 /* A chain with only one element can't have any alternates */
1858 if (chain->context.cChain <= 1 && chain->context.rgpChain[0]->cElement <= 1)
1862 DWORD i, j, infoStatus;
1863 PCCERT_CONTEXT alternateIssuer = NULL;
1866 for (i = 0; !alternateIssuer && i < chain->context.cChain; i++)
1867 for (j = 0; !alternateIssuer &&
1868 j < chain->context.rgpChain[i]->cElement - 1; j++)
1870 PCCERT_CONTEXT subject =
1871 chain->context.rgpChain[i]->rgpElement[j]->pCertContext;
1872 PCCERT_CONTEXT prevIssuer = CertDuplicateCertificateContext(
1873 chain->context.rgpChain[i]->rgpElement[j + 1]->pCertContext);
1875 alternateIssuer = CRYPT_GetIssuer(prevIssuer->hCertStore,
1876 subject, prevIssuer, &infoStatus);
1878 if (alternateIssuer)
1882 alternate = CRYPT_CopyChainToElement(chain, i, j);
1885 BOOL ret = CRYPT_AddCertToSimpleChain(engine,
1886 alternate->context.rgpChain[i], alternateIssuer, infoStatus);
1888 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it
1889 * to close the enumeration that found it
1891 CertFreeCertificateContext(alternateIssuer);
1894 ret = CRYPT_BuildSimpleChain(engine, alternate->world,
1895 alternate->context.rgpChain[i]);
1897 CRYPT_CheckSimpleChain(engine,
1898 alternate->context.rgpChain[i], pTime);
1899 CRYPT_CombineTrustStatus(&alternate->context.TrustStatus,
1900 &alternate->context.rgpChain[i]->TrustStatus);
1904 CRYPT_FreeChainContext(alternate);
1910 TRACE("%p\n", alternate);
1914 #define CHAIN_QUALITY_SIGNATURE_VALID 0x16
1915 #define CHAIN_QUALITY_TIME_VALID 8
1916 #define CHAIN_QUALITY_COMPLETE_CHAIN 4
1917 #define CHAIN_QUALITY_BASIC_CONSTRAINTS 2
1918 #define CHAIN_QUALITY_TRUSTED_ROOT 1
1920 #define CHAIN_QUALITY_HIGHEST \
1921 CHAIN_QUALITY_SIGNATURE_VALID | CHAIN_QUALITY_TIME_VALID | \
1922 CHAIN_QUALITY_COMPLETE_CHAIN | CHAIN_QUALITY_BASIC_CONSTRAINTS | \
1923 CHAIN_QUALITY_TRUSTED_ROOT
1925 #define IS_TRUST_ERROR_SET(TrustStatus, bits) \
1926 (TrustStatus)->dwErrorStatus & (bits)
1928 static DWORD CRYPT_ChainQuality(const CertificateChain *chain)
1930 DWORD quality = CHAIN_QUALITY_HIGHEST;
1932 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1933 CERT_TRUST_IS_UNTRUSTED_ROOT))
1934 quality &= ~CHAIN_QUALITY_TRUSTED_ROOT;
1935 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1936 CERT_TRUST_INVALID_BASIC_CONSTRAINTS))
1937 quality &= ~CHAIN_QUALITY_BASIC_CONSTRAINTS;
1938 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1939 CERT_TRUST_IS_PARTIAL_CHAIN))
1940 quality &= ~CHAIN_QUALITY_COMPLETE_CHAIN;
1941 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1942 CERT_TRUST_IS_NOT_TIME_VALID | CERT_TRUST_IS_NOT_TIME_NESTED))
1943 quality &= ~CHAIN_QUALITY_TIME_VALID;
1944 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1945 CERT_TRUST_IS_NOT_SIGNATURE_VALID))
1946 quality &= ~CHAIN_QUALITY_SIGNATURE_VALID;
1950 /* Chooses the highest quality chain among chain and its "lower quality"
1951 * alternate chains. Returns the highest quality chain, with all other
1952 * chains as lower quality chains of it.
1954 static PCertificateChain CRYPT_ChooseHighestQualityChain(
1955 PCertificateChain chain)
1959 /* There are always only two chains being considered: chain, and an
1960 * alternate at chain->rgpLowerQualityChainContext[i]. If the alternate
1961 * has a higher quality than chain, the alternate gets assigned the lower
1962 * quality contexts, with chain taking the alternate's place among the
1963 * lower quality contexts.
1965 for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
1967 PCertificateChain alternate =
1968 (PCertificateChain)chain->context.rgpLowerQualityChainContext[i];
1970 if (CRYPT_ChainQuality(alternate) > CRYPT_ChainQuality(chain))
1972 alternate->context.cLowerQualityChainContext =
1973 chain->context.cLowerQualityChainContext;
1974 alternate->context.rgpLowerQualityChainContext =
1975 chain->context.rgpLowerQualityChainContext;
1976 alternate->context.rgpLowerQualityChainContext[i] =
1977 (PCCERT_CHAIN_CONTEXT)chain;
1978 chain->context.cLowerQualityChainContext = 0;
1979 chain->context.rgpLowerQualityChainContext = NULL;
1986 static BOOL CRYPT_AddAlternateChainToChain(PCertificateChain chain,
1987 const CertificateChain *alternate)
1991 if (chain->context.cLowerQualityChainContext)
1992 chain->context.rgpLowerQualityChainContext =
1993 CryptMemRealloc(chain->context.rgpLowerQualityChainContext,
1994 (chain->context.cLowerQualityChainContext + 1) *
1995 sizeof(PCCERT_CHAIN_CONTEXT));
1997 chain->context.rgpLowerQualityChainContext =
1998 CryptMemAlloc(sizeof(PCCERT_CHAIN_CONTEXT));
1999 if (chain->context.rgpLowerQualityChainContext)
2001 chain->context.rgpLowerQualityChainContext[
2002 chain->context.cLowerQualityChainContext++] =
2003 (PCCERT_CHAIN_CONTEXT)alternate;
2011 static PCERT_CHAIN_ELEMENT CRYPT_FindIthElementInChain(
2012 const CERT_CHAIN_CONTEXT *chain, DWORD i)
2015 PCERT_CHAIN_ELEMENT element = NULL;
2017 for (j = 0, iElement = 0; !element && j < chain->cChain; j++)
2019 if (iElement + chain->rgpChain[j]->cElement < i)
2020 iElement += chain->rgpChain[j]->cElement;
2022 element = chain->rgpChain[j]->rgpElement[i - iElement];
2027 typedef struct _CERT_CHAIN_PARA_NO_EXTRA_FIELDS {
2029 CERT_USAGE_MATCH RequestedUsage;
2030 } CERT_CHAIN_PARA_NO_EXTRA_FIELDS, *PCERT_CHAIN_PARA_NO_EXTRA_FIELDS;
2032 static void CRYPT_VerifyChainRevocation(PCERT_CHAIN_CONTEXT chain,
2033 LPFILETIME pTime, const CERT_CHAIN_PARA *pChainPara, DWORD chainFlags)
2037 if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_END_CERT)
2039 else if ((chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN) ||
2040 (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT))
2044 for (i = 0, cContext = 0; i < chain->cChain; i++)
2046 if (i < chain->cChain - 1 ||
2047 chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN)
2048 cContext += chain->rgpChain[i]->cElement;
2050 cContext += chain->rgpChain[i]->cElement - 1;
2057 PCCERT_CONTEXT *contexts =
2058 CryptMemAlloc(cContext * sizeof(PCCERT_CONTEXT *));
2062 DWORD i, j, iContext, revocationFlags;
2063 CERT_REVOCATION_PARA revocationPara = { sizeof(revocationPara), 0 };
2064 CERT_REVOCATION_STATUS revocationStatus =
2065 { sizeof(revocationStatus), 0 };
2068 for (i = 0, iContext = 0; iContext < cContext && i < chain->cChain;
2071 for (j = 0; iContext < cContext &&
2072 j < chain->rgpChain[i]->cElement; j++)
2073 contexts[iContext++] =
2074 chain->rgpChain[i]->rgpElement[j]->pCertContext;
2076 revocationFlags = CERT_VERIFY_REV_CHAIN_FLAG;
2077 if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY)
2078 revocationFlags |= CERT_VERIFY_CACHE_ONLY_BASED_REVOCATION;
2079 if (chainFlags & CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT)
2080 revocationFlags |= CERT_VERIFY_REV_ACCUMULATIVE_TIMEOUT_FLAG;
2081 revocationPara.pftTimeToUse = pTime;
2082 if (pChainPara->cbSize == sizeof(CERT_CHAIN_PARA))
2084 revocationPara.dwUrlRetrievalTimeout =
2085 pChainPara->dwUrlRetrievalTimeout;
2086 revocationPara.fCheckFreshnessTime =
2087 pChainPara->fCheckRevocationFreshnessTime;
2088 revocationPara.dwFreshnessTime =
2089 pChainPara->dwRevocationFreshnessTime;
2091 ret = CertVerifyRevocation(X509_ASN_ENCODING,
2092 CERT_CONTEXT_REVOCATION_TYPE, cContext, (void **)contexts,
2093 revocationFlags, &revocationPara, &revocationStatus);
2096 PCERT_CHAIN_ELEMENT element =
2097 CRYPT_FindIthElementInChain(chain, revocationStatus.dwIndex);
2100 switch (revocationStatus.dwError)
2102 case CRYPT_E_NO_REVOCATION_CHECK:
2103 case CRYPT_E_NO_REVOCATION_DLL:
2104 case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
2105 error = CERT_TRUST_REVOCATION_STATUS_UNKNOWN;
2107 case CRYPT_E_REVOCATION_OFFLINE:
2108 error = CERT_TRUST_IS_OFFLINE_REVOCATION;
2110 case CRYPT_E_REVOKED:
2111 error = CERT_TRUST_IS_REVOKED;
2114 WARN("unmapped error %08x\n", revocationStatus.dwError);
2119 /* FIXME: set element's pRevocationInfo member */
2120 element->TrustStatus.dwErrorStatus |= error;
2122 chain->TrustStatus.dwErrorStatus |= error;
2124 CryptMemFree(contexts);
2129 static void dump_usage_match(LPCSTR name, const CERT_USAGE_MATCH *usageMatch)
2133 TRACE_(chain)("%s: %s\n", name,
2134 usageMatch->dwType == USAGE_MATCH_TYPE_AND ? "AND" : "OR");
2135 for (i = 0; i < usageMatch->Usage.cUsageIdentifier; i++)
2136 TRACE_(chain)("%s\n", usageMatch->Usage.rgpszUsageIdentifier[i]);
2139 static void dump_chain_para(const CERT_CHAIN_PARA *pChainPara)
2141 TRACE_(chain)("%d\n", pChainPara->cbSize);
2142 if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA_NO_EXTRA_FIELDS))
2143 dump_usage_match("RequestedUsage", &pChainPara->RequestedUsage);
2144 if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA))
2146 dump_usage_match("RequestedIssuancePolicy",
2147 &pChainPara->RequestedIssuancePolicy);
2148 TRACE_(chain)("%d\n", pChainPara->dwUrlRetrievalTimeout);
2149 TRACE_(chain)("%d\n", pChainPara->fCheckRevocationFreshnessTime);
2150 TRACE_(chain)("%d\n", pChainPara->dwRevocationFreshnessTime);
2154 BOOL WINAPI CertGetCertificateChain(HCERTCHAINENGINE hChainEngine,
2155 PCCERT_CONTEXT pCertContext, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
2156 PCERT_CHAIN_PARA pChainPara, DWORD dwFlags, LPVOID pvReserved,
2157 PCCERT_CHAIN_CONTEXT* ppChainContext)
2160 PCertificateChain chain = NULL;
2162 TRACE("(%p, %p, %p, %p, %p, %08x, %p, %p)\n", hChainEngine, pCertContext,
2163 pTime, hAdditionalStore, pChainPara, dwFlags, pvReserved, ppChainContext);
2166 *ppChainContext = NULL;
2169 SetLastError(E_INVALIDARG);
2172 if (!pCertContext->pCertInfo->SignatureAlgorithm.pszObjId)
2174 SetLastError(ERROR_INVALID_DATA);
2179 hChainEngine = CRYPT_GetDefaultChainEngine();
2180 if (TRACE_ON(chain))
2181 dump_chain_para(pChainPara);
2182 /* FIXME: what about HCCE_LOCAL_MACHINE? */
2183 ret = CRYPT_BuildCandidateChainFromCert(hChainEngine, pCertContext, pTime,
2184 hAdditionalStore, &chain);
2187 PCertificateChain alternate = NULL;
2188 PCERT_CHAIN_CONTEXT pChain;
2191 alternate = CRYPT_BuildAlternateContextFromChain(hChainEngine,
2192 pTime, hAdditionalStore, chain);
2194 /* Alternate contexts are added as "lower quality" contexts of
2195 * chain, to avoid loops in alternate chain creation.
2196 * The highest-quality chain is chosen at the end.
2199 ret = CRYPT_AddAlternateChainToChain(chain, alternate);
2200 } while (ret && alternate);
2201 chain = CRYPT_ChooseHighestQualityChain(chain);
2202 if (!(dwFlags & CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS))
2203 CRYPT_FreeLowerQualityChains(chain);
2204 pChain = (PCERT_CHAIN_CONTEXT)chain;
2205 CRYPT_VerifyChainRevocation(pChain, pTime, pChainPara, dwFlags);
2207 *ppChainContext = pChain;
2209 CertFreeCertificateChain(pChain);
2211 TRACE("returning %d\n", ret);
2215 PCCERT_CHAIN_CONTEXT WINAPI CertDuplicateCertificateChain(
2216 PCCERT_CHAIN_CONTEXT pChainContext)
2218 PCertificateChain chain = (PCertificateChain)pChainContext;
2220 TRACE("(%p)\n", pChainContext);
2223 InterlockedIncrement(&chain->ref);
2224 return pChainContext;
2227 VOID WINAPI CertFreeCertificateChain(PCCERT_CHAIN_CONTEXT pChainContext)
2229 PCertificateChain chain = (PCertificateChain)pChainContext;
2231 TRACE("(%p)\n", pChainContext);
2235 if (InterlockedDecrement(&chain->ref) == 0)
2236 CRYPT_FreeChainContext(chain);
2240 static void find_element_with_error(PCCERT_CHAIN_CONTEXT chain, DWORD error,
2241 LONG *iChain, LONG *iElement)
2245 for (i = 0; i < chain->cChain; i++)
2246 for (j = 0; j < chain->rgpChain[i]->cElement; j++)
2247 if (chain->rgpChain[i]->rgpElement[j]->TrustStatus.dwErrorStatus &
2256 static BOOL WINAPI verify_base_policy(LPCSTR szPolicyOID,
2257 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2258 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2260 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2261 if (pChainContext->TrustStatus.dwErrorStatus &
2262 CERT_TRUST_IS_NOT_SIGNATURE_VALID)
2264 pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
2265 find_element_with_error(pChainContext,
2266 CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
2267 &pPolicyStatus->lElementIndex);
2269 else if (pChainContext->TrustStatus.dwErrorStatus &
2270 CERT_TRUST_IS_UNTRUSTED_ROOT)
2272 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
2273 find_element_with_error(pChainContext,
2274 CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
2275 &pPolicyStatus->lElementIndex);
2277 else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
2279 pPolicyStatus->dwError = CERT_E_CHAINING;
2280 find_element_with_error(pChainContext, CERT_TRUST_IS_CYCLIC,
2281 &pPolicyStatus->lChainIndex, &pPolicyStatus->lElementIndex);
2282 /* For a cyclic chain, which element is a cycle isn't meaningful */
2283 pPolicyStatus->lElementIndex = -1;
2286 pPolicyStatus->dwError = NO_ERROR;
2290 static BYTE msTestPubKey1[] = {
2291 0x30,0x47,0x02,0x40,0x81,0x55,0x22,0xb9,0x8a,0xa4,0x6f,0xed,0xd6,0xe7,0xd9,
2292 0x66,0x0f,0x55,0xbc,0xd7,0xcd,0xd5,0xbc,0x4e,0x40,0x02,0x21,0xa2,0xb1,0xf7,
2293 0x87,0x30,0x85,0x5e,0xd2,0xf2,0x44,0xb9,0xdc,0x9b,0x75,0xb6,0xfb,0x46,0x5f,
2294 0x42,0xb6,0x9d,0x23,0x36,0x0b,0xde,0x54,0x0f,0xcd,0xbd,0x1f,0x99,0x2a,0x10,
2295 0x58,0x11,0xcb,0x40,0xcb,0xb5,0xa7,0x41,0x02,0x03,0x01,0x00,0x01 };
2296 static BYTE msTestPubKey2[] = {
2297 0x30,0x47,0x02,0x40,0x9c,0x50,0x05,0x1d,0xe2,0x0e,0x4c,0x53,0xd8,0xd9,0xb5,
2298 0xe5,0xfd,0xe9,0xe3,0xad,0x83,0x4b,0x80,0x08,0xd9,0xdc,0xe8,0xe8,0x35,0xf8,
2299 0x11,0xf1,0xe9,0x9b,0x03,0x7a,0x65,0x64,0x76,0x35,0xce,0x38,0x2c,0xf2,0xb6,
2300 0x71,0x9e,0x06,0xd9,0xbf,0xbb,0x31,0x69,0xa3,0xf6,0x30,0xa0,0x78,0x7b,0x18,
2301 0xdd,0x50,0x4d,0x79,0x1e,0xeb,0x61,0xc1,0x02,0x03,0x01,0x00,0x01 };
2303 static BOOL WINAPI verify_authenticode_policy(LPCSTR szPolicyOID,
2304 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2305 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2307 BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
2310 if (ret && pPolicyStatus->dwError == CERT_E_UNTRUSTEDROOT)
2312 CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
2313 BOOL isMSTestRoot = FALSE;
2314 PCCERT_CONTEXT failingCert =
2315 pChainContext->rgpChain[pPolicyStatus->lChainIndex]->
2316 rgpElement[pPolicyStatus->lElementIndex]->pCertContext;
2318 CRYPT_DATA_BLOB keyBlobs[] = {
2319 { sizeof(msTestPubKey1), msTestPubKey1 },
2320 { sizeof(msTestPubKey2), msTestPubKey2 },
2323 /* Check whether the root is an MS test root */
2324 for (i = 0; !isMSTestRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
2327 msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
2328 msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
2329 if (CertComparePublicKeyInfo(
2330 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
2331 &failingCert->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
2332 isMSTestRoot = TRUE;
2335 pPolicyStatus->dwError = CERT_E_UNTRUSTEDTESTROOT;
2340 static BOOL WINAPI verify_basic_constraints_policy(LPCSTR szPolicyOID,
2341 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2342 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2344 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2345 if (pChainContext->TrustStatus.dwErrorStatus &
2346 CERT_TRUST_INVALID_BASIC_CONSTRAINTS)
2348 pPolicyStatus->dwError = TRUST_E_BASIC_CONSTRAINTS;
2349 find_element_with_error(pChainContext,
2350 CERT_TRUST_INVALID_BASIC_CONSTRAINTS, &pPolicyStatus->lChainIndex,
2351 &pPolicyStatus->lElementIndex);
2354 pPolicyStatus->dwError = NO_ERROR;
2358 static BOOL match_dns_to_subject_alt_name(PCERT_EXTENSION ext,
2359 LPCWSTR server_name)
2361 BOOL matches = FALSE;
2362 CERT_ALT_NAME_INFO *subjectName;
2365 TRACE_(chain)("%s\n", debugstr_w(server_name));
2366 /* FIXME: This can be spoofed by the embedded NULL vulnerability. The
2367 * returned CERT_ALT_NAME_INFO doesn't have a way to indicate the
2368 * encoded length of a name, so a certificate issued to
2369 * winehq.org\0badsite.com will get treated as having been issued to
2372 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
2373 ext->Value.pbData, ext->Value.cbData,
2374 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2375 &subjectName, &size))
2380 for (i = 0; !found && i < subjectName->cAltEntry; i++)
2382 if (subjectName->rgAltEntry[i].dwAltNameChoice ==
2383 CERT_ALT_NAME_DNS_NAME)
2385 TRACE_(chain)("dNSName: %s\n", debugstr_w(
2386 subjectName->rgAltEntry[i].u.pwszDNSName));
2388 if (!strcmpiW(server_name,
2389 subjectName->rgAltEntry[i].u.pwszDNSName))
2393 LocalFree(subjectName);
2398 static BOOL find_matching_domain_component(CERT_NAME_INFO *name,
2401 BOOL matches = FALSE;
2404 for (i = 0; !matches && i < name->cRDN; i++)
2405 for (j = 0; j < name->rgRDN[i].cRDNAttr; j++)
2406 if (!strcmp(szOID_DOMAIN_COMPONENT,
2407 name->rgRDN[i].rgRDNAttr[j].pszObjId))
2409 PCERT_RDN_ATTR attr;
2411 attr = &name->rgRDN[i].rgRDNAttr[j];
2412 /* Compare with memicmpW rather than strcmpiW in order to avoid
2413 * a match with a string with an embedded NULL. The component
2414 * must match one domain component attribute's entire string
2415 * value with a case-insensitive match.
2417 matches = !memicmpW(component, (LPWSTR)attr->Value.pbData,
2418 attr->Value.cbData / sizeof(WCHAR));
2423 static BOOL match_dns_to_subject_dn(PCCERT_CONTEXT cert, LPCWSTR server_name)
2425 BOOL matches = FALSE;
2426 CERT_NAME_INFO *name;
2429 TRACE_(chain)("%s\n", debugstr_w(server_name));
2430 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_UNICODE_NAME,
2431 cert->pCertInfo->Subject.pbData, cert->pCertInfo->Subject.cbData,
2432 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2435 /* If the subject distinguished name contains any name components,
2436 * make sure all of them are present.
2438 if (CertFindRDNAttr(szOID_DOMAIN_COMPONENT, name))
2440 LPCWSTR ptr = server_name;
2444 LPCWSTR dot = strchrW(ptr, '.'), end;
2445 /* 254 is the maximum DNS label length, see RFC 1035 */
2446 WCHAR component[255];
2449 end = dot ? dot : ptr + strlenW(ptr);
2451 if (len >= sizeof(component) / sizeof(component[0]))
2453 WARN_(chain)("domain component %s too long\n",
2454 debugstr_wn(ptr, len));
2459 memcpy(component, ptr, len * sizeof(WCHAR));
2461 matches = find_matching_domain_component(name, component);
2463 ptr = dot ? dot + 1 : end;
2464 } while (matches && ptr && *ptr);
2468 PCERT_RDN_ATTR attr;
2470 /* If the certificate isn't using a DN attribute in the name, make
2471 * make sure the common name matches. Again, use memicmpW rather
2472 * than strcmpiW in order to avoid being fooled by an embedded NULL.
2474 if ((attr = CertFindRDNAttr(szOID_COMMON_NAME, name)))
2476 TRACE_(chain)("CN = %s\n", debugstr_w(
2477 (LPWSTR)attr->Value.pbData));
2478 matches = !memicmpW(server_name, (LPWSTR)attr->Value.pbData,
2479 attr->Value.cbData / sizeof(WCHAR));
2487 static BOOL WINAPI verify_ssl_policy(LPCSTR szPolicyOID,
2488 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2489 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2491 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2492 if (pChainContext->TrustStatus.dwErrorStatus &
2493 CERT_TRUST_IS_NOT_SIGNATURE_VALID)
2495 pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
2496 find_element_with_error(pChainContext,
2497 CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
2498 &pPolicyStatus->lElementIndex);
2500 else if (pChainContext->TrustStatus.dwErrorStatus &
2501 CERT_TRUST_IS_UNTRUSTED_ROOT)
2503 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
2504 find_element_with_error(pChainContext,
2505 CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
2506 &pPolicyStatus->lElementIndex);
2508 else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
2510 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
2511 find_element_with_error(pChainContext,
2512 CERT_TRUST_IS_CYCLIC, &pPolicyStatus->lChainIndex,
2513 &pPolicyStatus->lElementIndex);
2514 /* For a cyclic chain, which element is a cycle isn't meaningful */
2515 pPolicyStatus->lElementIndex = -1;
2517 else if (pChainContext->TrustStatus.dwErrorStatus &
2518 CERT_TRUST_IS_NOT_TIME_VALID)
2520 pPolicyStatus->dwError = CERT_E_EXPIRED;
2521 find_element_with_error(pChainContext,
2522 CERT_TRUST_IS_NOT_TIME_VALID, &pPolicyStatus->lChainIndex,
2523 &pPolicyStatus->lElementIndex);
2526 pPolicyStatus->dwError = NO_ERROR;
2527 /* We only need bother checking whether the name in the end certificate
2528 * matches if the chain is otherwise okay.
2530 if (!pPolicyStatus->dwError && pPolicyPara &&
2531 pPolicyPara->cbSize >= sizeof(CERT_CHAIN_POLICY_PARA))
2533 HTTPSPolicyCallbackData *sslPara = pPolicyPara->pvExtraPolicyPara;
2535 if (sslPara && sslPara->u.cbSize >= sizeof(HTTPSPolicyCallbackData))
2537 if (sslPara->dwAuthType == AUTHTYPE_SERVER &&
2538 sslPara->pwszServerName)
2540 PCCERT_CONTEXT cert;
2541 PCERT_EXTENSION altNameExt;
2544 cert = pChainContext->rgpChain[0]->rgpElement[0]->pCertContext;
2545 altNameExt = get_subject_alt_name_ext(cert->pCertInfo);
2546 /* If the alternate name extension exists, the name it contains
2547 * is bound to the certificate, so make sure the name matches
2548 * it. Otherwise, look for the server name in the subject
2549 * distinguished name. RFC5280, section 4.2.1.6:
2550 * "Whenever such identities are to be bound into a
2551 * certificate, the subject alternative name (or issuer
2552 * alternative name) extension MUST be used; however, a DNS
2553 * name MAY also be represented in the subject field using the
2554 * domainComponent attribute."
2557 matches = match_dns_to_subject_alt_name(altNameExt,
2558 sslPara->pwszServerName);
2560 matches = match_dns_to_subject_dn(cert,
2561 sslPara->pwszServerName);
2564 pPolicyStatus->dwError = CERT_E_CN_NO_MATCH;
2565 pPolicyStatus->lChainIndex = 0;
2566 pPolicyStatus->lElementIndex = 0;
2574 static BYTE msPubKey1[] = {
2575 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xdf,0x08,0xba,0xe3,0x3f,0x6e,
2576 0x64,0x9b,0xf5,0x89,0xaf,0x28,0x96,0x4a,0x07,0x8f,0x1b,0x2e,0x8b,0x3e,0x1d,
2577 0xfc,0xb8,0x80,0x69,0xa3,0xa1,0xce,0xdb,0xdf,0xb0,0x8e,0x6c,0x89,0x76,0x29,
2578 0x4f,0xca,0x60,0x35,0x39,0xad,0x72,0x32,0xe0,0x0b,0xae,0x29,0x3d,0x4c,0x16,
2579 0xd9,0x4b,0x3c,0x9d,0xda,0xc5,0xd3,0xd1,0x09,0xc9,0x2c,0x6f,0xa6,0xc2,0x60,
2580 0x53,0x45,0xdd,0x4b,0xd1,0x55,0xcd,0x03,0x1c,0xd2,0x59,0x56,0x24,0xf3,0xe5,
2581 0x78,0xd8,0x07,0xcc,0xd8,0xb3,0x1f,0x90,0x3f,0xc0,0x1a,0x71,0x50,0x1d,0x2d,
2582 0xa7,0x12,0x08,0x6d,0x7c,0xb0,0x86,0x6c,0xc7,0xba,0x85,0x32,0x07,0xe1,0x61,
2583 0x6f,0xaf,0x03,0xc5,0x6d,0xe5,0xd6,0xa1,0x8f,0x36,0xf6,0xc1,0x0b,0xd1,0x3e,
2584 0x69,0x97,0x48,0x72,0xc9,0x7f,0xa4,0xc8,0xc2,0x4a,0x4c,0x7e,0xa1,0xd1,0x94,
2585 0xa6,0xd7,0xdc,0xeb,0x05,0x46,0x2e,0xb8,0x18,0xb4,0x57,0x1d,0x86,0x49,0xdb,
2586 0x69,0x4a,0x2c,0x21,0xf5,0x5e,0x0f,0x54,0x2d,0x5a,0x43,0xa9,0x7a,0x7e,0x6a,
2587 0x8e,0x50,0x4d,0x25,0x57,0xa1,0xbf,0x1b,0x15,0x05,0x43,0x7b,0x2c,0x05,0x8d,
2588 0xbd,0x3d,0x03,0x8c,0x93,0x22,0x7d,0x63,0xea,0x0a,0x57,0x05,0x06,0x0a,0xdb,
2589 0x61,0x98,0x65,0x2d,0x47,0x49,0xa8,0xe7,0xe6,0x56,0x75,0x5c,0xb8,0x64,0x08,
2590 0x63,0xa9,0x30,0x40,0x66,0xb2,0xf9,0xb6,0xe3,0x34,0xe8,0x67,0x30,0xe1,0x43,
2591 0x0b,0x87,0xff,0xc9,0xbe,0x72,0x10,0x5e,0x23,0xf0,0x9b,0xa7,0x48,0x65,0xbf,
2592 0x09,0x88,0x7b,0xcd,0x72,0xbc,0x2e,0x79,0x9b,0x7b,0x02,0x03,0x01,0x00,0x01 };
2593 static BYTE msPubKey2[] = {
2594 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xa9,0x02,0xbd,0xc1,0x70,0xe6,
2595 0x3b,0xf2,0x4e,0x1b,0x28,0x9f,0x97,0x78,0x5e,0x30,0xea,0xa2,0xa9,0x8d,0x25,
2596 0x5f,0xf8,0xfe,0x95,0x4c,0xa3,0xb7,0xfe,0x9d,0xa2,0x20,0x3e,0x7c,0x51,0xa2,
2597 0x9b,0xa2,0x8f,0x60,0x32,0x6b,0xd1,0x42,0x64,0x79,0xee,0xac,0x76,0xc9,0x54,
2598 0xda,0xf2,0xeb,0x9c,0x86,0x1c,0x8f,0x9f,0x84,0x66,0xb3,0xc5,0x6b,0x7a,0x62,
2599 0x23,0xd6,0x1d,0x3c,0xde,0x0f,0x01,0x92,0xe8,0x96,0xc4,0xbf,0x2d,0x66,0x9a,
2600 0x9a,0x68,0x26,0x99,0xd0,0x3a,0x2c,0xbf,0x0c,0xb5,0x58,0x26,0xc1,0x46,0xe7,
2601 0x0a,0x3e,0x38,0x96,0x2c,0xa9,0x28,0x39,0xa8,0xec,0x49,0x83,0x42,0xe3,0x84,
2602 0x0f,0xbb,0x9a,0x6c,0x55,0x61,0xac,0x82,0x7c,0xa1,0x60,0x2d,0x77,0x4c,0xe9,
2603 0x99,0xb4,0x64,0x3b,0x9a,0x50,0x1c,0x31,0x08,0x24,0x14,0x9f,0xa9,0xe7,0x91,
2604 0x2b,0x18,0xe6,0x3d,0x98,0x63,0x14,0x60,0x58,0x05,0x65,0x9f,0x1d,0x37,0x52,
2605 0x87,0xf7,0xa7,0xef,0x94,0x02,0xc6,0x1b,0xd3,0xbf,0x55,0x45,0xb3,0x89,0x80,
2606 0xbf,0x3a,0xec,0x54,0x94,0x4e,0xae,0xfd,0xa7,0x7a,0x6d,0x74,0x4e,0xaf,0x18,
2607 0xcc,0x96,0x09,0x28,0x21,0x00,0x57,0x90,0x60,0x69,0x37,0xbb,0x4b,0x12,0x07,
2608 0x3c,0x56,0xff,0x5b,0xfb,0xa4,0x66,0x0a,0x08,0xa6,0xd2,0x81,0x56,0x57,0xef,
2609 0xb6,0x3b,0x5e,0x16,0x81,0x77,0x04,0xda,0xf6,0xbe,0xae,0x80,0x95,0xfe,0xb0,
2610 0xcd,0x7f,0xd6,0xa7,0x1a,0x72,0x5c,0x3c,0xca,0xbc,0xf0,0x08,0xa3,0x22,0x30,
2611 0xb3,0x06,0x85,0xc9,0xb3,0x20,0x77,0x13,0x85,0xdf,0x02,0x03,0x01,0x00,0x01 };
2612 static BYTE msPubKey3[] = {
2613 0x30,0x82,0x02,0x0a,0x02,0x82,0x02,0x01,0x00,0xf3,0x5d,0xfa,0x80,0x67,0xd4,
2614 0x5a,0xa7,0xa9,0x0c,0x2c,0x90,0x20,0xd0,0x35,0x08,0x3c,0x75,0x84,0xcd,0xb7,
2615 0x07,0x89,0x9c,0x89,0xda,0xde,0xce,0xc3,0x60,0xfa,0x91,0x68,0x5a,0x9e,0x94,
2616 0x71,0x29,0x18,0x76,0x7c,0xc2,0xe0,0xc8,0x25,0x76,0x94,0x0e,0x58,0xfa,0x04,
2617 0x34,0x36,0xe6,0xdf,0xaf,0xf7,0x80,0xba,0xe9,0x58,0x0b,0x2b,0x93,0xe5,0x9d,
2618 0x05,0xe3,0x77,0x22,0x91,0xf7,0x34,0x64,0x3c,0x22,0x91,0x1d,0x5e,0xe1,0x09,
2619 0x90,0xbc,0x14,0xfe,0xfc,0x75,0x58,0x19,0xe1,0x79,0xb7,0x07,0x92,0xa3,0xae,
2620 0x88,0x59,0x08,0xd8,0x9f,0x07,0xca,0x03,0x58,0xfc,0x68,0x29,0x6d,0x32,0xd7,
2621 0xd2,0xa8,0xcb,0x4b,0xfc,0xe1,0x0b,0x48,0x32,0x4f,0xe6,0xeb,0xb8,0xad,0x4f,
2622 0xe4,0x5c,0x6f,0x13,0x94,0x99,0xdb,0x95,0xd5,0x75,0xdb,0xa8,0x1a,0xb7,0x94,
2623 0x91,0xb4,0x77,0x5b,0xf5,0x48,0x0c,0x8f,0x6a,0x79,0x7d,0x14,0x70,0x04,0x7d,
2624 0x6d,0xaf,0x90,0xf5,0xda,0x70,0xd8,0x47,0xb7,0xbf,0x9b,0x2f,0x6c,0xe7,0x05,
2625 0xb7,0xe1,0x11,0x60,0xac,0x79,0x91,0x14,0x7c,0xc5,0xd6,0xa6,0xe4,0xe1,0x7e,
2626 0xd5,0xc3,0x7e,0xe5,0x92,0xd2,0x3c,0x00,0xb5,0x36,0x82,0xde,0x79,0xe1,0x6d,
2627 0xf3,0xb5,0x6e,0xf8,0x9f,0x33,0xc9,0xcb,0x52,0x7d,0x73,0x98,0x36,0xdb,0x8b,
2628 0xa1,0x6b,0xa2,0x95,0x97,0x9b,0xa3,0xde,0xc2,0x4d,0x26,0xff,0x06,0x96,0x67,
2629 0x25,0x06,0xc8,0xe7,0xac,0xe4,0xee,0x12,0x33,0x95,0x31,0x99,0xc8,0x35,0x08,
2630 0x4e,0x34,0xca,0x79,0x53,0xd5,0xb5,0xbe,0x63,0x32,0x59,0x40,0x36,0xc0,0xa5,
2631 0x4e,0x04,0x4d,0x3d,0xdb,0x5b,0x07,0x33,0xe4,0x58,0xbf,0xef,0x3f,0x53,0x64,
2632 0xd8,0x42,0x59,0x35,0x57,0xfd,0x0f,0x45,0x7c,0x24,0x04,0x4d,0x9e,0xd6,0x38,
2633 0x74,0x11,0x97,0x22,0x90,0xce,0x68,0x44,0x74,0x92,0x6f,0xd5,0x4b,0x6f,0xb0,
2634 0x86,0xe3,0xc7,0x36,0x42,0xa0,0xd0,0xfc,0xc1,0xc0,0x5a,0xf9,0xa3,0x61,0xb9,
2635 0x30,0x47,0x71,0x96,0x0a,0x16,0xb0,0x91,0xc0,0x42,0x95,0xef,0x10,0x7f,0x28,
2636 0x6a,0xe3,0x2a,0x1f,0xb1,0xe4,0xcd,0x03,0x3f,0x77,0x71,0x04,0xc7,0x20,0xfc,
2637 0x49,0x0f,0x1d,0x45,0x88,0xa4,0xd7,0xcb,0x7e,0x88,0xad,0x8e,0x2d,0xec,0x45,
2638 0xdb,0xc4,0x51,0x04,0xc9,0x2a,0xfc,0xec,0x86,0x9e,0x9a,0x11,0x97,0x5b,0xde,
2639 0xce,0x53,0x88,0xe6,0xe2,0xb7,0xfd,0xac,0x95,0xc2,0x28,0x40,0xdb,0xef,0x04,
2640 0x90,0xdf,0x81,0x33,0x39,0xd9,0xb2,0x45,0xa5,0x23,0x87,0x06,0xa5,0x55,0x89,
2641 0x31,0xbb,0x06,0x2d,0x60,0x0e,0x41,0x18,0x7d,0x1f,0x2e,0xb5,0x97,0xcb,0x11,
2642 0xeb,0x15,0xd5,0x24,0xa5,0x94,0xef,0x15,0x14,0x89,0xfd,0x4b,0x73,0xfa,0x32,
2643 0x5b,0xfc,0xd1,0x33,0x00,0xf9,0x59,0x62,0x70,0x07,0x32,0xea,0x2e,0xab,0x40,
2644 0x2d,0x7b,0xca,0xdd,0x21,0x67,0x1b,0x30,0x99,0x8f,0x16,0xaa,0x23,0xa8,0x41,
2645 0xd1,0xb0,0x6e,0x11,0x9b,0x36,0xc4,0xde,0x40,0x74,0x9c,0xe1,0x58,0x65,0xc1,
2646 0x60,0x1e,0x7a,0x5b,0x38,0xc8,0x8f,0xbb,0x04,0x26,0x7c,0xd4,0x16,0x40,0xe5,
2647 0xb6,0x6b,0x6c,0xaa,0x86,0xfd,0x00,0xbf,0xce,0xc1,0x35,0x02,0x03,0x01,0x00,
2650 static BOOL WINAPI verify_ms_root_policy(LPCSTR szPolicyOID,
2651 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2652 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2654 BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
2657 if (ret && !pPolicyStatus->dwError)
2659 CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
2660 BOOL isMSRoot = FALSE;
2662 CRYPT_DATA_BLOB keyBlobs[] = {
2663 { sizeof(msPubKey1), msPubKey1 },
2664 { sizeof(msPubKey2), msPubKey2 },
2665 { sizeof(msPubKey3), msPubKey3 },
2667 PCERT_SIMPLE_CHAIN rootChain =
2668 pChainContext->rgpChain[pChainContext->cChain -1 ];
2669 PCCERT_CONTEXT root =
2670 rootChain->rgpElement[rootChain->cElement - 1]->pCertContext;
2672 for (i = 0; !isMSRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
2675 msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
2676 msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
2677 if (CertComparePublicKeyInfo(
2678 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
2679 &root->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
2683 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = 0;
2688 typedef BOOL (WINAPI *CertVerifyCertificateChainPolicyFunc)(LPCSTR szPolicyOID,
2689 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2690 PCERT_CHAIN_POLICY_STATUS pPolicyStatus);
2692 BOOL WINAPI CertVerifyCertificateChainPolicy(LPCSTR szPolicyOID,
2693 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2694 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2696 static HCRYPTOIDFUNCSET set = NULL;
2698 CertVerifyCertificateChainPolicyFunc verifyPolicy = NULL;
2699 HCRYPTOIDFUNCADDR hFunc = NULL;
2701 TRACE("(%s, %p, %p, %p)\n", debugstr_a(szPolicyOID), pChainContext,
2702 pPolicyPara, pPolicyStatus);
2704 if (!HIWORD(szPolicyOID))
2706 switch (LOWORD(szPolicyOID))
2708 case LOWORD(CERT_CHAIN_POLICY_BASE):
2709 verifyPolicy = verify_base_policy;
2711 case LOWORD(CERT_CHAIN_POLICY_AUTHENTICODE):
2712 verifyPolicy = verify_authenticode_policy;
2714 case LOWORD(CERT_CHAIN_POLICY_SSL):
2715 verifyPolicy = verify_ssl_policy;
2717 case LOWORD(CERT_CHAIN_POLICY_BASIC_CONSTRAINTS):
2718 verifyPolicy = verify_basic_constraints_policy;
2720 case LOWORD(CERT_CHAIN_POLICY_MICROSOFT_ROOT):
2721 verifyPolicy = verify_ms_root_policy;
2724 FIXME("unimplemented for %d\n", LOWORD(szPolicyOID));
2730 set = CryptInitOIDFunctionSet(
2731 CRYPT_OID_VERIFY_CERTIFICATE_CHAIN_POLICY_FUNC, 0);
2732 CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING, szPolicyOID, 0,
2733 (void **)&verifyPolicy, &hFunc);
2736 ret = verifyPolicy(szPolicyOID, pChainContext, pPolicyPara,
2739 CryptFreeOIDFunctionAddress(hFunc, 0);
2740 TRACE("returning %d (%08x)\n", ret, pPolicyStatus->dwError);