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"
48 #include "SecCertificateP.h"
49 #include "SecCertificatePrivP.h"
51 #include "AppleBaselineEscrowCertificates.h"
54 OSStatus
SecCertificateGetCLHandle_legacy(SecCertificateRef certificate
, CSSM_CL_HANDLE
*clHandle
);
55 extern CSSM_KEYUSE
ConvertArrayToKeyUsage(CFArrayRef usage
);
57 #define SEC_CONST_DECL(k,v) const CFStringRef k = CFSTR(v);
59 SEC_CONST_DECL (kSecCertificateProductionEscrowKey
, "ProductionEscrowKey");
60 SEC_CONST_DECL (kSecCertificateProductionPCSEscrowKey
, "ProductionPCSEscrowKey");
61 SEC_CONST_DECL (kSecCertificateEscrowFileName
, "AppleESCertificates");
64 using namespace CssmClient
;
66 CFTypeID
static SecCertificateGetTypeID_osx(void)
70 return gTypes().Certificate
.typeID
;
72 END_SECAPI1(_kCFRuntimeNotATypeID
)
76 SecCertificateIsItemImplInstance(SecCertificateRef certificate
)
78 if (certificate
== NULL
) {
82 CFTypeID typeID
= CFGetTypeID(certificate
);
84 #if 0 /* debug code to verify type IDs */
85 syslog(LOG_ERR
, "SecCertificate typeID=%d [STU=%d, OSX=%d, SKI=%d]",
87 (int)SecCertificateGetTypeID(),
88 (int)SecCertificateGetTypeID_osx(),
89 (int)SecKeychainItemGetTypeID());
91 if (typeID
== _kCFRuntimeNotATypeID
) {
95 return (typeID
== SecCertificateGetTypeID_osx() ||
96 typeID
== SecKeychainItemGetTypeID()) ? true : false;
99 /* convert a new-world SecCertificateRef to an old-world ItemImpl instance */
101 SecCertificateCreateItemImplInstance(SecCertificateRef certificate
)
106 SecCertificateRef implCertRef
= (SecCertificateRef
) SecCertificateCopyKeychainItem(certificate
);
110 CFDataRef data
= SecCertificateCopyData(certificate
);
115 CSSM_DATA cssmCertData
;
116 cssmCertData
.Length
= (data
) ? (CSSM_SIZE
)CFDataGetLength(data
) : 0;
117 cssmCertData
.Data
= (data
) ? (uint8
*)CFDataGetBytePtr(data
) : NULL
;
119 SecPointer
<Certificate
> certificatePtr(new Certificate(cssmCertData
, CSSM_CERT_X_509v3
, CSSM_CERT_ENCODING_DER
));
120 implCertRef
= certificatePtr
->handle();
127 /* convert an old-world ItemImpl instance to a new-world SecCertificateRef */
129 SecCertificateCreateFromItemImplInstance(SecCertificateRef certificate
)
134 SecCertificateRef result
= NULL
;
135 CFDataRef data
= NULL
;
137 CssmData certData
= Certificate::required(certificate
)->data();
138 if (certData
.Data
&& certData
.Length
) {
139 data
= CFDataCreate(NULL
, certData
.Data
, certData
.Length
);
142 if (certData
.Data
&& !certData
.Length
) {
143 /* zero-length certs can exist, so don't bother logging this */
146 syslog(LOG_ERR
, "WARNING: SecKeychainSearchCopyNext failed to retrieve certificate data (length=%ld, data=0x%lX)",
147 (long)certData
.Length
, (uintptr_t)certData
.Data
);
154 result
= SecCertificateCreateWithKeychainItem(NULL
, data
, certificate
);
161 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
163 SecCertificateCreateFromData(const CSSM_DATA
*data
, CSSM_CERT_TYPE type
, CSSM_CERT_ENCODING encoding
, SecCertificateRef
*certificate
)
165 /* bridge to support old functionality */
166 if (!data
|| !data
->Data
|| !data
->Length
|| !certificate
) {
169 SecCertificateRef certRef
= NULL
;
171 // <rdar://problem/24403998> REG: Adobe {Photoshop, InDesign} CC(2015) crashes on launch
172 // If you take the length that SecKeychainItemCopyContent gives you (a Uint32) and assign it incorrectly
173 // to a CSSM_DATA Length field (a CSSM_SIZE, i.e., a size_t), the upper 32 bits aren't set. If those bits
174 // are non-zero, the length is incredibly wrong.
176 // Assume that there will not exist a certificate > 4GiB, and fake this length field.
177 CSSM_SIZE length
= data
->Length
& 0xfffffffful
;
179 CFDataRef dataRef
= CFDataCreate(NULL
, data
->Data
, length
);
181 certRef
= SecCertificateCreateWithData(NULL
, dataRef
);
184 *certificate
= certRef
;
185 return (certRef
) ? errSecSuccess
: errSecUnknownFormat
;
188 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA) */
190 SecCertificateAddToKeychain(SecCertificateRef certificate
, SecKeychainRef keychain
)
192 // This macro creates an ItemImpl certificate if it does not exist
195 Item
item(Certificate::required(__itemImplRef
));
196 Keychain::optional(keychain
)->add(item
);
201 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
203 SecCertificateGetData(SecCertificateRef certificate
, CSSM_DATA_PTR data
)
207 if (!certificate
|| !data
) {
208 __secapiresult
=errSecParam
;
210 else if (SecCertificateIsItemImplInstance(certificate
)) {
211 Required(data
) = Certificate::required(certificate
)->data();
214 data
->Length
= (CSSM_SIZE
)SecCertificateGetLength(certificate
);
215 data
->Data
= (uint8
*)SecCertificateGetBytePtr(certificate
);
221 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
223 SecCertificateGetType(SecCertificateRef certificate
, CSSM_CERT_TYPE
*certificateType
)
225 // This macro creates an ItemImpl certificate if it does not exist
228 Required(certificateType
) = Certificate::required(__itemImplRef
)->type();
233 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
235 SecCertificateGetSubject(SecCertificateRef certificate
, const CSSM_X509_NAME
**subject
)
237 // This macro creates an ItemImpl certificate if it does not exist
240 Required(subject
) = Certificate::required(__itemImplRef
)->subjectName();
245 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
247 SecCertificateGetIssuer(SecCertificateRef certificate
, const CSSM_X509_NAME
**issuer
)
249 // This macro creates an ItemImpl certificate if it does not exist
252 Required(issuer
) = Certificate::required(__itemImplRef
)->issuerName();
257 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
259 SecCertificateGetCLHandle(SecCertificateRef certificate
, CSSM_CL_HANDLE
*clHandle
)
261 // This macro creates an ItemImpl certificate if it does not exist
264 Required(clHandle
) = Certificate::required(__itemImplRef
)->clHandle();
269 /* private function; assumes input is old-style ItemImpl certificate reference,
270 and does not release that certificate reference!
273 SecCertificateGetCLHandle_legacy(SecCertificateRef certificate
, CSSM_CL_HANDLE
*clHandle
)
277 Required(clHandle
) = Certificate::required(certificate
)->clHandle();
283 * Private API to infer a display name for a SecCertificateRef which
284 * may or may not be in a keychain.
289 SecCertificateInferLabel(SecCertificateRef certificate
, CFStringRef
*label
)
291 // This macro creates an ItemImpl certificate if it does not exist
294 Certificate::required(__itemImplRef
)->inferLabel(false, &Required(label
));
299 /* OS X only (note: iOS version has different arguments and return value) */
301 SecCertificateCopyPublicKey(SecCertificateRef certificate
, SecKeyRef
*key
)
303 // This macro creates an ItemImpl certificate if it does not exist
306 Required(key
) = Certificate::required(__itemImplRef
)->publicKey()->handle();
311 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
313 SecCertificateGetAlgorithmID(SecCertificateRef certificate
, const CSSM_X509_ALGORITHM_IDENTIFIER
**algid
)
315 // This macro creates an ItemImpl certificate if it does not exist
318 Required(algid
) = Certificate::required(__itemImplRef
)->algorithmID();
325 SecCertificateCopySubjectComponent(SecCertificateRef certificate
, const CSSM_OID
*component
, CFStringRef
*result
)
327 // This macro creates an ItemImpl certificate if it does not exist
330 Required(result
) = Certificate::required(__itemImplRef
)->distinguishedName(&CSSMOID_X509V1SubjectNameCStruct
, component
);
335 /* OS X only; deprecated SPI */
337 SecCertificateGetCommonName(SecCertificateRef certificate
, CFStringRef
*commonName
)
339 // deprecated SPI signature; replaced by SecCertificateCopyCommonName
340 return SecCertificateCopyCommonName(certificate
, commonName
);
343 /* OS X only; deprecated SPI */
345 SecCertificateGetEmailAddress(SecCertificateRef certificate
, CFStringRef
*emailAddress
)
347 // This macro creates an ItemImpl certificate if it does not exist
350 Required(emailAddress
) = Certificate::required(__itemImplRef
)->copyFirstEmailAddress();
357 SecCertificateCopyEmailAddresses(SecCertificateRef certificate
, CFArrayRef
*emailAddresses
)
359 // This macro creates an ItemImpl certificate if it does not exist
362 Required(emailAddresses
) = Certificate::required(__itemImplRef
)->copyEmailAddresses();
367 /* Return a zero terminated list of CSSM_DATA_PTR's with the values of the field specified by field.
368 * Caller must call releaseFieldValues to free the storage allocated by this call.
373 SecCertificateCopyFieldValues(SecCertificateRef certificate
, const CSSM_OID
*field
, CSSM_DATA_PTR
**fieldValues
)
375 // This macro creates an ItemImpl certificate if it does not exist
378 Required(fieldValues
) = Certificate::required(__itemImplRef
)->copyFieldValues(Required(field
));
385 SecCertificateReleaseFieldValues(SecCertificateRef certificate
, const CSSM_OID
*field
, CSSM_DATA_PTR
*fieldValues
)
387 // This macro creates an ItemImpl certificate if it does not exist
390 Certificate::required(__itemImplRef
)->releaseFieldValues(Required(field
), fieldValues
);
397 SecCertificateCopyFirstFieldValue(SecCertificateRef certificate
, const CSSM_OID
*field
, CSSM_DATA_PTR
*fieldValue
)
399 // This macro creates an ItemImpl certificate if it does not exist
402 Required(fieldValue
) = Certificate::required(__itemImplRef
)->copyFirstFieldValue(Required(field
));
409 SecCertificateReleaseFirstFieldValue(SecCertificateRef certificate
, const CSSM_OID
*field
, CSSM_DATA_PTR fieldValue
)
411 // This macro creates an ItemImpl certificate if it does not exist
414 Certificate::required(__itemImplRef
)->releaseFieldValue(Required(field
), fieldValue
);
421 SecCertificateFindByIssuerAndSN(CFTypeRef keychainOrArray
,const CSSM_DATA
*issuer
,
422 const CSSM_DATA
*serialNumber
, SecCertificateRef
*certificate
)
424 if (issuer
&& serialNumber
) {
425 CFRef
<CFMutableDictionaryRef
> query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
426 CFDictionarySetValue(query
, kSecClass
, kSecClassCertificate
);
427 CFDictionarySetValue(query
, kSecReturnRef
, kCFBooleanTrue
);
428 CFDictionarySetValue(query
, kSecAttrNoLegacy
, kCFBooleanTrue
);
430 CFRef
<CFDataRef
> issuerData
= CFDataCreateWithBytesNoCopy(kCFAllocatorDefault
, (const UInt8
*)issuer
->Data
, issuer
->Length
, kCFAllocatorNull
);
431 CFDictionarySetValue(query
, kSecAttrIssuer
, issuerData
);
433 CFRef
<CFDataRef
> serialNumberData
= CFDataCreateWithBytesNoCopy(kCFAllocatorDefault
, (const UInt8
*)serialNumber
->Data
, serialNumber
->Length
, kCFAllocatorNull
);
434 CFDictionarySetValue(query
, kSecAttrSerialNumber
, serialNumberData
);
436 OSStatus status
= SecItemCopyMatching(query
, (CFTypeRef
*)certificate
);
437 if (status
== errSecSuccess
) {
444 StorageManager::KeychainList keychains
;
445 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
446 Required(certificate
) = Certificate::findByIssuerAndSN(keychains
, CssmData::required(issuer
), CssmData::required(serialNumber
))->handle();
448 // convert ItemImpl-based SecCertificateRef to new-world version before returning
449 CssmData certData
= Certificate::required(*certificate
)->data();
450 CFRef
<CFDataRef
> cfData(CFDataCreate(NULL
, certData
.Data
, certData
.Length
));
451 SecCertificateRef tmpRef
= *certificate
;
452 *certificate
= SecCertificateCreateWithData(NULL
, cfData
);
460 SecCertificateFindBySubjectKeyID(CFTypeRef keychainOrArray
, const CSSM_DATA
*subjectKeyID
,
461 SecCertificateRef
*certificate
)
464 CFRef
<CFMutableDictionaryRef
> query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
465 CFDictionarySetValue(query
, kSecClass
, kSecClassCertificate
);
466 CFDictionarySetValue(query
, kSecReturnRef
, kCFBooleanTrue
);
467 CFDictionarySetValue(query
, kSecAttrNoLegacy
, kCFBooleanTrue
);
469 CFRef
<CFDataRef
> subjectKeyIDData
= CFDataCreateWithBytesNoCopy(kCFAllocatorDefault
, (const UInt8
*)subjectKeyID
->Data
, subjectKeyID
->Length
, kCFAllocatorNull
);
470 CFDictionarySetValue(query
, kSecAttrSubjectKeyID
, subjectKeyIDData
);
472 OSStatus status
= SecItemCopyMatching(query
, (CFTypeRef
*)certificate
);
473 if (status
== errSecSuccess
) {
480 StorageManager::KeychainList keychains
;
481 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
482 Required(certificate
) = Certificate::findBySubjectKeyID(keychains
, CssmData::required(subjectKeyID
))->handle();
484 // convert ItemImpl-based SecCertificateRef to new-world version before returning
485 CssmData certData
= Certificate::required(*certificate
)->data();
486 CFRef
<CFDataRef
> cfData(CFDataCreate(NULL
, certData
.Data
, certData
.Length
));
487 SecCertificateRef tmpRef
= *certificate
;
488 *certificate
= SecCertificateCreateWithData(NULL
, cfData
);
496 SecCertificateFindByEmail(CFTypeRef keychainOrArray
, const char *emailAddress
, SecCertificateRef
*certificate
)
499 CFRef
<CFMutableDictionaryRef
> query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
500 CFDictionarySetValue(query
, kSecClass
, kSecClassCertificate
);
501 CFDictionarySetValue(query
, kSecReturnRef
, kCFBooleanTrue
);
502 CFDictionarySetValue(query
, kSecAttrNoLegacy
, kCFBooleanTrue
);
504 CFRef
<CFStringRef
> emailAddressString
= CFStringCreateWithCString(kCFAllocatorDefault
, emailAddress
, kCFStringEncodingUTF8
);
505 CFTypeRef keys
[] = { kSecPolicyName
};
506 CFTypeRef values
[] = { emailAddressString
};
507 CFRef
<CFDictionaryRef
> properties
= CFDictionaryCreate(kCFAllocatorDefault
, keys
, values
, 1, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
508 CFRef
<SecPolicyRef
> policy
= SecPolicyCreateWithProperties(kSecPolicyAppleSMIME
, properties
);
509 CFDictionarySetValue(query
, kSecMatchPolicy
, policy
);
511 OSStatus status
= SecItemCopyMatching(query
, (CFTypeRef
*)certificate
);
512 if (status
== errSecSuccess
) {
519 StorageManager::KeychainList keychains
;
520 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
521 Required(certificate
) = Certificate::findByEmail(keychains
, emailAddress
)->handle();
523 // convert ItemImpl-based SecCertificateRef to new-world version before returning
524 CssmData certData
= Certificate::required(*certificate
)->data();
525 CFRef
<CFDataRef
> cfData(CFDataCreate(NULL
, certData
.Data
, certData
.Length
));
526 SecCertificateRef tmpRef
= *certificate
;
527 *certificate
= SecCertificateCreateWithData(NULL
, cfData
);
535 SecKeychainSearchCreateForCertificateByIssuerAndSN(CFTypeRef keychainOrArray
, const CSSM_DATA
*issuer
,
536 const CSSM_DATA
*serialNumber
, SecKeychainSearchRef
*searchRef
)
542 StorageManager::KeychainList keychains
;
543 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
544 KCCursor
cursor(Certificate::cursorForIssuerAndSN(keychains
, CssmData::required(issuer
), CssmData::required(serialNumber
)));
545 *searchRef
= cursor
->handle();
552 SecKeychainSearchCreateForCertificateByIssuerAndSN_CF(CFTypeRef keychainOrArray
, CFDataRef issuer
,
553 CFDataRef serialNumber
, SecKeychainSearchRef
*searchRef
)
559 StorageManager::KeychainList keychains
;
560 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
562 Required(serialNumber
);
563 KCCursor
cursor(Certificate::cursorForIssuerAndSN_CF(keychains
, issuer
, serialNumber
));
564 *searchRef
= cursor
->handle();
571 SecKeychainSearchCreateForCertificateBySubjectKeyID(CFTypeRef keychainOrArray
, const CSSM_DATA
*subjectKeyID
,
572 SecKeychainSearchRef
*searchRef
)
578 StorageManager::KeychainList keychains
;
579 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
580 KCCursor
cursor(Certificate::cursorForSubjectKeyID(keychains
, CssmData::required(subjectKeyID
)));
581 *searchRef
= cursor
->handle();
588 SecKeychainSearchCreateForCertificateByEmail(CFTypeRef keychainOrArray
, const char *emailAddress
,
589 SecKeychainSearchRef
*searchRef
)
595 StorageManager::KeychainList keychains
;
596 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
597 KCCursor
cursor(Certificate::cursorForEmail(keychains
, emailAddress
));
598 *searchRef
= cursor
->handle();
605 SecDigestGetData (CSSM_ALGORITHMS alg
, CSSM_DATA
* digest
, const CSSM_DATA
* data
)
609 if (!digest
|| !digest
->Data
|| !digest
->Length
|| !data
|| !data
->Data
|| !data
->Length
)
612 CSP
csp(gGuidAppleCSP
);
613 Digest
context(csp
, alg
);
614 CssmData
input(data
->Data
, data
->Length
);
615 CssmData
output(digest
->Data
, digest
->Length
);
617 context
.digest(input
, output
);
618 digest
->Length
= output
.length();
624 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
626 SecCertificateCopyPreference(
628 CSSM_KEYUSE keyUsage
,
629 SecCertificateRef
*certificate
)
634 Required(certificate
);
635 StorageManager::KeychainList keychains
;
636 globals().storageManager
.getSearchList(keychains
);
637 KCCursor
cursor(keychains
, kSecGenericPasswordItemClass
, NULL
);
639 char idUTF8
[MAXPATHLEN
];
640 if (!CFStringGetCString(name
, idUTF8
, sizeof(idUTF8
)-1, kCFStringEncodingUTF8
))
641 idUTF8
[0] = (char)'\0';
642 CssmData
service(const_cast<char *>(idUTF8
), strlen(idUTF8
));
643 FourCharCode itemType
= 'cprf';
644 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecServiceItemAttr
), service
);
645 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecTypeItemAttr
), itemType
);
647 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecScriptCodeItemAttr
), (sint32
)keyUsage
);
650 if (!cursor
->next(prefItem
))
651 MacOSError::throwMe(errSecItemNotFound
);
653 // get persistent certificate reference
654 SecKeychainAttribute itemAttrs
[] = { { kSecGenericItemAttr
, 0, NULL
} };
655 SecKeychainAttributeList itemAttrList
= { sizeof(itemAttrs
) / sizeof(itemAttrs
[0]), itemAttrs
};
656 prefItem
->getContent(NULL
, &itemAttrList
, NULL
, NULL
);
658 // find certificate, given persistent reference data
659 CFDataRef pItemRef
= CFDataCreateWithBytesNoCopy(NULL
, (const UInt8
*)itemAttrs
[0].data
, itemAttrs
[0].length
, kCFAllocatorNull
);
660 SecKeychainItemRef certItemRef
= nil
;
661 OSStatus status
= SecKeychainItemCopyFromPersistentReference(pItemRef
, &certItemRef
); //%%% need to make this a method of ItemImpl
662 prefItem
->freeContent(&itemAttrList
, NULL
);
668 *certificate
= (SecCertificateRef
)certItemRef
;
670 if (certItemRef
&& (CFGetTypeID(certItemRef
) == SecIdentityGetTypeID())) {
671 // SecKeychainItemCopyFromPersistentReference handed out an identity reference
673 status
= SecIdentityCopyCertificate((SecIdentityRef
)certItemRef
, certificate
);
674 CFRelease(certItemRef
);
683 SecCertificateCopyPreferred(
687 // This function will look for a matching preference in the following order:
688 // - matches the name and the supplied key use
689 // - matches the name and the special 'ANY' key use
690 // - matches the name with no key usage constraint
692 SecCertificateRef certRef
= NULL
;
693 CSSM_KEYUSE keyUse
= ConvertArrayToKeyUsage(keyUsage
);
694 OSStatus status
= SecCertificateCopyPreference(name
, keyUse
, &certRef
);
695 if (status
!= errSecSuccess
&& keyUse
!= CSSM_KEYUSE_ANY
)
696 status
= SecCertificateCopyPreference(name
, CSSM_KEYUSE_ANY
, &certRef
);
697 if (status
!= errSecSuccess
&& keyUse
!= 0)
698 status
= SecCertificateCopyPreference(name
, 0, &certRef
);
703 /* OS X only; not exported */
705 SecCertificateFindPreferenceItemWithNameAndKeyUsage(
706 CFTypeRef keychainOrArray
,
709 SecKeychainItemRef
*itemRef
)
713 StorageManager::KeychainList keychains
;
714 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
715 KCCursor
cursor(keychains
, kSecGenericPasswordItemClass
, NULL
);
717 char idUTF8
[MAXPATHLEN
];
718 idUTF8
[0] = (char)'\0';
721 if (!CFStringGetCString(name
, idUTF8
, sizeof(idUTF8
)-1, kCFStringEncodingUTF8
))
722 idUTF8
[0] = (char)'\0';
724 size_t idUTF8Len
= strlen(idUTF8
);
726 MacOSError::throwMe(errSecParam
);
728 CssmData
service(const_cast<char *>(idUTF8
), idUTF8Len
);
729 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecServiceItemAttr
), service
);
730 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecTypeItemAttr
), (FourCharCode
)'cprf');
732 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecScriptCodeItemAttr
), (sint32
)keyUsage
);
735 if (!cursor
->next(item
))
736 MacOSError::throwMe(errSecItemNotFound
);
739 *itemRef
=item
->handle();
744 /* OS X only; not exported */
746 OSStatus
SecCertificateDeletePreferenceItemWithNameAndKeyUsage(
747 CFTypeRef keychainOrArray
,
751 // when a specific key usage is passed, we'll only match & delete that pref;
752 // when a key usage of 0 is passed, all matching prefs should be deleted.
753 // maxUsages represents the most matches there could theoretically be, so
754 // cut things off at that point if we're still finding items (if they can't
755 // be deleted for some reason, we'd never break out of the loop.)
757 OSStatus status
= errSecSuccess
;
758 SecKeychainItemRef item
= NULL
;
759 int count
= 0, maxUsages
= 12;
760 while (++count
<= maxUsages
&&
761 (status
= SecCertificateFindPreferenceItemWithNameAndKeyUsage(keychainOrArray
, name
, keyUsage
, &item
)) == errSecSuccess
) {
762 status
= SecKeychainItemDelete(item
);
767 // it's not an error if the item isn't found
768 return (status
== errSecItemNotFound
) ? errSecSuccess
: status
;
771 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA) */
772 OSStatus
SecCertificateSetPreference(
773 SecCertificateRef certificate
,
775 CSSM_KEYUSE keyUsage
,
782 // treat NULL certificate as a request to clear the preference
783 // (note: if keyUsage is 0, this clears all key usage prefs for name)
784 return SecCertificateDeletePreferenceItemWithNameAndKeyUsage(NULL
, name
, keyUsage
);
787 // This macro creates an ItemImpl certificate if it does not exist
790 // determine the account attribute
792 // This attribute must be synthesized from certificate label + pref item type + key usage,
793 // as only the account and service attributes can make a generic keychain item unique.
794 // For 'iprf' type items (but not 'cprf'), we append a trailing space. This insures that
795 // we can save a certificate preference if an identity preference already exists for the
796 // given service name, and vice-versa.
797 // If the key usage is 0 (i.e. the normal case), we omit the appended key usage string.
799 CFStringRef labelStr
= nil
;
800 Certificate::required(__itemImplRef
)->inferLabel(false, &labelStr
);
802 MacOSError::throwMe(errSecDataTooLarge
); // data is "in a format which cannot be displayed"
804 CFIndex accountUTF8Len
= CFStringGetMaximumSizeForEncoding(CFStringGetLength(labelStr
), kCFStringEncodingUTF8
) + 1;
805 const char *templateStr
= "%s [key usage 0x%X]";
806 const int keyUsageMaxStrLen
= 8;
807 accountUTF8Len
+= strlen(templateStr
) + keyUsageMaxStrLen
;
808 char accountUTF8
[accountUTF8Len
];
809 if (!CFStringGetCString(labelStr
, accountUTF8
, accountUTF8Len
-1, kCFStringEncodingUTF8
))
810 accountUTF8
[0] = (char)'\0';
812 snprintf(accountUTF8
, accountUTF8Len
-1, templateStr
, accountUTF8
, keyUsage
);
813 CssmData
account(const_cast<char *>(accountUTF8
), strlen(accountUTF8
));
816 // service attribute (name provided by the caller)
817 CFIndex serviceUTF8Len
= CFStringGetMaximumSizeForEncoding(CFStringGetLength(name
), kCFStringEncodingUTF8
) + 1;;
818 char serviceUTF8
[serviceUTF8Len
];
819 if (!CFStringGetCString(name
, serviceUTF8
, serviceUTF8Len
-1, kCFStringEncodingUTF8
))
820 serviceUTF8
[0] = (char)'\0';
821 CssmData
service(const_cast<char *>(serviceUTF8
), strlen(serviceUTF8
));
823 // look for existing preference item, in case this is an update
824 StorageManager::KeychainList keychains
;
825 globals().storageManager
.getSearchList(keychains
);
826 KCCursor
cursor(keychains
, kSecGenericPasswordItemClass
, NULL
);
827 FourCharCode itemType
= 'cprf';
828 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecServiceItemAttr
), service
);
829 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecTypeItemAttr
), itemType
);
831 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecScriptCodeItemAttr
), (sint32
)keyUsage
);
835 Item
item(kSecGenericPasswordItemClass
, 'aapl', 0, NULL
, false);
836 bool add
= (!cursor
->next(item
));
837 // at this point, we either have a new item to add or an existing item to update
839 // set item attribute values
840 item
->setAttribute(Schema::attributeInfo(kSecServiceItemAttr
), service
);
841 item
->setAttribute(Schema::attributeInfo(kSecTypeItemAttr
), itemType
);
842 item
->setAttribute(Schema::attributeInfo(kSecAccountItemAttr
), account
);
843 item
->setAttribute(Schema::attributeInfo(kSecScriptCodeItemAttr
), (sint32
)keyUsage
);
844 item
->setAttribute(Schema::attributeInfo(kSecLabelItemAttr
), service
);
850 // generic attribute (store persistent certificate reference)
851 CFDataRef pItemRef
= nil
;
852 Certificate::required(__itemImplRef
)->copyPersistentReference(pItemRef
);
854 MacOSError::throwMe(errSecInvalidItemRef
);
856 const UInt8
*dataPtr
= CFDataGetBytePtr(pItemRef
);
857 CFIndex dataLen
= CFDataGetLength(pItemRef
);
858 CssmData
pref(const_cast<void *>(reinterpret_cast<const void *>(dataPtr
)), dataLen
);
859 item
->setAttribute(Schema::attributeInfo(kSecGenericItemAttr
), pref
);
863 Keychain keychain
= nil
;
865 keychain
= globals().storageManager
.defaultKeychain();
866 if (!keychain
->exists())
867 MacOSError::throwMe(errSecNoSuchKeychain
); // Might be deleted or not available at this time.
870 keychain
= globals().storageManager
.defaultKeychainUI(item
);
876 catch (const MacOSError
&err
) {
877 if (err
.osStatus() != errSecDuplicateItem
)
878 throw; // if item already exists, fall through to update
886 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
887 OSStatus
SecCertificateSetPreferred(
888 SecCertificateRef certificate
,
892 CSSM_KEYUSE keyUse
= ConvertArrayToKeyUsage(keyUsage
);
893 return SecCertificateSetPreference(certificate
, name
, keyUse
, NULL
);
896 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
897 CFDictionaryRef
SecCertificateCopyValues(SecCertificateRef certificate
, CFArrayRef keys
, CFErrorRef
*error
)
899 CFDictionaryRef result
= NULL
;
900 OSStatus __secapiresult
;
901 SecCertificateRef tmpcert
= NULL
;
903 // convert input to a new-style certificate reference if necessary,
904 // since the implementation of CertificateValues calls SecCertificate API functions
905 // which now assume a unified certificate reference.
906 if (SecCertificateIsItemImplInstance(certificate
)) {
907 tmpcert
= SecCertificateCreateFromItemImplInstance(certificate
);
909 if (certificate
&& !tmpcert
) {
910 tmpcert
= (SecCertificateRef
) CFRetain(certificate
);
914 CertificateValues
cv(tmpcert
);
915 result
= cv
.copyFieldValues(keys
,error
);
918 catch (const MacOSError
&err
) { __secapiresult
=err
.osStatus(); }
919 catch (const CommonError
&err
) { __secapiresult
=SecKeychainErrFromOSStatus(err
.osStatus()); }
920 catch (const std::bad_alloc
&) { __secapiresult
=errSecAllocate
; }
921 catch (...) { __secapiresult
=errSecInternalComponent
; }
922 if (tmpcert
) { CFRelease(tmpcert
); }
926 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
927 CFStringRef
SecCertificateCopyLongDescription(CFAllocatorRef alloc
, SecCertificateRef certificate
, CFErrorRef
*error
)
929 return SecCertificateCopyShortDescription(alloc
, certificate
, error
);
932 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
933 CFStringRef
SecCertificateCopyShortDescription(CFAllocatorRef alloc
, SecCertificateRef certificate
, CFErrorRef
*error
)
935 CFStringRef result
= NULL
;
936 OSStatus __secapiresult
= SecCertificateInferLabel(certificate
, &result
);
937 if (error
!=NULL
&& __secapiresult
!=errSecSuccess
)
939 *error
= CFErrorCreate(kCFAllocatorDefault
, kCFErrorDomainOSStatus
,
940 __secapiresult
? __secapiresult
: CSSM_ERRCODE_INTERNAL_ERROR
, NULL
);
945 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
946 CFDataRef
SecCertificateCopySerialNumber(SecCertificateRef certificate
, CFErrorRef
*error
)
948 CFDataRef result
= NULL
;
949 OSStatus __secapiresult
;
952 CertificateValues
cv(certificate
);
953 result
= cv
.copySerialNumber(error
);
956 catch (const MacOSError
&err
) { __secapiresult
=err
.osStatus(); }
957 catch (const CommonError
&err
) { __secapiresult
=SecKeychainErrFromOSStatus(err
.osStatus()); }
958 catch (const std::bad_alloc
&) { __secapiresult
=errSecAllocate
; }
959 catch (...) { __secapiresult
=errSecInternalComponent
; }
963 /* OS X only: __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_7, __MAC_10_12_4, __IPHONE_NA, __IPHONE_NA) */
964 CFDataRef
SecCertificateCopyNormalizedIssuerContent(SecCertificateRef certificate
, CFErrorRef
*error
)
966 CFDataRef result
= NULL
;
967 OSStatus __secapiresult
;
970 CertificateValues
cv(certificate
);
971 result
= cv
.copyNormalizedIssuerContent(error
);
974 catch (const MacOSError
&err
) { __secapiresult
=err
.osStatus(); }
975 catch (const CommonError
&err
) { __secapiresult
=SecKeychainErrFromOSStatus(err
.osStatus()); }
976 catch (const std::bad_alloc
&) { __secapiresult
=errSecAllocate
; }
977 catch (...) { __secapiresult
=errSecInternalComponent
; }
981 /* OS X only: __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_7, __MAC_10_12_4, __IPHONE_NA, __IPHONE_NA) */
982 CFDataRef
SecCertificateCopyNormalizedSubjectContent(SecCertificateRef certificate
, CFErrorRef
*error
)
984 CFDataRef result
= NULL
;
985 OSStatus __secapiresult
;
988 CertificateValues
cv(certificate
);
989 result
= cv
.copyNormalizedSubjectContent(error
);
992 catch (const MacOSError
&err
) { __secapiresult
=err
.osStatus(); }
993 catch (const CommonError
&err
) { __secapiresult
=SecKeychainErrFromOSStatus(err
.osStatus()); }
994 catch (const std::bad_alloc
&) { __secapiresult
=errSecAllocate
; }
995 catch (...) { __secapiresult
=errSecInternalComponent
; }
999 /* OS X only: __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_7, __MAC_10_9, __IPHONE_NA, __IPHONE_NA) */
1000 bool SecCertificateIsValidX(SecCertificateRef certificate
, CFAbsoluteTime verifyTime
)
1003 * deprecated function name
1005 return SecCertificateIsValid(certificate
, verifyTime
);