]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_keychain/lib/TrustAdditions.cpp
Security-59306.101.1.tar.gz
[apple/security.git] / OSX / libsecurity_keychain / lib / TrustAdditions.cpp
1 /*
2 * Copyright (c) 2002-2009,2011-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 // TrustAdditions.cpp
26 //
27 #include "TrustAdditions.h"
28 #include "TrustKeychains.h"
29 #include "SecBridge.h"
30 #include <security_keychain/SecCFTypes.h>
31 #include <security_keychain/Globals.h>
32 #include <security_keychain/Certificate.h>
33 #include <security_keychain/Item.h>
34 #include <security_keychain/KCCursor.h>
35 #include <security_keychain/KCUtilities.h>
36
37 #include <sys/stat.h>
38 #include <sys/file.h>
39 #include <sys/unistd.h>
40 #include <string>
41 #include <AvailabilityMacros.h>
42 #include <CoreFoundation/CoreFoundation.h>
43 #include <CommonCrypto/CommonDigest.h>
44 #include <Security/SecBase.h>
45 #include <Security/Security.h>
46 #include <Security/SecCertificatePriv.h>
47 #include <Security/cssmtype.h>
48 #include <Security/cssmapplePriv.h> // for CSSM_APPLE_TP_OCSP_OPTIONS, CSSM_APPLE_TP_OCSP_OPT_FLAGS
49
50 #include <Security/SecTrustPriv.h>
51 #include <Security/SecTrustSettings.h>
52 #include <Security/SecTrustSettingsPriv.h>
53
54 //
55 // Macros
56 //
57 #define BEGIN_SECAPI_INTERNAL_CALL \
58 try {
59 #define END_SECAPI_INTERNAL_CALL \
60 } /* status is only set on error */ \
61 catch (const MacOSError &err) { status=err.osStatus(); } \
62 catch (const CommonError &err) { status=SecKeychainErrFromOSStatus(err.osStatus()); } \
63 catch (const std::bad_alloc &) { status=errSecAllocate; } \
64 catch (...) { status=errSecInternalComponent; }
65
66 #ifdef NDEBUG
67 /* this actually compiles to nothing */
68 #define trustDebug(args...) secinfo("trust", ## args)
69 #else
70 #define trustDebug(args...) printf(args)
71 #endif
72
73 //
74 // Static constants
75 //
76 static const char *EV_ROOTS_PLIST_SYSTEM_PATH = "/System/Library/Keychains/EVRoots.plist";
77 static const char *SYSTEM_ROOTS_PLIST_SYSTEM_PATH = "/System/Library/Keychains/SystemRootCertificates.keychain";
78 static const char *X509ANCHORS_SYSTEM_PATH = "/System/Library/Keychains/X509Anchors";
79
80 //
81 // Static functions
82 //
83 static CFArrayRef CF_RETURNS_RETAINED _allowedRootCertificatesForOidString(CFStringRef oidString);
84 static CSSM_DATA_PTR _copyFieldDataForOid(CSSM_OID_PTR oid, CSSM_DATA_PTR cert, CSSM_CL_HANDLE clHandle);
85 static CFStringRef CF_RETURNS_RETAINED _decimalStringForOid(CSSM_OID_PTR oid);
86 static CFDictionaryRef CF_RETURNS_RETAINED _evCAOidDict();
87 static void _freeFieldData(CSSM_DATA_PTR value, CSSM_OID_PTR oid, CSSM_CL_HANDLE clHandle);
88 static CFStringRef CF_RETURNS_RETAINED _oidStringForCertificatePolicies(const CE_CertPolicies *certPolicies);
89 static SecCertificateRef _rootCertificateWithSubjectOfCertificate(SecCertificateRef certificate);
90 static SecCertificateRef _rootCertificateWithSubjectKeyIDOfCertificate(SecCertificateRef certificate);
91
92 // utility function to safely release (and clear) the given CFTypeRef variable.
93 //
94 static void SafeCFRelease(void * CF_CONSUMED cfTypeRefPtr)
95 {
96 CFTypeRef *obj = (CFTypeRef *)cfTypeRefPtr;
97 if (obj && *obj) {
98 CFRelease(*obj);
99 *obj = NULL;
100 }
101 }
102
103 // utility function to create a CFDataRef from the contents of the specified file;
104 // caller must release
105 //
106 static CFDataRef CF_RETURNS_RETAINED dataWithContentsOfFile(const char *fileName)
107 {
108 int rtn;
109 int fd;
110 struct stat sb;
111 size_t fileSize;
112 UInt8 *fileData = NULL;
113 CFDataRef outCFData = NULL;
114
115 fd = open(fileName, O_RDONLY, 0);
116 if(fd < 0)
117 return NULL;
118
119 rtn = fstat(fd, &sb);
120 if(rtn)
121 goto errOut;
122
123 fileSize = (size_t)sb.st_size;
124 fileData = (UInt8 *) malloc(fileSize);
125 if(fileData == NULL)
126 goto errOut;
127
128 rtn = (int)lseek(fd, 0, SEEK_SET);
129 if(rtn < 0)
130 goto errOut;
131
132 rtn = (int)read(fd, fileData, fileSize);
133 if(rtn != (int)fileSize) {
134 rtn = EIO;
135 } else {
136 rtn = 0;
137 outCFData = CFDataCreate(NULL, fileData, fileSize);
138 }
139 errOut:
140 close(fd);
141 if (fileData) {
142 free(fileData);
143 }
144 return outCFData;
145 }
146
147 // returns a SecKeychainRef for the system root certificate store; caller must release
148 //
149 static SecKeychainRef systemRootStore()
150 {
151 SecKeychainStatus keychainStatus = 0;
152 SecKeychainRef systemRoots = NULL;
153 OSStatus status = errSecSuccess;
154 // note: Sec* APIs are not re-entrant due to the API lock
155 // status = SecKeychainOpen(SYSTEM_ROOTS_PLIST_SYSTEM_PATH, &systemRoots);
156 BEGIN_SECAPI_INTERNAL_CALL
157 systemRoots=globals().storageManager.make(SYSTEM_ROOTS_PLIST_SYSTEM_PATH, false)->handle();
158 END_SECAPI_INTERNAL_CALL
159
160 // SecKeychainOpen will return errSecSuccess even if the file didn't exist on disk.
161 // We need to do a further check using SecKeychainGetStatus().
162 if (!status && systemRoots) {
163 // note: Sec* APIs are not re-entrant due to the API lock
164 // status = SecKeychainGetStatus(systemRoots, &keychainStatus);
165 BEGIN_SECAPI_INTERNAL_CALL
166 keychainStatus=(SecKeychainStatus)Keychain::optional(systemRoots)->status();
167 END_SECAPI_INTERNAL_CALL
168 }
169 if (status || !systemRoots) {
170 // SystemRootCertificates.keychain can't be opened; look in X509Anchors instead.
171 SafeCFRelease(&systemRoots);
172 // note: Sec* APIs are not re-entrant due to the API lock
173 // status = SecKeychainOpen(X509ANCHORS_SYSTEM_PATH, &systemRoots);
174 BEGIN_SECAPI_INTERNAL_CALL
175 systemRoots=globals().storageManager.make(X509ANCHORS_SYSTEM_PATH, false)->handle();
176 END_SECAPI_INTERNAL_CALL
177 // SecKeychainOpen will return errSecSuccess even if the file didn't exist on disk.
178 // We need to do a further check using SecKeychainGetStatus().
179 if (!status && systemRoots) {
180 // note: Sec* APIs are not re-entrant due to the API lock
181 // status = SecKeychainGetStatus(systemRoots, &keychainStatus);
182 BEGIN_SECAPI_INTERNAL_CALL
183 keychainStatus=(SecKeychainStatus)Keychain::optional(systemRoots)->status();
184 END_SECAPI_INTERNAL_CALL
185 }
186 }
187 if (status || !systemRoots) {
188 // Cannot get root certificates if there is no trusted system root certificate store.
189 SafeCFRelease(&systemRoots);
190 return NULL;
191 }
192 return systemRoots;
193 }
194
195 // returns a CFDictionaryRef created from the specified XML plist file; caller must release
196 //
197 static CFDictionaryRef CF_RETURNS_RETAINED dictionaryWithContentsOfPlistFile(const char *fileName)
198 {
199 CFDictionaryRef resultDict = NULL;
200 CFDataRef fileData = dataWithContentsOfFile(fileName);
201 if (fileData) {
202 CFPropertyListRef xmlPlist = CFPropertyListCreateFromXMLData(NULL, fileData, kCFPropertyListImmutable, NULL);
203 if (xmlPlist && CFGetTypeID(xmlPlist) == CFDictionaryGetTypeID()) {
204 resultDict = (CFDictionaryRef)xmlPlist;
205 } else {
206 SafeCFRelease(&xmlPlist);
207 }
208 SafeCFRelease(&fileData);
209 }
210 return resultDict;
211 }
212
213 // returns the Organization component of the given certificate's subject name,
214 // or nil if that component could not be found. Caller must release the string.
215 //
216 static CFStringRef organizationNameForCertificate(SecCertificateRef certificate)
217 {
218 CFStringRef organizationName = nil;
219 OSStatus status = errSecSuccess;
220
221 #if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4
222 CSSM_OID_PTR oidPtr = (CSSM_OID_PTR) &CSSMOID_OrganizationName;
223 // note: Sec* APIs are not re-entrant due to the API lock
224 // status = SecCertificateCopySubjectComponent(certificate, oidPtr, &organizationName);
225 BEGIN_SECAPI_INTERNAL_CALL
226 organizationName = Certificate::required(certificate)->distinguishedName(&CSSMOID_X509V1SubjectNameCStruct, oidPtr);
227 END_SECAPI_INTERNAL_CALL
228 if (status) {
229 return (CFStringRef)NULL;
230 }
231 #else
232 // SecCertificateCopySubjectComponent() doesn't exist on Tiger, so we have
233 // to go get the CSSMOID_OrganizationName the hard way, ourselves.
234 CSSM_DATA_PTR *fieldValues = NULL;
235 // note: Sec* APIs are not re-entrant due to the API lock
236 // status = SecCertificateCopyFieldValues(certificate, &CSSMOID_X509V1SubjectNameCStruct, &fieldValues);
237 BEGIN_SECAPI_INTERNAL_CALL
238 fieldValues = Certificate::required(certificate)->copyFieldValues(&CSSMOID_X509V1SubjectNameCStruct);
239 END_SECAPI_INTERNAL_CALL
240 if (*fieldValues == NULL) {
241 return (CFStringRef)NULL;
242 }
243 if (status || (*fieldValues)->Length == 0 || (*fieldValues)->Data == NULL) {
244 // note: Sec* APIs are not re-entrant due to the API lock
245 // status = SecCertificateReleaseFieldValues(certificate, &CSSMOID_X509V1SubjectNameCStruct, fieldValues);
246 BEGIN_SECAPI_INTERNAL_CALL
247 Certificate::required(certificate)->releaseFieldValues(&CSSMOID_X509V1SubjectNameCStruct, fieldValues);
248 END_SECAPI_INTERNAL_CALL
249 return (CFStringRef)NULL;
250 }
251
252 CSSM_X509_NAME_PTR x509Name = (CSSM_X509_NAME_PTR)(*fieldValues)->Data;
253
254 // Iterate over all the relative distinguished name (RDN) entries...
255 unsigned rdnIndex = 0;
256 bool foundIt = FALSE;
257 for (rdnIndex = 0; rdnIndex < x509Name->numberOfRDNs; rdnIndex++) {
258 CSSM_X509_RDN *rdnPtr = x509Name->RelativeDistinguishedName + rdnIndex;
259
260 // And then iterate over the attribute-value pairs of each RDN, looking for a CSSMOID_OrganizationName.
261 unsigned pairIndex;
262 for (pairIndex = 0; pairIndex < rdnPtr->numberOfPairs; pairIndex++) {
263 CSSM_X509_TYPE_VALUE_PAIR *pair = rdnPtr->AttributeTypeAndValue + pairIndex;
264
265 // If this pair isn't the organization name, move on to check the next one.
266 if (!oidsAreEqual(&pair->type, &CSSMOID_OrganizationName))
267 continue;
268
269 // We've found the organization name. Convert value to a string (eg, "Apple Inc.")
270 // Note: there can be more than one organization name in any given CSSM_X509_RDN.
271 // In practice, it's OK to use the first one. In future, if we have a means for
272 // displaying more than one name, this would be where they should be collected
273 // into an array.
274 switch (pair->valueType) {
275 case BER_TAG_PKIX_UTF8_STRING:
276 case BER_TAG_PKIX_UNIVERSAL_STRING:
277 case BER_TAG_GENERAL_STRING:
278 organizationName = CFStringCreateWithBytes(NULL, pair->value.Data, pair->value.Length, kCFStringEncodingUTF8, FALSE);
279 break;
280 case BER_TAG_PRINTABLE_STRING:
281 case BER_TAG_IA5_STRING:
282 organizationName = CFStringCreateWithBytes(NULL, pair->value.Data, pair->value.Length, kCFStringEncodingASCII, FALSE);
283 break;
284 case BER_TAG_T61_STRING:
285 case BER_TAG_VIDEOTEX_STRING:
286 case BER_TAG_ISO646_STRING:
287 organizationName = CFStringCreateWithBytes(NULL, pair->value.Data, pair->value.Length, kCFStringEncodingUTF8, FALSE);
288 // If the data cannot be represented as a UTF-8 string, fall back to ISO Latin 1
289 if (!organizationName) {
290 organizationName = CFStringCreateWithBytes(NULL, pair->value.Data, pair->value.Length, kCFStringEncodingISOLatin1, FALSE);
291 }
292 break;
293 case BER_TAG_PKIX_BMP_STRING:
294 organizationName = CFStringCreateWithBytes(NULL, pair->value.Data, pair->value.Length, kCFStringEncodingUnicode, FALSE);
295 break;
296 default:
297 break;
298 }
299
300 // If we found the organization name, there's no need to keep looping.
301 if (organizationName) {
302 foundIt = TRUE;
303 break;
304 }
305 }
306 if (foundIt)
307 break;
308 }
309 // note: Sec* APIs are not re-entrant due to the API lock
310 // status = SecCertificateReleaseFieldValues(certificate, &CSSMOID_X509V1SubjectNameCStruct, fieldValues);
311 BEGIN_SECAPI_INTERNAL_CALL
312 Certificate::required(certificate)->releaseFieldValues(&CSSMOID_X509V1SubjectNameCStruct, fieldValues);
313 END_SECAPI_INTERNAL_CALL
314 #endif
315 return organizationName;
316 }
317
318 #if !defined(NDEBUG)
319 void showCertSKID(const void *value, void *context);
320 #endif
321
322 static ModuleNexus<Mutex> gPotentialEVChainWithCertificatesMutex;
323
324 // returns a CFArrayRef of SecCertificateRef instances; caller must release the returned array
325 //
326 CFArrayRef potentialEVChainWithCertificates(CFArrayRef certificates)
327 {
328 StLock<Mutex> _(gPotentialEVChainWithCertificatesMutex());
329
330 // Given a partial certificate chain (which may or may not include the root,
331 // and does not have a guaranteed order except the first item is the leaf),
332 // examine intermediate certificates to see if they are cross-certified (i.e.
333 // have the same subject and public key as a trusted root); if so, remove the
334 // intermediate from the returned certificate array.
335
336 CFIndex chainIndex, chainLen = (certificates) ? CFArrayGetCount(certificates) : 0;
337 secinfo("trusteval", "potentialEVChainWithCertificates: chainLen: %ld", chainLen);
338 if (chainLen < 2) {
339 if (certificates) {
340 CFRetain(certificates);
341 }
342 return certificates;
343 }
344
345 CFMutableArrayRef certArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
346 for (chainIndex = 0; chainIndex < chainLen; chainIndex++) {
347 SecCertificateRef aCert = (SecCertificateRef) CFArrayGetValueAtIndex(certificates, chainIndex);
348 SecCertificateRef replacementCert = NULL;
349 secinfo("trusteval", "potentialEVChainWithCertificates: examining chainIndex: %ld", chainIndex);
350 if (chainIndex > 0) {
351 // if this is not the leaf, then look for a possible replacement root to end the chain
352 // Try lookup using Subject Key ID first
353 replacementCert = _rootCertificateWithSubjectKeyIDOfCertificate(aCert);
354 if (!replacementCert)
355 {
356 secinfo("trusteval", " not found using SKID, try by subject");
357 replacementCert = _rootCertificateWithSubjectOfCertificate(aCert);
358 }
359 }
360 if (!replacementCert) {
361 secinfo("trusteval", " No replacement found using SKID or subject; keeping original intermediate");
362 CFArrayAppendValue(certArray, aCert);
363 }
364 SafeCFRelease(&replacementCert);
365 }
366 secinfo("trusteval", "potentialEVChainWithCertificates: exit: new chainLen: %ld", CFArrayGetCount(certArray));
367 #if !defined(NDEBUG)
368 CFArrayApplyFunction(certArray, CFRangeMake(0, CFArrayGetCount(certArray)), showCertSKID, NULL);
369 #endif
370
371 return certArray;
372 }
373
374 // returns a reference to a root certificate, if one can be found in the
375 // system root store whose subject name and public key are identical to
376 // that of the provided certificate, otherwise returns nil.
377 //
378 static SecCertificateRef _rootCertificateWithSubjectOfCertificate(SecCertificateRef certificate)
379 {
380 if (!certificate)
381 return NULL;
382
383 StLock<Mutex> _(SecTrustKeychainsGetMutex());
384
385 // get data+length for the provided certificate
386 CSSM_CL_HANDLE clHandle = 0;
387 CSSM_DATA certData = { 0, NULL };
388 OSStatus status = errSecSuccess;
389 // note: Sec* APIs are not re-entrant due to the API lock
390 // status = SecCertificateGetCLHandle(certificate, &clHandle);
391 BEGIN_SECAPI_INTERNAL_CALL
392 clHandle = Certificate::required(certificate)->clHandle();
393 END_SECAPI_INTERNAL_CALL
394 if (status)
395 return NULL;
396 // note: Sec* APIs are not re-entrant due to the API lock
397 // status = SecCertificateGetData(certificate, &certData);
398 BEGIN_SECAPI_INTERNAL_CALL
399 certData = Certificate::required(certificate)->data();
400 END_SECAPI_INTERNAL_CALL
401 if (status)
402 return NULL;
403
404 // get system roots keychain reference
405 SecKeychainRef systemRoots = systemRootStore();
406 if (!systemRoots)
407 return NULL;
408
409 // copy (normalized) subject for the provided certificate
410 const CSSM_OID_PTR oidPtr = (const CSSM_OID_PTR) &CSSMOID_X509V1SubjectName;
411 const CSSM_DATA_PTR subjectDataPtr = _copyFieldDataForOid(oidPtr, &certData, clHandle);
412 if (!subjectDataPtr)
413 return NULL;
414
415 // copy public key for the provided certificate
416 SecKeyRef keyRef = NULL;
417 SecCertificateRef resultCert = NULL;
418 // note: Sec* APIs are not re-entrant due to the API lock
419 BEGIN_SECAPI_INTERNAL_CALL
420 keyRef = Certificate::required(certificate)->publicKey()->handle();
421 END_SECAPI_INTERNAL_CALL
422 if (!status) {
423 const CSSM_KEY *cssmKey = NULL;
424 // note: Sec* APIs are not re-entrant due to the API lock
425 // status = SecKeyGetCSSMKey(keyRef, &cssmKey);
426 BEGIN_SECAPI_INTERNAL_CALL
427 cssmKey = KeyItem::required(keyRef)->key();
428 END_SECAPI_INTERNAL_CALL
429 if (!status) {
430 // get SHA-1 hash of the public key
431 uint8 buf[CC_SHA1_DIGEST_LENGTH];
432 CSSM_DATA digest = { sizeof(buf), buf };
433 if (!cssmKey || !cssmKey->KeyData.Data || !cssmKey->KeyData.Length) {
434 status = errSecParam;
435 } else {
436 CC_SHA1(cssmKey->KeyData.Data, (CC_LONG)cssmKey->KeyData.Length, buf);
437 }
438 if (!status) {
439 // set up attribute vector (each attribute consists of {tag, length, pointer})
440 // we want to match on the public key hash and the normalized subject name
441 // as well as ensure that the issuer matches the subject
442 SecKeychainAttribute attrs[] = {
443 { kSecPublicKeyHashItemAttr, (UInt32)digest.Length, (void *)digest.Data },
444 { kSecSubjectItemAttr, (UInt32)subjectDataPtr->Length, (void *)subjectDataPtr->Data },
445 { kSecIssuerItemAttr, (UInt32)subjectDataPtr->Length, (void *)subjectDataPtr->Data }
446 };
447 const SecKeychainAttributeList attributes = { sizeof(attrs) / sizeof(attrs[0]), attrs };
448 SecKeychainSearchRef searchRef = NULL;
449 // note: Sec* APIs are not re-entrant due to the API lock
450 // status = SecKeychainSearchCreateFromAttributes(systemRoots, kSecCertificateItemClass, &attributes, &searchRef);
451 BEGIN_SECAPI_INTERNAL_CALL
452 StorageManager::KeychainList keychains;
453 globals().storageManager.optionalSearchList(systemRoots, keychains);
454 KCCursor cursor(keychains, kSecCertificateItemClass, &attributes);
455 searchRef = cursor->handle();
456 END_SECAPI_INTERNAL_CALL
457 if (!status && searchRef) {
458 SecKeychainItemRef certRef = nil;
459 // note: Sec* APIs are not re-entrant due to the API lock
460 // status = SecKeychainSearchCopyNext(searchRef, &certRef); // only need the first one that matches
461 BEGIN_SECAPI_INTERNAL_CALL
462 Item item;
463 if (!KCCursorImpl::required(searchRef)->next(item)) {
464 status=errSecItemNotFound;
465 } else {
466 certRef=item->handle();
467 }
468 END_SECAPI_INTERNAL_CALL
469 if (!status)
470 resultCert = (SecCertificateRef)certRef; // caller must release
471 SafeCFRelease(&searchRef);
472 }
473 }
474 }
475 }
476 _freeFieldData(subjectDataPtr, oidPtr, clHandle);
477 SafeCFRelease(&keyRef);
478 SafeCFRelease(&systemRoots);
479
480 return resultCert;
481 }
482
483
484 #if !defined(NDEBUG)
485 static void logSKID(const char *msg, const CssmData &subjectKeyID)
486 {
487 const unsigned char *px = (const unsigned char *)subjectKeyID.data();
488 char buffer[256]={0,};
489 char bytes[16];
490 if (px && msg)
491 {
492 strcpy(buffer, msg);
493 for (unsigned int ix=0; ix<20; ix++)
494 {
495 sprintf(bytes, "%02X", px[ix]);
496 strcat(buffer, bytes);
497 }
498 secinfo("trusteval", " SKID: %s",buffer);
499 }
500 }
501
502 void showCertSKID(const void *value, void *context)
503 {
504 SecCertificateRef certificate = (SecCertificateRef)value;
505 OSStatus status = errSecSuccess;
506 BEGIN_SECAPI_INTERNAL_CALL
507 const CssmData &subjectKeyID = Certificate::required(certificate)->subjectKeyIdentifier();
508 logSKID("subjectKeyID: ", subjectKeyID);
509 END_SECAPI_INTERNAL_CALL
510 }
511 #endif
512
513 // returns a reference to a root certificate, if one can be found in the
514 // system root store whose subject key ID are identical to
515 // that of the provided certificate, otherwise returns nil.
516 //
517 static SecCertificateRef _rootCertificateWithSubjectKeyIDOfCertificate(SecCertificateRef certificate)
518 {
519 SecCertificateRef resultCert = NULL;
520 OSStatus status = errSecSuccess;
521
522 if (!certificate)
523 return NULL;
524
525 StLock<Mutex> _(SecTrustKeychainsGetMutex());
526
527 // get system roots keychain reference
528 SecKeychainRef systemRoots = systemRootStore();
529 if (!systemRoots)
530 return NULL;
531
532 StorageManager::KeychainList keychains;
533 globals().storageManager.optionalSearchList(systemRoots, keychains);
534
535 BEGIN_SECAPI_INTERNAL_CALL
536 const CssmData &subjectKeyID = Certificate::required(certificate)->subjectKeyIdentifier();
537 #if !defined(NDEBUG)
538 logSKID("search for SKID: ", subjectKeyID);
539 #endif
540 // caller must release
541 resultCert = Certificate::required(certificate)->findBySubjectKeyID(keychains, subjectKeyID)->handle();
542 #if !defined(NDEBUG)
543 logSKID(" found SKID: ", subjectKeyID);
544 #endif
545 END_SECAPI_INTERNAL_CALL
546
547 SafeCFRelease(&systemRoots);
548
549 return resultCert;
550 }
551
552 // returns an array of possible root certificates (SecCertificateRef instances)
553 // for the given EV OID (a hex string); caller must release the array
554 //
555 static
556 CFArrayRef CF_RETURNS_RETAINED _possibleRootCertificatesForOidString(CFStringRef oidString)
557 {
558 StLock<Mutex> _(SecTrustKeychainsGetMutex());
559
560 if (!oidString)
561 return NULL;
562 CFDictionaryRef evOidDict = _evCAOidDict();
563 if (!evOidDict)
564 return NULL;
565 CFArrayRef possibleCertificateHashes = (CFArrayRef) CFDictionaryGetValue(evOidDict, oidString);
566 SecKeychainRef systemRoots = systemRootStore();
567 if (!possibleCertificateHashes || !systemRoots) {
568 SafeCFRelease(&evOidDict);
569 return NULL;
570 }
571
572 CFMutableArrayRef possibleRootCertificates = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
573 CFIndex hashCount = CFArrayGetCount(possibleCertificateHashes);
574 secinfo("evTrust", "_possibleRootCertificatesForOidString: %d possible hashes", (int)hashCount);
575
576 OSStatus status = errSecSuccess;
577 SecKeychainSearchRef searchRef = NULL;
578 // note: Sec* APIs are not re-entrant due to the API lock
579 // status = SecKeychainSearchCreateFromAttributes(systemRoots, kSecCertificateItemClass, NULL, &searchRef);
580 BEGIN_SECAPI_INTERNAL_CALL
581 StorageManager::KeychainList keychains;
582 globals().storageManager.optionalSearchList(systemRoots, keychains);
583 KCCursor cursor(keychains, kSecCertificateItemClass, NULL);
584 searchRef = cursor->handle();
585 END_SECAPI_INTERNAL_CALL
586 if (searchRef) {
587 while (!status) {
588 SecKeychainItemRef certRef = NULL;
589 // note: Sec* APIs are not re-entrant due to the API lock
590 // status = SecKeychainSearchCopyNext(searchRef, &certRef);
591 BEGIN_SECAPI_INTERNAL_CALL
592 Item item;
593 if (!KCCursorImpl::required(searchRef)->next(item)) {
594 certRef=NULL;
595 status=errSecItemNotFound;
596 } else {
597 certRef=item->handle();
598 }
599 END_SECAPI_INTERNAL_CALL
600 if (status || !certRef) {
601 break;
602 }
603
604 CSSM_DATA certData = { 0, NULL };
605 // note: Sec* APIs are not re-entrant due to the API lock
606 // status = SecCertificateGetData((SecCertificateRef) certRef, &certData);
607 BEGIN_SECAPI_INTERNAL_CALL
608 certData = Certificate::required((SecCertificateRef)certRef)->data();
609 END_SECAPI_INTERNAL_CALL
610 if (!status) {
611 uint8 buf[CC_SHA1_DIGEST_LENGTH];
612 CSSM_DATA digest = { sizeof(buf), buf };
613 if (!certData.Data || !certData.Length) {
614 status = errSecParam;
615 } else {
616 CC_SHA1(certData.Data, (CC_LONG)certData.Length, buf);
617 }
618 if (!status) {
619 CFDataRef hashData = CFDataCreateWithBytesNoCopy(NULL, digest.Data, digest.Length, kCFAllocatorNull);
620 if (hashData && CFArrayContainsValue(possibleCertificateHashes, CFRangeMake(0, hashCount), hashData)) {
621 CFArrayAppendValue(possibleRootCertificates, certRef);
622 }
623 SafeCFRelease(&hashData);
624 }
625 }
626 SafeCFRelease(&certRef);
627 }
628 }
629 SafeCFRelease(&searchRef);
630 SafeCFRelease(&systemRoots);
631 SafeCFRelease(&evOidDict);
632
633 return possibleRootCertificates;
634 }
635
636 // returns an array of allowed root certificates (SecCertificateRef instances)
637 // for the given EV OID (a hex string); caller must release the array.
638 // This differs from _possibleRootCertificatesForOidString in that each possible
639 // certificate is further checked for trust settings, so we don't include
640 // a certificate which is untrusted (or explicitly distrusted).
641 //
642 CFArrayRef _allowedRootCertificatesForOidString(CFStringRef oidString)
643 {
644 CFMutableArrayRef allowedRootCertificates = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
645 CFArrayRef possibleRootCertificates = _possibleRootCertificatesForOidString(oidString);
646 if (possibleRootCertificates) {
647 CFIndex idx, count = CFArrayGetCount(possibleRootCertificates);
648 for (idx=0; idx<count; idx++) {
649 SecCertificateRef cert = (SecCertificateRef) CFArrayGetValueAtIndex(possibleRootCertificates, idx);
650 /* Need a unified SecCertificateRef instance to hand to SecTrustSettingsCertHashStrFromCert */
651 SecCertificateRef certRef = SecCertificateCreateFromItemImplInstance(cert);
652 CFStringRef hashStr = SecTrustSettingsCertHashStrFromCert(certRef);
653 if (hashStr) {
654 bool foundMatch = false;
655 bool foundAny = false;
656 CSSM_RETURN *errors = NULL;
657 uint32 errorCount = 0;
658 SecTrustSettingsDomain foundDomain = kSecTrustSettingsDomainUser;
659 SecTrustSettingsResult result = kSecTrustSettingsResultInvalid;
660 OSStatus status = SecTrustSettingsEvaluateCert(
661 hashStr, /* certHashStr */
662 NULL, /* policyOID (optional) */
663 NULL, /* policyString (optional) */
664 0, /* policyStringLen */
665 0, /* keyUsage */
666 true, /* isRootCert */
667 &foundDomain, /* foundDomain */
668 &errors, /* allowedErrors */
669 &errorCount, /* numAllowedErrors */
670 &result, /* resultType */
671 &foundMatch, /* foundMatchingEntry */
672 &foundAny); /* foundAnyEntry */
673
674 if (status == errSecSuccess) {
675 secinfo("evTrust", "_allowedRootCertificatesForOidString: cert %lu has result %d from domain %d",
676 idx, (int)result, (int)foundDomain);
677 // Root certificates must be trusted by the system (and not have
678 // any explicit trust overrides) to be allowed for EV use.
679 if (foundMatch && foundDomain == kSecTrustSettingsDomainSystem &&
680 result == kSecTrustSettingsResultTrustRoot) {
681 CFArrayAppendValue(allowedRootCertificates, cert);
682 }
683 } else {
684 secinfo("evTrust", "_allowedRootCertificatesForOidString: cert %lu SecTrustSettingsEvaluateCert error %d",
685 idx, (int)status);
686 }
687 if (errors) {
688 free(errors);
689 }
690 CFRelease(hashStr);
691 }
692 if (certRef) {
693 CFRelease(certRef);
694 }
695 }
696 CFRelease(possibleRootCertificates);
697 }
698
699 return allowedRootCertificates;
700 }
701
702 // return a CSSM_DATA_PTR containing field data; caller must release with _freeFieldData
703 //
704 static CSSM_DATA_PTR _copyFieldDataForOid(CSSM_OID_PTR oid, CSSM_DATA_PTR cert, CSSM_CL_HANDLE clHandle)
705 {
706 uint32 numFields = 0;
707 CSSM_HANDLE results = 0;
708 CSSM_DATA_PTR value = 0;
709 CSSM_RETURN crtn = CSSM_CL_CertGetFirstFieldValue(clHandle, cert, oid, &results, &numFields, &value);
710
711 // we aren't going to look for any further fields, so free the results handle immediately
712 if (results) {
713 CSSM_CL_CertAbortQuery(clHandle, results);
714 }
715
716 return (crtn || !numFields) ? NULL : value;
717 }
718
719 // Some errors are ignorable errors because they do not indicate a problem
720 // with the certificate itself, but rather a problem getting a response from
721 // the CA server. The EV Certificate spec does not mandate that the application
722 // software vendor *must* get a response from OCSP or CRL, it is a "best
723 // attempt" approach which will not fail if the server does not respond.
724 //
725 // The EV spec (26. EV Certificate Status Checking) says that CAs have to
726 // maintain either a CRL or OCSP server. They are not required to maintain
727 // an OCSP server until after Dec 31, 2010.
728 //
729 // As to the responsibility of the application software vendor to perform
730 // revocation checking, this is only covered by the following section (37.2.):
731 //
732 // This [indemnification of Application Software Vendors]
733 // shall not apply, however, to any claim, damages, or loss
734 // suffered by such Application Software Vendor related to an EV Certificate
735 // issued by the CA where such claim, damage, or loss was directly caused by
736 // such Application Software Vendor’s software displaying as not trustworthy an
737 // EV Certificate that is still valid, or displaying as trustworthy: (1) an EV
738 // Certificate that has expired, or (2) an EV Certificate that has been revoked
739 // (but only in cases where the revocation status is currently available from the
740 // CA online, and the browser software either failed to check such status or
741 // ignored an indication of revoked status).
742 //
743 // The last section describes what a browser is required to do: it must attempt
744 // to check revocation status (as indicated by the OCSP or CRL server info in
745 // the certificate), and it cannot ignore an indication of revoked status
746 // (i.e. a positive thumbs-down response from the server, which would be a
747 // different error than the ones being skipped.) However, given that we meet
748 // those requirements, if the revocation server is down or will not give us a
749 // response for whatever reason, that is not our problem.
750
751 bool isRevocationServerMetaError(CSSM_RETURN statusCode)
752 {
753 switch (statusCode) {
754 case CSSMERR_APPLETP_CRL_NOT_FOUND: // 13. CRL not found
755 case CSSMERR_APPLETP_CRL_SERVER_DOWN: // 14. CRL server down
756 case CSSMERR_APPLETP_OCSP_UNAVAILABLE: // 33. OCSP service unavailable
757 case CSSMERR_APPLETP_NETWORK_FAILURE: // 36. General network failure
758 case CSSMERR_APPLETP_OCSP_RESP_MALFORMED_REQ: // 41. OCSP responder status: malformed request
759 case CSSMERR_APPLETP_OCSP_RESP_INTERNAL_ERR: // 42. OCSP responder status: internal error
760 case CSSMERR_APPLETP_OCSP_RESP_TRY_LATER: // 43. OCSP responder status: try later
761 case CSSMERR_APPLETP_OCSP_RESP_SIG_REQUIRED: // 44. OCSP responder status: signature required
762 case CSSMERR_APPLETP_OCSP_RESP_UNAUTHORIZED: // 45. OCSP responder status: unauthorized
763 return true;
764 default:
765 return false;
766 }
767 }
768
769 // returns true if the given status code is related to performing an OCSP revocation check
770 //
771 bool isOCSPStatusCode(CSSM_RETURN statusCode)
772 {
773 switch (statusCode)
774 {
775 case CSSMERR_APPLETP_OCSP_BAD_RESPONSE: // 31. Unparseable OCSP response
776 case CSSMERR_APPLETP_OCSP_BAD_REQUEST: // 32. Unparseable OCSP request
777 case CSSMERR_APPLETP_OCSP_RESP_MALFORMED_REQ: // 41. OCSP responder status: malformed request
778 case CSSMERR_APPLETP_OCSP_UNAVAILABLE: // 33. OCSP service unavailable
779 case CSSMERR_APPLETP_OCSP_STATUS_UNRECOGNIZED: // 34. OCSP status: cert unrecognized
780 case CSSMERR_APPLETP_OCSP_NOT_TRUSTED: // 37. OCSP response not verifiable to anchor or root
781 case CSSMERR_APPLETP_OCSP_INVALID_ANCHOR_CERT: // 38. OCSP response verified to untrusted root
782 case CSSMERR_APPLETP_OCSP_SIG_ERROR: // 39. OCSP response signature error
783 case CSSMERR_APPLETP_OCSP_NO_SIGNER: // 40. No signer for OCSP response found
784 case CSSMERR_APPLETP_OCSP_RESP_INTERNAL_ERR: // 42. OCSP responder status: internal error
785 case CSSMERR_APPLETP_OCSP_RESP_TRY_LATER: // 43. OCSP responder status: try later
786 case CSSMERR_APPLETP_OCSP_RESP_SIG_REQUIRED: // 44. OCSP responder status: signature required
787 case CSSMERR_APPLETP_OCSP_RESP_UNAUTHORIZED: // 45. OCSP responder status: unauthorized
788 case CSSMERR_APPLETP_OCSP_NONCE_MISMATCH: // 46. OCSP response nonce did not match request
789 return true;
790 default:
791 return false;
792 }
793 }
794
795 // returns true if the given status code is related to performing a CRL revocation check
796 //
797 bool isCRLStatusCode(CSSM_RETURN statusCode)
798 {
799 switch (statusCode)
800 {
801 case CSSMERR_APPLETP_CRL_EXPIRED: // 11. CRL expired
802 case CSSMERR_APPLETP_CRL_NOT_VALID_YET: // 12. CRL not yet valid
803 case CSSMERR_APPLETP_CRL_NOT_FOUND: // 13. CRL not found
804 case CSSMERR_APPLETP_CRL_SERVER_DOWN: // 14. CRL server down
805 case CSSMERR_APPLETP_CRL_BAD_URI: // 15. Illegal CRL distribution point URI
806 case CSSMERR_APPLETP_CRL_NOT_TRUSTED: // 18. CRL not verifiable to anchor or root
807 case CSSMERR_APPLETP_CRL_INVALID_ANCHOR_CERT: // 19. CRL verified to untrusted root
808 case CSSMERR_APPLETP_CRL_POLICY_FAIL: // 20. CRL failed policy verification
809 return true;
810 default:
811 return false;
812 }
813 }
814
815 // returns true if the given status code is related to performing a revocation check
816 //
817 bool isRevocationStatusCode(CSSM_RETURN statusCode)
818 {
819 if (statusCode == CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK || // 35. Revocation check not successful for each cert
820 statusCode == CSSMERR_APPLETP_NETWORK_FAILURE || // 36. General network error
821 isOCSPStatusCode(statusCode) == true || // OCSP error
822 isCRLStatusCode(statusCode) == true) // CRL error
823 return true;
824 else
825 return false;
826 }
827
828 // returns a CFArrayRef of allowed root certificates for the provided leaf certificate
829 // if it passes initial EV evaluation criteria and should be subject to OCSP revocation
830 // checking; otherwise, NULL is returned. (Caller must release the result if not NULL.)
831 //
832 CFArrayRef allowedEVRootsForLeafCertificate(CFArrayRef certificates)
833 {
834 // Given a partial certificate chain (which may or may not include the root,
835 // and does not have a guaranteed order except the first item is the leaf),
836 // determine whether the leaf claims to have a supported EV policy OID.
837 //
838 // Unless this function returns NULL, a full SSL trust evaluation with OCSP revocation
839 // checking must be performed successfully for the certificate to be considered valid.
840 // This function is intended to be called before the chain has been evaluated,
841 // in order to obtain the list of allowed roots for the evaluation. Once the "regular"
842 // TP evaluation has taken place, chainMeetsExtendedValidationCriteria() should be
843 // called to complete extended validation checking.
844
845 CFIndex count = (certificates) ? CFArrayGetCount(certificates) : 0;
846 if (count < 1)
847 return NULL;
848
849 CSSM_CL_HANDLE clHandle = 0;
850 CSSM_DATA certData = { 0, NULL };
851 SecCertificateRef certRef = (SecCertificateRef) CFArrayGetValueAtIndex(certificates, 0);
852 OSStatus status = errSecSuccess;
853 // note: Sec* APIs are not re-entrant due to the API lock
854 // status = SecCertificateGetCLHandle(certRef, &clHandle);
855 BEGIN_SECAPI_INTERNAL_CALL
856 clHandle = Certificate::required(certRef)->clHandle();
857 END_SECAPI_INTERNAL_CALL
858 if (status)
859 return NULL;
860 // note: Sec* APIs are not re-entrant due to the API lock
861 // status = SecCertificateGetData(certRef, &certData);
862 BEGIN_SECAPI_INTERNAL_CALL
863 certData = Certificate::required(certRef)->data();
864 END_SECAPI_INTERNAL_CALL
865 if (status)
866 return NULL;
867
868 // Does the leaf certificate contain a Certificate Policies extension?
869 const CSSM_OID_PTR oidPtr = (CSSM_OID_PTR) &CSSMOID_CertificatePolicies;
870 CSSM_DATA_PTR extensionDataPtr = _copyFieldDataForOid(oidPtr, &certData, clHandle);
871 if (!extensionDataPtr)
872 return NULL;
873
874 // Does the extension contain one of the magic EV CA OIDs we know about?
875 CSSM_X509_EXTENSION *cssmExtension = (CSSM_X509_EXTENSION *)extensionDataPtr->Data;
876 CE_CertPolicies *certPolicies = (CE_CertPolicies *)cssmExtension->value.parsedValue;
877 CFStringRef oidString = _oidStringForCertificatePolicies(certPolicies);
878 _freeFieldData(extensionDataPtr, oidPtr, clHandle);
879
880 // Fetch the allowed root CA certificates for this OID, if any
881 CFArrayRef allowedRoots = (oidString) ? _allowedRootCertificatesForOidString(oidString) : NULL;
882 CFIndex rootCount = (allowedRoots) ? CFArrayGetCount(allowedRoots) : 0;
883 secinfo("evTrust", "allowedEVRootsForLeafCertificate: found %d allowed roots", (int)rootCount);
884 SafeCFRelease(&oidString);
885 if (!allowedRoots || !rootCount) {
886 SafeCFRelease(&allowedRoots);
887 return NULL;
888 }
889
890 // The leaf certificate needs extended validation (with revocation checking).
891 // Return the array of allowed roots for this leaf certificate.
892 return allowedRoots;
893 }
894
895 // returns true if the provided certificate contains a wildcard in either
896 // its common name or subject alternative name.
897 //
898 static
899 bool hasWildcardDNSName(SecCertificateRef certRef)
900 {
901 OSStatus status = errSecSuccess;
902 CFArrayRef dnsNames = NULL;
903
904 BEGIN_SECAPI_INTERNAL_CALL
905 Required(&dnsNames) = Certificate::required(certRef)->copyDNSNames();
906 END_SECAPI_INTERNAL_CALL
907 if (status || !dnsNames)
908 return false;
909
910 bool hasWildcard = false;
911 const CFStringRef wildcard = CFSTR("*");
912 CFIndex index, count = CFArrayGetCount(dnsNames);
913 for (index = 0; index < count; index ++) {
914 CFStringRef name = (CFStringRef) CFArrayGetValueAtIndex(dnsNames, index);
915 if (name) {
916 CFRange foundRange = CFStringFind(name, wildcard, 0);
917 if (foundRange.length != 0 && foundRange.location != kCFNotFound) {
918 hasWildcard = true;
919 break;
920 }
921 }
922 }
923 CFRelease(dnsNames);
924 return hasWildcard;
925 }
926
927 // returns a CFDictionaryRef of extended validation results for the given chain,
928 // or NULL if the certificate chain did not meet all EV criteria. (Caller must
929 // release the result if not NULL.)
930 //
931 static
932 CFDictionaryRef extendedValidationResults(CFArrayRef certChain, SecTrustResultType trustResult, OSStatus tpResult)
933 {
934 // This function is intended to be called after the "regular" TP evaluation
935 // has taken place (i.e. trustResult and tpResult are available), and there
936 // is a full certificate chain to examine.
937
938 CFIndex chainIndex, chainLen = (certChain) ? CFArrayGetCount(certChain) : 0;
939 if (chainLen < 2) {
940 return NULL; // invalid chain length
941 }
942
943 if (trustResult != kSecTrustResultUnspecified) {
944
945 // "Recoverable" means the certificate failed to meet all policy requirements, but is intrinsically OK.
946 // One of the failures we might encounter is if the OCSP responder tells us to go away. Since this is a
947 // real-world case, we'll check for OCSP and CRL meta-errors specifically.
948 bool recovered = false;
949 if (trustResult == kSecTrustResultRecoverableTrustFailure) {
950 recovered = isRevocationServerMetaError((CSSM_RETURN)tpResult);
951 }
952 if (!recovered) {
953 return NULL;
954 }
955 }
956
957 //
958 // What we know at this point:
959 //
960 // 1. From a previous call to allowedEVRootsForLeafCertificate
961 // (or we wouldn't be getting called by extendedTrustResults):
962 // - a leaf certificate exists
963 // - that certificate contains a Certificate Policies extension
964 // - that extension contains an OID from one of the trusted EV CAs we know about
965 // - we have found at least one allowed EV root for that OID
966 //
967 // 2. From the TP evaluation:
968 // - the leaf certificate verifies back to a trusted EV root (with no trust settings overrides)
969 // - SSL trust evaluation with OCSP revocation checking enabled returned no (fatal) errors
970 //
971 // We need to verify the following additional requirements for the leaf (as of EV 1.1, 6(a)(2)):
972 // - cannot specify a wildcard in commonName or subjectAltName
973 // (note: this is a change since EV 1.0 (9.2.1), which stated that "Wildcard FQDNs are permitted.")
974 //
975 // Finally, we need to check the following requirements (EV 1.1 specification, Appendix B):
976 // - the trusted root, if created after 10/31/2006, must have:
977 // - critical basicConstraints extension with CA bit set
978 // - critical keyUsage extension with keyCertSign and cRLSign bits set
979 // - intermediate certs, if present, must have:
980 // - certificatePolicies extension, containing either a known EV CA OID, or anyPolicy
981 // - non-critical cRLDistributionPoint extension
982 // - critical basicConstraints extension with CA bit set
983 // - critical keyUsage extension with keyCertSign and cRLSign bits set
984 //
985
986 // check leaf certificate for wildcard names
987 if (hasWildcardDNSName((SecCertificateRef) CFArrayGetValueAtIndex(certChain, 0))) {
988 trustDebug("has wildcard name (does not meet EV criteria)\n");
989 return NULL;
990 }
991
992 // check intermediate CA certificates for required extensions per Appendix B of EV 1.1 specification.
993 bool hasRequiredExtensions = true;
994 CSSM_CL_HANDLE clHandle = 0;
995 CSSM_DATA certData = { 0, NULL };
996 CSSM_OID_PTR oidPtr = (CSSM_OID_PTR) &CSSMOID_CertificatePolicies;
997 for (chainIndex = 1; hasRequiredExtensions && chainLen > 2 && chainIndex < chainLen - 1; chainIndex++) {
998 SecCertificateRef intermediateCert = (SecCertificateRef) CFArrayGetValueAtIndex(certChain, chainIndex);
999 OSStatus status = errSecSuccess;
1000 // note: Sec* APIs are not re-entrant due to the API lock
1001 // status = SecCertificateGetCLHandle(intermediateCert, &clHandle);
1002 BEGIN_SECAPI_INTERNAL_CALL
1003 clHandle = Certificate::required(intermediateCert)->clHandle();
1004 END_SECAPI_INTERNAL_CALL
1005 if (status)
1006 return NULL;
1007 // note: Sec* APIs are not re-entrant due to the API lock
1008 // status = SecCertificateGetData(intermediateCert, &certData);
1009 BEGIN_SECAPI_INTERNAL_CALL
1010 certData = Certificate::required(intermediateCert)->data();
1011 END_SECAPI_INTERNAL_CALL
1012 if (status)
1013 return NULL;
1014
1015 CSSM_DATA_PTR extensionDataPtr = _copyFieldDataForOid(oidPtr, &certData, clHandle);
1016 if (!extensionDataPtr)
1017 return NULL;
1018
1019 CSSM_X509_EXTENSION *cssmExtension = (CSSM_X509_EXTENSION *)extensionDataPtr->Data;
1020 CE_CertPolicies *certPolicies = (CE_CertPolicies *)cssmExtension->value.parsedValue;
1021 CFStringRef oidString = _oidStringForCertificatePolicies(certPolicies);
1022 hasRequiredExtensions = (oidString != NULL);
1023 SafeCFRelease(&oidString);
1024 _freeFieldData(extensionDataPtr, oidPtr, clHandle);
1025
1026 // FIX: add checks for the following (not essential to this implementation):
1027 // - non-critical cRLDistributionPoint extension
1028 // - critical basicConstraints extension with CA bit set
1029 // - critical keyUsage extension with keyCertSign and cRLSign bits set
1030 // Tracked by <rdar://problem/6119322>
1031 }
1032
1033 if (hasRequiredExtensions) {
1034 SecCertificateRef leafCert = (SecCertificateRef) CFArrayGetValueAtIndex(certChain, 0);
1035 CFStringRef organizationName = organizationNameForCertificate(leafCert);
1036 if (organizationName != NULL) {
1037 CFMutableDictionaryRef resultDict = CFDictionaryCreateMutable(NULL, 0,
1038 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1039 CFDictionaryAddValue(resultDict, kSecEVOrganizationName, organizationName);
1040 trustDebug("[EV] extended validation succeeded\n");
1041 SafeCFRelease(&organizationName);
1042 return resultDict;
1043 }
1044 }
1045
1046 return NULL;
1047 }
1048
1049 // returns a CFDictionaryRef containing extended trust results.
1050 // Caller must release this dictionary.
1051 //
1052 // If the isEVCandidate argument is true, extended validation checking is performed
1053 // and the kSecEVOrganizationName key will be set in the dictionary if EV criteria is met.
1054 // In all cases, kSecTrustEvaluationDate and kSecTrustExpirationDate will be set.
1055 //
1056 CFDictionaryRef extendedTrustResults(CFArrayRef certChain, SecTrustResultType trustResult, OSStatus tpResult, bool isEVCandidate)
1057 {
1058 CFMutableDictionaryRef resultDict = NULL;
1059 if (isEVCandidate) {
1060 resultDict = (CFMutableDictionaryRef) extendedValidationResults(certChain, trustResult, tpResult);
1061 }
1062 if (!resultDict) {
1063 resultDict = CFDictionaryCreateMutable(NULL, 0,
1064 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1065 if (!resultDict) {
1066 return NULL;
1067 }
1068 }
1069 CFAbsoluteTime at = CFAbsoluteTimeGetCurrent();
1070 CFDateRef trustEvaluationDate = CFDateCreate(kCFAllocatorDefault, at);
1071 // by default, permit caching of trust evaluation results for up to 2 hours
1072 // FIXME: need to modify this based on cert expiration and OCSP/CRL validity
1073 CFDateRef trustExpirationDate = CFDateCreate(kCFAllocatorDefault, at + (60*60*2));
1074 CFDictionaryAddValue(resultDict, kSecTrustEvaluationDate, trustEvaluationDate);
1075 SafeCFRelease(&trustEvaluationDate);
1076 CFDictionaryAddValue(resultDict, kSecTrustExpirationDate, trustExpirationDate);
1077 SafeCFRelease(&trustExpirationDate);
1078
1079 return resultDict;
1080 }
1081
1082 // returns a CFDictionaryRef containing mappings from supported EV CA OIDs to SHA-1 hash values;
1083 // caller must release
1084 //
1085 static CFDictionaryRef _evCAOidDict()
1086 {
1087 static CFDictionaryRef s_evCAOidDict = NULL;
1088 if (s_evCAOidDict) {
1089 CFRetain(s_evCAOidDict);
1090 secinfo("evTrust", "_evCAOidDict: returning static instance (rc=%d)", (int)CFGetRetainCount(s_evCAOidDict));
1091 return s_evCAOidDict;
1092 }
1093 secinfo("evTrust", "_evCAOidDict: initializing static instance");
1094
1095 s_evCAOidDict = dictionaryWithContentsOfPlistFile(EV_ROOTS_PLIST_SYSTEM_PATH);
1096 if (!s_evCAOidDict)
1097 return NULL;
1098
1099 #if !defined MAC_OS_X_VERSION_10_6 || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
1100 // Work around rdar://6302788 by hard coding a hash that was missed when addressing <rdar://problem/6238289&6238296>
1101 // This is being addressed in SnowLeopard by rdar://6305989
1102 CFStringRef oidString = CFSTR("2.16.840.1.114028.10.1.2");
1103 CFMutableArrayRef hashes = (CFMutableArrayRef) CFDictionaryGetValue(s_evCAOidDict, oidString);
1104 if (hashes) {
1105 uint8 hashBytes[] = {0xB3, 0x1E, 0xB1, 0xB7, 0x40, 0xE3, 0x6C, 0x84, 0x02, 0xDA, 0xDC, 0x37, 0xD4, 0x4D, 0xF5, 0xD4, 0x67, 0x49, 0x52, 0xF9};
1106 CFDataRef hashData = CFDataCreate(NULL, hashBytes, sizeof(hashBytes));
1107 CFIndex hashCount = CFArrayGetCount(hashes);
1108 if (hashData && CFArrayContainsValue(hashes, CFRangeMake(0, hashCount), hashData)) {
1109 secinfo("evTrust", "_evCAOidDict: added hardcoded hash value");
1110 CFArrayAppendValue(hashes, hashData);
1111 }
1112 SafeCFRelease(&hashData);
1113 }
1114 #endif
1115 CFRetain(s_evCAOidDict);
1116 secinfo("evTrust", "_evCAOidDict: returning static instance (rc=%d)", (int)CFGetRetainCount(s_evCAOidDict));
1117 return s_evCAOidDict;
1118 }
1119
1120 // returns a CFStringRef containing a decimal representation of the given OID.
1121 // Caller must release.
1122
1123 static CFStringRef _decimalStringForOid(CSSM_OID_PTR oid)
1124 {
1125 CFMutableStringRef str = CFStringCreateMutable(NULL, 0);
1126 if (!str || oid->Length > 32)
1127 return str;
1128
1129 // The first two levels are encoded into one byte, since the root level
1130 // has only 3 nodes (40*x + y). However if x = joint-iso-itu-t(2) then
1131 // y may be > 39, so we have to add special-case handling for this.
1132 unsigned long value = 0;
1133 unsigned int x = oid->Data[0] / 40;
1134 unsigned int y = oid->Data[0] % 40;
1135 if (x > 2) {
1136 // Handle special case for large y if x = 2
1137 y += (x - 2) * 40;
1138 x = 2;
1139 }
1140
1141 CFStringAppendFormat(str, NULL, CFSTR("%d.%d"), x, y);
1142
1143 for (x = 1; x < oid->Length; x++) {
1144 value = (value << 7) | (oid->Data[x] & 0x7F);
1145 if(!(oid->Data[x] & 0x80)) {
1146 CFStringAppendFormat(str, NULL, CFSTR(".%ld"), value);
1147 value = 0;
1148 }
1149 }
1150
1151 #if !defined(NDEBUG)
1152 CFIndex nameLen = CFStringGetLength(str);
1153 CFIndex bufLen = 1 + CFStringGetMaximumSizeForEncoding(nameLen, kCFStringEncodingUTF8);
1154 char *nameBuf = (char *)malloc(bufLen);
1155 if (!CFStringGetCString(str, nameBuf, bufLen-1, kCFStringEncodingUTF8))
1156 nameBuf[0]=0;
1157 secinfo("evTrust", "_decimalStringForOid: \"%s\"", nameBuf);
1158 free(nameBuf);
1159 #endif
1160
1161 return str;
1162 }
1163
1164 static void _freeFieldData(CSSM_DATA_PTR value, CSSM_OID_PTR oid, CSSM_CL_HANDLE clHandle)
1165 {
1166 if (value && value->Data) {
1167 CSSM_CL_FreeFieldValue(clHandle, oid, value);
1168 }
1169 return;
1170 }
1171
1172 static ModuleNexus<Mutex> gOidStringForCertificatePoliciesMutex;
1173
1174 static CFStringRef CF_RETURNS_RETAINED _oidStringForCertificatePolicies(const CE_CertPolicies *certPolicies)
1175 {
1176 StLock<Mutex> _(gOidStringForCertificatePoliciesMutex());
1177
1178 // returns the first EV OID (as a string) found in the given Certificate Policies extension,
1179 // or NULL if the extension does not contain any known EV OIDs. (Note that the "any policy" OID
1180 // is a special case and will be returned if present, although its presence is only meaningful
1181 // in an intermediate CA.)
1182
1183 if (!certPolicies) {
1184 secinfo("evTrust", "oidStringForCertificatePolicies: missing certPolicies!");
1185 return NULL;
1186 }
1187
1188 CFDictionaryRef evOidDict = _evCAOidDict();
1189 if (!evOidDict) {
1190 secinfo("evTrust", "oidStringForCertificatePolicies: nil OID dictionary!");
1191 return NULL;
1192 }
1193
1194 CFStringRef foundOidStr = NULL;
1195 uint32 policyIndex, maxIndex = 10; // sanity check; EV certs normally have EV OID as first policy
1196 for (policyIndex = 0; policyIndex < certPolicies->numPolicies && policyIndex < maxIndex; policyIndex++) {
1197 CE_PolicyInformation *certPolicyInfo = &certPolicies->policies[policyIndex];
1198 CSSM_OID_PTR oid = &certPolicyInfo->certPolicyId;
1199 CFStringRef oidStr = _decimalStringForOid(oid);
1200 if (!oidStr)
1201 continue;
1202 if (!CFStringCompare(oidStr, CFSTR("2.5.29.32.0"), 0) || // is it the "any" OID, or
1203 CFDictionaryGetValue(evOidDict, oidStr) != NULL) { // a known EV CA OID?
1204 foundOidStr = CFStringCreateCopy(NULL, oidStr);
1205 }
1206 SafeCFRelease(&oidStr);
1207 if (foundOidStr)
1208 break;
1209 }
1210 SafeCFRelease(&evOidDict);
1211
1212 return foundOidStr;
1213 }
1214