Sync to trunk (r44371)
[reactos.git] / reactos / 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 inline BOOL CRYPT_IsCertificateSelfSigned(PCCERT_CONTEXT cert)
234 {
235 return CertCompareCertificateName(cert->dwCertEncodingType,
236 &cert->pCertInfo->Subject, &cert->pCertInfo->Issuer);
237 }
238
239 static void CRYPT_FreeChainElement(PCERT_CHAIN_ELEMENT element)
240 {
241 CertFreeCertificateContext(element->pCertContext);
242 CryptMemFree(element);
243 }
244
245 static void CRYPT_CheckSimpleChainForCycles(PCERT_SIMPLE_CHAIN chain)
246 {
247 DWORD i, j, cyclicCertIndex = 0;
248
249 /* O(n^2) - I don't think there's a faster way */
250 for (i = 0; !cyclicCertIndex && i < chain->cElement; i++)
251 for (j = i + 1; !cyclicCertIndex && j < chain->cElement; j++)
252 if (CertCompareCertificate(X509_ASN_ENCODING,
253 chain->rgpElement[i]->pCertContext->pCertInfo,
254 chain->rgpElement[j]->pCertContext->pCertInfo))
255 cyclicCertIndex = j;
256 if (cyclicCertIndex)
257 {
258 chain->rgpElement[cyclicCertIndex]->TrustStatus.dwErrorStatus
259 |= CERT_TRUST_IS_CYCLIC | CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
260 /* Release remaining certs */
261 for (i = cyclicCertIndex + 1; i < chain->cElement; i++)
262 CRYPT_FreeChainElement(chain->rgpElement[i]);
263 /* Truncate chain */
264 chain->cElement = cyclicCertIndex + 1;
265 }
266 }
267
268 /* Checks whether the chain is cyclic by examining the last element's status */
269 static inline BOOL CRYPT_IsSimpleChainCyclic(const CERT_SIMPLE_CHAIN *chain)
270 {
271 if (chain->cElement)
272 return chain->rgpElement[chain->cElement - 1]->TrustStatus.dwErrorStatus
273 & CERT_TRUST_IS_CYCLIC;
274 else
275 return FALSE;
276 }
277
278 static inline void CRYPT_CombineTrustStatus(CERT_TRUST_STATUS *chainStatus,
279 const CERT_TRUST_STATUS *elementStatus)
280 {
281 /* Any error that applies to an element also applies to a chain.. */
282 chainStatus->dwErrorStatus |= elementStatus->dwErrorStatus;
283 /* but the bottom nibble of an element's info status doesn't apply to the
284 * chain.
285 */
286 chainStatus->dwInfoStatus |= (elementStatus->dwInfoStatus & 0xfffffff0);
287 }
288
289 static BOOL CRYPT_AddCertToSimpleChain(const CertificateChainEngine *engine,
290 PCERT_SIMPLE_CHAIN chain, PCCERT_CONTEXT cert, DWORD subjectInfoStatus)
291 {
292 BOOL ret = FALSE;
293 PCERT_CHAIN_ELEMENT element = CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
294
295 if (element)
296 {
297 if (!chain->cElement)
298 chain->rgpElement = CryptMemAlloc(sizeof(PCERT_CHAIN_ELEMENT));
299 else
300 chain->rgpElement = CryptMemRealloc(chain->rgpElement,
301 (chain->cElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
302 if (chain->rgpElement)
303 {
304 chain->rgpElement[chain->cElement++] = element;
305 memset(element, 0, sizeof(CERT_CHAIN_ELEMENT));
306 element->cbSize = sizeof(CERT_CHAIN_ELEMENT);
307 element->pCertContext = CertDuplicateCertificateContext(cert);
308 if (chain->cElement > 1)
309 chain->rgpElement[chain->cElement - 2]->TrustStatus.dwInfoStatus
310 = subjectInfoStatus;
311 /* FIXME: initialize the rest of element */
312 if (!(chain->cElement % engine->CycleDetectionModulus))
313 {
314 CRYPT_CheckSimpleChainForCycles(chain);
315 /* Reinitialize the element pointer in case the chain is
316 * cyclic, in which case the chain is truncated.
317 */
318 element = chain->rgpElement[chain->cElement - 1];
319 }
320 CRYPT_CombineTrustStatus(&chain->TrustStatus,
321 &element->TrustStatus);
322 ret = TRUE;
323 }
324 else
325 CryptMemFree(element);
326 }
327 return ret;
328 }
329
330 static void CRYPT_FreeSimpleChain(PCERT_SIMPLE_CHAIN chain)
331 {
332 DWORD i;
333
334 for (i = 0; i < chain->cElement; i++)
335 CRYPT_FreeChainElement(chain->rgpElement[i]);
336 CryptMemFree(chain->rgpElement);
337 CryptMemFree(chain);
338 }
339
340 static void CRYPT_CheckTrustedStatus(HCERTSTORE hRoot,
341 PCERT_CHAIN_ELEMENT rootElement)
342 {
343 PCCERT_CONTEXT trustedRoot = CRYPT_FindCertInStore(hRoot,
344 rootElement->pCertContext);
345
346 if (!trustedRoot)
347 rootElement->TrustStatus.dwErrorStatus |=
348 CERT_TRUST_IS_UNTRUSTED_ROOT;
349 else
350 CertFreeCertificateContext(trustedRoot);
351 }
352
353 static void CRYPT_CheckRootCert(HCERTCHAINENGINE hRoot,
354 PCERT_CHAIN_ELEMENT rootElement)
355 {
356 PCCERT_CONTEXT root = rootElement->pCertContext;
357
358 if (!CryptVerifyCertificateSignatureEx(0, root->dwCertEncodingType,
359 CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, (void *)root,
360 CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, (void *)root, 0, NULL))
361 {
362 TRACE_(chain)("Last certificate's signature is invalid\n");
363 rootElement->TrustStatus.dwErrorStatus |=
364 CERT_TRUST_IS_NOT_SIGNATURE_VALID;
365 }
366 CRYPT_CheckTrustedStatus(hRoot, rootElement);
367 }
368
369 /* Decodes a cert's basic constraints extension (either szOID_BASIC_CONSTRAINTS
370 * or szOID_BASIC_CONSTRAINTS2, whichever is present) into a
371 * CERT_BASIC_CONSTRAINTS2_INFO. If it neither extension is present, sets
372 * constraints->fCA to defaultIfNotSpecified.
373 * Returns FALSE if the extension is present but couldn't be decoded.
374 */
375 static BOOL CRYPT_DecodeBasicConstraints(PCCERT_CONTEXT cert,
376 CERT_BASIC_CONSTRAINTS2_INFO *constraints, BOOL defaultIfNotSpecified)
377 {
378 BOOL ret = TRUE;
379 PCERT_EXTENSION ext = CertFindExtension(szOID_BASIC_CONSTRAINTS,
380 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
381
382 constraints->fPathLenConstraint = FALSE;
383 if (ext)
384 {
385 CERT_BASIC_CONSTRAINTS_INFO *info;
386 DWORD size = 0;
387
388 ret = CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
389 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
390 NULL, &info, &size);
391 if (ret)
392 {
393 if (info->SubjectType.cbData == 1)
394 constraints->fCA =
395 info->SubjectType.pbData[0] & CERT_CA_SUBJECT_FLAG;
396 LocalFree(info);
397 }
398 }
399 else
400 {
401 ext = CertFindExtension(szOID_BASIC_CONSTRAINTS2,
402 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
403 if (ext)
404 {
405 DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
406
407 ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
408 szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
409 0, NULL, constraints, &size);
410 }
411 else
412 constraints->fCA = defaultIfNotSpecified;
413 }
414 return ret;
415 }
416
417 /* Checks element's basic constraints to see if it can act as a CA, with
418 * remainingCAs CAs left in this chain. In general, a cert must include the
419 * basic constraints extension, with the CA flag asserted, in order to be
420 * allowed to be a CA. A V1 or V2 cert, which has no extensions, is also
421 * allowed to be a CA if it's installed locally (in the engine's world store.)
422 * This matches the expected usage in RFC 5280, section 4.2.1.9: a conforming
423 * CA MUST include the basic constraints extension in all certificates that are
424 * used to validate digital signatures on certificates. It also matches
425 * section 6.1.4(k): "If a certificate is a v1 or v2 certificate, then the
426 * application MUST either verify that the certificate is a CA certificate
427 * through out-of-band means or reject the certificate." Rejecting the
428 * certificate prohibits a large number of commonly used certificates, so
429 * accepting locally installed ones is a compromise.
430 * Root certificates are also allowed to be CAs even without a basic
431 * constraints extension. This is implied by RFC 5280, section 6.1: the
432 * root of a certificate chain's only requirement is that it was used to issue
433 * the next certificate in the chain.
434 * Updates chainConstraints with the element's constraints, if:
435 * 1. chainConstraints doesn't have a path length constraint, or
436 * 2. element's path length constraint is smaller than chainConstraints's
437 * Sets *pathLengthConstraintViolated to TRUE if a path length violation
438 * occurs.
439 * Returns TRUE if the element can be a CA, and the length of the remaining
440 * chain is valid.
441 */
442 static BOOL CRYPT_CheckBasicConstraintsForCA(PCertificateChainEngine engine,
443 PCCERT_CONTEXT cert, CERT_BASIC_CONSTRAINTS2_INFO *chainConstraints,
444 DWORD remainingCAs, BOOL isRoot, BOOL *pathLengthConstraintViolated)
445 {
446 BOOL validBasicConstraints, implicitCA = FALSE;
447 CERT_BASIC_CONSTRAINTS2_INFO constraints;
448
449 if (isRoot)
450 implicitCA = TRUE;
451 else if (cert->pCertInfo->dwVersion == CERT_V1 ||
452 cert->pCertInfo->dwVersion == CERT_V2)
453 {
454 BYTE hash[20];
455 DWORD size = sizeof(hash);
456
457 if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID,
458 hash, &size))
459 {
460 CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
461 PCCERT_CONTEXT localCert = CertFindCertificateInStore(
462 engine->hWorld, cert->dwCertEncodingType, 0, CERT_FIND_SHA1_HASH,
463 &blob, NULL);
464
465 if (localCert)
466 {
467 CertFreeCertificateContext(localCert);
468 implicitCA = TRUE;
469 }
470 }
471 }
472 if ((validBasicConstraints = CRYPT_DecodeBasicConstraints(cert,
473 &constraints, implicitCA)))
474 {
475 chainConstraints->fCA = constraints.fCA;
476 if (!constraints.fCA)
477 {
478 TRACE_(chain)("chain element %d can't be a CA\n", remainingCAs + 1);
479 validBasicConstraints = FALSE;
480 }
481 else if (constraints.fPathLenConstraint)
482 {
483 /* If the element has path length constraints, they apply to the
484 * entire remaining chain.
485 */
486 if (!chainConstraints->fPathLenConstraint ||
487 constraints.dwPathLenConstraint <
488 chainConstraints->dwPathLenConstraint)
489 {
490 TRACE_(chain)("setting path length constraint to %d\n",
491 chainConstraints->dwPathLenConstraint);
492 chainConstraints->fPathLenConstraint = TRUE;
493 chainConstraints->dwPathLenConstraint =
494 constraints.dwPathLenConstraint;
495 }
496 }
497 }
498 if (chainConstraints->fPathLenConstraint &&
499 remainingCAs > chainConstraints->dwPathLenConstraint)
500 {
501 TRACE_(chain)("remaining CAs %d exceed max path length %d\n",
502 remainingCAs, chainConstraints->dwPathLenConstraint);
503 validBasicConstraints = FALSE;
504 *pathLengthConstraintViolated = TRUE;
505 }
506 return validBasicConstraints;
507 }
508
509 static BOOL url_matches(LPCWSTR constraint, LPCWSTR name,
510 DWORD *trustErrorStatus)
511 {
512 BOOL match = FALSE;
513
514 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
515
516 if (!constraint)
517 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
518 else if (!name)
519 ; /* no match */
520 else if (constraint[0] == '.')
521 {
522 if (lstrlenW(name) > lstrlenW(constraint))
523 match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
524 constraint);
525 }
526 else
527 match = !lstrcmpiW(constraint, name);
528 return match;
529 }
530
531 static BOOL rfc822_name_matches(LPCWSTR constraint, LPCWSTR name,
532 DWORD *trustErrorStatus)
533 {
534 BOOL match = FALSE;
535 LPCWSTR at;
536
537 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
538
539 if (!constraint)
540 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
541 else if (!name)
542 ; /* no match */
543 else if ((at = strchrW(constraint, '@')))
544 match = !lstrcmpiW(constraint, name);
545 else
546 {
547 if ((at = strchrW(name, '@')))
548 match = url_matches(constraint, at + 1, trustErrorStatus);
549 else
550 match = !lstrcmpiW(constraint, name);
551 }
552 return match;
553 }
554
555 static BOOL dns_name_matches(LPCWSTR constraint, LPCWSTR name,
556 DWORD *trustErrorStatus)
557 {
558 BOOL match = FALSE;
559
560 TRACE("%s, %s\n", debugstr_w(constraint), debugstr_w(name));
561
562 if (!constraint)
563 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
564 else if (!name)
565 ; /* no match */
566 else if (lstrlenW(name) >= lstrlenW(constraint))
567 match = !lstrcmpiW(name + lstrlenW(name) - lstrlenW(constraint),
568 constraint);
569 /* else: name is too short, no match */
570
571 return match;
572 }
573
574 static BOOL ip_address_matches(const CRYPT_DATA_BLOB *constraint,
575 const CRYPT_DATA_BLOB *name, DWORD *trustErrorStatus)
576 {
577 BOOL match = FALSE;
578
579 TRACE("(%d, %p), (%d, %p)\n", constraint->cbData, constraint->pbData,
580 name->cbData, name->pbData);
581
582 /* RFC5280, section 4.2.1.10, iPAddress syntax: either 8 or 32 bytes, for
583 * IPv4 or IPv6 addresses, respectively.
584 */
585 if (constraint->cbData != sizeof(DWORD) * 2 && constraint->cbData != 32)
586 *trustErrorStatus |= CERT_TRUST_INVALID_NAME_CONSTRAINTS;
587 else if (name->cbData == sizeof(DWORD) &&
588 constraint->cbData == sizeof(DWORD) * 2)
589 {
590 DWORD subnet, mask, addr;
591
592 memcpy(&subnet, constraint->pbData, sizeof(subnet));
593 memcpy(&mask, constraint->pbData + sizeof(subnet), sizeof(mask));
594 memcpy(&addr, name->pbData, sizeof(addr));
595 /* These are really in big-endian order, but for equality matching we
596 * don't need to swap to host order
597 */
598 match = (subnet & mask) == (addr & mask);
599 }
600 else if (name->cbData == 16 && constraint->cbData == 32)
601 {
602 const BYTE *subnet, *mask, *addr;
603 DWORD i;
604
605 subnet = constraint->pbData;
606 mask = constraint->pbData + 16;
607 addr = name->pbData;
608 match = TRUE;
609 for (i = 0; match && i < 16; i++)
610 if ((subnet[i] & mask[i]) != (addr[i] & mask[i]))
611 match = FALSE;
612 }
613 /* else: name is wrong size, no match */
614
615 return match;
616 }
617
618 static void CRYPT_FindMatchingNameEntry(const CERT_ALT_NAME_ENTRY *constraint,
619 const CERT_ALT_NAME_INFO *subjectName, DWORD *trustErrorStatus,
620 DWORD errorIfFound, DWORD errorIfNotFound)
621 {
622 DWORD i;
623 BOOL match = FALSE;
624
625 for (i = 0; i < subjectName->cAltEntry; i++)
626 {
627 if (subjectName->rgAltEntry[i].dwAltNameChoice ==
628 constraint->dwAltNameChoice)
629 {
630 switch (constraint->dwAltNameChoice)
631 {
632 case CERT_ALT_NAME_RFC822_NAME:
633 match = rfc822_name_matches(constraint->u.pwszURL,
634 subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
635 break;
636 case CERT_ALT_NAME_DNS_NAME:
637 match = dns_name_matches(constraint->u.pwszURL,
638 subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
639 break;
640 case CERT_ALT_NAME_URL:
641 match = url_matches(constraint->u.pwszURL,
642 subjectName->rgAltEntry[i].u.pwszURL, trustErrorStatus);
643 break;
644 case CERT_ALT_NAME_IP_ADDRESS:
645 match = ip_address_matches(&constraint->u.IPAddress,
646 &subjectName->rgAltEntry[i].u.IPAddress, trustErrorStatus);
647 break;
648 case CERT_ALT_NAME_DIRECTORY_NAME:
649 default:
650 ERR("name choice %d unsupported in this context\n",
651 constraint->dwAltNameChoice);
652 *trustErrorStatus |=
653 CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
654 }
655 }
656 }
657 *trustErrorStatus |= match ? errorIfFound : errorIfNotFound;
658 }
659
660 static inline PCERT_EXTENSION get_subject_alt_name_ext(const CERT_INFO *cert)
661 {
662 PCERT_EXTENSION ext;
663
664 ext = CertFindExtension(szOID_SUBJECT_ALT_NAME2,
665 cert->cExtension, cert->rgExtension);
666 if (!ext)
667 ext = CertFindExtension(szOID_SUBJECT_ALT_NAME,
668 cert->cExtension, cert->rgExtension);
669 return ext;
670 }
671
672 static void CRYPT_CheckNameConstraints(
673 const CERT_NAME_CONSTRAINTS_INFO *nameConstraints, const CERT_INFO *cert,
674 DWORD *trustErrorStatus)
675 {
676 /* If there aren't any existing constraints, don't bother checking */
677 if (nameConstraints->cPermittedSubtree || nameConstraints->cExcludedSubtree)
678 {
679 CERT_EXTENSION *ext = get_subject_alt_name_ext(cert);
680
681 if (ext)
682 {
683 CERT_ALT_NAME_INFO *subjectName;
684 DWORD size;
685
686 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
687 ext->Value.pbData, ext->Value.cbData,
688 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
689 &subjectName, &size))
690 {
691 DWORD i;
692
693 for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
694 CRYPT_FindMatchingNameEntry(
695 &nameConstraints->rgExcludedSubtree[i].Base, subjectName,
696 trustErrorStatus,
697 CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT, 0);
698 for (i = 0; i < nameConstraints->cPermittedSubtree; i++)
699 CRYPT_FindMatchingNameEntry(
700 &nameConstraints->rgPermittedSubtree[i].Base, subjectName,
701 trustErrorStatus, 0,
702 CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT);
703 LocalFree(subjectName);
704 }
705 else
706 *trustErrorStatus |=
707 CERT_TRUST_INVALID_EXTENSION |
708 CERT_TRUST_INVALID_NAME_CONSTRAINTS;
709 }
710 else
711 {
712 if (nameConstraints->cPermittedSubtree)
713 *trustErrorStatus |=
714 CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT |
715 CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
716 if (nameConstraints->cExcludedSubtree)
717 *trustErrorStatus |=
718 CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
719 }
720 }
721 }
722
723 /* Gets cert's name constraints, if any. Free with LocalFree. */
724 static CERT_NAME_CONSTRAINTS_INFO *CRYPT_GetNameConstraints(CERT_INFO *cert)
725 {
726 CERT_NAME_CONSTRAINTS_INFO *info = NULL;
727
728 CERT_EXTENSION *ext;
729
730 if ((ext = CertFindExtension(szOID_NAME_CONSTRAINTS, cert->cExtension,
731 cert->rgExtension)))
732 {
733 DWORD size;
734
735 CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
736 ext->Value.pbData, ext->Value.cbData,
737 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &info,
738 &size);
739 }
740 return info;
741 }
742
743 static BOOL CRYPT_IsValidNameConstraint(const CERT_NAME_CONSTRAINTS_INFO *info)
744 {
745 DWORD i;
746 BOOL ret = TRUE;
747
748 /* Check that none of the constraints specifies a minimum or a maximum.
749 * See RFC 5280, section 4.2.1.10:
750 * "Within this profile, the minimum and maximum fields are not used with
751 * any name forms, thus, the minimum MUST be zero, and maximum MUST be
752 * absent. However, if an application encounters a critical name
753 * constraints extension that specifies other values for minimum or
754 * maximum for a name form that appears in a subsequent certificate, the
755 * application MUST either process these fields or reject the
756 * certificate."
757 * Since it gives no guidance as to how to process these fields, we
758 * reject any name constraint that contains them.
759 */
760 for (i = 0; ret && i < info->cPermittedSubtree; i++)
761 if (info->rgPermittedSubtree[i].dwMinimum ||
762 info->rgPermittedSubtree[i].fMaximum)
763 {
764 TRACE_(chain)("found a minimum or maximum in permitted subtrees\n");
765 ret = FALSE;
766 }
767 for (i = 0; ret && i < info->cExcludedSubtree; i++)
768 if (info->rgExcludedSubtree[i].dwMinimum ||
769 info->rgExcludedSubtree[i].fMaximum)
770 {
771 TRACE_(chain)("found a minimum or maximum in excluded subtrees\n");
772 ret = FALSE;
773 }
774 return ret;
775 }
776
777 static void CRYPT_CheckChainNameConstraints(PCERT_SIMPLE_CHAIN chain)
778 {
779 int i, j;
780
781 /* Microsoft's implementation appears to violate RFC 3280: according to
782 * MSDN, the various CERT_TRUST_*_NAME_CONSTRAINT errors are set if a CA's
783 * name constraint is violated in the end cert. According to RFC 3280,
784 * the constraints should be checked against every subsequent certificate
785 * in the chain, not just the end cert.
786 * Microsoft's implementation also sets the name constraint errors on the
787 * certs whose constraints were violated, not on the certs that violated
788 * them.
789 * In order to be error-compatible with Microsoft's implementation, while
790 * still adhering to RFC 3280, I use a O(n ^ 2) algorithm to check name
791 * constraints.
792 */
793 for (i = chain->cElement - 1; i > 0; i--)
794 {
795 CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
796
797 if ((nameConstraints = CRYPT_GetNameConstraints(
798 chain->rgpElement[i]->pCertContext->pCertInfo)))
799 {
800 if (!CRYPT_IsValidNameConstraint(nameConstraints))
801 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
802 CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
803 else
804 {
805 for (j = i - 1; j >= 0; j--)
806 {
807 DWORD errorStatus = 0;
808
809 /* According to RFC 3280, self-signed certs don't have name
810 * constraints checked unless they're the end cert.
811 */
812 if (j == 0 || !CRYPT_IsCertificateSelfSigned(
813 chain->rgpElement[j]->pCertContext))
814 {
815 CRYPT_CheckNameConstraints(nameConstraints,
816 chain->rgpElement[j]->pCertContext->pCertInfo,
817 &errorStatus);
818 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
819 errorStatus;
820 }
821 }
822 }
823 LocalFree(nameConstraints);
824 }
825 }
826 }
827
828 static LPWSTR name_value_to_str(const CERT_NAME_BLOB *name)
829 {
830 DWORD len = cert_name_to_str_with_indent(X509_ASN_ENCODING, 0, name,
831 CERT_SIMPLE_NAME_STR, NULL, 0);
832 LPWSTR str = NULL;
833
834 if (len)
835 {
836 str = CryptMemAlloc(len * sizeof(WCHAR));
837 if (str)
838 cert_name_to_str_with_indent(X509_ASN_ENCODING, 0, name,
839 CERT_SIMPLE_NAME_STR, str, len);
840 }
841 return str;
842 }
843
844 static void dump_alt_name_entry(const CERT_ALT_NAME_ENTRY *entry)
845 {
846 LPWSTR str;
847
848 switch (entry->dwAltNameChoice)
849 {
850 case CERT_ALT_NAME_OTHER_NAME:
851 TRACE_(chain)("CERT_ALT_NAME_OTHER_NAME, oid = %s\n",
852 debugstr_a(entry->u.pOtherName->pszObjId));
853 break;
854 case CERT_ALT_NAME_RFC822_NAME:
855 TRACE_(chain)("CERT_ALT_NAME_RFC822_NAME: %s\n",
856 debugstr_w(entry->u.pwszRfc822Name));
857 break;
858 case CERT_ALT_NAME_DNS_NAME:
859 TRACE_(chain)("CERT_ALT_NAME_DNS_NAME: %s\n",
860 debugstr_w(entry->u.pwszDNSName));
861 break;
862 case CERT_ALT_NAME_DIRECTORY_NAME:
863 str = name_value_to_str(&entry->u.DirectoryName);
864 TRACE_(chain)("CERT_ALT_NAME_DIRECTORY_NAME: %s\n", debugstr_w(str));
865 CryptMemFree(str);
866 break;
867 case CERT_ALT_NAME_URL:
868 TRACE_(chain)("CERT_ALT_NAME_URL: %s\n", debugstr_w(entry->u.pwszURL));
869 break;
870 case CERT_ALT_NAME_IP_ADDRESS:
871 TRACE_(chain)("CERT_ALT_NAME_IP_ADDRESS: %d bytes\n",
872 entry->u.IPAddress.cbData);
873 break;
874 case CERT_ALT_NAME_REGISTERED_ID:
875 TRACE_(chain)("CERT_ALT_NAME_REGISTERED_ID: %s\n",
876 debugstr_a(entry->u.pszRegisteredID));
877 break;
878 default:
879 TRACE_(chain)("dwAltNameChoice = %d\n", entry->dwAltNameChoice);
880 }
881 }
882
883 static void dump_alt_name(LPCSTR type, const CERT_EXTENSION *ext)
884 {
885 CERT_ALT_NAME_INFO *name;
886 DWORD size;
887
888 TRACE_(chain)("%s:\n", type);
889 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
890 ext->Value.pbData, ext->Value.cbData,
891 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &name, &size))
892 {
893 DWORD i;
894
895 TRACE_(chain)("%d alt name entries:\n", name->cAltEntry);
896 for (i = 0; i < name->cAltEntry; i++)
897 dump_alt_name_entry(&name->rgAltEntry[i]);
898 LocalFree(name);
899 }
900 }
901
902 static void dump_basic_constraints(const CERT_EXTENSION *ext)
903 {
904 CERT_BASIC_CONSTRAINTS_INFO *info;
905 DWORD size = 0;
906
907 if (CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
908 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
909 NULL, &info, &size))
910 {
911 TRACE_(chain)("SubjectType: %02x\n", info->SubjectType.pbData[0]);
912 TRACE_(chain)("%s path length constraint\n",
913 info->fPathLenConstraint ? "has" : "doesn't have");
914 TRACE_(chain)("path length=%d\n", info->dwPathLenConstraint);
915 LocalFree(info);
916 }
917 }
918
919 static void dump_basic_constraints2(const CERT_EXTENSION *ext)
920 {
921 CERT_BASIC_CONSTRAINTS2_INFO constraints;
922 DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
923
924 if (CryptDecodeObjectEx(X509_ASN_ENCODING,
925 szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
926 0, NULL, &constraints, &size))
927 {
928 TRACE_(chain)("basic constraints:\n");
929 TRACE_(chain)("can%s be a CA\n", constraints.fCA ? "" : "not");
930 TRACE_(chain)("%s path length constraint\n",
931 constraints.fPathLenConstraint ? "has" : "doesn't have");
932 TRACE_(chain)("path length=%d\n", constraints.dwPathLenConstraint);
933 }
934 }
935
936 static void dump_key_usage(const CERT_EXTENSION *ext)
937 {
938 CRYPT_BIT_BLOB usage;
939 DWORD size = sizeof(usage);
940
941 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
942 ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
943 {
944 #define trace_usage_bit(bits, bit) \
945 if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
946 if (usage.cbData)
947 {
948 trace_usage_bit(usage.pbData[0], CERT_DIGITAL_SIGNATURE_KEY_USAGE);
949 trace_usage_bit(usage.pbData[0], CERT_NON_REPUDIATION_KEY_USAGE);
950 trace_usage_bit(usage.pbData[0], CERT_KEY_ENCIPHERMENT_KEY_USAGE);
951 trace_usage_bit(usage.pbData[0], CERT_DATA_ENCIPHERMENT_KEY_USAGE);
952 trace_usage_bit(usage.pbData[0], CERT_KEY_AGREEMENT_KEY_USAGE);
953 trace_usage_bit(usage.pbData[0], CERT_KEY_CERT_SIGN_KEY_USAGE);
954 trace_usage_bit(usage.pbData[0], CERT_CRL_SIGN_KEY_USAGE);
955 trace_usage_bit(usage.pbData[0], CERT_ENCIPHER_ONLY_KEY_USAGE);
956 }
957 #undef trace_usage_bit
958 if (usage.cbData > 1 && usage.pbData[1] & CERT_DECIPHER_ONLY_KEY_USAGE)
959 TRACE_(chain)("CERT_DECIPHER_ONLY_KEY_USAGE\n");
960 }
961 }
962
963 static void dump_general_subtree(const CERT_GENERAL_SUBTREE *subtree)
964 {
965 dump_alt_name_entry(&subtree->Base);
966 TRACE_(chain)("dwMinimum = %d, fMaximum = %d, dwMaximum = %d\n",
967 subtree->dwMinimum, subtree->fMaximum, subtree->dwMaximum);
968 }
969
970 static void dump_name_constraints(const CERT_EXTENSION *ext)
971 {
972 CERT_NAME_CONSTRAINTS_INFO *nameConstraints;
973 DWORD size;
974
975 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_CONSTRAINTS,
976 ext->Value.pbData, ext->Value.cbData,
977 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL, &nameConstraints,
978 &size))
979 {
980 DWORD i;
981
982 TRACE_(chain)("%d permitted subtrees:\n",
983 nameConstraints->cPermittedSubtree);
984 for (i = 0; i < nameConstraints->cPermittedSubtree; i++)
985 dump_general_subtree(&nameConstraints->rgPermittedSubtree[i]);
986 TRACE_(chain)("%d excluded subtrees:\n",
987 nameConstraints->cExcludedSubtree);
988 for (i = 0; i < nameConstraints->cExcludedSubtree; i++)
989 dump_general_subtree(&nameConstraints->rgExcludedSubtree[i]);
990 LocalFree(nameConstraints);
991 }
992 }
993
994 static void dump_cert_policies(const CERT_EXTENSION *ext)
995 {
996 CERT_POLICIES_INFO *policies;
997 DWORD size;
998
999 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_CERT_POLICIES,
1000 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1001 &policies, &size))
1002 {
1003 DWORD i, j;
1004
1005 TRACE_(chain)("%d policies:\n", policies->cPolicyInfo);
1006 for (i = 0; i < policies->cPolicyInfo; i++)
1007 {
1008 TRACE_(chain)("policy identifier: %s\n",
1009 debugstr_a(policies->rgPolicyInfo[i].pszPolicyIdentifier));
1010 TRACE_(chain)("%d policy qualifiers:\n",
1011 policies->rgPolicyInfo[i].cPolicyQualifier);
1012 for (j = 0; j < policies->rgPolicyInfo[i].cPolicyQualifier; j++)
1013 TRACE_(chain)("%s\n", debugstr_a(
1014 policies->rgPolicyInfo[i].rgPolicyQualifier[j].
1015 pszPolicyQualifierId));
1016 }
1017 LocalFree(policies);
1018 }
1019 }
1020
1021 static void dump_enhanced_key_usage(const CERT_EXTENSION *ext)
1022 {
1023 CERT_ENHKEY_USAGE *usage;
1024 DWORD size;
1025
1026 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ENHANCED_KEY_USAGE,
1027 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1028 &usage, &size))
1029 {
1030 DWORD i;
1031
1032 TRACE_(chain)("%d usages:\n", usage->cUsageIdentifier);
1033 for (i = 0; i < usage->cUsageIdentifier; i++)
1034 TRACE_(chain)("%s\n", usage->rgpszUsageIdentifier[i]);
1035 LocalFree(usage);
1036 }
1037 }
1038
1039 static void dump_netscape_cert_type(const CERT_EXTENSION *ext)
1040 {
1041 CRYPT_BIT_BLOB usage;
1042 DWORD size = sizeof(usage);
1043
1044 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_BITS, ext->Value.pbData,
1045 ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
1046 {
1047 #define trace_cert_type_bit(bits, bit) \
1048 if ((bits) & (bit)) TRACE_(chain)("%s\n", #bit)
1049 if (usage.cbData)
1050 {
1051 trace_cert_type_bit(usage.pbData[0],
1052 NETSCAPE_SSL_CLIENT_AUTH_CERT_TYPE);
1053 trace_cert_type_bit(usage.pbData[0],
1054 NETSCAPE_SSL_SERVER_AUTH_CERT_TYPE);
1055 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SMIME_CERT_TYPE);
1056 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SIGN_CERT_TYPE);
1057 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SSL_CA_CERT_TYPE);
1058 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SMIME_CA_CERT_TYPE);
1059 trace_cert_type_bit(usage.pbData[0], NETSCAPE_SIGN_CA_CERT_TYPE);
1060 }
1061 #undef trace_cert_type_bit
1062 }
1063 }
1064
1065 static void dump_extension(const CERT_EXTENSION *ext)
1066 {
1067 TRACE_(chain)("%s (%scritical)\n", debugstr_a(ext->pszObjId),
1068 ext->fCritical ? "" : "not ");
1069 if (!strcmp(ext->pszObjId, szOID_SUBJECT_ALT_NAME))
1070 dump_alt_name("subject alt name", ext);
1071 else if (!strcmp(ext->pszObjId, szOID_ISSUER_ALT_NAME))
1072 dump_alt_name("issuer alt name", ext);
1073 else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS))
1074 dump_basic_constraints(ext);
1075 else if (!strcmp(ext->pszObjId, szOID_KEY_USAGE))
1076 dump_key_usage(ext);
1077 else if (!strcmp(ext->pszObjId, szOID_SUBJECT_ALT_NAME2))
1078 dump_alt_name("subject alt name 2", ext);
1079 else if (!strcmp(ext->pszObjId, szOID_ISSUER_ALT_NAME2))
1080 dump_alt_name("issuer alt name 2", ext);
1081 else if (!strcmp(ext->pszObjId, szOID_BASIC_CONSTRAINTS2))
1082 dump_basic_constraints2(ext);
1083 else if (!strcmp(ext->pszObjId, szOID_NAME_CONSTRAINTS))
1084 dump_name_constraints(ext);
1085 else if (!strcmp(ext->pszObjId, szOID_CERT_POLICIES))
1086 dump_cert_policies(ext);
1087 else if (!strcmp(ext->pszObjId, szOID_ENHANCED_KEY_USAGE))
1088 dump_enhanced_key_usage(ext);
1089 else if (!strcmp(ext->pszObjId, szOID_NETSCAPE_CERT_TYPE))
1090 dump_netscape_cert_type(ext);
1091 }
1092
1093 static LPCWSTR filetime_to_str(const FILETIME *time)
1094 {
1095 static WCHAR date[80];
1096 WCHAR dateFmt[80]; /* sufficient for all versions of LOCALE_SSHORTDATE */
1097 SYSTEMTIME sysTime;
1098
1099 if (!time) return NULL;
1100
1101 GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, dateFmt,
1102 sizeof(dateFmt) / sizeof(dateFmt[0]));
1103 FileTimeToSystemTime(time, &sysTime);
1104 GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, date,
1105 sizeof(date) / sizeof(date[0]));
1106 return date;
1107 }
1108
1109 static void dump_element(PCCERT_CONTEXT cert)
1110 {
1111 LPWSTR name = NULL;
1112 DWORD len, i;
1113
1114 TRACE_(chain)("%p: version %d\n", cert, cert->pCertInfo->dwVersion);
1115 len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
1116 CERT_NAME_ISSUER_FLAG, NULL, NULL, 0);
1117 name = CryptMemAlloc(len * sizeof(WCHAR));
1118 if (name)
1119 {
1120 CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
1121 CERT_NAME_ISSUER_FLAG, NULL, name, len);
1122 TRACE_(chain)("issued by %s\n", debugstr_w(name));
1123 CryptMemFree(name);
1124 }
1125 len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
1126 NULL, 0);
1127 name = CryptMemAlloc(len * sizeof(WCHAR));
1128 if (name)
1129 {
1130 CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
1131 name, len);
1132 TRACE_(chain)("issued to %s\n", debugstr_w(name));
1133 CryptMemFree(name);
1134 }
1135 TRACE_(chain)("valid from %s to %s\n",
1136 debugstr_w(filetime_to_str(&cert->pCertInfo->NotBefore)),
1137 debugstr_w(filetime_to_str(&cert->pCertInfo->NotAfter)));
1138 TRACE_(chain)("%d extensions\n", cert->pCertInfo->cExtension);
1139 for (i = 0; i < cert->pCertInfo->cExtension; i++)
1140 dump_extension(&cert->pCertInfo->rgExtension[i]);
1141 }
1142
1143 static BOOL CRYPT_KeyUsageValid(PCertificateChainEngine engine,
1144 PCCERT_CONTEXT cert, BOOL isRoot, BOOL isCA, DWORD index)
1145 {
1146 PCERT_EXTENSION ext;
1147 BOOL ret;
1148 BYTE usageBits = 0;
1149
1150 ext = CertFindExtension(szOID_KEY_USAGE, cert->pCertInfo->cExtension,
1151 cert->pCertInfo->rgExtension);
1152 if (ext)
1153 {
1154 CRYPT_BIT_BLOB usage;
1155 DWORD size = sizeof(usage);
1156
1157 ret = CryptDecodeObjectEx(cert->dwCertEncodingType, X509_BITS,
1158 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL,
1159 &usage, &size);
1160 if (!ret)
1161 return FALSE;
1162 else if (usage.cbData > 2)
1163 {
1164 /* The key usage extension only defines 9 bits => no more than 2
1165 * bytes are needed to encode all known usages.
1166 */
1167 return FALSE;
1168 }
1169 else
1170 {
1171 /* The only bit relevant to chain validation is the keyCertSign
1172 * bit, which is always in the least significant byte of the
1173 * key usage bits.
1174 */
1175 usageBits = usage.pbData[usage.cbData - 1];
1176 }
1177 }
1178 if (isCA)
1179 {
1180 if (!ext)
1181 {
1182 /* MS appears to violate RFC 5280, section 4.2.1.3 (Key Usage)
1183 * here. Quoting the RFC:
1184 * "This [key usage] extension MUST appear in certificates that
1185 * contain public keys that are used to validate digital signatures
1186 * on other public key certificates or CRLs."
1187 * MS appears to accept certs that do not contain key usage
1188 * extensions as CA certs. V1 and V2 certificates did not have
1189 * extensions, and many root certificates are V1 certificates, so
1190 * perhaps this is prudent. On the other hand, MS also accepts V3
1191 * certs without key usage extensions. We are more restrictive:
1192 * we accept locally installed V1 or V2 certs as CA certs.
1193 * We also accept a lack of key usage extension on root certs,
1194 * which is implied in RFC 5280, section 6.1: the trust anchor's
1195 * only requirement is that it was used to issue the next
1196 * certificate in the chain.
1197 */
1198 if (isRoot)
1199 ret = TRUE;
1200 else if (cert->pCertInfo->dwVersion == CERT_V1 ||
1201 cert->pCertInfo->dwVersion == CERT_V2)
1202 {
1203 PCCERT_CONTEXT localCert = CRYPT_FindCertInStore(
1204 engine->hWorld, cert);
1205
1206 ret = localCert != NULL;
1207 CertFreeCertificateContext(localCert);
1208 }
1209 else
1210 ret = FALSE;
1211 if (!ret)
1212 WARN_(chain)("no key usage extension on a CA cert\n");
1213 }
1214 else
1215 {
1216 if (!(usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
1217 {
1218 WARN_(chain)("keyCertSign not asserted on a CA cert\n");
1219 ret = FALSE;
1220 }
1221 else
1222 ret = TRUE;
1223 }
1224 }
1225 else
1226 {
1227 if (ext && (usageBits & CERT_KEY_CERT_SIGN_KEY_USAGE))
1228 {
1229 WARN_(chain)("keyCertSign asserted on a non-CA cert\n");
1230 ret = FALSE;
1231 }
1232 else
1233 ret = TRUE;
1234 }
1235 return ret;
1236 }
1237
1238 static BOOL CRYPT_ExtendedKeyUsageValidForCA(PCCERT_CONTEXT cert)
1239 {
1240 PCERT_EXTENSION ext;
1241 BOOL ret;
1242
1243 /* RFC 5280, section 4.2.1.12: "In general, this extension will only
1244 * appear in end entity certificates." And, "If a certificate contains
1245 * both a key usage extension and an extended key usage extension, then
1246 * both extensions MUST be processed independently and the certificate MUST
1247 * only be used for a purpose consistent with both extensions." This seems
1248 * to imply that it should be checked if present, and ignored if not.
1249 * Unfortunately some CAs, e.g. the Thawte SGC CA, don't include the code
1250 * signing extended key usage, whereas they do include the keyCertSign
1251 * key usage. Thus, when checking for a CA, we only require the
1252 * code signing extended key usage if the extended key usage is critical.
1253 */
1254 ext = CertFindExtension(szOID_ENHANCED_KEY_USAGE,
1255 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
1256 if (ext && ext->fCritical)
1257 {
1258 CERT_ENHKEY_USAGE *usage;
1259 DWORD size;
1260
1261 ret = CryptDecodeObjectEx(cert->dwCertEncodingType,
1262 X509_ENHANCED_KEY_USAGE, ext->Value.pbData, ext->Value.cbData,
1263 CRYPT_DECODE_ALLOC_FLAG, NULL, &usage, &size);
1264 if (ret)
1265 {
1266 DWORD i;
1267
1268 /* Explicitly require the code signing extended key usage for a CA
1269 * with an extended key usage extension. That is, don't assume
1270 * a cert is allowed to be a CA if it specifies the
1271 * anyExtendedKeyUsage usage oid. See again RFC 5280, section
1272 * 4.2.1.12: "Applications that require the presence of a
1273 * particular purpose MAY reject certificates that include the
1274 * anyExtendedKeyUsage OID but not the particular OID expected for
1275 * the application."
1276 */
1277 ret = FALSE;
1278 for (i = 0; !ret && i < usage->cUsageIdentifier; i++)
1279 if (!strcmp(usage->rgpszUsageIdentifier[i],
1280 szOID_PKIX_KP_CODE_SIGNING))
1281 ret = TRUE;
1282 LocalFree(usage);
1283 }
1284 }
1285 else
1286 ret = TRUE;
1287 return ret;
1288 }
1289
1290 static BOOL CRYPT_CriticalExtensionsSupported(PCCERT_CONTEXT cert)
1291 {
1292 BOOL ret = TRUE;
1293 DWORD i;
1294
1295 for (i = 0; ret && i < cert->pCertInfo->cExtension; i++)
1296 {
1297 if (cert->pCertInfo->rgExtension[i].fCritical)
1298 {
1299 LPCSTR oid = cert->pCertInfo->rgExtension[i].pszObjId;
1300
1301 if (!strcmp(oid, szOID_BASIC_CONSTRAINTS))
1302 ret = TRUE;
1303 else if (!strcmp(oid, szOID_BASIC_CONSTRAINTS2))
1304 ret = TRUE;
1305 else if (!strcmp(oid, szOID_NAME_CONSTRAINTS))
1306 ret = TRUE;
1307 else if (!strcmp(oid, szOID_KEY_USAGE))
1308 ret = TRUE;
1309 else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME))
1310 ret = TRUE;
1311 else if (!strcmp(oid, szOID_SUBJECT_ALT_NAME2))
1312 ret = TRUE;
1313 else if (!strcmp(oid, szOID_ENHANCED_KEY_USAGE))
1314 ret = TRUE;
1315 else
1316 {
1317 FIXME("unsupported critical extension %s\n",
1318 debugstr_a(oid));
1319 ret = FALSE;
1320 }
1321 }
1322 }
1323 return ret;
1324 }
1325
1326 static BOOL CRYPT_IsCertVersionValid(PCCERT_CONTEXT cert)
1327 {
1328 BOOL ret = TRUE;
1329
1330 /* Checks whether the contents of the cert match the cert's version. */
1331 switch (cert->pCertInfo->dwVersion)
1332 {
1333 case CERT_V1:
1334 /* A V1 cert may not contain unique identifiers. See RFC 5280,
1335 * section 4.1.2.8:
1336 * "These fields MUST only appear if the version is 2 or 3 (Section
1337 * 4.1.2.1). These fields MUST NOT appear if the version is 1."
1338 */
1339 if (cert->pCertInfo->IssuerUniqueId.cbData ||
1340 cert->pCertInfo->SubjectUniqueId.cbData)
1341 ret = FALSE;
1342 /* A V1 cert may not contain extensions. See RFC 5280, section 4.1.2.9:
1343 * "This field MUST only appear if the version is 3 (Section 4.1.2.1)."
1344 */
1345 if (cert->pCertInfo->cExtension)
1346 ret = FALSE;
1347 break;
1348 case CERT_V2:
1349 /* A V2 cert may not contain extensions. See RFC 5280, section 4.1.2.9:
1350 * "This field MUST only appear if the version is 3 (Section 4.1.2.1)."
1351 */
1352 if (cert->pCertInfo->cExtension)
1353 ret = FALSE;
1354 break;
1355 case CERT_V3:
1356 /* Do nothing, all fields are allowed for V3 certs */
1357 break;
1358 default:
1359 WARN_(chain)("invalid cert version %d\n", cert->pCertInfo->dwVersion);
1360 ret = FALSE;
1361 }
1362 return ret;
1363 }
1364
1365 static void CRYPT_CheckSimpleChain(PCertificateChainEngine engine,
1366 PCERT_SIMPLE_CHAIN chain, LPFILETIME time)
1367 {
1368 PCERT_CHAIN_ELEMENT rootElement = chain->rgpElement[chain->cElement - 1];
1369 int i;
1370 BOOL pathLengthConstraintViolated = FALSE;
1371 CERT_BASIC_CONSTRAINTS2_INFO constraints = { FALSE, FALSE, 0 };
1372
1373 TRACE_(chain)("checking chain with %d elements for time %s\n",
1374 chain->cElement, debugstr_w(filetime_to_str(time)));
1375 for (i = chain->cElement - 1; i >= 0; i--)
1376 {
1377 BOOL isRoot;
1378
1379 if (TRACE_ON(chain))
1380 dump_element(chain->rgpElement[i]->pCertContext);
1381 if (i == chain->cElement - 1)
1382 isRoot = CRYPT_IsCertificateSelfSigned(
1383 chain->rgpElement[i]->pCertContext);
1384 else
1385 isRoot = FALSE;
1386 if (!CRYPT_IsCertVersionValid(chain->rgpElement[i]->pCertContext))
1387 {
1388 /* MS appears to accept certs whose versions don't match their
1389 * contents, so there isn't an appropriate error code.
1390 */
1391 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1392 CERT_TRUST_INVALID_EXTENSION;
1393 }
1394 if (CertVerifyTimeValidity(time,
1395 chain->rgpElement[i]->pCertContext->pCertInfo) != 0)
1396 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1397 CERT_TRUST_IS_NOT_TIME_VALID;
1398 if (i != 0)
1399 {
1400 /* Check the signature of the cert this issued */
1401 if (!CryptVerifyCertificateSignatureEx(0, X509_ASN_ENCODING,
1402 CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT,
1403 (void *)chain->rgpElement[i - 1]->pCertContext,
1404 CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT,
1405 (void *)chain->rgpElement[i]->pCertContext, 0, NULL))
1406 chain->rgpElement[i - 1]->TrustStatus.dwErrorStatus |=
1407 CERT_TRUST_IS_NOT_SIGNATURE_VALID;
1408 /* Once a path length constraint has been violated, every remaining
1409 * CA cert's basic constraints is considered invalid.
1410 */
1411 if (pathLengthConstraintViolated)
1412 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1413 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1414 else if (!CRYPT_CheckBasicConstraintsForCA(engine,
1415 chain->rgpElement[i]->pCertContext, &constraints, i - 1, isRoot,
1416 &pathLengthConstraintViolated))
1417 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1418 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1419 else if (constraints.fPathLenConstraint &&
1420 constraints.dwPathLenConstraint)
1421 {
1422 /* This one's valid - decrement max length */
1423 constraints.dwPathLenConstraint--;
1424 }
1425 }
1426 else
1427 {
1428 /* Check whether end cert has a basic constraints extension */
1429 if (!CRYPT_DecodeBasicConstraints(
1430 chain->rgpElement[i]->pCertContext, &constraints, FALSE))
1431 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1432 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1433 }
1434 if (!CRYPT_KeyUsageValid(engine, chain->rgpElement[i]->pCertContext,
1435 isRoot, constraints.fCA, i))
1436 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1437 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
1438 if (i != 0)
1439 if (!CRYPT_ExtendedKeyUsageValidForCA(
1440 chain->rgpElement[i]->pCertContext))
1441 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1442 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
1443 if (CRYPT_IsSimpleChainCyclic(chain))
1444 {
1445 /* If the chain is cyclic, then the path length constraints
1446 * are violated, because the chain is infinitely long.
1447 */
1448 pathLengthConstraintViolated = TRUE;
1449 chain->TrustStatus.dwErrorStatus |=
1450 CERT_TRUST_IS_PARTIAL_CHAIN |
1451 CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
1452 }
1453 /* Check whether every critical extension is supported */
1454 if (!CRYPT_CriticalExtensionsSupported(
1455 chain->rgpElement[i]->pCertContext))
1456 chain->rgpElement[i]->TrustStatus.dwErrorStatus |=
1457 CERT_TRUST_INVALID_EXTENSION;
1458 CRYPT_CombineTrustStatus(&chain->TrustStatus,
1459 &chain->rgpElement[i]->TrustStatus);
1460 }
1461 CRYPT_CheckChainNameConstraints(chain);
1462 if (CRYPT_IsCertificateSelfSigned(rootElement->pCertContext))
1463 {
1464 rootElement->TrustStatus.dwInfoStatus |=
1465 CERT_TRUST_IS_SELF_SIGNED | CERT_TRUST_HAS_NAME_MATCH_ISSUER;
1466 CRYPT_CheckRootCert(engine->hRoot, rootElement);
1467 }
1468 CRYPT_CombineTrustStatus(&chain->TrustStatus, &rootElement->TrustStatus);
1469 }
1470
1471 static PCCERT_CONTEXT CRYPT_GetIssuer(HCERTSTORE store, PCCERT_CONTEXT subject,
1472 PCCERT_CONTEXT prevIssuer, DWORD *infoStatus)
1473 {
1474 PCCERT_CONTEXT issuer = NULL;
1475 PCERT_EXTENSION ext;
1476 DWORD size;
1477
1478 *infoStatus = 0;
1479 if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
1480 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1481 {
1482 CERT_AUTHORITY_KEY_ID_INFO *info;
1483 BOOL ret;
1484
1485 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1486 X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
1487 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1488 &info, &size);
1489 if (ret)
1490 {
1491 CERT_ID id;
1492
1493 if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
1494 {
1495 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1496 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
1497 sizeof(CERT_NAME_BLOB));
1498 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1499 &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
1500 issuer = CertFindCertificateInStore(store,
1501 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1502 prevIssuer);
1503 if (issuer)
1504 *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
1505 }
1506 else if (info->KeyId.cbData)
1507 {
1508 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1509 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1510 issuer = CertFindCertificateInStore(store,
1511 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1512 prevIssuer);
1513 if (issuer)
1514 *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
1515 }
1516 LocalFree(info);
1517 }
1518 }
1519 else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
1520 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1521 {
1522 CERT_AUTHORITY_KEY_ID2_INFO *info;
1523 BOOL ret;
1524
1525 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1526 X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
1527 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1528 &info, &size);
1529 if (ret)
1530 {
1531 CERT_ID id;
1532
1533 if (info->AuthorityCertIssuer.cAltEntry &&
1534 info->AuthorityCertSerialNumber.cbData)
1535 {
1536 PCERT_ALT_NAME_ENTRY directoryName = NULL;
1537 DWORD i;
1538
1539 for (i = 0; !directoryName &&
1540 i < info->AuthorityCertIssuer.cAltEntry; i++)
1541 if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
1542 == CERT_ALT_NAME_DIRECTORY_NAME)
1543 directoryName =
1544 &info->AuthorityCertIssuer.rgAltEntry[i];
1545 if (directoryName)
1546 {
1547 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1548 memcpy(&id.u.IssuerSerialNumber.Issuer,
1549 &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
1550 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1551 &info->AuthorityCertSerialNumber,
1552 sizeof(CRYPT_INTEGER_BLOB));
1553 issuer = CertFindCertificateInStore(store,
1554 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1555 prevIssuer);
1556 if (issuer)
1557 *infoStatus = CERT_TRUST_HAS_EXACT_MATCH_ISSUER;
1558 }
1559 else
1560 FIXME("no supported name type in authority key id2\n");
1561 }
1562 else if (info->KeyId.cbData)
1563 {
1564 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1565 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1566 issuer = CertFindCertificateInStore(store,
1567 subject->dwCertEncodingType, 0, CERT_FIND_CERT_ID, &id,
1568 prevIssuer);
1569 if (issuer)
1570 *infoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER;
1571 }
1572 LocalFree(info);
1573 }
1574 }
1575 else
1576 {
1577 issuer = CertFindCertificateInStore(store,
1578 subject->dwCertEncodingType, 0, CERT_FIND_SUBJECT_NAME,
1579 &subject->pCertInfo->Issuer, prevIssuer);
1580 *infoStatus = CERT_TRUST_HAS_NAME_MATCH_ISSUER;
1581 }
1582 return issuer;
1583 }
1584
1585 /* Builds a simple chain by finding an issuer for the last cert in the chain,
1586 * until reaching a self-signed cert, or until no issuer can be found.
1587 */
1588 static BOOL CRYPT_BuildSimpleChain(const CertificateChainEngine *engine,
1589 HCERTSTORE world, PCERT_SIMPLE_CHAIN chain)
1590 {
1591 BOOL ret = TRUE;
1592 PCCERT_CONTEXT cert = chain->rgpElement[chain->cElement - 1]->pCertContext;
1593
1594 while (ret && !CRYPT_IsSimpleChainCyclic(chain) &&
1595 !CRYPT_IsCertificateSelfSigned(cert))
1596 {
1597 PCCERT_CONTEXT issuer = CRYPT_GetIssuer(world, cert, NULL,
1598 &chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
1599
1600 if (issuer)
1601 {
1602 ret = CRYPT_AddCertToSimpleChain(engine, chain, issuer,
1603 chain->rgpElement[chain->cElement - 1]->TrustStatus.dwInfoStatus);
1604 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it to
1605 * close the enumeration that found it
1606 */
1607 CertFreeCertificateContext(issuer);
1608 cert = issuer;
1609 }
1610 else
1611 {
1612 TRACE_(chain)("Couldn't find issuer, halting chain creation\n");
1613 chain->TrustStatus.dwErrorStatus |= CERT_TRUST_IS_PARTIAL_CHAIN;
1614 break;
1615 }
1616 }
1617 return ret;
1618 }
1619
1620 static BOOL CRYPT_GetSimpleChainForCert(PCertificateChainEngine engine,
1621 HCERTSTORE world, PCCERT_CONTEXT cert, LPFILETIME pTime,
1622 PCERT_SIMPLE_CHAIN *ppChain)
1623 {
1624 BOOL ret = FALSE;
1625 PCERT_SIMPLE_CHAIN chain;
1626
1627 TRACE("(%p, %p, %p, %p)\n", engine, world, cert, pTime);
1628
1629 chain = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
1630 if (chain)
1631 {
1632 memset(chain, 0, sizeof(CERT_SIMPLE_CHAIN));
1633 chain->cbSize = sizeof(CERT_SIMPLE_CHAIN);
1634 ret = CRYPT_AddCertToSimpleChain(engine, chain, cert, 0);
1635 if (ret)
1636 {
1637 ret = CRYPT_BuildSimpleChain(engine, world, chain);
1638 if (ret)
1639 CRYPT_CheckSimpleChain(engine, chain, pTime);
1640 }
1641 if (!ret)
1642 {
1643 CRYPT_FreeSimpleChain(chain);
1644 chain = NULL;
1645 }
1646 *ppChain = chain;
1647 }
1648 return ret;
1649 }
1650
1651 static BOOL CRYPT_BuildCandidateChainFromCert(HCERTCHAINENGINE hChainEngine,
1652 PCCERT_CONTEXT cert, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1653 PCertificateChain *ppChain)
1654 {
1655 PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
1656 PCERT_SIMPLE_CHAIN simpleChain = NULL;
1657 HCERTSTORE world;
1658 BOOL ret;
1659
1660 world = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
1661 CERT_STORE_CREATE_NEW_FLAG, NULL);
1662 CertAddStoreToCollection(world, engine->hWorld, 0, 0);
1663 if (hAdditionalStore)
1664 CertAddStoreToCollection(world, hAdditionalStore, 0, 0);
1665 /* FIXME: only simple chains are supported for now, as CTLs aren't
1666 * supported yet.
1667 */
1668 if ((ret = CRYPT_GetSimpleChainForCert(engine, world, cert, pTime,
1669 &simpleChain)))
1670 {
1671 PCertificateChain chain = CryptMemAlloc(sizeof(CertificateChain));
1672
1673 if (chain)
1674 {
1675 chain->ref = 1;
1676 chain->world = world;
1677 chain->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
1678 chain->context.TrustStatus = simpleChain->TrustStatus;
1679 chain->context.cChain = 1;
1680 chain->context.rgpChain = CryptMemAlloc(sizeof(PCERT_SIMPLE_CHAIN));
1681 chain->context.rgpChain[0] = simpleChain;
1682 chain->context.cLowerQualityChainContext = 0;
1683 chain->context.rgpLowerQualityChainContext = NULL;
1684 chain->context.fHasRevocationFreshnessTime = FALSE;
1685 chain->context.dwRevocationFreshnessTime = 0;
1686 }
1687 else
1688 ret = FALSE;
1689 *ppChain = chain;
1690 }
1691 return ret;
1692 }
1693
1694 /* Makes and returns a copy of chain, up to and including element iElement. */
1695 static PCERT_SIMPLE_CHAIN CRYPT_CopySimpleChainToElement(
1696 const CERT_SIMPLE_CHAIN *chain, DWORD iElement)
1697 {
1698 PCERT_SIMPLE_CHAIN copy = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
1699
1700 if (copy)
1701 {
1702 memset(copy, 0, sizeof(CERT_SIMPLE_CHAIN));
1703 copy->cbSize = sizeof(CERT_SIMPLE_CHAIN);
1704 copy->rgpElement =
1705 CryptMemAlloc((iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
1706 if (copy->rgpElement)
1707 {
1708 DWORD i;
1709 BOOL ret = TRUE;
1710
1711 memset(copy->rgpElement, 0,
1712 (iElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
1713 for (i = 0; ret && i <= iElement; i++)
1714 {
1715 PCERT_CHAIN_ELEMENT element =
1716 CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
1717
1718 if (element)
1719 {
1720 *element = *chain->rgpElement[i];
1721 element->pCertContext = CertDuplicateCertificateContext(
1722 chain->rgpElement[i]->pCertContext);
1723 /* Reset the trust status of the copied element, it'll get
1724 * rechecked after the new chain is done.
1725 */
1726 memset(&element->TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
1727 copy->rgpElement[copy->cElement++] = element;
1728 }
1729 else
1730 ret = FALSE;
1731 }
1732 if (!ret)
1733 {
1734 for (i = 0; i <= iElement; i++)
1735 CryptMemFree(copy->rgpElement[i]);
1736 CryptMemFree(copy->rgpElement);
1737 CryptMemFree(copy);
1738 copy = NULL;
1739 }
1740 }
1741 else
1742 {
1743 CryptMemFree(copy);
1744 copy = NULL;
1745 }
1746 }
1747 return copy;
1748 }
1749
1750 static void CRYPT_FreeLowerQualityChains(PCertificateChain chain)
1751 {
1752 DWORD i;
1753
1754 for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
1755 CertFreeCertificateChain(chain->context.rgpLowerQualityChainContext[i]);
1756 CryptMemFree(chain->context.rgpLowerQualityChainContext);
1757 chain->context.cLowerQualityChainContext = 0;
1758 chain->context.rgpLowerQualityChainContext = NULL;
1759 }
1760
1761 static void CRYPT_FreeChainContext(PCertificateChain chain)
1762 {
1763 DWORD i;
1764
1765 CRYPT_FreeLowerQualityChains(chain);
1766 for (i = 0; i < chain->context.cChain; i++)
1767 CRYPT_FreeSimpleChain(chain->context.rgpChain[i]);
1768 CryptMemFree(chain->context.rgpChain);
1769 CertCloseStore(chain->world, 0);
1770 CryptMemFree(chain);
1771 }
1772
1773 /* Makes and returns a copy of chain, up to and including element iElement of
1774 * simple chain iChain.
1775 */
1776 static PCertificateChain CRYPT_CopyChainToElement(PCertificateChain chain,
1777 DWORD iChain, DWORD iElement)
1778 {
1779 PCertificateChain copy = CryptMemAlloc(sizeof(CertificateChain));
1780
1781 if (copy)
1782 {
1783 copy->ref = 1;
1784 copy->world = CertDuplicateStore(chain->world);
1785 copy->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
1786 /* Leave the trust status of the copied chain unset, it'll get
1787 * rechecked after the new chain is done.
1788 */
1789 memset(&copy->context.TrustStatus, 0, sizeof(CERT_TRUST_STATUS));
1790 copy->context.cLowerQualityChainContext = 0;
1791 copy->context.rgpLowerQualityChainContext = NULL;
1792 copy->context.fHasRevocationFreshnessTime = FALSE;
1793 copy->context.dwRevocationFreshnessTime = 0;
1794 copy->context.rgpChain = CryptMemAlloc(
1795 (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
1796 if (copy->context.rgpChain)
1797 {
1798 BOOL ret = TRUE;
1799 DWORD i;
1800
1801 memset(copy->context.rgpChain, 0,
1802 (iChain + 1) * sizeof(PCERT_SIMPLE_CHAIN));
1803 if (iChain)
1804 {
1805 for (i = 0; ret && iChain && i < iChain - 1; i++)
1806 {
1807 copy->context.rgpChain[i] =
1808 CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
1809 chain->context.rgpChain[i]->cElement - 1);
1810 if (!copy->context.rgpChain[i])
1811 ret = FALSE;
1812 }
1813 }
1814 else
1815 i = 0;
1816 if (ret)
1817 {
1818 copy->context.rgpChain[i] =
1819 CRYPT_CopySimpleChainToElement(chain->context.rgpChain[i],
1820 iElement);
1821 if (!copy->context.rgpChain[i])
1822 ret = FALSE;
1823 }
1824 if (!ret)
1825 {
1826 CRYPT_FreeChainContext(copy);
1827 copy = NULL;
1828 }
1829 else
1830 copy->context.cChain = iChain + 1;
1831 }
1832 else
1833 {
1834 CryptMemFree(copy);
1835 copy = NULL;
1836 }
1837 }
1838 return copy;
1839 }
1840
1841 static PCertificateChain CRYPT_BuildAlternateContextFromChain(
1842 HCERTCHAINENGINE hChainEngine, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
1843 PCertificateChain chain)
1844 {
1845 PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
1846 PCertificateChain alternate;
1847
1848 TRACE("(%p, %p, %p, %p)\n", hChainEngine, pTime, hAdditionalStore, chain);
1849
1850 /* Always start with the last "lower quality" chain to ensure a consistent
1851 * order of alternate creation:
1852 */
1853 if (chain->context.cLowerQualityChainContext)
1854 chain = (PCertificateChain)chain->context.rgpLowerQualityChainContext[
1855 chain->context.cLowerQualityChainContext - 1];
1856 /* A chain with only one element can't have any alternates */
1857 if (chain->context.cChain <= 1 && chain->context.rgpChain[0]->cElement <= 1)
1858 alternate = NULL;
1859 else
1860 {
1861 DWORD i, j, infoStatus;
1862 PCCERT_CONTEXT alternateIssuer = NULL;
1863
1864 alternate = NULL;
1865 for (i = 0; !alternateIssuer && i < chain->context.cChain; i++)
1866 for (j = 0; !alternateIssuer &&
1867 j < chain->context.rgpChain[i]->cElement - 1; j++)
1868 {
1869 PCCERT_CONTEXT subject =
1870 chain->context.rgpChain[i]->rgpElement[j]->pCertContext;
1871 PCCERT_CONTEXT prevIssuer = CertDuplicateCertificateContext(
1872 chain->context.rgpChain[i]->rgpElement[j + 1]->pCertContext);
1873
1874 alternateIssuer = CRYPT_GetIssuer(prevIssuer->hCertStore,
1875 subject, prevIssuer, &infoStatus);
1876 }
1877 if (alternateIssuer)
1878 {
1879 i--;
1880 j--;
1881 alternate = CRYPT_CopyChainToElement(chain, i, j);
1882 if (alternate)
1883 {
1884 BOOL ret = CRYPT_AddCertToSimpleChain(engine,
1885 alternate->context.rgpChain[i], alternateIssuer, infoStatus);
1886
1887 /* CRYPT_AddCertToSimpleChain add-ref's the issuer, so free it
1888 * to close the enumeration that found it
1889 */
1890 CertFreeCertificateContext(alternateIssuer);
1891 if (ret)
1892 {
1893 ret = CRYPT_BuildSimpleChain(engine, alternate->world,
1894 alternate->context.rgpChain[i]);
1895 if (ret)
1896 CRYPT_CheckSimpleChain(engine,
1897 alternate->context.rgpChain[i], pTime);
1898 CRYPT_CombineTrustStatus(&alternate->context.TrustStatus,
1899 &alternate->context.rgpChain[i]->TrustStatus);
1900 }
1901 if (!ret)
1902 {
1903 CRYPT_FreeChainContext(alternate);
1904 alternate = NULL;
1905 }
1906 }
1907 }
1908 }
1909 TRACE("%p\n", alternate);
1910 return alternate;
1911 }
1912
1913 #define CHAIN_QUALITY_SIGNATURE_VALID 0x16
1914 #define CHAIN_QUALITY_TIME_VALID 8
1915 #define CHAIN_QUALITY_COMPLETE_CHAIN 4
1916 #define CHAIN_QUALITY_BASIC_CONSTRAINTS 2
1917 #define CHAIN_QUALITY_TRUSTED_ROOT 1
1918
1919 #define CHAIN_QUALITY_HIGHEST \
1920 CHAIN_QUALITY_SIGNATURE_VALID | CHAIN_QUALITY_TIME_VALID | \
1921 CHAIN_QUALITY_COMPLETE_CHAIN | CHAIN_QUALITY_BASIC_CONSTRAINTS | \
1922 CHAIN_QUALITY_TRUSTED_ROOT
1923
1924 #define IS_TRUST_ERROR_SET(TrustStatus, bits) \
1925 (TrustStatus)->dwErrorStatus & (bits)
1926
1927 static DWORD CRYPT_ChainQuality(const CertificateChain *chain)
1928 {
1929 DWORD quality = CHAIN_QUALITY_HIGHEST;
1930
1931 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1932 CERT_TRUST_IS_UNTRUSTED_ROOT))
1933 quality &= ~CHAIN_QUALITY_TRUSTED_ROOT;
1934 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1935 CERT_TRUST_INVALID_BASIC_CONSTRAINTS))
1936 quality &= ~CHAIN_QUALITY_BASIC_CONSTRAINTS;
1937 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1938 CERT_TRUST_IS_PARTIAL_CHAIN))
1939 quality &= ~CHAIN_QUALITY_COMPLETE_CHAIN;
1940 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1941 CERT_TRUST_IS_NOT_TIME_VALID | CERT_TRUST_IS_NOT_TIME_NESTED))
1942 quality &= ~CHAIN_QUALITY_TIME_VALID;
1943 if (IS_TRUST_ERROR_SET(&chain->context.TrustStatus,
1944 CERT_TRUST_IS_NOT_SIGNATURE_VALID))
1945 quality &= ~CHAIN_QUALITY_SIGNATURE_VALID;
1946 return quality;
1947 }
1948
1949 /* Chooses the highest quality chain among chain and its "lower quality"
1950 * alternate chains. Returns the highest quality chain, with all other
1951 * chains as lower quality chains of it.
1952 */
1953 static PCertificateChain CRYPT_ChooseHighestQualityChain(
1954 PCertificateChain chain)
1955 {
1956 DWORD i;
1957
1958 /* There are always only two chains being considered: chain, and an
1959 * alternate at chain->rgpLowerQualityChainContext[i]. If the alternate
1960 * has a higher quality than chain, the alternate gets assigned the lower
1961 * quality contexts, with chain taking the alternate's place among the
1962 * lower quality contexts.
1963 */
1964 for (i = 0; i < chain->context.cLowerQualityChainContext; i++)
1965 {
1966 PCertificateChain alternate =
1967 (PCertificateChain)chain->context.rgpLowerQualityChainContext[i];
1968
1969 if (CRYPT_ChainQuality(alternate) > CRYPT_ChainQuality(chain))
1970 {
1971 alternate->context.cLowerQualityChainContext =
1972 chain->context.cLowerQualityChainContext;
1973 alternate->context.rgpLowerQualityChainContext =
1974 chain->context.rgpLowerQualityChainContext;
1975 alternate->context.rgpLowerQualityChainContext[i] =
1976 (PCCERT_CHAIN_CONTEXT)chain;
1977 chain->context.cLowerQualityChainContext = 0;
1978 chain->context.rgpLowerQualityChainContext = NULL;
1979 chain = alternate;
1980 }
1981 }
1982 return chain;
1983 }
1984
1985 static BOOL CRYPT_AddAlternateChainToChain(PCertificateChain chain,
1986 const CertificateChain *alternate)
1987 {
1988 BOOL ret;
1989
1990 if (chain->context.cLowerQualityChainContext)
1991 chain->context.rgpLowerQualityChainContext =
1992 CryptMemRealloc(chain->context.rgpLowerQualityChainContext,
1993 (chain->context.cLowerQualityChainContext + 1) *
1994 sizeof(PCCERT_CHAIN_CONTEXT));
1995 else
1996 chain->context.rgpLowerQualityChainContext =
1997 CryptMemAlloc(sizeof(PCCERT_CHAIN_CONTEXT));
1998 if (chain->context.rgpLowerQualityChainContext)
1999 {
2000 chain->context.rgpLowerQualityChainContext[
2001 chain->context.cLowerQualityChainContext++] =
2002 (PCCERT_CHAIN_CONTEXT)alternate;
2003 ret = TRUE;
2004 }
2005 else
2006 ret = FALSE;
2007 return ret;
2008 }
2009
2010 static PCERT_CHAIN_ELEMENT CRYPT_FindIthElementInChain(
2011 const CERT_CHAIN_CONTEXT *chain, DWORD i)
2012 {
2013 DWORD j, iElement;
2014 PCERT_CHAIN_ELEMENT element = NULL;
2015
2016 for (j = 0, iElement = 0; !element && j < chain->cChain; j++)
2017 {
2018 if (iElement + chain->rgpChain[j]->cElement < i)
2019 iElement += chain->rgpChain[j]->cElement;
2020 else
2021 element = chain->rgpChain[j]->rgpElement[i - iElement];
2022 }
2023 return element;
2024 }
2025
2026 typedef struct _CERT_CHAIN_PARA_NO_EXTRA_FIELDS {
2027 DWORD cbSize;
2028 CERT_USAGE_MATCH RequestedUsage;
2029 } CERT_CHAIN_PARA_NO_EXTRA_FIELDS, *PCERT_CHAIN_PARA_NO_EXTRA_FIELDS;
2030
2031 static void CRYPT_VerifyChainRevocation(PCERT_CHAIN_CONTEXT chain,
2032 LPFILETIME pTime, const CERT_CHAIN_PARA *pChainPara, DWORD chainFlags)
2033 {
2034 DWORD cContext;
2035
2036 if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_END_CERT)
2037 cContext = 1;
2038 else if ((chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN) ||
2039 (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT))
2040 {
2041 DWORD i;
2042
2043 for (i = 0, cContext = 0; i < chain->cChain; i++)
2044 {
2045 if (i < chain->cChain - 1 ||
2046 chainFlags & CERT_CHAIN_REVOCATION_CHECK_CHAIN)
2047 cContext += chain->rgpChain[i]->cElement;
2048 else
2049 cContext += chain->rgpChain[i]->cElement - 1;
2050 }
2051 }
2052 else
2053 cContext = 0;
2054 if (cContext)
2055 {
2056 PCCERT_CONTEXT *contexts =
2057 CryptMemAlloc(cContext * sizeof(PCCERT_CONTEXT *));
2058
2059 if (contexts)
2060 {
2061 DWORD i, j, iContext, revocationFlags;
2062 CERT_REVOCATION_PARA revocationPara = { sizeof(revocationPara), 0 };
2063 CERT_REVOCATION_STATUS revocationStatus =
2064 { sizeof(revocationStatus), 0 };
2065 BOOL ret;
2066
2067 for (i = 0, iContext = 0; iContext < cContext && i < chain->cChain;
2068 i++)
2069 {
2070 for (j = 0; iContext < cContext &&
2071 j < chain->rgpChain[i]->cElement; j++)
2072 contexts[iContext++] =
2073 chain->rgpChain[i]->rgpElement[j]->pCertContext;
2074 }
2075 revocationFlags = CERT_VERIFY_REV_CHAIN_FLAG;
2076 if (chainFlags & CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY)
2077 revocationFlags |= CERT_VERIFY_CACHE_ONLY_BASED_REVOCATION;
2078 if (chainFlags & CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT)
2079 revocationFlags |= CERT_VERIFY_REV_ACCUMULATIVE_TIMEOUT_FLAG;
2080 revocationPara.pftTimeToUse = pTime;
2081 if (pChainPara->cbSize == sizeof(CERT_CHAIN_PARA))
2082 {
2083 revocationPara.dwUrlRetrievalTimeout =
2084 pChainPara->dwUrlRetrievalTimeout;
2085 revocationPara.fCheckFreshnessTime =
2086 pChainPara->fCheckRevocationFreshnessTime;
2087 revocationPara.dwFreshnessTime =
2088 pChainPara->dwRevocationFreshnessTime;
2089 }
2090 ret = CertVerifyRevocation(X509_ASN_ENCODING,
2091 CERT_CONTEXT_REVOCATION_TYPE, cContext, (void **)contexts,
2092 revocationFlags, &revocationPara, &revocationStatus);
2093 if (!ret)
2094 {
2095 PCERT_CHAIN_ELEMENT element =
2096 CRYPT_FindIthElementInChain(chain, revocationStatus.dwIndex);
2097 DWORD error;
2098
2099 switch (revocationStatus.dwError)
2100 {
2101 case CRYPT_E_NO_REVOCATION_CHECK:
2102 case CRYPT_E_NO_REVOCATION_DLL:
2103 case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
2104 error = CERT_TRUST_REVOCATION_STATUS_UNKNOWN;
2105 break;
2106 case CRYPT_E_REVOCATION_OFFLINE:
2107 error = CERT_TRUST_IS_OFFLINE_REVOCATION;
2108 break;
2109 case CRYPT_E_REVOKED:
2110 error = CERT_TRUST_IS_REVOKED;
2111 break;
2112 default:
2113 WARN("unmapped error %08x\n", revocationStatus.dwError);
2114 error = 0;
2115 }
2116 if (element)
2117 {
2118 /* FIXME: set element's pRevocationInfo member */
2119 element->TrustStatus.dwErrorStatus |= error;
2120 }
2121 chain->TrustStatus.dwErrorStatus |= error;
2122 }
2123 CryptMemFree(contexts);
2124 }
2125 }
2126 }
2127
2128 static void dump_usage_match(LPCSTR name, const CERT_USAGE_MATCH *usageMatch)
2129 {
2130 DWORD i;
2131
2132 TRACE_(chain)("%s: %s\n", name,
2133 usageMatch->dwType == USAGE_MATCH_TYPE_AND ? "AND" : "OR");
2134 for (i = 0; i < usageMatch->Usage.cUsageIdentifier; i++)
2135 TRACE_(chain)("%s\n", usageMatch->Usage.rgpszUsageIdentifier[i]);
2136 }
2137
2138 static void dump_chain_para(const CERT_CHAIN_PARA *pChainPara)
2139 {
2140 TRACE_(chain)("%d\n", pChainPara->cbSize);
2141 if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA_NO_EXTRA_FIELDS))
2142 dump_usage_match("RequestedUsage", &pChainPara->RequestedUsage);
2143 if (pChainPara->cbSize >= sizeof(CERT_CHAIN_PARA))
2144 {
2145 dump_usage_match("RequestedIssuancePolicy",
2146 &pChainPara->RequestedIssuancePolicy);
2147 TRACE_(chain)("%d\n", pChainPara->dwUrlRetrievalTimeout);
2148 TRACE_(chain)("%d\n", pChainPara->fCheckRevocationFreshnessTime);
2149 TRACE_(chain)("%d\n", pChainPara->dwRevocationFreshnessTime);
2150 }
2151 }
2152
2153 BOOL WINAPI CertGetCertificateChain(HCERTCHAINENGINE hChainEngine,
2154 PCCERT_CONTEXT pCertContext, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
2155 PCERT_CHAIN_PARA pChainPara, DWORD dwFlags, LPVOID pvReserved,
2156 PCCERT_CHAIN_CONTEXT* ppChainContext)
2157 {
2158 BOOL ret;
2159 PCertificateChain chain = NULL;
2160
2161 TRACE("(%p, %p, %p, %p, %p, %08x, %p, %p)\n", hChainEngine, pCertContext,
2162 pTime, hAdditionalStore, pChainPara, dwFlags, pvReserved, ppChainContext);
2163
2164 if (ppChainContext)
2165 *ppChainContext = NULL;
2166 if (!pChainPara)
2167 {
2168 SetLastError(E_INVALIDARG);
2169 return FALSE;
2170 }
2171 if (!pCertContext->pCertInfo->SignatureAlgorithm.pszObjId)
2172 {
2173 SetLastError(ERROR_INVALID_DATA);
2174 return FALSE;
2175 }
2176
2177 if (!hChainEngine)
2178 hChainEngine = CRYPT_GetDefaultChainEngine();
2179 if (TRACE_ON(chain))
2180 dump_chain_para(pChainPara);
2181 /* FIXME: what about HCCE_LOCAL_MACHINE? */
2182 ret = CRYPT_BuildCandidateChainFromCert(hChainEngine, pCertContext, pTime,
2183 hAdditionalStore, &chain);
2184 if (ret)
2185 {
2186 PCertificateChain alternate = NULL;
2187 PCERT_CHAIN_CONTEXT pChain;
2188
2189 do {
2190 alternate = CRYPT_BuildAlternateContextFromChain(hChainEngine,
2191 pTime, hAdditionalStore, chain);
2192
2193 /* Alternate contexts are added as "lower quality" contexts of
2194 * chain, to avoid loops in alternate chain creation.
2195 * The highest-quality chain is chosen at the end.
2196 */
2197 if (alternate)
2198 ret = CRYPT_AddAlternateChainToChain(chain, alternate);
2199 } while (ret && alternate);
2200 chain = CRYPT_ChooseHighestQualityChain(chain);
2201 if (!(dwFlags & CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS))
2202 CRYPT_FreeLowerQualityChains(chain);
2203 pChain = (PCERT_CHAIN_CONTEXT)chain;
2204 CRYPT_VerifyChainRevocation(pChain, pTime, pChainPara, dwFlags);
2205 if (ppChainContext)
2206 *ppChainContext = pChain;
2207 else
2208 CertFreeCertificateChain(pChain);
2209 }
2210 TRACE("returning %d\n", ret);
2211 return ret;
2212 }
2213
2214 PCCERT_CHAIN_CONTEXT WINAPI CertDuplicateCertificateChain(
2215 PCCERT_CHAIN_CONTEXT pChainContext)
2216 {
2217 PCertificateChain chain = (PCertificateChain)pChainContext;
2218
2219 TRACE("(%p)\n", pChainContext);
2220
2221 if (chain)
2222 InterlockedIncrement(&chain->ref);
2223 return pChainContext;
2224 }
2225
2226 VOID WINAPI CertFreeCertificateChain(PCCERT_CHAIN_CONTEXT pChainContext)
2227 {
2228 PCertificateChain chain = (PCertificateChain)pChainContext;
2229
2230 TRACE("(%p)\n", pChainContext);
2231
2232 if (chain)
2233 {
2234 if (InterlockedDecrement(&chain->ref) == 0)
2235 CRYPT_FreeChainContext(chain);
2236 }
2237 }
2238
2239 static void find_element_with_error(PCCERT_CHAIN_CONTEXT chain, DWORD error,
2240 LONG *iChain, LONG *iElement)
2241 {
2242 DWORD i, j;
2243
2244 for (i = 0; i < chain->cChain; i++)
2245 for (j = 0; j < chain->rgpChain[i]->cElement; j++)
2246 if (chain->rgpChain[i]->rgpElement[j]->TrustStatus.dwErrorStatus &
2247 error)
2248 {
2249 *iChain = i;
2250 *iElement = j;
2251 return;
2252 }
2253 }
2254
2255 static BOOL WINAPI verify_base_policy(LPCSTR szPolicyOID,
2256 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2257 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2258 {
2259 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2260 if (pChainContext->TrustStatus.dwErrorStatus &
2261 CERT_TRUST_IS_NOT_SIGNATURE_VALID)
2262 {
2263 pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
2264 find_element_with_error(pChainContext,
2265 CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
2266 &pPolicyStatus->lElementIndex);
2267 }
2268 else if (pChainContext->TrustStatus.dwErrorStatus &
2269 CERT_TRUST_IS_UNTRUSTED_ROOT)
2270 {
2271 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
2272 find_element_with_error(pChainContext,
2273 CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
2274 &pPolicyStatus->lElementIndex);
2275 }
2276 else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
2277 {
2278 pPolicyStatus->dwError = CERT_E_CHAINING;
2279 find_element_with_error(pChainContext, CERT_TRUST_IS_CYCLIC,
2280 &pPolicyStatus->lChainIndex, &pPolicyStatus->lElementIndex);
2281 /* For a cyclic chain, which element is a cycle isn't meaningful */
2282 pPolicyStatus->lElementIndex = -1;
2283 }
2284 else
2285 pPolicyStatus->dwError = NO_ERROR;
2286 return TRUE;
2287 }
2288
2289 static BYTE msTestPubKey1[] = {
2290 0x30,0x47,0x02,0x40,0x81,0x55,0x22,0xb9,0x8a,0xa4,0x6f,0xed,0xd6,0xe7,0xd9,
2291 0x66,0x0f,0x55,0xbc,0xd7,0xcd,0xd5,0xbc,0x4e,0x40,0x02,0x21,0xa2,0xb1,0xf7,
2292 0x87,0x30,0x85,0x5e,0xd2,0xf2,0x44,0xb9,0xdc,0x9b,0x75,0xb6,0xfb,0x46,0x5f,
2293 0x42,0xb6,0x9d,0x23,0x36,0x0b,0xde,0x54,0x0f,0xcd,0xbd,0x1f,0x99,0x2a,0x10,
2294 0x58,0x11,0xcb,0x40,0xcb,0xb5,0xa7,0x41,0x02,0x03,0x01,0x00,0x01 };
2295 static BYTE msTestPubKey2[] = {
2296 0x30,0x47,0x02,0x40,0x9c,0x50,0x05,0x1d,0xe2,0x0e,0x4c,0x53,0xd8,0xd9,0xb5,
2297 0xe5,0xfd,0xe9,0xe3,0xad,0x83,0x4b,0x80,0x08,0xd9,0xdc,0xe8,0xe8,0x35,0xf8,
2298 0x11,0xf1,0xe9,0x9b,0x03,0x7a,0x65,0x64,0x76,0x35,0xce,0x38,0x2c,0xf2,0xb6,
2299 0x71,0x9e,0x06,0xd9,0xbf,0xbb,0x31,0x69,0xa3,0xf6,0x30,0xa0,0x78,0x7b,0x18,
2300 0xdd,0x50,0x4d,0x79,0x1e,0xeb,0x61,0xc1,0x02,0x03,0x01,0x00,0x01 };
2301
2302 static BOOL WINAPI verify_authenticode_policy(LPCSTR szPolicyOID,
2303 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2304 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2305 {
2306 BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
2307 pPolicyStatus);
2308
2309 if (ret && pPolicyStatus->dwError == CERT_E_UNTRUSTEDROOT)
2310 {
2311 CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
2312 BOOL isMSTestRoot = FALSE;
2313 PCCERT_CONTEXT failingCert =
2314 pChainContext->rgpChain[pPolicyStatus->lChainIndex]->
2315 rgpElement[pPolicyStatus->lElementIndex]->pCertContext;
2316 DWORD i;
2317 CRYPT_DATA_BLOB keyBlobs[] = {
2318 { sizeof(msTestPubKey1), msTestPubKey1 },
2319 { sizeof(msTestPubKey2), msTestPubKey2 },
2320 };
2321
2322 /* Check whether the root is an MS test root */
2323 for (i = 0; !isMSTestRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
2324 i++)
2325 {
2326 msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
2327 msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
2328 if (CertComparePublicKeyInfo(
2329 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
2330 &failingCert->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
2331 isMSTestRoot = TRUE;
2332 }
2333 if (isMSTestRoot)
2334 pPolicyStatus->dwError = CERT_E_UNTRUSTEDTESTROOT;
2335 }
2336 return ret;
2337 }
2338
2339 static BOOL WINAPI verify_basic_constraints_policy(LPCSTR szPolicyOID,
2340 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2341 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2342 {
2343 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2344 if (pChainContext->TrustStatus.dwErrorStatus &
2345 CERT_TRUST_INVALID_BASIC_CONSTRAINTS)
2346 {
2347 pPolicyStatus->dwError = TRUST_E_BASIC_CONSTRAINTS;
2348 find_element_with_error(pChainContext,
2349 CERT_TRUST_INVALID_BASIC_CONSTRAINTS, &pPolicyStatus->lChainIndex,
2350 &pPolicyStatus->lElementIndex);
2351 }
2352 else
2353 pPolicyStatus->dwError = NO_ERROR;
2354 return TRUE;
2355 }
2356
2357 static BOOL match_dns_to_subject_alt_name(PCERT_EXTENSION ext,
2358 LPCWSTR server_name)
2359 {
2360 BOOL matches = FALSE;
2361 CERT_ALT_NAME_INFO *subjectName;
2362 DWORD size;
2363
2364 TRACE_(chain)("%s\n", debugstr_w(server_name));
2365 /* This could be spoofed by the embedded NULL vulnerability, since the
2366 * returned CERT_ALT_NAME_INFO doesn't have a way to indicate the
2367 * encoded length of a name. Fortunately CryptDecodeObjectEx fails if
2368 * the encoded form of the name contains a NULL.
2369 */
2370 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ALTERNATE_NAME,
2371 ext->Value.pbData, ext->Value.cbData,
2372 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2373 &subjectName, &size))
2374 {
2375 DWORD i;
2376
2377 /* RFC 5280 states that multiple instances of each name type may exist,
2378 * in section 4.2.1.6:
2379 * "Multiple name forms, and multiple instances of each name form,
2380 * MAY be included."
2381 * It doesn't specify the behavior in such cases, but common usage is
2382 * to accept a certificate if any name matches.
2383 */
2384 for (i = 0; !matches && i < subjectName->cAltEntry; i++)
2385 {
2386 if (subjectName->rgAltEntry[i].dwAltNameChoice ==
2387 CERT_ALT_NAME_DNS_NAME)
2388 {
2389 TRACE_(chain)("dNSName: %s\n", debugstr_w(
2390 subjectName->rgAltEntry[i].u.pwszDNSName));
2391 if (!strcmpiW(server_name,
2392 subjectName->rgAltEntry[i].u.pwszDNSName))
2393 matches = TRUE;
2394 }
2395 }
2396 LocalFree(subjectName);
2397 }
2398 return matches;
2399 }
2400
2401 static BOOL find_matching_domain_component(CERT_NAME_INFO *name,
2402 LPCWSTR component)
2403 {
2404 BOOL matches = FALSE;
2405 DWORD i, j;
2406
2407 for (i = 0; !matches && i < name->cRDN; i++)
2408 for (j = 0; j < name->rgRDN[i].cRDNAttr; j++)
2409 if (!strcmp(szOID_DOMAIN_COMPONENT,
2410 name->rgRDN[i].rgRDNAttr[j].pszObjId))
2411 {
2412 PCERT_RDN_ATTR attr;
2413
2414 attr = &name->rgRDN[i].rgRDNAttr[j];
2415 /* Compare with memicmpW rather than strcmpiW in order to avoid
2416 * a match with a string with an embedded NULL. The component
2417 * must match one domain component attribute's entire string
2418 * value with a case-insensitive match.
2419 */
2420 matches = !memicmpW(component, (LPWSTR)attr->Value.pbData,
2421 attr->Value.cbData / sizeof(WCHAR));
2422 }
2423 return matches;
2424 }
2425
2426 static BOOL match_domain_component(LPCWSTR allowed_component, DWORD allowed_len,
2427 LPCWSTR server_component, DWORD server_len, BOOL allow_wildcards,
2428 BOOL *see_wildcard)
2429 {
2430 LPCWSTR allowed_ptr, server_ptr;
2431 BOOL matches = TRUE;
2432
2433 *see_wildcard = FALSE;
2434 if (server_len < allowed_len)
2435 {
2436 WARN_(chain)("domain component %s too short for %s\n",
2437 debugstr_wn(server_component, server_len),
2438 debugstr_wn(allowed_component, allowed_len));
2439 /* A domain component can't contain a wildcard character, so a domain
2440 * component shorter than the allowed string can't produce a match.
2441 */
2442 return FALSE;
2443 }
2444 for (allowed_ptr = allowed_component, server_ptr = server_component;
2445 matches && allowed_ptr - allowed_component < allowed_len;
2446 allowed_ptr++, server_ptr++)
2447 {
2448 if (*allowed_ptr == '*')
2449 {
2450 if (allowed_ptr - allowed_component < allowed_len - 1)
2451 {
2452 WARN_(chain)("non-wildcard characters after wildcard not supported\n");
2453 matches = FALSE;
2454 }
2455 else if (!allow_wildcards)
2456 {
2457 WARN_(chain)("wildcard after non-wildcard component\n");
2458 matches = FALSE;
2459 }
2460 else
2461 {
2462 /* the preceding characters must have matched, so the rest of
2463 * the component also matches.
2464 */
2465 *see_wildcard = TRUE;
2466 break;
2467 }
2468 }
2469 matches = tolowerW(*allowed_ptr) == tolowerW(*server_ptr);
2470 }
2471 if (matches && server_ptr - server_component < server_len)
2472 {
2473 /* If there are unmatched characters in the server domain component,
2474 * the server domain only matches if the allowed string ended in a '*'.
2475 */
2476 matches = *allowed_ptr == '*';
2477 }
2478 return matches;
2479 }
2480
2481 static BOOL match_common_name(LPCWSTR server_name, PCERT_RDN_ATTR nameAttr)
2482 {
2483 LPCWSTR allowed = (LPCWSTR)nameAttr->Value.pbData;
2484 LPCWSTR allowed_component = allowed;
2485 DWORD allowed_len = nameAttr->Value.cbData / sizeof(WCHAR);
2486 LPCWSTR server_component = server_name;
2487 DWORD server_len = strlenW(server_name);
2488 BOOL matches = TRUE, allow_wildcards = TRUE;
2489
2490 TRACE_(chain)("CN = %s\n", debugstr_wn(allowed_component, allowed_len));
2491
2492 /* From RFC 2818 (HTTP over TLS), section 3.1:
2493 * "Names may contain the wildcard character * which is considered to match
2494 * any single domain name component or component fragment. E.g.,
2495 * *.a.com matches foo.a.com but not bar.foo.a.com. f*.com matches foo.com
2496 * but not bar.com."
2497 *
2498 * And from RFC 2595 (Using TLS with IMAP, POP3 and ACAP), section 2.4:
2499 * "A "*" wildcard character MAY be used as the left-most name component in
2500 * the certificate. For example, *.example.com would match a.example.com,
2501 * foo.example.com, etc. but would not match example.com."
2502 *
2503 * There are other protocols which use TLS, and none of them is
2504 * authoritative. This accepts certificates in common usage, e.g.
2505 * *.domain.com matches www.domain.com but not domain.com, and
2506 * www*.domain.com matches www1.domain.com but not mail.domain.com.
2507 */
2508 do {
2509 LPCWSTR allowed_dot, server_dot;
2510
2511 allowed_dot = memchrW(allowed_component, '.',
2512 allowed_len - (allowed_component - allowed));
2513 server_dot = memchrW(server_component, '.',
2514 server_len - (server_component - server_name));
2515 /* The number of components must match */
2516 if ((!allowed_dot && server_dot) || (allowed_dot && !server_dot))
2517 {
2518 if (!allowed_dot)
2519 WARN_(chain)("%s: too many components for CN=%s\n",
2520 debugstr_w(server_name), debugstr_wn(allowed, allowed_len));
2521 else
2522 WARN_(chain)("%s: not enough components for CN=%s\n",
2523 debugstr_w(server_name), debugstr_wn(allowed, allowed_len));
2524 matches = FALSE;
2525 }
2526 else
2527 {
2528 LPCWSTR allowed_end, server_end;
2529 BOOL has_wildcard;
2530
2531 allowed_end = allowed_dot ? allowed_dot : allowed + allowed_len;
2532 server_end = server_dot ? server_dot : server_name + server_len;
2533 matches = match_domain_component(allowed_component,
2534 allowed_end - allowed_component, server_component,
2535 server_end - server_component, allow_wildcards, &has_wildcard);
2536 /* Once a non-wildcard component is seen, no wildcard components
2537 * may follow
2538 */
2539 if (!has_wildcard)
2540 allow_wildcards = FALSE;
2541 if (matches)
2542 {
2543 allowed_component = allowed_dot ? allowed_dot + 1 : allowed_end;
2544 server_component = server_dot ? server_dot + 1 : server_end;
2545 }
2546 }
2547 } while (matches && allowed_component &&
2548 allowed_component - allowed < allowed_len &&
2549 server_component && server_component - server_name < server_len);
2550 TRACE_(chain)("returning %d\n", matches);
2551 return matches;
2552 }
2553
2554 static BOOL match_dns_to_subject_dn(PCCERT_CONTEXT cert, LPCWSTR server_name)
2555 {
2556 BOOL matches = FALSE;
2557 CERT_NAME_INFO *name;
2558 DWORD size;
2559
2560 TRACE_(chain)("%s\n", debugstr_w(server_name));
2561 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_UNICODE_NAME,
2562 cert->pCertInfo->Subject.pbData, cert->pCertInfo->Subject.cbData,
2563 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2564 &name, &size))
2565 {
2566 /* If the subject distinguished name contains any name components,
2567 * make sure all of them are present.
2568 */
2569 if (CertFindRDNAttr(szOID_DOMAIN_COMPONENT, name))
2570 {
2571 LPCWSTR ptr = server_name;
2572
2573 matches = TRUE;
2574 do {
2575 LPCWSTR dot = strchrW(ptr, '.'), end;
2576 /* 254 is the maximum DNS label length, see RFC 1035 */
2577 WCHAR component[255];
2578 DWORD len;
2579
2580 end = dot ? dot : ptr + strlenW(ptr);
2581 len = end - ptr;
2582 if (len >= sizeof(component) / sizeof(component[0]))
2583 {
2584 WARN_(chain)("domain component %s too long\n",
2585 debugstr_wn(ptr, len));
2586 matches = FALSE;
2587 }
2588 else
2589 {
2590 memcpy(component, ptr, len * sizeof(WCHAR));
2591 component[len] = 0;
2592 matches = find_matching_domain_component(name, component);
2593 }
2594 ptr = dot ? dot + 1 : end;
2595 } while (matches && ptr && *ptr);
2596 }
2597 else
2598 {
2599 PCERT_RDN_ATTR attr;
2600
2601 /* If the certificate isn't using a DN attribute in the name, make
2602 * make sure the common name matches.
2603 */
2604 if ((attr = CertFindRDNAttr(szOID_COMMON_NAME, name)))
2605 matches = match_common_name(server_name, attr);
2606 }
2607 LocalFree(name);
2608 }
2609 return matches;
2610 }
2611
2612 static BOOL WINAPI verify_ssl_policy(LPCSTR szPolicyOID,
2613 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2614 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2615 {
2616 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = -1;
2617 if (pChainContext->TrustStatus.dwErrorStatus &
2618 CERT_TRUST_IS_NOT_SIGNATURE_VALID)
2619 {
2620 pPolicyStatus->dwError = TRUST_E_CERT_SIGNATURE;
2621 find_element_with_error(pChainContext,
2622 CERT_TRUST_IS_NOT_SIGNATURE_VALID, &pPolicyStatus->lChainIndex,
2623 &pPolicyStatus->lElementIndex);
2624 }
2625 else if (pChainContext->TrustStatus.dwErrorStatus &
2626 CERT_TRUST_IS_UNTRUSTED_ROOT)
2627 {
2628 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
2629 find_element_with_error(pChainContext,
2630 CERT_TRUST_IS_UNTRUSTED_ROOT, &pPolicyStatus->lChainIndex,
2631 &pPolicyStatus->lElementIndex);
2632 }
2633 else if (pChainContext->TrustStatus.dwErrorStatus & CERT_TRUST_IS_CYCLIC)
2634 {
2635 pPolicyStatus->dwError = CERT_E_UNTRUSTEDROOT;
2636 find_element_with_error(pChainContext,
2637 CERT_TRUST_IS_CYCLIC, &pPolicyStatus->lChainIndex,
2638 &pPolicyStatus->lElementIndex);
2639 /* For a cyclic chain, which element is a cycle isn't meaningful */
2640 pPolicyStatus->lElementIndex = -1;
2641 }
2642 else if (pChainContext->TrustStatus.dwErrorStatus &
2643 CERT_TRUST_IS_NOT_TIME_VALID)
2644 {
2645 pPolicyStatus->dwError = CERT_E_EXPIRED;
2646 find_element_with_error(pChainContext,
2647 CERT_TRUST_IS_NOT_TIME_VALID, &pPolicyStatus->lChainIndex,
2648 &pPolicyStatus->lElementIndex);
2649 }
2650 else
2651 pPolicyStatus->dwError = NO_ERROR;
2652 /* We only need bother checking whether the name in the end certificate
2653 * matches if the chain is otherwise okay.
2654 */
2655 if (!pPolicyStatus->dwError && pPolicyPara &&
2656 pPolicyPara->cbSize >= sizeof(CERT_CHAIN_POLICY_PARA))
2657 {
2658 HTTPSPolicyCallbackData *sslPara = pPolicyPara->pvExtraPolicyPara;
2659
2660 if (sslPara && sslPara->u.cbSize >= sizeof(HTTPSPolicyCallbackData))
2661 {
2662 if (sslPara->dwAuthType == AUTHTYPE_SERVER &&
2663 sslPara->pwszServerName)
2664 {
2665 PCCERT_CONTEXT cert;
2666 PCERT_EXTENSION altNameExt;
2667 BOOL matches;
2668
2669 cert = pChainContext->rgpChain[0]->rgpElement[0]->pCertContext;
2670 altNameExt = get_subject_alt_name_ext(cert->pCertInfo);
2671 /* If the alternate name extension exists, the name it contains
2672 * is bound to the certificate, so make sure the name matches
2673 * it. Otherwise, look for the server name in the subject
2674 * distinguished name. RFC5280, section 4.2.1.6:
2675 * "Whenever such identities are to be bound into a
2676 * certificate, the subject alternative name (or issuer
2677 * alternative name) extension MUST be used; however, a DNS
2678 * name MAY also be represented in the subject field using the
2679 * domainComponent attribute."
2680 */
2681 if (altNameExt)
2682 matches = match_dns_to_subject_alt_name(altNameExt,
2683 sslPara->pwszServerName);
2684 else
2685 matches = match_dns_to_subject_dn(cert,
2686 sslPara->pwszServerName);
2687 if (!matches)
2688 {
2689 pPolicyStatus->dwError = CERT_E_CN_NO_MATCH;
2690 pPolicyStatus->lChainIndex = 0;
2691 pPolicyStatus->lElementIndex = 0;
2692 }
2693 }
2694 }
2695 }
2696 return TRUE;
2697 }
2698
2699 static BYTE msPubKey1[] = {
2700 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xdf,0x08,0xba,0xe3,0x3f,0x6e,
2701 0x64,0x9b,0xf5,0x89,0xaf,0x28,0x96,0x4a,0x07,0x8f,0x1b,0x2e,0x8b,0x3e,0x1d,
2702 0xfc,0xb8,0x80,0x69,0xa3,0xa1,0xce,0xdb,0xdf,0xb0,0x8e,0x6c,0x89,0x76,0x29,
2703 0x4f,0xca,0x60,0x35,0x39,0xad,0x72,0x32,0xe0,0x0b,0xae,0x29,0x3d,0x4c,0x16,
2704 0xd9,0x4b,0x3c,0x9d,0xda,0xc5,0xd3,0xd1,0x09,0xc9,0x2c,0x6f,0xa6,0xc2,0x60,
2705 0x53,0x45,0xdd,0x4b,0xd1,0x55,0xcd,0x03,0x1c,0xd2,0x59,0x56,0x24,0xf3,0xe5,
2706 0x78,0xd8,0x07,0xcc,0xd8,0xb3,0x1f,0x90,0x3f,0xc0,0x1a,0x71,0x50,0x1d,0x2d,
2707 0xa7,0x12,0x08,0x6d,0x7c,0xb0,0x86,0x6c,0xc7,0xba,0x85,0x32,0x07,0xe1,0x61,
2708 0x6f,0xaf,0x03,0xc5,0x6d,0xe5,0xd6,0xa1,0x8f,0x36,0xf6,0xc1,0x0b,0xd1,0x3e,
2709 0x69,0x97,0x48,0x72,0xc9,0x7f,0xa4,0xc8,0xc2,0x4a,0x4c,0x7e,0xa1,0xd1,0x94,
2710 0xa6,0xd7,0xdc,0xeb,0x05,0x46,0x2e,0xb8,0x18,0xb4,0x57,0x1d,0x86,0x49,0xdb,
2711 0x69,0x4a,0x2c,0x21,0xf5,0x5e,0x0f,0x54,0x2d,0x5a,0x43,0xa9,0x7a,0x7e,0x6a,
2712 0x8e,0x50,0x4d,0x25,0x57,0xa1,0xbf,0x1b,0x15,0x05,0x43,0x7b,0x2c,0x05,0x8d,
2713 0xbd,0x3d,0x03,0x8c,0x93,0x22,0x7d,0x63,0xea,0x0a,0x57,0x05,0x06,0x0a,0xdb,
2714 0x61,0x98,0x65,0x2d,0x47,0x49,0xa8,0xe7,0xe6,0x56,0x75,0x5c,0xb8,0x64,0x08,
2715 0x63,0xa9,0x30,0x40,0x66,0xb2,0xf9,0xb6,0xe3,0x34,0xe8,0x67,0x30,0xe1,0x43,
2716 0x0b,0x87,0xff,0xc9,0xbe,0x72,0x10,0x5e,0x23,0xf0,0x9b,0xa7,0x48,0x65,0xbf,
2717 0x09,0x88,0x7b,0xcd,0x72,0xbc,0x2e,0x79,0x9b,0x7b,0x02,0x03,0x01,0x00,0x01 };
2718 static BYTE msPubKey2[] = {
2719 0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xa9,0x02,0xbd,0xc1,0x70,0xe6,
2720 0x3b,0xf2,0x4e,0x1b,0x28,0x9f,0x97,0x78,0x5e,0x30,0xea,0xa2,0xa9,0x8d,0x25,
2721 0x5f,0xf8,0xfe,0x95,0x4c,0xa3,0xb7,0xfe,0x9d,0xa2,0x20,0x3e,0x7c,0x51,0xa2,
2722 0x9b,0xa2,0x8f,0x60,0x32,0x6b,0xd1,0x42,0x64,0x79,0xee,0xac,0x76,0xc9,0x54,
2723 0xda,0xf2,0xeb,0x9c,0x86,0x1c,0x8f,0x9f,0x84,0x66,0xb3,0xc5,0x6b,0x7a,0x62,
2724 0x23,0xd6,0x1d,0x3c,0xde,0x0f,0x01,0x92,0xe8,0x96,0xc4,0xbf,0x2d,0x66,0x9a,
2725 0x9a,0x68,0x26,0x99,0xd0,0x3a,0x2c,0xbf,0x0c,0xb5,0x58,0x26,0xc1,0x46,0xe7,
2726 0x0a,0x3e,0x38,0x96,0x2c,0xa9,0x28,0x39,0xa8,0xec,0x49,0x83,0x42,0xe3,0x84,
2727 0x0f,0xbb,0x9a,0x6c,0x55,0x61,0xac,0x82,0x7c,0xa1,0x60,0x2d,0x77,0x4c,0xe9,
2728 0x99,0xb4,0x64,0x3b,0x9a,0x50,0x1c,0x31,0x08,0x24,0x14,0x9f,0xa9,0xe7,0x91,
2729 0x2b,0x18,0xe6,0x3d,0x98,0x63,0x14,0x60,0x58,0x05,0x65,0x9f,0x1d,0x37,0x52,
2730 0x87,0xf7,0xa7,0xef,0x94,0x02,0xc6,0x1b,0xd3,0xbf,0x55,0x45,0xb3,0x89,0x80,
2731 0xbf,0x3a,0xec,0x54,0x94,0x4e,0xae,0xfd,0xa7,0x7a,0x6d,0x74,0x4e,0xaf,0x18,
2732 0xcc,0x96,0x09,0x28,0x21,0x00,0x57,0x90,0x60,0x69,0x37,0xbb,0x4b,0x12,0x07,
2733 0x3c,0x56,0xff,0x5b,0xfb,0xa4,0x66,0x0a,0x08,0xa6,0xd2,0x81,0x56,0x57,0xef,
2734 0xb6,0x3b,0x5e,0x16,0x81,0x77,0x04,0xda,0xf6,0xbe,0xae,0x80,0x95,0xfe,0xb0,
2735 0xcd,0x7f,0xd6,0xa7,0x1a,0x72,0x5c,0x3c,0xca,0xbc,0xf0,0x08,0xa3,0x22,0x30,
2736 0xb3,0x06,0x85,0xc9,0xb3,0x20,0x77,0x13,0x85,0xdf,0x02,0x03,0x01,0x00,0x01 };
2737 static BYTE msPubKey3[] = {
2738 0x30,0x82,0x02,0x0a,0x02,0x82,0x02,0x01,0x00,0xf3,0x5d,0xfa,0x80,0x67,0xd4,
2739 0x5a,0xa7,0xa9,0x0c,0x2c,0x90,0x20,0xd0,0x35,0x08,0x3c,0x75,0x84,0xcd,0xb7,
2740 0x07,0x89,0x9c,0x89,0xda,0xde,0xce,0xc3,0x60,0xfa,0x91,0x68,0x5a,0x9e,0x94,
2741 0x71,0x29,0x18,0x76,0x7c,0xc2,0xe0,0xc8,0x25,0x76,0x94,0x0e,0x58,0xfa,0x04,
2742 0x34,0x36,0xe6,0xdf,0xaf,0xf7,0x80,0xba,0xe9,0x58,0x0b,0x2b,0x93,0xe5,0x9d,
2743 0x05,0xe3,0x77,0x22,0x91,0xf7,0x34,0x64,0x3c,0x22,0x91,0x1d,0x5e,0xe1,0x09,
2744 0x90,0xbc,0x14,0xfe,0xfc,0x75,0x58,0x19,0xe1,0x79,0xb7,0x07,0x92,0xa3,0xae,
2745 0x88,0x59,0x08,0xd8,0x9f,0x07,0xca,0x03,0x58,0xfc,0x68,0x29,0x6d,0x32,0xd7,
2746 0xd2,0xa8,0xcb,0x4b,0xfc,0xe1,0x0b,0x48,0x32,0x4f,0xe6,0xeb,0xb8,0xad,0x4f,
2747 0xe4,0x5c,0x6f,0x13,0x94,0x99,0xdb,0x95,0xd5,0x75,0xdb,0xa8,0x1a,0xb7,0x94,
2748 0x91,0xb4,0x77,0x5b,0xf5,0x48,0x0c,0x8f,0x6a,0x79,0x7d,0x14,0x70,0x04,0x7d,
2749 0x6d,0xaf,0x90,0xf5,0xda,0x70,0xd8,0x47,0xb7,0xbf,0x9b,0x2f,0x6c,0xe7,0x05,
2750 0xb7,0xe1,0x11,0x60,0xac,0x79,0x91,0x14,0x7c,0xc5,0xd6,0xa6,0xe4,0xe1,0x7e,
2751 0xd5,0xc3,0x7e,0xe5,0x92,0xd2,0x3c,0x00,0xb5,0x36,0x82,0xde,0x79,0xe1,0x6d,
2752 0xf3,0xb5,0x6e,0xf8,0x9f,0x33,0xc9,0xcb,0x52,0x7d,0x73,0x98,0x36,0xdb,0x8b,
2753 0xa1,0x6b,0xa2,0x95,0x97,0x9b,0xa3,0xde,0xc2,0x4d,0x26,0xff,0x06,0x96,0x67,
2754 0x25,0x06,0xc8,0xe7,0xac,0xe4,0xee,0x12,0x33,0x95,0x31,0x99,0xc8,0x35,0x08,
2755 0x4e,0x34,0xca,0x79,0x53,0xd5,0xb5,0xbe,0x63,0x32,0x59,0x40,0x36,0xc0,0xa5,
2756 0x4e,0x04,0x4d,0x3d,0xdb,0x5b,0x07,0x33,0xe4,0x58,0xbf,0xef,0x3f,0x53,0x64,
2757 0xd8,0x42,0x59,0x35,0x57,0xfd,0x0f,0x45,0x7c,0x24,0x04,0x4d,0x9e,0xd6,0x38,
2758 0x74,0x11,0x97,0x22,0x90,0xce,0x68,0x44,0x74,0x92,0x6f,0xd5,0x4b,0x6f,0xb0,
2759 0x86,0xe3,0xc7,0x36,0x42,0xa0,0xd0,0xfc,0xc1,0xc0,0x5a,0xf9,0xa3,0x61,0xb9,
2760 0x30,0x47,0x71,0x96,0x0a,0x16,0xb0,0x91,0xc0,0x42,0x95,0xef,0x10,0x7f,0x28,
2761 0x6a,0xe3,0x2a,0x1f,0xb1,0xe4,0xcd,0x03,0x3f,0x77,0x71,0x04,0xc7,0x20,0xfc,
2762 0x49,0x0f,0x1d,0x45,0x88,0xa4,0xd7,0xcb,0x7e,0x88,0xad,0x8e,0x2d,0xec,0x45,
2763 0xdb,0xc4,0x51,0x04,0xc9,0x2a,0xfc,0xec,0x86,0x9e,0x9a,0x11,0x97,0x5b,0xde,
2764 0xce,0x53,0x88,0xe6,0xe2,0xb7,0xfd,0xac,0x95,0xc2,0x28,0x40,0xdb,0xef,0x04,
2765 0x90,0xdf,0x81,0x33,0x39,0xd9,0xb2,0x45,0xa5,0x23,0x87,0x06,0xa5,0x55,0x89,
2766 0x31,0xbb,0x06,0x2d,0x60,0x0e,0x41,0x18,0x7d,0x1f,0x2e,0xb5,0x97,0xcb,0x11,
2767 0xeb,0x15,0xd5,0x24,0xa5,0x94,0xef,0x15,0x14,0x89,0xfd,0x4b,0x73,0xfa,0x32,
2768 0x5b,0xfc,0xd1,0x33,0x00,0xf9,0x59,0x62,0x70,0x07,0x32,0xea,0x2e,0xab,0x40,
2769 0x2d,0x7b,0xca,0xdd,0x21,0x67,0x1b,0x30,0x99,0x8f,0x16,0xaa,0x23,0xa8,0x41,
2770 0xd1,0xb0,0x6e,0x11,0x9b,0x36,0xc4,0xde,0x40,0x74,0x9c,0xe1,0x58,0x65,0xc1,
2771 0x60,0x1e,0x7a,0x5b,0x38,0xc8,0x8f,0xbb,0x04,0x26,0x7c,0xd4,0x16,0x40,0xe5,
2772 0xb6,0x6b,0x6c,0xaa,0x86,0xfd,0x00,0xbf,0xce,0xc1,0x35,0x02,0x03,0x01,0x00,
2773 0x01 };
2774
2775 static BOOL WINAPI verify_ms_root_policy(LPCSTR szPolicyOID,
2776 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2777 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2778 {
2779 BOOL ret = verify_base_policy(szPolicyOID, pChainContext, pPolicyPara,
2780 pPolicyStatus);
2781
2782 if (ret && !pPolicyStatus->dwError)
2783 {
2784 CERT_PUBLIC_KEY_INFO msPubKey = { { 0 } };
2785 BOOL isMSRoot = FALSE;
2786 DWORD i;
2787 CRYPT_DATA_BLOB keyBlobs[] = {
2788 { sizeof(msPubKey1), msPubKey1 },
2789 { sizeof(msPubKey2), msPubKey2 },
2790 { sizeof(msPubKey3), msPubKey3 },
2791 };
2792 PCERT_SIMPLE_CHAIN rootChain =
2793 pChainContext->rgpChain[pChainContext->cChain -1 ];
2794 PCCERT_CONTEXT root =
2795 rootChain->rgpElement[rootChain->cElement - 1]->pCertContext;
2796
2797 for (i = 0; !isMSRoot && i < sizeof(keyBlobs) / sizeof(keyBlobs[0]);
2798 i++)
2799 {
2800 msPubKey.PublicKey.cbData = keyBlobs[i].cbData;
2801 msPubKey.PublicKey.pbData = keyBlobs[i].pbData;
2802 if (CertComparePublicKeyInfo(
2803 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
2804 &root->pCertInfo->SubjectPublicKeyInfo, &msPubKey))
2805 isMSRoot = TRUE;
2806 }
2807 if (isMSRoot)
2808 pPolicyStatus->lChainIndex = pPolicyStatus->lElementIndex = 0;
2809 }
2810 return ret;
2811 }
2812
2813 typedef BOOL (WINAPI *CertVerifyCertificateChainPolicyFunc)(LPCSTR szPolicyOID,
2814 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2815 PCERT_CHAIN_POLICY_STATUS pPolicyStatus);
2816
2817 BOOL WINAPI CertVerifyCertificateChainPolicy(LPCSTR szPolicyOID,
2818 PCCERT_CHAIN_CONTEXT pChainContext, PCERT_CHAIN_POLICY_PARA pPolicyPara,
2819 PCERT_CHAIN_POLICY_STATUS pPolicyStatus)
2820 {
2821 static HCRYPTOIDFUNCSET set = NULL;
2822 BOOL ret = FALSE;
2823 CertVerifyCertificateChainPolicyFunc verifyPolicy = NULL;
2824 HCRYPTOIDFUNCADDR hFunc = NULL;
2825
2826 TRACE("(%s, %p, %p, %p)\n", debugstr_a(szPolicyOID), pChainContext,
2827 pPolicyPara, pPolicyStatus);
2828
2829 if (!HIWORD(szPolicyOID))
2830 {
2831 switch (LOWORD(szPolicyOID))
2832 {
2833 case LOWORD(CERT_CHAIN_POLICY_BASE):
2834 verifyPolicy = verify_base_policy;
2835 break;
2836 case LOWORD(CERT_CHAIN_POLICY_AUTHENTICODE):
2837 verifyPolicy = verify_authenticode_policy;
2838 break;
2839 case LOWORD(CERT_CHAIN_POLICY_SSL):
2840 verifyPolicy = verify_ssl_policy;
2841 break;
2842 case LOWORD(CERT_CHAIN_POLICY_BASIC_CONSTRAINTS):
2843 verifyPolicy = verify_basic_constraints_policy;
2844 break;
2845 case LOWORD(CERT_CHAIN_POLICY_MICROSOFT_ROOT):
2846 verifyPolicy = verify_ms_root_policy;
2847 break;
2848 default:
2849 FIXME("unimplemented for %d\n", LOWORD(szPolicyOID));
2850 }
2851 }
2852 if (!verifyPolicy)
2853 {
2854 if (!set)
2855 set = CryptInitOIDFunctionSet(
2856 CRYPT_OID_VERIFY_CERTIFICATE_CHAIN_POLICY_FUNC, 0);
2857 CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING, szPolicyOID, 0,
2858 (void **)&verifyPolicy, &hFunc);
2859 }
2860 if (verifyPolicy)
2861 ret = verifyPolicy(szPolicyOID, pChainContext, pPolicyPara,
2862 pPolicyStatus);
2863 if (hFunc)
2864 CryptFreeOIDFunctionAddress(hFunc, 0);
2865 TRACE("returning %d (%08x)\n", ret, pPolicyStatus->dwError);
2866 return ret;
2867 }