2 * Copyright (c) 2002-2016 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
24 #include <Security/SecCertificate.h>
25 #include <Security/SecCertificatePriv.h>
26 #include <security_keychain/Certificate.h>
27 #include <security_keychain/Item.h>
28 #include <security_keychain/KCCursor.h>
29 #include <Security/cssmapi.h>
30 #include <Security/cssmapple.h>
31 #include <security_cdsa_client/cspclient.h>
32 #include <security_cdsa_client/clclient.h>
33 #include <security_cdsa_client/tpclient.h>
34 #include <Security/cssmtype.h>
36 #include "SecBridge.h"
38 // %%% used by SecCertificate{Copy,Set}Preference
39 #include <Security/SecKeychainItemPriv.h>
40 #include <Security/SecIdentityPriv.h>
41 #include <Security/SecItemPriv.h>
42 #include <security_keychain/KCCursor.h>
43 #include <security_cdsa_utilities/Schema.h>
44 #include <security_cdsa_utils/cuCdsaUtils.h>
45 #include <sys/param.h>
47 #include "CertificateValues.h"
49 #include "AppleBaselineEscrowCertificates.h"
52 OSStatus
SecCertificateGetCLHandle_legacy(SecCertificateRef certificate
, CSSM_CL_HANDLE
*clHandle
);
53 extern CSSM_KEYUSE
ConvertArrayToKeyUsage(CFArrayRef usage
);
58 using namespace CssmClient
;
60 CFTypeID
static SecCertificateGetTypeID_osx(void)
64 return gTypes().Certificate
.typeID
;
66 END_SECAPI1(_kCFRuntimeNotATypeID
)
70 SecCertificateIsItemImplInstance(SecCertificateRef certificate
)
72 if (certificate
== NULL
) {
76 CFTypeID typeID
= CFGetTypeID(certificate
);
78 #if 0 /* debug code to verify type IDs */
79 syslog(LOG_ERR
, "SecCertificate typeID=%d [STU=%d, OSX=%d, SKI=%d]",
81 (int)SecCertificateGetTypeID(),
82 (int)SecCertificateGetTypeID_osx(),
83 (int)SecKeychainItemGetTypeID());
85 if (typeID
== _kCFRuntimeNotATypeID
) {
89 return (typeID
== SecCertificateGetTypeID_osx() ||
90 typeID
== SecKeychainItemGetTypeID()) ? true : false;
93 /* convert a new-world SecCertificateRef to an old-world ItemImpl instance */
95 SecCertificateCreateItemImplInstance(SecCertificateRef certificate
)
100 SecCertificateRef implCertRef
= (SecCertificateRef
) SecCertificateCopyKeychainItem(certificate
);
104 CFDataRef data
= SecCertificateCopyData(certificate
);
109 CSSM_DATA cssmCertData
;
110 cssmCertData
.Length
= (data
) ? (CSSM_SIZE
)CFDataGetLength(data
) : 0;
111 cssmCertData
.Data
= (data
) ? (uint8
*)CFDataGetBytePtr(data
) : NULL
;
113 SecPointer
<Certificate
> certificatePtr(new Certificate(cssmCertData
, CSSM_CERT_X_509v3
, CSSM_CERT_ENCODING_DER
));
114 implCertRef
= certificatePtr
->handle();
121 /* convert an old-world ItemImpl instance to a new-world SecCertificateRef */
123 SecCertificateCreateFromItemImplInstance(SecCertificateRef certificate
)
128 SecCertificateRef result
= NULL
;
129 CFDataRef data
= NULL
;
131 CssmData certData
= Certificate::required(certificate
)->data();
132 if (certData
.Data
&& certData
.Length
) {
133 data
= CFDataCreate(NULL
, certData
.Data
, certData
.Length
);
136 if (certData
.Data
&& !certData
.Length
) {
137 /* zero-length certs can exist, so don't bother logging this */
140 syslog(LOG_ERR
, "WARNING: SecKeychainSearchCopyNext failed to retrieve certificate data (length=%ld, data=0x%lX)",
141 (long)certData
.Length
, (uintptr_t)certData
.Data
);
148 result
= SecCertificateCreateWithKeychainItem(NULL
, data
, certificate
);
155 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
157 SecCertificateCreateFromData(const CSSM_DATA
*data
, CSSM_CERT_TYPE type
, CSSM_CERT_ENCODING encoding
, SecCertificateRef
*certificate
)
159 /* bridge to support old functionality */
160 if (!data
|| !data
->Data
|| !data
->Length
|| !certificate
) {
163 SecCertificateRef certRef
= NULL
;
165 // <rdar://problem/24403998> REG: Adobe {Photoshop, InDesign} CC(2015) crashes on launch
166 // If you take the length that SecKeychainItemCopyContent gives you (a Uint32) and assign it incorrectly
167 // to a CSSM_DATA Length field (a CSSM_SIZE, i.e., a size_t), the upper 32 bits aren't set. If those bits
168 // are non-zero, the length is incredibly wrong.
170 // Assume that there will not exist a certificate > 4GiB, and fake this length field.
171 CSSM_SIZE length
= data
->Length
& 0xfffffffful
;
173 CFDataRef dataRef
= CFDataCreate(NULL
, data
->Data
, length
);
175 certRef
= SecCertificateCreateWithData(NULL
, dataRef
);
178 *certificate
= certRef
;
179 return (certRef
) ? errSecSuccess
: errSecUnknownFormat
;
182 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA) */
184 SecCertificateAddToKeychain(SecCertificateRef certificate
, SecKeychainRef keychain
)
186 // This macro creates an ItemImpl certificate if it does not exist
189 Item
item(Certificate::required(__itemImplRef
));
190 Keychain::optional(keychain
)->add(item
);
195 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
197 SecCertificateGetData(SecCertificateRef certificate
, CSSM_DATA_PTR data
)
201 if (!certificate
|| !data
) {
202 __secapiresult
=errSecParam
;
204 else if (SecCertificateIsItemImplInstance(certificate
)) {
205 Required(data
) = Certificate::required(certificate
)->data();
208 data
->Length
= (CSSM_SIZE
)SecCertificateGetLength(certificate
);
209 data
->Data
= (uint8
*)SecCertificateGetBytePtr(certificate
);
215 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
217 SecCertificateGetType(SecCertificateRef certificate
, CSSM_CERT_TYPE
*certificateType
)
219 // This macro creates an ItemImpl certificate if it does not exist
222 Required(certificateType
) = Certificate::required(__itemImplRef
)->type();
227 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
229 SecCertificateGetSubject(SecCertificateRef certificate
, const CSSM_X509_NAME
**subject
)
231 // This macro creates an ItemImpl certificate if it does not exist
234 Required(subject
) = Certificate::required(__itemImplRef
)->subjectName();
239 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
241 SecCertificateGetIssuer(SecCertificateRef certificate
, const CSSM_X509_NAME
**issuer
)
243 // This macro creates an ItemImpl certificate if it does not exist
246 Required(issuer
) = Certificate::required(__itemImplRef
)->issuerName();
251 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
253 SecCertificateGetCLHandle(SecCertificateRef certificate
, CSSM_CL_HANDLE
*clHandle
)
255 // This macro creates an ItemImpl certificate if it does not exist
258 Required(clHandle
) = Certificate::required(__itemImplRef
)->clHandle();
263 /* private function; assumes input is old-style ItemImpl certificate reference,
264 and does not release that certificate reference!
267 SecCertificateGetCLHandle_legacy(SecCertificateRef certificate
, CSSM_CL_HANDLE
*clHandle
)
271 Required(clHandle
) = Certificate::required(certificate
)->clHandle();
277 * Private API to infer a display name for a SecCertificateRef which
278 * may or may not be in a keychain.
283 SecCertificateInferLabel(SecCertificateRef certificate
, CFStringRef
*label
)
285 // This macro creates an ItemImpl certificate if it does not exist
288 Certificate::required(__itemImplRef
)->inferLabel(false, &Required(label
));
293 /* OS X only (note: iOS version has different arguments and return value) */
295 SecCertificateCopyPublicKey(SecCertificateRef certificate
, SecKeyRef
*key
)
297 // This macro creates an ItemImpl certificate if it does not exist
300 Required(key
) = Certificate::required(__itemImplRef
)->publicKey()->handle();
305 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
307 SecCertificateGetAlgorithmID(SecCertificateRef certificate
, const CSSM_X509_ALGORITHM_IDENTIFIER
**algid
)
309 // This macro creates an ItemImpl certificate if it does not exist
312 Required(algid
) = Certificate::required(__itemImplRef
)->algorithmID();
319 SecCertificateCopySubjectComponent(SecCertificateRef certificate
, const CSSM_OID
*component
, CFStringRef
*result
)
321 // This macro creates an ItemImpl certificate if it does not exist
324 Required(result
) = Certificate::required(__itemImplRef
)->distinguishedName(&CSSMOID_X509V1SubjectNameCStruct
, component
);
329 /* OS X only; deprecated SPI */
331 SecCertificateGetCommonName(SecCertificateRef certificate
, CFStringRef
*commonName
)
333 // deprecated SPI signature; replaced by SecCertificateCopyCommonName
334 return SecCertificateCopyCommonName(certificate
, commonName
);
337 /* OS X only; deprecated SPI */
339 SecCertificateGetEmailAddress(SecCertificateRef certificate
, CFStringRef
*emailAddress
)
341 // This macro creates an ItemImpl certificate if it does not exist
344 Required(emailAddress
) = Certificate::required(__itemImplRef
)->copyFirstEmailAddress();
349 /* Return a zero terminated list of CSSM_DATA_PTR's with the values of the field specified by field.
350 * Caller must call releaseFieldValues to free the storage allocated by this call.
355 SecCertificateCopyFieldValues(SecCertificateRef certificate
, const CSSM_OID
*field
, CSSM_DATA_PTR
**fieldValues
)
357 // This macro creates an ItemImpl certificate if it does not exist
360 Required(fieldValues
) = Certificate::required(__itemImplRef
)->copyFieldValues(Required(field
));
367 SecCertificateReleaseFieldValues(SecCertificateRef certificate
, const CSSM_OID
*field
, CSSM_DATA_PTR
*fieldValues
)
369 // This macro creates an ItemImpl certificate if it does not exist
372 Certificate::required(__itemImplRef
)->releaseFieldValues(Required(field
), fieldValues
);
379 SecCertificateCopyFirstFieldValue(SecCertificateRef certificate
, const CSSM_OID
*field
, CSSM_DATA_PTR
*fieldValue
)
381 // This macro creates an ItemImpl certificate if it does not exist
384 Required(fieldValue
) = Certificate::required(__itemImplRef
)->copyFirstFieldValue(Required(field
));
391 SecCertificateReleaseFirstFieldValue(SecCertificateRef certificate
, const CSSM_OID
*field
, CSSM_DATA_PTR fieldValue
)
393 // This macro creates an ItemImpl certificate if it does not exist
396 Certificate::required(__itemImplRef
)->releaseFieldValue(Required(field
), fieldValue
);
403 SecCertificateFindByIssuerAndSN(CFTypeRef keychainOrArray
,const CSSM_DATA
*issuer
,
404 const CSSM_DATA
*serialNumber
, SecCertificateRef
*certificate
)
406 if (issuer
&& serialNumber
) {
407 CFRef
<CFMutableDictionaryRef
> query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
408 CFDictionarySetValue(query
, kSecClass
, kSecClassCertificate
);
409 CFDictionarySetValue(query
, kSecReturnRef
, kCFBooleanTrue
);
410 CFDictionarySetValue(query
, kSecAttrNoLegacy
, kCFBooleanTrue
);
412 CFRef
<CFDataRef
> issuerData
= CFDataCreateWithBytesNoCopy(kCFAllocatorDefault
, (const UInt8
*)issuer
->Data
, issuer
->Length
, kCFAllocatorNull
);
413 CFDictionarySetValue(query
, kSecAttrIssuer
, issuerData
);
415 CFRef
<CFDataRef
> serialNumberData
= CFDataCreateWithBytesNoCopy(kCFAllocatorDefault
, (const UInt8
*)serialNumber
->Data
, serialNumber
->Length
, kCFAllocatorNull
);
416 CFDictionarySetValue(query
, kSecAttrSerialNumber
, serialNumberData
);
418 OSStatus status
= SecItemCopyMatching(query
, (CFTypeRef
*)certificate
);
419 if (status
== errSecSuccess
) {
426 StorageManager::KeychainList keychains
;
427 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
428 Required(certificate
) = Certificate::findByIssuerAndSN(keychains
, CssmData::required(issuer
), CssmData::required(serialNumber
))->handle();
430 // convert ItemImpl-based SecCertificateRef to new-world version before returning
431 CssmData certData
= Certificate::required(*certificate
)->data();
432 CFRef
<CFDataRef
> cfData(CFDataCreate(NULL
, certData
.Data
, certData
.Length
));
433 SecCertificateRef tmpRef
= *certificate
;
434 *certificate
= SecCertificateCreateWithData(NULL
, cfData
);
442 SecCertificateFindBySubjectKeyID(CFTypeRef keychainOrArray
, const CSSM_DATA
*subjectKeyID
,
443 SecCertificateRef
*certificate
)
446 CFRef
<CFMutableDictionaryRef
> query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
447 CFDictionarySetValue(query
, kSecClass
, kSecClassCertificate
);
448 CFDictionarySetValue(query
, kSecReturnRef
, kCFBooleanTrue
);
449 CFDictionarySetValue(query
, kSecAttrNoLegacy
, kCFBooleanTrue
);
451 CFRef
<CFDataRef
> subjectKeyIDData
= CFDataCreateWithBytesNoCopy(kCFAllocatorDefault
, (const UInt8
*)subjectKeyID
->Data
, subjectKeyID
->Length
, kCFAllocatorNull
);
452 CFDictionarySetValue(query
, kSecAttrSubjectKeyID
, subjectKeyIDData
);
454 OSStatus status
= SecItemCopyMatching(query
, (CFTypeRef
*)certificate
);
455 if (status
== errSecSuccess
) {
462 StorageManager::KeychainList keychains
;
463 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
464 Required(certificate
) = Certificate::findBySubjectKeyID(keychains
, CssmData::required(subjectKeyID
))->handle();
466 // convert ItemImpl-based SecCertificateRef to new-world version before returning
467 CssmData certData
= Certificate::required(*certificate
)->data();
468 CFRef
<CFDataRef
> cfData(CFDataCreate(NULL
, certData
.Data
, certData
.Length
));
469 SecCertificateRef tmpRef
= *certificate
;
470 *certificate
= SecCertificateCreateWithData(NULL
, cfData
);
478 SecCertificateFindByEmail(CFTypeRef keychainOrArray
, const char *emailAddress
, SecCertificateRef
*certificate
)
481 CFRef
<CFMutableDictionaryRef
> query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
482 CFDictionarySetValue(query
, kSecClass
, kSecClassCertificate
);
483 CFDictionarySetValue(query
, kSecReturnRef
, kCFBooleanTrue
);
484 CFDictionarySetValue(query
, kSecAttrNoLegacy
, kCFBooleanTrue
);
486 CFRef
<CFStringRef
> emailAddressString
= CFStringCreateWithCString(kCFAllocatorDefault
, emailAddress
, kCFStringEncodingUTF8
);
487 CFTypeRef keys
[] = { kSecPolicyName
};
488 CFTypeRef values
[] = { emailAddressString
};
489 CFRef
<CFDictionaryRef
> properties
= CFDictionaryCreate(kCFAllocatorDefault
, keys
, values
, 1, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
490 CFRef
<SecPolicyRef
> policy
= SecPolicyCreateWithProperties(kSecPolicyAppleSMIME
, properties
);
491 CFDictionarySetValue(query
, kSecMatchPolicy
, policy
);
493 OSStatus status
= SecItemCopyMatching(query
, (CFTypeRef
*)certificate
);
494 if (status
== errSecSuccess
) {
501 StorageManager::KeychainList keychains
;
502 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
503 Required(certificate
) = Certificate::findByEmail(keychains
, emailAddress
)->handle();
505 // convert ItemImpl-based SecCertificateRef to new-world version before returning
506 CssmData certData
= Certificate::required(*certificate
)->data();
507 CFRef
<CFDataRef
> cfData(CFDataCreate(NULL
, certData
.Data
, certData
.Length
));
508 SecCertificateRef tmpRef
= *certificate
;
509 *certificate
= SecCertificateCreateWithData(NULL
, cfData
);
517 SecKeychainSearchCreateForCertificateByIssuerAndSN(CFTypeRef keychainOrArray
, const CSSM_DATA
*issuer
,
518 const CSSM_DATA
*serialNumber
, SecKeychainSearchRef
*searchRef
)
524 StorageManager::KeychainList keychains
;
525 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
526 KCCursor
cursor(Certificate::cursorForIssuerAndSN(keychains
, CssmData::required(issuer
), CssmData::required(serialNumber
)));
527 *searchRef
= cursor
->handle();
534 SecKeychainSearchCreateForCertificateByIssuerAndSN_CF(CFTypeRef keychainOrArray
, CFDataRef issuer
,
535 CFDataRef serialNumber
, SecKeychainSearchRef
*searchRef
)
541 StorageManager::KeychainList keychains
;
542 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
544 Required(serialNumber
);
545 KCCursor
cursor(Certificate::cursorForIssuerAndSN_CF(keychains
, issuer
, serialNumber
));
546 *searchRef
= cursor
->handle();
553 SecKeychainSearchCreateForCertificateBySubjectKeyID(CFTypeRef keychainOrArray
, const CSSM_DATA
*subjectKeyID
,
554 SecKeychainSearchRef
*searchRef
)
560 StorageManager::KeychainList keychains
;
561 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
562 KCCursor
cursor(Certificate::cursorForSubjectKeyID(keychains
, CssmData::required(subjectKeyID
)));
563 *searchRef
= cursor
->handle();
570 SecKeychainSearchCreateForCertificateByEmail(CFTypeRef keychainOrArray
, const char *emailAddress
,
571 SecKeychainSearchRef
*searchRef
)
577 StorageManager::KeychainList keychains
;
578 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
579 KCCursor
cursor(Certificate::cursorForEmail(keychains
, emailAddress
));
580 *searchRef
= cursor
->handle();
587 SecDigestGetData (CSSM_ALGORITHMS alg
, CSSM_DATA
* digest
, const CSSM_DATA
* data
)
591 if (!digest
|| !digest
->Data
|| !digest
->Length
|| !data
|| !data
->Data
|| !data
->Length
)
594 CSP
csp(gGuidAppleCSP
);
595 Digest
context(csp
, alg
);
596 CssmData
input(data
->Data
, data
->Length
);
597 CssmData
output(digest
->Data
, digest
->Length
);
599 context
.digest(input
, output
);
600 digest
->Length
= output
.length();
606 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
608 SecCertificateCopyPreference(
610 CSSM_KEYUSE keyUsage
,
611 SecCertificateRef
*certificate
)
616 Required(certificate
);
617 StorageManager::KeychainList keychains
;
618 globals().storageManager
.getSearchList(keychains
);
619 KCCursor
cursor(keychains
, kSecGenericPasswordItemClass
, NULL
);
621 char idUTF8
[MAXPATHLEN
];
622 if (!CFStringGetCString(name
, idUTF8
, sizeof(idUTF8
)-1, kCFStringEncodingUTF8
))
623 idUTF8
[0] = (char)'\0';
624 CssmData
service(const_cast<char *>(idUTF8
), strlen(idUTF8
));
625 FourCharCode itemType
= 'cprf';
626 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecServiceItemAttr
), service
);
627 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecTypeItemAttr
), itemType
);
629 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecScriptCodeItemAttr
), (sint32
)keyUsage
);
632 if (!cursor
->next(prefItem
))
633 MacOSError::throwMe(errSecItemNotFound
);
635 // get persistent certificate reference
636 SecKeychainAttribute itemAttrs
[] = { { kSecGenericItemAttr
, 0, NULL
} };
637 SecKeychainAttributeList itemAttrList
= { sizeof(itemAttrs
) / sizeof(itemAttrs
[0]), itemAttrs
};
638 prefItem
->getContent(NULL
, &itemAttrList
, NULL
, NULL
);
640 // find certificate, given persistent reference data
641 CFDataRef pItemRef
= CFDataCreateWithBytesNoCopy(NULL
, (const UInt8
*)itemAttrs
[0].data
, itemAttrs
[0].length
, kCFAllocatorNull
);
642 SecKeychainItemRef certItemRef
= nil
;
643 OSStatus status
= SecKeychainItemCopyFromPersistentReference(pItemRef
, &certItemRef
); //%%% need to make this a method of ItemImpl
644 prefItem
->freeContent(&itemAttrList
, NULL
);
650 *certificate
= (SecCertificateRef
)certItemRef
;
652 if (certItemRef
&& (CFGetTypeID(certItemRef
) == SecIdentityGetTypeID())) {
653 // SecKeychainItemCopyFromPersistentReference handed out an identity reference
655 status
= SecIdentityCopyCertificate((SecIdentityRef
)certItemRef
, certificate
);
656 CFRelease(certItemRef
);
665 SecCertificateCopyPreferred(
669 // This function will look for a matching preference in the following order:
670 // - matches the name and the supplied key use
671 // - matches the name and the special 'ANY' key use
672 // - matches the name with no key usage constraint
674 SecCertificateRef certRef
= NULL
;
675 CSSM_KEYUSE keyUse
= ConvertArrayToKeyUsage(keyUsage
);
676 OSStatus status
= SecCertificateCopyPreference(name
, keyUse
, &certRef
);
677 if (status
!= errSecSuccess
&& keyUse
!= CSSM_KEYUSE_ANY
)
678 status
= SecCertificateCopyPreference(name
, CSSM_KEYUSE_ANY
, &certRef
);
679 if (status
!= errSecSuccess
&& keyUse
!= 0)
680 status
= SecCertificateCopyPreference(name
, 0, &certRef
);
685 /* OS X only; not exported */
687 SecCertificateFindPreferenceItemWithNameAndKeyUsage(
688 CFTypeRef keychainOrArray
,
691 SecKeychainItemRef
*itemRef
)
695 StorageManager::KeychainList keychains
;
696 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
697 KCCursor
cursor(keychains
, kSecGenericPasswordItemClass
, NULL
);
699 char idUTF8
[MAXPATHLEN
];
700 idUTF8
[0] = (char)'\0';
703 if (!CFStringGetCString(name
, idUTF8
, sizeof(idUTF8
)-1, kCFStringEncodingUTF8
))
704 idUTF8
[0] = (char)'\0';
706 size_t idUTF8Len
= strlen(idUTF8
);
708 MacOSError::throwMe(errSecParam
);
710 CssmData
service(const_cast<char *>(idUTF8
), idUTF8Len
);
711 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecServiceItemAttr
), service
);
712 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecTypeItemAttr
), (FourCharCode
)'cprf');
714 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecScriptCodeItemAttr
), (sint32
)keyUsage
);
717 if (!cursor
->next(item
))
718 MacOSError::throwMe(errSecItemNotFound
);
721 *itemRef
=item
->handle();
726 /* OS X only; not exported */
728 OSStatus
SecCertificateDeletePreferenceItemWithNameAndKeyUsage(
729 CFTypeRef keychainOrArray
,
733 // when a specific key usage is passed, we'll only match & delete that pref;
734 // when a key usage of 0 is passed, all matching prefs should be deleted.
735 // maxUsages represents the most matches there could theoretically be, so
736 // cut things off at that point if we're still finding items (if they can't
737 // be deleted for some reason, we'd never break out of the loop.)
739 OSStatus status
= errSecSuccess
;
740 SecKeychainItemRef item
= NULL
;
741 int count
= 0, maxUsages
= 12;
742 while (++count
<= maxUsages
&&
743 (status
= SecCertificateFindPreferenceItemWithNameAndKeyUsage(keychainOrArray
, name
, keyUsage
, &item
)) == errSecSuccess
) {
744 status
= SecKeychainItemDelete(item
);
749 // it's not an error if the item isn't found
750 return (status
== errSecItemNotFound
) ? errSecSuccess
: status
;
753 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA) */
754 OSStatus
SecCertificateSetPreference(
755 SecCertificateRef certificate
,
757 CSSM_KEYUSE keyUsage
,
764 // treat NULL certificate as a request to clear the preference
765 // (note: if keyUsage is 0, this clears all key usage prefs for name)
766 return SecCertificateDeletePreferenceItemWithNameAndKeyUsage(NULL
, name
, keyUsage
);
769 // This macro creates an ItemImpl certificate if it does not exist
772 // determine the account attribute
774 // This attribute must be synthesized from certificate label + pref item type + key usage,
775 // as only the account and service attributes can make a generic keychain item unique.
776 // For 'iprf' type items (but not 'cprf'), we append a trailing space. This insures that
777 // we can save a certificate preference if an identity preference already exists for the
778 // given service name, and vice-versa.
779 // If the key usage is 0 (i.e. the normal case), we omit the appended key usage string.
781 CFStringRef labelStr
= nil
;
782 Certificate::required(__itemImplRef
)->inferLabel(false, &labelStr
);
784 MacOSError::throwMe(errSecDataTooLarge
); // data is "in a format which cannot be displayed"
786 CFIndex accountUTF8Len
= CFStringGetMaximumSizeForEncoding(CFStringGetLength(labelStr
), kCFStringEncodingUTF8
) + 1;
787 const char *templateStr
= "%s [key usage 0x%X]";
788 const int keyUsageMaxStrLen
= 8;
789 accountUTF8Len
+= strlen(templateStr
) + keyUsageMaxStrLen
;
790 char *accountUTF8
= (char *)malloc(accountUTF8Len
);
792 MacOSError::throwMe(errSecMemoryError
);
794 if (!CFStringGetCString(labelStr
, accountUTF8
, accountUTF8Len
-1, kCFStringEncodingUTF8
))
795 accountUTF8
[0] = (char)'\0';
797 snprintf(accountUTF8
, accountUTF8Len
-1, templateStr
, accountUTF8
, keyUsage
);
798 CssmDataContainer
account(const_cast<char *>(accountUTF8
), strlen(accountUTF8
));
802 // service attribute (name provided by the caller)
803 CFIndex serviceUTF8Len
= CFStringGetMaximumSizeForEncoding(CFStringGetLength(name
), kCFStringEncodingUTF8
) + 1;;
804 char *serviceUTF8
= (char *)malloc(serviceUTF8Len
);
806 MacOSError::throwMe(errSecMemoryError
);
808 if (!CFStringGetCString(name
, serviceUTF8
, serviceUTF8Len
-1, kCFStringEncodingUTF8
))
809 serviceUTF8
[0] = (char)'\0';
810 CssmDataContainer
service(const_cast<char *>(serviceUTF8
), strlen(serviceUTF8
));
813 // look for existing preference item, in case this is an update
814 StorageManager::KeychainList keychains
;
815 globals().storageManager
.getSearchList(keychains
);
816 KCCursor
cursor(keychains
, kSecGenericPasswordItemClass
, NULL
);
817 FourCharCode itemType
= 'cprf';
818 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecServiceItemAttr
), service
);
819 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecTypeItemAttr
), itemType
);
821 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecScriptCodeItemAttr
), (sint32
)keyUsage
);
825 Item
item(kSecGenericPasswordItemClass
, 'aapl', 0, NULL
, false);
826 bool add
= (!cursor
->next(item
));
827 // at this point, we either have a new item to add or an existing item to update
829 // set item attribute values
830 item
->setAttribute(Schema::attributeInfo(kSecServiceItemAttr
), service
);
831 item
->setAttribute(Schema::attributeInfo(kSecTypeItemAttr
), itemType
);
832 item
->setAttribute(Schema::attributeInfo(kSecAccountItemAttr
), account
);
833 item
->setAttribute(Schema::attributeInfo(kSecScriptCodeItemAttr
), (sint32
)keyUsage
);
834 item
->setAttribute(Schema::attributeInfo(kSecLabelItemAttr
), service
);
840 // generic attribute (store persistent certificate reference)
841 CFDataRef pItemRef
= nil
;
842 Certificate::required(__itemImplRef
)->copyPersistentReference(pItemRef
);
844 MacOSError::throwMe(errSecInvalidItemRef
);
846 const UInt8
*dataPtr
= CFDataGetBytePtr(pItemRef
);
847 CFIndex dataLen
= CFDataGetLength(pItemRef
);
848 CssmData
pref(const_cast<void *>(reinterpret_cast<const void *>(dataPtr
)), dataLen
);
849 item
->setAttribute(Schema::attributeInfo(kSecGenericItemAttr
), pref
);
853 Keychain keychain
= nil
;
855 keychain
= globals().storageManager
.defaultKeychain();
856 if (!keychain
->exists())
857 MacOSError::throwMe(errSecNoSuchKeychain
); // Might be deleted or not available at this time.
860 keychain
= globals().storageManager
.defaultKeychainUI(item
);
866 catch (const MacOSError
&err
) {
867 if (err
.osStatus() != errSecDuplicateItem
)
868 throw; // if item already exists, fall through to update
876 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
877 OSStatus
SecCertificateSetPreferred(
878 SecCertificateRef certificate
,
882 CSSM_KEYUSE keyUse
= ConvertArrayToKeyUsage(keyUsage
);
883 return SecCertificateSetPreference(certificate
, name
, keyUse
, NULL
);
886 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
887 CFDictionaryRef
SecCertificateCopyValues(SecCertificateRef certificate
, CFArrayRef keys
, CFErrorRef
*error
)
889 CFDictionaryRef result
= NULL
;
890 OSStatus __secapiresult
;
891 SecCertificateRef tmpcert
= NULL
;
893 // convert input to a new-style certificate reference if necessary,
894 // since the implementation of CertificateValues calls SecCertificate API functions
895 // which now assume a unified certificate reference.
896 if (SecCertificateIsItemImplInstance(certificate
)) {
897 tmpcert
= SecCertificateCreateFromItemImplInstance(certificate
);
899 if (certificate
&& !tmpcert
) {
900 tmpcert
= (SecCertificateRef
) CFRetain(certificate
);
904 CertificateValues
cv(tmpcert
);
905 result
= cv
.copyFieldValues(keys
,error
);
908 catch (const MacOSError
&err
) { __secapiresult
=err
.osStatus(); }
909 catch (const CommonError
&err
) { __secapiresult
=SecKeychainErrFromOSStatus(err
.osStatus()); }
910 catch (const std::bad_alloc
&) { __secapiresult
=errSecAllocate
; }
911 catch (...) { __secapiresult
=errSecInternalComponent
; }
912 if (tmpcert
) { CFRelease(tmpcert
); }
916 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
917 CFStringRef
SecCertificateCopyLongDescription(CFAllocatorRef alloc
, SecCertificateRef certificate
, CFErrorRef
*error
)
919 return SecCertificateCopyShortDescription(alloc
, certificate
, error
);
922 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
923 CFStringRef
SecCertificateCopyShortDescription(CFAllocatorRef alloc
, SecCertificateRef certificate
, CFErrorRef
*error
)
925 CFStringRef result
= NULL
;
926 OSStatus __secapiresult
= SecCertificateInferLabel(certificate
, &result
);
927 if (error
!=NULL
&& __secapiresult
!=errSecSuccess
)
929 *error
= CFErrorCreate(kCFAllocatorDefault
, kCFErrorDomainOSStatus
,
930 __secapiresult
? __secapiresult
: CSSM_ERRCODE_INTERNAL_ERROR
, NULL
);
935 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
936 CFDataRef
SecCertificateCopySerialNumber(SecCertificateRef certificate
, CFErrorRef
*error
)
938 CFDataRef result
= NULL
;
939 OSStatus __secapiresult
;
942 CertificateValues
cv(certificate
);
943 result
= cv
.copySerialNumber(error
);
946 catch (const MacOSError
&err
) { __secapiresult
=err
.osStatus(); }
947 catch (const CommonError
&err
) { __secapiresult
=SecKeychainErrFromOSStatus(err
.osStatus()); }
948 catch (const std::bad_alloc
&) { __secapiresult
=errSecAllocate
; }
949 catch (...) { __secapiresult
=errSecInternalComponent
; }
953 /* OS X only: __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_7, __MAC_10_12_4, __IPHONE_NA, __IPHONE_NA) */
954 CFDataRef
SecCertificateCopyNormalizedIssuerContent(SecCertificateRef certificate
, CFErrorRef
*error
)
956 CFDataRef result
= NULL
;
957 OSStatus __secapiresult
;
960 CertificateValues
cv(certificate
);
961 result
= cv
.copyNormalizedIssuerContent(error
);
964 catch (const MacOSError
&err
) { __secapiresult
=err
.osStatus(); }
965 catch (const CommonError
&err
) { __secapiresult
=SecKeychainErrFromOSStatus(err
.osStatus()); }
966 catch (const std::bad_alloc
&) { __secapiresult
=errSecAllocate
; }
967 catch (...) { __secapiresult
=errSecInternalComponent
; }
971 /* OS X only: __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_7, __MAC_10_12_4, __IPHONE_NA, __IPHONE_NA) */
972 CFDataRef
SecCertificateCopyNormalizedSubjectContent(SecCertificateRef certificate
, CFErrorRef
*error
)
974 CFDataRef result
= NULL
;
975 OSStatus __secapiresult
;
978 CertificateValues
cv(certificate
);
979 result
= cv
.copyNormalizedSubjectContent(error
);
982 catch (const MacOSError
&err
) { __secapiresult
=err
.osStatus(); }
983 catch (const CommonError
&err
) { __secapiresult
=SecKeychainErrFromOSStatus(err
.osStatus()); }
984 catch (const std::bad_alloc
&) { __secapiresult
=errSecAllocate
; }
985 catch (...) { __secapiresult
=errSecInternalComponent
; }
989 /* OS X only: __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_7, __MAC_10_9, __IPHONE_NA, __IPHONE_NA) */
990 bool SecCertificateIsValidX(SecCertificateRef certificate
, CFAbsoluteTime verifyTime
)
993 * deprecated function name
995 return SecCertificateIsValid(certificate
, verifyTime
);
999 CFDataRef
SecCertificateCopyPublicKeySHA1DigestFromCertificateData(CFAllocatorRef allocator
,
1000 CFDataRef der_certificate
)
1002 CFDataRef result
= NULL
;
1003 SecCertificateRef iosCertRef
= SecCertificateCreateWithData(allocator
, der_certificate
);
1004 if (NULL
== iosCertRef
)
1009 result
= SecCertificateCopyPublicKeySHA1Digest(iosCertRef
);
1010 CFRelease(iosCertRef
);