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 "LegacyAPICounts.h"
50 OSStatus
SecCertificateGetCLHandle_legacy(SecCertificateRef certificate
, CSSM_CL_HANDLE
*clHandle
);
51 extern CSSM_KEYUSE
ConvertArrayToKeyUsage(CFArrayRef usage
);
56 using namespace CssmClient
;
58 CFTypeID
static SecCertificateGetTypeID_osx(void)
62 return gTypes().Certificate
.typeID
;
64 END_SECAPI1(_kCFRuntimeNotATypeID
)
68 SecCertificateIsItemImplInstance(SecCertificateRef certificate
)
70 if (certificate
== NULL
) {
74 CFTypeID typeID
= CFGetTypeID(certificate
);
76 if (typeID
== _kCFRuntimeNotATypeID
) {
80 return (typeID
== SecCertificateGetTypeID_osx() ||
81 typeID
== SecKeychainItemGetTypeID()) ? true : false;
84 /* convert a new-world SecCertificateRef to an old-world ItemImpl instance */
86 SecCertificateCreateItemImplInstance(SecCertificateRef certificate
)
91 SecCertificateRef implCertRef
= (SecCertificateRef
) SecCertificateCopyKeychainItem(certificate
);
95 CFDataRef data
= SecCertificateCopyData(certificate
);
100 CSSM_DATA cssmCertData
;
101 cssmCertData
.Length
= (data
) ? (CSSM_SIZE
)CFDataGetLength(data
) : 0;
102 cssmCertData
.Data
= (data
) ? (uint8
*)CFDataGetBytePtr(data
) : NULL
;
104 SecPointer
<Certificate
> certificatePtr(new Certificate(cssmCertData
, CSSM_CERT_X_509v3
, CSSM_CERT_ENCODING_DER
));
105 implCertRef
= certificatePtr
->handle();
112 /* convert an old-world ItemImpl instance to a new-world SecCertificateRef */
114 SecCertificateCreateFromItemImplInstance(SecCertificateRef certificate
)
119 SecCertificateRef result
= NULL
;
120 CFDataRef data
= NULL
;
122 CssmData certData
= Certificate::required(certificate
)->data();
123 if (certData
.Data
&& certData
.Length
) {
124 data
= CFDataCreate(NULL
, certData
.Data
, certData
.Length
);
127 if (certData
.Data
&& !certData
.Length
) {
128 /* zero-length certs can exist, so don't bother logging this */
131 syslog(LOG_ERR
, "WARNING: SecKeychainSearchCopyNext failed to retrieve certificate data (length=%ld, data=0x%lX)",
132 (long)certData
.Length
, (uintptr_t)certData
.Data
);
139 result
= SecCertificateCreateWithKeychainItem(NULL
, data
, certificate
);
146 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
148 SecCertificateCreateFromData(const CSSM_DATA
*data
, CSSM_CERT_TYPE type
, CSSM_CERT_ENCODING encoding
, SecCertificateRef
*certificate
)
150 /* bridge to support old functionality */
151 if (!data
|| !data
->Data
|| !data
->Length
|| !certificate
) {
154 SecCertificateRef certRef
= NULL
;
156 // <rdar://problem/24403998> REG: Adobe {Photoshop, InDesign} CC(2015) crashes on launch
157 // If you take the length that SecKeychainItemCopyContent gives you (a Uint32) and assign it incorrectly
158 // to a CSSM_DATA Length field (a CSSM_SIZE, i.e., a size_t), the upper 32 bits aren't set. If those bits
159 // are non-zero, the length is incredibly wrong.
161 // Assume that there will not exist a certificate > 4GiB, and fake this length field.
162 CSSM_SIZE length
= data
->Length
& 0xfffffffful
;
164 CFDataRef dataRef
= CFDataCreate(NULL
, data
->Data
, length
);
166 certRef
= SecCertificateCreateWithData(NULL
, dataRef
);
169 *certificate
= certRef
;
170 return (certRef
) ? errSecSuccess
: errSecUnknownFormat
;
173 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA) */
175 SecCertificateAddToKeychain(SecCertificateRef certificate
, SecKeychainRef keychain
)
177 // This macro creates an ItemImpl certificate if it does not exist
180 Item
item(Certificate::required(__itemImplRef
));
181 Keychain::optional(keychain
)->add(item
);
186 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
188 SecCertificateGetData(SecCertificateRef certificate
, CSSM_DATA_PTR data
)
192 if (!certificate
|| !data
) {
193 __secapiresult
=errSecParam
;
195 else if (SecCertificateIsItemImplInstance(certificate
)) {
196 Required(data
) = Certificate::required(certificate
)->data();
199 data
->Length
= (CSSM_SIZE
)SecCertificateGetLength(certificate
);
200 data
->Data
= (uint8
*)SecCertificateGetBytePtr(certificate
);
206 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
208 SecCertificateGetType(SecCertificateRef certificate
, CSSM_CERT_TYPE
*certificateType
)
210 // This macro creates an ItemImpl certificate if it does not exist
213 Required(certificateType
) = Certificate::required(__itemImplRef
)->type();
218 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
220 SecCertificateGetSubject(SecCertificateRef certificate
, const CSSM_X509_NAME
**subject
)
222 // This macro creates an ItemImpl certificate if it does not exist
225 Required(subject
) = Certificate::required(__itemImplRef
)->subjectName();
230 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
232 SecCertificateGetIssuer(SecCertificateRef certificate
, const CSSM_X509_NAME
**issuer
)
234 // This macro creates an ItemImpl certificate if it does not exist
237 Required(issuer
) = Certificate::required(__itemImplRef
)->issuerName();
242 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
244 SecCertificateGetCLHandle(SecCertificateRef certificate
, CSSM_CL_HANDLE
*clHandle
)
246 // This macro creates an ItemImpl certificate if it does not exist
249 Required(clHandle
) = Certificate::required(__itemImplRef
)->clHandle();
254 /* private function; assumes input is old-style ItemImpl certificate reference,
255 and does not release that certificate reference!
258 SecCertificateGetCLHandle_legacy(SecCertificateRef certificate
, CSSM_CL_HANDLE
*clHandle
)
262 Required(clHandle
) = Certificate::required(certificate
)->clHandle();
268 * Private API to infer a display name for a SecCertificateRef which
269 * may or may not be in a keychain.
274 SecCertificateInferLabel(SecCertificateRef certificate
, CFStringRef
*label
)
276 // This macro creates an ItemImpl certificate if it does not exist
279 Certificate::required(__itemImplRef
)->inferLabel(false, &Required(label
));
284 /* OS X only (note: iOS version has different arguments and return value) */
286 SecCertificateCopyPublicKey(SecCertificateRef certificate
, SecKeyRef
*key
)
288 // This macro creates an ItemImpl certificate if it does not exist
291 Required(key
) = Certificate::required(__itemImplRef
)->publicKey()->handle();
296 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
298 SecCertificateGetAlgorithmID(SecCertificateRef certificate
, const CSSM_X509_ALGORITHM_IDENTIFIER
**algid
)
300 // This macro creates an ItemImpl certificate if it does not exist
303 Required(algid
) = Certificate::required(__itemImplRef
)->algorithmID();
310 SecCertificateCopySubjectComponent(SecCertificateRef certificate
, const CSSM_OID
*component
, CFStringRef
*result
)
312 // This macro creates an ItemImpl certificate if it does not exist
315 Required(result
) = Certificate::required(__itemImplRef
)->distinguishedName(&CSSMOID_X509V1SubjectNameCStruct
, component
);
320 /* OS X only; deprecated SPI */
322 SecCertificateGetCommonName(SecCertificateRef certificate
, CFStringRef
*commonName
)
324 // deprecated SPI signature; replaced by SecCertificateCopyCommonName
325 return SecCertificateCopyCommonName(certificate
, commonName
);
328 /* OS X only; deprecated SPI */
330 SecCertificateGetEmailAddress(SecCertificateRef certificate
, CFStringRef
*emailAddress
)
332 // This macro creates an ItemImpl certificate if it does not exist
335 Required(emailAddress
) = Certificate::required(__itemImplRef
)->copyFirstEmailAddress();
340 /* Return a zero terminated list of CSSM_DATA_PTR's with the values of the field specified by field.
341 * Caller must call releaseFieldValues to free the storage allocated by this call.
346 SecCertificateCopyFieldValues(SecCertificateRef certificate
, const CSSM_OID
*field
, CSSM_DATA_PTR
**fieldValues
)
348 // This macro creates an ItemImpl certificate if it does not exist
351 Required(fieldValues
) = Certificate::required(__itemImplRef
)->copyFieldValues(Required(field
));
358 SecCertificateReleaseFieldValues(SecCertificateRef certificate
, const CSSM_OID
*field
, CSSM_DATA_PTR
*fieldValues
)
360 // This macro creates an ItemImpl certificate if it does not exist
363 Certificate::required(__itemImplRef
)->releaseFieldValues(Required(field
), fieldValues
);
370 SecCertificateCopyFirstFieldValue(SecCertificateRef certificate
, const CSSM_OID
*field
, CSSM_DATA_PTR
*fieldValue
)
372 // This macro creates an ItemImpl certificate if it does not exist
375 Required(fieldValue
) = Certificate::required(__itemImplRef
)->copyFirstFieldValue(Required(field
));
382 SecCertificateReleaseFirstFieldValue(SecCertificateRef certificate
, const CSSM_OID
*field
, CSSM_DATA_PTR fieldValue
)
384 // This macro creates an ItemImpl certificate if it does not exist
387 Certificate::required(__itemImplRef
)->releaseFieldValue(Required(field
), fieldValue
);
394 SecCertificateFindByIssuerAndSN(CFTypeRef keychainOrArray
,const CSSM_DATA
*issuer
,
395 const CSSM_DATA
*serialNumber
, SecCertificateRef
*certificate
)
397 if (issuer
&& serialNumber
) {
398 CFRef
<CFMutableDictionaryRef
> query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
399 CFDictionarySetValue(query
, kSecClass
, kSecClassCertificate
);
400 CFDictionarySetValue(query
, kSecReturnRef
, kCFBooleanTrue
);
401 CFDictionarySetValue(query
, kSecUseDataProtectionKeychain
, kCFBooleanTrue
);
403 CFRef
<CFDataRef
> issuerData
= CFDataCreateWithBytesNoCopy(kCFAllocatorDefault
, (const UInt8
*)issuer
->Data
, issuer
->Length
, kCFAllocatorNull
);
404 CFDictionarySetValue(query
, kSecAttrIssuer
, issuerData
);
406 CFRef
<CFDataRef
> serialNumberData
= CFDataCreateWithBytesNoCopy(kCFAllocatorDefault
, (const UInt8
*)serialNumber
->Data
, serialNumber
->Length
, kCFAllocatorNull
);
407 CFDictionarySetValue(query
, kSecAttrSerialNumber
, serialNumberData
);
409 OSStatus status
= SecItemCopyMatching(query
, (CFTypeRef
*)certificate
);
410 if (status
== errSecSuccess
) {
417 StorageManager::KeychainList keychains
;
418 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
419 Required(certificate
) = Certificate::findByIssuerAndSN(keychains
, CssmData::required(issuer
), CssmData::required(serialNumber
))->handle();
421 // convert ItemImpl-based SecCertificateRef to new-world version before returning
422 CssmData certData
= Certificate::required(*certificate
)->data();
423 CFRef
<CFDataRef
> cfData(CFDataCreate(NULL
, certData
.Data
, certData
.Length
));
424 SecCertificateRef tmpRef
= *certificate
;
425 *certificate
= SecCertificateCreateWithData(NULL
, cfData
);
433 SecCertificateFindBySubjectKeyID(CFTypeRef keychainOrArray
, const CSSM_DATA
*subjectKeyID
,
434 SecCertificateRef
*certificate
)
437 CFRef
<CFMutableDictionaryRef
> query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
438 CFDictionarySetValue(query
, kSecClass
, kSecClassCertificate
);
439 CFDictionarySetValue(query
, kSecReturnRef
, kCFBooleanTrue
);
440 CFDictionarySetValue(query
, kSecUseDataProtectionKeychain
, kCFBooleanTrue
);
442 CFRef
<CFDataRef
> subjectKeyIDData
= CFDataCreateWithBytesNoCopy(kCFAllocatorDefault
, (const UInt8
*)subjectKeyID
->Data
, subjectKeyID
->Length
, kCFAllocatorNull
);
443 CFDictionarySetValue(query
, kSecAttrSubjectKeyID
, subjectKeyIDData
);
445 OSStatus status
= SecItemCopyMatching(query
, (CFTypeRef
*)certificate
);
446 if (status
== errSecSuccess
) {
453 StorageManager::KeychainList keychains
;
454 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
455 Required(certificate
) = Certificate::findBySubjectKeyID(keychains
, CssmData::required(subjectKeyID
))->handle();
457 // convert ItemImpl-based SecCertificateRef to new-world version before returning
458 CssmData certData
= Certificate::required(*certificate
)->data();
459 CFRef
<CFDataRef
> cfData(CFDataCreate(NULL
, certData
.Data
, certData
.Length
));
460 SecCertificateRef tmpRef
= *certificate
;
461 *certificate
= SecCertificateCreateWithData(NULL
, cfData
);
469 SecCertificateFindByEmail(CFTypeRef keychainOrArray
, const char *emailAddress
, SecCertificateRef
*certificate
)
472 CFRef
<CFMutableDictionaryRef
> query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
473 CFDictionarySetValue(query
, kSecClass
, kSecClassCertificate
);
474 CFDictionarySetValue(query
, kSecReturnRef
, kCFBooleanTrue
);
475 CFDictionarySetValue(query
, kSecUseDataProtectionKeychain
, kCFBooleanTrue
);
477 CFRef
<CFStringRef
> emailAddressString
= CFStringCreateWithCString(kCFAllocatorDefault
, emailAddress
, kCFStringEncodingUTF8
);
478 CFTypeRef keys
[] = { kSecPolicyName
};
479 CFTypeRef values
[] = { emailAddressString
};
480 CFRef
<CFDictionaryRef
> properties
= CFDictionaryCreate(kCFAllocatorDefault
, keys
, values
, 1, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
481 CFRef
<SecPolicyRef
> policy
= SecPolicyCreateWithProperties(kSecPolicyAppleSMIME
, properties
);
482 CFDictionarySetValue(query
, kSecMatchPolicy
, policy
);
484 OSStatus status
= SecItemCopyMatching(query
, (CFTypeRef
*)certificate
);
485 if (status
== errSecSuccess
) {
492 StorageManager::KeychainList keychains
;
493 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
494 Required(certificate
) = Certificate::findByEmail(keychains
, emailAddress
)->handle();
496 // convert ItemImpl-based SecCertificateRef to new-world version before returning
497 CssmData certData
= Certificate::required(*certificate
)->data();
498 CFRef
<CFDataRef
> cfData(CFDataCreate(NULL
, certData
.Data
, certData
.Length
));
499 SecCertificateRef tmpRef
= *certificate
;
500 *certificate
= SecCertificateCreateWithData(NULL
, cfData
);
508 SecKeychainSearchCreateForCertificateByIssuerAndSN(CFTypeRef keychainOrArray
, const CSSM_DATA
*issuer
,
509 const CSSM_DATA
*serialNumber
, SecKeychainSearchRef
*searchRef
)
515 StorageManager::KeychainList keychains
;
516 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
517 KCCursor
cursor(Certificate::cursorForIssuerAndSN(keychains
, CssmData::required(issuer
), CssmData::required(serialNumber
)));
518 *searchRef
= cursor
->handle();
525 SecKeychainSearchCreateForCertificateByIssuerAndSN_CF(CFTypeRef keychainOrArray
, CFDataRef issuer
,
526 CFDataRef serialNumber
, SecKeychainSearchRef
*searchRef
)
532 StorageManager::KeychainList keychains
;
533 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
535 Required(serialNumber
);
536 KCCursor
cursor(Certificate::cursorForIssuerAndSN_CF(keychains
, issuer
, serialNumber
));
537 *searchRef
= cursor
->handle();
544 SecKeychainSearchCreateForCertificateBySubjectKeyID(CFTypeRef keychainOrArray
, const CSSM_DATA
*subjectKeyID
,
545 SecKeychainSearchRef
*searchRef
)
551 StorageManager::KeychainList keychains
;
552 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
553 KCCursor
cursor(Certificate::cursorForSubjectKeyID(keychains
, CssmData::required(subjectKeyID
)));
554 *searchRef
= cursor
->handle();
561 SecKeychainSearchCreateForCertificateByEmail(CFTypeRef keychainOrArray
, const char *emailAddress
,
562 SecKeychainSearchRef
*searchRef
)
568 StorageManager::KeychainList keychains
;
569 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
570 KCCursor
cursor(Certificate::cursorForEmail(keychains
, emailAddress
));
571 *searchRef
= cursor
->handle();
578 SecDigestGetData (CSSM_ALGORITHMS alg
, CSSM_DATA
* digest
, const CSSM_DATA
* data
)
582 if (!digest
|| !digest
->Data
|| !digest
->Length
|| !data
|| !data
->Data
|| !data
->Length
)
585 CSP
csp(gGuidAppleCSP
);
586 Digest
context(csp
, alg
);
587 CssmData
input(data
->Data
, data
->Length
);
588 CssmData
output(digest
->Data
, digest
->Length
);
590 context
.digest(input
, output
);
591 digest
->Length
= output
.length();
597 /* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */
599 SecCertificateCopyPreference(
601 CSSM_KEYUSE keyUsage
,
602 SecCertificateRef
*certificate
)
607 Required(certificate
);
608 StorageManager::KeychainList keychains
;
609 globals().storageManager
.getSearchList(keychains
);
610 KCCursor
cursor(keychains
, kSecGenericPasswordItemClass
, NULL
);
612 char idUTF8
[MAXPATHLEN
];
613 if (!CFStringGetCString(name
, idUTF8
, sizeof(idUTF8
)-1, kCFStringEncodingUTF8
))
614 idUTF8
[0] = (char)'\0';
615 CssmData
service(const_cast<char *>(idUTF8
), strlen(idUTF8
));
616 FourCharCode itemType
= 'cprf';
617 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecServiceItemAttr
), service
);
618 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecTypeItemAttr
), itemType
);
620 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecScriptCodeItemAttr
), (sint32
)keyUsage
);
624 if (!cursor
->next(prefItem
)) {
625 MacOSError::throwMe(errSecItemNotFound
);
628 // get persistent certificate reference
629 SecKeychainAttribute itemAttrs
[] = { { kSecGenericItemAttr
, 0, NULL
} };
630 SecKeychainAttributeList itemAttrList
= { sizeof(itemAttrs
) / sizeof(itemAttrs
[0]), itemAttrs
};
631 prefItem
->getContent(NULL
, &itemAttrList
, NULL
, NULL
);
633 // find certificate, given persistent reference data
634 CFDataRef pItemRef
= CFDataCreateWithBytesNoCopy(NULL
, (const UInt8
*)itemAttrs
[0].data
, itemAttrs
[0].length
, kCFAllocatorNull
);
635 SecKeychainItemRef certItemRef
= nil
;
636 OSStatus status
= SecKeychainItemCopyFromPersistentReference(pItemRef
, &certItemRef
); //%%% need to make this a method of ItemImpl
637 prefItem
->freeContent(&itemAttrList
, NULL
);
643 *certificate
= (SecCertificateRef
)certItemRef
;
645 if (certItemRef
&& (CFGetTypeID(certItemRef
) == SecIdentityGetTypeID())) {
646 // SecKeychainItemCopyFromPersistentReference handed out an identity reference
648 status
= SecIdentityCopyCertificate((SecIdentityRef
)certItemRef
, certificate
);
649 CFRelease(certItemRef
);
658 SecCertificateCopyPreferred(
662 // This function will look for a matching preference in the following order:
663 // - matches the name and the supplied key use
664 // - matches the name and the special 'ANY' key use
665 // - matches the name with no key usage constraint
667 SecCertificateRef certRef
= NULL
;
668 CSSM_KEYUSE keyUse
= ConvertArrayToKeyUsage(keyUsage
);
669 OSStatus status
= SecCertificateCopyPreference(name
, keyUse
, &certRef
);
670 if (status
!= errSecSuccess
&& keyUse
!= CSSM_KEYUSE_ANY
)
671 status
= SecCertificateCopyPreference(name
, CSSM_KEYUSE_ANY
, &certRef
);
672 if (status
!= errSecSuccess
&& keyUse
!= 0)
673 status
= SecCertificateCopyPreference(name
, 0, &certRef
);
678 /* OS X only; not exported */
680 SecCertificateFindPreferenceItemWithNameAndKeyUsage(
681 CFTypeRef keychainOrArray
,
684 SecKeychainItemRef
*itemRef
)
688 StorageManager::KeychainList keychains
;
689 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
690 KCCursor
cursor(keychains
, kSecGenericPasswordItemClass
, NULL
);
692 char idUTF8
[MAXPATHLEN
];
693 idUTF8
[0] = (char)'\0';
696 if (!CFStringGetCString(name
, idUTF8
, sizeof(idUTF8
)-1, kCFStringEncodingUTF8
))
697 idUTF8
[0] = (char)'\0';
699 size_t idUTF8Len
= strlen(idUTF8
);
701 MacOSError::throwMe(errSecParam
);
703 CssmData
service(const_cast<char *>(idUTF8
), idUTF8Len
);
704 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecServiceItemAttr
), service
);
705 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecTypeItemAttr
), (FourCharCode
)'cprf');
707 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecScriptCodeItemAttr
), (sint32
)keyUsage
);
711 if (!cursor
->next(item
))
712 MacOSError::throwMe(errSecItemNotFound
);
715 *itemRef
=item
->handle();
720 /* OS X only; not exported */
722 OSStatus
SecCertificateDeletePreferenceItemWithNameAndKeyUsage(
723 CFTypeRef keychainOrArray
,
727 // when a specific key usage is passed, we'll only match & delete that pref;
728 // when a key usage of 0 is passed, all matching prefs should be deleted.
729 // maxUsages represents the most matches there could theoretically be, so
730 // cut things off at that point if we're still finding items (if they can't
731 // be deleted for some reason, we'd never break out of the loop.)
733 OSStatus status
= errSecSuccess
;
734 SecKeychainItemRef item
= NULL
;
735 int count
= 0, maxUsages
= 12;
736 while (++count
<= maxUsages
&&
737 (status
= SecCertificateFindPreferenceItemWithNameAndKeyUsage(keychainOrArray
, name
, keyUsage
, &item
)) == errSecSuccess
) {
738 status
= SecKeychainItemDelete(item
);
743 // it's not an error if the item isn't found
744 return (status
== errSecItemNotFound
) ? errSecSuccess
: status
;
747 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA) */
748 OSStatus
SecCertificateSetPreference(
749 SecCertificateRef certificate
,
751 CSSM_KEYUSE keyUsage
,
758 // treat NULL certificate as a request to clear the preference
759 // (note: if keyUsage is 0, this clears all key usage prefs for name)
760 return SecCertificateDeletePreferenceItemWithNameAndKeyUsage(NULL
, name
, keyUsage
);
763 // This macro creates an ItemImpl certificate if it does not exist
766 // determine the account attribute
768 // This attribute must be synthesized from certificate label + pref item type + key usage,
769 // as only the account and service attributes can make a generic keychain item unique.
770 // For 'iprf' type items (but not 'cprf'), we append a trailing space. This insures that
771 // we can save a certificate preference if an identity preference already exists for the
772 // given service name, and vice-versa.
773 // If the key usage is 0 (i.e. the normal case), we omit the appended key usage string.
775 CFStringRef labelStr
= nil
;
776 Certificate::required(__itemImplRef
)->inferLabel(false, &labelStr
);
778 MacOSError::throwMe(errSecDataTooLarge
); // data is "in a format which cannot be displayed"
780 CFIndex accountUTF8Len
= CFStringGetMaximumSizeForEncoding(CFStringGetLength(labelStr
), kCFStringEncodingUTF8
) + 1;
781 const char *templateStr
= "%s [key usage 0x%X]";
782 const int keyUsageMaxStrLen
= 8;
783 accountUTF8Len
+= strlen(templateStr
) + keyUsageMaxStrLen
;
784 char *accountUTF8
= (char *)malloc(accountUTF8Len
);
786 MacOSError::throwMe(errSecMemoryError
);
788 if (!CFStringGetCString(labelStr
, accountUTF8
, accountUTF8Len
-1, kCFStringEncodingUTF8
))
789 accountUTF8
[0] = (char)'\0';
791 snprintf(accountUTF8
, accountUTF8Len
-1, templateStr
, accountUTF8
, keyUsage
);
792 CssmDataContainer
account(const_cast<char *>(accountUTF8
), strlen(accountUTF8
));
796 // service attribute (name provided by the caller)
797 CFIndex serviceUTF8Len
= CFStringGetMaximumSizeForEncoding(CFStringGetLength(name
), kCFStringEncodingUTF8
) + 1;;
798 char *serviceUTF8
= (char *)malloc(serviceUTF8Len
);
800 MacOSError::throwMe(errSecMemoryError
);
802 if (!CFStringGetCString(name
, serviceUTF8
, serviceUTF8Len
-1, kCFStringEncodingUTF8
))
803 serviceUTF8
[0] = (char)'\0';
804 CssmDataContainer
service(const_cast<char *>(serviceUTF8
), strlen(serviceUTF8
));
807 // look for existing preference item, in case this is an update
808 StorageManager::KeychainList keychains
;
809 globals().storageManager
.getSearchList(keychains
);
810 KCCursor
cursor(keychains
, kSecGenericPasswordItemClass
, NULL
);
811 FourCharCode itemType
= 'cprf';
812 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecServiceItemAttr
), service
);
813 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecTypeItemAttr
), itemType
);
815 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecScriptCodeItemAttr
), (sint32
)keyUsage
);
818 Item
item(kSecGenericPasswordItemClass
, 'aapl', 0, NULL
, false);
819 bool add
= (!cursor
->next(item
));
820 // at this point, we either have a new item to add or an existing item to update
822 // set item attribute values
823 item
->setAttribute(Schema::attributeInfo(kSecServiceItemAttr
), service
);
824 item
->setAttribute(Schema::attributeInfo(kSecTypeItemAttr
), itemType
);
825 item
->setAttribute(Schema::attributeInfo(kSecAccountItemAttr
), account
);
826 item
->setAttribute(Schema::attributeInfo(kSecScriptCodeItemAttr
), (sint32
)keyUsage
);
827 item
->setAttribute(Schema::attributeInfo(kSecLabelItemAttr
), service
);
829 // generic attribute (store persistent certificate reference)
830 CFDataRef pItemRef
= nil
;
831 Certificate::required(__itemImplRef
)->copyPersistentReference(pItemRef
);
833 MacOSError::throwMe(errSecInvalidItemRef
);
835 const UInt8
*dataPtr
= CFDataGetBytePtr(pItemRef
);
836 CFIndex dataLen
= CFDataGetLength(pItemRef
);
837 CssmData
pref(const_cast<void *>(reinterpret_cast<const void *>(dataPtr
)), dataLen
);
838 item
->setAttribute(Schema::attributeInfo(kSecGenericItemAttr
), pref
);
842 Keychain keychain
= nil
;
844 keychain
= globals().storageManager
.defaultKeychain();
845 if (!keychain
->exists())
846 MacOSError::throwMe(errSecNoSuchKeychain
); // Might be deleted or not available at this time.
849 keychain
= globals().storageManager
.defaultKeychainUI(item
);
855 catch (const MacOSError
&err
) {
856 if (err
.osStatus() != errSecDuplicateItem
)
857 throw; // if item already exists, fall through to update
865 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
866 OSStatus
SecCertificateSetPreferred(
867 SecCertificateRef certificate
,
872 CSSM_KEYUSE keyUse
= ConvertArrayToKeyUsage(keyUsage
);
873 return SecCertificateSetPreference(certificate
, name
, keyUse
, NULL
);
876 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
877 CFDictionaryRef
SecCertificateCopyValues(SecCertificateRef certificate
, CFArrayRef keys
, CFErrorRef
*error
)
879 CFDictionaryRef result
= NULL
;
880 OSStatus __secapiresult
;
881 SecCertificateRef tmpcert
= NULL
;
883 // convert input to a new-style certificate reference if necessary,
884 // since the implementation of CertificateValues calls SecCertificate API functions
885 // which now assume a unified certificate reference.
886 if (SecCertificateIsItemImplInstance(certificate
)) {
887 tmpcert
= SecCertificateCreateFromItemImplInstance(certificate
);
889 if (certificate
&& !tmpcert
) {
890 tmpcert
= (SecCertificateRef
) CFRetain(certificate
);
894 CertificateValues
cv(tmpcert
);
895 result
= cv
.copyFieldValues(keys
,error
);
898 catch (const MacOSError
&err
) { __secapiresult
=err
.osStatus(); }
899 catch (const CommonError
&err
) { __secapiresult
=SecKeychainErrFromOSStatus(err
.osStatus()); }
900 catch (const std::bad_alloc
&) { __secapiresult
=errSecAllocate
; }
901 catch (...) { __secapiresult
=errSecInternalComponent
; }
902 if (tmpcert
) { CFRelease(tmpcert
); }
906 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
907 CFStringRef
SecCertificateCopyLongDescription(CFAllocatorRef alloc
, SecCertificateRef certificate
, CFErrorRef
*error
)
909 return SecCertificateCopyShortDescription(alloc
, certificate
, error
);
912 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
913 CFStringRef
SecCertificateCopyShortDescription(CFAllocatorRef alloc
, SecCertificateRef certificate
, CFErrorRef
*error
)
915 CFStringRef result
= NULL
;
916 OSStatus __secapiresult
= SecCertificateInferLabel(certificate
, &result
);
917 if (error
!=NULL
&& __secapiresult
!=errSecSuccess
)
919 *error
= CFErrorCreate(kCFAllocatorDefault
, kCFErrorDomainOSStatus
,
920 __secapiresult
? __secapiresult
: CSSM_ERRCODE_INTERNAL_ERROR
, NULL
);
925 /* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */
926 CFDataRef
SecCertificateCopySerialNumber(SecCertificateRef certificate
, CFErrorRef
*error
)
928 CFDataRef result
= NULL
;
929 OSStatus __secapiresult
;
932 CertificateValues
cv(certificate
);
933 result
= cv
.copySerialNumber(error
);
936 catch (const MacOSError
&err
) { __secapiresult
=err
.osStatus(); }
937 catch (const CommonError
&err
) { __secapiresult
=SecKeychainErrFromOSStatus(err
.osStatus()); }
938 catch (const std::bad_alloc
&) { __secapiresult
=errSecAllocate
; }
939 catch (...) { __secapiresult
=errSecInternalComponent
; }
943 /* OS X only: __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_7, __MAC_10_12_4, __IPHONE_NA, __IPHONE_NA) */
944 CFDataRef
SecCertificateCopyNormalizedIssuerContent(SecCertificateRef certificate
, CFErrorRef
*error
)
946 CFDataRef result
= NULL
;
947 OSStatus __secapiresult
;
950 CertificateValues
cv(certificate
);
951 result
= cv
.copyNormalizedIssuerContent(error
);
954 catch (const MacOSError
&err
) { __secapiresult
=err
.osStatus(); }
955 catch (const CommonError
&err
) { __secapiresult
=SecKeychainErrFromOSStatus(err
.osStatus()); }
956 catch (const std::bad_alloc
&) { __secapiresult
=errSecAllocate
; }
957 catch (...) { __secapiresult
=errSecInternalComponent
; }
961 /* OS X only: __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_7, __MAC_10_12_4, __IPHONE_NA, __IPHONE_NA) */
962 CFDataRef
SecCertificateCopyNormalizedSubjectContent(SecCertificateRef certificate
, CFErrorRef
*error
)
964 CFDataRef result
= NULL
;
965 OSStatus __secapiresult
;
968 CertificateValues
cv(certificate
);
969 result
= cv
.copyNormalizedSubjectContent(error
);
972 catch (const MacOSError
&err
) { __secapiresult
=err
.osStatus(); }
973 catch (const CommonError
&err
) { __secapiresult
=SecKeychainErrFromOSStatus(err
.osStatus()); }
974 catch (const std::bad_alloc
&) { __secapiresult
=errSecAllocate
; }
975 catch (...) { __secapiresult
=errSecInternalComponent
; }
979 /* OS X only: __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_7, __MAC_10_9, __IPHONE_NA, __IPHONE_NA) */
980 bool SecCertificateIsValidX(SecCertificateRef certificate
, CFAbsoluteTime verifyTime
)
983 * deprecated function name
985 return SecCertificateIsValid(certificate
, verifyTime
);
989 CFDataRef
SecCertificateCopyPublicKeySHA1DigestFromCertificateData(CFAllocatorRef allocator
,
990 CFDataRef der_certificate
)
992 CFDataRef result
= NULL
;
993 SecCertificateRef iosCertRef
= SecCertificateCreateWithData(allocator
, der_certificate
);
994 if (NULL
== iosCertRef
)
999 result
= SecCertificateCopyPublicKeySHA1Digest(iosCertRef
);
1000 CFRelease(iosCertRef
);