]> git.saurik.com Git - apple/security.git/blob - OSX/sec/securityd/SecPolicyServer.c
46257024951597fc223169f38b24f507d7b9ac08
[apple/security.git] / OSX / sec / securityd / SecPolicyServer.c
1 /*
2 * Copyright (c) 2008-2015 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 /*
25 * SecPolicyServer.c - Trust policies dealing with certificate revocation.
26 */
27
28 #include <securityd/SecPolicyServer.h>
29 #include <Security/SecPolicyInternal.h>
30 #include <Security/SecPolicyPriv.h>
31 #include <utilities/SecIOFormat.h>
32 #include <securityd/asynchttp.h>
33 #include <securityd/policytree.h>
34 #include <securityd/nameconstraints.h>
35 #include <CoreFoundation/CFTimeZone.h>
36 #include <wctype.h>
37 #include <libDER/oidsPriv.h>
38 #include <CoreFoundation/CFNumber.h>
39 #include <Security/SecCertificateInternal.h>
40 #include <AssertMacros.h>
41 #include <utilities/debugging.h>
42 #include <security_asn1/SecAsn1Coder.h>
43 #include <security_asn1/ocspTemplates.h>
44 #include <security_asn1/oidsalg.h>
45 #include <security_asn1/oidsocsp.h>
46 #include <CommonCrypto/CommonDigest.h>
47 #include <Security/SecFramework.h>
48 #include <Security/SecPolicyInternal.h>
49 #include <Security/SecTrustPriv.h>
50 #include <Security/SecInternal.h>
51 #include <Security/SecKeyPriv.h>
52 #include <CFNetwork/CFHTTPMessage.h>
53 #include <CFNetwork/CFHTTPStream.h>
54 #include <SystemConfiguration/SCDynamicStoreCopySpecific.h>
55 #include <asl.h>
56 #include <securityd/SecOCSPRequest.h>
57 #include <securityd/SecOCSPResponse.h>
58 #include <securityd/asynchttp.h>
59 #include <securityd/SecTrustServer.h>
60 #include <securityd/SecOCSPCache.h>
61 #include <utilities/array_size.h>
62 #include <utilities/SecCFWrappers.h>
63 #include <utilities/SecAppleAnchorPriv.h>
64 #include "OTATrustUtilities.h"
65
66 #define ocspdErrorLog(args...) asl_log(NULL, NULL, ASL_LEVEL_ERR, ## args)
67
68 /* Set this to 1 to dump the ocsp responses received in DER form in /tmp. */
69 #ifndef DUMP_OCSPRESPONSES
70 #define DUMP_OCSPRESPONSES 0
71 #endif
72
73 #if DUMP_OCSPRESPONSES
74
75 #include <unistd.h>
76 #include <fcntl.h>
77
78 static void secdumpdata(CFDataRef data, const char *name) {
79 int fd = open(name, O_CREAT | O_WRONLY | O_TRUNC, 0666);
80 write(fd, CFDataGetBytePtr(data), CFDataGetLength(data));
81 close(fd);
82 }
83
84 #endif
85
86
87 /********************************************************
88 ****************** SecPolicy object ********************
89 ********************************************************/
90
91 static CFMutableDictionaryRef gSecPolicyLeafCallbacks = NULL;
92 static CFMutableDictionaryRef gSecPolicyPathCallbacks = NULL;
93
94 static CFArrayRef SecPolicyAnchorDigestsForEVPolicy(const DERItem *policyOID)
95 {
96 CFArrayRef result = NULL;
97 SecOTAPKIRef otapkiRef = SecOTAPKICopyCurrentOTAPKIRef();
98 if (NULL == otapkiRef)
99 {
100 return result;
101 }
102
103 CFDictionaryRef evToPolicyAnchorDigest = SecOTAPKICopyEVPolicyToAnchorMapping(otapkiRef);
104 CFRelease(otapkiRef);
105
106 if (NULL == evToPolicyAnchorDigest)
107 {
108 return result;
109 }
110
111 CFArrayRef roots = NULL;
112 CFStringRef oid = SecDERItemCopyOIDDecimalRepresentation(kCFAllocatorDefault, policyOID);
113 if (oid && evToPolicyAnchorDigest)
114 {
115 result = (CFArrayRef)CFDictionaryGetValue(evToPolicyAnchorDigest, oid);
116 if (roots && CFGetTypeID(result) != CFArrayGetTypeID())
117 {
118 ocspdErrorLog("EVRoot.plist has non array value");
119 result = NULL;
120 }
121 CFRelease(oid);
122 }
123 CFReleaseSafe(evToPolicyAnchorDigest);
124 return result;
125 }
126
127
128 static bool SecPolicyIsEVPolicy(const DERItem *policyOID) {
129 return SecPolicyAnchorDigestsForEVPolicy(policyOID);
130 }
131
132 static bool SecPolicyRootCACertificateIsEV(SecCertificateRef certificate,
133 policy_set_t valid_policies) {
134 /* Ensure that this certificate is a valid anchor for one of the
135 certificate policy oids specified in the leaf. */
136 CFDataRef digest = SecCertificateGetSHA1Digest(certificate);
137 policy_set_t ix;
138 bool good_ev_anchor = false;
139 for (ix = valid_policies; ix; ix = ix->oid_next) {
140 CFArrayRef digests = SecPolicyAnchorDigestsForEVPolicy(&ix->oid);
141 if (digests && CFArrayContainsValue(digests,
142 CFRangeMake(0, CFArrayGetCount(digests)), digest)) {
143 secdebug("ev", "found anchor for policy oid");
144 good_ev_anchor = true;
145 break;
146 }
147 }
148 require_quiet(good_ev_anchor, notEV);
149
150 CFAbsoluteTime october2006 = 178761600;
151 if (SecCertificateVersion(certificate) >= 3
152 && SecCertificateNotValidBefore(certificate) >= october2006) {
153 const SecCEBasicConstraints *bc = SecCertificateGetBasicConstraints(certificate);
154 require_quiet(bc && bc->isCA == true, notEV);
155 SecKeyUsage ku = SecCertificateGetKeyUsage(certificate);
156 require_quiet((ku & (kSecKeyUsageKeyCertSign | kSecKeyUsageCRLSign))
157 == (kSecKeyUsageKeyCertSign | kSecKeyUsageCRLSign), notEV);
158 }
159
160 CFAbsoluteTime jan2011 = 315532800;
161 if (SecCertificateNotValidBefore(certificate) < jan2011) {
162 /* At least MD5, SHA-1 with RSA 2048 or ECC NIST P-256. */
163 } else {
164 /* At least SHA-1, SHA-256, SHA-384 or SHA-512 with RSA 2048 or
165 ECC NIST P-256. */
166 }
167
168 return true;
169 notEV:
170 return false;
171 }
172
173 static bool SecPolicySubordinateCACertificateCouldBeEV(SecCertificateRef certificate) {
174 const SecCECertificatePolicies *cp;
175 cp = SecCertificateGetCertificatePolicies(certificate);
176 require_quiet(cp && cp->numPolicies > 0, notEV);
177 /* SecCertificateGetCRLDistributionPoints() is a noop right now */
178 #if 0
179 CFArrayRef cdp = SecCertificateGetCRLDistributionPoints(certificate);
180 require_quiet(cdp && CFArrayGetCount(cdp) > 0, notEV);
181 #endif
182 const SecCEBasicConstraints *bc = SecCertificateGetBasicConstraints(certificate);
183 require_quiet(bc && bc->isCA == true, notEV);
184 SecKeyUsage ku = SecCertificateGetKeyUsage(certificate);
185 require_quiet((ku & (kSecKeyUsageKeyCertSign | kSecKeyUsageCRLSign))
186 == (kSecKeyUsageKeyCertSign | kSecKeyUsageCRLSign), notEV);
187 CFAbsoluteTime jan2011 = 315532800;
188 if (SecCertificateNotValidBefore(certificate) < jan2011) {
189 /* At least SHA-1 with RSA 1024 or ECC NIST P-256. */
190 } else {
191 /* At least SHA-1, SHA-256, SHA-284 or SHA-512 with RSA 2028 or
192 ECC NIST P-256. */
193 }
194
195 return true;
196 notEV:
197 return false;
198 }
199
200 bool SecPolicySubscriberCertificateCouldBeEV(SecCertificateRef certificate) {
201 /* 3. Subscriber Certificate. */
202
203 /* (a) certificate Policies */
204 const SecCECertificatePolicies *cp;
205 cp = SecCertificateGetCertificatePolicies(certificate);
206 require_quiet(cp && cp->numPolicies > 0, notEV);
207 /* Now find at least one policy in here that has a qualifierID of id-qt 2
208 and a policyQualifier that is a URI to the CPS and an EV policy OID. */
209 uint32_t ix = 0;
210 bool found_ev_anchor_for_leaf_policy = false;
211 for (ix = 0; ix < cp->numPolicies; ++ix) {
212 if (SecPolicyIsEVPolicy(&cp->policies[ix].policyIdentifier)) {
213 found_ev_anchor_for_leaf_policy = true;
214 }
215 }
216 require_quiet(found_ev_anchor_for_leaf_policy, notEV);
217
218 /* SecCertificateGetCRLDistributionPoints() is a noop right now */
219 #if 0
220 /* (b) cRLDistributionPoint
221 (c) authorityInformationAccess */
222 CFArrayRef cdp = SecCertificateGetCRLDistributionPoints(certificate);
223 if (cdp) {
224 require_quiet(CFArrayGetCount(cdp) > 0, notEV);
225 } else {
226 CFArrayRef or = SecCertificateGetOCSPResponders(certificate);
227 require_quiet(or && CFArrayGetCount(or) > 0, notEV);
228 //CFArrayRef ci = SecCertificateGetCAIssuers(certificate);
229 }
230 #endif
231
232 /* (d) basicConstraints
233 If present, the cA field MUST be set false. */
234 const SecCEBasicConstraints *bc = SecCertificateGetBasicConstraints(certificate);
235 if (bc) {
236 require_quiet(bc->isCA == false, notEV);
237 }
238
239 /* (e) keyUsage. */
240 SecKeyUsage ku = SecCertificateGetKeyUsage(certificate);
241 if (ku) {
242 require_quiet((ku & (kSecKeyUsageKeyCertSign | kSecKeyUsageCRLSign)) == 0, notEV);
243 }
244
245 #if 0
246 /* The EV Cert Spec errata specifies this, though this is a check for SSL
247 not specifically EV. */
248
249 /* (e) extKeyUsage
250
251 Either the value id-kp-serverAuth [RFC5280] or id-kp-clientAuth [RFC5280] or both values MUST be present. Other values SHOULD NOT be present. */
252 SecCertificateCopyExtendedKeyUsage(certificate);
253 #endif
254
255 CFAbsoluteTime jan2011 = 315532800;
256 if (SecCertificateNotValidAfter(certificate) < jan2011) {
257 /* At least SHA-1 with RSA 1024 or ECC NIST P-256. */
258 } else {
259 /* At least SHA-1, SHA-256, SHA-284 or SHA-512 with RSA 2028 or
260 ECC NIST P-256. */
261 }
262
263 return true;
264 notEV:
265 return false;
266 }
267
268 /********************************************************
269 **************** SecPolicy Callbacks *******************
270 ********************************************************/
271 static void SecPolicyCheckCriticalExtensions(SecPVCRef pvc,
272 CFStringRef key) {
273 }
274
275 static void SecPolicyCheckIdLinkage(SecPVCRef pvc,
276 CFStringRef key) {
277 CFIndex ix, count = SecPVCGetCertificateCount(pvc);
278 CFDataRef parentSubjectKeyID = NULL;
279 for (ix = count - 1; ix >= 0; --ix) {
280 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, ix);
281 /* If the previous certificate in the chain had a SubjectKeyID,
282 make sure it matches the current certificates AuthorityKeyID. */
283 if (parentSubjectKeyID) {
284 /* @@@ According to RFC 2459 neither AuthorityKeyID nor
285 SubjectKeyID can be critical. Currenty we don't check
286 for this. */
287 CFDataRef authorityKeyID = SecCertificateGetAuthorityKeyID(cert);
288 if (authorityKeyID) {
289 if (!CFEqual(parentSubjectKeyID, authorityKeyID)) {
290 /* AuthorityKeyID doesn't match issuers SubjectKeyID. */
291 if (!SecPVCSetResult(pvc, key, ix, kCFBooleanFalse))
292 return;
293 }
294 }
295 }
296
297 parentSubjectKeyID = SecCertificateGetSubjectKeyID(cert);
298 }
299 }
300
301 static bool keyusage_allows(SecKeyUsage keyUsage, CFTypeRef xku) {
302 if (!xku || CFGetTypeID(xku) != CFNumberGetTypeID())
303 return false;
304
305 SInt32 dku;
306 CFNumberGetValue((CFNumberRef)xku, kCFNumberSInt32Type, &dku);
307 SecKeyUsage ku = (SecKeyUsage)dku;
308 return (keyUsage & ku) == ku;
309 }
310
311 static void SecPolicyCheckKeyUsage(SecPVCRef pvc,
312 CFStringRef key) {
313 SecCertificateRef leaf = SecPVCGetCertificateAtIndex(pvc, 0);
314 SecKeyUsage keyUsage = SecCertificateGetKeyUsage(leaf);
315 bool match = false;
316 SecPolicyRef policy = SecPVCGetPolicy(pvc);
317 CFTypeRef xku = CFDictionaryGetValue(policy->_options, key);
318 if (isArray(xku)) {
319 CFIndex ix, count = CFArrayGetCount(xku);
320 for (ix = 0; ix < count; ++ix) {
321 CFTypeRef ku = CFArrayGetValueAtIndex(xku, ix);
322 if (keyusage_allows(keyUsage, ku)) {
323 match = true;
324 break;
325 }
326 }
327 } else {
328 match = keyusage_allows(keyUsage, xku);
329 }
330 if (!match) {
331 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
332 }
333 }
334
335 static bool extendedkeyusage_allows(CFArrayRef extendedKeyUsage,
336 CFTypeRef xeku) {
337 if (!xeku || CFGetTypeID(xeku) != CFDataGetTypeID())
338 return false;
339 if (extendedKeyUsage) {
340 CFRange all = { 0, CFArrayGetCount(extendedKeyUsage) };
341 return CFArrayContainsValue(extendedKeyUsage, all, xeku);
342 } else {
343 /* Certificate has no extended key usage, only a match if the policy
344 contains a 0 length CFDataRef. */
345 return CFDataGetLength((CFDataRef)xeku) == 0;
346 }
347 }
348
349 /* AUDIT[securityd](done):
350 policy->_options is a caller provided dictionary, only its cf type has
351 been checked.
352 */
353 static void SecPolicyCheckExtendedKeyUsage(SecPVCRef pvc, CFStringRef key) {
354 SecCertificateRef leaf = SecPVCGetCertificateAtIndex(pvc, 0);
355 CFArrayRef leafExtendedKeyUsage = SecCertificateCopyExtendedKeyUsage(leaf);
356 bool match = false;
357 SecPolicyRef policy = SecPVCGetPolicy(pvc);
358 CFTypeRef xeku = CFDictionaryGetValue(policy->_options, key);
359 if (isArray(xeku)) {
360 CFIndex ix, count = CFArrayGetCount(xeku);
361 for (ix = 0; ix < count; ix++) {
362 CFTypeRef eku = CFArrayGetValueAtIndex(xeku, ix);
363 if (extendedkeyusage_allows(leafExtendedKeyUsage, eku)) {
364 match = true;
365 break;
366 }
367 }
368 } else {
369 match = extendedkeyusage_allows(leafExtendedKeyUsage, xeku);
370 }
371 CFReleaseSafe(leafExtendedKeyUsage);
372 if (!match) {
373 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
374 }
375 }
376
377 #if 0
378 static void SecPolicyCheckBasicContraintsCommon(SecPVCRef pvc,
379 CFStringRef key, bool strict) {
380 CFIndex ix, count = SecPVCGetCertificateCount(pvc);
381 for (ix = 0; ix < count; ++ix) {
382 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, ix);
383 const SecCEBasicConstraints *bc =
384 SecCertificateGetBasicConstraints(cert);
385 if (bc) {
386 if (strict) {
387 if (ix == 0) {
388 /* Leaf certificate has basic constraints extension. */
389 if (!SecPVCSetResult(pvc, key, ix, kCFBooleanFalse))
390 return;
391 } else if (!bc->critical) {
392 /* Basic constraints extension is not marked critical. */
393 if (!SecPVCSetResult(pvc, key, ix, kCFBooleanFalse))
394 return;
395 }
396 }
397
398 if (ix > 0 || count == 1) {
399 if (!bc->isCA) {
400 /* Non leaf certificate marked as isCA false. */
401 if (!SecPVCSetResult(pvc, key, ix, kCFBooleanFalse))
402 return;
403 }
404
405 if (bc->pathLenConstraintPresent) {
406 if (bc->pathLenConstraint < (uint32_t)(ix - 1)) {
407 #if 0
408 /* @@@ If a self signed certificate is issued by
409 another cert that is trusted, then we are supposed
410 to treat the self signed cert itself as the anchor
411 for path length purposes. */
412 CFIndex ssix = SecCertificatePathSelfSignedIndex(path);
413 if (ssix >= 0 && ix >= ssix) {
414 /* It's ok if the pathLenConstraint isn't met for
415 certificates signing a self signed cert in the
416 chain. */
417 } else
418 #endif
419 {
420 /* Path Length Constraint Exceeded. */
421 if (!SecPVCSetResult(pvc, key, ix,
422 kCFBooleanFalse))
423 return;
424 }
425 }
426 }
427 }
428 } else if (strict && ix > 0) {
429 /* In strict mode all CA certificates *MUST* have a critical
430 basic constraints extension and the leaf certificate
431 *MUST NOT* have a basic constraints extension. */
432 /* CA certificate is missing basicConstraints extension. */
433 if (!SecPVCSetResult(pvc, key, ix, kCFBooleanFalse))
434 return;
435 }
436 }
437 }
438 #endif
439
440 static void SecPolicyCheckBasicContraints(SecPVCRef pvc,
441 CFStringRef key) {
442 //SecPolicyCheckBasicContraintsCommon(pvc, key, false);
443 }
444
445 static void SecPolicyCheckNonEmptySubject(SecPVCRef pvc,
446 CFStringRef key) {
447 CFIndex ix, count = SecPVCGetCertificateCount(pvc);
448 for (ix = 0; ix < count; ++ix) {
449 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, ix);
450 /* If the certificate has a subject, or
451 if it doesn't, and it's the leaf and not self signed,
452 and also has a critical subjectAltName extension it's valid. */
453 if (!SecCertificateHasSubject(cert)) {
454 if (ix == 0 && count > 1) {
455 if (!SecCertificateHasCriticalSubjectAltName(cert)) {
456 /* Leaf certificate with empty subject does not have
457 a critical subject alt name extension. */
458 if (!SecPVCSetResult(pvc, key, ix, kCFBooleanFalse))
459 return;
460 }
461 } else {
462 /* CA certificate has empty subject. */
463 if (!SecPVCSetResult(pvc, key, ix, kCFBooleanFalse))
464 return;
465 }
466 }
467 }
468 }
469
470 static void SecPolicyCheckQualifiedCertStatements(SecPVCRef pvc,
471 CFStringRef key) {
472 }
473
474 /* Compare hostname suffix to domain name.
475 This function does not process wildcards, and allows hostname to match
476 any subdomain level of the provided domain.
477
478 To match, the last domain length chars of hostname must equal domain,
479 and the character immediately preceding domain in hostname (if any)
480 must be a dot. This means that domain 'bar.com' will match hostname
481 values 'host.bar.com' or 'host.sub.bar.com', but not 'host.foobar.com'.
482
483 Characters in each string are converted to lowercase for the comparison.
484 Trailing '.' characters in both names will be ignored.
485
486 Returns true on match, else false.
487 */
488 static bool SecDomainSuffixMatch(CFStringRef hostname, CFStringRef domain) {
489 CFStringInlineBuffer hbuf, dbuf;
490 UniChar hch, dch;
491 CFIndex hix, dix,
492 hlength = CFStringGetLength(hostname),
493 dlength = CFStringGetLength(domain);
494 CFRange hrange = { 0, hlength }, drange = { 0, dlength };
495 CFStringInitInlineBuffer(hostname, &hbuf, hrange);
496 CFStringInitInlineBuffer(domain, &dbuf, drange);
497
498 if((hlength == 0) || (dlength == 0)) {
499 /* trivial case with at least one empty name */
500 return (hlength == dlength) ? true : false;
501 }
502
503 /* trim off trailing dots */
504 hch = CFStringGetCharacterFromInlineBuffer(&hbuf, hlength-1);
505 dch = CFStringGetCharacterFromInlineBuffer(&dbuf, dlength-1);
506 if(hch == '.') {
507 hrange.length = --hlength;
508 }
509 if(dch == '.') {
510 drange.length = --dlength;
511 }
512
513 /* trim off leading dot in suffix, if present */
514 dch = CFStringGetCharacterFromInlineBuffer(&dbuf, 0);
515 if((dlength > 0) && (dch == '.')) {
516 drange.location++;
517 drange.length = --dlength;
518 }
519
520 if(hlength < dlength) {
521 return false;
522 }
523
524 /* perform case-insensitive comparison of domain suffix */
525 for (hix = (hlength-dlength),
526 dix = drange.location; dix < drange.length; dix++) {
527 hch = CFStringGetCharacterFromInlineBuffer(&hbuf, hix);
528 dch = CFStringGetCharacterFromInlineBuffer(&dbuf, dix);
529 if (towlower(hch) != towlower(dch)) {
530 return false;
531 }
532 }
533
534 /* require a dot prior to domain suffix, unless hostname == domain */
535 if(hlength > dlength) {
536 hch = CFStringGetCharacterFromInlineBuffer(&hbuf, (hlength-(dlength+1)));
537 if(hch != '.') {
538 return false;
539 }
540 }
541
542 return true;
543 }
544
545 /* Compare hostname, to a server name obtained from the server's cert
546 Obtained from the SubjectAltName or the CommonName entry in the Subject.
547 Limited wildcard checking is performed here as outlined in
548
549 RFC 2818 Section 3.1. Server Identity
550
551 [...] Names may contain the wildcard
552 character * which is considered to match any single domain name
553 component or component fragment. E.g., *.a.com matches foo.a.com but
554 not bar.foo.a.com. f*.com matches foo.com but not bar.com.
555 [...]
556
557 Trailing '.' characters in the hostname will be ignored.
558
559 Returns true on match, else false.
560
561 RFC6125:
562 */
563 bool SecDNSMatch(CFStringRef hostname, CFStringRef servername) {
564 CFStringInlineBuffer hbuf, sbuf;
565 CFIndex hix, six, tix,
566 hlength = CFStringGetLength(hostname),
567 slength = CFStringGetLength(servername);
568 CFRange hrange = { 0, hlength }, srange = { 0, slength };
569 CFStringInitInlineBuffer(hostname, &hbuf, hrange);
570 CFStringInitInlineBuffer(servername, &sbuf, srange);
571 bool prevLabel=false;
572
573 for (hix = six = 0; six < slength; ++six) {
574 UniChar tch, hch, sch = CFStringGetCharacterFromInlineBuffer(&sbuf, six);
575 if (sch == '*') {
576 if (prevLabel) {
577 /* RFC6125: No wildcard after a Previous Label */
578 /* INVALID: Means we have something like foo.*.<public_suffix> */
579 return false;
580 }
581
582 if (six + 1 >= slength) {
583 /* Trailing '*' in servername, match until end of hostname or
584 trailing '.'. */
585 do {
586 if (hix >= hlength) {
587 /* If we reach the end of the hostname we have a
588 match. */
589 return true;
590 }
591 hch = CFStringGetCharacterFromInlineBuffer(&hbuf, hix++);
592 } while (hch != '.');
593 /* We reached the end of servername and found a '.' in
594 hostname. Return true if hostname has a single
595 trailing '.' return false if there is anything after it. */
596 return hix == hlength;
597 }
598
599 /* Grab the character after the '*'. */
600 sch = CFStringGetCharacterFromInlineBuffer(&sbuf, ++six);
601 if (sch != '.') {
602 /* We have something of the form '*foo.com'. Or '**.com'
603 We don't deal with that yet, since it might require
604 backtracking. Also RFC 2818 doesn't seem to require it. */
605 return false;
606 }
607
608 /* We're looking at the '.' after the '*' in something of the
609 form 'foo*.com' or '*.com'. Match until next '.' in hostname. */
610 if (prevLabel==false) { /* RFC6125: Check if *.<tld> */
611 tix=six+1;
612 do { /* Loop to end of servername */
613 if (tix > slength)
614 return false; /* Means we have something like *.com */
615 tch = CFStringGetCharacterFromInlineBuffer(&sbuf, tix++);
616 } while (tch != '.');
617 if (tix > slength)
618 return false; /* In case we have *.com. */
619 }
620
621 do {
622 /* Since we're not at the end of servername yet (that case
623 was handled above), running out of chars in hostname
624 means we don't have a match. */
625 if (hix >= hlength)
626 return false;
627 hch = CFStringGetCharacterFromInlineBuffer(&hbuf, hix++);
628 } while (hch != '.');
629 } else {
630 /* We're looking at a non wildcard character in the servername.
631 If we reached the end of hostname, it's not a match. */
632 if (hix >= hlength)
633 return false;
634
635 /* Otherwise make sure the hostname matches the character in the
636 servername, case insensitively. */
637 hch = CFStringGetCharacterFromInlineBuffer(&hbuf, hix++);
638 if (towlower(hch) != towlower(sch))
639 return false;
640 if (sch == '.')
641 prevLabel=true; /* Set if a confirmed previous component */
642 }
643 }
644
645 if (hix < hlength) {
646 /* We reached the end of servername but we have one or more characters
647 left to compare against in the hostname. */
648 if (hix + 1 == hlength &&
649 CFStringGetCharacterFromInlineBuffer(&hbuf, hix) == '.') {
650 /* Hostname has a single trailing '.', we're ok with that. */
651 return true;
652 }
653 /* Anything else is not a match. */
654 return false;
655 }
656
657 return true;
658 }
659
660 #define kSecPolicySHA1Size 20
661 static const UInt8 kAppleCorpCASHA1[kSecPolicySHA1Size] = {
662 0xA1, 0x71, 0xDC, 0xDE, 0xE0, 0x8B, 0x1B, 0xAE, 0x30, 0xA1,
663 0xAE, 0x6C, 0xC6, 0xD4, 0x03, 0x3B, 0xFD, 0xEF, 0x91, 0xCE
664 };
665
666 /* Check whether hostname is in a particular set of allowed domains.
667 Returns true if OK, false if not allowed.
668 */
669 static bool SecPolicyCheckDomain(SecPVCRef pvc, CFStringRef hostname)
670 {
671 CFIndex count = SecPVCGetCertificateCount(pvc);
672 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, count - 1);
673 CFDataRef anchorSHA1 = SecCertificateGetSHA1Digest(cert);
674
675 /* is this chain anchored by kAppleCorpCASHA1? */
676 CFDataRef corpSHA1 = CFDataCreateWithBytesNoCopy(NULL,
677 kAppleCorpCASHA1, kSecPolicySHA1Size, kCFAllocatorNull);
678 bool isCorpSHA1 = (corpSHA1 && CFEqual(anchorSHA1, corpSHA1));
679 CFReleaseSafe(corpSHA1);
680 if (isCorpSHA1) {
681 /* limit hostname to specified domains */
682 const CFStringRef dnlist[] = {
683 CFSTR("apple.com"),
684 CFSTR("icloud.com"),
685 };
686 unsigned int idx, dncount=2;
687 for (idx = 0; idx < dncount; idx++) {
688 if (SecDomainSuffixMatch(hostname, dnlist[idx])) {
689 return true;
690 }
691 }
692 return false;
693 }
694 /* %%% other CA pinning checks TBA */
695
696 return true;
697 }
698
699 /* AUDIT[securityd](done):
700 policy->_options is a caller provided dictionary, only its cf type has
701 been checked.
702 */
703 static void SecPolicyCheckSSLHostname(SecPVCRef pvc,
704 CFStringRef key) {
705 /* @@@ Consider what to do if the caller passes in no hostname. Should
706 we then still fail if the leaf has no dnsNames or IPAddresses at all? */
707 SecPolicyRef policy = SecPVCGetPolicy(pvc);
708 CFStringRef hostName = (CFStringRef)
709 CFDictionaryGetValue(policy->_options, key);
710 if (!isString(hostName)) {
711 /* @@@ We can't return an error here and making the evaluation fail
712 won't help much either. */
713 return;
714 }
715
716 SecCertificateRef leaf = SecPVCGetCertificateAtIndex(pvc, 0);
717 bool dnsMatch = false;
718 CFArrayRef dnsNames = SecCertificateCopyDNSNames(leaf);
719 if (dnsNames) {
720 CFIndex ix, count = CFArrayGetCount(dnsNames);
721 for (ix = 0; ix < count; ++ix) {
722 CFStringRef dns = (CFStringRef)CFArrayGetValueAtIndex(dnsNames, ix);
723 if (SecDNSMatch(hostName, dns)) {
724 dnsMatch = true;
725 break;
726 }
727 }
728 CFRelease(dnsNames);
729 }
730
731 if (!dnsMatch) {
732 /* Maybe hostname is an IPv4 or IPv6 address, let's compare against
733 the values returned by SecCertificateCopyIPAddresses() instead. */
734 CFArrayRef ipAddresses = SecCertificateCopyIPAddresses(leaf);
735 if (ipAddresses) {
736 CFIndex ix, count = CFArrayGetCount(ipAddresses);
737 for (ix = 0; ix < count; ++ix) {
738 CFStringRef ipAddress = (CFStringRef)CFArrayGetValueAtIndex(ipAddresses, ix);
739 if (!CFStringCompare(hostName, ipAddress, kCFCompareCaseInsensitive)) {
740 dnsMatch = true;
741 break;
742 }
743 }
744 CFRelease(ipAddresses);
745 }
746 }
747
748 if (!dnsMatch) {
749 /* Hostname mismatch or no hostnames found in certificate. */
750 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
751 }
752 else if (!SecPolicyCheckDomain(pvc, hostName)) {
753 /* Hostname match, but domain not allowed for this CA */
754 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
755 }
756
757 if ((dnsMatch || pvc->details)
758 && SecPolicySubscriberCertificateCouldBeEV(leaf)) {
759 secdebug("policy", "enabling optionally_ev");
760 pvc->optionally_ev = true;
761 /* optionally_ev => check_revocation, so we don't enable revocation
762 checking here, since we don't want it on for non EV ssl certs. */
763 #if 0
764 /* Check revocation status if the certificate asks for it (and we
765 support it) currently we only support ocsp. */
766 CFArrayRef ocspResponders = SecCertificateGetOCSPResponders(leaf);
767 if (ocspResponders) {
768 SecPVCSetCheckRevocation(pvc);
769 }
770 #endif
771 }
772 }
773
774 /* AUDIT[securityd](done):
775 policy->_options is a caller provided dictionary, only its cf type has
776 been checked.
777 */
778 static void SecPolicyCheckEmail(SecPVCRef pvc, CFStringRef key) {
779 SecPolicyRef policy = SecPVCGetPolicy(pvc);
780 CFStringRef email = (CFStringRef)CFDictionaryGetValue(policy->_options, key);
781 bool match = false;
782 if (!isString(email)) {
783 /* We can't return an error here and making the evaluation fail
784 won't help much either. */
785 return;
786 }
787
788 SecCertificateRef leaf = SecPVCGetCertificateAtIndex(pvc, 0);
789 CFArrayRef addrs = SecCertificateCopyRFC822Names(leaf);
790 if (addrs) {
791 CFIndex ix, count = CFArrayGetCount(addrs);
792 for (ix = 0; ix < count; ++ix) {
793 CFStringRef addr = (CFStringRef)CFArrayGetValueAtIndex(addrs, ix);
794 if (!CFStringCompare(email, addr, kCFCompareCaseInsensitive)) {
795 match = true;
796 break;
797 }
798 }
799 CFRelease(addrs);
800 }
801
802 if (!match) {
803 /* Hostname mismatch or no hostnames found in certificate. */
804 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
805 }
806 }
807
808 static void SecPolicyCheckValidIntermediates(SecPVCRef pvc,
809 CFStringRef key) {
810 CFIndex ix, count = SecPVCGetCertificateCount(pvc);
811 CFAbsoluteTime verifyTime = SecPVCGetVerifyTime(pvc);
812 for (ix = 1; ix < count - 1; ++ix) {
813 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, ix);
814 if (!SecCertificateIsValid(cert, verifyTime)) {
815 /* Intermediate certificate has expired. */
816 if (!SecPVCSetResult(pvc, key, ix, kCFBooleanFalse))
817 return;
818 }
819 }
820 }
821
822 static void SecPolicyCheckValidLeaf(SecPVCRef pvc,
823 CFStringRef key) {
824 CFAbsoluteTime verifyTime = SecPVCGetVerifyTime(pvc);
825 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, 0);
826 if (!SecCertificateIsValid(cert, verifyTime)) {
827 /* Leaf certificate has expired. */
828 if (!SecPVCSetResult(pvc, key, 0, kCFBooleanFalse))
829 return;
830 }
831 }
832
833 static void SecPolicyCheckValidRoot(SecPVCRef pvc,
834 CFStringRef key) {
835 CFIndex ix, count = SecPVCGetCertificateCount(pvc);
836 CFAbsoluteTime verifyTime = SecPVCGetVerifyTime(pvc);
837 ix = count - 1;
838 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, ix);
839 if (!SecCertificateIsValid(cert, verifyTime)) {
840 /* Root certificate has expired. */
841 if (!SecPVCSetResult(pvc, key, ix, kCFBooleanFalse))
842 return;
843 }
844 }
845
846 /* AUDIT[securityd](done):
847 policy->_options is a caller provided dictionary, only its cf type has
848 been checked.
849 */
850 static void SecPolicyCheckIssuerCommonName(SecPVCRef pvc,
851 CFStringRef key) {
852 CFIndex count = SecPVCGetCertificateCount(pvc);
853 if (count < 2) {
854 /* Can't check intermediates common name if there is no intermediate. */
855 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
856 return;
857 }
858
859 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, 1);
860 SecPolicyRef policy = SecPVCGetPolicy(pvc);
861 CFStringRef commonName =
862 (CFStringRef)CFDictionaryGetValue(policy->_options, key);
863 if (!isString(commonName)) {
864 /* @@@ We can't return an error here and making the evaluation fail
865 won't help much either. */
866 return;
867 }
868 CFArrayRef commonNames = SecCertificateCopyCommonNames(cert);
869 if (!commonNames || CFArrayGetCount(commonNames) != 1 ||
870 !CFEqual(commonName, CFArrayGetValueAtIndex(commonNames, 0))) {
871 /* Common Name mismatch. */
872 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
873 }
874 CFReleaseSafe(commonNames);
875 }
876
877 /* AUDIT[securityd](done):
878 policy->_options is a caller provided dictionary, only its cf type has
879 been checked.
880 */
881 static void SecPolicyCheckSubjectCommonName(SecPVCRef pvc,
882 CFStringRef key) {
883 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, 0);
884 SecPolicyRef policy = SecPVCGetPolicy(pvc);
885 CFStringRef common_name = (CFStringRef)CFDictionaryGetValue(policy->_options,
886 key);
887 if (!isString(common_name)) {
888 /* @@@ We can't return an error here and making the evaluation fail
889 won't help much either. */
890 return;
891 }
892 CFArrayRef commonNames = SecCertificateCopyCommonNames(cert);
893 if (!commonNames || CFArrayGetCount(commonNames) != 1 ||
894 !CFEqual(common_name, CFArrayGetValueAtIndex(commonNames, 0))) {
895 /* Common Name mismatch. */
896 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
897 }
898 CFReleaseSafe(commonNames);
899 }
900
901 /* AUDIT[securityd](done):
902 policy->_options is a caller provided dictionary, only its cf type has
903 been checked.
904 */
905 static void SecPolicyCheckSubjectCommonNamePrefix(SecPVCRef pvc,
906 CFStringRef key) {
907 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, 0);
908 SecPolicyRef policy = SecPVCGetPolicy(pvc);
909 CFStringRef prefix = (CFStringRef)CFDictionaryGetValue(policy->_options,
910 key);
911 if (!isString(prefix)) {
912 /* @@@ We can't return an error here and making the evaluation fail
913 won't help much either. */
914 return;
915 }
916 CFArrayRef commonNames = SecCertificateCopyCommonNames(cert);
917 if (!commonNames || CFArrayGetCount(commonNames) != 1 ||
918 !CFStringHasPrefix(CFArrayGetValueAtIndex(commonNames, 0), prefix)) {
919 /* Common Name prefix mismatch. */
920 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
921 }
922 CFReleaseSafe(commonNames);
923 }
924
925 /* AUDIT[securityd](done):
926 policy->_options is a caller provided dictionary, only its cf type has
927 been checked.
928 */
929 static void SecPolicyCheckSubjectCommonNameTEST(SecPVCRef pvc,
930 CFStringRef key) {
931 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, 0);
932 SecPolicyRef policy = SecPVCGetPolicy(pvc);
933 CFStringRef common_name = (CFStringRef)CFDictionaryGetValue(policy->_options,
934 key);
935 if (!isString(common_name)) {
936 /* @@@ We can't return an error here and making the evaluation fail
937 won't help much either. */
938 return;
939 }
940 CFArrayRef commonNames = SecCertificateCopyCommonNames(cert);
941 if (!commonNames || CFArrayGetCount(commonNames) != 1) {
942 CFStringRef cert_common_name = CFArrayGetValueAtIndex(commonNames, 0);
943 CFStringRef test_common_name = common_name ?
944 CFStringCreateWithFormat(kCFAllocatorDefault,
945 NULL, CFSTR("TEST %@ TEST"), common_name) :
946 NULL;
947 if (!CFEqual(common_name, cert_common_name) &&
948 (!test_common_name || !CFEqual(test_common_name, cert_common_name)))
949 /* Common Name mismatch. */
950 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
951 CFReleaseSafe(test_common_name);
952 }
953 CFReleaseSafe(commonNames);
954 }
955
956 /* AUDIT[securityd](done):
957 policy->_options is a caller provided dictionary, only its cf type has
958 been checked.
959 */
960 static void SecPolicyCheckNotValidBefore(SecPVCRef pvc,
961 CFStringRef key) {
962 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, 0);
963 SecPolicyRef policy = SecPVCGetPolicy(pvc);
964 CFDateRef date = (CFDateRef)CFDictionaryGetValue(policy->_options, key);
965 if (!isDate(date)) {
966 /* @@@ We can't return an error here and making the evaluation fail
967 won't help much either. */
968 return;
969 }
970 CFAbsoluteTime at = CFDateGetAbsoluteTime(date);
971 if (SecCertificateNotValidBefore(cert) <= at) {
972 /* Leaf certificate has not valid before that is too old. */
973 if (!SecPVCSetResult(pvc, key, 0, kCFBooleanFalse))
974 return;
975 }
976 }
977
978 /* AUDIT[securityd](done):
979 policy->_options is a caller provided dictionary, only its cf type has
980 been checked.
981 */
982 static void SecPolicyCheckChainLength(SecPVCRef pvc,
983 CFStringRef key) {
984 CFIndex count = SecPVCGetCertificateCount(pvc);
985 SecPolicyRef policy = SecPVCGetPolicy(pvc);
986 CFNumberRef chainLength =
987 (CFNumberRef)CFDictionaryGetValue(policy->_options, key);
988 CFIndex value;
989 if (!chainLength || CFGetTypeID(chainLength) != CFNumberGetTypeID() ||
990 !CFNumberGetValue(chainLength, kCFNumberCFIndexType, &value)) {
991 /* @@@ We can't return an error here and making the evaluation fail
992 won't help much either. */
993 return;
994 }
995 if (value != count) {
996 /* Chain length doesn't match policy requirement. */
997 if (!SecPVCSetResult(pvc, key, 0, kCFBooleanFalse))
998 return;
999 }
1000 }
1001
1002 /* AUDIT[securityd](done):
1003 policy->_options is a caller provided dictionary, only its cf type has
1004 been checked.
1005 */
1006 static void SecPolicyCheckAnchorSHA1(SecPVCRef pvc,
1007 CFStringRef key) {
1008 CFIndex count = SecPVCGetCertificateCount(pvc);
1009 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, count - 1);
1010 SecPolicyRef policy = SecPVCGetPolicy(pvc);
1011 CFTypeRef value = CFDictionaryGetValue(policy->_options, key);
1012 CFDataRef anchorSHA1 = SecCertificateGetSHA1Digest(cert);
1013
1014 bool foundMatch = false;
1015
1016 if (isData(value))
1017 foundMatch = CFEqual(anchorSHA1, value);
1018 else if (isArray(value))
1019 foundMatch = CFArrayContainsValue((CFArrayRef) value, CFRangeMake(0, CFArrayGetCount((CFArrayRef) value)), anchorSHA1);
1020 else {
1021 /* @@@ We only support Data and Array but we can't return an error here so.
1022 we let the evaluation fail (not much help) and assert in debug. */
1023 assert(false);
1024 }
1025
1026 if (!foundMatch)
1027 if (!SecPVCSetResult(pvc, kSecPolicyCheckAnchorSHA1, 0, kCFBooleanFalse))
1028 return;
1029
1030 return;
1031 }
1032
1033 /*
1034 Check the SHA256 of SPKI of the first intermediate CA certificate in the path
1035 policy->_options is a caller provided dictionary, only its cf type has
1036 been checked.
1037 */
1038 static void SecPolicyCheckIntermediateSPKISHA256(SecPVCRef pvc,
1039 CFStringRef key) {
1040 SecPolicyRef policy = SecPVCGetPolicy(pvc);
1041 CFTypeRef value = CFDictionaryGetValue(policy->_options, key);
1042 SecCertificateRef cert = NULL;
1043 CFDataRef digest = NULL;
1044 bool foundMatch = false;
1045
1046 if (SecPVCGetCertificateCount(pvc) < 2) {
1047 SecPVCSetResult(pvc, kSecPolicyCheckIntermediateSPKISHA256, 0, kCFBooleanFalse);
1048 return;
1049 }
1050
1051 cert = SecPVCGetCertificateAtIndex(pvc, 1);
1052 digest = SecCertificateCopySubjectPublicKeyInfoSHA256Digest(cert);
1053
1054 if (isData(value))
1055 foundMatch = CFEqual(digest, value);
1056 else if (isArray(value))
1057 foundMatch = CFArrayContainsValue((CFArrayRef) value, CFRangeMake(0, CFArrayGetCount((CFArrayRef) value)), digest);
1058 else {
1059 /* @@@ We only support Data and Array but we can't return an error here so.
1060 we let the evaluation fail (not much help) and assert in debug. */
1061 assert(false);
1062 }
1063
1064 CFReleaseNull(digest);
1065
1066 if (!foundMatch) {
1067 SecPVCSetResult(pvc, kSecPolicyCheckIntermediateSPKISHA256, 0, kCFBooleanFalse);
1068 }
1069 }
1070
1071 /*
1072 policy->_options is a caller provided dictionary, only its cf type has
1073 been checked.
1074 */
1075 static void SecPolicyCheckAnchorApple(SecPVCRef pvc,
1076 CFStringRef key) {
1077 CFIndex count = SecPVCGetCertificateCount(pvc);
1078 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, count - 1);
1079 SecPolicyRef policy = SecPVCGetPolicy(pvc);
1080 CFTypeRef value = CFDictionaryGetValue(policy->_options, key);
1081 SecAppleTrustAnchorFlags flags = 0;
1082
1083 if (isDictionary(value)) {
1084 if (CFDictionaryGetValue(value, kSecPolicyAppleAnchorIncludeTestRoots))
1085 flags |= kSecAppleTrustAnchorFlagsIncludeTestAnchors;
1086 if (CFDictionaryGetValue(value, kSecPolicyAppleAnchorAllowTestRootsOnProduction))
1087 flags |= kSecAppleTrustAnchorFlagsAllowNonProduction;
1088 }
1089
1090 bool foundMatch = SecIsAppleTrustAnchor(cert, flags);
1091
1092 if (!foundMatch)
1093 if (!SecPVCSetResult(pvc, kSecPolicyCheckAnchorApple, 0, kCFBooleanFalse))
1094 return;
1095
1096 return;
1097 }
1098
1099
1100 /* AUDIT[securityd](done):
1101 policy->_options is a caller provided dictionary, only its cf type has
1102 been checked.
1103 */
1104 static void SecPolicyCheckSubjectOrganization(SecPVCRef pvc,
1105 CFStringRef key) {
1106 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, 0);
1107 SecPolicyRef policy = SecPVCGetPolicy(pvc);
1108 CFStringRef org = (CFStringRef)CFDictionaryGetValue(policy->_options,
1109 key);
1110 if (!isString(org)) {
1111 /* @@@ We can't return an error here and making the evaluation fail
1112 won't help much either. */
1113 return;
1114 }
1115 CFArrayRef organization = SecCertificateCopyOrganization(cert);
1116 if (!organization || CFArrayGetCount(organization) != 1 ||
1117 !CFEqual(org, CFArrayGetValueAtIndex(organization, 0))) {
1118 /* Leaf Subject Organization mismatch. */
1119 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
1120 }
1121 CFReleaseSafe(organization);
1122 }
1123
1124 static void SecPolicyCheckSubjectOrganizationalUnit(SecPVCRef pvc,
1125 CFStringRef key) {
1126 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, 0);
1127 SecPolicyRef policy = SecPVCGetPolicy(pvc);
1128 CFStringRef orgUnit = (CFStringRef)CFDictionaryGetValue(policy->_options,
1129 key);
1130 if (!isString(orgUnit)) {
1131 /* @@@ We can't return an error here and making the evaluation fail
1132 won't help much either. */
1133 return;
1134 }
1135 CFArrayRef organizationalUnit = SecCertificateCopyOrganizationalUnit(cert);
1136 if (!organizationalUnit || CFArrayGetCount(organizationalUnit) != 1 ||
1137 !CFEqual(orgUnit, CFArrayGetValueAtIndex(organizationalUnit, 0))) {
1138 /* Leaf Subject Organizational Unit mismatch. */
1139 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
1140 }
1141 CFReleaseSafe(organizationalUnit);
1142 }
1143
1144 /* AUDIT[securityd](done):
1145 policy->_options is a caller provided dictionary, only its cf type has
1146 been checked.
1147 */
1148 static void SecPolicyCheckEAPTrustedServerNames(SecPVCRef pvc,
1149 CFStringRef key) {
1150 SecPolicyRef policy = SecPVCGetPolicy(pvc);
1151 CFArrayRef trustedServerNames = (CFArrayRef)
1152 CFDictionaryGetValue(policy->_options, key);
1153 /* No names specified means we accept any name. */
1154 if (!trustedServerNames)
1155 return;
1156 if (!isArray(trustedServerNames)) {
1157 /* @@@ We can't return an error here and making the evaluation fail
1158 won't help much either. */
1159 return;
1160 }
1161
1162 CFIndex tsnCount = CFArrayGetCount(trustedServerNames);
1163 SecCertificateRef leaf = SecPVCGetCertificateAtIndex(pvc, 0);
1164 bool dnsMatch = false;
1165 CFArrayRef dnsNames = SecCertificateCopyDNSNames(leaf);
1166 if (dnsNames) {
1167 CFIndex ix, count = CFArrayGetCount(dnsNames);
1168 // @@@ This is O(N^2) unfortunately we can't do better easily unless
1169 // we don't do wildcard matching. */
1170 for (ix = 0; !dnsMatch && ix < count; ++ix) {
1171 CFStringRef dns = (CFStringRef)CFArrayGetValueAtIndex(dnsNames, ix);
1172 CFIndex tix;
1173 for (tix = 0; tix < tsnCount; ++tix) {
1174 CFStringRef serverName =
1175 (CFStringRef)CFArrayGetValueAtIndex(trustedServerNames, tix);
1176 if (!isString(serverName)) {
1177 /* @@@ We can't return an error here and making the
1178 evaluation fail won't help much either. */
1179 CFReleaseSafe(dnsNames);
1180 return;
1181 }
1182 /* we purposefully reverse the arguments here such that dns names
1183 from the cert are matched against a server name list, where
1184 the server names list can contain wildcards and the dns name
1185 cannot. References: http://support.microsoft.com/kb/941123
1186 It's easy to find occurrences where people tried to use
1187 wildcard certificates and were told that those don't work
1188 in this context. */
1189 if (SecDNSMatch(dns, serverName)) {
1190 dnsMatch = true;
1191 break;
1192 }
1193 }
1194 }
1195 CFRelease(dnsNames);
1196 }
1197
1198 if (!dnsMatch) {
1199 /* Hostname mismatch or no hostnames found in certificate. */
1200 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
1201 }
1202 }
1203
1204 static const unsigned char UTN_USERFirst_Hardware_Serial[][16] = {
1205 { 0xd8, 0xf3, 0x5f, 0x4e, 0xb7, 0x87, 0x2b, 0x2d, 0xab, 0x06, 0x92, 0xe3, 0x15, 0x38, 0x2f, 0xb0 },
1206 { 0x92, 0x39, 0xd5, 0x34, 0x8f, 0x40, 0xd1, 0x69, 0x5a, 0x74, 0x54, 0x70, 0xe1, 0xf2, 0x3f, 0x43 },
1207 { 0xb0, 0xb7, 0x13, 0x3e, 0xd0, 0x96, 0xf9, 0xb5, 0x6f, 0xae, 0x91, 0xc8, 0x74, 0xbd, 0x3a, 0xc0 },
1208 { 0xe9, 0x02, 0x8b, 0x95, 0x78, 0xe4, 0x15, 0xdc, 0x1a, 0x71, 0x0a, 0x2b, 0x88, 0x15, 0x44, 0x47 },
1209 { 0x39, 0x2a, 0x43, 0x4f, 0x0e, 0x07, 0xdf, 0x1f, 0x8a, 0xa3, 0x05, 0xde, 0x34, 0xe0, 0xc2, 0x29 },
1210 { 0x3e, 0x75, 0xce, 0xd4, 0x6b, 0x69, 0x30, 0x21, 0x21, 0x88, 0x30, 0xae, 0x86, 0xa8, 0x2a, 0x71 },
1211 { 0xd7, 0x55, 0x8f, 0xda, 0xf5, 0xf1, 0x10, 0x5b, 0xb2, 0x13, 0x28, 0x2b, 0x70, 0x77, 0x29, 0xa3 },
1212 { 0x04, 0x7e, 0xcb, 0xe9, 0xfc, 0xa5, 0x5f, 0x7b, 0xd0, 0x9e, 0xae, 0x36, 0xe1, 0x0c, 0xae, 0x1e },
1213 { 0xf5, 0xc8, 0x6a, 0xf3, 0x61, 0x62, 0xf1, 0x3a, 0x64, 0xf5, 0x4f, 0x6d, 0xc9, 0x58, 0x7c, 0x06 } };
1214
1215 static const unsigned char UTN_USERFirst_Hardware_Normalized_Issuer[] = {
1216 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55,
1217 0x53, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x02,
1218 0x55, 0x54, 0x31, 0x17, 0x30, 0x15, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13,
1219 0x0e, 0x53, 0x41, 0x4c, 0x54, 0x20, 0x4c, 0x41, 0x4b, 0x45, 0x20, 0x43,
1220 0x49, 0x54, 0x59, 0x31, 0x1e, 0x30, 0x1c, 0x06, 0x03, 0x55, 0x04, 0x0a,
1221 0x13, 0x15, 0x54, 0x48, 0x45, 0x20, 0x55, 0x53, 0x45, 0x52, 0x54, 0x52,
1222 0x55, 0x53, 0x54, 0x20, 0x4e, 0x45, 0x54, 0x57, 0x4f, 0x52, 0x4b, 0x31,
1223 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x18, 0x48, 0x54,
1224 0x54, 0x50, 0x3a, 0x2f, 0x2f, 0x57, 0x57, 0x57, 0x2e, 0x55, 0x53, 0x45,
1225 0x52, 0x54, 0x52, 0x55, 0x53, 0x54, 0x2e, 0x43, 0x4f, 0x4d, 0x31, 0x1f,
1226 0x30, 0x1d, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x16, 0x55, 0x54, 0x4e,
1227 0x2d, 0x55, 0x53, 0x45, 0x52, 0x46, 0x49, 0x52, 0x53, 0x54, 0x2d, 0x48,
1228 0x41, 0x52, 0x44, 0x57, 0x41, 0x52, 0x45
1229 };
1230 static const unsigned int UTN_USERFirst_Hardware_Normalized_Issuer_len = 151;
1231
1232
1233 static void SecPolicyCheckBlackListedLeaf(SecPVCRef pvc,
1234 CFStringRef key) {
1235 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, 0);
1236 CFDataRef issuer = cert ? SecCertificateGetNormalizedIssuerContent(cert) : NULL;
1237
1238 if (issuer && (CFDataGetLength(issuer) == (CFIndex)UTN_USERFirst_Hardware_Normalized_Issuer_len) &&
1239 (0 == memcmp(UTN_USERFirst_Hardware_Normalized_Issuer, CFDataGetBytePtr(issuer),
1240 UTN_USERFirst_Hardware_Normalized_Issuer_len)))
1241 {
1242 #if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE))
1243 CFDataRef serial = SecCertificateCopySerialNumber(cert, NULL);
1244 #else
1245 CFDataRef serial = SecCertificateCopySerialNumber(cert);
1246 #endif
1247
1248 if (serial) {
1249 CFIndex serial_length = CFDataGetLength(serial);
1250 const uint8_t *serial_ptr = CFDataGetBytePtr(serial);
1251
1252 while ((serial_length > 0) && (*serial_ptr == 0)) {
1253 serial_ptr++;
1254 serial_length--;
1255 }
1256
1257 if (serial_length == (CFIndex)sizeof(*UTN_USERFirst_Hardware_Serial)) {
1258 unsigned int i;
1259 for (i = 0; i < array_size(UTN_USERFirst_Hardware_Serial); i++)
1260 {
1261 if (0 == memcmp(UTN_USERFirst_Hardware_Serial[i],
1262 serial_ptr, sizeof(*UTN_USERFirst_Hardware_Serial)))
1263 {
1264 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
1265 CFReleaseSafe(serial);
1266 return;
1267 }
1268 }
1269 }
1270 CFRelease(serial);
1271 }
1272 }
1273
1274 SecOTAPKIRef otapkiRef = SecOTAPKICopyCurrentOTAPKIRef();
1275 if (NULL != otapkiRef)
1276 {
1277 CFSetRef blackListedKeys = SecOTAPKICopyBlackListSet(otapkiRef);
1278 CFRelease(otapkiRef);
1279 if (NULL != blackListedKeys)
1280 {
1281 /* Check for blacklisted intermediates keys. */
1282 CFDataRef dgst = SecCertificateCopyPublicKeySHA1Digest(cert);
1283 if (dgst)
1284 {
1285 /* Check dgst against blacklist. */
1286 if (CFSetContainsValue(blackListedKeys, dgst))
1287 {
1288 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
1289 }
1290 CFRelease(dgst);
1291 }
1292 CFRelease(blackListedKeys);
1293 }
1294 }
1295 }
1296
1297 static void SecPolicyCheckGrayListedLeaf(SecPVCRef pvc, CFStringRef key)
1298 {
1299 SecOTAPKIRef otapkiRef = SecOTAPKICopyCurrentOTAPKIRef();
1300 if (NULL != otapkiRef)
1301 {
1302 CFSetRef grayListedKeys = SecOTAPKICopyGrayList(otapkiRef);
1303 CFRelease(otapkiRef);
1304 if (NULL != grayListedKeys)
1305 {
1306 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, 0);
1307
1308 CFDataRef dgst = SecCertificateCopyPublicKeySHA1Digest(cert);
1309 if (dgst)
1310 {
1311 /* Check dgst against gray. */
1312 if (CFSetContainsValue(grayListedKeys, dgst))
1313 {
1314 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
1315 }
1316 CFRelease(dgst);
1317 }
1318 CFRelease(grayListedKeys);
1319 }
1320 }
1321 }
1322
1323 static void SecPolicyCheckLeafMarkerOid(SecPVCRef pvc, CFStringRef key)
1324 {
1325 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, 0);
1326 SecPolicyRef policy = SecPVCGetPolicy(pvc);
1327 CFTypeRef value = CFDictionaryGetValue(policy->_options, key);
1328
1329 if (value && SecCertificateHasMarkerExtension(cert, value))
1330 return;
1331
1332 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
1333 }
1334
1335 static void SecPolicyCheckIntermediateMarkerOid(SecPVCRef pvc, CFStringRef key)
1336 {
1337 CFIndex ix, count = SecPVCGetCertificateCount(pvc);
1338 SecPolicyRef policy = SecPVCGetPolicy(pvc);
1339 CFTypeRef value = CFDictionaryGetValue(policy->_options, key);
1340
1341 for (ix = 1; ix < count - 1; ix++) {
1342 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, ix);
1343 if (SecCertificateHasMarkerExtension(cert, value))
1344 return;
1345 }
1346 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
1347 }
1348
1349 /* Returns true if path is on the allow list, false otherwise */
1350 static bool SecPVCCheckCertificateAllowList(SecPVCRef pvc)
1351 {
1352 bool result = false;
1353 CFIndex ix = 0, count = SecPVCGetCertificateCount(pvc);
1354 CFStringRef authKey = NULL;
1355 SecOTAPKIRef otapkiRef = NULL;
1356
1357 //get authKeyID from the last chain in the cert
1358 if (count < 1) {
1359 return result;
1360 }
1361 SecCertificateRef lastCert = SecPVCGetCertificateAtIndex(pvc, count - 1);
1362 CFDataRef authKeyID = SecCertificateGetAuthorityKeyID(lastCert);
1363 if (NULL == authKeyID) {
1364 return result;
1365 }
1366 authKey = CFDataCopyHexString(authKeyID);
1367
1368 //if allowList && key is in allowList, this would have chained up to a now-removed anchor
1369 otapkiRef = SecOTAPKICopyCurrentOTAPKIRef();
1370 if (NULL == otapkiRef) {
1371 goto errout;
1372 }
1373 CFDictionaryRef allowList = SecOTAPKICopyAllowList(otapkiRef);
1374 if (NULL == allowList) {
1375 goto errout;
1376 }
1377
1378 CFArrayRef allowedCerts = CFDictionaryGetValue(allowList, authKey);
1379 if (!allowedCerts || !CFArrayGetCount(allowedCerts)) {
1380 goto errout;
1381 }
1382
1383 //search sorted array for the SHA256 hash of a cert in the chain
1384 CFRange range = CFRangeMake(0, CFArrayGetCount(allowedCerts));
1385 for (ix = 0; ix < count; ix++) {
1386 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, ix);
1387 if (!cert) {
1388 goto errout;
1389 }
1390
1391 CFDataRef certHash = SecCertificateCopySHA256Digest(cert);
1392 if (!certHash) {
1393 goto errout;
1394 }
1395
1396 CFIndex position = CFArrayBSearchValues(allowedCerts, range, certHash,
1397 (CFComparatorFunction)CFDataCompare, NULL);
1398 if (position < CFArrayGetCount(allowedCerts)) {
1399 CFDataRef possibleMatch = CFArrayGetValueAtIndex(allowedCerts, position);
1400 if (!CFDataCompare(certHash, possibleMatch)) {
1401 //this cert is in the allowlist
1402 result = true;
1403 }
1404 }
1405
1406 CFRelease(certHash);
1407 }
1408
1409 errout:
1410 CFRelease(authKey);
1411 CFReleaseNull(otapkiRef);
1412 CFReleaseNull(allowList);
1413 return result;
1414 }
1415
1416
1417 /****************************************************************************
1418 *********************** New rfc5280 Chain Validation ***********************
1419 ****************************************************************************/
1420
1421 #if 0
1422 typedef struct cert_path *cert_path_t;
1423 struct cert_path {
1424 int length;
1425 };
1426
1427 typedef struct x500_name *x500_name_t;
1428 struct x500_name {
1429 };
1430
1431 typedef struct algorithm_id *algorithm_id_t;
1432 struct algorithm_id {
1433 oid_t algorithm_oid;
1434 der_t parameters;
1435 };
1436
1437 typedef struct trust_anchor *trust_anchor_t;
1438 struct trust_anchor {
1439 x500_name_t issuer_name;
1440 algorithm_id_t public_key_algorithm; /* includes optional params */
1441 SecKeyRef public_key;
1442 };
1443
1444 typedef struct certificate_policy *certificate_policy_t;
1445 struct certificate_policy {
1446 policy_qualifier_t qualifiers;
1447 oid_t oid;
1448 SLIST_ENTRY(certificate_policy) policies;
1449 };
1450
1451 typedef struct policy_mapping *policy_mapping_t;
1452 struct policy_mapping {
1453 SLIST_ENTRY(policy_mapping) mappings;
1454 oid_t issuer_domain_policy;
1455 oid_t subject_domain_policy;
1456 };
1457
1458 typedef struct root_name *root_name_t;
1459 struct root_name {
1460 };
1461 #endif
1462
1463 struct policy_tree_add_ctx {
1464 oid_t p_oid;
1465 policy_qualifier_t p_q;
1466 };
1467
1468 /* For each node of depth i-1 in the valid_policy_tree where P-OID is in the expected_policy_set, create a child node as follows: set the valid_policy to P-OID, set the qualifier_set to P-Q, and set the expected_policy_set to {P-OID}. */
1469 static bool policy_tree_add_if_match(policy_tree_t node, void *ctx) {
1470 struct policy_tree_add_ctx *info = (struct policy_tree_add_ctx *)ctx;
1471 policy_set_t policy_set;
1472 for (policy_set = node->expected_policy_set;
1473 policy_set;
1474 policy_set = policy_set->oid_next) {
1475 if (oid_equal(policy_set->oid, info->p_oid)) {
1476 policy_tree_add_child(node, &info->p_oid, info->p_q);
1477 return true;
1478 }
1479 }
1480 return false;
1481 }
1482
1483 /* If the valid_policy_tree includes a node of depth i-1 with the valid_policy anyPolicy, generate a child node with the following values: set the valid_policy to P-OID, set the qualifier_set to P-Q, and set the expected_policy_set to {P-OID}. */
1484 static bool policy_tree_add_if_any(policy_tree_t node, void *ctx) {
1485 struct policy_tree_add_ctx *info = (struct policy_tree_add_ctx *)ctx;
1486 if (oid_equal(node->valid_policy, oidAnyPolicy)) {
1487 policy_tree_add_child(node, &info->p_oid, info->p_q);
1488 return true;
1489 }
1490 return false;
1491 }
1492
1493 /* Return true iff node has a child with a valid_policy equal to oid. */
1494 static bool policy_tree_has_child_with_oid(policy_tree_t node,
1495 const oid_t *oid) {
1496 policy_tree_t child;
1497 for (child = node->children; child; child = child->siblings) {
1498 if (oid_equal(child->valid_policy, (*oid))) {
1499 return true;
1500 }
1501 }
1502 return false;
1503 }
1504
1505 /* For each node in the valid_policy_tree of depth i-1, for each value in the expected_policy_set (including anyPolicy) that does not appear in a child node, create a child node with the following values: set the valid_policy to the value from the expected_policy_set in the parent node, set the qualifier_set to AP-Q, and set the expected_policy_set to the value in the valid_policy from this node. */
1506 static bool policy_tree_add_expected(policy_tree_t node, void *ctx) {
1507 policy_qualifier_t p_q = (policy_qualifier_t)ctx;
1508 policy_set_t policy_set;
1509 bool added_node = false;
1510 for (policy_set = node->expected_policy_set;
1511 policy_set;
1512 policy_set = policy_set->oid_next) {
1513 if (!policy_tree_has_child_with_oid(node, &policy_set->oid)) {
1514 policy_tree_add_child(node, &policy_set->oid, p_q);
1515 added_node = true;
1516 }
1517 }
1518 return added_node;
1519 }
1520
1521 #if 0
1522 /* For each node where ID-P is the valid_policy, set expected_policy_set to the set of subjectDomainPolicy values that are specified as equivalent to ID-P by the policy mappings extension. */
1523 static bool policy_tree_map(policy_tree_t node, void *ctx) {
1524 /* Can't map oidAnyPolicy. */
1525 if (oid_equal(node->valid_policy, oidAnyPolicy))
1526 return false;
1527
1528 const SecCEPolicyMappings *pm = (const SecCEPolicyMappings *)ctx;
1529 uint32_t mapping_ix, mapping_count = pm->numMappings;
1530 policy_set_t policy_set = NULL;
1531 /* First count how many mappings match this nodes valid_policy. */
1532 for (mapping_ix = 0; mapping_ix < mapping_count; ++mapping_ix) {
1533 const SecCEPolicyMapping *mapping = &pm->mappings[mapping_ix];
1534 if (oid_equal(node->valid_policy, mapping->issuerDomainPolicy)) {
1535 policy_set_t p_node = (policy_set_t)malloc(sizeof(*policy_set));
1536 p_node->oid = mapping->subjectDomainPolicy;
1537 p_node->oid_next = policy_set ? policy_set : NULL;
1538 policy_set = p_node;
1539 }
1540 }
1541 if (policy_set) {
1542 policy_tree_set_expected_policy(node, policy_set);
1543 return true;
1544 }
1545 return false;
1546 }
1547 #endif
1548
1549 #define POLICY_MAPPING 0
1550 #define POLICY_SUBTREES 1
1551
1552 /* rfc5280 basic cert processing. */
1553 static void SecPolicyCheckBasicCertificateProcessing(SecPVCRef pvc,
1554 CFStringRef key) {
1555 /* Inputs */
1556 //cert_path_t path;
1557 CFIndex count = SecPVCGetCertificateCount(pvc);
1558 /* 64 bits cast: worst case here is we truncate the number of cert, and the validation may fail */
1559 assert((unsigned long)count<=UINT32_MAX); /* Debug check. Correct as long as CFIndex is long */
1560 uint32_t n = (uint32_t)count;
1561 bool is_anchored = SecPVCIsAnchored(pvc);
1562 if (is_anchored) {
1563 /* If the anchor is trusted we don't procces the last cert in the
1564 chain (root). */
1565 n--;
1566 } else {
1567 /* trust may be restored for a path with an untrusted root that matches the allow list */
1568 if (!SecPVCCheckCertificateAllowList(pvc)) {
1569 /* Add a detail for the root not being trusted. */
1570 if (SecPVCSetResultForced(pvc, kSecPolicyCheckAnchorTrusted,
1571 n - 1, kCFBooleanFalse, true))
1572 return;
1573 }
1574 }
1575
1576 CFAbsoluteTime verify_time = SecPVCGetVerifyTime(pvc);
1577 //policy_set_t user_initial_policy_set = NULL;
1578 //trust_anchor_t anchor;
1579 bool initial_policy_mapping_inhibit = false;
1580 bool initial_explicit_policy = false;
1581 bool initial_any_policy_inhibit = false;
1582
1583 /* Initialization */
1584 pvc->valid_policy_tree = policy_tree_create(&oidAnyPolicy, NULL);
1585 #if POLICY_SUBTREES
1586 CFMutableArrayRef permitted_subtrees = NULL;
1587 CFMutableArrayRef excluded_subtrees = NULL;
1588 permitted_subtrees = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
1589 excluded_subtrees = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
1590 assert(permitted_subtrees != NULL);
1591 assert(excluded_subtrees != NULL);
1592 #endif
1593 uint32_t explicit_policy = initial_explicit_policy ? 0 : n + 1;
1594 uint32_t inhibit_any_policy = initial_any_policy_inhibit ? 0 : n + 1;
1595 uint32_t policy_mapping = initial_policy_mapping_inhibit ? 0 : n + 1;
1596
1597 #if 0
1598 /* Path builder ensures we only get cert chains with proper issuer
1599 chaining with valid signatures along the way. */
1600 algorithm_id_t working_public_key_algorithm = anchor->public_key_algorithm;
1601 SecKeyRef working_public_key = anchor->public_key;
1602 x500_name_t working_issuer_name = anchor->issuer_name;
1603 #endif
1604 uint32_t i, max_path_length = n;
1605 SecCertificateRef cert = NULL;
1606 for (i = 1; i <= n; ++i) {
1607 /* Process Cert */
1608 cert = SecPVCGetCertificateAtIndex(pvc, n - i);
1609 bool is_self_issued = SecPVCIsCertificateAtIndexSelfSigned(pvc, n - i);
1610
1611 /* (a) Verify the basic certificate information. */
1612 /* @@@ Ensure that cert was signed with working_public_key_algorithm
1613 using the working_public_key and the working_public_key_parameters. */
1614 #if 1
1615 /* Already done by chain builder. */
1616 if (!SecCertificateIsValid(cert, verify_time)) {
1617 CFStringRef fail_key = i == n ? kSecPolicyCheckValidLeaf : kSecPolicyCheckValidIntermediates;
1618 if (!SecPVCSetResult(pvc, fail_key, n - i, kCFBooleanFalse))
1619 return;
1620 }
1621 if (SecCertificateIsWeak(cert)) {
1622 CFStringRef fail_key = i == n ? kSecPolicyCheckWeakLeaf : kSecPolicyCheckWeakIntermediates;
1623 if (!SecPVCSetResult(pvc, fail_key, n - i, kCFBooleanFalse))
1624 return;
1625 }
1626 #endif
1627 #if 0
1628 /* Check revocation status if the certificate asks for it. */
1629 CFArrayRef ocspResponders = SecCertificateGetOCSPResponders(cert);
1630 if (ocspResponders) {
1631 SecPVCSetCheckRevocation(pvc);
1632 }
1633 #endif
1634 /* @@@ cert.issuer == working_issuer_name. */
1635
1636 #if POLICY_SUBTREES
1637 /* (b) (c) */
1638 if (!is_self_issued || i == n) {
1639 bool found = false;
1640 /* Verify certificate Subject Name and SubjectAltNames are not within any of the excluded_subtrees */
1641 if(excluded_subtrees && CFArrayGetCount(excluded_subtrees)) {
1642 if ((errSecSuccess != SecNameContraintsMatchSubtrees(cert, excluded_subtrees, &found, false)) || found) {
1643 if(!SecPVCSetResultForced(pvc, key, n - i, kCFBooleanFalse, true)) return;
1644 }
1645 }
1646 /* Verify certificate Subject Name and SubjectAltNames are within the permitted_subtrees */
1647 if(permitted_subtrees && CFArrayGetCount(permitted_subtrees)) {
1648 if ((errSecSuccess != SecNameContraintsMatchSubtrees(cert, permitted_subtrees, &found, true)) || !found) {
1649 if(!SecPVCSetResultForced(pvc, key, n - i, kCFBooleanFalse, true)) return;
1650 }
1651 }
1652 }
1653 #endif
1654 /* (d) */
1655 if (pvc->valid_policy_tree) {
1656 const SecCECertificatePolicies *cp =
1657 SecCertificateGetCertificatePolicies(cert);
1658 size_t policy_ix, policy_count = cp ? cp->numPolicies : 0;
1659 for (policy_ix = 0; policy_ix < policy_count; ++policy_ix) {
1660 const SecCEPolicyInformation *policy = &cp->policies[policy_ix];
1661 oid_t p_oid = policy->policyIdentifier;
1662 policy_qualifier_t p_q = &policy->policyQualifiers;
1663 struct policy_tree_add_ctx ctx = { p_oid, p_q };
1664 if (!oid_equal(p_oid, oidAnyPolicy)) {
1665 if (!policy_tree_walk_depth(pvc->valid_policy_tree, i - 1,
1666 policy_tree_add_if_match, &ctx)) {
1667 policy_tree_walk_depth(pvc->valid_policy_tree, i - 1,
1668 policy_tree_add_if_any, &ctx);
1669 }
1670 }
1671 }
1672 /* The certificate policies extension includes the policy
1673 anyPolicy with the qualifier set AP-Q and either
1674 (a) inhibit_anyPolicy is greater than 0 or
1675 (b) i < n and the certificate is self-issued. */
1676 if (inhibit_any_policy > 0 || (i < n && is_self_issued)) {
1677 for (policy_ix = 0; policy_ix < policy_count; ++policy_ix) {
1678 const SecCEPolicyInformation *policy = &cp->policies[policy_ix];
1679 oid_t p_oid = policy->policyIdentifier;
1680 policy_qualifier_t p_q = &policy->policyQualifiers;
1681 if (oid_equal(p_oid, oidAnyPolicy)) {
1682 policy_tree_walk_depth(pvc->valid_policy_tree, i - 1,
1683 policy_tree_add_expected, (void *)p_q);
1684 }
1685 }
1686 }
1687 policy_tree_prune_childless(&pvc->valid_policy_tree, i - 1);
1688 /* (e) */
1689 if (!cp) {
1690 if (pvc->valid_policy_tree)
1691 policy_tree_prune(&pvc->valid_policy_tree);
1692 }
1693 }
1694 /* (f) Verify that either explicit_policy is greater than 0 or the
1695 valid_policy_tree is not equal to NULL. */
1696 if (!pvc->valid_policy_tree && explicit_policy == 0) {
1697 /* valid_policy_tree is empty and explicit policy is 0, illegal. */
1698 if (!SecPVCSetResultForced(pvc, key /* @@@ Need custom key */, n - i, kCFBooleanFalse, true))
1699 return;
1700 }
1701 /* If Last Cert in Path */
1702 if (i == n)
1703 break;
1704
1705 /* Prepare for Next Cert */
1706 #if POLICY_MAPPING
1707 /* (a) verify that anyPolicy does not appear as an
1708 issuerDomainPolicy or a subjectDomainPolicy */
1709 CFDictionaryRef pm = SecCertificateGetPolicyMappings(cert);
1710 if (pm) {
1711 uint32_t mapping_ix, mapping_count = pm->numMappings;
1712 for (mapping_ix = 0; mapping_ix < mapping_count; ++mapping_ix) {
1713 const SecCEPolicyMapping *mapping = &pm->mappings[mapping_ix];
1714 if (oid_equal(mapping->issuerDomainPolicy, oidAnyPolicy)
1715 || oid_equal(mapping->subjectDomainPolicy, oidAnyPolicy)) {
1716 /* Policy mapping uses anyPolicy, illegal. */
1717 if (!SecPVCSetResultForced(pvc, key /* @@@ Need custom key */, n - i, kCFBooleanFalse))
1718 return;
1719 }
1720 }
1721 /* (b) */
1722 /* (1) If the policy_mapping variable is greater than 0 */
1723 if (policy_mapping > 0) {
1724 if (!policy_tree_walk_depth(pvc->valid_policy_tree, i,
1725 policy_tree_map, (void *)pm)) {
1726 /* If no node of depth i in the valid_policy_tree has a valid_policy of ID-P but there is a node of depth i with a valid_policy of anyPolicy, then generate a child node of the node of depth i-1 that has a valid_policy of anyPolicy as follows:
1727
1728 (i) set the valid_policy to ID-P;
1729
1730 (ii) set the qualifier_set to the qualifier set of the
1731 policy anyPolicy in the certificate policies
1732 extension of certificate i; and
1733 (iii) set the expected_policy_set to the set of subjectDomainPolicy values that are specified as equivalent to ID-P by the policy mappings extension. */
1734 }
1735 } else {
1736 #if 0
1737 /* (i) delete each node of depth i in the valid_policy_tree
1738 where ID-P is the valid_policy. */
1739 struct policy_tree_map_ctx ctx = { idp_oid, sdp_oid };
1740 policy_tree_walk_depth(pvc->valid_policy_tree, i,
1741 policy_tree_delete_if_match, &ctx);
1742 #endif
1743 /* (ii) If there is a node in the valid_policy_tree of depth
1744 i-1 or less without any child nodes, delete that
1745 node. Repeat this step until there are no nodes of
1746 depth i-1 or less without children. */
1747 policy_tree_prune_childless(&pvc->valid_policy_tree, i - 1);
1748 }
1749 }
1750 #endif /* POLICY_MAPPING */
1751 /* (c)(d)(e)(f) */
1752 //working_issuer_name = SecCertificateGetNormalizedSubjectContent(cert);
1753 //working_public_key = SecCertificateCopyPublicKey(cert);
1754 //working_public_key_parameters = SecCertificateCopyPublicKeyParameters(cert);
1755 //working_public_key_algorithm = SecCertificateCopyPublicKeyAlgorithm(cert);
1756 #if POLICY_SUBTREES
1757 /* (g) If a name constraints extension is included in the certificate, modify the permitted_subtrees and excluded_subtrees state variables.
1758 */
1759 CFArrayRef permitted_subtrees_in_cert = SecCertificateGetPermittedSubtrees(cert);
1760 if (permitted_subtrees_in_cert) {
1761 SecNameConstraintsIntersectSubtrees(permitted_subtrees, permitted_subtrees_in_cert);
1762 }
1763
1764 // could do something smart here to avoid inserting the exact same constraint
1765 CFArrayRef excluded_subtrees_in_cert = SecCertificateGetExcludedSubtrees(cert);
1766 if (excluded_subtrees_in_cert) {
1767 CFIndex num_trees = CFArrayGetCount(excluded_subtrees_in_cert);
1768 CFRange range = { 0, num_trees };
1769 CFArrayAppendArray(excluded_subtrees, excluded_subtrees_in_cert, range);
1770 }
1771 #endif
1772 /* (h) */
1773 if (!is_self_issued) {
1774 if (explicit_policy)
1775 explicit_policy--;
1776 if (policy_mapping)
1777 policy_mapping--;
1778 if (inhibit_any_policy)
1779 inhibit_any_policy--;
1780 }
1781 /* (i) */
1782 const SecCEPolicyConstraints *pc =
1783 SecCertificateGetPolicyConstraints(cert);
1784 if (pc) {
1785 if (pc->requireExplicitPolicyPresent
1786 && pc->requireExplicitPolicy < explicit_policy) {
1787 explicit_policy = pc->requireExplicitPolicy;
1788 }
1789 if (pc->inhibitPolicyMappingPresent
1790 && pc->inhibitPolicyMapping < policy_mapping) {
1791 policy_mapping = pc->inhibitPolicyMapping;
1792 }
1793 }
1794 /* (j) */
1795 uint32_t iap = SecCertificateGetInhibitAnyPolicySkipCerts(cert);
1796 if (iap < inhibit_any_policy) {
1797 inhibit_any_policy = iap;
1798 }
1799 /* (k) */
1800 const SecCEBasicConstraints *bc =
1801 SecCertificateGetBasicConstraints(cert);
1802 #if 0 /* Checked in chain builder pre signature verify already. */
1803 if (!bc || !bc->isCA) {
1804 /* Basic constraints not present or not marked as isCA, illegal. */
1805 if (!SecPVCSetResult(pvc, kSecPolicyCheckBasicContraints,
1806 n - i, kCFBooleanFalse))
1807 return;
1808 }
1809 #endif
1810 /* (l) */
1811 if (!is_self_issued) {
1812 if (max_path_length > 0) {
1813 max_path_length--;
1814 } else {
1815 /* max_path_len exceeded, illegal. */
1816 if (!SecPVCSetResult(pvc, kSecPolicyCheckBasicContraints,
1817 n - i, kCFBooleanFalse))
1818 return;
1819 }
1820 }
1821 /* (m) */
1822 if (bc && bc->pathLenConstraintPresent
1823 && bc->pathLenConstraint < max_path_length) {
1824 max_path_length = bc->pathLenConstraint;
1825 }
1826 #if 0 /* Checked in chain builder pre signature verify already. */
1827 /* (n) If a key usage extension is present, verify that the keyCertSign bit is set. */
1828 SecKeyUsage keyUsage = SecCertificateGetKeyUsage(cert);
1829 if (keyUsage && !(keyUsage & kSecKeyUsageKeyCertSign)) {
1830 if (!SecPVCSetResultForced(pvc, kSecPolicyCheckKeyUsage,
1831 n - i, kCFBooleanFalse, true))
1832 return;
1833 }
1834 #endif
1835 /* (o) Recognize and process any other critical extension present in the certificate. Process any other recognized non-critical extension present in the certificate that is relevant to path processing. */
1836 if (SecCertificateHasUnknownCriticalExtension(cert)) {
1837 /* Certificate contains one or more unknown critical extensions. */
1838 if (!SecPVCSetResult(pvc, kSecPolicyCheckCriticalExtensions,
1839 n - i, kCFBooleanFalse))
1840 return;
1841 }
1842 } /* end loop over certs in path */
1843 /* Wrap up */
1844 cert = SecPVCGetCertificateAtIndex(pvc, 0);
1845 /* (a) */
1846 if (explicit_policy)
1847 explicit_policy--;
1848 /* (b) */
1849 const SecCEPolicyConstraints *pc = SecCertificateGetPolicyConstraints(cert);
1850 if (pc) {
1851 if (pc->requireExplicitPolicyPresent
1852 && pc->requireExplicitPolicy == 0) {
1853 explicit_policy = 0;
1854 }
1855 }
1856 /* (c) */
1857 //working_public_key = SecCertificateCopyPublicKey(cert);
1858 /* (d) */
1859 /* If the subjectPublicKeyInfo field of the certificate contains an algorithm field with null parameters or parameters are omitted, compare the certificate subjectPublicKey algorithm to the working_public_key_algorithm. If the certificate subjectPublicKey algorithm and the
1860 working_public_key_algorithm are different, set the working_public_key_parameters to null. */
1861 //working_public_key_parameters = SecCertificateCopyPublicKeyParameters(cert);
1862 /* (e) */
1863 //working_public_key_algorithm = SecCertificateCopyPublicKeyAlgorithm(cert);
1864 /* (f) Recognize and process any other critical extension present in the certificate n. Process any other recognized non-critical extension present in certificate n that is relevant to path processing. */
1865 if (SecCertificateHasUnknownCriticalExtension(cert)) {
1866 /* Certificate contains one or more unknown critical extensions. */
1867 if (!SecPVCSetResult(pvc, kSecPolicyCheckCriticalExtensions,
1868 0, kCFBooleanFalse))
1869 return;
1870 }
1871 /* (g) Calculate the intersection of the valid_policy_tree and the user-initial-policy-set, as follows */
1872
1873 if (pvc->valid_policy_tree) {
1874 #if !defined(NDEBUG)
1875 policy_tree_dump(pvc->valid_policy_tree);
1876 #endif
1877 /* (g3c4) */
1878 //policy_tree_prune_childless(&pvc->valid_policy_tree, n - 1);
1879 }
1880
1881 /* If either (1) the value of explicit_policy variable is greater than
1882 zero or (2) the valid_policy_tree is not NULL, then path processing
1883 has succeeded. */
1884 if (!pvc->valid_policy_tree && explicit_policy == 0) {
1885 /* valid_policy_tree is empty and explicit policy is 0, illegal. */
1886 if (!SecPVCSetResultForced(pvc, key /* @@@ Need custom key */, 0, kCFBooleanFalse, true))
1887 return;
1888 }
1889
1890 CFReleaseNull(permitted_subtrees);
1891 CFReleaseNull(excluded_subtrees);
1892 }
1893
1894 static policy_set_t policies_for_cert(SecCertificateRef cert) {
1895 policy_set_t policies = NULL;
1896 const SecCECertificatePolicies *cp =
1897 SecCertificateGetCertificatePolicies(cert);
1898 size_t policy_ix, policy_count = cp ? cp->numPolicies : 0;
1899 for (policy_ix = 0; policy_ix < policy_count; ++policy_ix) {
1900 policy_set_add(&policies, &cp->policies[policy_ix].policyIdentifier);
1901 }
1902 return policies;
1903 }
1904
1905 static void SecPolicyCheckEV(SecPVCRef pvc,
1906 CFStringRef key) {
1907 CFIndex ix, count = SecPVCGetCertificateCount(pvc);
1908 policy_set_t valid_policies = NULL;
1909
1910 for (ix = 0; ix < count; ++ix) {
1911 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, ix);
1912 policy_set_t policies = policies_for_cert(cert);
1913 if (ix == 0) {
1914 /* Subscriber */
1915 /* anyPolicy in the leaf isn't allowed for EV, so only init
1916 valid_policies if we have real policies. */
1917 if (!policy_set_contains(policies, &oidAnyPolicy)) {
1918 valid_policies = policies;
1919 policies = NULL;
1920 }
1921 } else if (ix < count - 1) {
1922 /* Subordinate CA */
1923 if (!SecPolicySubordinateCACertificateCouldBeEV(cert)) {
1924 secdebug("ev", "subordinate certificate is not ev");
1925 if (SecPVCSetResultForced(pvc, key,
1926 ix, kCFBooleanFalse, true)) {
1927 policy_set_free(valid_policies);
1928 policy_set_free(policies);
1929 return;
1930 }
1931 }
1932 policy_set_intersect(&valid_policies, policies);
1933 } else {
1934 /* Root CA */
1935 if (!SecPolicyRootCACertificateIsEV(cert, valid_policies)) {
1936 secdebug("ev", "anchor certificate is not ev");
1937 if (SecPVCSetResultForced(pvc, key,
1938 ix, kCFBooleanFalse, true)) {
1939 policy_set_free(valid_policies);
1940 policy_set_free(policies);
1941 return;
1942 }
1943 }
1944 }
1945 policy_set_free(policies);
1946 if (!valid_policies) {
1947 secdebug("ev", "valid_policies set is empty: chain not ev");
1948 /* If we ever get into a state where no policies are valid anymore
1949 this can't be an ev chain. */
1950 if (SecPVCSetResultForced(pvc, key,
1951 ix, kCFBooleanFalse, true)) {
1952 return;
1953 }
1954 }
1955 }
1956
1957 policy_set_free(valid_policies);
1958
1959 /* (a) EV Subscriber Certificates Each EV Certificate issued by the CA to a
1960 Subscriber MUST contain an OID defined by the CA in the certificate’s
1961 certificatePolicies extension that: (i) indicates which CA policy statement relates
1962 to that certificate, (ii) asserts the CA’s adherence to and compliance with these
1963 Guidelines, and (iii), by pre-agreement with the Application Software Vendor,
1964 marks the certificate as being an EV Certificate.
1965 (b) EV Subordinate CA Certificates
1966 (1) Certificates issued to Subordinate CAs that are not controlled by the issuing
1967 CA MUST contain one or more OIDs defined by the issuing CA that
1968 explicitly identify the EV Policies that are implemented by the Subordinate
1969 CA;
1970 (2) Certificates issued to Subordinate CAs that are controlled by the Root CA
1971 MAY contain the special anyPolicy OID (2.5.29.32.0).
1972 (c) Root CA Certificates Root CA Certificates SHOULD NOT contain the
1973 certificatePolicies or extendedKeyUsage extensions.
1974 */
1975 }
1976
1977
1978 /*
1979 * MARK: Certificate Transparency support
1980 */
1981
1982 /***
1983
1984 struct {
1985 Version sct_version; // 1 byte
1986 LogID id; // 32 bytes
1987 uint64 timestamp; // 8 bytes
1988 CtExtensions extensions; // 2 bytes len field, + n bytes data
1989 digitally-signed struct { // 1 byte hash alg, 1 byte sig alg, n bytes signature
1990 Version sct_version;
1991 SignatureType signature_type = certificate_timestamp;
1992 uint64 timestamp;
1993 LogEntryType entry_type;
1994 select(entry_type) {
1995 case x509_entry: ASN.1Cert;
1996 case precert_entry: PreCert;
1997 } signed_entry;
1998 CtExtensions extensions;
1999 };
2000 } SignedCertificateTimestamp;
2001
2002 ***/
2003
2004 #include <Security/SecureTransportPriv.h>
2005
2006 static const
2007 SecAsn1Oid *oidForSigAlg(SSL_HashAlgorithm hash, SSL_SignatureAlgorithm alg)
2008 {
2009 switch(alg) {
2010 case SSL_SignatureAlgorithmRSA:
2011 switch (hash) {
2012 case SSL_HashAlgorithmSHA1:
2013 return &CSSMOID_SHA1WithRSA;
2014 case SSL_HashAlgorithmSHA256:
2015 return &CSSMOID_SHA256WithRSA;
2016 case SSL_HashAlgorithmSHA384:
2017 return &CSSMOID_SHA384WithRSA;
2018 default:
2019 break;
2020 }
2021 case SSL_SignatureAlgorithmECDSA:
2022 switch (hash) {
2023 case SSL_HashAlgorithmSHA1:
2024 return &CSSMOID_ECDSA_WithSHA1;
2025 case SSL_HashAlgorithmSHA256:
2026 return &CSSMOID_ECDSA_WithSHA256;
2027 case SSL_HashAlgorithmSHA384:
2028 return &CSSMOID_ECDSA_WithSHA384;
2029 default:
2030 break;
2031 }
2032 default:
2033 break;
2034 }
2035
2036 return NULL;
2037 }
2038
2039
2040 static size_t SSLDecodeUint16(const uint8_t *p)
2041 {
2042 return (p[0]<<8 | p[1]);
2043 }
2044
2045 static uint8_t *SSLEncodeUint16(uint8_t *p, size_t len)
2046 {
2047 p[0] = (len >> 8)&0xff;
2048 p[1] = (len & 0xff);
2049 return p+2;
2050 }
2051
2052 static uint8_t *SSLEncodeUint24(uint8_t *p, size_t len)
2053 {
2054 p[0] = (len >> 16)&0xff;
2055 p[1] = (len >> 8)&0xff;
2056 p[2] = (len & 0xff);
2057 return p+3;
2058 }
2059
2060
2061 static
2062 uint64_t SSLDecodeUint64(const uint8_t *p)
2063 {
2064 uint64_t u = 0;
2065 for(int i=0; i<8; i++) {
2066 u=(u<<8)|p[0];
2067 p++;
2068 }
2069 return u;
2070 }
2071
2072 #include <libDER/DER_CertCrl.h>
2073 #include <libDER/DER_Encode.h>
2074 #include <libDER/asn1Types.h>
2075
2076
2077 static CFDataRef copy_x509_entry_from_chain(SecPVCRef pvc)
2078 {
2079 SecCertificateRef leafCert = SecPVCGetCertificateAtIndex(pvc, 0);
2080
2081 CFMutableDataRef data = CFDataCreateMutable(kCFAllocatorDefault, 3+SecCertificateGetLength(leafCert));
2082
2083 CFDataSetLength(data, 3+SecCertificateGetLength(leafCert));
2084
2085 uint8_t *q = CFDataGetMutableBytePtr(data);
2086 q = SSLEncodeUint24(q, SecCertificateGetLength(leafCert));
2087 memcpy(q, SecCertificateGetBytePtr(leafCert), SecCertificateGetLength(leafCert));
2088
2089 return data;
2090 }
2091
2092
2093 static CFDataRef copy_precert_entry_from_chain(SecPVCRef pvc)
2094 {
2095 SecCertificateRef leafCert = NULL;
2096 SecCertificateRef issuer = NULL;
2097 CFDataRef issuerKeyHash = NULL;
2098 CFDataRef tbs_precert = NULL;
2099 CFMutableDataRef data= NULL;
2100
2101 require_quiet(SecPVCGetCertificateCount(pvc)>=2, out); //we need the issuer key for precerts.
2102 leafCert = SecPVCGetCertificateAtIndex(pvc, 0);
2103 issuer = SecPVCGetCertificateAtIndex(pvc, 1);
2104
2105 require(leafCert, out);
2106 require(issuer, out); // Those two would likely indicate an internal error, since we already checked the chain length above.
2107 issuerKeyHash = SecCertificateCopySubjectPublicKeyInfoSHA256Digest(issuer);
2108 tbs_precert = SecCertificateCopyPrecertTBS(leafCert);
2109
2110 require(issuerKeyHash, out);
2111 require(tbs_precert, out);
2112 data = CFDataCreateMutable(kCFAllocatorDefault, CFDataGetLength(issuerKeyHash) + 3 + CFDataGetLength(tbs_precert));
2113 CFDataSetLength(data, CFDataGetLength(issuerKeyHash) + 3 + CFDataGetLength(tbs_precert));
2114
2115 uint8_t *q = CFDataGetMutableBytePtr(data);
2116 memcpy(q, CFDataGetBytePtr(issuerKeyHash), CFDataGetLength(issuerKeyHash)); q += CFDataGetLength(issuerKeyHash); // issuer key hash
2117 q = SSLEncodeUint24(q, CFDataGetLength(tbs_precert));
2118 memcpy(q, CFDataGetBytePtr(tbs_precert), CFDataGetLength(tbs_precert));
2119
2120 out:
2121 CFReleaseSafe(issuerKeyHash);
2122 CFReleaseSafe(tbs_precert);
2123 return data;
2124 }
2125
2126 /* If the 'sct' is valid, return the operator ID of the log that signed this sct.
2127
2128 The SCT is valid if:
2129 - It decodes properly.
2130 - Its timestamp is less than 'verifyTime'.
2131 - It is signed by a log in 'trustedLogs'.
2132 - The signing log expiryTime (if any) is less than 'verifyTime' (entry_type==0) or 'issuanceTime' (entry_type==1).
2133
2134 If the SCT is valid, the returned CFStringRef is the identifier for the log operator. That value is not retained.
2135 If the SCT is valid, '*validLogAtVerifyTime' is set to true if the log is not expired at 'verifyTime'
2136
2137 If the SCT is not valid this function return NULL.
2138 */
2139 static CFStringRef get_valid_sct_operator(CFDataRef sct, int entry_type, CFDataRef entry, CFAbsoluteTime verifyTime, CFAbsoluteTime issuanceTime, CFArrayRef trustedLogs, bool *validLogAtVerifyTime)
2140 {
2141 uint8_t version;
2142 const uint8_t *logID;
2143 const uint8_t *timestampData;
2144 uint64_t timestamp;
2145 size_t extensionsLen;
2146 const uint8_t *extensionsData;
2147 uint8_t hashAlg;
2148 uint8_t sigAlg;
2149 size_t signatureLen;
2150 const uint8_t *signatureData;
2151 CFStringRef result = NULL;
2152 SecKeyRef pubKey = NULL;
2153 uint8_t *signed_data = NULL;
2154 const SecAsn1Oid *oid = NULL;
2155 SecAsn1AlgId algId;
2156
2157 const uint8_t *p = CFDataGetBytePtr(sct);
2158 size_t len = CFDataGetLength(sct);
2159 uint64_t vt =(uint64_t)( verifyTime + kCFAbsoluteTimeIntervalSince1970) * 1000;
2160
2161 require(len>=43, out);
2162
2163 version = p[0]; p++; len--;
2164 logID = p; p+=32; len-=32;
2165 timestampData = p; p+=8; len-=8;
2166 extensionsLen = SSLDecodeUint16(p); p+=2; len-=2;
2167
2168 require(len>=extensionsLen, out);
2169 extensionsData = p; p+=extensionsLen; len-=extensionsLen;
2170
2171 require(len>=4, out);
2172 hashAlg=p[0]; p++; len--;
2173 sigAlg=p[0]; p++; len--;
2174 signatureLen = SSLDecodeUint16(p); p+=2; len-=2;
2175 require(len==signatureLen, out); /* We do not tolerate any extra data after the signature */
2176 signatureData = p;
2177
2178 /* verify version: only v1(0) is supported */
2179 if(version!=0) {
2180 secerror("SCT version unsupported: %d\n", version);
2181 goto out;
2182 }
2183
2184 /* verify timestamp not in the future */
2185 timestamp = SSLDecodeUint64(timestampData);
2186 if(timestamp > vt) {
2187 secerror("SCT is in the future: %llu > %llu\n", timestamp, vt);
2188 goto out;
2189 }
2190
2191 uint8_t *q;
2192
2193 /* signed entry */
2194 size_t signed_data_len = 12 + CFDataGetLength(entry) + 2 + extensionsLen ;
2195 signed_data = malloc(signed_data_len);
2196 require(signed_data, out);
2197 q = signed_data;
2198 *q++ = version;
2199 *q++ = 0; // certificate_timestamp
2200 memcpy(q, timestampData, 8); q+=8;
2201 q = SSLEncodeUint16(q, entry_type); // logentry type: 0=cert 1=precert
2202 memcpy(q, CFDataGetBytePtr(entry), CFDataGetLength(entry)); q += CFDataGetLength(entry);
2203 q = SSLEncodeUint16(q, extensionsLen);
2204 memcpy(q, extensionsData, extensionsLen);
2205
2206 CFDataRef logIDData = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, logID, 32, NULL);
2207
2208 CFDictionaryRef logData = CFArrayGetValueMatching(trustedLogs, ^bool(const void *dict) {
2209 const void *key_data;
2210 if(!isDictionary(dict)) return false;
2211 if(!CFDictionaryGetValueIfPresent(dict, CFSTR("key"), &key_data)) return false;
2212 if(!isData(key_data)) return false;
2213 CFDataRef valueID = SecSHA256DigestCreateFromData(kCFAllocatorDefault, (CFDataRef)key_data);
2214 bool result = (bool)(CFDataCompare(logIDData, valueID)==kCFCompareEqualTo);
2215 CFReleaseSafe(valueID);
2216 return result;
2217 });
2218 require(logData, out);
2219
2220 /* If an expiry date is specified, and is a valid CFDate, then we check it against issuanceTime or verifyTime */
2221 const void *expiry_date;
2222 if(CFDictionaryGetValueIfPresent(logData, CFSTR("expiry"), &expiry_date) && isDate(expiry_date)) {
2223 CFAbsoluteTime expiryTime = CFDateGetAbsoluteTime(expiry_date);
2224 if(entry_type == 1) {/* pre-cert: check the validity of the log at issuanceTime */
2225 require(issuanceTime<=expiryTime, out);
2226 } else {
2227 require(verifyTime<=expiryTime, out);
2228 }
2229 *validLogAtVerifyTime = (verifyTime<=expiryTime);
2230 } else {
2231 *validLogAtVerifyTime = true;
2232 }
2233
2234 CFDataRef logKeyData = CFDictionaryGetValue(logData, CFSTR("key"));
2235 require(logKeyData, out); // This failing would be an internal logic error
2236 pubKey = SecKeyCreateFromSubjectPublicKeyInfoData(kCFAllocatorDefault, logKeyData);
2237 require(pubKey, out);
2238
2239 oid = oidForSigAlg(hashAlg, sigAlg);
2240 require(oid, out);
2241
2242 algId.algorithm = *oid;
2243 algId.parameters.Data = NULL;
2244 algId.parameters.Length = 0;
2245
2246 if(SecKeyDigestAndVerify(pubKey, &algId, signed_data, signed_data_len, signatureData, signatureLen)==0) {
2247 result = CFDictionaryGetValue(logData, CFSTR("operator"));
2248 } else {
2249 secerror("SCT signature failed (log=%@)\n", logData);
2250 }
2251
2252 out:
2253 CFReleaseSafe(pubKey);
2254 free(signed_data);
2255 return result;
2256 }
2257
2258 static CFArrayRef copy_ocsp_scts(SecPVCRef pvc)
2259 {
2260 CFMutableArrayRef SCTs = NULL;
2261 SecCertificateRef leafCert = NULL;
2262 SecCertificateRef issuer = NULL;
2263 CFArrayRef ocspResponsesData = NULL;
2264 SecOCSPRequestRef ocspRequest = NULL;
2265
2266 ocspResponsesData = SecPathBuilderCopyOCSPResponses(pvc->builder);
2267 require_quiet(ocspResponsesData, out);
2268
2269 require_quiet(SecPVCGetCertificateCount(pvc)>=2, out); //we need the issuer key for precerts.
2270 leafCert = SecPVCGetCertificateAtIndex(pvc, 0);
2271 issuer = SecPVCGetCertificateAtIndex(pvc, 1);
2272
2273 require(leafCert, out);
2274 require(issuer, out); // not quiet: Those two would likely indicate an internal error, since we already checked the chain length above.
2275 ocspRequest = SecOCSPRequestCreate(leafCert, issuer);
2276
2277 SCTs = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
2278 require(SCTs, out);
2279
2280 CFArrayForEach(ocspResponsesData, ^(const void *value) {
2281 /* TODO: Should the builder already have the appropriate SecOCSPResponseRef ? */
2282 SecOCSPResponseRef ocspResponse = SecOCSPResponseCreate(value);
2283 if(ocspResponse && SecOCSPGetResponseStatus(ocspResponse)==kSecOCSPSuccess) {
2284 SecOCSPSingleResponseRef ocspSingleResponse = SecOCSPResponseCopySingleResponse(ocspResponse, ocspRequest);
2285 if(ocspSingleResponse) {
2286 CFArrayRef singleResponseSCTs = SecOCSPSingleResponseCopySCTs(ocspSingleResponse);
2287 if(singleResponseSCTs) {
2288 CFArrayAppendArray(SCTs, singleResponseSCTs, CFRangeMake(0, CFArrayGetCount(singleResponseSCTs)));
2289 CFRelease(singleResponseSCTs);
2290 }
2291 SecOCSPSingleResponseDestroy(ocspSingleResponse);
2292 }
2293 SecOCSPResponseFinalize(ocspResponse);
2294 }
2295 });
2296
2297 if(CFArrayGetCount(SCTs)==0) {
2298 CFReleaseNull(SCTs);
2299 }
2300
2301 out:
2302 CFReleaseSafe(ocspResponsesData);
2303 if(ocspRequest)
2304 SecOCSPRequestFinalize(ocspRequest);
2305
2306 return SCTs;
2307 }
2308
2309 static void SecPolicyCheckCT(SecPVCRef pvc, CFStringRef key)
2310 {
2311 SecCertificateRef leafCert = SecPVCGetCertificateAtIndex(pvc, 0);
2312 CFArrayRef embeddedScts = SecCertificateCopySignedCertificateTimestamps(leafCert);
2313 CFArrayRef builderScts = SecPathBuilderCopySignedCertificateTimestamps(pvc->builder);
2314 CFArrayRef trustedLogs = SecPathBuilderCopyTrustedLogs(pvc->builder);
2315 CFArrayRef ocspScts = copy_ocsp_scts(pvc);
2316 CFDataRef precertEntry = copy_precert_entry_from_chain(pvc);
2317 CFDataRef x509Entry = copy_x509_entry_from_chain(pvc);
2318
2319 // This eventually contain the list of operators who validated the SCT.
2320 CFMutableSetRef operatorsValidatingEmbeddedScts = CFSetCreateMutable(kCFAllocatorDefault, 0, &kCFTypeSetCallBacks);
2321 CFMutableSetRef operatorsValidatingExternalScts = CFSetCreateMutable(kCFAllocatorDefault, 0, &kCFTypeSetCallBacks);
2322
2323 __block bool atLeastOneValidAtVerifyTime = false;
2324 __block int lifetime; // in Months
2325
2326 require(operatorsValidatingEmbeddedScts, out);
2327 require(operatorsValidatingExternalScts, out);
2328
2329 if(trustedLogs) { // Don't bother trying to validate SCTs if we don't have any trusted logs.
2330 if(embeddedScts && precertEntry) { // Don't bother if we could not get the precert.
2331 CFArrayForEach(embeddedScts, ^(const void *value){
2332 bool validLogAtVerifyTime = false;
2333 CFStringRef operator = get_valid_sct_operator(value, 1, precertEntry, pvc->verifyTime, SecCertificateNotValidBefore(leafCert), trustedLogs, &validLogAtVerifyTime);
2334 if(operator) CFSetAddValue(operatorsValidatingEmbeddedScts, operator);
2335 if(validLogAtVerifyTime) atLeastOneValidAtVerifyTime = true;
2336 });
2337 }
2338
2339 if(builderScts && x509Entry) { // Don't bother if we could not get the cert.
2340 CFArrayForEach(builderScts, ^(const void *value){
2341 bool validLogAtVerifyTime = false;
2342 CFStringRef operator = get_valid_sct_operator(value, 0, x509Entry, pvc->verifyTime, SecCertificateNotValidBefore(leafCert), trustedLogs, &validLogAtVerifyTime);
2343 if(operator) CFSetAddValue(operatorsValidatingExternalScts, operator);
2344 if(validLogAtVerifyTime) atLeastOneValidAtVerifyTime = true;
2345 });
2346 }
2347
2348 if(ocspScts && x509Entry) {
2349 CFArrayForEach(ocspScts, ^(const void *value){
2350 bool validLogAtVerifyTime = false;
2351 CFStringRef operator = get_valid_sct_operator(value, 0, x509Entry, pvc->verifyTime, SecCertificateNotValidBefore(leafCert), trustedLogs, &validLogAtVerifyTime);
2352 if(operator) CFSetAddValue(operatorsValidatingExternalScts, operator);
2353 if(validLogAtVerifyTime) atLeastOneValidAtVerifyTime = true;
2354 });
2355 }
2356 }
2357
2358 /* We now have 2 sets of operators that validated those SCTS, count them and make a final decision.
2359 Current Policy:
2360 is_ct = (A1 OR A2) AND B.
2361
2362 A1: 2+ to 5+ SCTs from the cert from independent logs valid at issuance time
2363 (operatorsValidatingEmbeddedScts)
2364 A2: 2+ SCTs from external sources (OCSP stapled response and TLS extension)
2365 from independent logs valid at verify time. (operatorsValidatingExternalScts)
2366 B: All least one SCTs from a log valid at verify time.
2367
2368 Policy is based on: https://docs.google.com/viewer?a=v&pid=sites&srcid=ZGVmYXVsdGRvbWFpbnxjZXJ0aWZpY2F0ZXRyYW5zcGFyZW5jeXxneDo0ODhjNGRlOTIyMzYwNTcz
2369 with one difference: we consider SCTs from OCSP and TLS extensions as a whole.
2370 It sounds like this is what Google will eventually do, per:
2371 https://groups.google.com/forum/?fromgroups#!topic/certificate-transparency/VdXuzA3TLWY
2372
2373 */
2374
2375 SecCFCalendarDoWithZuluCalendar(^(CFCalendarRef zuluCalendar) {
2376 int _lifetime;
2377 CFCalendarGetComponentDifference(zuluCalendar,
2378 SecCertificateNotValidBefore(leafCert),
2379 SecCertificateNotValidAfter(leafCert),
2380 0, "M", &_lifetime);
2381 lifetime = _lifetime;
2382 });
2383
2384 CFIndex requiredEmbeddedSctsCount;
2385
2386 if (lifetime < 15) {
2387 requiredEmbeddedSctsCount = 2;
2388 } else if (lifetime <= 27) {
2389 requiredEmbeddedSctsCount = 3;
2390 } else if (lifetime <= 39) {
2391 requiredEmbeddedSctsCount = 4;
2392 } else {
2393 requiredEmbeddedSctsCount = 5;
2394 }
2395
2396 pvc->is_ct = ((CFSetGetCount(operatorsValidatingEmbeddedScts) >= requiredEmbeddedSctsCount) ||
2397 (CFSetGetCount(operatorsValidatingExternalScts) >= 2)
2398 ) && atLeastOneValidAtVerifyTime;
2399
2400 out:
2401
2402 CFReleaseSafe(operatorsValidatingEmbeddedScts);
2403 CFReleaseSafe(operatorsValidatingExternalScts);
2404 CFReleaseSafe(builderScts);
2405 CFReleaseSafe(embeddedScts);
2406 CFReleaseSafe(ocspScts);
2407 CFReleaseSafe(precertEntry);
2408 CFReleaseSafe(trustedLogs);
2409 CFReleaseSafe(x509Entry);
2410 }
2411
2412 static void SecPolicyCheckCertificatePolicyOid(SecPVCRef pvc, CFStringRef key)
2413 {
2414 CFIndex ix, count = SecPVCGetCertificateCount(pvc);
2415 SecPolicyRef policy = SecPVCGetPolicy(pvc);
2416 CFTypeRef value = CFDictionaryGetValue(policy->_options, key);
2417 DERItem key_value;
2418 key_value.data = NULL;
2419 key_value.length = 0;
2420
2421 if (CFGetTypeID(value) == CFDataGetTypeID())
2422 {
2423 CFDataRef key_data = (CFDataRef)value;
2424 key_value.data = (DERByte *)CFDataGetBytePtr(key_data);
2425 key_value.length = (DERSize)CFDataGetLength(key_data);
2426
2427 for (ix = 0; ix < count; ix++) {
2428 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, ix);
2429 policy_set_t policies = policies_for_cert(cert);
2430
2431 if (policy_set_contains(policies, &key_value)) {
2432 return;
2433 }
2434 }
2435 SecPVCSetResult(pvc, key, 0, kCFBooleanFalse);
2436 }
2437 }
2438
2439
2440 static void SecPolicyCheckRevocation(SecPVCRef pvc,
2441 CFStringRef key) {
2442 SecPVCSetCheckRevocation(pvc);
2443 }
2444
2445 static void SecPolicyCheckRevocationResponseRequired(SecPVCRef pvc,
2446 CFStringRef key) {
2447 SecPVCSetCheckRevocationResponseRequired(pvc);
2448 }
2449
2450 static void SecPolicyCheckNoNetworkAccess(SecPVCRef pvc,
2451 CFStringRef key) {
2452 SecPathBuilderSetCanAccessNetwork(pvc->builder, false);
2453 }
2454
2455 static void SecPolicyCheckWeakIntermediates(SecPVCRef pvc,
2456 CFStringRef key) {
2457 CFIndex ix, count = SecPVCGetCertificateCount(pvc);
2458 for (ix = 1; ix < count - 1; ++ix) {
2459 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, ix);
2460 if (cert && SecCertificateIsWeak(cert)) {
2461 /* Intermediate certificate has a weak key. */
2462 if (!SecPVCSetResult(pvc, key, ix, kCFBooleanFalse))
2463 return;
2464 }
2465 }
2466 }
2467
2468 static void SecPolicyCheckWeakLeaf(SecPVCRef pvc,
2469 CFStringRef key) {
2470 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, 0);
2471 if (cert && SecCertificateIsWeak(cert)) {
2472 /* Leaf certificate has a weak key. */
2473 if (!SecPVCSetResult(pvc, key, 0, kCFBooleanFalse))
2474 return;
2475 }
2476 }
2477
2478 static void SecPolicyCheckWeakRoot(SecPVCRef pvc,
2479 CFStringRef key) {
2480 CFIndex ix, count = SecPVCGetCertificateCount(pvc);
2481 ix = count - 1;
2482 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, ix);
2483 if (cert && SecCertificateIsWeak(cert)) {
2484 /* Root certificate has a weak key. */
2485 if (!SecPVCSetResult(pvc, key, ix, kCFBooleanFalse))
2486 return;
2487 }
2488 }
2489
2490 // MARK: -
2491 // MARK: SecRVCRef
2492 /********************************************************
2493 ****************** SecRVCRef Functions *****************
2494 ********************************************************/
2495
2496 const CFAbsoluteTime kSecDefaultOCSPResponseTTL = 24.0 * 60.0 * 60.0;
2497
2498 /* Revocation verification context. */
2499 struct OpaqueSecRVC {
2500 /* Will contain the response data. */
2501 asynchttp_t http;
2502
2503 /* Pointer to the pvc for this revocation check. */
2504 SecPVCRef pvc;
2505
2506 /* The ocsp request we send to each responder. */
2507 SecOCSPRequestRef ocspRequest;
2508
2509 /* The freshest response we received so far, from stapling or cache or responder. */
2510 SecOCSPResponseRef ocspResponse;
2511
2512 /* The best validated candidate single response we received so far, from stapling or cache or responder. */
2513 SecOCSPSingleResponseRef ocspSingleResponse;
2514
2515 /* Index of cert in pvc that this RVC is for 0 = leaf, etc. */
2516 CFIndex certIX;
2517
2518 /* Index in array returned by SecCertificateGetOCSPResponders() for current
2519 responder. */
2520 CFIndex responderIX;
2521
2522 /* URL of current responder. */
2523 CFURLRef responder;
2524
2525 /* Date until which this revocation status is valid. */
2526 CFAbsoluteTime nextUpdate;
2527
2528 bool done;
2529 };
2530 typedef struct OpaqueSecRVC *SecRVCRef;
2531
2532 static void SecRVCDelete(SecRVCRef rvc) {
2533 secdebug("alloc", "%p", rvc);
2534 asynchttp_free(&rvc->http);
2535 SecOCSPRequestFinalize(rvc->ocspRequest);
2536 if (rvc->ocspResponse) {
2537 SecOCSPResponseFinalize(rvc->ocspResponse);
2538 rvc->ocspResponse = NULL;
2539 if (rvc->ocspSingleResponse) {
2540 SecOCSPSingleResponseDestroy(rvc->ocspSingleResponse);
2541 rvc->ocspSingleResponse = NULL;
2542 }
2543 }
2544 }
2545
2546 /* Return the next responder we should contact for this rvc or NULL if we
2547 exhausted them all. */
2548 static CFURLRef SecRVCGetNextResponder(SecRVCRef rvc) {
2549 SecCertificateRef cert = SecPVCGetCertificateAtIndex(rvc->pvc, rvc->certIX);
2550 CFArrayRef ocspResponders = SecCertificateGetOCSPResponders(cert);
2551 if (ocspResponders) {
2552 CFIndex responderCount = CFArrayGetCount(ocspResponders);
2553 while (rvc->responderIX < responderCount) {
2554 CFURLRef responder = CFArrayGetValueAtIndex(ocspResponders, rvc->responderIX);
2555 rvc->responderIX++;
2556 CFStringRef scheme = CFURLCopyScheme(responder);
2557 if (scheme) {
2558 /* We only support http and https responders currently. */
2559 bool valid_responder = (CFEqual(CFSTR("http"), scheme) ||
2560 CFEqual(CFSTR("https"), scheme));
2561 CFRelease(scheme);
2562 if (valid_responder)
2563 return responder;
2564 }
2565 }
2566 }
2567 return NULL;
2568 }
2569
2570 /* Fire off an async http request for this certs revocation status, return
2571 false if request was queued, true if we're done. */
2572 static bool SecRVCFetchNext(SecRVCRef rvc) {
2573 while ((rvc->responder = SecRVCGetNextResponder(rvc))) {
2574 CFDataRef request = SecOCSPRequestGetDER(rvc->ocspRequest);
2575 if (!request)
2576 goto errOut;
2577
2578 secdebug("ocsp", "Sending http ocsp request for cert %ld", rvc->certIX);
2579 if (!asyncHttpPost(rvc->responder, request, &rvc->http)) {
2580 /* Async request was posted, wait for reply. */
2581 return false;
2582 }
2583 }
2584
2585 errOut:
2586 rvc->done = true;
2587 return true;
2588 }
2589
2590 /* Process a verified ocsp response for a given cert. Return true if the
2591 certificate status was obtained. */
2592 static bool SecOCSPSingleResponseProcess(SecOCSPSingleResponseRef this,
2593 SecRVCRef rvc) {
2594 bool processed;
2595 switch (this->certStatus) {
2596 case CS_Good:
2597 secdebug("ocsp", "CS_Good for cert %" PRIdCFIndex, rvc->certIX);
2598 /* @@@ Mark cert as valid until a given date (nextUpdate if we have one)
2599 in the info dictionary. */
2600 //cert.revokeCheckGood(true);
2601 rvc->nextUpdate = this->nextUpdate == NULL_TIME ? this->thisUpdate + kSecDefaultOCSPResponseTTL : this->nextUpdate;
2602 processed = true;
2603 break;
2604 case CS_Revoked:
2605 secdebug("ocsp", "CS_Revoked for cert %" PRIdCFIndex, rvc->certIX);
2606 /* @@@ Mark cert as revoked (with reason) at revocation date in
2607 the info dictionary, or perhaps we should use a different key per
2608 reason? That way a client using exceptions can ignore some but
2609 not all reasons. */
2610 SInt32 reason = this->crlReason;
2611 CFNumberRef cfreason = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &reason);
2612 SecPVCSetResultForced(rvc->pvc, kSecPolicyCheckRevocation, rvc->certIX,
2613 cfreason, true);
2614 if (rvc->pvc && rvc->pvc->info) {
2615 /* make the revocation reason available in the trust result */
2616 CFDictionarySetValue(rvc->pvc->info, kSecTrustRevocationReason, cfreason);
2617 }
2618 CFRelease(cfreason);
2619 processed = true;
2620 break;
2621 case CS_Unknown:
2622 /* not an error, no per-cert status, nothing here */
2623 secdebug("ocsp", "CS_Unknown for cert %" PRIdCFIndex, rvc->certIX);
2624 processed = false;
2625 break;
2626 default:
2627 secdebug("ocsp", "BAD certStatus (%d) for cert %" PRIdCFIndex,
2628 (int)this->certStatus, rvc->certIX);
2629 processed = false;
2630 break;
2631 }
2632
2633 return processed;
2634 }
2635
2636 static void SecRVCUpdatePVC(SecRVCRef rvc) {
2637 if (rvc->ocspSingleResponse) {
2638 SecOCSPSingleResponseProcess(rvc->ocspSingleResponse, rvc);
2639 }
2640 if (rvc->ocspResponse) {
2641 rvc->nextUpdate = SecOCSPResponseGetExpirationTime(rvc->ocspResponse);
2642 }
2643 }
2644
2645 static bool SecOCSPResponseVerify(SecOCSPResponseRef ocspResponse, SecRVCRef rvc, CFAbsoluteTime verifyTime) {
2646 bool trusted;
2647 SecCertificatePathRef issuer = SecCertificatePathCopyFromParent(rvc->pvc->path, rvc->certIX + 1);
2648 SecCertificatePathRef signer = SecOCSPResponseCopySigner(ocspResponse, issuer);
2649 CFRelease(issuer);
2650
2651 if (signer) {
2652 if (signer == issuer) {
2653 /* We already know we trust issuer since it's the path we are
2654 trying to verify minus the leaf. */
2655 secdebug("ocsp", "ocsp responder: %@ response signed by issuer",
2656 rvc->responder);
2657 trusted = true;
2658 } else {
2659 secdebug("ocsp",
2660 "ocsp responder: %@ response signed by cert issued by issuer",
2661 rvc->responder);
2662 /* @@@ Now check that we trust signer. */
2663 const void *ocspSigner = SecPolicyCreateOCSPSigner();
2664 CFArrayRef policies = CFArrayCreate(kCFAllocatorDefault,
2665 &ocspSigner, 1, &kCFTypeArrayCallBacks);
2666 CFRelease(ocspSigner);
2667 struct OpaqueSecPVC ospvc;
2668 SecPVCInit(&ospvc, rvc->pvc->builder, policies, verifyTime);
2669 CFRelease(policies);
2670 SecPVCSetPath(&ospvc, signer, NULL);
2671 SecPVCLeafChecks(&ospvc);
2672 if (ospvc.result) {
2673 bool completed = SecPVCPathChecks(&ospvc);
2674 /* If completed is false we are waiting for a callback, this
2675 shouldn't happen since we aren't asking for details, no
2676 revocation checking is done. */
2677 if (!completed) {
2678 ocspdErrorLog("SecPVCPathChecks unexpectedly started "
2679 "background job!");
2680 /* @@@ assert() or abort here perhaps? */
2681 }
2682 }
2683 if (ospvc.result) {
2684 secdebug("ocsp", "response satisfies ocspSigner policy (%@)",
2685 rvc->responder);
2686 trusted = true;
2687 } else {
2688 /* @@@ We don't trust the cert so don't use this response. */
2689 ocspdErrorLog("ocsp response signed by certificate which "
2690 "does not satisfy ocspSigner policy");
2691 trusted = false;
2692 }
2693 SecPVCDelete(&ospvc);
2694 }
2695
2696 CFRelease(signer);
2697 } else {
2698 /* @@@ No signer found for this ocsp response, discard it. */
2699 secdebug("ocsp", "ocsp responder: %@ no signer found for response",
2700 rvc->responder);
2701 trusted = false;
2702 }
2703
2704 #if DUMP_OCSPRESPONSES
2705 char buf[40];
2706 snprintf(buf, 40, "/tmp/ocspresponse%ld%s.der",
2707 rvc->certIX, (trusted ? "t" : "u"));
2708 secdumpdata(ocspResponse->data, buf);
2709 #endif
2710
2711 return trusted;
2712 }
2713
2714 static void SecRVCConsumeOCSPResponse(SecRVCRef rvc, SecOCSPResponseRef ocspResponse /*CF_CONSUMED*/, CFTimeInterval maxAge, bool updateCache) {
2715 SecOCSPSingleResponseRef sr = NULL;
2716 require_quiet(ocspResponse, errOut);
2717 SecOCSPResponseStatus orStatus = SecOCSPGetResponseStatus(ocspResponse);
2718 require_action_quiet(orStatus == kSecOCSPSuccess, errOut,
2719 secdebug("ocsp", "responder: %@ returned status: %d", rvc->responder, orStatus));
2720 require_action_quiet(sr = SecOCSPResponseCopySingleResponse(ocspResponse, rvc->ocspRequest), errOut,
2721 secdebug("ocsp", "ocsp responder: %@ did not include status of requested cert", rvc->responder));
2722 // Check if this response is fresher than any (cached) response we might still have in the rvc.
2723 require_quiet(!rvc->ocspSingleResponse || rvc->ocspSingleResponse->thisUpdate < sr->thisUpdate, errOut);
2724
2725 CFAbsoluteTime verifyTime = CFAbsoluteTimeGetCurrent();
2726 /* TODO: If the responder doesn't have the ocsp-nocheck extension we should
2727 check whether the leaf was revoked (we are already checking the rest of
2728 the chain). */
2729 /* Check the OCSP response signature and verify the response. */
2730 require_quiet(SecOCSPResponseVerify(ocspResponse, rvc,
2731 sr->certStatus == CS_Revoked ? SecOCSPResponseProducedAt(ocspResponse) : verifyTime), errOut);
2732
2733 // If we get here, we have a properly signed ocsp response
2734 // but we haven't checked dates yet.
2735
2736 bool sr_valid = SecOCSPSingleResponseCalculateValidity(sr, kSecDefaultOCSPResponseTTL, verifyTime);
2737 if (sr->certStatus == CS_Good) {
2738 // Side effect of SecOCSPResponseCalculateValidity sets ocspResponse->expireTime
2739 require_quiet(sr_valid && SecOCSPResponseCalculateValidity(ocspResponse, maxAge, kSecDefaultOCSPResponseTTL, verifyTime), errOut);
2740 } else if (sr->certStatus == CS_Revoked) {
2741 // Expire revoked responses when the subject certificate itself expires.
2742 ocspResponse->expireTime = SecCertificateNotValidAfter(SecPVCGetCertificateAtIndex(rvc->pvc, rvc->certIX));
2743 }
2744
2745 // Ok we like the new response, let's toss the old one.
2746 if (updateCache)
2747 SecOCSPCacheReplaceResponse(rvc->ocspResponse, ocspResponse, rvc->responder, verifyTime);
2748
2749 if (rvc->ocspResponse) SecOCSPResponseFinalize(rvc->ocspResponse);
2750 rvc->ocspResponse = ocspResponse;
2751 ocspResponse = NULL;
2752
2753 if (rvc->ocspSingleResponse) SecOCSPSingleResponseDestroy(rvc->ocspSingleResponse);
2754 rvc->ocspSingleResponse = sr;
2755 sr = NULL;
2756
2757 rvc->done = sr_valid;
2758
2759 errOut:
2760 if (sr) SecOCSPSingleResponseDestroy(sr);
2761 if (ocspResponse) SecOCSPResponseFinalize(ocspResponse);
2762 }
2763
2764 /* Callback from async http code after an ocsp response has been received. */
2765 static void SecOCSPFetchCompleted(asynchttp_t *http, CFTimeInterval maxAge) {
2766 SecRVCRef rvc = (SecRVCRef)http->info;
2767 SecPVCRef pvc = rvc->pvc;
2768 SecOCSPResponseRef ocspResponse = NULL;
2769 if (http->response) {
2770 CFDataRef data = CFHTTPMessageCopyBody(http->response);
2771 if (data) {
2772 /* Parse the returned data as if it's an ocspResponse. */
2773 ocspResponse = SecOCSPResponseCreate(data);
2774 CFRelease(data);
2775 }
2776 }
2777
2778 SecRVCConsumeOCSPResponse(rvc, ocspResponse, maxAge, true);
2779 // TODO: maybe we should set the cache-control: false in the http header and try again if the response is stale
2780
2781 if (!rvc->done) {
2782 /* Clear the data for the next response. */
2783 asynchttp_free(http);
2784 SecRVCFetchNext(rvc);
2785 }
2786
2787 if (rvc->done) {
2788 SecRVCUpdatePVC(rvc);
2789 SecRVCDelete(rvc);
2790 if (!--pvc->asyncJobCount) {
2791 SecPathBuilderStep(pvc->builder);
2792 }
2793 }
2794 }
2795
2796 static void SecRVCInit(SecRVCRef rvc, SecPVCRef pvc, CFIndex certIX) {
2797 secdebug("alloc", "%p", rvc);
2798 rvc->pvc = pvc;
2799 rvc->certIX = certIX;
2800 rvc->http.queue = SecPathBuilderGetQueue(pvc->builder);
2801 rvc->http.token = SecPathBuilderCopyClientAuditToken(pvc->builder);
2802 rvc->http.completed = SecOCSPFetchCompleted;
2803 rvc->http.info = rvc;
2804 rvc->ocspRequest = NULL;
2805 rvc->responderIX = 0;
2806 rvc->responder = NULL;
2807 rvc->nextUpdate = NULL_TIME;
2808 rvc->ocspResponse = NULL;
2809 rvc->ocspSingleResponse = NULL;
2810 rvc->done = false;
2811 }
2812
2813
2814 static bool SecPVCCheckRevocation(SecPVCRef pvc) {
2815 secdebug("ocsp", "checking revocation");
2816 CFIndex certIX, certCount = SecPVCGetCertificateCount(pvc);
2817 bool completed = true;
2818 if (certCount <= 1) {
2819 /* Can't verify without an issuer; we're done */
2820 return completed;
2821 }
2822 if (!SecPVCIsAnchored(pvc)) {
2823 /* We can't check revocation for chains without a trusted anchor. */
2824 return completed;
2825 }
2826 certCount--;
2827
2828 #if 0
2829 /* TODO: Implement getting this value from the client.
2830 Optional responder passed in though policy. */
2831 CFURLRef localResponder = NULL;
2832 /* Generate a nonce in outgoing request if true. */
2833 bool genNonce = false;
2834 /* Require a nonce in response if true. */
2835 bool requireRespNonce = false;
2836 bool cacheReadDisable = false;
2837 bool cacheWriteDisable = false;
2838 #endif
2839
2840 if (pvc->rvcs) {
2841 /* We have done revocation checking already, we're done. */
2842 secdebug("ocsp", "Not rechecking revocation");
2843 return completed;
2844 }
2845
2846 /* Setup things so we check revocation status of all certs except the
2847 anchor. */
2848 pvc->rvcs = calloc(sizeof(struct OpaqueSecRVC), certCount);
2849
2850 #if 0
2851 /* Lookup cached revocation data for each certificate. */
2852 for (certIX = 0; certIX < certCount; ++certIX) {
2853 SecCertificateRef cert = SecPVCGetCertificateAtIndex(rvc->pvc, rvc->certIX);
2854 CFArrayRef ocspResponders = SecCertificateGetOCSPResponders(cert);
2855 if (ocspResponders) {
2856 /* First look though passed in ocsp responses. */
2857 //SecPVCGetOCSPResponseForCertificateAtIndex(pvc, ix, singleResponse);
2858
2859 /* Then look though shared cache (we don't care which responder
2860 something came from here). */
2861 CFDataRef ocspResponse = SecOCSPCacheCopyMatching(SecCertIDRef certID, NULL);
2862
2863 /* Now let's parse the response. */
2864 if (decodeOCSPResponse(ocspResp)) {
2865 secdebug("ocsp", "response ok: %@", ocspResp);
2866 } else {
2867 secdebug("ocsp", "response bad: %@", ocspResp);
2868 /* ocsp response not ok. */
2869 if (!SecPVCSetResultForced(pvc, key, ix, kCFBooleanFalse, true))
2870 return completed;
2871 }
2872 CFReleaseSafe(ocspResp);
2873 } else {
2874 /* Check if certificate has any crl distributionPoints. */
2875 CFArrayRef distributionPoints = SecCertificateGetCRLDistributionPoints(cert);
2876 if (distributionPoints) {
2877 /* Look for a cached CRL and potentially delta CRL for this certificate. */
2878 }
2879 }
2880 }
2881 #endif
2882
2883 /* Note that if we are multi threaded and a job completes after it
2884 is started but before we return from this function, we don't want
2885 a callback to decrement asyncJobCount to zero before we finish issuing
2886 all the jobs. To avoid this we pretend we issued certCount async jobs,
2887 and decrement pvc->asyncJobCount for each cert that we don't start a
2888 background fetch for. */
2889 pvc->asyncJobCount = (unsigned int) certCount;
2890
2891 /* Loop though certificates again and issue an ocsp fetch if the
2892 revocation status checking isn't done yet. */
2893 for (certIX = 0; certIX < certCount; ++certIX) {
2894 secdebug("ocsp", "checking revocation for cert: %ld", certIX);
2895 SecRVCRef rvc = &((SecRVCRef)pvc->rvcs)[certIX];
2896 SecRVCInit(rvc, pvc, certIX);
2897 if (rvc->done)
2898 continue;
2899
2900 SecCertificateRef cert = SecPVCGetCertificateAtIndex(rvc->pvc,
2901 rvc->certIX);
2902 /* The certIX + 1 is ok here since certCount is always at least 1
2903 less than the actual number of certs. */
2904 SecCertificateRef issuer = SecPVCGetCertificateAtIndex(rvc->pvc,
2905 rvc->certIX + 1);
2906
2907 rvc->ocspRequest = SecOCSPRequestCreate(cert, issuer);
2908
2909 /* Get stapled OCSP responses */
2910 CFArrayRef ocspResponsesData = SecPathBuilderCopyOCSPResponses(pvc->builder);
2911
2912 /* If we have any OCSP stapled responses, check those first */
2913 if(ocspResponsesData) {
2914 secdebug("ocsp", "Checking stapled responses for cert %ld", certIX);
2915 CFArrayForEach(ocspResponsesData, ^(const void *value) {
2916 /* TODO: Should the builder already have the appropriate SecOCSPResponseRef ? */
2917 SecOCSPResponseRef ocspResponse = SecOCSPResponseCreate(value);
2918 SecRVCConsumeOCSPResponse(rvc, ocspResponse, NULL_TIME, false);
2919 });
2920 CFRelease(ocspResponsesData);
2921 }
2922
2923 /* Then check the cached response */
2924 secdebug("ocsp", "Checking cached responses for cert %ld", certIX);
2925 SecRVCConsumeOCSPResponse(rvc, SecOCSPCacheCopyMatching(rvc->ocspRequest, NULL), NULL_TIME, false);
2926
2927 /* If the cert is EV or if revocation checking was explicitly enabled, attempt to fire off an
2928 async http request for this cert's revocation status, unless we already successfully checked
2929 the revocation status of this cert based on the cache or stapled responses, */
2930 bool allow_fetch = SecPathBuilderCanAccessNetwork(pvc->builder) && (pvc->is_ev || pvc->check_revocation);
2931 bool fetch_done = true;
2932 if (rvc->done || !allow_fetch ||
2933 (fetch_done = SecRVCFetchNext(rvc))) {
2934 /* We got a cache hit or we aren't allowed to access the network,
2935 or the async http post failed. */
2936 SecRVCUpdatePVC(rvc);
2937 SecRVCDelete(rvc);
2938 /* We didn't really start a background job for this cert. */
2939 pvc->asyncJobCount--;
2940 } else if (!fetch_done) {
2941 /* We started at least one background fetch. */
2942 completed = false;
2943 }
2944 }
2945
2946 /* Return false if we started any background jobs. */
2947 /* We can't just return !pvc->asyncJobCount here, since if we started any
2948 jobs the completion callback will be called eventually and it will call
2949 SecPathBuilderStep(). If for some reason everything completed before we
2950 get here we still want the outer SecPathBuilderStep() to terminate so we
2951 keep track of whether we started any jobs and return false if so. */
2952 return completed;
2953 }
2954
2955
2956 void SecPolicyServerInitalize(void) {
2957 gSecPolicyLeafCallbacks = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
2958 &kCFTypeDictionaryKeyCallBacks, NULL);
2959 gSecPolicyPathCallbacks = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
2960 &kCFTypeDictionaryKeyCallBacks, NULL);
2961
2962 CFDictionaryAddValue(gSecPolicyPathCallbacks,
2963 kSecPolicyCheckBasicCertificateProcessing,
2964 SecPolicyCheckBasicCertificateProcessing);
2965 CFDictionaryAddValue(gSecPolicyPathCallbacks,
2966 kSecPolicyCheckCriticalExtensions,
2967 SecPolicyCheckCriticalExtensions);
2968 CFDictionaryAddValue(gSecPolicyPathCallbacks,
2969 kSecPolicyCheckIdLinkage,
2970 SecPolicyCheckIdLinkage);
2971 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
2972 kSecPolicyCheckKeyUsage,
2973 SecPolicyCheckKeyUsage);
2974 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
2975 kSecPolicyCheckExtendedKeyUsage,
2976 SecPolicyCheckExtendedKeyUsage);
2977 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
2978 kSecPolicyCheckBasicContraints,
2979 SecPolicyCheckBasicContraints);
2980 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
2981 kSecPolicyCheckNonEmptySubject,
2982 SecPolicyCheckNonEmptySubject);
2983 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
2984 kSecPolicyCheckQualifiedCertStatements,
2985 SecPolicyCheckQualifiedCertStatements);
2986 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
2987 kSecPolicyCheckSSLHostname,
2988 SecPolicyCheckSSLHostname);
2989 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
2990 kSecPolicyCheckEmail,
2991 SecPolicyCheckEmail);
2992 CFDictionaryAddValue(gSecPolicyPathCallbacks,
2993 kSecPolicyCheckValidIntermediates,
2994 SecPolicyCheckValidIntermediates);
2995 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
2996 kSecPolicyCheckValidLeaf,
2997 SecPolicyCheckValidLeaf);
2998 CFDictionaryAddValue(gSecPolicyPathCallbacks,
2999 kSecPolicyCheckValidRoot,
3000 SecPolicyCheckValidRoot);
3001 CFDictionaryAddValue(gSecPolicyPathCallbacks,
3002 kSecPolicyCheckIssuerCommonName,
3003 SecPolicyCheckIssuerCommonName);
3004 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3005 kSecPolicyCheckSubjectCommonNamePrefix,
3006 SecPolicyCheckSubjectCommonNamePrefix);
3007 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3008 kSecPolicyCheckSubjectCommonName,
3009 SecPolicyCheckSubjectCommonName);
3010 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3011 kSecPolicyCheckNotValidBefore,
3012 SecPolicyCheckNotValidBefore);
3013 CFDictionaryAddValue(gSecPolicyPathCallbacks,
3014 kSecPolicyCheckChainLength,
3015 SecPolicyCheckChainLength);
3016 CFDictionaryAddValue(gSecPolicyPathCallbacks,
3017 kSecPolicyCheckAnchorSHA1,
3018 SecPolicyCheckAnchorSHA1);
3019 CFDictionaryAddValue(gSecPolicyPathCallbacks,
3020 kSecPolicyCheckIntermediateSPKISHA256,
3021 SecPolicyCheckIntermediateSPKISHA256);
3022 CFDictionaryAddValue(gSecPolicyPathCallbacks,
3023 kSecPolicyCheckAnchorApple,
3024 SecPolicyCheckAnchorApple);
3025 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3026 kSecPolicyCheckSubjectOrganization,
3027 SecPolicyCheckSubjectOrganization);
3028 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3029 kSecPolicyCheckSubjectOrganizationalUnit,
3030 SecPolicyCheckSubjectOrganizationalUnit);
3031 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3032 kSecPolicyCheckEAPTrustedServerNames,
3033 SecPolicyCheckEAPTrustedServerNames);
3034 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3035 kSecPolicyCheckSubjectCommonNameTEST,
3036 SecPolicyCheckSubjectCommonNameTEST);
3037 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3038 kSecPolicyCheckRevocation,
3039 SecPolicyCheckRevocation);
3040 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3041 kSecPolicyCheckRevocationResponseRequired,
3042 SecPolicyCheckRevocationResponseRequired);
3043 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3044 kSecPolicyCheckNoNetworkAccess,
3045 SecPolicyCheckNoNetworkAccess);
3046 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3047 kSecPolicyCheckBlackListedLeaf,
3048 SecPolicyCheckBlackListedLeaf);
3049 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3050 kSecPolicyCheckGrayListedLeaf,
3051 SecPolicyCheckGrayListedLeaf);
3052 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3053 kSecPolicyCheckLeafMarkerOid,
3054 SecPolicyCheckLeafMarkerOid);
3055 CFDictionaryAddValue(gSecPolicyPathCallbacks,
3056 kSecPolicyCheckIntermediateMarkerOid,
3057 SecPolicyCheckIntermediateMarkerOid);
3058 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3059 kSecPolicyCheckCertificatePolicy,
3060 SecPolicyCheckCertificatePolicyOid);
3061 CFDictionaryAddValue(gSecPolicyPathCallbacks,
3062 kSecPolicyCheckWeakIntermediates,
3063 SecPolicyCheckWeakIntermediates);
3064 CFDictionaryAddValue(gSecPolicyLeafCallbacks,
3065 kSecPolicyCheckWeakLeaf,
3066 SecPolicyCheckWeakLeaf);
3067 CFDictionaryAddValue(gSecPolicyPathCallbacks,
3068 kSecPolicyCheckWeakRoot,
3069 SecPolicyCheckWeakRoot);
3070 }
3071
3072 /* AUDIT[securityd](done):
3073 array (ok) is a caller provided array, only its cf type has
3074 been checked.
3075 The options (ok) field ends up in policy->_options unchecked, so every access
3076 of policy->_options needs to be validated.
3077 */
3078 static SecPolicyRef SecPolicyCreateWithArray(CFArrayRef array) {
3079 SecPolicyRef policy = NULL;
3080 require_quiet(array && CFArrayGetCount(array) == 2, errOut);
3081 CFStringRef oid = (CFStringRef)CFArrayGetValueAtIndex(array, 0);
3082 require_quiet(isString(oid), errOut);
3083 CFDictionaryRef options = (CFDictionaryRef)CFArrayGetValueAtIndex(array, 1);
3084 require_quiet(isDictionary(options), errOut);
3085 policy = SecPolicyCreate(oid, options);
3086 errOut:
3087 return policy;
3088 }
3089
3090 /* AUDIT[securityd](done):
3091 value (ok) is an element in a caller provided array.
3092 */
3093 static void deserializePolicy(const void *value, void *context) {
3094 CFArrayRef policyArray = (CFArrayRef)value;
3095 if (isArray(policyArray)) {
3096 CFTypeRef deserializedPolicy = SecPolicyCreateWithArray(policyArray);
3097 if (deserializedPolicy) {
3098 CFArrayAppendValue((CFMutableArrayRef)context, deserializedPolicy);
3099 CFRelease(deserializedPolicy);
3100 }
3101 }
3102 }
3103
3104 /* AUDIT[securityd](done):
3105 serializedPolicies (ok) is a caller provided array, only its cf type has
3106 been checked.
3107 */
3108 CFArrayRef SecPolicyArrayDeserialize(CFArrayRef serializedPolicies) {
3109 CFMutableArrayRef result = NULL;
3110 require_quiet(isArray(serializedPolicies), errOut);
3111 CFIndex count = CFArrayGetCount(serializedPolicies);
3112 result = CFArrayCreateMutable(kCFAllocatorDefault, count, &kCFTypeArrayCallBacks);
3113 CFRange all_policies = { 0, count };
3114 CFArrayApplyFunction(serializedPolicies, all_policies, deserializePolicy, result);
3115 errOut:
3116 return result;
3117 }
3118
3119 // MARK: -
3120 // MARK: SecPVCRef
3121 /********************************************************
3122 ****************** SecPVCRef Functions *****************
3123 ********************************************************/
3124
3125 void SecPVCInit(SecPVCRef pvc, SecPathBuilderRef builder, CFArrayRef policies,
3126 CFAbsoluteTime verifyTime) {
3127 secdebug("alloc", "%p", pvc);
3128 // Weird logging policies crashes.
3129 //secdebug("policy", "%@", policies);
3130 pvc->builder = builder;
3131 pvc->policies = policies;
3132 if (policies)
3133 CFRetain(policies);
3134 pvc->verifyTime = verifyTime;
3135 pvc->path = NULL;
3136 pvc->details = NULL;
3137 pvc->info = NULL;
3138 pvc->valid_policy_tree = NULL;
3139 pvc->callbacks = NULL;
3140 pvc->policyIX = 0;
3141 pvc->rvcs = NULL;
3142 pvc->asyncJobCount = 0;
3143 pvc->check_revocation = false;
3144 pvc->response_required = false;
3145 pvc->optionally_ev = false;
3146 pvc->is_ev = false;
3147 pvc->result = true;
3148 }
3149
3150 static void SecPVCDeleteRVCs(SecPVCRef pvc) {
3151 secdebug("alloc", "%p", pvc);
3152 if (pvc->rvcs) {
3153 free(pvc->rvcs);
3154 pvc->rvcs = NULL;
3155 }
3156 }
3157
3158 void SecPVCDelete(SecPVCRef pvc) {
3159 secdebug("alloc", "%p", pvc);
3160 CFReleaseNull(pvc->policies);
3161 CFReleaseNull(pvc->details);
3162 CFReleaseNull(pvc->info);
3163 if (pvc->valid_policy_tree) {
3164 policy_tree_prune(&pvc->valid_policy_tree);
3165 }
3166 SecPVCDeleteRVCs(pvc);
3167 }
3168
3169 void SecPVCSetPath(SecPVCRef pvc, SecCertificatePathRef path,
3170 CF_CONSUMED CFArrayRef details) {
3171 secdebug("policy", "%@", path);
3172 if (pvc->path != path) {
3173 /* Changing path makes us clear the Revocation Verification Contexts */
3174 SecPVCDeleteRVCs(pvc);
3175 pvc->path = path;
3176 }
3177 pvc->details = details;
3178 CFReleaseNull(pvc->info);
3179 if (pvc->valid_policy_tree) {
3180 policy_tree_prune(&pvc->valid_policy_tree);
3181 }
3182 pvc->policyIX = 0;
3183 pvc->result = true;
3184 }
3185
3186 SecPolicyRef SecPVCGetPolicy(SecPVCRef pvc) {
3187 return (SecPolicyRef)CFArrayGetValueAtIndex(pvc->policies, pvc->policyIX);
3188 }
3189
3190 CFIndex SecPVCGetCertificateCount(SecPVCRef pvc) {
3191 return SecCertificatePathGetCount(pvc->path);
3192 }
3193
3194 SecCertificateRef SecPVCGetCertificateAtIndex(SecPVCRef pvc, CFIndex ix) {
3195 return SecCertificatePathGetCertificateAtIndex(pvc->path, ix);
3196 }
3197
3198 bool SecPVCIsCertificateAtIndexSelfSigned(SecPVCRef pvc, CFIndex ix) {
3199 return SecCertificatePathSelfSignedIndex(pvc->path) == ix;
3200 }
3201
3202 void SecPVCSetCheckRevocation(SecPVCRef pvc) {
3203 pvc->check_revocation = true;
3204 secdebug("ocsp", "deferred revocation checking enabled");
3205 }
3206
3207 void SecPVCSetCheckRevocationResponseRequired(SecPVCRef pvc) {
3208 pvc->response_required = true;
3209 secdebug("ocsp", "revocation response required");
3210 }
3211
3212 bool SecPVCIsAnchored(SecPVCRef pvc) {
3213 return SecCertificatePathIsAnchored(pvc->path);
3214 }
3215
3216 CFAbsoluteTime SecPVCGetVerifyTime(SecPVCRef pvc) {
3217 return pvc->verifyTime;
3218 }
3219
3220 /* AUDIT[securityd](done):
3221 policy->_options is a caller provided dictionary, only its cf type has
3222 been checked.
3223 */
3224 bool SecPVCSetResultForced(SecPVCRef pvc,
3225 CFStringRef key, CFIndex ix, CFTypeRef result, bool force) {
3226
3227 secdebug("policy", "cert[%d]: %@ =(%s)[%s]> %@", (int) ix, key,
3228 (pvc->callbacks == gSecPolicyLeafCallbacks ? "leaf"
3229 : (pvc->callbacks == gSecPolicyPathCallbacks ? "path"
3230 : "custom")),
3231 (force ? "force" : ""), result);
3232
3233 /* If this is not something the current policy cares about ignore
3234 this error and return true so our caller continues evaluation. */
3235 if (!force) {
3236 /* @@@ The right long term fix might be to check if none of the passed
3237 in policies contain this key, since not all checks are run for all
3238 policies. */
3239 SecPolicyRef policy = SecPVCGetPolicy(pvc);
3240 if (policy && !CFDictionaryContainsKey(policy->_options, key))
3241 return true;
3242 }
3243
3244 /* @@@ Check to see if the SecTrustSettings for the certificate in question
3245 tell us to ignore this error. */
3246 pvc->result = false;
3247 if (!pvc->details)
3248 return false;
3249
3250 CFMutableDictionaryRef detail =
3251 (CFMutableDictionaryRef)CFArrayGetValueAtIndex(pvc->details, ix);
3252
3253 /* Perhaps detail should have an array of results per key? As it stands
3254 in the case of multiple policy failures the last failure stands. */
3255 CFDictionarySetValue(detail, key, result);
3256
3257 return true;
3258 }
3259
3260 bool SecPVCSetResult(SecPVCRef pvc,
3261 CFStringRef key, CFIndex ix, CFTypeRef result) {
3262 return SecPVCSetResultForced(pvc, key, ix, result, false);
3263 }
3264
3265 /* AUDIT[securityd](done):
3266 key(ok) is a caller provided.
3267 value(ok, unused) is a caller provided.
3268 */
3269 static void SecPVCValidateKey(const void *key, const void *value,
3270 void *context) {
3271 SecPVCRef pvc = (SecPVCRef)context;
3272
3273 /* If our caller doesn't want full details and we failed earlier there is
3274 no point in doing additional checks. */
3275 if (!pvc->result && !pvc->details)
3276 return;
3277
3278 SecPolicyCheckFunction fcn = (SecPolicyCheckFunction)
3279 CFDictionaryGetValue(pvc->callbacks, key);
3280
3281 if (!fcn) {
3282 #if 0
3283 /* Why not to have optional policy checks rant:
3284 Not all keys are in all dictionaries anymore, so why not make checks
3285 optional? This way a client can ask for something and the server will
3286 do a best effort based on the supported flags. It works since they are
3287 synchronized now, but we need some debug checking here for now. */
3288 pvc->result = false;
3289 #endif
3290 if (pvc->callbacks == gSecPolicyLeafCallbacks) {
3291 if (!CFDictionaryContainsKey(gSecPolicyPathCallbacks, key)) {
3292 pvc->result = false;
3293 }
3294 } else if (pvc->callbacks == gSecPolicyPathCallbacks) {
3295 if (!CFDictionaryContainsKey(gSecPolicyLeafCallbacks, key)) {
3296 pvc->result = false;
3297 }
3298 } else {
3299 /* Non standard validation phase, nothing is optional. */
3300 pvc->result = false;
3301 }
3302 return;
3303 }
3304
3305 fcn(pvc, (CFStringRef)key);
3306 }
3307
3308 /* AUDIT[securityd](done):
3309 policy->_options is a caller provided dictionary, only its cf type has
3310 been checked.
3311 */
3312 bool SecPVCLeafChecks(SecPVCRef pvc) {
3313 pvc->result = true;
3314 CFArrayRef policies = pvc->policies;
3315 CFIndex ix, count = CFArrayGetCount(policies);
3316 for (ix = 0; ix < count; ++ix) {
3317 SecPolicyRef policy = (SecPolicyRef)CFArrayGetValueAtIndex(policies, ix);
3318 pvc->policyIX = ix;
3319 /* Validate all keys for all policies. */
3320 pvc->callbacks = gSecPolicyLeafCallbacks;
3321 CFDictionaryApplyFunction(policy->_options, SecPVCValidateKey, pvc);
3322 if (!pvc->result && !pvc->details)
3323 return pvc->result;
3324 }
3325
3326 return pvc->result;
3327 }
3328
3329 bool SecPVCParentCertificateChecks(SecPVCRef pvc, CFIndex ix) {
3330 /* Check stuff common to intermediate and anchors. */
3331 CFAbsoluteTime verifyTime = SecPVCGetVerifyTime(pvc);
3332 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, ix);
3333 bool is_anchor = (ix == SecPVCGetCertificateCount(pvc) - 1
3334 && SecPVCIsAnchored(pvc));
3335 if (!SecCertificateIsValid(cert, verifyTime)) {
3336 /* Certificate has expired. */
3337 if (!SecPVCSetResult(pvc, is_anchor ? kSecPolicyCheckValidRoot
3338 : kSecPolicyCheckValidIntermediates, ix, kCFBooleanFalse))
3339 goto errOut;
3340 }
3341
3342 if (SecCertificateIsWeak(cert)) {
3343 /* Certificate uses weak key. */
3344 if (!SecPVCSetResult(pvc, is_anchor ? kSecPolicyCheckWeakRoot
3345 : kSecPolicyCheckWeakIntermediates, ix, kCFBooleanFalse))
3346 goto errOut;
3347 }
3348
3349 if (is_anchor) {
3350 /* Perform anchor specific checks. */
3351 /* Don't think we have any of these. */
3352 } else {
3353 /* Perform intermediate specific checks. */
3354
3355 /* (k) */
3356 const SecCEBasicConstraints *bc =
3357 SecCertificateGetBasicConstraints(cert);
3358 if (!bc || !bc->isCA) {
3359 /* Basic constraints not present or not marked as isCA, illegal. */
3360 if (!SecPVCSetResultForced(pvc, kSecPolicyCheckBasicContraints,
3361 ix, kCFBooleanFalse, true))
3362 goto errOut;
3363 }
3364 /* Consider adding (l) max_path_length checking here. */
3365
3366 /* (n) If a key usage extension is present, verify that the keyCertSign bit is set. */
3367 SecKeyUsage keyUsage = SecCertificateGetKeyUsage(cert);
3368 if (keyUsage && !(keyUsage & kSecKeyUsageKeyCertSign)) {
3369 if (!SecPVCSetResultForced(pvc, kSecPolicyCheckKeyUsage,
3370 ix, kCFBooleanFalse, true))
3371 goto errOut;
3372 }
3373 }
3374
3375 errOut:
3376 return pvc->result;
3377 }
3378
3379 bool SecPVCBlackListedKeyChecks(SecPVCRef pvc, CFIndex ix) {
3380 /* Check stuff common to intermediate and anchors. */
3381
3382 SecOTAPKIRef otapkiRef = SecOTAPKICopyCurrentOTAPKIRef();
3383 if (NULL != otapkiRef)
3384 {
3385 CFSetRef blackListedKeys = SecOTAPKICopyBlackListSet(otapkiRef);
3386 CFRelease(otapkiRef);
3387 if (NULL != blackListedKeys)
3388 {
3389 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, ix);
3390 bool is_anchor = (ix == SecPVCGetCertificateCount(pvc) - 1
3391 && SecPVCIsAnchored(pvc));
3392 if (!is_anchor) {
3393 /* Check for blacklisted intermediates keys. */
3394 CFDataRef dgst = SecCertificateCopyPublicKeySHA1Digest(cert);
3395 if (dgst) {
3396 /* Check dgst against blacklist. */
3397 if (CFSetContainsValue(blackListedKeys, dgst)) {
3398 SecPVCSetResultForced(pvc, kSecPolicyCheckBlackListedKey,
3399 ix, kCFBooleanFalse, true);
3400 }
3401 CFRelease(dgst);
3402 }
3403 }
3404 CFRelease(blackListedKeys);
3405 return pvc->result;
3406 }
3407 }
3408 // Assume OK
3409 return true;
3410 }
3411
3412 bool SecPVCGrayListedKeyChecks(SecPVCRef pvc, CFIndex ix)
3413 {
3414 /* Check stuff common to intermediate and anchors. */
3415 SecOTAPKIRef otapkiRef = SecOTAPKICopyCurrentOTAPKIRef();
3416 if (NULL != otapkiRef)
3417 {
3418 CFSetRef grayListKeys = SecOTAPKICopyGrayList(otapkiRef);
3419 CFRelease(otapkiRef);
3420 if (NULL != grayListKeys)
3421 {
3422 SecCertificateRef cert = SecPVCGetCertificateAtIndex(pvc, ix);
3423 bool is_anchor = (ix == SecPVCGetCertificateCount(pvc) - 1
3424 && SecPVCIsAnchored(pvc));
3425 if (!is_anchor) {
3426 /* Check for gray listed intermediates keys. */
3427 CFDataRef dgst = SecCertificateCopyPublicKeySHA1Digest(cert);
3428 if (dgst) {
3429 /* Check dgst against gray list. */
3430 if (CFSetContainsValue(grayListKeys, dgst)) {
3431 SecPVCSetResultForced(pvc, kSecPolicyCheckGrayListedKey,
3432 ix, kCFBooleanFalse, true);
3433 }
3434 CFRelease(dgst);
3435 }
3436 }
3437 CFRelease(grayListKeys);
3438 return pvc->result;
3439 }
3440 }
3441 // Assume ok
3442 return true;
3443 }
3444
3445 /* AUDIT[securityd](done):
3446 policy->_options is a caller provided dictionary, only its cf type has
3447 been checked.
3448 */
3449 bool SecPVCPathChecks(SecPVCRef pvc) {
3450 secdebug("policy", "begin path: %@", pvc->path);
3451 bool completed = true;
3452 /* This needs to be initialized before we call any function that might call
3453 SecPVCSetResultForced(). */
3454 pvc->policyIX = 0;
3455 SecPolicyCheckIdLinkage(pvc, kSecPolicyCheckIdLinkage);
3456 if (pvc->result || pvc->details) {
3457 SecPolicyCheckBasicCertificateProcessing(pvc,
3458 kSecPolicyCheckBasicCertificateProcessing);
3459 }
3460
3461 CFArrayRef policies = pvc->policies;
3462 CFIndex count = CFArrayGetCount(policies);
3463 for (; pvc->policyIX < count; ++pvc->policyIX) {
3464 /* Validate all keys for all policies. */
3465 pvc->callbacks = gSecPolicyPathCallbacks;
3466 SecPolicyRef policy = SecPVCGetPolicy(pvc);
3467 CFDictionaryApplyFunction(policy->_options, SecPVCValidateKey, pvc);
3468 if (!pvc->result && !pvc->details)
3469 return completed;
3470 }
3471
3472 /* Check the things we can't check statically for the certificate path. */
3473 /* Critical Extensions, chainLength. */
3474
3475 /* Policy tests. */
3476 pvc->is_ev = false;
3477 if ((pvc->result || pvc->details) && pvc->optionally_ev) {
3478 bool pre_ev_check_result = pvc->result;
3479 SecPolicyCheckEV(pvc, kSecPolicyCheckExtendedValidation);
3480 pvc->is_ev = pvc->result;
3481 /* If ev checking failed, we still want to accept this chain
3482 as a non EV one, if it was valid as such. */
3483 pvc->result = pre_ev_check_result;
3484 }
3485 /* Check revocation only if the chain is valid so far. The revocation will
3486 only fetch OCSP response over the network if the client asked for revocation
3487 check explicitly or is_ev is true. */
3488 if (pvc->result) {
3489 completed = SecPVCCheckRevocation(pvc);
3490 }
3491
3492 /* Check for CT */
3493 if (pvc->result || pvc->details) {
3494 /* This call will set the value of pvc->is_ct, but won't change the result (pvc->result) */
3495 SecPolicyCheckCT(pvc, kSecPolicyCheckCertificateTransparency);
3496 }
3497
3498
3499 //errOut:
3500 secdebug("policy", "end %strusted completed: %d path: %@",
3501 (pvc->result ? "" : "not "), completed, pvc->path);
3502 return completed;
3503 }
3504
3505 /* This function returns 0 to indicate revocation checking was not completed
3506 for this certificate chain, otherwise return to date at which the first
3507 piece of revocation checking info we used expires. */
3508 CFAbsoluteTime SecPVCGetEarliestNextUpdate(SecPVCRef pvc) {
3509 CFIndex certIX, certCount = SecPVCGetCertificateCount(pvc);
3510 CFAbsoluteTime enu = 0;
3511 if (certCount <= 1 || !pvc->rvcs) {
3512 return enu;
3513 }
3514 certCount--;
3515
3516 for (certIX = 0; certIX < certCount; ++certIX) {
3517 SecRVCRef rvc = &((SecRVCRef)pvc->rvcs)[certIX];
3518 if (rvc->nextUpdate == 0) {
3519 if (certIX > 0) {
3520 /* We allow for CA certs to not be revocation checked if they
3521 have no ocspResponders to check against, but the leaf
3522 must be checked in order for us to claim we did revocation
3523 checking. */
3524 SecCertificateRef cert =
3525 SecPVCGetCertificateAtIndex(rvc->pvc, rvc->certIX);
3526 CFArrayRef ocspResponders = SecCertificateGetOCSPResponders(cert);
3527 if (!ocspResponders || CFArrayGetCount(ocspResponders) == 0) {
3528 /* We can't check this cert so we don't consider it a soft
3529 failure that we didn't. Ideally we should support crl
3530 checking and remove this workaround, since that more
3531 strict. */
3532 continue;
3533 }
3534 }
3535 secdebug("ocsp", "revocation checking soft failure for cert: %ld",
3536 certIX);
3537 enu = rvc->nextUpdate;
3538 break;
3539 }
3540 if (enu == 0 || rvc->nextUpdate < enu) {
3541 enu = rvc->nextUpdate;
3542 }
3543 #if 0
3544 /* Perhaps we don't want to do this since some policies might
3545 ignore the certificate expiration but still use revocation
3546 checking. */
3547
3548 /* Earliest certificate expiration date. */
3549 SecCertificateRef cert = SecPVCGetCertificateAtIndex(rvc->pvc, rvc->certIX);
3550 CFAbsoluteTime nva = SecCertificateNotValidAfter(cert);
3551 if (nva && (enu == 0 || nva < enu)
3552 enu = nva;
3553 #endif
3554 }
3555
3556 secdebug("ocsp", "revocation valid until: %lg", enu);
3557 return enu;
3558 }