Create a branch for header work.
[reactos.git] / dll / win32 / crypt32 / chain.c
1 /*
2 * Copyright 2006 Juan Lang
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17 *
18 */
19 #include <stdarg.h>
20 #define NONAMELESSUNION
21 #include "windef.h"
22 #include "winbase.h"
23 #define CERT_CHAIN_PARA_HAS_EXTRA_FIELDS
24 #define CERT_REVOCATION_PARA_HAS_EXTRA_FIELDS
25 #include "wincrypt.h"
26 #include "wine/debug.h"
27 #include "wine/unicode.h"
28 #include "crypt32_private.h"
29
30 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
31 WINE_DECLARE_DEBUG_CHANNEL(chain);
32
33 #define DEFAULT_CYCLE_MODULUS 7
34
35 static HCERTCHAINENGINE CRYPT_defaultChainEngine;
36
37 /* This represents a subset of a certificate chain engine: it doesn't include
38 * the "hOther" store described by MSDN, because I'm not sure how that's used.
39 * It also doesn't include the "hTrust" store, because I don't yet implement
40 * CTLs or complex certificate chains.
41 */
42 typedef struct _CertificateChainEngine
43 {
44 LONG ref;
45 HCERTSTORE hRoot;
46 HCERTSTORE hWorld;
47 DWORD dwFlags;
48 DWORD dwUrlRetrievalTimeout;
49 DWORD MaximumCachedCertificates;
50 DWORD CycleDetectionModulus;
51 } CertificateChainEngine, *PCertificateChainEngine;
52
53 static inline void CRYPT_AddStoresToCollection(HCERTSTORE collection,
54 DWORD cStores, HCERTSTORE *stores)
55 {
56 DWORD i;
57
58 for (i = 0; i < cStores; i++)
59 CertAddStoreToCollection(collection, stores[i], 0, 0);
60 }
61
62 static inline void CRYPT_CloseStores(DWORD cStores, HCERTSTORE *stores)
63 {
64 DWORD i;
65
66 for (i = 0; i < cStores; i++)
67 CertCloseStore(stores[i], 0);
68 }
69
70 static const WCHAR rootW[] = { 'R','o','o','t',0 };
71
72 /* Finds cert in store by comparing the cert's hashes. */
73 static PCCERT_CONTEXT CRYPT_FindCertInStore(HCERTSTORE store,
74 PCCERT_CONTEXT cert)
75 {
76 PCCERT_CONTEXT matching = NULL;
77 BYTE hash[20];
78 DWORD size = sizeof(hash);
79
80 if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID, hash, &size))
81 {
82 CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
83
84 matching = CertFindCertificateInStore(store, cert->dwCertEncodingType,
85 0, CERT_FIND_SHA1_HASH, &blob, NULL);
86 }
87 return matching;
88 }
89
90 static BOOL CRYPT_CheckRestrictedRoot(HCERTSTORE store)
91 {
92 BOOL ret = TRUE;
93
94 if (store)
95 {
96 HCERTSTORE rootStore = CertOpenSystemStoreW(0, rootW);
97 PCCERT_CONTEXT cert = NULL, check;
98
99 do {
100 cert = CertEnumCertificatesInStore(store, cert);
101 if (cert)
102 {
103 if (!(check = CRYPT_FindCertInStore(rootStore, cert)))
104 ret = FALSE;
105 else
106 CertFreeCertificateContext(check);
107 }
108 } while (ret && cert);
109 if (cert)
110 CertFreeCertificateContext(cert);
111 CertCloseStore(rootStore, 0);
112 }
113 return ret;
114 }
115
116 HCERTCHAINENGINE CRYPT_CreateChainEngine(HCERTSTORE root,
117 PCERT_CHAIN_ENGINE_CONFIG pConfig)
118 {
119 static const WCHAR caW[] = { 'C','A',0 };
120 static const WCHAR myW[] = { 'M','y',0 };
121 static const WCHAR trustW[] = { 'T','r','u','s','t',0 };
122 PCertificateChainEngine engine =
123 CryptMemAlloc(sizeof(CertificateChainEngine));
124
125 if (engine)
126 {
127 HCERTSTORE worldStores[4];
128
129 engine->ref = 1;
130 engine->hRoot = root;
131 engine->hWorld = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
132 CERT_STORE_CREATE_NEW_FLAG, NULL);
133 worldStores[0] = CertDuplicateStore(engine->hRoot);
134 worldStores[1] = CertOpenSystemStoreW(0, caW);
135 worldStores[2] = CertOpenSystemStoreW(0, myW);
136 worldStores[3] = CertOpenSystemStoreW(0, trustW);
137 CRYPT_AddStoresToCollection(engine->hWorld,
138 sizeof(worldStores) / sizeof(worldStores[0]), worldStores);
139 CRYPT_AddStoresToCollection(engine->hWorld,
140 pConfig->cAdditionalStore, pConfig->rghAdditionalStore);
141 CRYPT_CloseStores(sizeof(worldStores) / sizeof(worldStores[0]),
142 worldStores);
143 engine->dwFlags = pConfig->dwFlags;
144 engine->dwUrlRetrievalTimeout = pConfig->dwUrlRetrievalTimeout;
145 engine->MaximumCachedCertificates =
146 pConfig->MaximumCachedCertificates;
147 if (pConfig->CycleDetectionModulus)
148 engine->CycleDetectionModulus = pConfig->CycleDetectionModulus;
149 else
150 engine->CycleDetectionModulus = DEFAULT_CYCLE_MODULUS;
151 }
152 return engine;
153 }
154
155 BOOL WINAPI CertCreateCertificateChainEngine(PCERT_CHAIN_ENGINE_CONFIG pConfig,
156 HCERTCHAINENGINE *phChainEngine)
157 {
158 BOOL ret;
159
160 TRACE("(%p, %p)\n", pConfig, phChainEngine);
161
162 if (pConfig->cbSize != sizeof(*pConfig))
163 {
164 SetLastError(E_INVALIDARG);
165 return FALSE;
166 }
167 *phChainEngine = NULL;
168 ret = CRYPT_CheckRestrictedRoot(pConfig->hRestrictedRoot);
169 if (ret)
170 {
171 HCERTSTORE root;
172 HCERTCHAINENGINE engine;
173
174 if (pConfig->hRestrictedRoot)
175 root = CertDuplicateStore(pConfig->hRestrictedRoot);
176 else
177 root = CertOpenSystemStoreW(0, rootW);
178 engine = CRYPT_CreateChainEngine(root, pConfig);
179 if (engine)
180 {
181 *phChainEngine = engine;
182 ret = TRUE;
183 }
184 else
185 ret = FALSE;
186 }
187 return ret;
188 }
189
190 VOID WINAPI CertFreeCertificateChainEngine(HCERTCHAINENGINE hChainEngine)
191 {
192 PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
193
194 TRACE("(%p)\n", hChainEngine);
195
196 if (engine && InterlockedDecrement(&engine->ref) == 0)
197 {
198 CertCloseStore(engine->hWorld, 0);
199 CertCloseStore(engine->hRoot, 0);
200 CryptMemFree(engine);
201 }
202 }
203
204 static HCERTCHAINENGINE CRYPT_GetDefaultChainEngine(void)
205 {
206 if (!CRYPT_defaultChainEngine)
207 {
208 CERT_CHAIN_ENGINE_CONFIG config = { 0 };
209 HCERTCHAINENGINE engine;
210
211 config.cbSize = sizeof(config);
212 CertCreateCertificateChainEngine(&config, &engine);
213 InterlockedCompareExchangePointer(&CRYPT_defaultChainEngine, engine,
214 NULL);
215 if (CRYPT_defaultChainEngine != engine)
216 CertFreeCertificateChainEngine(engine);
217 }
218 return CRYPT_defaultChainEngine;
219 }
220
221 void default_chain_engine_free(void)
222 {
223 CertFreeCertificateChainEngine(CRYPT_defaultChainEngine);
224 }
225
226 typedef struct _CertificateChain
227 {
228 CERT_CHAIN_CONTEXT context;
229 HCERTSTORE world;
230 LONG ref;
231 } CertificateChain, *PCertificateChain;
232
233 static BOOL CRYPT_IsCertificateSelfSigned(PCCERT_CONTEXT cert)
234 {
235 PCERT_EXTENSION ext;
236 DWORD size;
237 BOOL ret;
238
239 if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
240 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension)))
241 {
242 CERT_AUTHORITY_KEY_ID2_INFO *info;
243
244 ret = CryptDecodeObjectEx(cert->dwCertEncodingType,
245 X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
246 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
247 &info, &size);
248 if (ret)
249 {
250 if (info->AuthorityCertIssuer.cAltEntry &&
251 info->AuthorityCertSerialNumber.cbData)
252 {
253 PCERT_ALT_NAME_ENTRY directoryName = NULL;
254 DWORD i;
255
256 for (i = 0; !directoryName &&
257 i < info->AuthorityCertIssuer.cAltEntry; i++)
258 if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
259 == CERT_ALT_NAME_DIRECTORY_NAME)
260 directoryName =
261 &info->AuthorityCertIssuer.rgAltEntry[i];
262 if (directoryName)
263 {
264 ret = CertCompareCertificateName(cert->dwCertEncodingType,
265 &directoryName->u.DirectoryName, &cert->pCertInfo->Issuer)
266 && CertCompareIntegerBlob(&info->AuthorityCertSerialNumber,
267 &cert->pCertInfo->SerialNumber);
268 }
269 else
270 {
271 FIXME("no supported name type in authority key id2\n");
272 ret = FALSE;
273 }
274 }
275 else if (info->KeyId.cbData)
276 {
277 ret = CertGetCertificateContextProperty(cert,
278 CERT_KEY_IDENTIFIER_PROP_ID, NULL, &size);
279 if (ret && size == info->KeyId.cbData)
280 {
281 LPBYTE buf = CryptMemAlloc(size);
282
283 if (buf)
284 {
285 CertGetCertificateContextProperty(cert,
286 CERT_KEY_IDENTIFIER_PROP_ID, buf, &size);
287 ret = !memcmp(buf, info->KeyId.pbData, size);
288 CryptMemFree(buf);
289 }
290 }
291 else
292 ret = FALSE;
293 }
294 LocalFree(info);
295 }
296 }
297 else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
298 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension)))
299 {
300 CERT_AUTHORITY_KEY_ID_INFO *info;
301
302 ret = CryptDecodeObjectEx(cert->dwCertEncodingType,
303 X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
304 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
305 &info, &size);
306 if (ret)
307 {
308 if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
309 {
310 ret = CertCompareCertificateName(cert->dwCertEncodingType,
311 &info->CertIssuer, &cert->pCertInfo->Issuer) &&
312 CertCompareIntegerBlob(&info->CertSerialNumber,
313 &cert->pCertInfo->SerialNumber);
314 }
315 else if (info->KeyId.cbData)
316 {
317 ret = CertGetCertificateContextProperty(cert,
318 CERT_KEY_IDENTIFIER_PROP_ID, NULL, &size);
319 if (ret && size == info->KeyId.cbData)
320 {
321 LPBYTE buf = CryptMemAlloc(size);
322
323 if (buf)
324 {
325 CertGetCertificateContextProperty(cert,
326 CERT_KEY_IDENTIFIER_PROP_ID, buf, &size);
327 ret = !memcmp(buf, info->KeyId.pbData, size);
328 CryptMemFree(buf);
329 }
330 else
331 ret = FALSE;
332 }
333 else
334 ret = FALSE;
335 }
336 else
337 ret = FALSE;
338 LocalFree(info);
339 }
340 }
341 else
342 ret = CertCompareCertificateName(cert->dwCertEncodingType,
343 &cert->pCertInfo->Subject, &cert->pCertInfo->Issuer);
344 return ret;
345 }
346
347 static void CRYPT_FreeChainElement(PCERT_CHAIN_ELEMENT element)
348 {
349 CertFreeCertificateContext(element->pCertContext);
350 CryptMemFree(element);
351 }
352
353 static void CRYPT_CheckSimpleChainForCycles(PCERT_SIMPLE_CHAIN chain)
354 {
355 DWORD i, j, cyclicCertIndex = 0;
356
357 /* O(n^2) - I don't think there's a faster way */
358 for (i = 0; !cyclicCertIndex && i < chain->cElement; i++)
359 for (j = i + 1; !cyclicCertIndex && j < chain->cElement; j++)
360 if (CertCompareCertificate(X509_ASN_ENCODING,
361 chain->rgpElement[i]->pCertContext->pCertInfo,
362 chain->rgpElement[j]->pCertContext->pCertInfo))
363 cyclicCertIndex = j;
364 if (cyclicCertIndex)
365 {
366 chain->rgpElement[cyclicCertIndex]->TrustStatus.dwErrorStatus
367 |= CERT_TRUST_IS_CYCLIC | CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
368 /* Release remaining certs */
369 for (i = cyclicCertIndex + 1; i < chain->cElement; i++)
370 CRYPT_FreeChainElement(chain->rgpElement[i]);
371 /* Truncate chain */
372 chain->cElement = cyclicCertIndex + 1;
373 }
374 }
375
376 /* Checks whether the chain is cyclic by examining the last element's status */
377 static inline BOOL CRYPT_IsSimpleChainCyclic(const CERT_SIMPLE_CHAIN *chain)
378 {
379 if (chain->cElement)
380 return chain->rgpElement[chain->cElement - 1]->TrustStatus.dwErrorStatus
381 & CERT_TRUST_IS_CYCLIC;
382 else
383 return FALSE;
384 }
385
386 static inline void CRYPT_CombineTrustStatus(CERT_TRUST_STATUS *chainStatus,
387 const CERT_TRUST_STATUS *elementStatus)
388 {
389 /* Any error that applies to an element also applies to a chain.. */
390 chainStatus->dwErrorStatus |= elementStatus->dwErrorStatus;
391 /* but the bottom nibble of an element's info status doesn't apply to the
392 * chain.
393 */
394 chainStatus->dwInfoStatus |= (elementStatus->dwInfoStatus & 0xfffffff0);
395 }
396
397 static BOOL CRYPT_AddCertToSimpleChain(const CertificateChainEngine *engine,
398 PCERT_SIMPLE_CHAIN chain, PCCERT_CONTEXT cert, DWORD subjectInfoStatus)
399 {
400 BOOL ret = FALSE;
401 PCERT_CHAIN_ELEMENT element = CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
402
403 if (element)
404 {
405 if (!chain->cElement)
406 chain->rgpElement = CryptMemAlloc(sizeof(PCERT_CHAIN_ELEMENT));
407 else
408 chain->rgpElement = CryptMemRealloc(chain->rgpElement,
409 (chain->cElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
410 if (chain->rgpElement)
411 {
412 chain->rgpElement[chain->cElement++] = element;
413 memset(element, 0, sizeof(CERT_CHAIN_ELEMENT));
414 element->cbSize = sizeof(CERT_CHAIN_ELEMENT);
415 element->pCertContext = CertDuplicateCertificateContext(cert);
416 if (chain->cElement > 1)
417 chain->rgpElement[chain->cElement - 2]->TrustStatus.dwInfoStatus
418 = subjectInfoStatus;
419 /* FIXME: initialize the rest of element */
420 if (!(chain->cElement % engine->CycleDetectionModulus))
421 {
422 CRYPT_CheckSimpleChainForCycles(chain);
423 /* Reinitialize the element pointer in case the chain is
424 * cyclic, in which case the chain is truncated.
425 */
426 element = chain->rgpElement[chain->cElement - 1];
427 }
428 CRYPT_CombineTrustStatus(&chain->TrustStatus,
429 &element->TrustStatus);
430 ret = TRUE;
431 }
432 else
433 CryptMemFree(element);
434 }
435 return ret;
436 }
437
438 static void CRYPT_FreeSimpleChain(PCERT_SIMPLE_CHAIN chain)
439 {
440 DWORD i;
441
442 for (i = 0; i < chain->cElement; i++)
443 CRYPT_FreeChainElement(chain->rgpElement[i]);
444 CryptMemFree(chain->rgpElement);
445 CryptMemFree(chain);
446 }
447
448 static void CRYPT_CheckTrustedStatus(HCERTSTORE hRoot,
449 PCERT_CHAIN_ELEMENT rootElement)
450 {
451 PCCERT_CONTEXT trustedRoot = CRYPT_FindCertInStore(hRoot,
452 rootElement->pCertContext);
453
454 if (!trustedRoot)
455 rootElement->TrustStatus.dwErrorStatus |=
456 CERT_TRUST_IS_UNTRUSTED_ROOT;
457 else
458 CertFreeCertificateContext(trustedRoot);
459 }
460
461 static void CRYPT_CheckRootCert(HCERTCHAINENGINE hRoot,
462 PCERT_CHAIN_ELEMENT rootElement)
463 {
464 PCCERT_CONTEXT root = rootElement->pCertContext;
465
466 if (!CryptVerifyCertificateSignatureEx(0, root->dwCertEncodingType,
467 CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, (void *)root,
468 CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, (void *)root, 0, NULL))
469 {
470 TRACE_(chain)("Last certificate's signature is invalid\n");
471 rootElement->TrustStatus.dwErrorStatus |=
472 CERT_TRUST_IS_NOT_SIGNATURE_VALID;
473 }
474 CRYPT_CheckTrustedStatus(hRoot, rootElement);
475 }
476
477 /* Decodes a cert's basic constraints extension (either szOID_BASIC_CONSTRAINTS
478 * or szOID_BASIC_CONSTRAINTS2, whichever is present) into a
479 * CERT_BASIC_CONSTRAINTS2_INFO. If it neither extension is present, sets
480 * constraints->fCA to defaultIfNotSpecified.
481 * Returns FALSE if the extension is present but couldn't be decoded.
482 */
483 static BOOL CRYPT_DecodeBasicConstraints(PCCERT_CONTEXT cert,
484 CERT_BASIC_CONSTRAINTS2_INFO *constraints, BOOL defaultIfNotSpecified)
485 {
486 BOOL ret = TRUE;
487 PCERT_EXTENSION ext = CertFindExtension(szOID_BASIC_CONSTRAINTS,
488 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
489
490 constraints->fPathLenConstraint = FALSE;
491 if (ext)
492 {
493 CERT_BASIC_CONSTRAINTS_INFO *info;
494 DWORD size = 0;
495
496 ret = CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
497 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
498 NULL, &info, &size);
499 if (ret)
500 {
501 if (info->SubjectType.cbData == 1)
502 constraints->fCA =
503 info->SubjectType.pbData[0] & CERT_CA_SUBJECT_FLAG;
504 LocalFree(info);
505 }
506 }
507 else
508 {
509 ext = CertFindExtension(szOID_BASIC_CONSTRAINTS2,
510 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
511 if (ext)
512 {
513 DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
514
515 ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
516 szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
517 0, NULL, constraints, &size);
518 }
519 else
520 constraints->fCA = defaultIfNotSpecified;
521 }
522 return ret;
523 }
524
525 /* Checks element's basic constraints to see if it can act as a CA, with
526 * remainingCAs CAs left in this chain. In general, a cert must include the
527 * basic constraints extension, with the CA flag asserted, in order to be
528 * allowed to be a CA. A V1 or V2 cert, which has no extensions, is also
529 * allowed to be a CA if it's installed locally (in the engine's world store.)
530 * This matches the expected usage in RFC 5280, section 4.2.1.9: a conforming
531 * CA MUST include the basic constraints extension in all certificates that are
532 * used to validate digital signatures on certificates. It also matches
533 * section 6.1.4(k): "If a certificate is a v1 or v2 certificate, then the
534 * application MUST either verify that the certificate is a CA certificate
535 * through out-of-band means or reject the certificate." Rejecting the
536 * certificate prohibits a large number of commonly used certificates, so
537 * accepting locally installed ones is a compromise.
538 * Root certificates are also allowed to be CAs even without a basic
539 * constraints extension. This is implied by RFC 5280, section 6.1: the
540 * root of a certificate chain's only requirement is that it was used to issue
541 * the next certificate in the chain.
542 * Updates chainConstraints with the element's constraints, if:
543 * 1. chainConstraints doesn't have a path length constraint, or
544 * 2. element's path length constraint is smaller than chainConstraints's
545 * Sets *pathLengthConstraintViolated to TRUE if a path length violation
546 * occurs.
547 * Returns TRUE if the element can be a CA, and the length of the remaining
548 * chain is valid.
549 */
550 static BOOL CRYPT_CheckBasicConstraintsForCA(PCertificateChainEngine engine,
551 PCCERT_CONTEXT cert, CERT_BASIC_CONSTRAINTS2_INFO *chainConstraints,
552 DWORD remainingCAs, BOOL isRoot, BOOL *pathLengthConstraintViolated)
553 {
554 BOOL validBasicConstraints, implicitCA = FALSE;
555 CERT_BASIC_CONSTRAINTS2_INFO constraints;
556
557 if (isRoot)
558 implicitCA = TRUE;
559 else if (cert->pCertInfo->dwVersion == CERT_V1 ||
560 cert->pCertInfo->dwVersion == CERT_V2)
561 {
562 BYTE hash[20];
563 DWORD size = sizeof(hash);
564
565 if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID,
566 hash, &size))
567 {
568 CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
569 PCCERT_CONTEXT localCert = CertFindCertificateInStore(
570 engine->hWorld, cert->dwCertEncodingType, 0, CERT_FIND_SHA1_HASH,
571 &blob, NULL);
572
573 if (localCert)
574 {
575 CertFreeCertificateContext(localCert);
576 implicitCA = TRUE;
577 }
578 }
579 }
580 if ((validBasicConstraints = CRYPT_DecodeBasicConstraints(cert,
581 &constraints, implicitCA)))
582 {
583 chainConstraints->fCA = constraints.fCA;
584 if (!constraints.fCA)
585 {
586 TRACE_(chain)("chain element %d can't be a CA\n", remainingCAs + 1);
587 validBasicConstraints = FALSE;
588 }
589 else if (constraints.fPathLenConstraint)
590 {
591 /* If the element has path length constraints, they apply to the
592 * entire remaining chain.
593 */
594 if (!chainConstraints->fPathLenConstraint ||
595 constraints.dwPathLenConstraint <
596 chainConstraints->dwPathLenConstraint)
597 {
598 TRACE_(chain)("setting path length constraint to %d\n",
599 chainConstraints->dwPathLenConstraint);
600 chainConstraints->fPathLenConstraint = TRUE;
601 chainConstraints->dwPathLenConstraint =
602 constraints.dwPathLenConstraint;
603 }
604 }
605 }
606 if (chainConstraints->fPathLenConstraint &&
607 remainingCAs > chainConstraints->dwPathLenConstraint)
608 {
609 TRACE_(chain)("remaining CAs %d exceed max path length %d\n",
610 remainingCAs, chainConstraints->dwPathLenConstraint);
611 validBasicConstraints = FALSE;
612 *pathLengthConstraintViolated = TRUE;
613 }
614 return validBasicConstraints;
615 }
616
617 static BOOL domain_name_matches(LPCWSTR constraint, LPCWSTR name)
618 {
619 BOOL match;
620
621 /* RFC 5280, section 4.2.1.10:
622 * "For URIs, the constraint applies to the host part of the name...
623 * When the constraint begins with a period, it MAY be expanded with one
624 * or more labels. That is, the constraint ".example.com" is satisfied by
625 * both host.example.com and my.host.example.com. However, the constraint
626 * ".example.com" is not satisfied by "example.com". When the constraint
627 * does not begin with a period, it specifies a host."
628 * and for email addresses,
629 * "To indicate all Internet mail addresses on a particular host, the
630 * constraint is specified as the host name. For example, the constraint
631 * "example.com" is satisfied by any mail address at the host
632 * "example.com". To specify any address within a domain, the constraint
633 * is specified with a leading period (as with URIs)."
634 */
635 if (constraint[0] == '.')
636 {
637 /* Must be strictly greater than, a name can't begin with '.' */
638 if (lstrlenW(name) > lstrlenW(constraint))
639 match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
640 constraint);
641 else
642 {
643 /* name is too short, no match */
644 match = FALSE;
645 }
646 }
647 else
648 match = !lstrcmpiW(name, constraint);
649 return match;
650 }
651
652 static BOOL url_matches(LPCWSTR constraint, LPCWSTR name,
653 DWORD *trustErrorStatus)
654 {
655 BOOL match = FALSE;
656
657 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
658
659 if (!constraint)
660 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
661 else if (!name)
662 ; /* no match */
663 else
664 {
665 LPCWSTR colon, authority_end, at, hostname = NULL;
666 /* The maximum length for a hostname is 254 in the DNS, see RFC 1034 */
667 WCHAR hostname_buf[255];
668
669 /* RFC 5280: only the hostname portion of the URL is compared. From
670 * section 4.2.1.10:
671 * "For URIs, the constraint applies to the host part of the name.
672 * The constraint MUST be specified as a fully qualified domain name
673 * and MAY specify a host or a domain."
674 * The format for URIs is in RFC 2396.
675 *
676 * First, remove any scheme that's present. */
677 colon = strchrW(name, ':');
678 if (colon && *(colon + 1) == '/' && *(colon + 2) == '/')
679 name = colon + 3;
680 /* Next, find the end of the authority component. (The authority is
681 * generally just the hostname, but it may contain a username or a port.
682 * Those are removed next.)
683 */
684 authority_end = strchrW(name, '/');
685 if (!authority_end)
686 authority_end = strchrW(name, '?');
687 if (!authority_end)
688 authority_end = name + strlenW(name);
689 /* Remove any port number from the authority */
690 for (colon = authority_end; colon >= name && *colon != ':'; colon--)
691 ;
692 if (*colon == ':')
693 authority_end = colon;
694 /* Remove any username from the authority */
695 if ((at = strchrW(name, '@')))
696 name = at;
697 /* Ignore any path or query portion of the URL. */
698 if (*authority_end)
699 {
700 if (authority_end - name < sizeof(hostname_buf) /
701 sizeof(hostname_buf[0]))
702 {
703 memcpy(hostname_buf, name,
704 (authority_end - name) * sizeof(WCHAR));
705 hostname_buf[authority_end - name] = 0;
706 hostname = hostname_buf;
707 }
708 /* else: Hostname is too long, not a match */
709 }
710 else
711 hostname = name;
712 if (hostname)
713 match = domain_name_matches(constraint, hostname);
714 }
715 return match;
716 }
717
718 static BOOL rfc822_name_matches(LPCWSTR constraint, LPCWSTR name,
719 DWORD *trustErrorStatus)
720 {
721 BOOL match = FALSE;
722 LPCWSTR at;
723
724 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
725
726 if (!constraint)
727 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
728 else if (!name)
729 ; /* no match */
730 else if (strchrW(constraint, '@'))
731 match = !lstrcmpiW(constraint, name);
732 else
733 {
734 if ((at = strchrW(name, '@')))
735 match = domain_name_matches(constraint, at + 1);
736 else
737 match = !lstrcmpiW(constraint, name);
738 }
739 return match;
740 }
741
742 static BOOL dns_name_matches(LPCWSTR constraint, LPCWSTR name,
743 DWORD *trustErrorStatus)
744 {
745 BOOL match = FALSE;
746
747 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
748
749 if (!constraint)
750 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
751 else if (!name)
752 ; /* no match */
753 /* RFC 5280, section 4.2.1.10:
754 * "DNS name restrictions are expressed as host.example.com. Any DNS name
755 * that can be constructed by simply adding zero or more labels to the
756 * left-hand side of the name satisfies the name constraint. For example,
757 * www.host.example.com would satisfy the constraint but host1.example.com
758 * would not."
759 */
760 else if (lstrlenW(name) == lstrlenW(constraint))
761 match = !lstrcmpiW(name, constraint);
762 else if (lstrlenW(name) > lstrlenW(constraint))
763 {
764 match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
765 constraint);
766 if (match)
767 {
768 BOOL dot = FALSE;
769 LPCWSTR ptr;
770
771 /* This only matches if name is a subdomain of constraint, i.e.
772 * there's a '.' between the beginning of the name and the
773 * matching portion of the name.
774 */
775 for (ptr = name + lstrlenW(name) - lstrlenW(constraint);
776 !dot && ptr >= name; ptr--)
777 if (*ptr == '.')
778 dot = TRUE;
779 match = dot;
780 }
781 }
782 /* else: name is too short, no match */
783
784 return match;
785 }
786
787 static BOOL ip_address_matches(const CRYPT_DATA_BLOB *constraint,
788 const CRYPT_DATA_BLOB *name, DWORD *trustErrorStatus)
789 {
790 BOOL match = FALSE;
791
792 TRACE("(%d, %p), (%d, %p)\n", constraint->cbData, constraint->pbData,
793 name->cbData, name->pbData);
794
795 /* RFC5280, section 4.2.1.10, iPAddress syntax: either 8 or 32 bytes, for
796 * IPv4 or IPv6 addresses, respectively.
797 */
798 if (constraint->cbData != sizeof(DWORD) * 2 && constraint->cbData != 32)
799 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
800 else if (name->cbData == sizeof(DWORD) &&
801 constraint->cbData == sizeof(DWORD) * 2)
802 {
803 DWORD subnet, mask, addr;
804
805 memcpy(&subnet, constraint->pbData, sizeof(subnet));
806 memcpy(&mask, constraint->pbData + sizeof(subnet), sizeof(mask));
807 memcpy(&addr, name->pbData, sizeof(addr));
808 /* These are really in big-endian order, but for equality matching we
809 * don't need to swap to host order
810 */
811 match = (subnet & mask) == (addr & mask);
812 }
813 else if (name->cbData == 16 && constraint->cbData == 32)
814 {
815 const BYTE *subnet, *mask, *addr;
816 DWORD i;
817
818 subnet = constraint->pbData;
819 mask = constraint->pbData + 16;
820 addr = name->pbData;
821 match = TRUE;
822 for (i = 0; match && i < 16; i++)
823 if ((subnet[i] & mask[i]) != (addr[i] & mask[i]))
824 match = FALSE;
825 }
826 /* else: name is wrong size, no match */
827
828 return match;
829 }
830
831 static BOOL directory_name_matches(const CERT_NAME_BLOB *constraint,
832 const CERT_NAME_BLOB *name)
833 {
834 CERT_NAME_INFO *constraintName;
835 DWORD size;
836 BOOL match = FALSE;
837
838 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME, constraint->pbData,
839 constraint->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &constraintName, &size))
840 {
841 DWORD i;
842
843 match = TRUE;
844 for (i = 0; match && i < constraintName->cRDN; i++)
845 match = CertIsRDNAttrsInCertificateName(X509_ASN_ENCODING,
846 CERT_CASE_INSENSITIVE_IS_RDN_ATTRS_FLAG,
847 (CERT_NAME_BLOB *)name, &constraintName->rgRDN[i]);
848 LocalFree(constraintName);
849 }
850 return match;
851 }
852
853 static BOOL alt_name_matches(const CERT_ALT_NAME_ENTRY *name,
854 const CERT_ALT_NAME_ENTRY *constraint, DWORD *trustErrorStatus, BOOL *present)
855 {
856 BOOL match = FALSE;
857
858 if (name->dwAltNameChoice == constraint->dwAltNameChoice)
859 {
860 if (present)
861 *present = TRUE;
862 switch (constraint->dwAltNameChoice)
863 {
864 case CERT_ALT_NAME_RFC822_NAME:
865 match = rfc822_name_matches(constraint->u.pwszURL,
866 name->u.pwszURL, trustErrorStatus);
867 break;
868 case CERT_ALT_NAME_DNS_NAME:
869 match = dns_name_matches(constraint->u.pwszURL,
870 name->u.pwszURL, trustErrorStatus);
871 break;
872 case CERT_ALT_NAME_URL:
873 match = url_matches(constraint->u.pwszURL,
874 name->u.pwszURL, trustErrorStatus);
875 break;
876 case CERT_ALT_NAME_IP_ADDRESS:
877 match = ip_address_matches(&constraint->u.IPAddress,
878 &name->u.IPAddress, trustErrorStatus);
879 break;
880 case CERT_ALT_NAME_DIRECTORY_NAME:
881 match = directory_name_matches(&constraint->u.DirectoryName,
882 &name->u.DirectoryName);
883 break;
884 default:
885 ERR("name choice %d unsupported in this context\n",
886 constraint->dwAltNameChoice);
887 *trustErrorStatus |=
888 CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
889 }
890 }
891 else if (present)
892 *present = FALSE;
893 return match;
894 }
895
896 static BOOL alt_name_matches_excluded_name(const CERT_ALT_NAME_ENTRY *name,
897 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
898 {
899 DWORD i;
900 BOOL match = FALSE;
901
902 for (i = 0; !match && i < nameConstraints->cExcludedSubtree; i++)
903 match = alt_name_matches(name,
904 &nameConstraints->rgExcludedSubtree[i].Base, trustErrorStatus, NULL);
905 return match;
906 }
907
908 static BOOL alt_name_matches_permitted_name(const CERT_ALT_NAME_ENTRY *name,
909 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus,
910 BOOL *present)
911 {
912 DWORD i;
913 BOOL match = FALSE;
914
915 for (i = 0; !match && i < nameConstraints->cPermittedSubtree; i++)
916 match = alt_name_matches(name,
917 &nameConstraints->rgPermittedSubtree[i].Base, trustErrorStatus,
918 present);
919 return match;
920 }
921
922 static inline PCERT_EXTENSION get_subject_alt_name_ext(const CERT_INFO *cert)
923 {
924 PCERT_EXTENSION ext;
925
926 ext = CertFindExtension(szOID_SUBJECT_ALT_NAME2,
927 cert->cExtension, cert->rgExtension);
928 if (!ext)
929 ext = CertFindExtension(szOID_SUBJECT_ALT_NAME,
930 cert->cExtension, cert->rgExtension);
931 return ext;
932 }
933
934 static void compare_alt_name_with_constraints(const CERT_EXTENSION *altNameExt,
935 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
936 {
937 CERT_ALT_NAME_INFO *subjectAltName;
938 DWORD size;
939
940 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
941 altNameExt->Value.pbData, altNameExt->Value.cbData,
942 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
943 &subjectAltName, &size))
944 {
945 DWORD i;
946
947 for (i = 0; i < subjectAltName->cAltEntry; i++)
948 {
949 BOOL nameFormPresent;
950
951 /* A name constraint only applies if the name form is present.
952 * From RFC 5280, section 4.2.1.10:
953 * "Restrictions apply only when the specified name form is
954 * present. If no name of the type is in the certificate,
955 * the certificate is acceptable."
956 */
957 if (alt_name_matches_excluded_name(
958 &subjectAltName->rgAltEntry[i], nameConstraints,
959 trustErrorStatus))
960 {
961 TRACE_(chain)("subject alternate name form %d excluded\n",
962 subjectAltName->rgAltEntry[i].dwAltNameChoice);
963 *trustErrorStatus |=
964 CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
965 }
966 nameFormPresent = FALSE;
967 if (!alt_name_matches_permitted_name(
968 &subjectAltName->rgAltEntry[i], nameConstraints,
969 trustErrorStatus, &nameFormPresent) && nameFormPresent)
970 {
971 TRACE_(chain)("subject alternate name form %d not permitted\n",
972 subjectAltName->rgAltEntry[i].dwAltNameChoice);
973 *trustErrorStatus |=
974 CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
975 }
976 }
977 LocalFree(subjectAltName);
978 }
979 else
980 *trustErrorStatus |=
981 CERT_TRUST_INVALID_EXTENSION | CERT_TRUST_INVALID_NAME_CONSTRAINTS;
982 }
983
984 static BOOL rfc822_attr_matches_excluded_name(const CERT_RDN_ATTR *attr,
985 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
986 {
987 DWORD i;
988 BOOL match = FALSE;
989
990 for (i = 0; !match && i < nameConstraints->cExcludedSubtree; i++)
991 {
992 const CERT_ALT_NAME_ENTRY *constraint =
993 &nameConstraints->rgExcludedSubtree[i].Base;
994
995 if (constraint->dwAltNameChoice == CERT_ALT_NAME_RFC822_NAME)
996 match = rfc822_name_matches(constraint->u.pwszRfc822Name,
997 (LPCWSTR)attr->Value.pbData, trustErrorStatus);
998 }
999 return match;
1000 }
1001
1002 static BOOL rfc822_attr_matches_permitted_name(const CERT_RDN_ATTR *attr,
1003 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus,
1004 BOOL *present)
1005 {
1006 DWORD i;
1007 BOOL match = FALSE;
1008
1009 for (i = 0; !match && i < nameConstraints->cPermittedSubtree; i++)
1010 {
1011 const CERT_ALT_NAME_ENTRY *constraint =
1012 &nameConstraints->rgPermittedSubtree[i].Base;
1013
1014 if (constraint->dwAltNameChoice == CERT_ALT_NAME_RFC822_NAME)
1015 {
1016 *present = TRUE;
1017 match = rfc822_name_matches(constraint->u.pwszRfc822Name,
1018 (LPCWSTR)attr->Value.pbData, trustErrorStatus);
1019 }
1020 }
1021 return match;
1022 }
1023
1024 static void compare_subject_with_email_constraints(
1025 const CERT_NAME_BLOB *subjectName,
1026 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
1027 {
1028 CERT_NAME_INFO *name;
1029 DWORD size;
1030
1031 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_UNICODE_NAME,
1032 subjectName->pbData, subjectName->cbData,
1033 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &name, &size))
1034 {
1035 DWORD i, j;
1036
1037 for (i = 0; i < name->cRDN; i++)
1038 for (j = 0; j < name->rgRDN[i].cRDNAttr; j++)
1039 if (!strcmp(name->rgRDN[i].rgRDNAttr[j].pszObjId,
1040 szOID_RSA_emailAddr))
1041 {
1042 BOOL nameFormPresent;
1043
1044 /* A name constraint only applies if the name form is
1045 * present. From RFC 5280, section 4.2.1.10:
1046 * "Restrictions apply only when the specified name form is
1047 * present. If no name of the type is in the certificate,
1048 * the certificate is acceptable."
1049 */
1050 if (rfc822_attr_matches_excluded_name(
1051 &name->rgRDN[i].rgRDNAttr[j], nameConstraints,
1052 trustErrorStatus))
1053 {
1054 TRACE_(chain)(
1055 "email address in subject name is excluded\n");
1056 *trustErrorStatus |=
1057 CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
1058 }
1059 nameFormPresent = FALSE;
1060 if (!rfc822_attr_matches_permitted_name(
1061 &name->rgRDN[i].rgRDNAttr[j], nameConstraints,
1062 trustErrorStatus, &nameFormPresent) && nameFormPresent)
1063 {
1064 TRACE_(chain)(
1065 "email address in subject name is not permitted\n");
1066 *trustErrorStatus |=
1067 CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
1068 }
1069 }
1070 LocalFree(name);
1071 }
1072 else
1073 *trustErrorStatus |=
1074 CERT_TRUST_INVALID_EXTENSION | CERT_TRUST_INVALID_NAME_CONSTRAINTS;
1075 }
1076
1077 static BOOL CRYPT_IsEmptyName(const CERT_NAME_BLOB *name)
1078 {
1079 BOOL empty;
1080
1081 if (!name->cbData)
1082 empty = TRUE;
1083 else if (name->cbData == 2 && name->pbData[1] == 0)
1084 {
1085 /* An empty sequence is also empty */
1086 empty = TRUE;
1087 }
1088 else
1089 empty = FALSE;
1090 return empty;
1091 }
1092
1093 static void compare_subject_with_constraints(const CERT_NAME_BLOB *subjectName,
1094 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, DWORD *trustErrorStatus)
1095 {
1096 BOOL hasEmailConstraint = FALSE;
1097 DWORD i;
1098
1099 /* In general, a subject distinguished name only matches a directory name
1100 * constraint. However, an exception exists for email addresses.
1101 * From RFC 5280, section 4.2.1.6:
1102 * "Legacy implementations exist where an electronic mail address is
1103 * embedded in the subject distinguished name as an emailAddress
1104 * attribute [RFC2985]."
1105 * If an email address constraint exists, check that constraint separately.
1106 */
1107 for (i = 0; !hasEmailConstraint && i < nameConstraints->cExcludedSubtree;
1108 i++)
1109 if (nameConstraints->rgExcludedSubtree[i].Base.dwAltNameChoice ==
1110 CERT_ALT_NAME_RFC822_NAME)
1111 hasEmailConstraint = TRUE;
1112 for (i = 0; !hasEmailConstraint && i < nameConstraints->cPermittedSubtree;
1113 i++)
1114 if (nameConstraints->rgPermittedSubtree[i].Base.dwAltNameChoice ==
1115 CERT_ALT_NAME_RFC822_NAME)
1116 hasEmailConstraint = TRUE;
1117 if (hasEmailConstraint)
1118 compare_subject_with_email_constraints(subjectName, nameConstraints,
1119 trustErrorStatus);
1120 for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
1121 {
1122 CERT_ALT_NAME_ENTRY *constraint =
1123 &nameConstraints->rgExcludedSubtree[i].Base;
1124
1125 if (constraint->dwAltNameChoice == CERT_ALT_NAME_DIRECTORY_NAME &&
1126 directory_name_matches(&constraint->u.DirectoryName, subjectName))
1127 {
1128 TRACE_(chain)("subject name is excluded\n");
1129 *trustErrorStatus |=
1130 CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
1131 }
1132 }
1133 /* RFC 5280, section 4.2.1.10:
1134 * "Restrictions apply only when the specified name form is present.
1135 * If no name of the type is in the certificate, the certificate is
1136 * acceptable."
1137 * An empty name can't have the name form present, so don't check it.
1138 */
1139 if (nameConstraints->cPermittedSubtree && !CRYPT_IsEmptyName(subjectName))
1140 {
1141 BOOL match = FALSE, hasDirectoryConstraint = FALSE;
1142
1143 for (i = 0; !match && i < nameConstraints->cPermittedSubtree; i++)
1144 {
1145 CERT_ALT_NAME_ENTRY *constraint =
1146 &nameConstraints->rgPermittedSubtree[i].Base;
1147
1148 if (constraint->dwAltNameChoice == CERT_ALT_NAME_DIRECTORY_NAME)
1149 {
1150 hasDirectoryConstraint = TRUE;
1151 match = directory_name_matches(&constraint->u.DirectoryName,
1152 subjectName);
1153 }
1154 }
1155 if (hasDirectoryConstraint && !match)
1156 {
1157 TRACE_(chain)("subject name is not permitted\n");
1158 *trustErrorStatus |= CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
1159 }
1160 }
1161 }
1162
1163 static void CRYPT_CheckNameConstraints(
1164 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, const CERT_INFO *cert,
1165 DWORD *trustErrorStatus)
1166 {
1167 CERT_EXTENSION *ext = get_subject_alt_name_ext(cert);
1168
1169 if (ext)
1170 compare_alt_name_with_constraints(ext, nameConstraints,
1171 trustErrorStatus);
1172 /* Name constraints apply to the subject alternative name as well as the
1173 * subject name. From RFC 5280, section 4.2.1.10:
1174 * "Restrictions apply to the subject distinguished name and apply to
1175 * subject alternative names."
1176 */
1177 compare_subject_with_constraints(&cert->Subject, nameConstraints,
1178 trustErrorStatus);
1179 }
1180
1181 /* Gets cert's name constraints, if any. Free with LocalFree. */
1182 static CERT_NAME_CONSTRAINTS_INFO *CRYPT_GetNameConstraints(CERT_INFO *cert)
1183 {
1184 CERT_NAME_CONSTRAINTS_INFO *info = NULL;
1185
1186 CERT_EXTENSION *ext;
1187
1188 if ((ext = CertFindExtension(szOID_NAME_CONSTRAINTS, cert->cExtension,
1189 cert->rgExtension)))
1190 {
1191 DWORD size;
1192
1193 CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
1194 ext->Value.pbData, ext->Value.cbData,
1195 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &info,
1196 &size);
1197 }
1198 return info;
1199 }
1200
1201 static BOOL CRYPT_IsValidNameConstraint(const CERT_NAME_CONSTRAINTS_INFO *info)
1202 {
1203 DWORD i;
1204 BOOL ret = TRUE;
1205
1206 /* Make sure at least one permitted or excluded subtree is present. From
1207 * RFC 5280, section 4.2.1.10:
1208 * "Conforming CAs MUST NOT issue certificates where name constraints is an
1209 * empty sequence. That is, either the permittedSubtrees field or the
1210 * excludedSubtrees MUST be present."
1211 */
1212 if (!info->cPermittedSubtree && !info->cExcludedSubtree)
1213 {
1214 WARN_(chain)("constraints contain no permitted nor excluded subtree\n");
1215 ret = FALSE;
1216 }
1217 /* Check that none of the constraints specifies a minimum or a maximum.
1218 * See RFC 5280, section 4.2.1.10:
1219 * "Within this profile, the minimum and maximum fields are not used with
1220 * any name forms, thus, the minimum MUST be zero, and maximum MUST be
1221 * absent. However, if an application encounters a critical name
1222 * constraints extension that specifies other values for minimum or
1223 * maximum for a name form that appears in a subsequent certificate, the
1224 * application MUST either process these fields or reject the
1225 * certificate."
1226 * Since it gives no guidance as to how to process these fields, we
1227 * reject any name constraint that contains them.
1228 */
1229 for (i = 0; ret && i < info->cPermittedSubtree; i++)
1230 if (info->rgPermittedSubtree[i].dwMinimum ||
1231 info->rgPermittedSubtree[i].fMaximum)
1232 {
1233 TRACE_(chain)("found a minimum or maximum in permitted subtrees\n");
1234 ret = FALSE;
1235 }
1236 for (i = 0; ret && i < info->cExcludedSubtree; i++)
1237 if (info->rgExcludedSubtree[i].dwMinimum ||
1238 info->rgExcludedSubtree[i].fMaximum)
1239 {
1240 TRACE_(chain)("found a minimum or maximum in excluded subtrees\n");
1241 ret = FALSE;
1242 }
1243 return ret;
1244 }
1245
1246 static void CRYPT_CheckChainNameConstraints(PCERT_SIMPLE_CHAIN chain)
1247 {
1248 int i, j;
1249
1250 /* Microsoft's implementation appears to violate RFC 3280: according to
1251 * MSDN, the various CERT_TRUST_*_NAME_CONSTRAINT errors are set if a CA's
1252 * name constraint is violated in the end cert. According to RFC 3280,
1253 * the constraints should be checked against every subsequent certificate
1254 * in the chain, not just the end cert.
1255 * Microsoft's implementation also sets the name constraint errors on the
1256 * certs whose constraints were violated, not on the certs that violated
1257 * them.
1258 * In order to be error-compatible with Microsoft's implementation, while
1259 * still adhering to RFC 3280, I use a O(n ^ 2) algorithm to check name
1260 * constraints.
1261 */
1262 for (i = chain->cElement - 1; i > 0; i--)
1263 {
1264 CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
1265
1266 if ((nameConstraints = CRYPT_GetNameConstraints(
1267 chain->rgpElement[i]->pCertContext->pCertInfo)))
1268 {
1269 if (!CRYPT_IsValidNameConstraint(nameConstraints))
1270 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1271 CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
1272 else
1273 {
1274 for (j = i - 1; j >= 0; j--)
1275 {
1276 DWORD errorStatus = 0;
1277
1278 /* According to RFC 3280, self-signed certs don't have name
1279 * constraints checked unless they're the end cert.
1280 */
1281 if (j == 0 || !CRYPT_IsCertificateSelfSigned(
1282 chain->rgpElement[j]->pCertContext))
1283 {
1284 CRYPT_CheckNameConstraints(nameConstraints,
1285 chain->rgpElement[j]->pCertContext->pCertInfo,
1286 &errorStatus);
1287 if (errorStatus)
1288 {
1289 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1290 errorStatus;
1291 CRYPT_CombineTrustStatus(&chain->TrustStatus,
1292 &chain->rgpElement[i]->TrustStatus);
1293 }
1294 else
1295 chain->rgpElement[i]->TrustStatus.dwInfoStatus |=
1296 CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS;
1297 }
1298 }
1299 }
1300 LocalFree(nameConstraints);
1301 }
1302 }
1303 }
1304
1305 static LPWSTR name_value_to_str(const CERT_NAME_BLOB *name)
1306 {
1307 DWORD len = cert_name_to_str_with_indent(X509_ASN_ENCODING, 0, name,
1308 CERT_SIMPLE_NAME_STR, NULL, 0);
1309 LPWSTR str = NULL;
1310
1311 if (len)
1312 {
1313 str = CryptMemAlloc(len * sizeof(WCHAR));
1314 if (str)
1315 cert_name_to_str_with_indent(X509_ASN_ENCODING, 0, name,
1316 CERT_SIMPLE_NAME_STR, str, len);
1317 }
1318 return str;
1319 }
1320
1321 static void dump_alt_name_entry(const CERT_ALT_NAME_ENTRY *entry)
1322 {
1323 LPWSTR str;
1324
1325 switch (entry->dwAltNameChoice)
1326 {
1327 case CERT_ALT_NAME_OTHER_NAME:
1328 TRACE_(chain)("CERT_ALT_NAME_OTHER_NAME, oid = %s\n",
1329 debugstr_a(entry->u.pOtherName->pszObjId));
1330 break;
1331 case CERT_ALT_NAME_RFC822_NAME:
1332 TRACE_(chain)("CERT_ALT_NAME_RFC822_NAME: %s\n",
1333 debugstr_w(entry->u.pwszRfc822Name));
1334 break;
1335 case CERT_ALT_NAME_DNS_NAME:
1336 TRACE_(chain)("CERT_ALT_NAME_DNS_NAME: %s\n",
1337 debugstr_w(entry->u.pwszDNSName));
1338 break;
1339 case CERT_ALT_NAME_DIRECTORY_NAME:
1340 str = name_value_to_str(&entry->u.DirectoryName);
1341 TRACE_(chain)("CERT_ALT_NAME_DIRECTORY_NAME: %s\n", debugstr_w(str));
1342 CryptMemFree(str);
1343 break;
1344 case CERT_ALT_NAME_URL:
1345 TRACE_(chain)("CERT_ALT_NAME_URL: %s\n", debugstr_w(entry->u.pwszURL));
1346 break;
1347 case CERT_ALT_NAME_IP_ADDRESS:
1348 TRACE_(chain)("CERT_ALT_NAME_IP_ADDRESS: %d bytes\n",
1349 entry->u.IPAddress.cbData);
1350 break;
1351 case CERT_ALT_NAME_REGISTERED_ID:
1352 TRACE_(chain)("CERT_ALT_NAME_REGISTERED_ID: %s\n",
1353 debugstr_a(entry->u.pszRegisteredID));
1354 break;
1355 default:
1356 TRACE_(chain)("dwAltNameChoice = %d\n", entry->dwAltNameChoice);
1357 }
1358 }
1359
1360 static void dump_alt_name(LPCSTR type, const CERT_EXTENSION *ext)
1361 {
1362 CERT_ALT_NAME_INFO *name;
1363 DWORD size;
1364
1365 TRACE_(chain)("%s:\n", type);
1366 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
1367 ext->Value.pbData, ext->Value.cbData,
1368 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &name, &size))
1369 {
1370 DWORD i;
1371
1372 TRACE_(chain)("%d alt name entries:\n", name->cAltEntry);
1373 for (i = 0; i < name->cAltEntry; i++)
1374 dump_alt_name_entry(&name->rgAltEntry[i]);
1375 LocalFree(name);
1376 }
1377 }
1378
1379 static void dump_basic_constraints(const CERT_EXTENSION *ext)
1380 {
1381 CERT_BASIC_CONSTRAINTS_INFO *info;
1382 DWORD size = 0;
1383
1384 if (CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
1385 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
1386 NULL, &info, &size))
1387 {
1388 TRACE_(chain)("SubjectType: %02x\n", info->SubjectType.pbData[0]);
1389 TRACE_(chain)("%s path length constraint\n",
1390 info->fPathLenConstraint ? "has" : "doesn't have");
1391 TRACE_(chain)("path length=%d\n", info->dwPathLenConstraint);
1392 LocalFree(info);
1393 }
1394 }
1395
1396 static void dump_basic_constraints2(const CERT_EXTENSION *ext)
1397 {
1398 CERT_BASIC_CONSTRAINTS2_INFO constraints;
1399 DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
1400
1401 if (CryptDecodeObjectEx(X509_ASN_ENCODING,
1402 szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
1403 0, NULL, &constraints, &size))
1404 {
1405 TRACE_(chain)("basic constraints:\n");
1406 TRACE_(chain)("can%s be a CA\n", constraints.fCA ? "" : "not");
1407 TRACE_(chain)("%s path length constraint\n",
1408 constraints.fPathLenConstraint ? "has" : "doesn't have");
1409 TRACE_(chain)("path length=%d\n", constraints.dwPathLenConstraint);
1410 }
1411 }
1412
1413 static void dump_key_usage(const CERT_EXTENSION *ext)
1414 {
1415 CRYPT_BIT_BLOB usage;
1416 DWORD size = sizeof(usage);
1417
1418 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
1419 ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
1420 {
1421 #define trace_usage_bit(bits, bit) \
1422 if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
1423 if (usage.cbData)
1424 {
1425 trace_usage_bit(usage.pbData[0], CERT_DIGITAL_SIGNATURE_KEY_USAGE);
1426 trace_usage_bit(usage.pbData[0], CERT_NON_REPUDIATION_KEY_USAGE);
1427 trace_usage_bit(usage.pbData[0], CERT_KEY_ENCIPHERMENT_KEY_USAGE);
1428 trace_usage_bit(usage.pbData[0], CERT_DATA_ENCIPHERMENT_KEY_USAGE);
1429 trace_usage_bit(usage.pbData[0], CERT_KEY_AGREEMENT_KEY_USAGE);
1430 trace_usage_bit(usage.pbData[0], CERT_KEY_CERT_SIGN_KEY_USAGE);
1431 trace_usage_bit(usage.pbData[0], CERT_CRL_SIGN_KEY_USAGE);
1432 trace_usage_bit(usage.pbData[0], CERT_ENCIPHER_ONLY_KEY_USAGE);
1433 }
1434 #undef trace_usage_bit
1435 if (usage.cbData > 1 && usage.pbData[1] & CERT_DECIPHER_ONLY_KEY_USAGE)
1436 TRACE_(chain)("CERT_DECIPHER_ONLY_KEY_USAGE\n");
1437 }
1438 }
1439
1440 static void dump_general_subtree(const CERT_GENERAL_SUBTREE *subtree)
1441 {
1442 dump_alt_name_entry(&subtree->Base);
1443 TRACE_(chain)("dwMinimum = %d, fMaximum = %d, dwMaximum = %d\n",
1444 subtree->dwMinimum, subtree->fMaximum, subtree->dwMaximum);
1445 }
1446
1447 static void dump_name_constraints(const CERT_EXTENSION *ext)
1448 {
1449 CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
1450 DWORD size;
1451
1452 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
1453 ext->Value.pbData, ext->Value.cbData,
1454 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &nameConstraints,
1455 &size))
1456 {
1457 DWORD i;
1458
1459 TRACE_(chain)("%d permitted subtrees:\n",
1460 nameConstraints->cPermittedSubtree);
1461 for (i = 0; i < nameConstraints->cPermittedSubtree; i++)
1462 dump_general_subtree(&nameConstraints->rgPermittedSubtree[i]);
1463 TRACE_(chain)("%d excluded subtrees:\n",
1464 nameConstraints->cExcludedSubtree);
1465 for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
1466 dump_general_subtree(&nameConstraints->rgExcludedSubtree[i]);
1467 LocalFree(nameConstraints);
1468 }
1469 }
1470
1471 static void dump_cert_policies(const CERT_EXTENSION *ext)
1472 {
1473 CERT_POLICIES_INFO *policies;
1474 DWORD size;
1475
1476 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_CERT_POLICIES,
1477 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1478 &policies, &size))
1479 {
1480 DWORD i, j;
1481
1482 TRACE_(chain)("%d policies:\n", policies->cPolicyInfo);
1483 for (i = 0; i < policies->cPolicyInfo; i++)
1484 {
1485 TRACE_(chain)("policy identifier: %s\n",
1486 debugstr_a(policies->rgPolicyInfo[i].pszPolicyIdentifier));
1487 TRACE_(chain)("%d policy qualifiers:\n",
1488 policies->rgPolicyInfo[i].cPolicyQualifier);
1489 for (j = 0; j < policies->rgPolicyInfo[i].cPolicyQualifier; j++)
1490 TRACE_(chain)("%s\n", debugstr_a(
1491 policies->rgPolicyInfo[i].rgPolicyQualifier[j].
1492 pszPolicyQualifierId));
1493 }
1494 LocalFree(policies);
1495 }
1496 }
1497
1498 static void dump_enhanced_key_usage(const CERT_EXTENSION *ext)
1499 {
1500 CERT_ENHKEY_USAGE *usage;
1501 DWORD size;
1502
1503 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ENHANCED_KEY_USAGE,
1504 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1505 &usage, &size))
1506 {
1507 DWORD i;
1508
1509 TRACE_(chain)("%d usages:\n", usage->cUsageIdentifier);
1510 for (i = 0; i < usage->cUsageIdentifier; i++)
1511 TRACE_(chain)("%s\n", usage->rgpszUsageIdentifier[i]);
1512 LocalFree(usage);
1513 }
1514 }
1515
1516 static void dump_netscape_cert_type(const CERT_EXTENSION *ext)
1517 {
1518 CRYPT_BIT_BLOB usage;
1519 DWORD size = sizeof(usage);
1520
1521 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
1522 ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
1523 {
1524 #define trace_cert_type_bit(bits, bit) \
1525 if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
1526 if (usage.cbData)
1527 {
1528 trace_cert_type_bit(usage.pbData[0],
1529 NETSCAPE_SSL_CLIENT_AUTH_CERT_TYPE);
1530 trace_cert_type_bit(usage.pbData[0],
1531 NETSCAPE_SSL_SERVER_AUTH_CERT_TYPE);
1532 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SMIME_CERT_TYPE);
1533 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SIGN_CERT_TYPE);
1534 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SSL_CA_CERT_TYPE);
1535 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SMIME_CA_CERT_TYPE);
1536 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SIGN_CA_CERT_TYPE);
1537 }
1538 #undef trace_cert_type_bit
1539 }
1540 }
1541
1542 static void dump_extension(const CERT_EXTENSION *ext)
1543 {
1544 TRACE_(chain)("%s (%scritical)\n", debugstr_a(ext->pszObjId),
1545 ext->fCritical ? "" : "not ");
1546 if (!strcmp(ext->pszObjId, szOID_SUBJECT_ALT_NAME))
1547 dump_alt_name("subject alt name", ext);
1548 else if (!strcmp(ext->pszObjId, szOID_ISSUER_ALT_NAME))
1549 dump_alt_name("issuer alt name", ext);
1550 else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS))
1551 dump_basic_constraints(ext);
1552 else if (!strcmp(ext->pszObjId, szOID_KEY_USAGE))
1553 dump_key_usage(ext);
1554 else if (!strcmp(ext->pszObjId, szOID_SUBJECT_ALT_NAME2))
1555 dump_alt_name("subject alt name 2", ext);
1556 else if (!strcmp(ext->pszObjId, szOID_ISSUER_ALT_NAME2))
1557 dump_alt_name("issuer alt name 2", ext);
1558 else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS2))
1559 dump_basic_constraints2(ext);
1560 else if (!strcmp(ext->pszObjId, szOID_NAME_CONSTRAINTS))
1561 dump_name_constraints(ext);
1562 else if (!strcmp(ext->pszObjId, szOID_CERT_POLICIES))
1563 dump_cert_policies(ext);
1564 else if (!strcmp(ext->pszObjId, szOID_ENHANCED_KEY_USAGE))
1565 dump_enhanced_key_usage(ext);
1566 else if (!strcmp(ext->pszObjId, szOID_NETSCAPE_CERT_TYPE))
1567 dump_netscape_cert_type(ext);
1568 }
1569
1570 static LPCWSTR filetime_to_str(const FILETIME *time)
1571 {
1572 static WCHAR date[80];
1573 WCHAR dateFmt[80]; /* sufficient for all versions of LOCALE_SSHORTDATE */
1574 SYSTEMTIME sysTime;
1575
1576 if (!time) return NULL;
1577
1578 GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, dateFmt,
1579 sizeof(dateFmt) / sizeof(dateFmt[0]));
1580 FileTimeToSystemTime(time, &sysTime);
1581 GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, date,
1582 sizeof(date) / sizeof(date[0]));
1583 return date;
1584 }
1585
1586 static void dump_element(PCCERT_CONTEXT cert)
1587 {
1588 LPWSTR name = NULL;
1589 DWORD len, i;
1590
1591 TRACE_(chain)("%p: version %d\n", cert, cert->pCertInfo->dwVersion);
1592 len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
1593 CERT_NAME_ISSUER_FLAG, NULL, NULL, 0);
1594 name = CryptMemAlloc(len * sizeof(WCHAR));
1595 if (name)
1596 {
1597 CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
1598 CERT_NAME_ISSUER_FLAG, NULL, name, len);
1599 TRACE_(chain)("issued by %s\n", debugstr_w(name));
1600 CryptMemFree(name);
1601 }
1602 len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
1603 NULL, 0);
1604 name = CryptMemAlloc(len * sizeof(WCHAR));
1605 if (name)
1606 {
1607 CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
1608 name, len);
1609 TRACE_(chain)("issued to %s\n", debugstr_w(name));
1610 CryptMemFree(name);
1611 }
1612 TRACE_(chain)("valid from %s to %s\n",
1613 debugstr_w(filetime_to_str(&cert->pCertInfo->NotBefore)),
1614 debugstr_w(filetime_to_str(&cert->pCertInfo->NotAfter)));
1615 TRACE_(chain)("%d extensions\n", cert->pCertInfo->cExtension);
1616 for (i = 0; i < cert->pCertInfo->cExtension; i++)
1617 dump_extension(&cert->pCertInfo->rgExtension[i]);
1618 }
1619
1620 static BOOL CRYPT_KeyUsageValid(PCertificateChainEngine engine,
1621 PCCERT_CONTEXT cert, BOOL isRoot, BOOL isCA, DWORD index)
1622 {
1623 PCERT_EXTENSION ext;
1624 BOOL ret;
1625 BYTE usageBits = 0;
1626
1627 ext = CertFindExtension(szOID_KEY_USAGE, cert->pCertInfo->cExtension,
1628 cert->pCertInfo->rgExtension);
1629 if (ext)
1630 {
1631 CRYPT_BIT_BLOB usage;
1632 DWORD size = sizeof(usage);
1633
1634 ret = CryptDecodeObjectEx(cert->dwCertEncodingType, X509_BITS,
1635 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL,
1636 &usage, &size);
1637 if (!ret)
1638 return FALSE;
1639 else if (usage.cbData > 2)
1640 {
1641 /* The key usage extension only defines 9 bits => no more than 2
1642 * bytes are needed to encode all known usages.
1643 */
1644 return FALSE;
1645 }
1646 else
1647 {
1648 /* The only bit relevant to chain validation is the keyCertSign
1649 * bit, which is always in the least significant byte of the
1650 * key usage bits.
1651 */
1652 usageBits = usage.pbData[usage.cbData - 1];
1653 }
1654 }
1655 if (isCA)
1656 {
1657 if (!ext)
1658 {
1659 /* MS appears to violate RFC 5280, section 4.2.1.3 (Key Usage)
1660 * here. Quoting the RFC:
1661 * "This [key usage] extension MUST appear in certificates that
1662 * contain public keys that are used to validate digital signatures
1663 * on other public key certificates or CRLs."
1664 * MS appears to accept certs that do not contain key usage
1665 * extensions as CA certs. V1 and V2 certificates did not have
1666 * extensions, and many root certificates are V1 certificates, so
1667 * perhaps this is prudent. On the other hand, MS also accepts V3
1668 * certs without key usage extensions. We are more restrictive:
1669 * we accept locally installed V1 or V2 certs as CA certs.
1670 * We also accept a lack of key usage extension on root certs,
1671 * which is implied in RFC 5280, section 6.1: the trust anchor's
1672 * only requirement is that it was used to issue the next
1673 * certificate in the chain.
1674 */
1675 if (isRoot)
1676 ret = TRUE;
1677 else if (cert->pCertInfo->dwVersion == CERT_V1 ||
1678 cert->pCertInfo->dwVersion == CERT_V2)
1679 {
1680 PCCERT_CONTEXT localCert = CRYPT_FindCertInStore(
1681 engine->hWorld, cert);
1682
1683 ret = localCert != NULL;
1684 CertFreeCertificateContext(localCert);
1685 }
1686 else
1687 ret = FALSE;
1688 if (!ret)
1689 WARN_(chain)("no key usage extension on a CA cert\n");
1690 }
1691 else
1692 {
1693 if (!(usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
1694 {
1695 WARN_(chain)("keyCertSign not asserted on a CA cert\n");
1696 ret = FALSE;
1697 }
1698 else
1699 ret = TRUE;
1700 }
1701 }
1702 else
1703 {
1704 if (ext && (usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
1705 {
1706 WARN_(chain)("keyCertSign asserted on a non-CA cert\n");
1707 ret = FALSE;
1708 }
1709 else
1710 ret = TRUE;
1711 }
1712 return ret;
1713 }
1714
1715 static BOOL CRYPT_CriticalExtensionsSupported(PCCERT_CONTEXT cert)
1716 {
1717 BOOL ret = TRUE;
1718 DWORD i;
1719
1720 for (i = 0; ret && i < cert->pCertInfo->cExtension; i++)
1721 {
1722 if (cert->pCertInfo->rgExtension[i].fCritical)
1723 {
1724 LPCSTR oid = cert->pCertInfo->rgExtension[i].pszObjId;
1725
1726 if (!strcmp(oid, szOID_BASIC_CONSTRAINTS))
1727 ret = TRUE;
1728 else if (!strcmp(oid, szOID_BASIC_CONSTRAINTS2))
1729 ret = TRUE;
1730 else if (!strcmp(oid, szOID_NAME_CONSTRAINTS))
1731 ret = TRUE;
1732 else if (!strcmp(oid, szOID_KEY_USAGE))
1733 ret = TRUE;
1734 else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME))
1735 ret = TRUE;
1736 else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME2))
1737 ret = TRUE;
1738 else if (!strcmp(oid, szOID_ENHANCED_KEY_USAGE))
1739 ret = TRUE;
1740 else
1741 {
1742 FIXME("unsupported critical extension %s\n",
1743 debugstr_a(oid));
1744 ret = FALSE;
1745 }
1746 }
1747 }
1748 return ret;
1749 }
1750
1751 static BOOL CRYPT_IsCertVersionValid(PCCERT_CONTEXT cert)
1752 {
1753 BOOL ret = TRUE;
1754
1755 /* Checks whether the contents of the cert match the cert's version. */
1756 switch (cert->pCertInfo->dwVersion)
1757 {
1758 case CERT_V1:
1759 /* A V1 cert may not contain unique identifiers. See RFC 5280,
1760 * section 4.1.2.8:
1761 * "These fields MUST only appear if the version is 2 or 3 (Section
1762 * 4.1.2.1). These fields MUST NOT appear if the version is 1."
1763 */
1764 if (cert->pCertInfo->IssuerUniqueId.cbData ||
1765 cert->pCertInfo->SubjectUniqueId.cbData)
1766 ret = FALSE;
1767 /* A V1 cert may not contain extensions. See RFC 5280, section 4.1.2.9:
1768 * "This field MUST only appear if the version is 3 (Section 4.1.2.1)."
1769 */
1770 if (cert->pCertInfo->cExtension)
1771 ret = FALSE;
1772 break;
1773 case CERT_V2:
1774 /* A V2 cert may not contain extensions. See RFC 5280, section 4.1.2.9:
1775 * "This field MUST only appear if the version is 3 (Section 4.1.2.1)."
1776 */
1777 if (cert->pCertInfo->cExtension)
1778 ret = FALSE;
1779 break;
1780 case CERT_V3:
1781 /* Do nothing, all fields are allowed for V3 certs */
1782 break;
1783 default:
1784 WARN_(chain)("invalid cert version %d\n", cert->pCertInfo->dwVersion);
1785 ret = FALSE;
1786 }
1787 return ret;
1788 }
1789
1790 static void CRYPT_CheckSimpleChain(PCertificateChainEngine engine,
1791 PCERT_SIMPLE_CHAIN chain, LPFILETIME time)
1792 {
1793 PCERT_CHAIN_ELEMENT rootElement = chain->rgpElement[chain->cElement - 1];
1794 int i;
1795 BOOL pathLengthConstraintViolated = FALSE;
1796 CERT_BASIC_CONSTRAINTS2_INFO constraints = { FALSE, FALSE, 0 };
1797
1798 TRACE_(chain)("checking chain with %d elements for time %s\n",
1799 chain->cElement, debugstr_w(filetime_to_str(time)));
1800 for (i = chain->cElement - 1; i >= 0; i--)
1801 {
1802 BOOL isRoot;
1803
1804 if (TRACE_ON(chain))
1805 dump_element(chain->rgpElement[i]->pCertContext);
1806 if (i == chain->cElement - 1)
1807 isRoot = CRYPT_IsCertificateSelfSigned(
1808 chain->rgpElement[i]->pCertContext);
1809 else
1810 isRoot = FALSE;
1811 if (!CRYPT_IsCertVersionValid(chain->rgpElement[i]->pCertContext))
1812 {
1813 /* MS appears to accept certs whose versions don't match their
1814 * contents, so there isn't an appropriate error code.
1815 */
1816 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1817 CERT_TRUST_INVALID_EXTENSION;
1818 }
1819 if (CertVerifyTimeValidity(time,
1820 chain->rgpElement[i]->pCertContext->pCertInfo) != 0)
1821 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1822 CERT_TRUST_IS_NOT_TIME_VALID;
1823 if (i != 0)
1824 {
1825 /* Check the signature of the cert this issued */
1826 if (!CryptVerifyCertificateSignatureEx(0, X509_ASN_ENCODING,
1827 CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT,
1828 (void *)chain->rgpElement[i - 1]->pCertContext,
1829 CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT,
1830 (void *)chain->rgpElement[i]->pCertContext, 0, NULL))
1831 chain->rgpElement[i - 1]->TrustStatus.dwErrorStatus |=
1832 CERT_TRUST_IS_NOT_SIGNATURE_VALID;
1833 /* Once a path length constraint has been violated, every remaining
1834 * CA cert's basic constraints is considered invalid.
1835 */
1836 if (pathLengthConstraintViolated)
1837 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1838 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1839 else if (!CRYPT_CheckBasicConstraintsForCA(engine,
1840 chain->rgpElement[i]->pCertContext, &constraints, i - 1, isRoot,
1841 &pathLengthConstraintViolated))
1842 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1843 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1844 else if (constraints.fPathLenConstraint &&
1845 constraints.dwPathLenConstraint)
1846 {
1847 /* This one's valid - decrement max length */
1848 constraints.dwPathLenConstraint--;
1849 }
1850 }
1851 else
1852 {
1853 /* Check whether end cert has a basic constraints extension */
1854 if (!CRYPT_DecodeBasicConstraints(
1855 chain->rgpElement[i]->pCertContext, &constraints, FALSE))
1856 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1857 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1858 }
1859 if (!CRYPT_KeyUsageValid(engine, chain->rgpElement[i]->pCertContext,
1860 isRoot, constraints.fCA, i))
1861 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1862 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
1863 if (CRYPT_IsSimpleChainCyclic(chain))
1864 {
1865 /* If the chain is cyclic, then the path length constraints
1866 * are violated, because the chain is infinitely long.
1867 */
1868 pathLengthConstraintViolated = TRUE;
1869 chain->TrustStatus.dwErrorStatus |=
1870 CERT_TRUST_IS_PARTIAL_CHAIN |
1871 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1872 }
1873 /* Check whether every critical extension is supported */
1874 if (!CRYPT_CriticalExtensionsSupported(
1875 chain->rgpElement[i]->pCertContext))
1876 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1877 CERT_TRUST_INVALID_EXTENSION;
1878 CRYPT_CombineTrustStatus(&chain->TrustStatus,
1879 &chain->rgpElement[i]->TrustStatus);
1880 }
1881 CRYPT_CheckChainNameConstraints(chain);
1882 if (CRYPT_IsCertificateSelfSigned(rootElement->pCertContext))
1883 {
1884 rootElement->TrustStatus.dwInfoStatus |=
1885 CERT_TRUST_IS_SELF_SIGNED | CERT_TRUST_HAS_NAME_MATCH_ISSUER;
1886 CRYPT_CheckRootCert(engine->hRoot, rootElement);
1887 }
1888 CRYPT_CombineTrustStatus(&chain->TrustStatus, &rootElement->TrustStatus);
1889 }
1890
1891 static PCCERT_CONTEXT CRYPT_GetIssuer(HCERTSTORE store, PCCERT_CONTEXT subject,
1892 PCCERT_CONTEXT prevIssuer, DWORD *infoStatus)
1893 {
1894 PCCERT_CONTEXT issuer = NULL;
1895 PCERT_EXTENSION ext;
1896 DWORD size;
1897
1898 *infoStatus = 0;
1899 if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
1900 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1901 {
1902 CERT_AUTHORITY_KEY_ID_INFO *info;
1903 BOOL ret;
1904
1905 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1906 X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
1907 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1908 &info, &size);
1909 if (ret)
1910 {
1911 CERT_ID id;
1912
1913 if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
1914 {
1915 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1916 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
1917 sizeof(CERT_NAME_BLOB));
1918 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1919 &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
1920 issuer = CertFindCertificateInStore(store,
1921 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1922 prevIssuer);
1923 if (issuer)
1924 {
1925 TRACE_(chain)("issuer found by issuer/serial number\n");
1926 *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
1927 }
1928 }
1929 else if (info->KeyId.cbData)
1930 {
1931 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1932 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1933 issuer = CertFindCertificateInStore(store,
1934 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1935 prevIssuer);
1936 if (issuer)
1937 {
1938 TRACE_(chain)("issuer found by key id\n");
1939 *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
1940 }
1941 }
1942 LocalFree(info);
1943 }
1944 }
1945 else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
1946 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1947 {
1948 CERT_AUTHORITY_KEY_ID2_INFO *info;
1949 BOOL ret;
1950
1951 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1952 X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
1953 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1954 &info, &size);
1955 if (ret)
1956 {
1957 CERT_ID id;
1958
1959 if (info->AuthorityCertIssuer.cAltEntry &&
1960 info->AuthorityCertSerialNumber.cbData)
1961 {
1962 PCERT_ALT_NAME_ENTRY directoryName = NULL;
1963 DWORD i;
1964
1965 for (i = 0; !directoryName &&
1966 i < info->AuthorityCertIssuer.cAltEntry; i++)
1967 if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
1968 == CERT_ALT_NAME_DIRECTORY_NAME)
1969 directoryName =
1970 &info->AuthorityCertIssuer.rgAltEntry[i];
1971 if (directoryName)
1972 {
1973 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1974 memcpy(&id.u.IssuerSerialNumber.Issuer,
1975 &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
1976 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1977 &info->AuthorityCertSerialNumber,
1978 sizeof(CRYPT_INTEGER_BLOB));
1979 issuer = CertFindCertificateInStore(store,
1980 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1981 prevIssuer);
1982 if (issuer)
1983 {
1984 TRACE_(chain)("issuer found by directory name\n");
1985 *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
1986 }
1987 }
1988 else
1989 FIXME("no supported name type in authority key id2\n");
1990 }
1991 else if (info->KeyId.cbData)
1992 {
1993 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1994 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1995 issuer = CertFindCertificateInStore(store,
1996 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1997 prevIssuer);
1998 if (issuer)
1999 {
2000 TRACE_(chain)("issuer found by key id\n");
2001 *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
2002 }
2003 }
2004 LocalFree(info);
2005 }
2006 }
2007 else
2008 {
2009 issuer = CertFindCertificateInStore(store,
2010 subject->dwCertEncodingType, 0, CERT_FIND_SUBJECT_NAME,
2011 &subject->pCertInfo->Issuer, prevIssuer);
2012 TRACE_(chain)("issuer found by name\n");
2013 *infoStatus = CERT_TRUST_HAS_NAME_MATCH_ISSUER;
2014 }
2015 return issuer;
2016 }
2017
2018 /* Builds a simple chain by finding an issuer for the last cert in the chain,
2019 * until reaching a self-signed cert, or until no issuer can be found.
2020 */
2021 static BOOL CRYPT_BuildSimpleChain(const CertificateChainEngine *engine,
2022 HCERTSTORE world, PCERT_SIMPLE_CHAIN chain)
2023 {
2024 BOOL ret = TRUE;
2025 PCCERT_CONTEXT cert = chain->rgpElement[chain->cElement - 1]->pCertContext;
2026
2027 while (ret && !CRYPT_IsSimpleChainCyclic(chain) &&
2028 !CRYPT_IsCertificateSelfSigned(cert))
2029 {
2030 PCCERT_CONTEXT issuer = CRYPT_GetIssuer(world, cert, NULL,
2031 &chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
2032
2033 if (issuer)
2034 {
2035 ret = CRYPT_AddCertToSimpleChain(engine, chain, issuer,
2036 chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
2037 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it to
2038 * close the enumeration that found it
2039 */
2040 CertFreeCertificateContext(issuer);
2041 cert = issuer;
2042 }
2043 else
2044 {
2045 TRACE_(chain)("Couldn't find issuer, halting chain creation\n");
2046 chain->TrustStatus.dwErrorStatus |= CERT_TRUST_IS_PARTIAL_CHAIN;
2047 break;
2048 }
2049 }
2050 return ret;
2051 }
2052
2053 static BOOL CRYPT_GetSimpleChainForCert(PCertificateChainEngine engine,
2054 HCERTSTORE world, PCCERT_CONTEXT cert, LPFILETIME pTime,
2055 PCERT_SIMPLE_CHAIN *ppChain)
2056 {
2057 BOOL ret = FALSE;
2058 PCERT_SIMPLE_CHAIN chain;
2059
2060 TRACE("(%p, %p, %p, %p)\n", engine, world, cert, pTime);
2061
2062 chain = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
2063 if (chain)
2064 {
2065 memset(chain, 0, sizeof(CERT_SIMPLE_CHAIN));
2066 chain->cbSize = sizeof(CERT_SIMPLE_CHAIN);
2067 ret = CRYPT_AddCertToSimpleChain(engine, chain, cert, 0);
2068 if (ret)
2069 {
2070 ret = CRYPT_BuildSimpleChain(engine, world, chain);
2071 if (ret)
2072 CRYPT_CheckSimpleChain(engine, chain, pTime);
2073 }
2074 if (!ret)
2075 {
2076 CRYPT_FreeSimpleChain(chain);
2077 chain = NULL;
2078 }
2079 *ppChain = chain;
2080 }
2081 return ret;
2082 }
2083
2084 static BOOL CRYPT_BuildCandidateChainFromCert(HCERTCHAINENGINE hChainEngine,
2085 PCCERT_CONTEXT cert, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
2086 PCertificateChain *ppChain)
2087 {
2088 PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
2089 PCERT_SIMPLE_CHAIN simpleChain = NULL;
2090 HCERTSTORE world;
2091 BOOL ret;
2092
2093 world = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
2094 CERT_STORE_CREATE_NEW_FLAG, NULL);
2095 CertAddStoreToCollection(world, engine->hWorld, 0, 0);
2096 if (hAdditionalStore)
2097 CertAddStoreToCollection(world, hAdditionalStore, 0, 0);
2098 /* FIXME: only simple chains are supported for now, as CTLs aren't
2099 * supported yet.
2100 */
2101 if ((ret = CRYPT_GetSimpleChainForCert(engine, world, cert, pTime,
2102 &simpleChain)))
2103 {
2104 PCertificateChain chain = CryptMemAlloc(sizeof(CertificateChain));
2105
2106 if (chain)
2107 {
2108 chain->ref = 1;
2109 chain->world = world;
2110 chain->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
2111 chain->context.TrustStatus = simpleChain->TrustStatus;
2112 chain->context.cChain = 1;
2113 chain->context.rgpChain = CryptMemAlloc(sizeof(PCERT_SIMPLE_CHAIN));
2114 chain->context.rgpChain[0] = simpleChain;
2115 chain->context.cLowerQualityChainContext = 0;
2116 chain->context.rgpLowerQualityChainContext = NULL;
2117 chain->context.fHasRevocationFreshnessTime = FALSE;
2118 chain->context.dwRevocationFreshnessTime = 0;
2119 }
2120 else
2121 ret = FALSE;
2122 *ppChain = chain;
2123 }
2124 return ret;
2125 }
2126
2127 /* Makes and returns a copy of chain, up to and including element iElement. */
2128 static PCERT_SIMPLE_CHAIN CRYPT_CopySimpleChainToElement(
2129 const CERT_SIMPLE_CHAIN *chain, DWORD iElement)
2130 {
2131 PCERT_SIMPLE_CHAIN copy = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
2132
2133 if (copy)
2134 {
2135 memset(copy, 0, sizeof(CERT_SIMPLE_CHAIN));
2136 copy->cbSize = sizeof(CERT_SIMPLE_CHAIN);
2137 copy->rgpElement =
2138 CryptMemAlloc((iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
2139 if (copy->rgpElement)
2140 {
2141 DWORD i;
2142 BOOL ret = TRUE;
2143
2144 memset(copy->rgpElement, 0,
2145 (iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
2146 for (i = 0; ret && i <= iElement; i++)
2147 {
2148 PCERT_CHAIN_ELEMENT element =
2149 CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
2150
2151 if (element)
2152 {
2153 *element = *chain->rgpElement[i];
2154 element->pCertContext = CertDuplicateCertificateContext(
2155 chain->rgpElement[i]->pCertContext);
2156 /* Reset the trust status of the copied element, it'll get
2157 * rechecked after the new chain is done.
2158 */
2159 memset(&element->TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
2160 copy->rgpElement[copy->cElement++] = element;
2161 }
2162 else
2163 ret = FALSE;
2164 }
2165 if (!ret)
2166 {
2167 for (i = 0; i <= iElement; i++)
2168 CryptMemFree(copy->rgpElement[i]);
2169 CryptMemFree(copy->rgpElement);
2170 CryptMemFree(copy);
2171 copy = NULL;
2172 }
2173 }
2174 else
2175 {
2176 CryptMemFree(copy);
2177 copy = NULL;
2178 }
2179 }
2180 return copy;
2181 }
2182
2183 static void CRYPT_FreeLowerQualityChains(PCertificateChain chain)
2184 {
2185 DWORD i;
2186
2187 for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
2188 CertFreeCertificateChain(chain->context.rgpLowerQualityChainContext[i]);
2189 CryptMemFree(chain->context.rgpLowerQualityChainContext);
2190 chain->context.cLowerQualityChainContext = 0;
2191 chain->context.rgpLowerQualityChainContext = NULL;
2192 }
2193
2194 static void CRYPT_FreeChainContext(PCertificateChain chain)
2195 {
2196 DWORD i;
2197
2198 CRYPT_FreeLowerQualityChains(chain);
2199 for (i = 0; i < chain->context.cChain; i++)
2200 CRYPT_FreeSimpleChain(chain->context.rgpChain[i]);
2201 CryptMemFree(chain->context.rgpChain);
2202 CertCloseStore(chain->world, 0);
2203 CryptMemFree(chain);
2204 }
2205
2206 /* Makes and returns a copy of chain, up to and including element iElement of
2207 * simple chain iChain.
2208 */
2209 static PCertificateChain CRYPT_CopyChainToElement(PCertificateChain chain,
2210 DWORD iChain, DWORD iElement)
2211 {
2212 PCertificateChain copy = CryptMemAlloc(sizeof(CertificateChain));
2213
2214 if (copy)
2215 {
2216 copy->ref = 1;
2217 copy->world = CertDuplicateStore(chain->world);
2218 copy->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
2219 /* Leave the trust status of the copied chain unset, it'll get
2220 * rechecked after the new chain is done.
2221 */
2222 memset(&copy->context.TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
2223 copy->context.cLowerQualityChainContext = 0;
2224 copy->context.rgpLowerQualityChainContext = NULL;
2225 copy->context.fHasRevocationFreshnessTime = FALSE;
2226 copy->context.dwRevocationFreshnessTime = 0;
2227 copy->context.rgpChain = CryptMemAlloc(
2228 (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
2229 if (copy->context.rgpChain)
2230 {
2231 BOOL ret = TRUE;
2232 DWORD i;
2233
2234 memset(copy->context.rgpChain, 0,
2235 (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
2236 if (iChain)
2237 {
2238 for (i = 0; ret && iChain && i < iChain - 1; i++)
2239 {
2240 copy->context.rgpChain[i] =
2241 CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
2242 chain->context.rgpChain[i]->cElement - 1);
2243 if (!copy->context.rgpChain[i])
2244 ret = FALSE;
2245 }
2246 }
2247 else
2248 i = 0;
2249 if (ret)
2250 {
2251 copy->context.rgpChain[i] =
2252 CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
2253 iElement);
2254 if (!copy->context.rgpChain[i])
2255 ret = FALSE;
2256 }
2257 if (!ret)
2258 {
2259 CRYPT_FreeChainContext(copy);
2260 copy = NULL;
2261 }
2262 else
2263 copy->context.cChain = iChain + 1;
2264 }
2265 else
2266 {
2267 CryptMemFree(copy);
2268 copy = NULL;
2269 }
2270 }
2271 return copy;
2272 }
2273
2274 static PCertificateChain CRYPT_BuildAlternateContextFromChain(
2275 HCERTCHAINENGINE hChainEngine, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
2276 PCertificateChain chain)
2277 {
2278 PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
2279 PCertificateChain alternate;
2280
2281 TRACE("(%p, %p, %p, %p)\n", hChainEngine, pTime, hAdditionalStore, chain);
2282
2283 /* Always start with the last "lower quality" chain to ensure a consistent
2284 * order of alternate creation:
2285 */
2286 if (chain->context.cLowerQualityChainContext)
2287 chain = (PCertificateChain)chain->context.rgpLowerQualityChainContext[
2288 chain->context.cLowerQualityChainContext - 1];
2289 /* A chain with only one element can't have any alternates */
2290 if (chain->context.cChain <= 1 && chain->context.rgpChain[0]->cElement <= 1)
2291 alternate = NULL;
2292 else
2293 {
2294 DWORD i, j, infoStatus;
2295 PCCERT_CONTEXT alternateIssuer = NULL;
2296
2297 alternate = NULL;
2298 for (i = 0; !alternateIssuer && i < chain->context.cChain; i++)
2299 for (j = 0; !alternateIssuer &&
2300 j < chain->context.rgpChain[i]->cElement - 1; j++)
2301 {
2302 PCCERT_CONTEXT subject =
2303 chain->context.rgpChain[i]->rgpElement[j]->pCertContext;
2304 PCCERT_CONTEXT prevIssuer = CertDuplicateCertificateContext(
2305 chain->context.rgpChain[i]->rgpElement[j + 1]->pCertContext);
2306
2307 alternateIssuer = CRYPT_GetIssuer(prevIssuer->hCertStore,
2308 subject, prevIssuer, &infoStatus);
2309 }
2310 if (alternateIssuer)
2311 {
2312 i--;
2313 j--;
2314 alternate = CRYPT_CopyChainToElement(chain, i, j);
2315 if (alternate)
2316 {
2317 BOOL ret = CRYPT_AddCertToSimpleChain(engine,
2318 alternate->context.rgpChain[i], alternateIssuer, infoStatus);
2319
2320 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it
2321 * to close the enumeration that found it
2322 */
2323 CertFreeCertificateContext(alternateIssuer);
2324 if (ret)
2325 {
2326 ret = CRYPT_BuildSimpleChain(engine, alternate->world,
2327 alternate->context.rgpChain[i]);
2328 if (ret)
2329 CRYPT_CheckSimpleChain(engine,
2330 alternate->context.rgpChain[i], pTime);
2331 CRYPT_CombineTrustStatus(&alternate->context.TrustStatus,
2332 &alternate->context.rgpChain[i]->TrustStatus);
2333 }
2334 if (!ret)
2335 {
2336 CRYPT_FreeChainContext(alternate);
2337 alternate = NULL;
2338 }
2339 }
2340 }
2341 }
2342 TRACE("%p\n", alternate);
2343 return alternate;
2344 }
2345
2346 #define CHAIN_QUALITY_SIGNATURE_VALID 0x16
2347 #define CHAIN_QUALITY_TIME_VALID 8
2348 #define CHAIN_QUALITY_COMPLETE_CHAIN 4
2349 #define CHAIN_QUALITY_BASIC_CONSTRAINTS 2
2350 #define CHAIN_QUALITY_TRUSTED_ROOT 1
2351
2352 #define CHAIN_QUALITY_HIGHEST \
2353 CHAIN_QUALITY_SIGNATURE_VALID | CHAIN_QUALITY_TIME_VALID | \
2354 CHAIN_QUALITY_COMPLETE_CHAIN | CHAIN_QUALITY_BASIC_CONSTRAINTS | \
2355 CHAIN_QUALITY_TRUSTED_ROOT
2356
2357 #define IS_TRUST_ERROR_SET(TrustStatus, bits) \
2358 (TrustStatus)->dwErrorStatus & (bits)
2359
2360 static DWORD CRYPT_ChainQuality(const CertificateChain *chain)
2361 {
2362 DWORD quality = CHAIN_QUALITY_HIGHEST;
2363
2364 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2365 CERT_TRUST_IS_UNTRUSTED_ROOT))
2366 quality &= ~CHAIN_QUALITY_TRUSTED_ROOT;
2367 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2368 CERT_TRUST_INVALID_BASIC_CONSTRAINTS))
2369 quality &= ~CHAIN_QUALITY_BASIC_CONSTRAINTS;
2370 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2371 CERT_TRUST_IS_PARTIAL_CHAIN))
2372 quality &= ~CHAIN_QUALITY_COMPLETE_CHAIN;
2373 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2374 CERT_TRUST_IS_NOT_TIME_VALID | CERT_TRUST_IS_NOT_TIME_NESTED))
2375 quality &= ~CHAIN_QUALITY_TIME_VALID;
2376 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
2377 CERT_TRUST_IS_NOT_SIGNATURE_VALID))
2378 quality &= ~CHAIN_QUALITY_SIGNATURE_VALID;
2379 return quality;
2380 }
2381
2382 /* Chooses the highest quality chain among chain and its "lower quality"
2383 * alternate chains. Returns the highest quality chain, with all other
2384 * chains as lower quality chains of it.
2385 */
2386 static PCertificateChain CRYPT_ChooseHighestQualityChain(
2387 PCertificateChain chain)
2388 {
2389 DWORD i;
2390
2391 /* There are always only two chains being considered: chain, and an
2392 * alternate at chain->rgpLowerQualityChainContext[i]. If the alternate
2393 * has a higher quality than chain, the alternate gets assigned the lower
2394 * quality contexts, with chain taking the alternate's place among the
2395 * lower quality contexts.
2396 */
2397 for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
2398 {
2399 PCertificateChain alternate =
2400 (PCertificateChain)chain->context.rgpLowerQualityChainContext[i];
2401
2402 if (CRYPT_ChainQuality(alternate) > CRYPT_ChainQuality(chain))
2403 {
2404 alternate->context.cLowerQualityChainContext =
2405 chain->context.cLowerQualityChainContext;
2406 alternate->context.rgpLowerQualityChainContext =
2407 chain->context.rgpLowerQualityChainContext;
2408 alternate->context.rgpLowerQualityChainContext[i] =
2409 (PCCERT_CHAIN_CONTEXT)chain;
2410 chain->context.cLowerQualityChainContext = 0;
2411 chain->context.rgpLowerQualityChainContext = NULL;
2412 chain = alternate;
2413 }
2414 }
2415 return chain;
2416 }
2417
2418 static BOOL CRYPT_AddAlternateChainToChain(PCertificateChain chain,
2419 const CertificateChain *alternate)
2420 {
2421 BOOL ret;
2422
2423 if (chain->context.cLowerQualityChainContext)
2424 chain->context.rgpLowerQualityChainContext =
2425 CryptMemRealloc(chain->context.rgpLowerQualityChainContext,
2426 (chain->context.cLowerQualityChainContext + 1) *
2427 sizeof(PCCERT_CHAIN_CONTEXT));
2428 else
2429 chain->context.rgpLowerQualityChainContext =
2430 CryptMemAlloc(sizeof(PCCERT_CHAIN_CONTEXT));
2431 if (chain->context.rgpLowerQualityChainContext)
2432 {
2433 chain->context.rgpLowerQualityChainContext[
2434 chain->context.cLowerQualityChainContext++] =
2435 (PCCERT_CHAIN_CONTEXT)alternate;
2436 ret = TRUE;
2437 }
2438 else
2439 ret = FALSE;
2440 return ret;
2441 }
2442
2443 static PCERT_CHAIN_ELEMENT CRYPT_FindIthElementInChain(
2444 const CERT_CHAIN_CONTEXT *chain, DWORD i)
2445 {
2446 DWORD j, iElement;
2447 PCERT_CHAIN_ELEMENT element = NULL;
2448
2449 for (j = 0, iElement = 0; !element && j < chain->cChain; j++)
2450 {
2451 if (iElement + chain->rgpChain[j]->cElement < i)
2452 iElement += chain->rgpChain[j]->cElement;
2453 else
2454 element = chain->rgpChain[j]->rgpElement[i - iElement];
2455 }
2456 return element;
2457 }
2458
2459 typedef struct _CERT_CHAIN_PARA_NO_EXTRA_FIELDS {
2460 DWORD cbSize;
2461 CERT_USAGE_MATCH RequestedUsage;
2462 } CERT_CHAIN_PARA_NO_EXTRA_FIELDS, *PCERT_CHAIN_PARA_NO_EXTRA_FIELDS;
2463
2464 static void CRYPT_VerifyChainRevocation(PCERT_CHAIN_CONTEXT chain,
2465 LPFILETIME pTime, const CERT_CHAIN_PARA *pChainPara, DWORD chainFlags)
2466 {
2467 DWORD cContext;
2468
2469 if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_END_CERT)
2470 cContext = 1;
2471 else if ((chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN) ||
2472 (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT))
2473 {
2474 DWORD i;
2475
2476 for (i = 0, cContext = 0; i < chain->cChain; i++)
2477 {
2478 if (i < chain->cChain - 1 ||
2479 chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN)
2480 cContext += chain->rgpChain[i]->cElement;
2481 else
2482 cContext += chain->rgpChain[i]->cElement - 1;
2483 }
2484 }
2485 else
2486 cContext = 0;
2487 if (cContext)
2488 {
2489 PCCERT_CONTEXT *contexts =
2490 CryptMemAlloc(cContext * sizeof(PCCERT_CONTEXT));
2491
2492 if (contexts)
2493 {
2494 DWORD i, j, iContext, revocationFlags;
2495 CERT_REVOCATION_PARA revocationPara = { sizeof(revocationPara), 0 };
2496 CERT_REVOCATION_STATUS revocationStatus =
2497 { sizeof(revocationStatus), 0 };
2498 BOOL ret;
2499
2500 for (i = 0, iContext = 0; iContext < cContext && i < chain->cChain;
2501 i++)
2502 {
2503 for (j = 0; iContext < cContext &&
2504 j < chain->rgpChain[i]->cElement; j++)
2505 contexts[iContext++] =
2506 chain->rgpChain[i]->rgpElement[j]->pCertContext;
2507 }
2508 revocationFlags = CERT_VERIFY_REV_CHAIN_FLAG;
2509 if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY)
2510 revocationFlags |= CERT_VERIFY_CACHE_ONLY_BASED_REVOCATION;
2511 if (chainFlags & CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT)
2512 revocationFlags |= CERT_VERIFY_REV_ACCUMULATIVE_TIMEOUT_FLAG;
2513 revocationPara.pftTimeToUse = pTime;
2514 if (pChainPara->cbSize == sizeof(CERT_CHAIN_PARA))
2515 {
2516 revocationPara.dwUrlRetrievalTimeout =
2517 pChainPara->dwUrlRetrievalTimeout;
2518 revocationPara.fCheckFreshnessTime =
2519 pChainPara->fCheckRevocationFreshnessTime;
2520 revocationPara.dwFreshnessTime =
2521 pChainPara->dwRevocationFreshnessTime;
2522 }
2523 ret = CertVerifyRevocation(X509_ASN_ENCODING,
2524 CERT_CONTEXT_REVOCATION_TYPE, cContext, (void **)contexts,
2525 revocationFlags, &revocationPara, &revocationStatus);
2526 if (!ret)
2527 {
2528 PCERT_CHAIN_ELEMENT element =
2529 CRYPT_FindIthElementInChain(chain, revocationStatus.dwIndex);
2530 DWORD error;
2531
2532 switch (revocationStatus.dwError)
2533 {
2534 case CRYPT_E_NO_REVOCATION_CHECK:
2535 case CRYPT_E_NO_REVOCATION_DLL:
2536 case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
2537 /* If the revocation status is unknown, it's assumed to be
2538 * offline too.
2539 */
2540 error = CERT_TRUST_REVOCATION_STATUS_UNKNOWN |
2541 CERT_TRUST_IS_OFFLINE_REVOCATION;
2542 break;
2543 case CRYPT_E_REVOCATION_OFFLINE:
2544 error = CERT_TRUST_IS_OFFLINE_REVOCATION;
2545 break;
2546 case CRYPT_E_REVOKED:
2547 error = CERT_TRUST_IS_REVOKED;
2548 break;
2549 default:
2550 WARN("unmapped error %08x\n", revocationStatus.dwError);
2551 error = 0;
2552 }
2553 if (element)
2554 {
2555 /* FIXME: set element's pRevocationInfo member */
2556 element->TrustStatus.dwErrorStatus |= error;
2557 }
2558 chain->TrustStatus.dwErrorStatus |= error;
2559 }
2560 CryptMemFree(contexts);
2561 }
2562 }
2563 }
2564
2565 static void CRYPT_CheckUsages(PCERT_CHAIN_CONTEXT chain,
2566 const CERT_CHAIN_PARA *pChainPara)
2567 {
2568 if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA_NO_EXTRA_FIELDS) &&
2569 pChainPara->RequestedUsage.Usage.cUsageIdentifier)
2570 {
2571 PCCERT_CONTEXT endCert;
2572 PCERT_EXTENSION ext;
2573 BOOL validForUsage;
2574
2575 /* A chain, if created, always includes the end certificate */
2576 endCert = chain->rgpChain[0]->rgpElement[0]->pCertContext;
2577 /* The extended key usage extension specifies how a certificate's
2578 * public key may be used. From RFC 5280, section 4.2.1.12:
2579 * "This extension indicates one or more purposes for which the
2580 * certified public key may be used, in addition to or in place of the
2581 * basic purposes indicated in the key usage extension."
2582 * If the extension is present, it only satisfies the requested usage
2583 * if that usage is included in the extension:
2584 * "If the extension is present, then the certificate MUST only be used
2585 * for one of the purposes indicated."
2586 * There is also the special anyExtendedKeyUsage OID, but it doesn't
2587 * have to be respected:
2588 * "Applications that require the presence of a particular purpose
2589 * MAY reject certificates that include the anyExtendedKeyUsage OID
2590 * but not the particular OID expected for the application."
2591 * For now, I'm being more conservative and ignoring the presence of
2592 * the anyExtendedKeyUsage OID.
2593 */
2594 if ((ext = CertFindExtension(szOID_ENHANCED_KEY_USAGE,
2595 endCert->pCertInfo->cExtension, endCert->pCertInfo->rgExtension)))
2596 {
2597 const CERT_ENHKEY_USAGE *requestedUsage =
2598 &pChainPara->RequestedUsage.Usage;
2599 CERT_ENHKEY_USAGE *usage;
2600 DWORD size;
2601
2602 if (CryptDecodeObjectEx(X509_ASN_ENCODING,
2603 X509_ENHANCED_KEY_USAGE, ext->Value.pbData, ext->Value.cbData,
2604 CRYPT_DECODE_ALLOC_FLAG, NULL, &usage, &size))
2605 {
2606 if (pChainPara->RequestedUsage.dwType == USAGE_MATCH_TYPE_AND)
2607 {
2608 DWORD i, j;
2609
2610 /* For AND matches, all usages must be present */
2611 validForUsage = TRUE;
2612 for (i = 0; validForUsage &&
2613 i < requestedUsage->cUsageIdentifier; i++)
2614 {
2615 BOOL match = FALSE;
2616
2617 for (j = 0; !match && j < usage->cUsageIdentifier; j++)
2618 match = !strcmp(usage->rgpszUsageIdentifier[j],
2619 requestedUsage->rgpszUsageIdentifier[i]);
2620 if (!match)
2621 validForUsage = FALSE;
2622 }
2623 }
2624 else
2625 {
2626 DWORD i, j;
2627
2628 /* For OR matches, any matching usage suffices */
2629 validForUsage = FALSE;
2630 for (i = 0; !validForUsage &&
2631 i < requestedUsage->cUsageIdentifier; i++)
2632 {
2633 for (j = 0; !validForUsage &&
2634 j < usage->cUsageIdentifier; j++)
2635 validForUsage =
2636 !strcmp(usage->rgpszUsageIdentifier[j],
2637 requestedUsage->rgpszUsageIdentifier[i]);
2638 }
2639 }
2640 LocalFree(usage);
2641 }
2642 else
2643 validForUsage = FALSE;
2644 }
2645 else
2646 {
2647 /* If the extension isn't present, any interpretation is valid:
2648 * "Certificate using applications MAY require that the extended
2649 * key usage extension be present and that a particular purpose
2650 * be indicated in order for the certificate to be acceptable to
2651 * that application."
2652 * Not all web sites include the extended key usage extension, so
2653 * accept chains without it.
2654 */
2655 TRACE_(chain)("requested usage from certificate with no usages\n");
2656 validForUsage = TRUE;
2657 }
2658 if (!validForUsage)
2659 {
2660 chain->TrustStatus.dwErrorStatus |=
2661 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
2662 chain->rgpChain[0]->rgpElement[0]->TrustStatus.dwErrorStatus |=
2663 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
2664 }
2665 }
2666 if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA) &&
2667 pChainPara->RequestedIssuancePolicy.Usage.cUsageIdentifier)
2668 FIXME("unimplemented for RequestedIssuancePolicy\n");
2669 }
2670
2671 static void dump_usage_match(LPCSTR name, const CERT_USAGE_MATCH *usageMatch)
2672 {
2673 if (usageMatch->Usage.cUsageIdentifier)
2674 {
2675 DWORD i;
2676
2677 TRACE_(chain)("%s: %s\n", name,
2678 usageMatch->dwType == USAGE_MATCH_TYPE_AND ? "AND" : "OR");
2679 for (i = 0; i < usageMatch->Usage.cUsageIdentifier; i++)
2680 TRACE_(chain)("%s\n", usageMatch->Usage.rgpszUsageIdentifier[i]);
2681 }
2682 }
2683
2684 static void dump_chain_para(const CERT_CHAIN_PARA *pChainPara)
2685 {
2686 TRACE_(chain)("%d\n", pChainPara->cbSize);
2687 if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA_NO_EXTRA_FIELDS))
2688 dump_usage_match("RequestedUsage", &pChainPara->RequestedUsage);
2689 if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA))
2690 {
2691 dump_usage_match("RequestedIssuancePolicy",
2692 &pChainPara->RequestedIssuancePolicy);
2693 TRACE_(chain)("%d\n", pChainPara->dwUrlRetrievalTimeout);
2694 TRACE_(chain)("%d\n", pChainPara->fCheckRevocationFreshnessTime);
2695 TRACE_(chain)("%d\n", pChainPara->dwRevocationFreshnessTime);
2696 }
2697 }
2698
2699 BOOL WINAPI CertGetCertificateChain(HCERTCHAINENGINE hChainEngine,
2700 PCCERT_CONTEXT pCertContext, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
2701 PCERT_CHAIN_PARA pChainPara, DWORD dwFlags, LPVOID pvReserved,
2702 PCCERT_CHAIN_CONTEXT* ppChainContext)
2703 {
2704 BOOL ret;
2705 PCertificateChain chain = NULL;
2706
2707 TRACE("(%p, %p, %p, %p, %p, %08x, %p, %p)\n", hChainEngine, pCertContext,
2708 pTime, hAdditionalStore, pChainPara, dwFlags, pvReserved, ppChainContext);
2709
2710 if (ppChainContext)
2711 *ppChainContext = NULL;
2712 if (!pChainPara)
2713 {
2714 SetLastError(E_INVALIDARG);
2715 return FALSE;
2716 }
2717 if (!pCertContext->pCertInfo->SignatureAlgorithm.pszObjId)
2718 {
2719 SetLastError(ERROR_INVALID_DATA);
2720 return FALSE;
2721 }
2722
2723 if (!hChainEngine)
2724 hChainEngine = CRYPT_GetDefaultChainEngine();
2725 if (TRACE_ON(chain))
2726 dump_chain_para(pChainPara);
2727 /* FIXME: what about HCCE_LOCAL_MACHINE? */
2728 ret = CRYPT_BuildCandidateChainFromCert(hChainEngine, pCertContext, pTime,
2729 hAdditionalStore, &chain);
2730 if (ret)
2731 {
2732 PCertificateChain alternate = NULL;
2733 PCERT_CHAIN_CONTEXT pChain;
2734
2735 do {
2736 alternate = CRYPT_BuildAlternateContextFromChain(hChainEngine,
2737 pTime, hAdditionalStore, chain);
2738
2739 /* Alternate contexts are added as "lower quality" contexts of
2740 * chain, to avoid loops in alternate chain creation.
2741 * The highest-quality chain is chosen at the end.
2742 */
2743 if (alternate)
2744 ret = CRYPT_AddAlternateChainToChain(chain, alternate);
2745 } while (ret && alternate);
2746 chain = CRYPT_ChooseHighestQualityChain(chain);
2747 if (!(dwFlags & CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS))
2748 CRYPT_FreeLowerQualityChains(chain);
2749 pChain = (PCERT_CHAIN_CONTEXT)chain;
2750 if (!pChain->TrustStatus.dwErrorStatus)
2751 CRYPT_VerifyChainRevocation(pChain, pTime, pChainPara, dwFlags);
2752 CRYPT_CheckUsages(pChain, pChainPara);
2753 TRACE_(chain)("error status: %08x\n",
2754 pChain->TrustStatus.dwErrorStatus);
2755 if (ppChainContext)
2756 *ppChainContext = pChain;
2757 else
2758 CertFreeCertificateChain(pChain);
2759 }
2760 TRACE("returning %d\n", ret);
2761 return ret;
2762 }
2763
2764 PCCERT_CHAIN_CONTEXT WINAPI CertDuplicateCertificateChain(
2765 PCCERT_CHAIN_CONTEXT pChainContext)
2766 {
2767 PCertificateChain chain = (PCertificateChain)pChainContext;
2768
2769 TRACE("(%p)\n", pChainContext);
2770
2771 if (chain)
2772 InterlockedIncrement(&chain->ref);
2773 return pChainContext;
2774 }
2775
2776 VOID WINAPI CertFreeCertificateChain(PCCERT_CHAIN_CONTEXT pChainContext)
2777 {
2778 PCertificateChain chain = (PCertificateChain)pChainContext;
2779
2780 TRACE("(%p)\n", pChainContext);
2781
2782 if (chain)
2783 {
2784 if (InterlockedDecrement(&chain->ref) == 0)
2785 CRYPT_FreeChainContext(chain);
2786 }
2787 }
2788
2789 static void find_element_with_error(PCCERT_CHAIN_CONTEXT chain, DWORD error,
2790 LONG *iChain, LONG *iElement)
2791 {
2792 DWORD i, j;
2793
2794 for (i = 0; i < chain->cChain; i++)
2795 for (j = 0; j < chain->rgpChain[i]->cElement; j++)
2796 if (chain->rgpChain[i]->rgpElement[j]->TrustStatus.dwErrorStatus &
2797 error)
2798 {
2799 *iChain = i;
2800 *iElement = j;
2801 return;
2802 }
2803 }
2804
2805 static BOOL WINAPI verify_base_policy(LPCSTR szPolicyOID,
2806 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2807 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2808 {
2809 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2810 if (pChainContext->TrustStatus.dwErrorStatus &
2811 CERT_TRUST_IS_NOT_SIGNATURE_VALID)
2812 {
2813 pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
2814 find_element_with_error(pChainContext,
2815 CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
2816 &pPolicyStatus->lElementIndex);
2817 }
2818 else if (pChainContext->TrustStatus.dwErrorStatus &
2819 CERT_TRUST_IS_UNTRUSTED_ROOT)
2820 {
2821 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
2822 find_element_with_error(pChainContext,
2823 CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
2824 &pPolicyStatus->lElementIndex);
2825 }
2826 else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
2827 {
2828 pPolicyStatus->dwError = CERT_E_CHAINING;
2829 find_element_with_error(pChainContext, CERT_TRUST_IS_CYCLIC,
2830 &pPolicyStatus->lChainIndex, &pPolicyStatus->lElementIndex);
2831 /* For a cyclic chain, which element is a cycle isn't meaningful */
2832 pPolicyStatus->lElementIndex = -1;
2833 }
2834 else
2835 pPolicyStatus->dwError = NO_ERROR;
2836 return TRUE;
2837 }
2838
2839 static BYTE msTestPubKey1[] = {
2840 0x30,0x47,0x02,0x40,0x81,0x55,0x22,0xb9,0x8a,0xa4,0x6f,0xed,0xd6,0xe7,0xd9,
2841 0x66,0x0f,0x55,0xbc,0xd7,0xcd,0xd5,0xbc,0x4e,0x40,0x02,0x21,0xa2,0xb1,0xf7,
2842 0x87,0x30,0x85,0x5e,0xd2,0xf2,0x44,0xb9,0xdc,0x9b,0x75,0xb6,0xfb,0x46,0x5f,
2843 0x42,0xb6,0x9d,0x23,0x36,0x0b,0xde,0x54,0x0f,0xcd,0xbd,0x1f,0x99,0x2a,0x10,
2844 0x58,0x11,0xcb,0x40,0xcb,0xb5,0xa7,0x41,0x02,0x03,0x01,0x00,0x01 };
2845 static BYTE msTestPubKey2[] = {
2846 0x30,0x47,0x02,0x40,0x9c,0x50,0x05,0x1d,0xe2,0x0e,0x4c,0x53,0xd8,0xd9,0xb5,
2847 0xe5,0xfd,0xe9,0xe3,0xad,0x83,0x4b,0x80,0x08,0xd9,0xdc,0xe8,0xe8,0x35,0xf8,
2848 0x11,0xf1,0xe9,0x9b,0x03,0x7a,0x65,0x64,0x76,0x35,0xce,0x38,0x2c,0xf2,0xb6,
2849 0x71,0x9e,0x06,0xd9,0xbf,0xbb,0x31,0x69,0xa3,0xf6,0x30,0xa0,0x78,0x7b,0x18,
2850 0xdd,0x50,0x4d,0x79,0x1e,0xeb,0x61,0xc1,0x02,0x03,0x01,0x00,0x01 };
2851
2852 static BOOL WINAPI verify_authenticode_policy(LPCSTR szPolicyOID,
2853 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2854 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2855 {
2856 BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
2857 pPolicyStatus);
2858
2859 if (ret && pPolicyStatus->dwError == CERT_E_UNTRUSTEDROOT)
2860 {
2861 CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
2862 BOOL isMSTestRoot = FALSE;
2863 PCCERT_CONTEXT failingCert =
2864 pChainContext->rgpChain[pPolicyStatus->lChainIndex]->
2865 rgpElement[pPolicyStatus->lElementIndex]->pCertContext;
2866 DWORD i;
2867 CRYPT_DATA_BLOB keyBlobs[] = {
2868 { sizeof(msTestPubKey1), msTestPubKey1 },
2869 { sizeof(msTestPubKey2), msTestPubKey2 },
2870 };
2871
2872 /* Check whether the root is an MS test root */
2873 for (i = 0; !isMSTestRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
2874 i++)
2875 {
2876 msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
2877 msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
2878 if (CertComparePublicKeyInfo(
2879 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
2880 &failingCert->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
2881 isMSTestRoot = TRUE;
2882 }
2883 if (isMSTestRoot)
2884 pPolicyStatus->dwError = CERT_E_UNTRUSTEDTESTROOT;
2885 }
2886 return ret;
2887 }
2888
2889 static BOOL WINAPI verify_basic_constraints_policy(LPCSTR szPolicyOID,
2890 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2891 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2892 {
2893 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2894 if (pChainContext->TrustStatus.dwErrorStatus &
2895 CERT_TRUST_INVALID_BASIC_CONSTRAINTS)
2896 {
2897 pPolicyStatus->dwError = TRUST_E_BASIC_CONSTRAINTS;
2898 find_element_with_error(pChainContext,
2899 CERT_TRUST_INVALID_BASIC_CONSTRAINTS, &pPolicyStatus->lChainIndex,
2900 &pPolicyStatus->lElementIndex);
2901 }
2902 else
2903 pPolicyStatus->dwError = NO_ERROR;
2904 return TRUE;
2905 }
2906
2907 static BOOL match_dns_to_subject_alt_name(PCERT_EXTENSION ext,
2908 LPCWSTR server_name)
2909 {
2910 BOOL matches = FALSE;
2911 CERT_ALT_NAME_INFO *subjectName;
2912 DWORD size;
2913
2914 TRACE_(chain)("%s\n", debugstr_w(server_name));
2915 /* This could be spoofed by the embedded NULL vulnerability, since the
2916 * returned CERT_ALT_NAME_INFO doesn't have a way to indicate the
2917 * encoded length of a name. Fortunately CryptDecodeObjectEx fails if
2918 * the encoded form of the name contains a NULL.
2919 */
2920 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
2921 ext->Value.pbData, ext->Value.cbData,
2922 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2923 &subjectName, &size))
2924 {
2925 DWORD i;
2926
2927 /* RFC 5280 states that multiple instances of each name type may exist,
2928 * in section 4.2.1.6:
2929 * "Multiple name forms, and multiple instances of each name form,
2930 * MAY be included."
2931 * It doesn't specify the behavior in such cases, but both RFC 2818
2932 * and RFC 2595 explicitly accept a certificate if any name matches.
2933 */
2934 for (i = 0; !matches && i < subjectName->cAltEntry; i++)
2935 {
2936 if (subjectName->rgAltEntry[i].dwAltNameChoice ==
2937 CERT_ALT_NAME_DNS_NAME)
2938 {
2939 TRACE_(chain)("dNSName: %s\n", debugstr_w(
2940 subjectName->rgAltEntry[i].u.pwszDNSName));
2941 if (!strcmpiW(server_name,
2942 subjectName->rgAltEntry[i].u.pwszDNSName))
2943 matches = TRUE;
2944 }
2945 }
2946 LocalFree(subjectName);
2947 }
2948 return matches;
2949 }
2950
2951 static BOOL find_matching_domain_component(CERT_NAME_INFO *name,
2952 LPCWSTR component)
2953 {
2954 BOOL matches = FALSE;
2955 DWORD i, j;
2956
2957 for (i = 0; !matches && i < name->cRDN; i++)
2958 for (j = 0; j < name->rgRDN[i].cRDNAttr; j++)
2959 if (!strcmp(szOID_DOMAIN_COMPONENT,
2960 name->rgRDN[i].rgRDNAttr[j].pszObjId))
2961 {
2962 PCERT_RDN_ATTR attr;
2963
2964 attr = &name->rgRDN[i].rgRDNAttr[j];
2965 /* Compare with memicmpW rather than strcmpiW in order to avoid
2966 * a match with a string with an embedded NULL. The component
2967 * must match one domain component attribute's entire string
2968 * value with a case-insensitive match.
2969 */
2970 matches = !memicmpW(component, (LPWSTR)attr->Value.pbData,
2971 attr->Value.cbData / sizeof(WCHAR));
2972 }
2973 return matches;
2974 }
2975
2976 static BOOL match_domain_component(LPCWSTR allowed_component, DWORD allowed_len,
2977 LPCWSTR server_component, DWORD server_len, BOOL allow_wildcards,
2978 BOOL *see_wildcard)
2979 {
2980 LPCWSTR allowed_ptr, server_ptr;
2981 BOOL matches = TRUE;
2982
2983 *see_wildcard = FALSE;
2984 if (server_len < allowed_len)
2985 {
2986 WARN_(chain)("domain component %s too short for %s\n",
2987 debugstr_wn(server_component, server_len),
2988 debugstr_wn(allowed_component, allowed_len));
2989 /* A domain component can't contain a wildcard character, so a domain
2990 * component shorter than the allowed string can't produce a match.
2991 */
2992 return FALSE;
2993 }
2994 for (allowed_ptr = allowed_component, server_ptr = server_component;
2995 matches && allowed_ptr - allowed_component < allowed_len;
2996 allowed_ptr++, server_ptr++)
2997 {
2998 if (*allowed_ptr == '*')
2999 {
3000 if (allowed_ptr - allowed_component < allowed_len - 1)
3001 {
3002 WARN_(chain)("non-wildcard characters after wildcard not supported\n");
3003 matches = FALSE;
3004 }
3005 else if (!allow_wildcards)
3006 {
3007 WARN_(chain)("wildcard after non-wildcard component\n");
3008 matches = FALSE;
3009 }
3010 else
3011 {
3012 /* the preceding characters must have matched, so the rest of
3013 * the component also matches.
3014 */
3015 *see_wildcard = TRUE;
3016 break;
3017 }
3018 }
3019 matches = tolowerW(*allowed_ptr) == tolowerW(*server_ptr);
3020 }
3021 if (matches && server_ptr - server_component < server_len)
3022 {
3023 /* If there are unmatched characters in the server domain component,
3024 * the server domain only matches if the allowed string ended in a '*'.
3025 */
3026 matches = *allowed_ptr == '*';
3027 }
3028 return matches;
3029 }
3030
3031 static BOOL match_common_name(LPCWSTR server_name, PCERT_RDN_ATTR nameAttr)
3032 {
3033 LPCWSTR allowed = (LPCWSTR)nameAttr->Value.pbData;
3034 LPCWSTR allowed_component = allowed;
3035 DWORD allowed_len = nameAttr->Value.cbData / sizeof(WCHAR);
3036 LPCWSTR server_component = server_name;
3037 DWORD server_len = strlenW(server_name);
3038 BOOL matches = TRUE, allow_wildcards = TRUE;
3039
3040 TRACE_(chain)("CN = %s\n", debugstr_wn(allowed_component, allowed_len));
3041
3042 /* From RFC 2818 (HTTP over TLS), section 3.1:
3043 * "Names may contain the wildcard character * which is considered to match
3044 * any single domain name component or component fragment. E.g.,
3045 * *.a.com matches foo.a.com but not bar.foo.a.com. f*.com matches foo.com
3046 * but not bar.com."
3047 *
3048 * And from RFC 2595 (Using TLS with IMAP, POP3 and ACAP), section 2.4:
3049 * "A "*" wildcard character MAY be used as the left-most name component in
3050 * the certificate. For example, *.example.com would match a.example.com,
3051 * foo.example.com, etc. but would not match example.com."
3052 *
3053 * There are other protocols which use TLS, and none of them is
3054 * authoritative. This accepts certificates in common usage, e.g.
3055 * *.domain.com matches www.domain.com but not domain.com, and
3056 * www*.domain.com matches www1.domain.com but not mail.domain.com.
3057 */
3058 do {
3059 LPCWSTR allowed_dot, server_dot;
3060
3061 allowed_dot = memchrW(allowed_component, '.',
3062 allowed_len - (allowed_component - allowed));
3063 server_dot = memchrW(server_component, '.',
3064 server_len - (server_component - server_name));
3065 /* The number of components must match */
3066 if ((!allowed_dot && server_dot) || (allowed_dot && !server_dot))
3067 {
3068 if (!allowed_dot)
3069 WARN_(chain)("%s: too many components for CN=%s\n",
3070 debugstr_w(server_name), debugstr_wn(allowed, allowed_len));
3071 else
3072 WARN_(chain)("%s: not enough components for CN=%s\n",
3073 debugstr_w(server_name), debugstr_wn(allowed, allowed_len));
3074 matches = FALSE;
3075 }
3076 else
3077 {
3078 LPCWSTR allowed_end, server_end;
3079 BOOL has_wildcard;
3080
3081 allowed_end = allowed_dot ? allowed_dot : allowed + allowed_len;
3082 server_end = server_dot ? server_dot : server_name + server_len;
3083 matches = match_domain_component(allowed_component,
3084 allowed_end - allowed_component, server_component,
3085 server_end - server_component, allow_wildcards, &has_wildcard);
3086 /* Once a non-wildcard component is seen, no wildcard components
3087 * may follow
3088 */
3089 if (!has_wildcard)
3090 allow_wildcards = FALSE;
3091 if (matches)
3092 {
3093 allowed_component = allowed_dot ? allowed_dot + 1 : allowed_end;
3094 server_component = server_dot ? server_dot + 1 : server_end;
3095 }
3096 }
3097 } while (matches && allowed_component &&
3098 allowed_component - allowed < allowed_len &&
3099 server_component && server_component - server_name < server_len);
3100 TRACE_(chain)("returning %d\n", matches);
3101 return matches;
3102 }
3103
3104 static BOOL match_dns_to_subject_dn(PCCERT_CONTEXT cert, LPCWSTR server_name)
3105 {
3106 BOOL matches = FALSE;
3107 CERT_NAME_INFO *name;
3108 DWORD size;
3109
3110 TRACE_(chain)("%s\n", debugstr_w(server_name));
3111 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_UNICODE_NAME,
3112 cert->pCertInfo->Subject.pbData, cert->pCertInfo->Subject.cbData,
3113 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
3114 &name, &size))
3115 {
3116 /* If the subject distinguished name contains any name components,
3117 * make sure all of them are present.
3118 */
3119 if (CertFindRDNAttr(szOID_DOMAIN_COMPONENT, name))
3120 {
3121 LPCWSTR ptr = server_name;
3122
3123 matches = TRUE;
3124 do {
3125 LPCWSTR dot = strchrW(ptr, '.'), end;
3126 /* 254 is the maximum DNS label length, see RFC 1035 */
3127 WCHAR component[255];
3128 DWORD len;
3129
3130 end = dot ? dot : ptr + strlenW(ptr);
3131 len = end - ptr;
3132 if (len >= sizeof(component) / sizeof(component[0]))
3133 {
3134 WARN_(chain)("domain component %s too long\n",
3135 debugstr_wn(ptr, len));
3136 matches = FALSE;
3137 }
3138 else
3139 {
3140 memcpy(component, ptr, len * sizeof(WCHAR));
3141 component[len] = 0;
3142 matches = find_matching_domain_component(name, component);
3143 }
3144 ptr = dot ? dot + 1 : end;
3145 } while (matches && ptr && *ptr);
3146 }
3147 else
3148 {
3149 PCERT_RDN_ATTR attr;
3150
3151 /* If the certificate isn't using a DN attribute in the name, make
3152 * make sure the common name matches.
3153 */
3154 if ((attr = CertFindRDNAttr(szOID_COMMON_NAME, name)))
3155 matches = match_common_name(server_name, attr);
3156 }
3157 LocalFree(name);
3158 }
3159 return matches;
3160 }
3161
3162 static BOOL WINAPI verify_ssl_policy(LPCSTR szPolicyOID,
3163 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3164 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
3165 {
3166 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
3167 if (pChainContext->TrustStatus.dwErrorStatus &
3168 CERT_TRUST_IS_NOT_SIGNATURE_VALID)
3169 {
3170 pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
3171 find_element_with_error(pChainContext,
3172 CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
3173 &pPolicyStatus->lElementIndex);
3174 }
3175 else if (pChainContext->TrustStatus.dwErrorStatus &
3176 CERT_TRUST_IS_UNTRUSTED_ROOT)
3177 {
3178 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
3179 find_element_with_error(pChainContext,
3180 CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
3181 &pPolicyStatus->lElementIndex);
3182 }
3183 else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
3184 {
3185 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
3186 find_element_with_error(pChainContext,
3187 CERT_TRUST_IS_CYCLIC, &pPolicyStatus->lChainIndex,
3188 &pPolicyStatus->lElementIndex);
3189 /* For a cyclic chain, which element is a cycle isn't meaningful */
3190 pPolicyStatus->lElementIndex = -1;
3191 }
3192 else if (pChainContext->TrustStatus.dwErrorStatus &
3193 CERT_TRUST_IS_NOT_TIME_VALID)
3194 {
3195 pPolicyStatus->dwError = CERT_E_EXPIRED;
3196 find_element_with_error(pChainContext,
3197 CERT_TRUST_IS_NOT_TIME_VALID, &pPolicyStatus->lChainIndex,
3198 &pPolicyStatus->lElementIndex);
3199 }
3200 else
3201 pPolicyStatus->dwError = NO_ERROR;
3202 /* We only need bother checking whether the name in the end certificate
3203 * matches if the chain is otherwise okay.
3204 */
3205 if (!pPolicyStatus->dwError && pPolicyPara &&
3206 pPolicyPara->cbSize >= sizeof(CERT_CHAIN_POLICY_PARA))
3207 {
3208 HTTPSPolicyCallbackData *sslPara = pPolicyPara->pvExtraPolicyPara;
3209
3210 if (sslPara && sslPara->u.cbSize >= sizeof(HTTPSPolicyCallbackData))
3211 {
3212 if (sslPara->dwAuthType == AUTHTYPE_SERVER &&
3213 sslPara->pwszServerName)
3214 {
3215 PCCERT_CONTEXT cert;
3216 PCERT_EXTENSION altNameExt;
3217 BOOL matches;
3218
3219 cert = pChainContext->rgpChain[0]->rgpElement[0]->pCertContext;
3220 altNameExt = get_subject_alt_name_ext(cert->pCertInfo);
3221 /* If the alternate name extension exists, the name it contains
3222 * is bound to the certificate, so make sure the name matches
3223 * it. Otherwise, look for the server name in the subject
3224 * distinguished name. RFC5280, section 4.2.1.6:
3225 * "Whenever such identities are to be bound into a
3226 * certificate, the subject alternative name (or issuer
3227 * alternative name) extension MUST be used; however, a DNS
3228 * name MAY also be represented in the subject field using the
3229 * domainComponent attribute."
3230 */
3231 if (altNameExt)
3232 matches = match_dns_to_subject_alt_name(altNameExt,
3233 sslPara->pwszServerName);
3234 else
3235 matches = match_dns_to_subject_dn(cert,
3236 sslPara->pwszServerName);
3237 if (!matches)
3238 {
3239 pPolicyStatus->dwError = CERT_E_CN_NO_MATCH;
3240 pPolicyStatus->lChainIndex = 0;
3241 pPolicyStatus->lElementIndex = 0;
3242 }
3243 }
3244 }
3245 }
3246 return TRUE;
3247 }
3248
3249 static BYTE msPubKey1[] = {
3250 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xdf,0x08,0xba,0xe3,0x3f,0x6e,
3251 0x64,0x9b,0xf5,0x89,0xaf,0x28,0x96,0x4a,0x07,0x8f,0x1b,0x2e,0x8b,0x3e,0x1d,
3252 0xfc,0xb8,0x80,0x69,0xa3,0xa1,0xce,0xdb,0xdf,0xb0,0x8e,0x6c,0x89,0x76,0x29,
3253 0x4f,0xca,0x60,0x35,0x39,0xad,0x72,0x32,0xe0,0x0b,0xae,0x29,0x3d,0x4c,0x16,
3254 0xd9,0x4b,0x3c,0x9d,0xda,0xc5,0xd3,0xd1,0x09,0xc9,0x2c,0x6f,0xa6,0xc2,0x60,
3255 0x53,0x45,0xdd,0x4b,0xd1,0x55,0xcd,0x03,0x1c,0xd2,0x59,0x56,0x24,0xf3,0xe5,
3256 0x78,0xd8,0x07,0xcc,0xd8,0xb3,0x1f,0x90,0x3f,0xc0,0x1a,0x71,0x50,0x1d,0x2d,
3257 0xa7,0x12,0x08,0x6d,0x7c,0xb0,0x86,0x6c,0xc7,0xba,0x85,0x32,0x07,0xe1,0x61,
3258 0x6f,0xaf,0x03,0xc5,0x6d,0xe5,0xd6,0xa1,0x8f,0x36,0xf6,0xc1,0x0b,0xd1,0x3e,
3259 0x69,0x97,0x48,0x72,0xc9,0x7f,0xa4,0xc8,0xc2,0x4a,0x4c,0x7e,0xa1,0xd1,0x94,
3260 0xa6,0xd7,0xdc,0xeb,0x05,0x46,0x2e,0xb8,0x18,0xb4,0x57,0x1d,0x86,0x49,0xdb,
3261 0x69,0x4a,0x2c,0x21,0xf5,0x5e,0x0f,0x54,0x2d,0x5a,0x43,0xa9,0x7a,0x7e,0x6a,
3262 0x8e,0x50,0x4d,0x25,0x57,0xa1,0xbf,0x1b,0x15,0x05,0x43,0x7b,0x2c,0x05,0x8d,
3263 0xbd,0x3d,0x03,0x8c,0x93,0x22,0x7d,0x63,0xea,0x0a,0x57,0x05,0x06,0x0a,0xdb,
3264 0x61,0x98,0x65,0x2d,0x47,0x49,0xa8,0xe7,0xe6,0x56,0x75,0x5c,0xb8,0x64,0x08,
3265 0x63,0xa9,0x30,0x40,0x66,0xb2,0xf9,0xb6,0xe3,0x34,0xe8,0x67,0x30,0xe1,0x43,
3266 0x0b,0x87,0xff,0xc9,0xbe,0x72,0x10,0x5e,0x23,0xf0,0x9b,0xa7,0x48,0x65,0xbf,
3267 0x09,0x88,0x7b,0xcd,0x72,0xbc,0x2e,0x79,0x9b,0x7b,0x02,0x03,0x01,0x00,0x01 };
3268 static BYTE msPubKey2[] = {
3269 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xa9,0x02,0xbd,0xc1,0x70,0xe6,
3270 0x3b,0xf2,0x4e,0x1b,0x28,0x9f,0x97,0x78,0x5e,0x30,0xea,0xa2,0xa9,0x8d,0x25,
3271 0x5f,0xf8,0xfe,0x95,0x4c,0xa3,0xb7,0xfe,0x9d,0xa2,0x20,0x3e,0x7c,0x51,0xa2,
3272 0x9b,0xa2,0x8f,0x60,0x32,0x6b,0xd1,0x42,0x64,0x79,0xee,0xac,0x76,0xc9,0x54,
3273 0xda,0xf2,0xeb,0x9c,0x86,0x1c,0x8f,0x9f,0x84,0x66,0xb3,0xc5,0x6b,0x7a,0x62,
3274 0x23,0xd6,0x1d,0x3c,0xde,0x0f,0x01,0x92,0xe8,0x96,0xc4,0xbf,0x2d,0x66,0x9a,
3275 0x9a,0x68,0x26,0x99,0xd0,0x3a,0x2c,0xbf,0x0c,0xb5,0x58,0x26,0xc1,0x46,0xe7,
3276 0x0a,0x3e,0x38,0x96,0x2c,0xa9,0x28,0x39,0xa8,0xec,0x49,0x83,0x42,0xe3,0x84,
3277 0x0f,0xbb,0x9a,0x6c,0x55,0x61,0xac,0x82,0x7c,0xa1,0x60,0x2d,0x77,0x4c,0xe9,
3278 0x99,0xb4,0x64,0x3b,0x9a,0x50,0x1c,0x31,0x08,0x24,0x14,0x9f,0xa9,0xe7,0x91,
3279 0x2b,0x18,0xe6,0x3d,0x98,0x63,0x14,0x60,0x58,0x05,0x65,0x9f,0x1d,0x37,0x52,
3280 0x87,0xf7,0xa7,0xef,0x94,0x02,0xc6,0x1b,0xd3,0xbf,0x55,0x45,0xb3,0x89,0x80,
3281 0xbf,0x3a,0xec,0x54,0x94,0x4e,0xae,0xfd,0xa7,0x7a,0x6d,0x74,0x4e,0xaf,0x18,
3282 0xcc,0x96,0x09,0x28,0x21,0x00,0x57,0x90,0x60,0x69,0x37,0xbb,0x4b,0x12,0x07,
3283 0x3c,0x56,0xff,0x5b,0xfb,0xa4,0x66,0x0a,0x08,0xa6,0xd2,0x81,0x56,0x57,0xef,
3284 0xb6,0x3b,0x5e,0x16,0x81,0x77,0x04,0xda,0xf6,0xbe,0xae,0x80,0x95,0xfe,0xb0,
3285 0xcd,0x7f,0xd6,0xa7,0x1a,0x72,0x5c,0x3c,0xca,0xbc,0xf0,0x08,0xa3,0x22,0x30,
3286 0xb3,0x06,0x85,0xc9,0xb3,0x20,0x77,0x13,0x85,0xdf,0x02,0x03,0x01,0x00,0x01 };
3287 static BYTE msPubKey3[] = {
3288 0x30,0x82,0x02,0x0a,0x02,0x82,0x02,0x01,0x00,0xf3,0x5d,0xfa,0x80,0x67,0xd4,
3289 0x5a,0xa7,0xa9,0x0c,0x2c,0x90,0x20,0xd0,0x35,0x08,0x3c,0x75,0x84,0xcd,0xb7,
3290 0x07,0x89,0x9c,0x89,0xda,0xde,0xce,0xc3,0x60,0xfa,0x91,0x68,0x5a,0x9e,0x94,
3291 0x71,0x29,0x18,0x76,0x7c,0xc2,0xe0,0xc8,0x25,0x76,0x94,0x0e,0x58,0xfa,0x04,
3292 0x34,0x36,0xe6,0xdf,0xaf,0xf7,0x80,0xba,0xe9,0x58,0x0b,0x2b,0x93,0xe5,0x9d,
3293 0x05,0xe3,0x77,0x22,0x91,0xf7,0x34,0x64,0x3c,0x22,0x91,0x1d,0x5e,0xe1,0x09,
3294 0x90,0xbc,0x14,0xfe,0xfc,0x75,0x58,0x19,0xe1,0x79,0xb7,0x07,0x92,0xa3,0xae,
3295 0x88,0x59,0x08,0xd8,0x9f,0x07,0xca,0x03,0x58,0xfc,0x68,0x29,0x6d,0x32,0xd7,
3296 0xd2,0xa8,0xcb,0x4b,0xfc,0xe1,0x0b,0x48,0x32,0x4f,0xe6,0xeb,0xb8,0xad,0x4f,
3297 0xe4,0x5c,0x6f,0x13,0x94,0x99,0xdb,0x95,0xd5,0x75,0xdb,0xa8,0x1a,0xb7,0x94,
3298 0x91,0xb4,0x77,0x5b,0xf5,0x48,0x0c,0x8f,0x6a,0x79,0x7d,0x14,0x70,0x04,0x7d,
3299 0x6d,0xaf,0x90,0xf5,0xda,0x70,0xd8,0x47,0xb7,0xbf,0x9b,0x2f,0x6c,0xe7,0x05,
3300 0xb7,0xe1,0x11,0x60,0xac,0x79,0x91,0x14,0x7c,0xc5,0xd6,0xa6,0xe4,0xe1,0x7e,
3301 0xd5,0xc3,0x7e,0xe5,0x92,0xd2,0x3c,0x00,0xb5,0x36,0x82,0xde,0x79,0xe1,0x6d,
3302 0xf3,0xb5,0x6e,0xf8,0x9f,0x33,0xc9,0xcb,0x52,0x7d,0x73,0x98,0x36,0xdb,0x8b,
3303 0xa1,0x6b,0xa2,0x95,0x97,0x9b,0xa3,0xde,0xc2,0x4d,0x26,0xff,0x06,0x96,0x67,
3304 0x25,0x06,0xc8,0xe7,0xac,0xe4,0xee,0x12,0x33,0x95,0x31,0x99,0xc8,0x35,0x08,
3305 0x4e,0x34,0xca,0x79,0x53,0xd5,0xb5,0xbe,0x63,0x32,0x59,0x40,0x36,0xc0,0xa5,
3306 0x4e,0x04,0x4d,0x3d,0xdb,0x5b,0x07,0x33,0xe4,0x58,0xbf,0xef,0x3f,0x53,0x64,
3307 0xd8,0x42,0x59,0x35,0x57,0xfd,0x0f,0x45,0x7c,0x24,0x04,0x4d,0x9e,0xd6,0x38,
3308 0x74,0x11,0x97,0x22,0x90,0xce,0x68,0x44,0x74,0x92,0x6f,0xd5,0x4b,0x6f,0xb0,
3309 0x86,0xe3,0xc7,0x36,0x42,0xa0,0xd0,0xfc,0xc1,0xc0,0x5a,0xf9,0xa3,0x61,0xb9,
3310 0x30,0x47,0x71,0x96,0x0a,0x16,0xb0,0x91,0xc0,0x42,0x95,0xef,0x10,0x7f,0x28,
3311 0x6a,0xe3,0x2a,0x1f,0xb1,0xe4,0xcd,0x03,0x3f,0x77,0x71,0x04,0xc7,0x20,0xfc,
3312 0x49,0x0f,0x1d,0x45,0x88,0xa4,0xd7,0xcb,0x7e,0x88,0xad,0x8e,0x2d,0xec,0x45,
3313 0xdb,0xc4,0x51,0x04,0xc9,0x2a,0xfc,0xec,0x86,0x9e,0x9a,0x11,0x97,0x5b,0xde,
3314 0xce,0x53,0x88,0xe6,0xe2,0xb7,0xfd,0xac,0x95,0xc2,0x28,0x40,0xdb,0xef,0x04,
3315 0x90,0xdf,0x81,0x33,0x39,0xd9,0xb2,0x45,0xa5,0x23,0x87,0x06,0xa5,0x55,0x89,
3316 0x31,0xbb,0x06,0x2d,0x60,0x0e,0x41,0x18,0x7d,0x1f,0x2e,0xb5,0x97,0xcb,0x11,
3317 0xeb,0x15,0xd5,0x24,0xa5,0x94,0xef,0x15,0x14,0x89,0xfd,0x4b,0x73,0xfa,0x32,
3318 0x5b,0xfc,0xd1,0x33,0x00,0xf9,0x59,0x62,0x70,0x07,0x32,0xea,0x2e,0xab,0x40,
3319 0x2d,0x7b,0xca,0xdd,0x21,0x67,0x1b,0x30,0x99,0x8f,0x16,0xaa,0x23,0xa8,0x41,
3320 0xd1,0xb0,0x6e,0x11,0x9b,0x36,0xc4,0xde,0x40,0x74,0x9c,0xe1,0x58,0x65,0xc1,
3321 0x60,0x1e,0x7a,0x5b,0x38,0xc8,0x8f,0xbb,0x04,0x26,0x7c,0xd4,0x16,0x40,0xe5,
3322 0xb6,0x6b,0x6c,0xaa,0x86,0xfd,0x00,0xbf,0xce,0xc1,0x35,0x02,0x03,0x01,0x00,
3323 0x01 };
3324
3325 static BOOL WINAPI verify_ms_root_policy(LPCSTR szPolicyOID,
3326 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3327 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
3328 {
3329 BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
3330 pPolicyStatus);
3331
3332 if (ret && !pPolicyStatus->dwError)
3333 {
3334 CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
3335 BOOL isMSRoot = FALSE;
3336 DWORD i;
3337 CRYPT_DATA_BLOB keyBlobs[] = {
3338 { sizeof(msPubKey1), msPubKey1 },
3339 { sizeof(msPubKey2), msPubKey2 },
3340 { sizeof(msPubKey3), msPubKey3 },
3341 };
3342 PCERT_SIMPLE_CHAIN rootChain =
3343 pChainContext->rgpChain[pChainContext->cChain -1 ];
3344 PCCERT_CONTEXT root =
3345 rootChain->rgpElement[rootChain->cElement - 1]->pCertContext;
3346
3347 for (i = 0; !isMSRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
3348 i++)
3349 {
3350 msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
3351 msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
3352 if (CertComparePublicKeyInfo(
3353 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
3354 &root->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
3355 isMSRoot = TRUE;
3356 }
3357 if (isMSRoot)
3358 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = 0;
3359 }
3360 return ret;
3361 }
3362
3363 typedef BOOL (WINAPI *CertVerifyCertificateChainPolicyFunc)(LPCSTR szPolicyOID,
3364 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3365 PCERT_CHAIN_POLICY_STATUS pPolicyStatus);
3366
3367 BOOL WINAPI CertVerifyCertificateChainPolicy(LPCSTR szPolicyOID,
3368 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
3369 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
3370 {
3371 static HCRYPTOIDFUNCSET set = NULL;
3372 BOOL ret = FALSE;
3373 CertVerifyCertificateChainPolicyFunc verifyPolicy = NULL;
3374 HCRYPTOIDFUNCADDR hFunc = NULL;
3375
3376 TRACE("(%s, %p, %p, %p)\n", debugstr_a(szPolicyOID), pChainContext,
3377 pPolicyPara, pPolicyStatus);
3378
3379 if (!HIWORD(szPolicyOID))
3380 {
3381 switch (LOWORD(szPolicyOID))
3382 {
3383 case LOWORD(CERT_CHAIN_POLICY_BASE):
3384 verifyPolicy = verify_base_policy;
3385 break;
3386 case LOWORD(CERT_CHAIN_POLICY_AUTHENTICODE):
3387 verifyPolicy = verify_authenticode_policy;
3388 break;
3389 case LOWORD(CERT_CHAIN_POLICY_SSL):
3390 verifyPolicy = verify_ssl_policy;
3391 break;
3392 case LOWORD(CERT_CHAIN_POLICY_BASIC_CONSTRAINTS):
3393 verifyPolicy = verify_basic_constraints_policy;
3394 break;
3395 case LOWORD(CERT_CHAIN_POLICY_MICROSOFT_ROOT):
3396 verifyPolicy = verify_ms_root_policy;
3397 break;
3398 default:
3399 FIXME("unimplemented for %d\n", LOWORD(szPolicyOID));
3400 }
3401 }
3402 if (!verifyPolicy)
3403 {
3404 if (!set)
3405 set = CryptInitOIDFunctionSet(
3406 CRYPT_OID_VERIFY_CERTIFICATE_CHAIN_POLICY_FUNC, 0);
3407 CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING, szPolicyOID, 0,
3408 (void **)&verifyPolicy, &hFunc);
3409 }
3410 if (verifyPolicy)
3411 ret = verifyPolicy(szPolicyOID, pChainContext, pPolicyPara,
3412 pPolicyStatus);
3413 if (hFunc)
3414 CryptFreeOIDFunctionAddress(hFunc, 0);
3415 TRACE("returning %d (%08x)\n", ret, pPolicyStatus->dwError);
3416 return ret;
3417 }