wined3d: Record sampler usage for WINED3DSIH_LD_RAW.
[wine.git] / dlls / crypt32 / chain.c
blobaab2e91583bc45d4c02182b243bbe99bb453e26c
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 "wininet.h"
27 #include "wine/debug.h"
28 #include "wine/unicode.h"
29 #include "crypt32_private.h"
31 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
32 WINE_DECLARE_DEBUG_CHANNEL(chain);
34 #define DEFAULT_CYCLE_MODULUS 7
36 /* This represents a subset of a certificate chain engine: it doesn't include
37 * the "hOther" store described by MSDN, because I'm not sure how that's used.
38 * It also doesn't include the "hTrust" store, because I don't yet implement
39 * CTLs or complex certificate chains.
41 typedef struct _CertificateChainEngine
43 LONG ref;
44 HCERTSTORE hRoot;
45 HCERTSTORE hWorld;
46 DWORD dwFlags;
47 DWORD dwUrlRetrievalTimeout;
48 DWORD MaximumCachedCertificates;
49 DWORD CycleDetectionModulus;
50 } CertificateChainEngine;
52 static inline void CRYPT_AddStoresToCollection(HCERTSTORE collection,
53 DWORD cStores, HCERTSTORE *stores)
55 DWORD i;
57 for (i = 0; i < cStores; i++)
58 CertAddStoreToCollection(collection, stores[i], 0, 0);
61 static inline void CRYPT_CloseStores(DWORD cStores, HCERTSTORE *stores)
63 DWORD i;
65 for (i = 0; i < cStores; i++)
66 CertCloseStore(stores[i], 0);
69 static const WCHAR rootW[] = { 'R','o','o','t',0 };
71 /* Finds cert in store by comparing the cert's hashes. */
72 static PCCERT_CONTEXT CRYPT_FindCertInStore(HCERTSTORE store,
73 PCCERT_CONTEXT cert)
75 PCCERT_CONTEXT matching = NULL;
76 BYTE hash[20];
77 DWORD size = sizeof(hash);
79 if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID, hash, &size))
81 CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
83 matching = CertFindCertificateInStore(store, cert->dwCertEncodingType,
84 0, CERT_FIND_SHA1_HASH, &blob, NULL);
86 return matching;
89 static BOOL CRYPT_CheckRestrictedRoot(HCERTSTORE store)
91 BOOL ret = TRUE;
93 if (store)
95 HCERTSTORE rootStore = CertOpenSystemStoreW(0, rootW);
96 PCCERT_CONTEXT cert = NULL, check;
98 do {
99 cert = CertEnumCertificatesInStore(store, cert);
100 if (cert)
102 if (!(check = CRYPT_FindCertInStore(rootStore, cert)))
103 ret = FALSE;
104 else
105 CertFreeCertificateContext(check);
107 } while (ret && cert);
108 if (cert)
109 CertFreeCertificateContext(cert);
110 CertCloseStore(rootStore, 0);
112 return ret;
115 HCERTCHAINENGINE CRYPT_CreateChainEngine(HCERTSTORE root, DWORD system_store, const CERT_CHAIN_ENGINE_CONFIG *config)
117 CertificateChainEngine *engine;
118 HCERTSTORE worldStores[4];
120 static const WCHAR caW[] = { 'C','A',0 };
121 static const WCHAR myW[] = { 'M','y',0 };
122 static const WCHAR trustW[] = { 'T','r','u','s','t',0 };
124 if(!root) {
125 if(config->cbSize >= sizeof(CERT_CHAIN_ENGINE_CONFIG) && config->hExclusiveRoot)
126 root = CertDuplicateStore(config->hExclusiveRoot);
127 else if (config->hRestrictedRoot)
128 root = CertDuplicateStore(config->hRestrictedRoot);
129 else
130 root = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0, system_store, rootW);
131 if(!root)
132 return NULL;
135 engine = CryptMemAlloc(sizeof(CertificateChainEngine));
136 if(!engine) {
137 CertCloseStore(root, 0);
138 return NULL;
141 engine->ref = 1;
142 engine->hRoot = root;
143 engine->hWorld = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL);
144 worldStores[0] = CertDuplicateStore(engine->hRoot);
145 worldStores[1] = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0, system_store, caW);
146 worldStores[2] = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0, system_store, myW);
147 worldStores[3] = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0, system_store, trustW);
149 CRYPT_AddStoresToCollection(engine->hWorld, sizeof(worldStores) / sizeof(worldStores[0]), worldStores);
150 CRYPT_AddStoresToCollection(engine->hWorld, config->cAdditionalStore, config->rghAdditionalStore);
151 CRYPT_CloseStores(sizeof(worldStores) / sizeof(worldStores[0]), worldStores);
153 engine->dwFlags = config->dwFlags;
154 engine->dwUrlRetrievalTimeout = config->dwUrlRetrievalTimeout;
155 engine->MaximumCachedCertificates = config->MaximumCachedCertificates;
156 if(config->CycleDetectionModulus)
157 engine->CycleDetectionModulus = config->CycleDetectionModulus;
158 else
159 engine->CycleDetectionModulus = DEFAULT_CYCLE_MODULUS;
161 return engine;
164 static CertificateChainEngine *default_cu_engine, *default_lm_engine;
166 static CertificateChainEngine *get_chain_engine(HCERTCHAINENGINE handle, BOOL allow_default)
168 const CERT_CHAIN_ENGINE_CONFIG config = { sizeof(config) };
170 if(handle == HCCE_CURRENT_USER) {
171 if(!allow_default)
172 return NULL;
174 if(!default_cu_engine) {
175 handle = CRYPT_CreateChainEngine(NULL, CERT_SYSTEM_STORE_CURRENT_USER, &config);
176 InterlockedCompareExchangePointer((void**)&default_cu_engine, handle, NULL);
177 if(default_cu_engine != handle)
178 CertFreeCertificateChainEngine(handle);
181 return default_cu_engine;
184 if(handle == HCCE_LOCAL_MACHINE) {
185 if(!allow_default)
186 return NULL;
188 if(!default_lm_engine) {
189 handle = CRYPT_CreateChainEngine(NULL, CERT_SYSTEM_STORE_LOCAL_MACHINE, &config);
190 InterlockedCompareExchangePointer((void**)&default_lm_engine, handle, NULL);
191 if(default_lm_engine != handle)
192 CertFreeCertificateChainEngine(handle);
195 return default_lm_engine;
198 return (CertificateChainEngine*)handle;
201 static void free_chain_engine(CertificateChainEngine *engine)
203 if(!engine || InterlockedDecrement(&engine->ref))
204 return;
206 CertCloseStore(engine->hWorld, 0);
207 CertCloseStore(engine->hRoot, 0);
208 CryptMemFree(engine);
211 typedef struct _CERT_CHAIN_ENGINE_CONFIG_NO_EXCLUSIVE_ROOT
213 DWORD cbSize;
214 HCERTSTORE hRestrictedRoot;
215 HCERTSTORE hRestrictedTrust;
216 HCERTSTORE hRestrictedOther;
217 DWORD cAdditionalStore;
218 HCERTSTORE *rghAdditionalStore;
219 DWORD dwFlags;
220 DWORD dwUrlRetrievalTimeout;
221 DWORD MaximumCachedCertificates;
222 DWORD CycleDetectionModulus;
223 } CERT_CHAIN_ENGINE_CONFIG_NO_EXCLUSIVE_ROOT;
225 BOOL WINAPI CertCreateCertificateChainEngine(PCERT_CHAIN_ENGINE_CONFIG pConfig,
226 HCERTCHAINENGINE *phChainEngine)
228 BOOL ret;
230 TRACE("(%p, %p)\n", pConfig, phChainEngine);
232 if (pConfig->cbSize != sizeof(CERT_CHAIN_ENGINE_CONFIG_NO_EXCLUSIVE_ROOT)
233 && pConfig->cbSize != sizeof(CERT_CHAIN_ENGINE_CONFIG))
235 SetLastError(E_INVALIDARG);
236 return FALSE;
238 ret = CRYPT_CheckRestrictedRoot(pConfig->hRestrictedRoot);
239 if (!ret)
241 *phChainEngine = NULL;
242 return FALSE;
245 *phChainEngine = CRYPT_CreateChainEngine(NULL, CERT_SYSTEM_STORE_CURRENT_USER, pConfig);
246 return *phChainEngine != NULL;
249 void WINAPI CertFreeCertificateChainEngine(HCERTCHAINENGINE hChainEngine)
251 TRACE("(%p)\n", hChainEngine);
252 free_chain_engine(get_chain_engine(hChainEngine, FALSE));
255 void default_chain_engine_free(void)
257 free_chain_engine(default_cu_engine);
258 free_chain_engine(default_lm_engine);
261 typedef struct _CertificateChain
263 CERT_CHAIN_CONTEXT context;
264 HCERTSTORE world;
265 LONG ref;
266 } CertificateChain;
268 BOOL CRYPT_IsCertificateSelfSigned(PCCERT_CONTEXT cert)
270 PCERT_EXTENSION ext;
271 DWORD size;
272 BOOL ret;
274 if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
275 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension)))
277 CERT_AUTHORITY_KEY_ID2_INFO *info;
279 ret = CryptDecodeObjectEx(cert->dwCertEncodingType,
280 X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
281 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
282 &info, &size);
283 if (ret)
285 if (info->AuthorityCertIssuer.cAltEntry &&
286 info->AuthorityCertSerialNumber.cbData)
288 PCERT_ALT_NAME_ENTRY directoryName = NULL;
289 DWORD i;
291 for (i = 0; !directoryName &&
292 i < info->AuthorityCertIssuer.cAltEntry; i++)
293 if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
294 == CERT_ALT_NAME_DIRECTORY_NAME)
295 directoryName =
296 &info->AuthorityCertIssuer.rgAltEntry[i];
297 if (directoryName)
299 ret = CertCompareCertificateName(cert->dwCertEncodingType,
300 &directoryName->u.DirectoryName, &cert->pCertInfo->Issuer)
301 && CertCompareIntegerBlob(&info->AuthorityCertSerialNumber,
302 &cert->pCertInfo->SerialNumber);
304 else
306 FIXME("no supported name type in authority key id2\n");
307 ret = FALSE;
310 else if (info->KeyId.cbData)
312 ret = CertGetCertificateContextProperty(cert,
313 CERT_KEY_IDENTIFIER_PROP_ID, NULL, &size);
314 if (ret && size == info->KeyId.cbData)
316 LPBYTE buf = CryptMemAlloc(size);
318 if (buf)
320 CertGetCertificateContextProperty(cert,
321 CERT_KEY_IDENTIFIER_PROP_ID, buf, &size);
322 ret = !memcmp(buf, info->KeyId.pbData, size);
323 CryptMemFree(buf);
325 else
326 ret = FALSE;
328 else
329 ret = FALSE;
331 LocalFree(info);
334 else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
335 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension)))
337 CERT_AUTHORITY_KEY_ID_INFO *info;
339 ret = CryptDecodeObjectEx(cert->dwCertEncodingType,
340 X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
341 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
342 &info, &size);
343 if (ret)
345 if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
347 ret = CertCompareCertificateName(cert->dwCertEncodingType,
348 &info->CertIssuer, &cert->pCertInfo->Issuer) &&
349 CertCompareIntegerBlob(&info->CertSerialNumber,
350 &cert->pCertInfo->SerialNumber);
352 else if (info->KeyId.cbData)
354 ret = CertGetCertificateContextProperty(cert,
355 CERT_KEY_IDENTIFIER_PROP_ID, NULL, &size);
356 if (ret && size == info->KeyId.cbData)
358 LPBYTE buf = CryptMemAlloc(size);
360 if (buf)
362 CertGetCertificateContextProperty(cert,
363 CERT_KEY_IDENTIFIER_PROP_ID, buf, &size);
364 ret = !memcmp(buf, info->KeyId.pbData, size);
365 CryptMemFree(buf);
367 else
368 ret = FALSE;
370 else
371 ret = FALSE;
373 else
374 ret = FALSE;
375 LocalFree(info);
378 else
379 ret = CertCompareCertificateName(cert->dwCertEncodingType,
380 &cert->pCertInfo->Subject, &cert->pCertInfo->Issuer);
381 return ret;
384 static void CRYPT_FreeChainElement(PCERT_CHAIN_ELEMENT element)
386 CertFreeCertificateContext(element->pCertContext);
387 CryptMemFree(element);
390 static void CRYPT_CheckSimpleChainForCycles(PCERT_SIMPLE_CHAIN chain)
392 DWORD i, j, cyclicCertIndex = 0;
394 /* O(n^2) - I don't think there's a faster way */
395 for (i = 0; !cyclicCertIndex && i < chain->cElement; i++)
396 for (j = i + 1; !cyclicCertIndex && j < chain->cElement; j++)
397 if (CertCompareCertificate(X509_ASN_ENCODING,
398 chain->rgpElement[i]->pCertContext->pCertInfo,
399 chain->rgpElement[j]->pCertContext->pCertInfo))
400 cyclicCertIndex = j;
401 if (cyclicCertIndex)
403 chain->rgpElement[cyclicCertIndex]->TrustStatus.dwErrorStatus
404 |= CERT_TRUST_IS_CYCLIC | CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
405 /* Release remaining certs */
406 for (i = cyclicCertIndex + 1; i < chain->cElement; i++)
407 CRYPT_FreeChainElement(chain->rgpElement[i]);
408 /* Truncate chain */
409 chain->cElement = cyclicCertIndex + 1;
413 /* Checks whether the chain is cyclic by examining the last element's status */
414 static inline BOOL CRYPT_IsSimpleChainCyclic(const CERT_SIMPLE_CHAIN *chain)
416 if (chain->cElement)
417 return chain->rgpElement[chain->cElement - 1]->TrustStatus.dwErrorStatus
418 & CERT_TRUST_IS_CYCLIC;
419 else
420 return FALSE;
423 static inline void CRYPT_CombineTrustStatus(CERT_TRUST_STATUS *chainStatus,
424 const CERT_TRUST_STATUS *elementStatus)
426 /* Any error that applies to an element also applies to a chain.. */
427 chainStatus->dwErrorStatus |= elementStatus->dwErrorStatus;
428 /* but the bottom nibble of an element's info status doesn't apply to the
429 * chain.
431 chainStatus->dwInfoStatus |= (elementStatus->dwInfoStatus & 0xfffffff0);
434 static BOOL CRYPT_AddCertToSimpleChain(const CertificateChainEngine *engine,
435 PCERT_SIMPLE_CHAIN chain, PCCERT_CONTEXT cert, DWORD subjectInfoStatus)
437 BOOL ret = FALSE;
438 PCERT_CHAIN_ELEMENT element = CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
440 if (element)
442 if (!chain->cElement)
443 chain->rgpElement = CryptMemAlloc(sizeof(PCERT_CHAIN_ELEMENT));
444 else
445 chain->rgpElement = CryptMemRealloc(chain->rgpElement,
446 (chain->cElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
447 if (chain->rgpElement)
449 chain->rgpElement[chain->cElement++] = element;
450 memset(element, 0, sizeof(CERT_CHAIN_ELEMENT));
451 element->cbSize = sizeof(CERT_CHAIN_ELEMENT);
452 element->pCertContext = CertDuplicateCertificateContext(cert);
453 if (chain->cElement > 1)
454 chain->rgpElement[chain->cElement - 2]->TrustStatus.dwInfoStatus
455 = subjectInfoStatus;
456 /* FIXME: initialize the rest of element */
457 if (!(chain->cElement % engine->CycleDetectionModulus))
459 CRYPT_CheckSimpleChainForCycles(chain);
460 /* Reinitialize the element pointer in case the chain is
461 * cyclic, in which case the chain is truncated.
463 element = chain->rgpElement[chain->cElement - 1];
465 CRYPT_CombineTrustStatus(&chain->TrustStatus,
466 &element->TrustStatus);
467 ret = TRUE;
469 else
470 CryptMemFree(element);
472 return ret;
475 static void CRYPT_FreeSimpleChain(PCERT_SIMPLE_CHAIN chain)
477 DWORD i;
479 for (i = 0; i < chain->cElement; i++)
480 CRYPT_FreeChainElement(chain->rgpElement[i]);
481 CryptMemFree(chain->rgpElement);
482 CryptMemFree(chain);
485 static void CRYPT_CheckTrustedStatus(HCERTSTORE hRoot,
486 PCERT_CHAIN_ELEMENT rootElement)
488 PCCERT_CONTEXT trustedRoot = CRYPT_FindCertInStore(hRoot,
489 rootElement->pCertContext);
491 if (!trustedRoot)
492 rootElement->TrustStatus.dwErrorStatus |=
493 CERT_TRUST_IS_UNTRUSTED_ROOT;
494 else
495 CertFreeCertificateContext(trustedRoot);
498 static void CRYPT_CheckRootCert(HCERTSTORE hRoot,
499 PCERT_CHAIN_ELEMENT rootElement)
501 PCCERT_CONTEXT root = rootElement->pCertContext;
503 if (!CryptVerifyCertificateSignatureEx(0, root->dwCertEncodingType,
504 CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, (void *)root,
505 CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, (void *)root, 0, NULL))
507 TRACE_(chain)("Last certificate's signature is invalid\n");
508 rootElement->TrustStatus.dwErrorStatus |=
509 CERT_TRUST_IS_NOT_SIGNATURE_VALID;
511 CRYPT_CheckTrustedStatus(hRoot, rootElement);
514 /* Decodes a cert's basic constraints extension (either szOID_BASIC_CONSTRAINTS
515 * or szOID_BASIC_CONSTRAINTS2, whichever is present) into a
516 * CERT_BASIC_CONSTRAINTS2_INFO. If it neither extension is present, sets
517 * constraints->fCA to defaultIfNotSpecified.
518 * Returns FALSE if the extension is present but couldn't be decoded.
520 static BOOL CRYPT_DecodeBasicConstraints(PCCERT_CONTEXT cert,
521 CERT_BASIC_CONSTRAINTS2_INFO *constraints, BOOL defaultIfNotSpecified)
523 BOOL ret = TRUE;
524 PCERT_EXTENSION ext = CertFindExtension(szOID_BASIC_CONSTRAINTS,
525 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
527 constraints->fPathLenConstraint = FALSE;
528 if (ext)
530 CERT_BASIC_CONSTRAINTS_INFO *info;
531 DWORD size = 0;
533 ret = CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
534 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
535 NULL, &info, &size);
536 if (ret)
538 if (info->SubjectType.cbData == 1)
539 constraints->fCA =
540 info->SubjectType.pbData[0] & CERT_CA_SUBJECT_FLAG;
541 LocalFree(info);
544 else
546 ext = CertFindExtension(szOID_BASIC_CONSTRAINTS2,
547 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
548 if (ext)
550 DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
552 ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
553 szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
554 0, NULL, constraints, &size);
556 else
557 constraints->fCA = defaultIfNotSpecified;
559 return ret;
562 /* Checks element's basic constraints to see if it can act as a CA, with
563 * remainingCAs CAs left in this chain. In general, a cert must include the
564 * basic constraints extension, with the CA flag asserted, in order to be
565 * allowed to be a CA. A V1 or V2 cert, which has no extensions, is also
566 * allowed to be a CA if it's installed locally (in the engine's world store.)
567 * This matches the expected usage in RFC 5280, section 4.2.1.9: a conforming
568 * CA MUST include the basic constraints extension in all certificates that are
569 * used to validate digital signatures on certificates. It also matches
570 * section 6.1.4(k): "If a certificate is a v1 or v2 certificate, then the
571 * application MUST either verify that the certificate is a CA certificate
572 * through out-of-band means or reject the certificate." Rejecting the
573 * certificate prohibits a large number of commonly used certificates, so
574 * accepting locally installed ones is a compromise.
575 * Root certificates are also allowed to be CAs even without a basic
576 * constraints extension. This is implied by RFC 5280, section 6.1: the
577 * root of a certificate chain's only requirement is that it was used to issue
578 * the next certificate in the chain.
579 * Updates chainConstraints with the element's constraints, if:
580 * 1. chainConstraints doesn't have a path length constraint, or
581 * 2. element's path length constraint is smaller than chainConstraints's
582 * Sets *pathLengthConstraintViolated to TRUE if a path length violation
583 * occurs.
584 * Returns TRUE if the element can be a CA, and the length of the remaining
585 * chain is valid.
587 static BOOL CRYPT_CheckBasicConstraintsForCA(CertificateChainEngine *engine,
588 PCCERT_CONTEXT cert, CERT_BASIC_CONSTRAINTS2_INFO *chainConstraints,
589 DWORD remainingCAs, BOOL isRoot, BOOL *pathLengthConstraintViolated)
591 BOOL validBasicConstraints, implicitCA = FALSE;
592 CERT_BASIC_CONSTRAINTS2_INFO constraints;
594 if (isRoot)
595 implicitCA = TRUE;
596 else if (cert->pCertInfo->dwVersion == CERT_V1 ||
597 cert->pCertInfo->dwVersion == CERT_V2)
599 BYTE hash[20];
600 DWORD size = sizeof(hash);
602 if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID,
603 hash, &size))
605 CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
606 PCCERT_CONTEXT localCert = CertFindCertificateInStore(
607 engine->hWorld, cert->dwCertEncodingType, 0, CERT_FIND_SHA1_HASH,
608 &blob, NULL);
610 if (localCert)
612 CertFreeCertificateContext(localCert);
613 implicitCA = TRUE;
617 if ((validBasicConstraints = CRYPT_DecodeBasicConstraints(cert,
618 &constraints, implicitCA)))
620 chainConstraints->fCA = constraints.fCA;
621 if (!constraints.fCA)
623 TRACE_(chain)("chain element %d can't be a CA\n", remainingCAs + 1);
624 validBasicConstraints = FALSE;
626 else if (constraints.fPathLenConstraint)
628 /* If the element has path length constraints, they apply to the
629 * entire remaining chain.
631 if (!chainConstraints->fPathLenConstraint ||
632 constraints.dwPathLenConstraint <
633 chainConstraints->dwPathLenConstraint)
635 TRACE_(chain)("setting path length constraint to %d\n",
636 chainConstraints->dwPathLenConstraint);
637 chainConstraints->fPathLenConstraint = TRUE;
638 chainConstraints->dwPathLenConstraint =
639 constraints.dwPathLenConstraint;
643 if (chainConstraints->fPathLenConstraint &&
644 remainingCAs > chainConstraints->dwPathLenConstraint)
646 TRACE_(chain)("remaining CAs %d exceed max path length %d\n",
647 remainingCAs, chainConstraints->dwPathLenConstraint);
648 validBasicConstraints = FALSE;
649 *pathLengthConstraintViolated = TRUE;
651 return validBasicConstraints;
654 static BOOL domain_name_matches(LPCWSTR constraint, LPCWSTR name)
656 BOOL match;
658 /* RFC 5280, section 4.2.1.10:
659 * "For URIs, the constraint applies to the host part of the name...
660 * When the constraint begins with a period, it MAY be expanded with one
661 * or more labels. That is, the constraint ".example.com" is satisfied by
662 * both host.example.com and my.host.example.com. However, the constraint
663 * ".example.com" is not satisfied by "example.com". When the constraint
664 * does not begin with a period, it specifies a host."
665 * and for email addresses,
666 * "To indicate all Internet mail addresses on a particular host, the
667 * constraint is specified as the host name. For example, the constraint
668 * "example.com" is satisfied by any mail address at the host
669 * "example.com". To specify any address within a domain, the constraint
670 * is specified with a leading period (as with URIs)."
672 if (constraint[0] == '.')
674 /* Must be strictly greater than, a name can't begin with '.' */
675 if (lstrlenW(name) > lstrlenW(constraint))
676 match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
677 constraint);
678 else
680 /* name is too short, no match */
681 match = FALSE;
684 else
685 match = !lstrcmpiW(name, constraint);
686 return match;
689 static BOOL url_matches(LPCWSTR constraint, LPCWSTR name,
690 DWORD *trustErrorStatus)
692 BOOL match = FALSE;
694 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
696 if (!constraint)
697 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
698 else if (!name)
699 ; /* no match */
700 else
702 LPCWSTR colon, authority_end, at, hostname = NULL;
703 /* The maximum length for a hostname is 254 in the DNS, see RFC 1034 */
704 WCHAR hostname_buf[255];
706 /* RFC 5280: only the hostname portion of the URL is compared. From
707 * section 4.2.1.10:
708 * "For URIs, the constraint applies to the host part of the name.
709 * The constraint MUST be specified as a fully qualified domain name
710 * and MAY specify a host or a domain."
711 * The format for URIs is in RFC 2396.
713 * First, remove any scheme that's present. */
714 colon = strchrW(name, ':');
715 if (colon && *(colon + 1) == '/' && *(colon + 2) == '/')
716 name = colon + 3;
717 /* Next, find the end of the authority component. (The authority is
718 * generally just the hostname, but it may contain a username or a port.
719 * Those are removed next.)
721 authority_end = strchrW(name, '/');
722 if (!authority_end)
723 authority_end = strchrW(name, '?');
724 if (!authority_end)
725 authority_end = name + strlenW(name);
726 /* Remove any port number from the authority. The userinfo portion
727 * of an authority may contain a colon, so stop if a userinfo portion
728 * is found (indicated by '@').
730 for (colon = authority_end; colon >= name && *colon != ':' &&
731 *colon != '@'; colon--)
733 if (*colon == ':')
734 authority_end = colon;
735 /* Remove any username from the authority */
736 if ((at = strchrW(name, '@')))
737 name = at;
738 /* Ignore any path or query portion of the URL. */
739 if (*authority_end)
741 if (authority_end - name < sizeof(hostname_buf) /
742 sizeof(hostname_buf[0]))
744 memcpy(hostname_buf, name,
745 (authority_end - name) * sizeof(WCHAR));
746 hostname_buf[authority_end - name] = 0;
747 hostname = hostname_buf;
749 /* else: Hostname is too long, not a match */
751 else
752 hostname = name;
753 if (hostname)
754 match = domain_name_matches(constraint, hostname);
756 return match;
759 static BOOL rfc822_name_matches(LPCWSTR constraint, LPCWSTR name,
760 DWORD *trustErrorStatus)
762 BOOL match = FALSE;
763 LPCWSTR at;
765 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
767 if (!constraint)
768 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
769 else if (!name)
770 ; /* no match */
771 else if (strchrW(constraint, '@'))
772 match = !lstrcmpiW(constraint, name);
773 else
775 if ((at = strchrW(name, '@')))
776 match = domain_name_matches(constraint, at + 1);
777 else
778 match = !lstrcmpiW(constraint, name);
780 return match;
783 static BOOL dns_name_matches(LPCWSTR constraint, LPCWSTR name,
784 DWORD *trustErrorStatus)
786 BOOL match = FALSE;
788 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
790 if (!constraint)
791 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
792 else if (!name)
793 ; /* no match */
794 /* RFC 5280, section 4.2.1.10:
795 * "DNS name restrictions are expressed as host.example.com. Any DNS name
796 * that can be constructed by simply adding zero or more labels to the
797 * left-hand side of the name satisfies the name constraint. For example,
798 * www.host.example.com would satisfy the constraint but host1.example.com
799 * would not."
801 else if (lstrlenW(name) == lstrlenW(constraint))
802 match = !lstrcmpiW(name, constraint);
803 else if (lstrlenW(name) > lstrlenW(constraint))
805 match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
806 constraint);
807 if (match)
809 BOOL dot = FALSE;
810 LPCWSTR ptr;
812 /* This only matches if name is a subdomain of constraint, i.e.
813 * there's a '.' between the beginning of the name and the
814 * matching portion of the name.
816 for (ptr = name + lstrlenW(name) - lstrlenW(constraint);
817 !dot && ptr >= name; ptr--)
818 if (*ptr == '.')
819 dot = TRUE;
820 match = dot;
823 /* else: name is too short, no match */
825 return match;
828 static BOOL ip_address_matches(const CRYPT_DATA_BLOB *constraint,
829 const CRYPT_DATA_BLOB *name, DWORD *trustErrorStatus)
831 BOOL match = FALSE;
833 TRACE("(%d, %p), (%d, %p)\n", constraint->cbData, constraint->pbData,
834 name->cbData, name->pbData);
836 /* RFC5280, section 4.2.1.10, iPAddress syntax: either 8 or 32 bytes, for
837 * IPv4 or IPv6 addresses, respectively.
839 if (constraint->cbData != sizeof(DWORD) * 2 && constraint->cbData != 32)
840 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
841 else if (name->cbData == sizeof(DWORD) &&
842 constraint->cbData == sizeof(DWORD) * 2)
844 DWORD subnet, mask, addr;
846 memcpy(&subnet, constraint->pbData, sizeof(subnet));
847 memcpy(&mask, constraint->pbData + sizeof(subnet), sizeof(mask));
848 memcpy(&addr, name->pbData, sizeof(addr));
849 /* These are really in big-endian order, but for equality matching we
850 * don't need to swap to host order
852 match = (subnet & mask) == (addr & mask);
854 else if (name->cbData == 16 && constraint->cbData == 32)
856 const BYTE *subnet, *mask, *addr;
857 DWORD i;
859 subnet = constraint->pbData;
860 mask = constraint->pbData + 16;
861 addr = name->pbData;
862 match = TRUE;
863 for (i = 0; match && i < 16; i++)
864 if ((subnet[i] & mask[i]) != (addr[i] & mask[i]))
865 match = FALSE;
867 /* else: name is wrong size, no match */
869 return match;
872 static BOOL directory_name_matches(const CERT_NAME_BLOB *constraint,
873 const CERT_NAME_BLOB *name)
875 CERT_NAME_INFO *constraintName;
876 DWORD size;
877 BOOL match = FALSE;
879 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME, constraint->pbData,
880 constraint->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &constraintName, &size))
882 DWORD i;
884 match = TRUE;
885 for (i = 0; match && i < constraintName->cRDN; i++)
886 match = CertIsRDNAttrsInCertificateName(X509_ASN_ENCODING,
887 CERT_CASE_INSENSITIVE_IS_RDN_ATTRS_FLAG,
888 (CERT_NAME_BLOB *)name, &constraintName->rgRDN[i]);
889 LocalFree(constraintName);
891 return match;
894 static BOOL alt_name_matches(const CERT_ALT_NAME_ENTRY *name,
895 const CERT_ALT_NAME_ENTRY *constraint, DWORD *trustErrorStatus, BOOL *present)
897 BOOL match = FALSE;
899 if (name->dwAltNameChoice == constraint->dwAltNameChoice)
901 if (present)
902 *present = TRUE;
903 switch (constraint->dwAltNameChoice)
905 case CERT_ALT_NAME_RFC822_NAME:
906 match = rfc822_name_matches(constraint->u.pwszURL,
907 name->u.pwszURL, trustErrorStatus);
908 break;
909 case CERT_ALT_NAME_DNS_NAME:
910 match = dns_name_matches(constraint->u.pwszURL,
911 name->u.pwszURL, trustErrorStatus);
912 break;
913 case CERT_ALT_NAME_URL:
914 match = url_matches(constraint->u.pwszURL,
915 name->u.pwszURL, trustErrorStatus);
916 break;
917 case CERT_ALT_NAME_IP_ADDRESS:
918 match = ip_address_matches(&constraint->u.IPAddress,
919 &name->u.IPAddress, trustErrorStatus);
920 break;
921 case CERT_ALT_NAME_DIRECTORY_NAME:
922 match = directory_name_matches(&constraint->u.DirectoryName,
923 &name->u.DirectoryName);
924 break;
925 default:
926 ERR("name choice %d unsupported in this context\n",
927 constraint->dwAltNameChoice);
928 *trustErrorStatus |=
929 CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
932 else if (present)
933 *present = FALSE;
934 return match;
937 static BOOL alt_name_matches_excluded_name(const CERT_ALT_NAME_ENTRY *name,
938 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
940 DWORD i;
941 BOOL match = FALSE;
943 for (i = 0; !match && i < nameConstraints->cExcludedSubtree; i++)
944 match = alt_name_matches(name,
945 &nameConstraints->rgExcludedSubtree[i].Base, trustErrorStatus, NULL);
946 return match;
949 static BOOL alt_name_matches_permitted_name(const CERT_ALT_NAME_ENTRY *name,
950 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus,
951 BOOL *present)
953 DWORD i;
954 BOOL match = FALSE;
956 for (i = 0; !match && i < nameConstraints->cPermittedSubtree; i++)
957 match = alt_name_matches(name,
958 &nameConstraints->rgPermittedSubtree[i].Base, trustErrorStatus,
959 present);
960 return match;
963 static inline PCERT_EXTENSION get_subject_alt_name_ext(const CERT_INFO *cert)
965 PCERT_EXTENSION ext;
967 ext = CertFindExtension(szOID_SUBJECT_ALT_NAME2,
968 cert->cExtension, cert->rgExtension);
969 if (!ext)
970 ext = CertFindExtension(szOID_SUBJECT_ALT_NAME,
971 cert->cExtension, cert->rgExtension);
972 return ext;
975 static void compare_alt_name_with_constraints(const CERT_EXTENSION *altNameExt,
976 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
978 CERT_ALT_NAME_INFO *subjectAltName;
979 DWORD size;
981 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
982 altNameExt->Value.pbData, altNameExt->Value.cbData,
983 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
984 &subjectAltName, &size))
986 DWORD i;
988 for (i = 0; i < subjectAltName->cAltEntry; i++)
990 BOOL nameFormPresent;
992 /* A name constraint only applies if the name form is present.
993 * From RFC 5280, section 4.2.1.10:
994 * "Restrictions apply only when the specified name form is
995 * present. If no name of the type is in the certificate,
996 * the certificate is acceptable."
998 if (alt_name_matches_excluded_name(
999 &subjectAltName->rgAltEntry[i], nameConstraints,
1000 trustErrorStatus))
1002 TRACE_(chain)("subject alternate name form %d excluded\n",
1003 subjectAltName->rgAltEntry[i].dwAltNameChoice);
1004 *trustErrorStatus |=
1005 CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
1007 nameFormPresent = FALSE;
1008 if (!alt_name_matches_permitted_name(
1009 &subjectAltName->rgAltEntry[i], nameConstraints,
1010 trustErrorStatus, &nameFormPresent) && nameFormPresent)
1012 TRACE_(chain)("subject alternate name form %d not permitted\n",
1013 subjectAltName->rgAltEntry[i].dwAltNameChoice);
1014 *trustErrorStatus |=
1015 CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
1018 LocalFree(subjectAltName);
1020 else
1021 *trustErrorStatus |=
1022 CERT_TRUST_INVALID_EXTENSION | CERT_TRUST_INVALID_NAME_CONSTRAINTS;
1025 static BOOL rfc822_attr_matches_excluded_name(const CERT_RDN_ATTR *attr,
1026 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
1028 DWORD i;
1029 BOOL match = FALSE;
1031 for (i = 0; !match && i < nameConstraints->cExcludedSubtree; i++)
1033 const CERT_ALT_NAME_ENTRY *constraint =
1034 &nameConstraints->rgExcludedSubtree[i].Base;
1036 if (constraint->dwAltNameChoice == CERT_ALT_NAME_RFC822_NAME)
1037 match = rfc822_name_matches(constraint->u.pwszRfc822Name,
1038 (LPCWSTR)attr->Value.pbData, trustErrorStatus);
1040 return match;
1043 static BOOL rfc822_attr_matches_permitted_name(const CERT_RDN_ATTR *attr,
1044 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus,
1045 BOOL *present)
1047 DWORD i;
1048 BOOL match = FALSE;
1050 for (i = 0; !match && i < nameConstraints->cPermittedSubtree; i++)
1052 const CERT_ALT_NAME_ENTRY *constraint =
1053 &nameConstraints->rgPermittedSubtree[i].Base;
1055 if (constraint->dwAltNameChoice == CERT_ALT_NAME_RFC822_NAME)
1057 *present = TRUE;
1058 match = rfc822_name_matches(constraint->u.pwszRfc822Name,
1059 (LPCWSTR)attr->Value.pbData, trustErrorStatus);
1062 return match;
1065 static void compare_subject_with_email_constraints(
1066 const CERT_NAME_BLOB *subjectName,
1067 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
1069 CERT_NAME_INFO *name;
1070 DWORD size;
1072 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_UNICODE_NAME,
1073 subjectName->pbData, subjectName->cbData,
1074 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &name, &size))
1076 DWORD i, j;
1078 for (i = 0; i < name->cRDN; i++)
1079 for (j = 0; j < name->rgRDN[i].cRDNAttr; j++)
1080 if (!strcmp(name->rgRDN[i].rgRDNAttr[j].pszObjId,
1081 szOID_RSA_emailAddr))
1083 BOOL nameFormPresent;
1085 /* A name constraint only applies if the name form is
1086 * present. From RFC 5280, section 4.2.1.10:
1087 * "Restrictions apply only when the specified name form is
1088 * present. If no name of the type is in the certificate,
1089 * the certificate is acceptable."
1091 if (rfc822_attr_matches_excluded_name(
1092 &name->rgRDN[i].rgRDNAttr[j], nameConstraints,
1093 trustErrorStatus))
1095 TRACE_(chain)(
1096 "email address in subject name is excluded\n");
1097 *trustErrorStatus |=
1098 CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
1100 nameFormPresent = FALSE;
1101 if (!rfc822_attr_matches_permitted_name(
1102 &name->rgRDN[i].rgRDNAttr[j], nameConstraints,
1103 trustErrorStatus, &nameFormPresent) && nameFormPresent)
1105 TRACE_(chain)(
1106 "email address in subject name is not permitted\n");
1107 *trustErrorStatus |=
1108 CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
1111 LocalFree(name);
1113 else
1114 *trustErrorStatus |=
1115 CERT_TRUST_INVALID_EXTENSION | CERT_TRUST_INVALID_NAME_CONSTRAINTS;
1118 static BOOL CRYPT_IsEmptyName(const CERT_NAME_BLOB *name)
1120 BOOL empty;
1122 if (!name->cbData)
1123 empty = TRUE;
1124 else if (name->cbData == 2 && name->pbData[1] == 0)
1126 /* An empty sequence is also empty */
1127 empty = TRUE;
1129 else
1130 empty = FALSE;
1131 return empty;
1134 static void compare_subject_with_constraints(const CERT_NAME_BLOB *subjectName,
1135 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
1137 BOOL hasEmailConstraint = FALSE;
1138 DWORD i;
1140 /* In general, a subject distinguished name only matches a directory name
1141 * constraint. However, an exception exists for email addresses.
1142 * From RFC 5280, section 4.2.1.6:
1143 * "Legacy implementations exist where an electronic mail address is
1144 * embedded in the subject distinguished name as an emailAddress
1145 * attribute [RFC2985]."
1146 * If an email address constraint exists, check that constraint separately.
1148 for (i = 0; !hasEmailConstraint && i < nameConstraints->cExcludedSubtree;
1149 i++)
1150 if (nameConstraints->rgExcludedSubtree[i].Base.dwAltNameChoice ==
1151 CERT_ALT_NAME_RFC822_NAME)
1152 hasEmailConstraint = TRUE;
1153 for (i = 0; !hasEmailConstraint && i < nameConstraints->cPermittedSubtree;
1154 i++)
1155 if (nameConstraints->rgPermittedSubtree[i].Base.dwAltNameChoice ==
1156 CERT_ALT_NAME_RFC822_NAME)
1157 hasEmailConstraint = TRUE;
1158 if (hasEmailConstraint)
1159 compare_subject_with_email_constraints(subjectName, nameConstraints,
1160 trustErrorStatus);
1161 for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
1163 CERT_ALT_NAME_ENTRY *constraint =
1164 &nameConstraints->rgExcludedSubtree[i].Base;
1166 if (constraint->dwAltNameChoice == CERT_ALT_NAME_DIRECTORY_NAME &&
1167 directory_name_matches(&constraint->u.DirectoryName, subjectName))
1169 TRACE_(chain)("subject name is excluded\n");
1170 *trustErrorStatus |=
1171 CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
1174 /* RFC 5280, section 4.2.1.10:
1175 * "Restrictions apply only when the specified name form is present.
1176 * If no name of the type is in the certificate, the certificate is
1177 * acceptable."
1178 * An empty name can't have the name form present, so don't check it.
1180 if (nameConstraints->cPermittedSubtree && !CRYPT_IsEmptyName(subjectName))
1182 BOOL match = FALSE, hasDirectoryConstraint = FALSE;
1184 for (i = 0; !match && i < nameConstraints->cPermittedSubtree; i++)
1186 CERT_ALT_NAME_ENTRY *constraint =
1187 &nameConstraints->rgPermittedSubtree[i].Base;
1189 if (constraint->dwAltNameChoice == CERT_ALT_NAME_DIRECTORY_NAME)
1191 hasDirectoryConstraint = TRUE;
1192 match = directory_name_matches(&constraint->u.DirectoryName,
1193 subjectName);
1196 if (hasDirectoryConstraint && !match)
1198 TRACE_(chain)("subject name is not permitted\n");
1199 *trustErrorStatus |= CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
1204 static void CRYPT_CheckNameConstraints(
1205 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, const CERT_INFO *cert,
1206 DWORD *trustErrorStatus)
1208 CERT_EXTENSION *ext = get_subject_alt_name_ext(cert);
1210 if (ext)
1211 compare_alt_name_with_constraints(ext, nameConstraints,
1212 trustErrorStatus);
1213 /* Name constraints apply to the subject alternative name as well as the
1214 * subject name. From RFC 5280, section 4.2.1.10:
1215 * "Restrictions apply to the subject distinguished name and apply to
1216 * subject alternative names."
1218 compare_subject_with_constraints(&cert->Subject, nameConstraints,
1219 trustErrorStatus);
1222 /* Gets cert's name constraints, if any. Free with LocalFree. */
1223 static CERT_NAME_CONSTRAINTS_INFO *CRYPT_GetNameConstraints(CERT_INFO *cert)
1225 CERT_NAME_CONSTRAINTS_INFO *info = NULL;
1227 CERT_EXTENSION *ext;
1229 if ((ext = CertFindExtension(szOID_NAME_CONSTRAINTS, cert->cExtension,
1230 cert->rgExtension)))
1232 DWORD size;
1234 CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
1235 ext->Value.pbData, ext->Value.cbData,
1236 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &info,
1237 &size);
1239 return info;
1242 static BOOL CRYPT_IsValidNameConstraint(const CERT_NAME_CONSTRAINTS_INFO *info)
1244 DWORD i;
1245 BOOL ret = TRUE;
1247 /* Make sure at least one permitted or excluded subtree is present. From
1248 * RFC 5280, section 4.2.1.10:
1249 * "Conforming CAs MUST NOT issue certificates where name constraints is an
1250 * empty sequence. That is, either the permittedSubtrees field or the
1251 * excludedSubtrees MUST be present."
1253 if (!info->cPermittedSubtree && !info->cExcludedSubtree)
1255 WARN_(chain)("constraints contain no permitted nor excluded subtree\n");
1256 ret = FALSE;
1258 /* Check that none of the constraints specifies a minimum or a maximum.
1259 * See RFC 5280, section 4.2.1.10:
1260 * "Within this profile, the minimum and maximum fields are not used with
1261 * any name forms, thus, the minimum MUST be zero, and maximum MUST be
1262 * absent. However, if an application encounters a critical name
1263 * constraints extension that specifies other values for minimum or
1264 * maximum for a name form that appears in a subsequent certificate, the
1265 * application MUST either process these fields or reject the
1266 * certificate."
1267 * Since it gives no guidance as to how to process these fields, we
1268 * reject any name constraint that contains them.
1270 for (i = 0; ret && i < info->cPermittedSubtree; i++)
1271 if (info->rgPermittedSubtree[i].dwMinimum ||
1272 info->rgPermittedSubtree[i].fMaximum)
1274 TRACE_(chain)("found a minimum or maximum in permitted subtrees\n");
1275 ret = FALSE;
1277 for (i = 0; ret && i < info->cExcludedSubtree; i++)
1278 if (info->rgExcludedSubtree[i].dwMinimum ||
1279 info->rgExcludedSubtree[i].fMaximum)
1281 TRACE_(chain)("found a minimum or maximum in excluded subtrees\n");
1282 ret = FALSE;
1284 return ret;
1287 static void CRYPT_CheckChainNameConstraints(PCERT_SIMPLE_CHAIN chain)
1289 int i, j;
1291 /* Microsoft's implementation appears to violate RFC 3280: according to
1292 * MSDN, the various CERT_TRUST_*_NAME_CONSTRAINT errors are set if a CA's
1293 * name constraint is violated in the end cert. According to RFC 3280,
1294 * the constraints should be checked against every subsequent certificate
1295 * in the chain, not just the end cert.
1296 * Microsoft's implementation also sets the name constraint errors on the
1297 * certs whose constraints were violated, not on the certs that violated
1298 * them.
1299 * In order to be error-compatible with Microsoft's implementation, while
1300 * still adhering to RFC 3280, I use a O(n ^ 2) algorithm to check name
1301 * constraints.
1303 for (i = chain->cElement - 1; i > 0; i--)
1305 CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
1307 if ((nameConstraints = CRYPT_GetNameConstraints(
1308 chain->rgpElement[i]->pCertContext->pCertInfo)))
1310 if (!CRYPT_IsValidNameConstraint(nameConstraints))
1311 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1312 CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
1313 else
1315 for (j = i - 1; j >= 0; j--)
1317 DWORD errorStatus = 0;
1319 /* According to RFC 3280, self-signed certs don't have name
1320 * constraints checked unless they're the end cert.
1322 if (j == 0 || !CRYPT_IsCertificateSelfSigned(
1323 chain->rgpElement[j]->pCertContext))
1325 CRYPT_CheckNameConstraints(nameConstraints,
1326 chain->rgpElement[j]->pCertContext->pCertInfo,
1327 &errorStatus);
1328 if (errorStatus)
1330 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1331 errorStatus;
1332 CRYPT_CombineTrustStatus(&chain->TrustStatus,
1333 &chain->rgpElement[i]->TrustStatus);
1335 else
1336 chain->rgpElement[i]->TrustStatus.dwInfoStatus |=
1337 CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS;
1341 LocalFree(nameConstraints);
1346 /* Gets cert's policies info, if any. Free with LocalFree. */
1347 static CERT_POLICIES_INFO *CRYPT_GetPolicies(PCCERT_CONTEXT cert)
1349 PCERT_EXTENSION ext;
1350 CERT_POLICIES_INFO *policies = NULL;
1352 ext = CertFindExtension(szOID_KEY_USAGE, cert->pCertInfo->cExtension,
1353 cert->pCertInfo->rgExtension);
1354 if (ext)
1356 DWORD size;
1358 CryptDecodeObjectEx(X509_ASN_ENCODING, X509_CERT_POLICIES,
1359 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1360 &policies, &size);
1362 return policies;
1365 static void CRYPT_CheckPolicies(const CERT_POLICIES_INFO *policies, CERT_INFO *cert,
1366 DWORD *errorStatus)
1368 DWORD i;
1370 for (i = 0; i < policies->cPolicyInfo; i++)
1372 /* For now, the only accepted policy identifier is the anyPolicy
1373 * identifier.
1374 * FIXME: the policy identifiers should be compared against the
1375 * cert's certificate policies extension, subject to the policy
1376 * mappings extension, and the policy constraints extension.
1377 * See RFC 5280, sections 4.2.1.4, 4.2.1.5, and 4.2.1.11.
1379 if (strcmp(policies->rgPolicyInfo[i].pszPolicyIdentifier,
1380 szOID_ANY_CERT_POLICY))
1382 FIXME("unsupported policy %s\n",
1383 policies->rgPolicyInfo[i].pszPolicyIdentifier);
1384 *errorStatus |= CERT_TRUST_INVALID_POLICY_CONSTRAINTS;
1389 static void CRYPT_CheckChainPolicies(PCERT_SIMPLE_CHAIN chain)
1391 int i, j;
1393 for (i = chain->cElement - 1; i > 0; i--)
1395 CERT_POLICIES_INFO *policies;
1397 if ((policies = CRYPT_GetPolicies(chain->rgpElement[i]->pCertContext)))
1399 for (j = i - 1; j >= 0; j--)
1401 DWORD errorStatus = 0;
1403 CRYPT_CheckPolicies(policies,
1404 chain->rgpElement[j]->pCertContext->pCertInfo, &errorStatus);
1405 if (errorStatus)
1407 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1408 errorStatus;
1409 CRYPT_CombineTrustStatus(&chain->TrustStatus,
1410 &chain->rgpElement[i]->TrustStatus);
1413 LocalFree(policies);
1418 static LPWSTR name_value_to_str(const CERT_NAME_BLOB *name)
1420 DWORD len = cert_name_to_str_with_indent(X509_ASN_ENCODING, 0, name,
1421 CERT_SIMPLE_NAME_STR, NULL, 0);
1422 LPWSTR str = NULL;
1424 if (len)
1426 str = CryptMemAlloc(len * sizeof(WCHAR));
1427 if (str)
1428 cert_name_to_str_with_indent(X509_ASN_ENCODING, 0, name,
1429 CERT_SIMPLE_NAME_STR, str, len);
1431 return str;
1434 static void dump_alt_name_entry(const CERT_ALT_NAME_ENTRY *entry)
1436 LPWSTR str;
1438 switch (entry->dwAltNameChoice)
1440 case CERT_ALT_NAME_OTHER_NAME:
1441 TRACE_(chain)("CERT_ALT_NAME_OTHER_NAME, oid = %s\n",
1442 debugstr_a(entry->u.pOtherName->pszObjId));
1443 break;
1444 case CERT_ALT_NAME_RFC822_NAME:
1445 TRACE_(chain)("CERT_ALT_NAME_RFC822_NAME: %s\n",
1446 debugstr_w(entry->u.pwszRfc822Name));
1447 break;
1448 case CERT_ALT_NAME_DNS_NAME:
1449 TRACE_(chain)("CERT_ALT_NAME_DNS_NAME: %s\n",
1450 debugstr_w(entry->u.pwszDNSName));
1451 break;
1452 case CERT_ALT_NAME_DIRECTORY_NAME:
1453 str = name_value_to_str(&entry->u.DirectoryName);
1454 TRACE_(chain)("CERT_ALT_NAME_DIRECTORY_NAME: %s\n", debugstr_w(str));
1455 CryptMemFree(str);
1456 break;
1457 case CERT_ALT_NAME_URL:
1458 TRACE_(chain)("CERT_ALT_NAME_URL: %s\n", debugstr_w(entry->u.pwszURL));
1459 break;
1460 case CERT_ALT_NAME_IP_ADDRESS:
1461 TRACE_(chain)("CERT_ALT_NAME_IP_ADDRESS: %d bytes\n",
1462 entry->u.IPAddress.cbData);
1463 break;
1464 case CERT_ALT_NAME_REGISTERED_ID:
1465 TRACE_(chain)("CERT_ALT_NAME_REGISTERED_ID: %s\n",
1466 debugstr_a(entry->u.pszRegisteredID));
1467 break;
1468 default:
1469 TRACE_(chain)("dwAltNameChoice = %d\n", entry->dwAltNameChoice);
1473 static void dump_alt_name(LPCSTR type, const CERT_EXTENSION *ext)
1475 CERT_ALT_NAME_INFO *name;
1476 DWORD size;
1478 TRACE_(chain)("%s:\n", type);
1479 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
1480 ext->Value.pbData, ext->Value.cbData,
1481 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &name, &size))
1483 DWORD i;
1485 TRACE_(chain)("%d alt name entries:\n", name->cAltEntry);
1486 for (i = 0; i < name->cAltEntry; i++)
1487 dump_alt_name_entry(&name->rgAltEntry[i]);
1488 LocalFree(name);
1492 static void dump_basic_constraints(const CERT_EXTENSION *ext)
1494 CERT_BASIC_CONSTRAINTS_INFO *info;
1495 DWORD size = 0;
1497 if (CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
1498 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
1499 NULL, &info, &size))
1501 TRACE_(chain)("SubjectType: %02x\n", info->SubjectType.pbData[0]);
1502 TRACE_(chain)("%s path length constraint\n",
1503 info->fPathLenConstraint ? "has" : "doesn't have");
1504 TRACE_(chain)("path length=%d\n", info->dwPathLenConstraint);
1505 LocalFree(info);
1509 static void dump_basic_constraints2(const CERT_EXTENSION *ext)
1511 CERT_BASIC_CONSTRAINTS2_INFO constraints;
1512 DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
1514 if (CryptDecodeObjectEx(X509_ASN_ENCODING,
1515 szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
1516 0, NULL, &constraints, &size))
1518 TRACE_(chain)("basic constraints:\n");
1519 TRACE_(chain)("can%s be a CA\n", constraints.fCA ? "" : "not");
1520 TRACE_(chain)("%s path length constraint\n",
1521 constraints.fPathLenConstraint ? "has" : "doesn't have");
1522 TRACE_(chain)("path length=%d\n", constraints.dwPathLenConstraint);
1526 static void dump_key_usage(const CERT_EXTENSION *ext)
1528 CRYPT_BIT_BLOB usage;
1529 DWORD size = sizeof(usage);
1531 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
1532 ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
1534 #define trace_usage_bit(bits, bit) \
1535 if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
1536 if (usage.cbData)
1538 trace_usage_bit(usage.pbData[0], CERT_DIGITAL_SIGNATURE_KEY_USAGE);
1539 trace_usage_bit(usage.pbData[0], CERT_NON_REPUDIATION_KEY_USAGE);
1540 trace_usage_bit(usage.pbData[0], CERT_KEY_ENCIPHERMENT_KEY_USAGE);
1541 trace_usage_bit(usage.pbData[0], CERT_DATA_ENCIPHERMENT_KEY_USAGE);
1542 trace_usage_bit(usage.pbData[0], CERT_KEY_AGREEMENT_KEY_USAGE);
1543 trace_usage_bit(usage.pbData[0], CERT_KEY_CERT_SIGN_KEY_USAGE);
1544 trace_usage_bit(usage.pbData[0], CERT_CRL_SIGN_KEY_USAGE);
1545 trace_usage_bit(usage.pbData[0], CERT_ENCIPHER_ONLY_KEY_USAGE);
1547 #undef trace_usage_bit
1548 if (usage.cbData > 1 && usage.pbData[1] & CERT_DECIPHER_ONLY_KEY_USAGE)
1549 TRACE_(chain)("CERT_DECIPHER_ONLY_KEY_USAGE\n");
1553 static void dump_general_subtree(const CERT_GENERAL_SUBTREE *subtree)
1555 dump_alt_name_entry(&subtree->Base);
1556 TRACE_(chain)("dwMinimum = %d, fMaximum = %d, dwMaximum = %d\n",
1557 subtree->dwMinimum, subtree->fMaximum, subtree->dwMaximum);
1560 static void dump_name_constraints(const CERT_EXTENSION *ext)
1562 CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
1563 DWORD size;
1565 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
1566 ext->Value.pbData, ext->Value.cbData,
1567 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &nameConstraints,
1568 &size))
1570 DWORD i;
1572 TRACE_(chain)("%d permitted subtrees:\n",
1573 nameConstraints->cPermittedSubtree);
1574 for (i = 0; i < nameConstraints->cPermittedSubtree; i++)
1575 dump_general_subtree(&nameConstraints->rgPermittedSubtree[i]);
1576 TRACE_(chain)("%d excluded subtrees:\n",
1577 nameConstraints->cExcludedSubtree);
1578 for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
1579 dump_general_subtree(&nameConstraints->rgExcludedSubtree[i]);
1580 LocalFree(nameConstraints);
1584 static void dump_cert_policies(const CERT_EXTENSION *ext)
1586 CERT_POLICIES_INFO *policies;
1587 DWORD size;
1589 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_CERT_POLICIES,
1590 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1591 &policies, &size))
1593 DWORD i, j;
1595 TRACE_(chain)("%d policies:\n", policies->cPolicyInfo);
1596 for (i = 0; i < policies->cPolicyInfo; i++)
1598 TRACE_(chain)("policy identifier: %s\n",
1599 debugstr_a(policies->rgPolicyInfo[i].pszPolicyIdentifier));
1600 TRACE_(chain)("%d policy qualifiers:\n",
1601 policies->rgPolicyInfo[i].cPolicyQualifier);
1602 for (j = 0; j < policies->rgPolicyInfo[i].cPolicyQualifier; j++)
1603 TRACE_(chain)("%s\n", debugstr_a(
1604 policies->rgPolicyInfo[i].rgPolicyQualifier[j].
1605 pszPolicyQualifierId));
1607 LocalFree(policies);
1611 static void dump_enhanced_key_usage(const CERT_EXTENSION *ext)
1613 CERT_ENHKEY_USAGE *usage;
1614 DWORD size;
1616 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ENHANCED_KEY_USAGE,
1617 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1618 &usage, &size))
1620 DWORD i;
1622 TRACE_(chain)("%d usages:\n", usage->cUsageIdentifier);
1623 for (i = 0; i < usage->cUsageIdentifier; i++)
1624 TRACE_(chain)("%s\n", usage->rgpszUsageIdentifier[i]);
1625 LocalFree(usage);
1629 static void dump_netscape_cert_type(const CERT_EXTENSION *ext)
1631 CRYPT_BIT_BLOB usage;
1632 DWORD size = sizeof(usage);
1634 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
1635 ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
1637 #define trace_cert_type_bit(bits, bit) \
1638 if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
1639 if (usage.cbData)
1641 trace_cert_type_bit(usage.pbData[0],
1642 NETSCAPE_SSL_CLIENT_AUTH_CERT_TYPE);
1643 trace_cert_type_bit(usage.pbData[0],
1644 NETSCAPE_SSL_SERVER_AUTH_CERT_TYPE);
1645 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SMIME_CERT_TYPE);
1646 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SIGN_CERT_TYPE);
1647 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SSL_CA_CERT_TYPE);
1648 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SMIME_CA_CERT_TYPE);
1649 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SIGN_CA_CERT_TYPE);
1651 #undef trace_cert_type_bit
1655 static void dump_extension(const CERT_EXTENSION *ext)
1657 TRACE_(chain)("%s (%scritical)\n", debugstr_a(ext->pszObjId),
1658 ext->fCritical ? "" : "not ");
1659 if (!strcmp(ext->pszObjId, szOID_SUBJECT_ALT_NAME))
1660 dump_alt_name("subject alt name", ext);
1661 else if (!strcmp(ext->pszObjId, szOID_ISSUER_ALT_NAME))
1662 dump_alt_name("issuer alt name", ext);
1663 else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS))
1664 dump_basic_constraints(ext);
1665 else if (!strcmp(ext->pszObjId, szOID_KEY_USAGE))
1666 dump_key_usage(ext);
1667 else if (!strcmp(ext->pszObjId, szOID_SUBJECT_ALT_NAME2))
1668 dump_alt_name("subject alt name 2", ext);
1669 else if (!strcmp(ext->pszObjId, szOID_ISSUER_ALT_NAME2))
1670 dump_alt_name("issuer alt name 2", ext);
1671 else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS2))
1672 dump_basic_constraints2(ext);
1673 else if (!strcmp(ext->pszObjId, szOID_NAME_CONSTRAINTS))
1674 dump_name_constraints(ext);
1675 else if (!strcmp(ext->pszObjId, szOID_CERT_POLICIES))
1676 dump_cert_policies(ext);
1677 else if (!strcmp(ext->pszObjId, szOID_ENHANCED_KEY_USAGE))
1678 dump_enhanced_key_usage(ext);
1679 else if (!strcmp(ext->pszObjId, szOID_NETSCAPE_CERT_TYPE))
1680 dump_netscape_cert_type(ext);
1683 static LPCSTR filetime_to_str(const FILETIME *time)
1685 char date[80];
1686 char dateFmt[80]; /* sufficient for all versions of LOCALE_SSHORTDATE */
1687 SYSTEMTIME sysTime;
1689 if (!time) return "(null)";
1691 GetLocaleInfoA(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, dateFmt,
1692 sizeof(dateFmt) / sizeof(dateFmt[0]));
1693 FileTimeToSystemTime(time, &sysTime);
1694 GetDateFormatA(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, date,
1695 sizeof(date) / sizeof(date[0]));
1696 return wine_dbg_sprintf("%s", date);
1699 static void dump_element(PCCERT_CONTEXT cert)
1701 LPWSTR name = NULL;
1702 DWORD len, i;
1704 TRACE_(chain)("%p: version %d\n", cert, cert->pCertInfo->dwVersion);
1705 len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
1706 CERT_NAME_ISSUER_FLAG, NULL, NULL, 0);
1707 name = CryptMemAlloc(len * sizeof(WCHAR));
1708 if (name)
1710 CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
1711 CERT_NAME_ISSUER_FLAG, NULL, name, len);
1712 TRACE_(chain)("issued by %s\n", debugstr_w(name));
1713 CryptMemFree(name);
1715 len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
1716 NULL, 0);
1717 name = CryptMemAlloc(len * sizeof(WCHAR));
1718 if (name)
1720 CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
1721 name, len);
1722 TRACE_(chain)("issued to %s\n", debugstr_w(name));
1723 CryptMemFree(name);
1725 TRACE_(chain)("valid from %s to %s\n",
1726 filetime_to_str(&cert->pCertInfo->NotBefore),
1727 filetime_to_str(&cert->pCertInfo->NotAfter));
1728 TRACE_(chain)("%d extensions\n", cert->pCertInfo->cExtension);
1729 for (i = 0; i < cert->pCertInfo->cExtension; i++)
1730 dump_extension(&cert->pCertInfo->rgExtension[i]);
1733 static BOOL CRYPT_KeyUsageValid(CertificateChainEngine *engine,
1734 PCCERT_CONTEXT cert, BOOL isRoot, BOOL isCA, DWORD index)
1736 PCERT_EXTENSION ext;
1737 BOOL ret;
1738 BYTE usageBits = 0;
1740 ext = CertFindExtension(szOID_KEY_USAGE, cert->pCertInfo->cExtension,
1741 cert->pCertInfo->rgExtension);
1742 if (ext)
1744 CRYPT_BIT_BLOB usage;
1745 DWORD size = sizeof(usage);
1747 ret = CryptDecodeObjectEx(cert->dwCertEncodingType, X509_BITS,
1748 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL,
1749 &usage, &size);
1750 if (!ret)
1751 return FALSE;
1752 else if (usage.cbData > 2)
1754 /* The key usage extension only defines 9 bits => no more than 2
1755 * bytes are needed to encode all known usages.
1757 return FALSE;
1759 else
1761 /* The only bit relevant to chain validation is the keyCertSign
1762 * bit, which is always in the least significant byte of the
1763 * key usage bits.
1765 usageBits = usage.pbData[usage.cbData - 1];
1768 if (isCA)
1770 if (!ext)
1772 /* MS appears to violate RFC 5280, section 4.2.1.3 (Key Usage)
1773 * here. Quoting the RFC:
1774 * "This [key usage] extension MUST appear in certificates that
1775 * contain public keys that are used to validate digital signatures
1776 * on other public key certificates or CRLs."
1777 * MS appears to accept certs that do not contain key usage
1778 * extensions as CA certs. V1 and V2 certificates did not have
1779 * extensions, and many root certificates are V1 certificates, so
1780 * perhaps this is prudent. On the other hand, MS also accepts V3
1781 * certs without key usage extensions. Because some CAs, e.g.
1782 * Certum, also do not include key usage extensions in their
1783 * intermediate certificates, we are forced to accept V3
1784 * certificates without key usage extensions as well.
1786 ret = TRUE;
1788 else
1790 if (!(usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
1792 WARN_(chain)("keyCertSign not asserted on a CA cert\n");
1793 ret = FALSE;
1795 else
1796 ret = TRUE;
1799 else
1801 if (ext && (usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
1803 WARN_(chain)("keyCertSign asserted on a non-CA cert\n");
1804 ret = FALSE;
1806 else
1807 ret = TRUE;
1809 return ret;
1812 static BOOL CRYPT_CriticalExtensionsSupported(PCCERT_CONTEXT cert)
1814 BOOL ret = TRUE;
1815 DWORD i;
1817 for (i = 0; ret && i < cert->pCertInfo->cExtension; i++)
1819 if (cert->pCertInfo->rgExtension[i].fCritical)
1821 LPCSTR oid = cert->pCertInfo->rgExtension[i].pszObjId;
1823 if (!strcmp(oid, szOID_BASIC_CONSTRAINTS))
1824 ret = TRUE;
1825 else if (!strcmp(oid, szOID_BASIC_CONSTRAINTS2))
1826 ret = TRUE;
1827 else if (!strcmp(oid, szOID_NAME_CONSTRAINTS))
1828 ret = TRUE;
1829 else if (!strcmp(oid, szOID_KEY_USAGE))
1830 ret = TRUE;
1831 else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME))
1832 ret = TRUE;
1833 else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME2))
1834 ret = TRUE;
1835 else if (!strcmp(oid, szOID_CERT_POLICIES))
1836 ret = TRUE;
1837 else if (!strcmp(oid, szOID_ENHANCED_KEY_USAGE))
1838 ret = TRUE;
1839 else
1841 FIXME("unsupported critical extension %s\n",
1842 debugstr_a(oid));
1843 ret = FALSE;
1847 return ret;
1850 static BOOL CRYPT_IsCertVersionValid(PCCERT_CONTEXT cert)
1852 BOOL ret = TRUE;
1854 /* Checks whether the contents of the cert match the cert's version. */
1855 switch (cert->pCertInfo->dwVersion)
1857 case CERT_V1:
1858 /* A V1 cert may not contain unique identifiers. See RFC 5280,
1859 * section 4.1.2.8:
1860 * "These fields MUST only appear if the version is 2 or 3 (Section
1861 * 4.1.2.1). These fields MUST NOT appear if the version is 1."
1863 if (cert->pCertInfo->IssuerUniqueId.cbData ||
1864 cert->pCertInfo->SubjectUniqueId.cbData)
1865 ret = FALSE;
1866 /* A V1 cert may not contain extensions. See RFC 5280, section 4.1.2.9:
1867 * "This field MUST only appear if the version is 3 (Section 4.1.2.1)."
1869 if (cert->pCertInfo->cExtension)
1870 ret = FALSE;
1871 break;
1872 case CERT_V2:
1873 /* A V2 cert may not contain extensions. See RFC 5280, section 4.1.2.9:
1874 * "This field MUST only appear if the version is 3 (Section 4.1.2.1)."
1876 if (cert->pCertInfo->cExtension)
1877 ret = FALSE;
1878 break;
1879 case CERT_V3:
1880 /* Do nothing, all fields are allowed for V3 certs */
1881 break;
1882 default:
1883 WARN_(chain)("invalid cert version %d\n", cert->pCertInfo->dwVersion);
1884 ret = FALSE;
1886 return ret;
1889 static void CRYPT_CheckSimpleChain(CertificateChainEngine *engine,
1890 PCERT_SIMPLE_CHAIN chain, LPFILETIME time)
1892 PCERT_CHAIN_ELEMENT rootElement = chain->rgpElement[chain->cElement - 1];
1893 int i;
1894 BOOL pathLengthConstraintViolated = FALSE;
1895 CERT_BASIC_CONSTRAINTS2_INFO constraints = { FALSE, FALSE, 0 };
1897 TRACE_(chain)("checking chain with %d elements for time %s\n",
1898 chain->cElement, filetime_to_str(time));
1899 for (i = chain->cElement - 1; i >= 0; i--)
1901 BOOL isRoot;
1903 if (TRACE_ON(chain))
1904 dump_element(chain->rgpElement[i]->pCertContext);
1905 if (i == chain->cElement - 1)
1906 isRoot = CRYPT_IsCertificateSelfSigned(
1907 chain->rgpElement[i]->pCertContext);
1908 else
1909 isRoot = FALSE;
1910 if (!CRYPT_IsCertVersionValid(chain->rgpElement[i]->pCertContext))
1912 /* MS appears to accept certs whose versions don't match their
1913 * contents, so there isn't an appropriate error code.
1915 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1916 CERT_TRUST_INVALID_EXTENSION;
1918 if (CertVerifyTimeValidity(time,
1919 chain->rgpElement[i]->pCertContext->pCertInfo) != 0)
1920 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1921 CERT_TRUST_IS_NOT_TIME_VALID;
1922 if (i != 0)
1924 /* Check the signature of the cert this issued */
1925 if (!CryptVerifyCertificateSignatureEx(0, X509_ASN_ENCODING,
1926 CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT,
1927 (void *)chain->rgpElement[i - 1]->pCertContext,
1928 CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT,
1929 (void *)chain->rgpElement[i]->pCertContext, 0, NULL))
1930 chain->rgpElement[i - 1]->TrustStatus.dwErrorStatus |=
1931 CERT_TRUST_IS_NOT_SIGNATURE_VALID;
1932 /* Once a path length constraint has been violated, every remaining
1933 * CA cert's basic constraints is considered invalid.
1935 if (pathLengthConstraintViolated)
1936 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1937 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1938 else if (!CRYPT_CheckBasicConstraintsForCA(engine,
1939 chain->rgpElement[i]->pCertContext, &constraints, i - 1, isRoot,
1940 &pathLengthConstraintViolated))
1941 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1942 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1943 else if (constraints.fPathLenConstraint &&
1944 constraints.dwPathLenConstraint)
1946 /* This one's valid - decrement max length */
1947 constraints.dwPathLenConstraint--;
1950 else
1952 /* Check whether end cert has a basic constraints extension */
1953 if (!CRYPT_DecodeBasicConstraints(
1954 chain->rgpElement[i]->pCertContext, &constraints, FALSE))
1955 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1956 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1958 if (!CRYPT_KeyUsageValid(engine, chain->rgpElement[i]->pCertContext,
1959 isRoot, constraints.fCA, i))
1960 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1961 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
1962 if (CRYPT_IsSimpleChainCyclic(chain))
1964 /* If the chain is cyclic, then the path length constraints
1965 * are violated, because the chain is infinitely long.
1967 pathLengthConstraintViolated = TRUE;
1968 chain->TrustStatus.dwErrorStatus |=
1969 CERT_TRUST_IS_PARTIAL_CHAIN |
1970 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1972 /* Check whether every critical extension is supported */
1973 if (!CRYPT_CriticalExtensionsSupported(
1974 chain->rgpElement[i]->pCertContext))
1975 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1976 CERT_TRUST_INVALID_EXTENSION |
1977 CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT;
1978 CRYPT_CombineTrustStatus(&chain->TrustStatus,
1979 &chain->rgpElement[i]->TrustStatus);
1981 CRYPT_CheckChainNameConstraints(chain);
1982 CRYPT_CheckChainPolicies(chain);
1983 if (CRYPT_IsCertificateSelfSigned(rootElement->pCertContext))
1985 rootElement->TrustStatus.dwInfoStatus |=
1986 CERT_TRUST_IS_SELF_SIGNED | CERT_TRUST_HAS_NAME_MATCH_ISSUER;
1987 CRYPT_CheckRootCert(engine->hRoot, rootElement);
1989 CRYPT_CombineTrustStatus(&chain->TrustStatus, &rootElement->TrustStatus);
1992 static PCCERT_CONTEXT CRYPT_FindIssuer(const CertificateChainEngine *engine, const CERT_CONTEXT *cert,
1993 HCERTSTORE store, DWORD type, void *para, DWORD flags, PCCERT_CONTEXT prev_issuer)
1995 CRYPT_URL_ARRAY *urls;
1996 PCCERT_CONTEXT issuer;
1997 DWORD size;
1998 BOOL res;
2000 issuer = CertFindCertificateInStore(store, cert->dwCertEncodingType, 0, type, para, prev_issuer);
2001 if(issuer) {
2002 TRACE("Found in store %p\n", issuer);
2003 return issuer;
2006 /* FIXME: For alternate issuers, we don't search world store nor try to retrieve issuer from URL.
2007 * This needs more tests.
2009 if(prev_issuer)
2010 return NULL;
2012 if(engine->hWorld) {
2013 issuer = CertFindCertificateInStore(engine->hWorld, cert->dwCertEncodingType, 0, type, para, NULL);
2014 if(issuer) {
2015 TRACE("Found in world %p\n", issuer);
2016 return issuer;
2020 res = CryptGetObjectUrl(URL_OID_CERTIFICATE_ISSUER, (void*)cert, 0, NULL, &size, NULL, NULL, NULL);
2021 if(!res)
2022 return NULL;
2024 urls = HeapAlloc(GetProcessHeap(), 0, size);
2025 if(!urls)
2026 return NULL;
2028 res = CryptGetObjectUrl(URL_OID_CERTIFICATE_ISSUER, (void*)cert, 0, urls, &size, NULL, NULL, NULL);
2029 if(res)
2031 CERT_CONTEXT *new_cert;
2032 HCERTSTORE new_store;
2033 unsigned i;
2035 for(i=0; i < urls->cUrl; i++)
2037 TRACE("Trying URL %s\n", debugstr_w(urls->rgwszUrl[i]));
2039 res = CryptRetrieveObjectByUrlW(urls->rgwszUrl[i], CONTEXT_OID_CERTIFICATE,
2040 (flags & CERT_CHAIN_CACHE_ONLY_URL_RETRIEVAL) ? CRYPT_CACHE_ONLY_RETRIEVAL : CRYPT_AIA_RETRIEVAL,
2041 0, (void**)&new_cert, NULL, NULL, NULL, NULL);
2042 if(!res)
2044 TRACE("CryptRetrieveObjectByUrlW failed: %u\n", GetLastError());
2045 continue;
2048 /* FIXME: Use new_cert->hCertStore once cert ref count bug is fixed. */
2049 new_store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL);
2050 CertAddCertificateContextToStore(new_store, new_cert, CERT_STORE_ADD_NEW, NULL);
2051 issuer = CertFindCertificateInStore(new_store, cert->dwCertEncodingType, 0, type, para, NULL);
2052 CertFreeCertificateContext(new_cert);
2053 CertCloseStore(new_store, 0);
2054 if(issuer)
2056 TRACE("Found downloaded issuer %p\n", issuer);
2057 break;
2062 HeapFree(GetProcessHeap(), 0, urls);
2063 return issuer;
2066 static PCCERT_CONTEXT CRYPT_GetIssuer(const CertificateChainEngine *engine,
2067 HCERTSTORE store, PCCERT_CONTEXT subject, PCCERT_CONTEXT prevIssuer,
2068 DWORD flags, DWORD *infoStatus)
2070 PCCERT_CONTEXT issuer = NULL;
2071 PCERT_EXTENSION ext;
2072 DWORD size;
2074 *infoStatus = 0;
2075 if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
2076 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
2078 CERT_AUTHORITY_KEY_ID_INFO *info;
2079 BOOL ret;
2081 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
2082 X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
2083 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2084 &info, &size);
2085 if (ret)
2087 CERT_ID id;
2089 if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
2091 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
2092 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
2093 sizeof(CERT_NAME_BLOB));
2094 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
2095 &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
2097 issuer = CRYPT_FindIssuer(engine, subject, store, CERT_FIND_CERT_ID, &id, flags, prevIssuer);
2098 if (issuer)
2100 TRACE_(chain)("issuer found by issuer/serial number\n");
2101 *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
2104 else if (info->KeyId.cbData)
2106 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
2108 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
2109 issuer = CRYPT_FindIssuer(engine, subject, store, CERT_FIND_CERT_ID, &id, flags, prevIssuer);
2110 if (issuer)
2112 TRACE_(chain)("issuer found by key id\n");
2113 *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
2116 LocalFree(info);
2119 else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
2120 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
2122 CERT_AUTHORITY_KEY_ID2_INFO *info;
2123 BOOL ret;
2125 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
2126 X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
2127 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2128 &info, &size);
2129 if (ret)
2131 CERT_ID id;
2133 if (info->AuthorityCertIssuer.cAltEntry &&
2134 info->AuthorityCertSerialNumber.cbData)
2136 PCERT_ALT_NAME_ENTRY directoryName = NULL;
2137 DWORD i;
2139 for (i = 0; !directoryName &&
2140 i < info->AuthorityCertIssuer.cAltEntry; i++)
2141 if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
2142 == CERT_ALT_NAME_DIRECTORY_NAME)
2143 directoryName =
2144 &info->AuthorityCertIssuer.rgAltEntry[i];
2145 if (directoryName)
2147 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
2148 memcpy(&id.u.IssuerSerialNumber.Issuer,
2149 &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
2150 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
2151 &info->AuthorityCertSerialNumber,
2152 sizeof(CRYPT_INTEGER_BLOB));
2154 issuer = CRYPT_FindIssuer(engine, subject, store, CERT_FIND_CERT_ID, &id, flags, prevIssuer);
2155 if (issuer)
2157 TRACE_(chain)("issuer found by directory name\n");
2158 *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
2161 else
2162 FIXME("no supported name type in authority key id2\n");
2164 else if (info->KeyId.cbData)
2166 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
2167 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
2168 issuer = CRYPT_FindIssuer(engine, subject, store, CERT_FIND_CERT_ID, &id, flags, prevIssuer);
2169 if (issuer)
2171 TRACE_(chain)("issuer found by key id\n");
2172 *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
2175 LocalFree(info);
2178 else
2180 issuer = CRYPT_FindIssuer(engine, subject, store, CERT_FIND_SUBJECT_NAME,
2181 &subject->pCertInfo->Issuer, flags, prevIssuer);
2182 TRACE_(chain)("issuer found by name\n");
2183 *infoStatus = CERT_TRUST_HAS_NAME_MATCH_ISSUER;
2185 return issuer;
2188 /* Builds a simple chain by finding an issuer for the last cert in the chain,
2189 * until reaching a self-signed cert, or until no issuer can be found.
2191 static BOOL CRYPT_BuildSimpleChain(const CertificateChainEngine *engine,
2192 HCERTSTORE world, DWORD flags, PCERT_SIMPLE_CHAIN chain)
2194 BOOL ret = TRUE;
2195 PCCERT_CONTEXT cert = chain->rgpElement[chain->cElement - 1]->pCertContext;
2197 while (ret && !CRYPT_IsSimpleChainCyclic(chain) &&
2198 !CRYPT_IsCertificateSelfSigned(cert))
2200 PCCERT_CONTEXT issuer = CRYPT_GetIssuer(engine, world, cert, NULL, flags,
2201 &chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
2203 if (issuer)
2205 ret = CRYPT_AddCertToSimpleChain(engine, chain, issuer,
2206 chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
2207 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it to
2208 * close the enumeration that found it
2210 CertFreeCertificateContext(issuer);
2211 cert = issuer;
2213 else
2215 TRACE_(chain)("Couldn't find issuer, halting chain creation\n");
2216 chain->TrustStatus.dwErrorStatus |= CERT_TRUST_IS_PARTIAL_CHAIN;
2217 break;
2220 return ret;
2223 static LPCSTR debugstr_filetime(LPFILETIME pTime)
2225 if (!pTime)
2226 return "(nil)";
2227 return wine_dbg_sprintf("%p (%s)", pTime, filetime_to_str(pTime));
2230 static BOOL CRYPT_GetSimpleChainForCert(CertificateChainEngine *engine,
2231 HCERTSTORE world, PCCERT_CONTEXT cert, LPFILETIME pTime, DWORD flags,
2232 PCERT_SIMPLE_CHAIN *ppChain)
2234 BOOL ret = FALSE;
2235 PCERT_SIMPLE_CHAIN chain;
2237 TRACE("(%p, %p, %p, %s)\n", engine, world, cert, debugstr_filetime(pTime));
2239 chain = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
2240 if (chain)
2242 memset(chain, 0, sizeof(CERT_SIMPLE_CHAIN));
2243 chain->cbSize = sizeof(CERT_SIMPLE_CHAIN);
2244 ret = CRYPT_AddCertToSimpleChain(engine, chain, cert, 0);
2245 if (ret)
2247 ret = CRYPT_BuildSimpleChain(engine, world, flags, chain);
2248 if (ret)
2249 CRYPT_CheckSimpleChain(engine, chain, pTime);
2251 if (!ret)
2253 CRYPT_FreeSimpleChain(chain);
2254 chain = NULL;
2256 *ppChain = chain;
2258 return ret;
2261 static BOOL CRYPT_BuildCandidateChainFromCert(CertificateChainEngine *engine,
2262 PCCERT_CONTEXT cert, LPFILETIME pTime, HCERTSTORE hAdditionalStore, DWORD flags,
2263 CertificateChain **ppChain)
2265 PCERT_SIMPLE_CHAIN simpleChain = NULL;
2266 HCERTSTORE world;
2267 BOOL ret;
2269 world = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
2270 CERT_STORE_CREATE_NEW_FLAG, NULL);
2271 CertAddStoreToCollection(world, engine->hWorld, 0, 0);
2272 if (hAdditionalStore)
2273 CertAddStoreToCollection(world, hAdditionalStore, 0, 0);
2274 /* FIXME: only simple chains are supported for now, as CTLs aren't
2275 * supported yet.
2277 if ((ret = CRYPT_GetSimpleChainForCert(engine, world, cert, pTime, flags, &simpleChain)))
2279 CertificateChain *chain = CryptMemAlloc(sizeof(CertificateChain));
2281 if (chain)
2283 chain->ref = 1;
2284 chain->world = world;
2285 chain->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
2286 chain->context.TrustStatus = simpleChain->TrustStatus;
2287 chain->context.cChain = 1;
2288 chain->context.rgpChain = CryptMemAlloc(sizeof(PCERT_SIMPLE_CHAIN));
2289 chain->context.rgpChain[0] = simpleChain;
2290 chain->context.cLowerQualityChainContext = 0;
2291 chain->context.rgpLowerQualityChainContext = NULL;
2292 chain->context.fHasRevocationFreshnessTime = FALSE;
2293 chain->context.dwRevocationFreshnessTime = 0;
2295 else
2297 CRYPT_FreeSimpleChain(simpleChain);
2298 ret = FALSE;
2300 *ppChain = chain;
2302 return ret;
2305 /* Makes and returns a copy of chain, up to and including element iElement. */
2306 static PCERT_SIMPLE_CHAIN CRYPT_CopySimpleChainToElement(
2307 const CERT_SIMPLE_CHAIN *chain, DWORD iElement)
2309 PCERT_SIMPLE_CHAIN copy = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
2311 if (copy)
2313 memset(copy, 0, sizeof(CERT_SIMPLE_CHAIN));
2314 copy->cbSize = sizeof(CERT_SIMPLE_CHAIN);
2315 copy->rgpElement =
2316 CryptMemAlloc((iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
2317 if (copy->rgpElement)
2319 DWORD i;
2320 BOOL ret = TRUE;
2322 memset(copy->rgpElement, 0,
2323 (iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
2324 for (i = 0; ret && i <= iElement; i++)
2326 PCERT_CHAIN_ELEMENT element =
2327 CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
2329 if (element)
2331 *element = *chain->rgpElement[i];
2332 element->pCertContext = CertDuplicateCertificateContext(
2333 chain->rgpElement[i]->pCertContext);
2334 /* Reset the trust status of the copied element, it'll get
2335 * rechecked after the new chain is done.
2337 memset(&element->TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
2338 copy->rgpElement[copy->cElement++] = element;
2340 else
2341 ret = FALSE;
2343 if (!ret)
2345 for (i = 0; i <= iElement; i++)
2346 CryptMemFree(copy->rgpElement[i]);
2347 CryptMemFree(copy->rgpElement);
2348 CryptMemFree(copy);
2349 copy = NULL;
2352 else
2354 CryptMemFree(copy);
2355 copy = NULL;
2358 return copy;
2361 static void CRYPT_FreeLowerQualityChains(CertificateChain *chain)
2363 DWORD i;
2365 for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
2366 CertFreeCertificateChain(chain->context.rgpLowerQualityChainContext[i]);
2367 CryptMemFree(chain->context.rgpLowerQualityChainContext);
2368 chain->context.cLowerQualityChainContext = 0;
2369 chain->context.rgpLowerQualityChainContext = NULL;
2372 static void CRYPT_FreeChainContext(CertificateChain *chain)
2374 DWORD i;
2376 CRYPT_FreeLowerQualityChains(chain);
2377 for (i = 0; i < chain->context.cChain; i++)
2378 CRYPT_FreeSimpleChain(chain->context.rgpChain[i]);
2379 CryptMemFree(chain->context.rgpChain);
2380 CertCloseStore(chain->world, 0);
2381 CryptMemFree(chain);
2384 /* Makes and returns a copy of chain, up to and including element iElement of
2385 * simple chain iChain.
2387 static CertificateChain *CRYPT_CopyChainToElement(CertificateChain *chain,
2388 DWORD iChain, DWORD iElement)
2390 CertificateChain *copy = CryptMemAlloc(sizeof(CertificateChain));
2392 if (copy)
2394 copy->ref = 1;
2395 copy->world = CertDuplicateStore(chain->world);
2396 copy->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
2397 /* Leave the trust status of the copied chain unset, it'll get
2398 * rechecked after the new chain is done.
2400 memset(&copy->context.TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
2401 copy->context.cLowerQualityChainContext = 0;
2402 copy->context.rgpLowerQualityChainContext = NULL;
2403 copy->context.fHasRevocationFreshnessTime = FALSE;
2404 copy->context.dwRevocationFreshnessTime = 0;
2405 copy->context.rgpChain = CryptMemAlloc(
2406 (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
2407 if (copy->context.rgpChain)
2409 BOOL ret = TRUE;
2410 DWORD i;
2412 memset(copy->context.rgpChain, 0,
2413 (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
2414 if (iChain)
2416 for (i = 0; ret && iChain && i < iChain - 1; i++)
2418 copy->context.rgpChain[i] =
2419 CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
2420 chain->context.rgpChain[i]->cElement - 1);
2421 if (!copy->context.rgpChain[i])
2422 ret = FALSE;
2425 else
2426 i = 0;
2427 if (ret)
2429 copy->context.rgpChain[i] =
2430 CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
2431 iElement);
2432 if (!copy->context.rgpChain[i])
2433 ret = FALSE;
2435 if (!ret)
2437 CRYPT_FreeChainContext(copy);
2438 copy = NULL;
2440 else
2441 copy->context.cChain = iChain + 1;
2443 else
2445 CryptMemFree(copy);
2446 copy = NULL;
2449 return copy;
2452 static CertificateChain *CRYPT_BuildAlternateContextFromChain(
2453 CertificateChainEngine *engine, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
2454 DWORD flags, CertificateChain *chain)
2456 CertificateChain *alternate;
2458 TRACE("(%p, %s, %p, %p)\n", engine, debugstr_filetime(pTime),
2459 hAdditionalStore, chain);
2461 /* Always start with the last "lower quality" chain to ensure a consistent
2462 * order of alternate creation:
2464 if (chain->context.cLowerQualityChainContext)
2465 chain = (CertificateChain*)chain->context.rgpLowerQualityChainContext[
2466 chain->context.cLowerQualityChainContext - 1];
2467 /* A chain with only one element can't have any alternates */
2468 if (chain->context.cChain <= 1 && chain->context.rgpChain[0]->cElement <= 1)
2469 alternate = NULL;
2470 else
2472 DWORD i, j, infoStatus;
2473 PCCERT_CONTEXT alternateIssuer = NULL;
2475 alternate = NULL;
2476 for (i = 0; !alternateIssuer && i < chain->context.cChain; i++)
2477 for (j = 0; !alternateIssuer &&
2478 j < chain->context.rgpChain[i]->cElement - 1; j++)
2480 PCCERT_CONTEXT subject =
2481 chain->context.rgpChain[i]->rgpElement[j]->pCertContext;
2482 PCCERT_CONTEXT prevIssuer = CertDuplicateCertificateContext(
2483 chain->context.rgpChain[i]->rgpElement[j + 1]->pCertContext);
2485 alternateIssuer = CRYPT_GetIssuer(engine, prevIssuer->hCertStore,
2486 subject, prevIssuer, flags, &infoStatus);
2488 if (alternateIssuer)
2490 i--;
2491 j--;
2492 alternate = CRYPT_CopyChainToElement(chain, i, j);
2493 if (alternate)
2495 BOOL ret = CRYPT_AddCertToSimpleChain(engine,
2496 alternate->context.rgpChain[i], alternateIssuer, infoStatus);
2498 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it
2499 * to close the enumeration that found it
2501 CertFreeCertificateContext(alternateIssuer);
2502 if (ret)
2504 ret = CRYPT_BuildSimpleChain(engine, alternate->world,
2505 flags, alternate->context.rgpChain[i]);
2506 if (ret)
2507 CRYPT_CheckSimpleChain(engine,
2508 alternate->context.rgpChain[i], pTime);
2509 CRYPT_CombineTrustStatus(&alternate->context.TrustStatus,
2510 &alternate->context.rgpChain[i]->TrustStatus);
2512 if (!ret)
2514 CRYPT_FreeChainContext(alternate);
2515 alternate = NULL;
2520 TRACE("%p\n", alternate);
2521 return alternate;
2524 #define CHAIN_QUALITY_SIGNATURE_VALID 0x16
2525 #define CHAIN_QUALITY_TIME_VALID 8
2526 #define CHAIN_QUALITY_COMPLETE_CHAIN 4
2527 #define CHAIN_QUALITY_BASIC_CONSTRAINTS 2
2528 #define CHAIN_QUALITY_TRUSTED_ROOT 1
2530 #define CHAIN_QUALITY_HIGHEST \
2531 CHAIN_QUALITY_SIGNATURE_VALID | CHAIN_QUALITY_TIME_VALID | \
2532 CHAIN_QUALITY_COMPLETE_CHAIN | CHAIN_QUALITY_BASIC_CONSTRAINTS | \
2533 CHAIN_QUALITY_TRUSTED_ROOT
2535 #define IS_TRUST_ERROR_SET(TrustStatus, bits) \
2536 (TrustStatus)->dwErrorStatus & (bits)
2538 static DWORD CRYPT_ChainQuality(const CertificateChain *chain)
2540 DWORD quality = CHAIN_QUALITY_HIGHEST;
2542 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2543 CERT_TRUST_IS_UNTRUSTED_ROOT))
2544 quality &= ~CHAIN_QUALITY_TRUSTED_ROOT;
2545 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2546 CERT_TRUST_INVALID_BASIC_CONSTRAINTS))
2547 quality &= ~CHAIN_QUALITY_BASIC_CONSTRAINTS;
2548 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2549 CERT_TRUST_IS_PARTIAL_CHAIN))
2550 quality &= ~CHAIN_QUALITY_COMPLETE_CHAIN;
2551 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2552 CERT_TRUST_IS_NOT_TIME_VALID | CERT_TRUST_IS_NOT_TIME_NESTED))
2553 quality &= ~CHAIN_QUALITY_TIME_VALID;
2554 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2555 CERT_TRUST_IS_NOT_SIGNATURE_VALID))
2556 quality &= ~CHAIN_QUALITY_SIGNATURE_VALID;
2557 return quality;
2560 /* Chooses the highest quality chain among chain and its "lower quality"
2561 * alternate chains. Returns the highest quality chain, with all other
2562 * chains as lower quality chains of it.
2564 static CertificateChain *CRYPT_ChooseHighestQualityChain(
2565 CertificateChain *chain)
2567 DWORD i;
2569 /* There are always only two chains being considered: chain, and an
2570 * alternate at chain->rgpLowerQualityChainContext[i]. If the alternate
2571 * has a higher quality than chain, the alternate gets assigned the lower
2572 * quality contexts, with chain taking the alternate's place among the
2573 * lower quality contexts.
2575 for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
2577 CertificateChain *alternate =
2578 (CertificateChain*)chain->context.rgpLowerQualityChainContext[i];
2580 if (CRYPT_ChainQuality(alternate) > CRYPT_ChainQuality(chain))
2582 alternate->context.cLowerQualityChainContext =
2583 chain->context.cLowerQualityChainContext;
2584 alternate->context.rgpLowerQualityChainContext =
2585 chain->context.rgpLowerQualityChainContext;
2586 alternate->context.rgpLowerQualityChainContext[i] =
2587 (PCCERT_CHAIN_CONTEXT)chain;
2588 chain->context.cLowerQualityChainContext = 0;
2589 chain->context.rgpLowerQualityChainContext = NULL;
2590 chain = alternate;
2593 return chain;
2596 static BOOL CRYPT_AddAlternateChainToChain(CertificateChain *chain,
2597 const CertificateChain *alternate)
2599 BOOL ret;
2601 if (chain->context.cLowerQualityChainContext)
2602 chain->context.rgpLowerQualityChainContext =
2603 CryptMemRealloc(chain->context.rgpLowerQualityChainContext,
2604 (chain->context.cLowerQualityChainContext + 1) *
2605 sizeof(PCCERT_CHAIN_CONTEXT));
2606 else
2607 chain->context.rgpLowerQualityChainContext =
2608 CryptMemAlloc(sizeof(PCCERT_CHAIN_CONTEXT));
2609 if (chain->context.rgpLowerQualityChainContext)
2611 chain->context.rgpLowerQualityChainContext[
2612 chain->context.cLowerQualityChainContext++] =
2613 (PCCERT_CHAIN_CONTEXT)alternate;
2614 ret = TRUE;
2616 else
2617 ret = FALSE;
2618 return ret;
2621 static PCERT_CHAIN_ELEMENT CRYPT_FindIthElementInChain(
2622 const CERT_CHAIN_CONTEXT *chain, DWORD i)
2624 DWORD j, iElement;
2625 PCERT_CHAIN_ELEMENT element = NULL;
2627 for (j = 0, iElement = 0; !element && j < chain->cChain; j++)
2629 if (iElement + chain->rgpChain[j]->cElement < i)
2630 iElement += chain->rgpChain[j]->cElement;
2631 else
2632 element = chain->rgpChain[j]->rgpElement[i - iElement];
2634 return element;
2637 typedef struct _CERT_CHAIN_PARA_NO_EXTRA_FIELDS {
2638 DWORD cbSize;
2639 CERT_USAGE_MATCH RequestedUsage;
2640 } CERT_CHAIN_PARA_NO_EXTRA_FIELDS;
2642 static void CRYPT_VerifyChainRevocation(PCERT_CHAIN_CONTEXT chain,
2643 LPFILETIME pTime, HCERTSTORE hAdditionalStore,
2644 const CERT_CHAIN_PARA *pChainPara, DWORD chainFlags)
2646 DWORD cContext;
2648 if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_END_CERT)
2649 cContext = 1;
2650 else if ((chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN) ||
2651 (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT))
2653 DWORD i;
2655 for (i = 0, cContext = 0; i < chain->cChain; i++)
2657 if (i < chain->cChain - 1 ||
2658 chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN)
2659 cContext += chain->rgpChain[i]->cElement;
2660 else
2661 cContext += chain->rgpChain[i]->cElement - 1;
2664 else
2665 cContext = 0;
2666 if (cContext)
2668 DWORD i, j, iContext, revocationFlags;
2669 CERT_REVOCATION_PARA revocationPara = { sizeof(revocationPara), 0 };
2670 CERT_REVOCATION_STATUS revocationStatus =
2671 { sizeof(revocationStatus), 0 };
2672 BOOL ret;
2674 revocationFlags = CERT_VERIFY_REV_CHAIN_FLAG;
2675 if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY)
2676 revocationFlags |= CERT_VERIFY_CACHE_ONLY_BASED_REVOCATION;
2677 if (chainFlags & CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT)
2678 revocationFlags |= CERT_VERIFY_REV_ACCUMULATIVE_TIMEOUT_FLAG;
2679 revocationPara.pftTimeToUse = pTime;
2680 if (hAdditionalStore)
2682 revocationPara.cCertStore = 1;
2683 revocationPara.rgCertStore = &hAdditionalStore;
2684 revocationPara.hCrlStore = hAdditionalStore;
2686 if (pChainPara->cbSize == sizeof(CERT_CHAIN_PARA))
2688 revocationPara.dwUrlRetrievalTimeout =
2689 pChainPara->dwUrlRetrievalTimeout;
2690 revocationPara.fCheckFreshnessTime =
2691 pChainPara->fCheckRevocationFreshnessTime;
2692 revocationPara.dwFreshnessTime =
2693 pChainPara->dwRevocationFreshnessTime;
2695 for (i = 0, iContext = 0; iContext < cContext && i < chain->cChain; i++)
2697 for (j = 0; iContext < cContext &&
2698 j < chain->rgpChain[i]->cElement; j++, iContext++)
2700 PCCERT_CONTEXT certToCheck =
2701 chain->rgpChain[i]->rgpElement[j]->pCertContext;
2703 if (j < chain->rgpChain[i]->cElement - 1)
2704 revocationPara.pIssuerCert =
2705 chain->rgpChain[i]->rgpElement[j + 1]->pCertContext;
2706 else
2707 revocationPara.pIssuerCert = NULL;
2708 ret = CertVerifyRevocation(X509_ASN_ENCODING,
2709 CERT_CONTEXT_REVOCATION_TYPE, 1, (void **)&certToCheck,
2710 revocationFlags, &revocationPara, &revocationStatus);
2711 if (!ret)
2713 PCERT_CHAIN_ELEMENT element = CRYPT_FindIthElementInChain(
2714 chain, iContext);
2715 DWORD error;
2717 switch (revocationStatus.dwError)
2719 case CRYPT_E_NO_REVOCATION_CHECK:
2720 case CRYPT_E_NO_REVOCATION_DLL:
2721 case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
2722 /* If the revocation status is unknown, it's assumed
2723 * to be offline too.
2725 error = CERT_TRUST_REVOCATION_STATUS_UNKNOWN |
2726 CERT_TRUST_IS_OFFLINE_REVOCATION;
2727 break;
2728 case CRYPT_E_REVOCATION_OFFLINE:
2729 error = CERT_TRUST_IS_OFFLINE_REVOCATION;
2730 break;
2731 case CRYPT_E_REVOKED:
2732 error = CERT_TRUST_IS_REVOKED;
2733 break;
2734 default:
2735 WARN("unmapped error %08x\n", revocationStatus.dwError);
2736 error = 0;
2738 if (element)
2740 /* FIXME: set element's pRevocationInfo member */
2741 element->TrustStatus.dwErrorStatus |= error;
2743 chain->TrustStatus.dwErrorStatus |= error;
2750 static void CRYPT_CheckUsages(PCERT_CHAIN_CONTEXT chain,
2751 const CERT_CHAIN_PARA *pChainPara)
2753 if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA_NO_EXTRA_FIELDS) &&
2754 pChainPara->RequestedUsage.Usage.cUsageIdentifier)
2756 PCCERT_CONTEXT endCert;
2757 PCERT_EXTENSION ext;
2758 BOOL validForUsage;
2760 /* A chain, if created, always includes the end certificate */
2761 endCert = chain->rgpChain[0]->rgpElement[0]->pCertContext;
2762 /* The extended key usage extension specifies how a certificate's
2763 * public key may be used. From RFC 5280, section 4.2.1.12:
2764 * "This extension indicates one or more purposes for which the
2765 * certified public key may be used, in addition to or in place of the
2766 * basic purposes indicated in the key usage extension."
2767 * If the extension is present, it only satisfies the requested usage
2768 * if that usage is included in the extension:
2769 * "If the extension is present, then the certificate MUST only be used
2770 * for one of the purposes indicated."
2771 * There is also the special anyExtendedKeyUsage OID, but it doesn't
2772 * have to be respected:
2773 * "Applications that require the presence of a particular purpose
2774 * MAY reject certificates that include the anyExtendedKeyUsage OID
2775 * but not the particular OID expected for the application."
2776 * For now, I'm being more conservative and ignoring the presence of
2777 * the anyExtendedKeyUsage OID.
2779 if ((ext = CertFindExtension(szOID_ENHANCED_KEY_USAGE,
2780 endCert->pCertInfo->cExtension, endCert->pCertInfo->rgExtension)))
2782 const CERT_ENHKEY_USAGE *requestedUsage =
2783 &pChainPara->RequestedUsage.Usage;
2784 CERT_ENHKEY_USAGE *usage;
2785 DWORD size;
2787 if (CryptDecodeObjectEx(X509_ASN_ENCODING,
2788 X509_ENHANCED_KEY_USAGE, ext->Value.pbData, ext->Value.cbData,
2789 CRYPT_DECODE_ALLOC_FLAG, NULL, &usage, &size))
2791 if (pChainPara->RequestedUsage.dwType == USAGE_MATCH_TYPE_AND)
2793 DWORD i, j;
2795 /* For AND matches, all usages must be present */
2796 validForUsage = TRUE;
2797 for (i = 0; validForUsage &&
2798 i < requestedUsage->cUsageIdentifier; i++)
2800 BOOL match = FALSE;
2802 for (j = 0; !match && j < usage->cUsageIdentifier; j++)
2803 match = !strcmp(usage->rgpszUsageIdentifier[j],
2804 requestedUsage->rgpszUsageIdentifier[i]);
2805 if (!match)
2806 validForUsage = FALSE;
2809 else
2811 DWORD i, j;
2813 /* For OR matches, any matching usage suffices */
2814 validForUsage = FALSE;
2815 for (i = 0; !validForUsage &&
2816 i < requestedUsage->cUsageIdentifier; i++)
2818 for (j = 0; !validForUsage &&
2819 j < usage->cUsageIdentifier; j++)
2820 validForUsage =
2821 !strcmp(usage->rgpszUsageIdentifier[j],
2822 requestedUsage->rgpszUsageIdentifier[i]);
2825 LocalFree(usage);
2827 else
2828 validForUsage = FALSE;
2830 else
2832 /* If the extension isn't present, any interpretation is valid:
2833 * "Certificate using applications MAY require that the extended
2834 * key usage extension be present and that a particular purpose
2835 * be indicated in order for the certificate to be acceptable to
2836 * that application."
2837 * Not all web sites include the extended key usage extension, so
2838 * accept chains without it.
2840 TRACE_(chain)("requested usage from certificate with no usages\n");
2841 validForUsage = TRUE;
2843 if (!validForUsage)
2845 chain->TrustStatus.dwErrorStatus |=
2846 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
2847 chain->rgpChain[0]->rgpElement[0]->TrustStatus.dwErrorStatus |=
2848 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
2851 if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA) &&
2852 pChainPara->RequestedIssuancePolicy.Usage.cUsageIdentifier)
2853 FIXME("unimplemented for RequestedIssuancePolicy\n");
2856 static void dump_usage_match(LPCSTR name, const CERT_USAGE_MATCH *usageMatch)
2858 if (usageMatch->Usage.cUsageIdentifier)
2860 DWORD i;
2862 TRACE_(chain)("%s: %s\n", name,
2863 usageMatch->dwType == USAGE_MATCH_TYPE_AND ? "AND" : "OR");
2864 for (i = 0; i < usageMatch->Usage.cUsageIdentifier; i++)
2865 TRACE_(chain)("%s\n", usageMatch->Usage.rgpszUsageIdentifier[i]);
2869 static void dump_chain_para(const CERT_CHAIN_PARA *pChainPara)
2871 TRACE_(chain)("%d\n", pChainPara->cbSize);
2872 if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA_NO_EXTRA_FIELDS))
2873 dump_usage_match("RequestedUsage", &pChainPara->RequestedUsage);
2874 if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA))
2876 dump_usage_match("RequestedIssuancePolicy",
2877 &pChainPara->RequestedIssuancePolicy);
2878 TRACE_(chain)("%d\n", pChainPara->dwUrlRetrievalTimeout);
2879 TRACE_(chain)("%d\n", pChainPara->fCheckRevocationFreshnessTime);
2880 TRACE_(chain)("%d\n", pChainPara->dwRevocationFreshnessTime);
2884 BOOL WINAPI CertGetCertificateChain(HCERTCHAINENGINE hChainEngine,
2885 PCCERT_CONTEXT pCertContext, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
2886 PCERT_CHAIN_PARA pChainPara, DWORD dwFlags, LPVOID pvReserved,
2887 PCCERT_CHAIN_CONTEXT* ppChainContext)
2889 CertificateChainEngine *engine;
2890 BOOL ret;
2891 CertificateChain *chain = NULL;
2893 TRACE("(%p, %p, %s, %p, %p, %08x, %p, %p)\n", hChainEngine, pCertContext,
2894 debugstr_filetime(pTime), hAdditionalStore, pChainPara, dwFlags,
2895 pvReserved, ppChainContext);
2897 engine = get_chain_engine(hChainEngine, TRUE);
2898 if (!engine)
2899 return FALSE;
2901 if (ppChainContext)
2902 *ppChainContext = NULL;
2903 if (!pChainPara)
2905 SetLastError(E_INVALIDARG);
2906 return FALSE;
2908 if (!pCertContext->pCertInfo->SignatureAlgorithm.pszObjId)
2910 SetLastError(ERROR_INVALID_DATA);
2911 return FALSE;
2914 if (TRACE_ON(chain))
2915 dump_chain_para(pChainPara);
2916 /* FIXME: what about HCCE_LOCAL_MACHINE? */
2917 ret = CRYPT_BuildCandidateChainFromCert(engine, pCertContext, pTime,
2918 hAdditionalStore, dwFlags, &chain);
2919 if (ret)
2921 CertificateChain *alternate = NULL;
2922 PCERT_CHAIN_CONTEXT pChain;
2924 do {
2925 alternate = CRYPT_BuildAlternateContextFromChain(engine,
2926 pTime, hAdditionalStore, dwFlags, chain);
2928 /* Alternate contexts are added as "lower quality" contexts of
2929 * chain, to avoid loops in alternate chain creation.
2930 * The highest-quality chain is chosen at the end.
2932 if (alternate)
2933 ret = CRYPT_AddAlternateChainToChain(chain, alternate);
2934 } while (ret && alternate);
2935 chain = CRYPT_ChooseHighestQualityChain(chain);
2936 if (!(dwFlags & CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS))
2937 CRYPT_FreeLowerQualityChains(chain);
2938 pChain = (PCERT_CHAIN_CONTEXT)chain;
2939 CRYPT_VerifyChainRevocation(pChain, pTime, hAdditionalStore,
2940 pChainPara, dwFlags);
2941 CRYPT_CheckUsages(pChain, pChainPara);
2942 TRACE_(chain)("error status: %08x\n",
2943 pChain->TrustStatus.dwErrorStatus);
2944 if (ppChainContext)
2945 *ppChainContext = pChain;
2946 else
2947 CertFreeCertificateChain(pChain);
2949 TRACE("returning %d\n", ret);
2950 return ret;
2953 PCCERT_CHAIN_CONTEXT WINAPI CertDuplicateCertificateChain(
2954 PCCERT_CHAIN_CONTEXT pChainContext)
2956 CertificateChain *chain = (CertificateChain*)pChainContext;
2958 TRACE("(%p)\n", pChainContext);
2960 if (chain)
2961 InterlockedIncrement(&chain->ref);
2962 return pChainContext;
2965 VOID WINAPI CertFreeCertificateChain(PCCERT_CHAIN_CONTEXT pChainContext)
2967 CertificateChain *chain = (CertificateChain*)pChainContext;
2969 TRACE("(%p)\n", pChainContext);
2971 if (chain)
2973 if (InterlockedDecrement(&chain->ref) == 0)
2974 CRYPT_FreeChainContext(chain);
2978 PCCERT_CHAIN_CONTEXT WINAPI CertFindChainInStore(HCERTSTORE store,
2979 DWORD certEncodingType, DWORD findFlags, DWORD findType,
2980 const void *findPara, PCCERT_CHAIN_CONTEXT prevChainContext)
2982 FIXME("(%p, %08x, %08x, %d, %p, %p): stub\n", store, certEncodingType,
2983 findFlags, findType, findPara, prevChainContext);
2984 return NULL;
2987 static void find_element_with_error(PCCERT_CHAIN_CONTEXT chain, DWORD error,
2988 LONG *iChain, LONG *iElement)
2990 DWORD i, j;
2992 for (i = 0; i < chain->cChain; i++)
2993 for (j = 0; j < chain->rgpChain[i]->cElement; j++)
2994 if (chain->rgpChain[i]->rgpElement[j]->TrustStatus.dwErrorStatus &
2995 error)
2997 *iChain = i;
2998 *iElement = j;
2999 return;
3003 static BOOL WINAPI verify_base_policy(LPCSTR szPolicyOID,
3004 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3005 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
3007 DWORD checks = 0;
3009 if (pPolicyPara)
3010 checks = pPolicyPara->dwFlags;
3011 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
3012 pPolicyStatus->dwError = NO_ERROR;
3013 if (pChainContext->TrustStatus.dwErrorStatus &
3014 CERT_TRUST_IS_NOT_SIGNATURE_VALID)
3016 pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
3017 find_element_with_error(pChainContext,
3018 CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
3019 &pPolicyStatus->lElementIndex);
3021 else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
3023 pPolicyStatus->dwError = CERT_E_CHAINING;
3024 find_element_with_error(pChainContext, CERT_TRUST_IS_CYCLIC,
3025 &pPolicyStatus->lChainIndex, &pPolicyStatus->lElementIndex);
3026 /* For a cyclic chain, which element is a cycle isn't meaningful */
3027 pPolicyStatus->lElementIndex = -1;
3029 if (!pPolicyStatus->dwError &&
3030 pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_UNTRUSTED_ROOT &&
3031 !(checks & CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG))
3033 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
3034 find_element_with_error(pChainContext,
3035 CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
3036 &pPolicyStatus->lElementIndex);
3038 if (!pPolicyStatus->dwError &&
3039 pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
3041 pPolicyStatus->dwError = CERT_E_EXPIRED;
3042 find_element_with_error(pChainContext,
3043 CERT_TRUST_IS_NOT_TIME_VALID, &pPolicyStatus->lChainIndex,
3044 &pPolicyStatus->lElementIndex);
3046 if (!pPolicyStatus->dwError &&
3047 pChainContext->TrustStatus.dwErrorStatus &
3048 CERT_TRUST_IS_NOT_VALID_FOR_USAGE &&
3049 !(checks & CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG))
3051 pPolicyStatus->dwError = CERT_E_WRONG_USAGE;
3052 find_element_with_error(pChainContext,
3053 CERT_TRUST_IS_NOT_VALID_FOR_USAGE, &pPolicyStatus->lChainIndex,
3054 &pPolicyStatus->lElementIndex);
3056 if (!pPolicyStatus->dwError &&
3057 pChainContext->TrustStatus.dwErrorStatus &
3058 CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT &&
3059 !(checks & CERT_CHAIN_POLICY_IGNORE_NOT_SUPPORTED_CRITICAL_EXT_FLAG))
3061 pPolicyStatus->dwError = CERT_E_CRITICAL;
3062 find_element_with_error(pChainContext,
3063 CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT, &pPolicyStatus->lChainIndex,
3064 &pPolicyStatus->lElementIndex);
3066 return TRUE;
3069 static BYTE msTestPubKey1[] = {
3070 0x30,0x47,0x02,0x40,0x81,0x55,0x22,0xb9,0x8a,0xa4,0x6f,0xed,0xd6,0xe7,0xd9,
3071 0x66,0x0f,0x55,0xbc,0xd7,0xcd,0xd5,0xbc,0x4e,0x40,0x02,0x21,0xa2,0xb1,0xf7,
3072 0x87,0x30,0x85,0x5e,0xd2,0xf2,0x44,0xb9,0xdc,0x9b,0x75,0xb6,0xfb,0x46,0x5f,
3073 0x42,0xb6,0x9d,0x23,0x36,0x0b,0xde,0x54,0x0f,0xcd,0xbd,0x1f,0x99,0x2a,0x10,
3074 0x58,0x11,0xcb,0x40,0xcb,0xb5,0xa7,0x41,0x02,0x03,0x01,0x00,0x01 };
3075 static BYTE msTestPubKey2[] = {
3076 0x30,0x47,0x02,0x40,0x9c,0x50,0x05,0x1d,0xe2,0x0e,0x4c,0x53,0xd8,0xd9,0xb5,
3077 0xe5,0xfd,0xe9,0xe3,0xad,0x83,0x4b,0x80,0x08,0xd9,0xdc,0xe8,0xe8,0x35,0xf8,
3078 0x11,0xf1,0xe9,0x9b,0x03,0x7a,0x65,0x64,0x76,0x35,0xce,0x38,0x2c,0xf2,0xb6,
3079 0x71,0x9e,0x06,0xd9,0xbf,0xbb,0x31,0x69,0xa3,0xf6,0x30,0xa0,0x78,0x7b,0x18,
3080 0xdd,0x50,0x4d,0x79,0x1e,0xeb,0x61,0xc1,0x02,0x03,0x01,0x00,0x01 };
3082 static void dump_authenticode_extra_chain_policy_para(
3083 AUTHENTICODE_EXTRA_CERT_CHAIN_POLICY_PARA *extraPara)
3085 if (extraPara)
3087 TRACE_(chain)("cbSize = %d\n", extraPara->cbSize);
3088 TRACE_(chain)("dwRegPolicySettings = %08x\n",
3089 extraPara->dwRegPolicySettings);
3090 TRACE_(chain)("pSignerInfo = %p\n", extraPara->pSignerInfo);
3094 static BOOL WINAPI verify_authenticode_policy(LPCSTR szPolicyOID,
3095 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3096 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
3098 BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
3099 pPolicyStatus);
3100 AUTHENTICODE_EXTRA_CERT_CHAIN_POLICY_PARA *extraPara = NULL;
3102 if (pPolicyPara)
3103 extraPara = pPolicyPara->pvExtraPolicyPara;
3104 if (TRACE_ON(chain))
3105 dump_authenticode_extra_chain_policy_para(extraPara);
3106 if (ret && pPolicyStatus->dwError == CERT_E_UNTRUSTEDROOT)
3108 CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
3109 BOOL isMSTestRoot = FALSE;
3110 PCCERT_CONTEXT failingCert =
3111 pChainContext->rgpChain[pPolicyStatus->lChainIndex]->
3112 rgpElement[pPolicyStatus->lElementIndex]->pCertContext;
3113 DWORD i;
3114 CRYPT_DATA_BLOB keyBlobs[] = {
3115 { sizeof(msTestPubKey1), msTestPubKey1 },
3116 { sizeof(msTestPubKey2), msTestPubKey2 },
3119 /* Check whether the root is an MS test root */
3120 for (i = 0; !isMSTestRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
3121 i++)
3123 msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
3124 msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
3125 if (CertComparePublicKeyInfo(
3126 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
3127 &failingCert->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
3128 isMSTestRoot = TRUE;
3130 if (isMSTestRoot)
3131 pPolicyStatus->dwError = CERT_E_UNTRUSTEDTESTROOT;
3133 return ret;
3136 static BOOL WINAPI verify_basic_constraints_policy(LPCSTR szPolicyOID,
3137 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3138 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
3140 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
3141 if (pChainContext->TrustStatus.dwErrorStatus &
3142 CERT_TRUST_INVALID_BASIC_CONSTRAINTS)
3144 pPolicyStatus->dwError = TRUST_E_BASIC_CONSTRAINTS;
3145 find_element_with_error(pChainContext,
3146 CERT_TRUST_INVALID_BASIC_CONSTRAINTS, &pPolicyStatus->lChainIndex,
3147 &pPolicyStatus->lElementIndex);
3149 else
3150 pPolicyStatus->dwError = NO_ERROR;
3151 return TRUE;
3154 static BOOL match_dns_to_subject_alt_name(const CERT_EXTENSION *ext,
3155 LPCWSTR server_name)
3157 BOOL matches = FALSE;
3158 CERT_ALT_NAME_INFO *subjectName;
3159 DWORD size;
3161 TRACE_(chain)("%s\n", debugstr_w(server_name));
3162 /* This could be spoofed by the embedded NULL vulnerability, since the
3163 * returned CERT_ALT_NAME_INFO doesn't have a way to indicate the
3164 * encoded length of a name. Fortunately CryptDecodeObjectEx fails if
3165 * the encoded form of the name contains a NULL.
3167 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
3168 ext->Value.pbData, ext->Value.cbData,
3169 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
3170 &subjectName, &size))
3172 DWORD i;
3174 /* RFC 5280 states that multiple instances of each name type may exist,
3175 * in section 4.2.1.6:
3176 * "Multiple name forms, and multiple instances of each name form,
3177 * MAY be included."
3178 * It doesn't specify the behavior in such cases, but both RFC 2818
3179 * and RFC 2595 explicitly accept a certificate if any name matches.
3181 for (i = 0; !matches && i < subjectName->cAltEntry; i++)
3183 if (subjectName->rgAltEntry[i].dwAltNameChoice ==
3184 CERT_ALT_NAME_DNS_NAME)
3186 TRACE_(chain)("dNSName: %s\n", debugstr_w(
3187 subjectName->rgAltEntry[i].u.pwszDNSName));
3188 if (subjectName->rgAltEntry[i].u.pwszDNSName[0] == '*')
3190 LPCWSTR server_name_dot;
3192 /* Matching a wildcard: a wildcard matches a single name
3193 * component, which is terminated by a dot. RFC 1034
3194 * doesn't define whether multiple wildcards are allowed,
3195 * but I will assume that they are not until proven
3196 * otherwise. RFC 1034 also states that 'the "*" label
3197 * always matches at least one whole label and sometimes
3198 * more, but always whole labels.' Native crypt32 does not
3199 * match more than one label with a wildcard, so I do the
3200 * same here. Thus, a wildcard only accepts the first
3201 * label, then requires an exact match of the remaining
3202 * string.
3204 server_name_dot = strchrW(server_name, '.');
3205 if (server_name_dot)
3207 if (!strcmpiW(server_name_dot,
3208 subjectName->rgAltEntry[i].u.pwszDNSName + 1))
3209 matches = TRUE;
3212 else if (!strcmpiW(server_name,
3213 subjectName->rgAltEntry[i].u.pwszDNSName))
3214 matches = TRUE;
3217 LocalFree(subjectName);
3219 return matches;
3222 static BOOL find_matching_domain_component(const CERT_NAME_INFO *name,
3223 LPCWSTR component)
3225 BOOL matches = FALSE;
3226 DWORD i, j;
3228 for (i = 0; !matches && i < name->cRDN; i++)
3229 for (j = 0; j < name->rgRDN[i].cRDNAttr; j++)
3230 if (!strcmp(szOID_DOMAIN_COMPONENT,
3231 name->rgRDN[i].rgRDNAttr[j].pszObjId))
3233 const CERT_RDN_ATTR *attr;
3235 attr = &name->rgRDN[i].rgRDNAttr[j];
3236 /* Compare with memicmpW rather than strcmpiW in order to avoid
3237 * a match with a string with an embedded NULL. The component
3238 * must match one domain component attribute's entire string
3239 * value with a case-insensitive match.
3241 matches = !memicmpW(component, (LPCWSTR)attr->Value.pbData,
3242 attr->Value.cbData / sizeof(WCHAR));
3244 return matches;
3247 static BOOL match_domain_component(LPCWSTR allowed_component, DWORD allowed_len,
3248 LPCWSTR server_component, DWORD server_len, BOOL allow_wildcards,
3249 BOOL *see_wildcard)
3251 LPCWSTR allowed_ptr, server_ptr;
3252 BOOL matches = TRUE;
3254 *see_wildcard = FALSE;
3256 if (server_len < allowed_len)
3258 WARN_(chain)("domain component %s too short for %s\n",
3259 debugstr_wn(server_component, server_len),
3260 debugstr_wn(allowed_component, allowed_len));
3261 /* A domain component can't contain a wildcard character, so a domain
3262 * component shorter than the allowed string can't produce a match.
3264 return FALSE;
3266 for (allowed_ptr = allowed_component, server_ptr = server_component;
3267 matches && allowed_ptr - allowed_component < allowed_len;
3268 allowed_ptr++, server_ptr++)
3270 if (*allowed_ptr == '*')
3272 if (allowed_ptr - allowed_component < allowed_len - 1)
3274 WARN_(chain)("non-wildcard characters after wildcard not supported\n");
3275 matches = FALSE;
3277 else if (!allow_wildcards)
3279 WARN_(chain)("wildcard after non-wildcard component\n");
3280 matches = FALSE;
3282 else
3284 /* the preceding characters must have matched, so the rest of
3285 * the component also matches.
3287 *see_wildcard = TRUE;
3288 break;
3291 if (matches)
3292 matches = tolowerW(*allowed_ptr) == tolowerW(*server_ptr);
3294 if (matches && server_ptr - server_component < server_len)
3296 /* If there are unmatched characters in the server domain component,
3297 * the server domain only matches if the allowed string ended in a '*'.
3299 matches = *allowed_ptr == '*';
3301 return matches;
3304 static BOOL match_common_name(LPCWSTR server_name, const CERT_RDN_ATTR *nameAttr)
3306 LPCWSTR allowed = (LPCWSTR)nameAttr->Value.pbData;
3307 LPCWSTR allowed_component = allowed;
3308 DWORD allowed_len = nameAttr->Value.cbData / sizeof(WCHAR);
3309 LPCWSTR server_component = server_name;
3310 DWORD server_len = strlenW(server_name);
3311 BOOL matches = TRUE, allow_wildcards = TRUE;
3313 TRACE_(chain)("CN = %s\n", debugstr_wn(allowed_component, allowed_len));
3315 /* Remove trailing NULLs from the allowed name; while they shouldn't appear
3316 * in a certificate in the first place, they sometimes do, and they should
3317 * be ignored.
3319 while (allowed_len && allowed_component[allowed_len - 1] == 0)
3320 allowed_len--;
3322 /* From RFC 2818 (HTTP over TLS), section 3.1:
3323 * "Names may contain the wildcard character * which is considered to match
3324 * any single domain name component or component fragment. E.g.,
3325 * *.a.com matches foo.a.com but not bar.foo.a.com. f*.com matches foo.com
3326 * but not bar.com."
3328 * And from RFC 2595 (Using TLS with IMAP, POP3 and ACAP), section 2.4:
3329 * "A "*" wildcard character MAY be used as the left-most name component in
3330 * the certificate. For example, *.example.com would match a.example.com,
3331 * foo.example.com, etc. but would not match example.com."
3333 * There are other protocols which use TLS, and none of them is
3334 * authoritative. This accepts certificates in common usage, e.g.
3335 * *.domain.com matches www.domain.com but not domain.com, and
3336 * www*.domain.com matches www1.domain.com but not mail.domain.com.
3338 do {
3339 LPCWSTR allowed_dot, server_dot;
3341 allowed_dot = memchrW(allowed_component, '.',
3342 allowed_len - (allowed_component - allowed));
3343 server_dot = memchrW(server_component, '.',
3344 server_len - (server_component - server_name));
3345 /* The number of components must match */
3346 if ((!allowed_dot && server_dot) || (allowed_dot && !server_dot))
3348 if (!allowed_dot)
3349 WARN_(chain)("%s: too many components for CN=%s\n",
3350 debugstr_w(server_name), debugstr_wn(allowed, allowed_len));
3351 else
3352 WARN_(chain)("%s: not enough components for CN=%s\n",
3353 debugstr_w(server_name), debugstr_wn(allowed, allowed_len));
3354 matches = FALSE;
3356 else
3358 LPCWSTR allowed_end, server_end;
3359 BOOL has_wildcard;
3361 allowed_end = allowed_dot ? allowed_dot : allowed + allowed_len;
3362 server_end = server_dot ? server_dot : server_name + server_len;
3363 matches = match_domain_component(allowed_component,
3364 allowed_end - allowed_component, server_component,
3365 server_end - server_component, allow_wildcards, &has_wildcard);
3366 /* Once a non-wildcard component is seen, no wildcard components
3367 * may follow
3369 if (!has_wildcard)
3370 allow_wildcards = FALSE;
3371 if (matches)
3373 allowed_component = allowed_dot ? allowed_dot + 1 : allowed_end;
3374 server_component = server_dot ? server_dot + 1 : server_end;
3377 } while (matches && allowed_component &&
3378 allowed_component - allowed < allowed_len &&
3379 server_component && server_component - server_name < server_len);
3380 TRACE_(chain)("returning %d\n", matches);
3381 return matches;
3384 static BOOL match_dns_to_subject_dn(PCCERT_CONTEXT cert, LPCWSTR server_name)
3386 BOOL matches = FALSE;
3387 CERT_NAME_INFO *name;
3388 DWORD size;
3390 TRACE_(chain)("%s\n", debugstr_w(server_name));
3391 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_UNICODE_NAME,
3392 cert->pCertInfo->Subject.pbData, cert->pCertInfo->Subject.cbData,
3393 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
3394 &name, &size))
3396 /* If the subject distinguished name contains any name components,
3397 * make sure all of them are present.
3399 if (CertFindRDNAttr(szOID_DOMAIN_COMPONENT, name))
3401 LPCWSTR ptr = server_name;
3403 do {
3404 LPCWSTR dot = strchrW(ptr, '.'), end;
3405 /* 254 is the maximum DNS label length, see RFC 1035 */
3406 WCHAR component[255];
3407 DWORD len;
3409 end = dot ? dot : ptr + strlenW(ptr);
3410 len = end - ptr;
3411 if (len >= sizeof(component) / sizeof(component[0]))
3413 WARN_(chain)("domain component %s too long\n",
3414 debugstr_wn(ptr, len));
3415 matches = FALSE;
3417 else
3419 memcpy(component, ptr, len * sizeof(WCHAR));
3420 component[len] = 0;
3421 matches = find_matching_domain_component(name, component);
3423 ptr = dot ? dot + 1 : end;
3424 } while (matches && ptr && *ptr);
3426 else
3428 DWORD i, j;
3430 /* If the certificate isn't using a DN attribute in the name, make
3431 * make sure at least one common name matches. From RFC 2818,
3432 * section 3.1:
3433 * "If more than one identity of a given type is present in the
3434 * certificate (e.g., more than one dNSName name, a match in any
3435 * one of the set is considered acceptable.)"
3437 for (i = 0; !matches && i < name->cRDN; i++)
3438 for (j = 0; !matches && j < name->rgRDN[i].cRDNAttr; j++)
3440 PCERT_RDN_ATTR attr = &name->rgRDN[i].rgRDNAttr[j];
3442 if (attr->pszObjId && !strcmp(szOID_COMMON_NAME,
3443 attr->pszObjId))
3444 matches = match_common_name(server_name, attr);
3447 LocalFree(name);
3449 return matches;
3452 static void dump_ssl_extra_chain_policy_para(HTTPSPolicyCallbackData *sslPara)
3454 if (sslPara)
3456 TRACE_(chain)("cbSize = %d\n", sslPara->u.cbSize);
3457 TRACE_(chain)("dwAuthType = %d\n", sslPara->dwAuthType);
3458 TRACE_(chain)("fdwChecks = %08x\n", sslPara->fdwChecks);
3459 TRACE_(chain)("pwszServerName = %s\n",
3460 debugstr_w(sslPara->pwszServerName));
3464 static BOOL WINAPI verify_ssl_policy(LPCSTR szPolicyOID,
3465 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3466 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
3468 HTTPSPolicyCallbackData *sslPara = NULL;
3469 DWORD checks = 0;
3471 if (pPolicyPara)
3472 sslPara = pPolicyPara->pvExtraPolicyPara;
3473 if (TRACE_ON(chain))
3474 dump_ssl_extra_chain_policy_para(sslPara);
3475 if (sslPara && sslPara->u.cbSize >= sizeof(HTTPSPolicyCallbackData))
3476 checks = sslPara->fdwChecks;
3477 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
3478 if (pChainContext->TrustStatus.dwErrorStatus &
3479 CERT_TRUST_IS_NOT_SIGNATURE_VALID)
3481 pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
3482 find_element_with_error(pChainContext,
3483 CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
3484 &pPolicyStatus->lElementIndex);
3486 else if (pChainContext->TrustStatus.dwErrorStatus &
3487 CERT_TRUST_IS_UNTRUSTED_ROOT &&
3488 !(checks & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
3490 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
3491 find_element_with_error(pChainContext,
3492 CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
3493 &pPolicyStatus->lElementIndex);
3495 else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
3497 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
3498 find_element_with_error(pChainContext,
3499 CERT_TRUST_IS_CYCLIC, &pPolicyStatus->lChainIndex,
3500 &pPolicyStatus->lElementIndex);
3501 /* For a cyclic chain, which element is a cycle isn't meaningful */
3502 pPolicyStatus->lElementIndex = -1;
3504 else if (pChainContext->TrustStatus.dwErrorStatus &
3505 CERT_TRUST_IS_NOT_TIME_VALID &&
3506 !(checks & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
3508 pPolicyStatus->dwError = CERT_E_EXPIRED;
3509 find_element_with_error(pChainContext,
3510 CERT_TRUST_IS_NOT_TIME_VALID, &pPolicyStatus->lChainIndex,
3511 &pPolicyStatus->lElementIndex);
3513 else if (pChainContext->TrustStatus.dwErrorStatus &
3514 CERT_TRUST_IS_NOT_VALID_FOR_USAGE &&
3515 !(checks & SECURITY_FLAG_IGNORE_WRONG_USAGE))
3517 pPolicyStatus->dwError = CERT_E_WRONG_USAGE;
3518 find_element_with_error(pChainContext,
3519 CERT_TRUST_IS_NOT_VALID_FOR_USAGE, &pPolicyStatus->lChainIndex,
3520 &pPolicyStatus->lElementIndex);
3522 else if (pChainContext->TrustStatus.dwErrorStatus &
3523 CERT_TRUST_IS_REVOKED && !(checks & SECURITY_FLAG_IGNORE_REVOCATION))
3525 pPolicyStatus->dwError = CERT_E_REVOKED;
3526 find_element_with_error(pChainContext,
3527 CERT_TRUST_IS_REVOKED, &pPolicyStatus->lChainIndex,
3528 &pPolicyStatus->lElementIndex);
3530 else if (pChainContext->TrustStatus.dwErrorStatus &
3531 CERT_TRUST_IS_OFFLINE_REVOCATION &&
3532 !(checks & SECURITY_FLAG_IGNORE_REVOCATION))
3534 pPolicyStatus->dwError = CERT_E_REVOCATION_FAILURE;
3535 find_element_with_error(pChainContext,
3536 CERT_TRUST_IS_OFFLINE_REVOCATION, &pPolicyStatus->lChainIndex,
3537 &pPolicyStatus->lElementIndex);
3539 else if (pChainContext->TrustStatus.dwErrorStatus &
3540 CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT)
3542 pPolicyStatus->dwError = CERT_E_CRITICAL;
3543 find_element_with_error(pChainContext,
3544 CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT, &pPolicyStatus->lChainIndex,
3545 &pPolicyStatus->lElementIndex);
3547 else
3548 pPolicyStatus->dwError = NO_ERROR;
3549 /* We only need bother checking whether the name in the end certificate
3550 * matches if the chain is otherwise okay.
3552 if (!pPolicyStatus->dwError && pPolicyPara &&
3553 pPolicyPara->cbSize >= sizeof(CERT_CHAIN_POLICY_PARA))
3555 if (sslPara && sslPara->u.cbSize >= sizeof(HTTPSPolicyCallbackData))
3557 if (sslPara->dwAuthType == AUTHTYPE_SERVER &&
3558 sslPara->pwszServerName &&
3559 !(checks & SECURITY_FLAG_IGNORE_CERT_CN_INVALID))
3561 PCCERT_CONTEXT cert;
3562 PCERT_EXTENSION altNameExt;
3563 BOOL matches;
3565 cert = pChainContext->rgpChain[0]->rgpElement[0]->pCertContext;
3566 altNameExt = get_subject_alt_name_ext(cert->pCertInfo);
3567 /* If the alternate name extension exists, the name it contains
3568 * is bound to the certificate, so make sure the name matches
3569 * it. Otherwise, look for the server name in the subject
3570 * distinguished name. RFC5280, section 4.2.1.6:
3571 * "Whenever such identities are to be bound into a
3572 * certificate, the subject alternative name (or issuer
3573 * alternative name) extension MUST be used; however, a DNS
3574 * name MAY also be represented in the subject field using the
3575 * domainComponent attribute."
3577 if (altNameExt)
3578 matches = match_dns_to_subject_alt_name(altNameExt,
3579 sslPara->pwszServerName);
3580 else
3581 matches = match_dns_to_subject_dn(cert,
3582 sslPara->pwszServerName);
3583 if (!matches)
3585 pPolicyStatus->dwError = CERT_E_CN_NO_MATCH;
3586 pPolicyStatus->lChainIndex = 0;
3587 pPolicyStatus->lElementIndex = 0;
3592 return TRUE;
3595 static BYTE msPubKey1[] = {
3596 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xdf,0x08,0xba,0xe3,0x3f,0x6e,
3597 0x64,0x9b,0xf5,0x89,0xaf,0x28,0x96,0x4a,0x07,0x8f,0x1b,0x2e,0x8b,0x3e,0x1d,
3598 0xfc,0xb8,0x80,0x69,0xa3,0xa1,0xce,0xdb,0xdf,0xb0,0x8e,0x6c,0x89,0x76,0x29,
3599 0x4f,0xca,0x60,0x35,0x39,0xad,0x72,0x32,0xe0,0x0b,0xae,0x29,0x3d,0x4c,0x16,
3600 0xd9,0x4b,0x3c,0x9d,0xda,0xc5,0xd3,0xd1,0x09,0xc9,0x2c,0x6f,0xa6,0xc2,0x60,
3601 0x53,0x45,0xdd,0x4b,0xd1,0x55,0xcd,0x03,0x1c,0xd2,0x59,0x56,0x24,0xf3,0xe5,
3602 0x78,0xd8,0x07,0xcc,0xd8,0xb3,0x1f,0x90,0x3f,0xc0,0x1a,0x71,0x50,0x1d,0x2d,
3603 0xa7,0x12,0x08,0x6d,0x7c,0xb0,0x86,0x6c,0xc7,0xba,0x85,0x32,0x07,0xe1,0x61,
3604 0x6f,0xaf,0x03,0xc5,0x6d,0xe5,0xd6,0xa1,0x8f,0x36,0xf6,0xc1,0x0b,0xd1,0x3e,
3605 0x69,0x97,0x48,0x72,0xc9,0x7f,0xa4,0xc8,0xc2,0x4a,0x4c,0x7e,0xa1,0xd1,0x94,
3606 0xa6,0xd7,0xdc,0xeb,0x05,0x46,0x2e,0xb8,0x18,0xb4,0x57,0x1d,0x86,0x49,0xdb,
3607 0x69,0x4a,0x2c,0x21,0xf5,0x5e,0x0f,0x54,0x2d,0x5a,0x43,0xa9,0x7a,0x7e,0x6a,
3608 0x8e,0x50,0x4d,0x25,0x57,0xa1,0xbf,0x1b,0x15,0x05,0x43,0x7b,0x2c,0x05,0x8d,
3609 0xbd,0x3d,0x03,0x8c,0x93,0x22,0x7d,0x63,0xea,0x0a,0x57,0x05,0x06,0x0a,0xdb,
3610 0x61,0x98,0x65,0x2d,0x47,0x49,0xa8,0xe7,0xe6,0x56,0x75,0x5c,0xb8,0x64,0x08,
3611 0x63,0xa9,0x30,0x40,0x66,0xb2,0xf9,0xb6,0xe3,0x34,0xe8,0x67,0x30,0xe1,0x43,
3612 0x0b,0x87,0xff,0xc9,0xbe,0x72,0x10,0x5e,0x23,0xf0,0x9b,0xa7,0x48,0x65,0xbf,
3613 0x09,0x88,0x7b,0xcd,0x72,0xbc,0x2e,0x79,0x9b,0x7b,0x02,0x03,0x01,0x00,0x01 };
3614 static BYTE msPubKey2[] = {
3615 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xa9,0x02,0xbd,0xc1,0x70,0xe6,
3616 0x3b,0xf2,0x4e,0x1b,0x28,0x9f,0x97,0x78,0x5e,0x30,0xea,0xa2,0xa9,0x8d,0x25,
3617 0x5f,0xf8,0xfe,0x95,0x4c,0xa3,0xb7,0xfe,0x9d,0xa2,0x20,0x3e,0x7c,0x51,0xa2,
3618 0x9b,0xa2,0x8f,0x60,0x32,0x6b,0xd1,0x42,0x64,0x79,0xee,0xac,0x76,0xc9,0x54,
3619 0xda,0xf2,0xeb,0x9c,0x86,0x1c,0x8f,0x9f,0x84,0x66,0xb3,0xc5,0x6b,0x7a,0x62,
3620 0x23,0xd6,0x1d,0x3c,0xde,0x0f,0x01,0x92,0xe8,0x96,0xc4,0xbf,0x2d,0x66,0x9a,
3621 0x9a,0x68,0x26,0x99,0xd0,0x3a,0x2c,0xbf,0x0c,0xb5,0x58,0x26,0xc1,0x46,0xe7,
3622 0x0a,0x3e,0x38,0x96,0x2c,0xa9,0x28,0x39,0xa8,0xec,0x49,0x83,0x42,0xe3,0x84,
3623 0x0f,0xbb,0x9a,0x6c,0x55,0x61,0xac,0x82,0x7c,0xa1,0x60,0x2d,0x77,0x4c,0xe9,
3624 0x99,0xb4,0x64,0x3b,0x9a,0x50,0x1c,0x31,0x08,0x24,0x14,0x9f,0xa9,0xe7,0x91,
3625 0x2b,0x18,0xe6,0x3d,0x98,0x63,0x14,0x60,0x58,0x05,0x65,0x9f,0x1d,0x37,0x52,
3626 0x87,0xf7,0xa7,0xef,0x94,0x02,0xc6,0x1b,0xd3,0xbf,0x55,0x45,0xb3,0x89,0x80,
3627 0xbf,0x3a,0xec,0x54,0x94,0x4e,0xae,0xfd,0xa7,0x7a,0x6d,0x74,0x4e,0xaf,0x18,
3628 0xcc,0x96,0x09,0x28,0x21,0x00,0x57,0x90,0x60,0x69,0x37,0xbb,0x4b,0x12,0x07,
3629 0x3c,0x56,0xff,0x5b,0xfb,0xa4,0x66,0x0a,0x08,0xa6,0xd2,0x81,0x56,0x57,0xef,
3630 0xb6,0x3b,0x5e,0x16,0x81,0x77,0x04,0xda,0xf6,0xbe,0xae,0x80,0x95,0xfe,0xb0,
3631 0xcd,0x7f,0xd6,0xa7,0x1a,0x72,0x5c,0x3c,0xca,0xbc,0xf0,0x08,0xa3,0x22,0x30,
3632 0xb3,0x06,0x85,0xc9,0xb3,0x20,0x77,0x13,0x85,0xdf,0x02,0x03,0x01,0x00,0x01 };
3633 static BYTE msPubKey3[] = {
3634 0x30,0x82,0x02,0x0a,0x02,0x82,0x02,0x01,0x00,0xf3,0x5d,0xfa,0x80,0x67,0xd4,
3635 0x5a,0xa7,0xa9,0x0c,0x2c,0x90,0x20,0xd0,0x35,0x08,0x3c,0x75,0x84,0xcd,0xb7,
3636 0x07,0x89,0x9c,0x89,0xda,0xde,0xce,0xc3,0x60,0xfa,0x91,0x68,0x5a,0x9e,0x94,
3637 0x71,0x29,0x18,0x76,0x7c,0xc2,0xe0,0xc8,0x25,0x76,0x94,0x0e,0x58,0xfa,0x04,
3638 0x34,0x36,0xe6,0xdf,0xaf,0xf7,0x80,0xba,0xe9,0x58,0x0b,0x2b,0x93,0xe5,0x9d,
3639 0x05,0xe3,0x77,0x22,0x91,0xf7,0x34,0x64,0x3c,0x22,0x91,0x1d,0x5e,0xe1,0x09,
3640 0x90,0xbc,0x14,0xfe,0xfc,0x75,0x58,0x19,0xe1,0x79,0xb7,0x07,0x92,0xa3,0xae,
3641 0x88,0x59,0x08,0xd8,0x9f,0x07,0xca,0x03,0x58,0xfc,0x68,0x29,0x6d,0x32,0xd7,
3642 0xd2,0xa8,0xcb,0x4b,0xfc,0xe1,0x0b,0x48,0x32,0x4f,0xe6,0xeb,0xb8,0xad,0x4f,
3643 0xe4,0x5c,0x6f,0x13,0x94,0x99,0xdb,0x95,0xd5,0x75,0xdb,0xa8,0x1a,0xb7,0x94,
3644 0x91,0xb4,0x77,0x5b,0xf5,0x48,0x0c,0x8f,0x6a,0x79,0x7d,0x14,0x70,0x04,0x7d,
3645 0x6d,0xaf,0x90,0xf5,0xda,0x70,0xd8,0x47,0xb7,0xbf,0x9b,0x2f,0x6c,0xe7,0x05,
3646 0xb7,0xe1,0x11,0x60,0xac,0x79,0x91,0x14,0x7c,0xc5,0xd6,0xa6,0xe4,0xe1,0x7e,
3647 0xd5,0xc3,0x7e,0xe5,0x92,0xd2,0x3c,0x00,0xb5,0x36,0x82,0xde,0x79,0xe1,0x6d,
3648 0xf3,0xb5,0x6e,0xf8,0x9f,0x33,0xc9,0xcb,0x52,0x7d,0x73,0x98,0x36,0xdb,0x8b,
3649 0xa1,0x6b,0xa2,0x95,0x97,0x9b,0xa3,0xde,0xc2,0x4d,0x26,0xff,0x06,0x96,0x67,
3650 0x25,0x06,0xc8,0xe7,0xac,0xe4,0xee,0x12,0x33,0x95,0x31,0x99,0xc8,0x35,0x08,
3651 0x4e,0x34,0xca,0x79,0x53,0xd5,0xb5,0xbe,0x63,0x32,0x59,0x40,0x36,0xc0,0xa5,
3652 0x4e,0x04,0x4d,0x3d,0xdb,0x5b,0x07,0x33,0xe4,0x58,0xbf,0xef,0x3f,0x53,0x64,
3653 0xd8,0x42,0x59,0x35,0x57,0xfd,0x0f,0x45,0x7c,0x24,0x04,0x4d,0x9e,0xd6,0x38,
3654 0x74,0x11,0x97,0x22,0x90,0xce,0x68,0x44,0x74,0x92,0x6f,0xd5,0x4b,0x6f,0xb0,
3655 0x86,0xe3,0xc7,0x36,0x42,0xa0,0xd0,0xfc,0xc1,0xc0,0x5a,0xf9,0xa3,0x61,0xb9,
3656 0x30,0x47,0x71,0x96,0x0a,0x16,0xb0,0x91,0xc0,0x42,0x95,0xef,0x10,0x7f,0x28,
3657 0x6a,0xe3,0x2a,0x1f,0xb1,0xe4,0xcd,0x03,0x3f,0x77,0x71,0x04,0xc7,0x20,0xfc,
3658 0x49,0x0f,0x1d,0x45,0x88,0xa4,0xd7,0xcb,0x7e,0x88,0xad,0x8e,0x2d,0xec,0x45,
3659 0xdb,0xc4,0x51,0x04,0xc9,0x2a,0xfc,0xec,0x86,0x9e,0x9a,0x11,0x97,0x5b,0xde,
3660 0xce,0x53,0x88,0xe6,0xe2,0xb7,0xfd,0xac,0x95,0xc2,0x28,0x40,0xdb,0xef,0x04,
3661 0x90,0xdf,0x81,0x33,0x39,0xd9,0xb2,0x45,0xa5,0x23,0x87,0x06,0xa5,0x55,0x89,
3662 0x31,0xbb,0x06,0x2d,0x60,0x0e,0x41,0x18,0x7d,0x1f,0x2e,0xb5,0x97,0xcb,0x11,
3663 0xeb,0x15,0xd5,0x24,0xa5,0x94,0xef,0x15,0x14,0x89,0xfd,0x4b,0x73,0xfa,0x32,
3664 0x5b,0xfc,0xd1,0x33,0x00,0xf9,0x59,0x62,0x70,0x07,0x32,0xea,0x2e,0xab,0x40,
3665 0x2d,0x7b,0xca,0xdd,0x21,0x67,0x1b,0x30,0x99,0x8f,0x16,0xaa,0x23,0xa8,0x41,
3666 0xd1,0xb0,0x6e,0x11,0x9b,0x36,0xc4,0xde,0x40,0x74,0x9c,0xe1,0x58,0x65,0xc1,
3667 0x60,0x1e,0x7a,0x5b,0x38,0xc8,0x8f,0xbb,0x04,0x26,0x7c,0xd4,0x16,0x40,0xe5,
3668 0xb6,0x6b,0x6c,0xaa,0x86,0xfd,0x00,0xbf,0xce,0xc1,0x35,0x02,0x03,0x01,0x00,
3669 0x01 };
3671 static BOOL WINAPI verify_ms_root_policy(LPCSTR szPolicyOID,
3672 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3673 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
3675 BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
3676 pPolicyStatus);
3678 if (ret && !pPolicyStatus->dwError)
3680 CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
3681 BOOL isMSRoot = FALSE;
3682 DWORD i;
3683 CRYPT_DATA_BLOB keyBlobs[] = {
3684 { sizeof(msPubKey1), msPubKey1 },
3685 { sizeof(msPubKey2), msPubKey2 },
3686 { sizeof(msPubKey3), msPubKey3 },
3688 PCERT_SIMPLE_CHAIN rootChain =
3689 pChainContext->rgpChain[pChainContext->cChain -1 ];
3690 PCCERT_CONTEXT root =
3691 rootChain->rgpElement[rootChain->cElement - 1]->pCertContext;
3693 for (i = 0; !isMSRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
3694 i++)
3696 msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
3697 msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
3698 if (CertComparePublicKeyInfo(
3699 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
3700 &root->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
3701 isMSRoot = TRUE;
3703 if (isMSRoot)
3704 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = 0;
3706 return ret;
3709 typedef BOOL (WINAPI *CertVerifyCertificateChainPolicyFunc)(LPCSTR szPolicyOID,
3710 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3711 PCERT_CHAIN_POLICY_STATUS pPolicyStatus);
3713 static void dump_policy_para(PCERT_CHAIN_POLICY_PARA para)
3715 if (para)
3717 TRACE_(chain)("cbSize = %d\n", para->cbSize);
3718 TRACE_(chain)("dwFlags = %08x\n", para->dwFlags);
3719 TRACE_(chain)("pvExtraPolicyPara = %p\n", para->pvExtraPolicyPara);
3723 BOOL WINAPI CertVerifyCertificateChainPolicy(LPCSTR szPolicyOID,
3724 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3725 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
3727 static HCRYPTOIDFUNCSET set = NULL;
3728 BOOL ret = FALSE;
3729 CertVerifyCertificateChainPolicyFunc verifyPolicy = NULL;
3730 HCRYPTOIDFUNCADDR hFunc = NULL;
3732 TRACE("(%s, %p, %p, %p)\n", debugstr_a(szPolicyOID), pChainContext,
3733 pPolicyPara, pPolicyStatus);
3734 if (TRACE_ON(chain))
3735 dump_policy_para(pPolicyPara);
3737 if (IS_INTOID(szPolicyOID))
3739 switch (LOWORD(szPolicyOID))
3741 case LOWORD(CERT_CHAIN_POLICY_BASE):
3742 verifyPolicy = verify_base_policy;
3743 break;
3744 case LOWORD(CERT_CHAIN_POLICY_AUTHENTICODE):
3745 verifyPolicy = verify_authenticode_policy;
3746 break;
3747 case LOWORD(CERT_CHAIN_POLICY_SSL):
3748 verifyPolicy = verify_ssl_policy;
3749 break;
3750 case LOWORD(CERT_CHAIN_POLICY_BASIC_CONSTRAINTS):
3751 verifyPolicy = verify_basic_constraints_policy;
3752 break;
3753 case LOWORD(CERT_CHAIN_POLICY_MICROSOFT_ROOT):
3754 verifyPolicy = verify_ms_root_policy;
3755 break;
3756 default:
3757 FIXME("unimplemented for %d\n", LOWORD(szPolicyOID));
3760 if (!verifyPolicy)
3762 if (!set)
3763 set = CryptInitOIDFunctionSet(
3764 CRYPT_OID_VERIFY_CERTIFICATE_CHAIN_POLICY_FUNC, 0);
3765 CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING, szPolicyOID, 0,
3766 (void **)&verifyPolicy, &hFunc);
3768 if (verifyPolicy)
3769 ret = verifyPolicy(szPolicyOID, pChainContext, pPolicyPara,
3770 pPolicyStatus);
3771 if (hFunc)
3772 CryptFreeOIDFunctionAddress(hFunc, 0);
3773 TRACE("returning %d (%08x)\n", ret, pPolicyStatus->dwError);
3774 return ret;