2 * Copyright (c) 2015 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 #import <Foundation/Foundation.h>
26 #include <AssertMacros.h>
27 #include <Security/SecFramework.h>
28 #include <Security/SecKeyPriv.h>
29 #include <Security/SecItem.h>
30 #include <Security/SecItemPriv.h>
31 #include <Security/SecItemInternal.h>
32 #include <Security/SecBasePriv.h>
33 #include <Security/SecAccessControlPriv.h>
34 #include <utilities/SecCFError.h>
35 #include <utilities/SecCFWrappers.h>
36 #include <utilities/array_size.h>
37 #include <ctkclient/ctkclient.h>
38 #include <libaks_acl_cf_keys.h>
39 #include <coreauthd_spi.h>
40 #include "OSX/sec/Security/SecItemShim.h"
43 #include "SecRSAKey.h"
44 #include "SecCTKKeyPriv.h"
46 const CFStringRef kSecUseToken = CFSTR("u_Token");
52 SecCFDictionaryCOW auth_params;
53 SecCFDictionaryCOW attributes;
54 CFMutableDictionaryRef params;
57 static void SecCTKKeyDestroy(SecKeyRef key) {
58 SecCTKKeyData *kd = key->key;
59 CFReleaseNull(kd->token);
60 CFReleaseNull(kd->token_id);
61 CFReleaseNull(kd->object_id);
62 CFReleaseNull(kd->auth_params.mutable_dictionary);
63 CFReleaseNull(kd->attributes.mutable_dictionary);
64 CFReleaseNull(kd->params);
67 static CFIndex SecCTKGetAlgorithmID(SecKeyRef key) {
68 SecCTKKeyData *kd = key->key;
69 if (CFEqualSafe(CFDictionaryGetValue(kd->attributes.dictionary, kSecAttrKeyType), kSecAttrKeyTypeECSECPrimeRandom) ||
70 CFEqualSafe(CFDictionaryGetValue(kd->attributes.dictionary, kSecAttrKeyType), kSecAttrKeyTypeECSECPrimeRandomPKA) ||
71 CFEqualSafe(CFDictionaryGetValue(kd->attributes.dictionary, kSecAttrKeyType), kSecAttrKeyTypeSecureEnclaveAttestation)) {
72 return kSecECDSAAlgorithmID;
74 return kSecRSAAlgorithmID;
77 static SecItemAuthResult SecCTKProcessError(CFStringRef operation, TKTokenRef token, CFDataRef object_id, CFArrayRef *ac_pairs, CFErrorRef *error) {
78 if (CFEqualSafe(CFErrorGetDomain(*error), CFSTR(kTKErrorDomain)) &&
79 CFErrorGetCode(*error) == kTKErrorCodeAuthenticationNeeded &&
81 CFDataRef access_control = TKTokenCopyObjectAccessControl(token, object_id, error);
82 if (access_control != NULL) {
83 CFArrayRef ac_pair = CFArrayCreateForCFTypes(NULL, access_control, operation, NULL);
84 CFAssignRetained(*ac_pairs, CFArrayCreateForCFTypes(NULL, ac_pair, NULL));
86 CFReleaseNull(*error);
88 CFRelease(access_control);
89 return kSecItemAuthResultNeedAuth;
92 return kSecItemAuthResultError;
95 static TKTokenRef SecCTKKeyCreateToken(SecKeyRef key, CFDictionaryRef auth_params, CFDictionaryRef *last_params, CFErrorRef *error) {
96 TKTokenRef token = NULL;
97 SecCTKKeyData *kd = key->key;
98 SecCFDictionaryCOW attributes = { auth_params };
99 if (kd->params && CFDictionaryGetCount(kd->params) > 0) {
100 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&attributes), CFSTR(kTKTokenCreateAttributeAuxParams), kd->params);
102 require_quiet(token = SecTokenCreate(kd->token_id, &attributes, error), out);
103 if (last_params != NULL) {
104 CFAssignRetained(*last_params, auth_params ? CFDictionaryCreateCopy(NULL, auth_params) : NULL);
108 CFReleaseNull(attributes.mutable_dictionary);
112 static TKTokenRef SecCTKKeyCopyToken(SecKeyRef key, CFErrorRef *error) {
113 SecCTKKeyData *kd = key->key;
114 TKTokenRef token = CFRetainSafe(kd->token);
116 token = SecCTKKeyCreateToken(key, kd->auth_params.dictionary, NULL, error);
121 static CFTypeRef SecCTKKeyCopyOperationResult(SecKeyRef key, SecKeyOperationType operation, SecKeyAlgorithm algorithm,
122 CFArrayRef algorithms, SecKeyOperationMode mode,
123 CFTypeRef in1, CFTypeRef in2, CFErrorRef *error) {
124 SecCTKKeyData *kd = key->key;
125 __block SecCFDictionaryCOW auth_params = { kd->auth_params.dictionary };
126 __block CFDictionaryRef last_params = kd->auth_params.dictionary ? CFDictionaryCreateCopy(NULL, kd->auth_params.dictionary) : NULL;
127 __block TKTokenRef token = CFRetainSafe(kd->token);
128 __block CFTypeRef result = kCFNull;
130 CFErrorRef localError = NULL;
131 SecItemAuthDo(&auth_params, &localError, ^SecItemAuthResult(CFArrayRef *ac_pairs, CFErrorRef *error) {
132 if (!CFEqualSafe(last_params, auth_params.dictionary) || token == NULL) {
133 // token was not connected yet or auth_params were modified, so reconnect the token in order to update the attributes.
134 CFAssignRetained(token, SecCTKKeyCreateToken(key, auth_params.dictionary, &last_params, error));
136 return kSecItemAuthResultError;
140 result = kCFBooleanTrue;
141 if (mode == kSecKeyOperationModePerform) {
142 // Check, whether we are not trying to perform the operation with large data. If yes, explicitly do the check whether
143 // the operation is supported first, in order to avoid jetsam of target extension with operation type which is typically
144 // not supported by the extension at all.
145 // <rdar://problem/31762984> unable to decrypt large data with kSecKeyAlgorithmECIESEncryptionCofactorX963SHA256AESGCM
146 CFIndex inputSize = 0;
147 if (in1 != NULL && CFGetTypeID(in1) == CFDataGetTypeID()) {
148 inputSize += CFDataGetLength(in1);
150 if (in2 != NULL && CFGetTypeID(in2) == CFDataGetTypeID()) {
151 inputSize += CFDataGetLength(in2);
153 if (inputSize > 32 * 1024) {
154 result = TKTokenCopyOperationResult(token, kd->object_id, operation, algorithms, kSecKeyOperationModeCheckIfSupported,
159 if (CFEqualSafe(result, kCFBooleanTrue)) {
160 result = TKTokenCopyOperationResult(token, kd->object_id, operation, algorithms, mode, in1, in2, error);
163 if (result != NULL) {
164 return kSecItemAuthResultOK;
167 CFStringRef AKSOperation = NULL;
169 case kSecKeyOperationTypeSign:
170 AKSOperation = kAKSKeyOpSign;
172 case kSecKeyOperationTypeDecrypt: {
173 AKSOperation = kAKSKeyOpDecrypt;
174 if (in2 != NULL && CFGetTypeID(in2) == CFDictionaryGetTypeID() && CFDictionaryGetValue(in2, kSecKeyEncryptionParameterRecryptCertificate) != NULL) {
175 // This is actually recrypt operation, which is special separate AKS operation.
176 AKSOperation = kAKSKeyOpECIESTranscode;
180 case kSecKeyOperationTypeKeyExchange:
181 AKSOperation = kAKSKeyOpComputeKey;
186 return SecCTKProcessError(AKSOperation, token, kd->object_id, ac_pairs, error);
188 CFAssignRetained(token, SecCTKKeyCreateToken(key, auth_params.dictionary, &last_params, NULL));
191 CFErrorPropagate(localError, error);
192 CFReleaseNull(auth_params.mutable_dictionary);
193 CFReleaseNull(token);
194 CFReleaseNull(last_params);
198 static size_t SecCTKKeyBlockSize(SecKeyRef key) {
199 SecCTKKeyData *kd = key->key;
200 CFTypeRef keySize = CFDictionaryGetValue(kd->attributes.dictionary, kSecAttrKeySizeInBits);
201 if (CFGetTypeID(keySize) == CFNumberGetTypeID()) {
203 if (CFNumberGetValue(keySize, kCFNumberCFIndexType, &bitSize))
204 return (bitSize + 7) / 8;
210 static OSStatus SecCTKKeyCopyPublicOctets(SecKeyRef key, CFDataRef *data) {
211 OSStatus status = errSecSuccess;
212 CFErrorRef error = NULL;
213 CFDataRef publicData = NULL;
214 TKTokenRef token = NULL;
216 SecCTKKeyData *kd = key->key;
217 require_action_quiet(token = SecCTKKeyCopyToken(key, &error), out, status = SecErrorGetOSStatus(error));
218 require_action_quiet(publicData = TKTokenCopyPublicKeyData(token, kd->object_id, &error), out,
219 status = SecErrorGetOSStatus(error));
223 CFReleaseSafe(error);
224 CFReleaseSafe(token);
228 static CFStringRef SecCTKKeyCopyKeyDescription(SecKeyRef key) {
229 SecCTKKeyData *kd = key->key;
230 return CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("<SecKeyRef:('%@') %p>"),
231 CFDictionaryGetValue(kd->attributes.dictionary, kSecAttrTokenID), key);
234 // Attributes allowed to be exported from all internal key attributes.
235 static const CFStringRef *kSecExportableCTKKeyAttributes[] = {
239 &kSecAttrAccessControl,
241 &kSecAttrIsModifiable,
243 &kSecAttrKeySizeInBits,
244 &kSecAttrEffectiveKeySize,
245 &kSecAttrIsSensitive,
246 &kSecAttrWasAlwaysSensitive,
247 &kSecAttrIsExtractable,
248 &kSecAttrWasNeverExtractable,
254 &kSecAttrCanSignRecover,
255 &kSecAttrCanVerifyRecover,
261 static CFDictionaryRef SecCTKKeyCopyAttributeDictionary(SecKeyRef key) {
262 CFMutableDictionaryRef attrs = NULL;
263 CFErrorRef error = NULL;
264 CFDataRef publicData = NULL, digest = NULL;
265 TKTokenRef token = NULL;
266 SecCTKKeyData *kd = key->key;
268 // Encode ApplicationLabel as SHA1 digest of public key bytes.
269 require_quiet(token = SecCTKKeyCopyToken(key, &error), out);
270 require_quiet(publicData = TKTokenCopyPublicKeyData(token, kd->object_id, &error), out);
272 // Calculate the digest of the public key.
273 require_quiet(digest = SecSHA1DigestCreate(NULL, CFDataGetBytePtr(publicData), CFDataGetLength(publicData)), out);
274 attrs = CFDictionaryCreateMutableForCFTypes(CFGetAllocator(key));
275 CFDictionarySetValue(attrs, kSecAttrApplicationLabel, digest);
277 for (const CFStringRef **attrKey = &kSecExportableCTKKeyAttributes[0]; *attrKey != NULL; attrKey++) {
278 CFTypeRef value = CFDictionaryGetValue(kd->attributes.dictionary, **attrKey);
280 CFDictionarySetValue(attrs, **attrKey, value);
284 // Consistently with existing RSA and EC software keys implementation, mark all keys as permanent ones.
285 CFDictionarySetValue(attrs, kSecAttrIsPermanent, kCFBooleanTrue);
287 // Always export token_id and object_id.
288 CFDictionarySetValue(attrs, kSecAttrTokenID, kd->token_id);
289 CFDictionarySetValue(attrs, kSecAttrTokenOID, kd->object_id);
292 CFReleaseSafe(error);
293 CFReleaseSafe(publicData);
294 CFReleaseSafe(digest);
295 CFReleaseSafe(token);
299 static SecKeyRef SecCTKKeyCreateDuplicate(SecKeyRef key);
301 static Boolean SecCTKKeySetParameter(SecKeyRef key, CFStringRef name, CFPropertyListRef value, CFErrorRef *error) {
302 SecCTKKeyData *kd = key->key;
303 CFTypeRef acm_reference = NULL;
305 static const CFStringRef *const knownUseFlags[] = {
306 &kSecUseOperationPrompt,
307 &kSecUseAuthenticationContext,
308 &kSecUseAuthenticationUI,
310 &kSecUseCredentialReference,
313 // Check, whether name is part of known use flags.
314 bool isUseFlag = false;
315 for (size_t i = 0; i < array_size(knownUseFlags); i++) {
316 if (CFEqual(*knownUseFlags[i], name)) {
322 if (CFEqual(name, kSecUseAuthenticationContext)) {
323 // Preprocess LAContext to ACMRef value.
325 require_quiet(acm_reference = LACopyACMContext(value, error), out);
326 value = acm_reference;
328 name = kSecUseCredentialReference;
331 // Release existing token connection to enforce creation of new connection with new params.
332 CFReleaseNull(kd->token);
336 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&kd->auth_params), name, value);
338 CFDictionaryRemoveValue(SecCFDictionaryCOWGetMutable(&kd->auth_params), name);
341 if (kd->params == NULL) {
342 kd->params = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
345 CFDictionarySetValue(kd->params, name, value);
347 CFDictionaryRemoveValue(kd->params, name);
352 CFReleaseSafe(acm_reference);
356 static SecKeyDescriptor kSecCTKKeyDescriptor = {
357 .version = kSecKeyDescriptorVersion,
359 .extraBytes = sizeof(SecCTKKeyData),
361 .destroy = SecCTKKeyDestroy,
362 .blockSize = SecCTKKeyBlockSize,
363 .copyDictionary = SecCTKKeyCopyAttributeDictionary,
364 .describe = SecCTKKeyCopyKeyDescription,
365 .getAlgorithmID = SecCTKGetAlgorithmID,
366 .copyPublic = SecCTKKeyCopyPublicOctets,
367 .copyOperationResult = SecCTKKeyCopyOperationResult,
368 .createDuplicate = SecCTKKeyCreateDuplicate,
369 .setParameter = SecCTKKeySetParameter,
372 static SecKeyRef SecCTKKeyCreateDuplicate(SecKeyRef key) {
373 SecKeyRef result = SecKeyCreate(CFGetAllocator(key), &kSecCTKKeyDescriptor, 0, 0, 0);
374 SecCTKKeyData *kd = key->key, *rd = result->key;
375 rd->token = CFRetainSafe(kd->token);
376 rd->object_id = CFRetainSafe(kd->object_id);
377 rd->token_id = CFRetainSafe(kd->token_id);
378 if (kd->attributes.dictionary != NULL) {
379 rd->attributes.dictionary = kd->attributes.dictionary;
380 SecCFDictionaryCOWGetMutable(&rd->attributes);
382 if (kd->auth_params.dictionary != NULL) {
383 rd->auth_params.dictionary = kd->auth_params.dictionary;
384 SecCFDictionaryCOWGetMutable(&rd->auth_params);
389 SecKeyRef SecKeyCreateCTKKey(CFAllocatorRef allocator, CFDictionaryRef refAttributes, CFErrorRef *error) {
390 SecKeyRef result = NULL;
391 SecKeyRef key = SecKeyCreate(allocator, &kSecCTKKeyDescriptor, 0, 0, 0);
392 SecCTKKeyData *kd = key->key;
393 kd->token = CFRetainSafe(CFDictionaryGetValue(refAttributes, kSecUseToken));
394 kd->object_id = CFRetainSafe(CFDictionaryGetValue(refAttributes, kSecAttrTokenOID));
395 kd->token_id = CFRetainSafe(CFDictionaryGetValue(refAttributes, kSecAttrTokenID));
396 kd->attributes.dictionary = refAttributes;
397 CFDictionaryRemoveValue(SecCFDictionaryCOWGetMutable(&kd->attributes), kSecUseToken);
398 CFDictionaryRemoveValue(SecCFDictionaryCOWGetMutable(&kd->attributes), kSecAttrTokenOID);
399 SecItemAuthCopyParams(&kd->auth_params, &kd->attributes);
400 if (CFDictionaryGetValue(kd->attributes.dictionary, kSecAttrIsPrivate) == NULL) {
401 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&kd->attributes), kSecAttrIsPrivate, kCFBooleanTrue);
404 // Convert some attributes which are stored as numbers in iOS keychain but a lot of code counts that the values
405 // are actually strings as specified by kSecAttrXxx constants.
406 static const CFStringRef *numericAttributes[] = {
412 CFMutableDictionaryRef attrs = NULL;
413 if (kd->token == NULL) {
414 require_quiet(kd->token = SecCTKKeyCopyToken(key, error), out);
415 if (kd->token != NULL) {
416 attrs = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, kd->attributes.dictionary);
417 CFAssignRetained(kd->object_id, TKTokenCreateOrUpdateObject(kd->token, kd->object_id, attrs, error));
418 require_quiet(kd->object_id, out);
419 CFDictionaryForEach(attrs, ^(const void *key, const void *value) {
420 CFDictionaryAddValue(SecCFDictionaryCOWGetMutable(&kd->attributes), key, value);
423 CFTypeRef accc = CFDictionaryGetValue(kd->attributes.dictionary, kSecAttrAccessControl);
424 if (accc && CFDataGetTypeID() == CFGetTypeID(accc)) {
425 SecAccessControlRef ac = SecAccessControlCreateFromData(kCFAllocatorDefault, accc, error);
426 require_quiet(ac, out);
427 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&kd->attributes), kSecAttrAccessControl, ac);
430 CFDictionaryRemoveValue(SecCFDictionaryCOWGetMutable(&kd->attributes), kSecAttrTokenOID);
432 require_quiet(kd->token != NULL && kd->object_id != NULL, out);
435 for (const CFStringRef **attrName = &numericAttributes[0]; *attrName != NULL; attrName++) {
436 CFTypeRef value = CFDictionaryGetValue(kd->attributes.dictionary, **attrName);
437 if (value != NULL && CFGetTypeID(value) == CFNumberGetTypeID()) {
439 if (CFNumberGetValue(value, kCFNumberCFIndexType, &number)) {
440 CFStringRef newValue = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%ld"), (long)number);
441 if (newValue != NULL) {
442 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&kd->attributes), **attrName, newValue);
448 result = (SecKeyRef)CFRetain(key);
451 CFReleaseSafe(attrs);
456 OSStatus SecCTKKeyGeneratePair(CFDictionaryRef parameters, SecKeyRef *publicKey, SecKeyRef *privateKey) {
458 __block SecCFDictionaryCOW attrs = { NULL };
459 CFDataRef publicData = NULL;
461 require_action_quiet(publicKey != NULL, out, status = errSecParam);
462 require_action_quiet(privateKey != NULL, out, status = errSecParam);
464 // Simply adding key on the token without value will cause the token to generate the key.
465 // Prepare dictionary specifying item to add.
466 attrs.dictionary = CFDictionaryGetValue(parameters, kSecPrivateKeyAttrs);
468 CFDictionaryForEach(parameters, ^(const void *key, const void *value) {
469 if (!CFEqual(key, kSecPrivateKeyAttrs) && !CFEqual(key, kSecPublicKeyAttrs)) {
470 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&attrs), key, value);
473 CFDictionaryRemoveValue(SecCFDictionaryCOWGetMutable(&attrs), kSecValueData);
474 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&attrs), kSecClass, kSecClassKey);
475 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&attrs), kSecAttrKeyClass, kSecAttrKeyClassPrivate);
476 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&attrs), kSecReturnRef, kCFBooleanTrue);
478 // Do not automatically store tke key into the keychain, caller will do it on its own if it is really requested.
479 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&attrs), kSecAttrIsPermanent, kCFBooleanFalse);
481 // Add key from given attributes to the token (having no data will cause the token to actually generate the key).
482 require_noerr_quiet(status = SecItemAdd(attrs.dictionary, (CFTypeRef *)privateKey), out);
484 // Create non-token public key.
485 require_noerr_quiet(status = SecCTKKeyCopyPublicOctets(*privateKey, &publicData), out);
486 if (CFEqualSafe(CFDictionaryGetValue(parameters, kSecAttrKeyType), kSecAttrKeyTypeEC) ||
487 CFEqualSafe(CFDictionaryGetValue(parameters, kSecAttrKeyType), kSecAttrKeyTypeECSECPrimeRandomPKA) ||
488 CFEqualSafe(CFDictionaryGetValue(parameters, kSecAttrKeyType), kSecAttrKeyTypeSecureEnclaveAttestation)) {
489 *publicKey = SecKeyCreateECPublicKey(NULL, CFDataGetBytePtr(publicData), CFDataGetLength(publicData),
490 kSecKeyEncodingBytes);
491 } else if (CFEqualSafe(CFDictionaryGetValue(parameters, kSecAttrKeyType), kSecAttrKeyTypeRSA)) {
492 *publicKey = SecKeyCreateRSAPublicKey(NULL, CFDataGetBytePtr(publicData), CFDataGetLength(publicData),
493 kSecKeyEncodingBytes);
496 if (*publicKey != NULL) {
497 status = errSecSuccess;
499 status = errSecInvalidKey;
500 CFReleaseNull(*privateKey);
504 CFReleaseSafe(attrs.mutable_dictionary);
505 CFReleaseSafe(publicData);
509 const CFStringRef kSecKeyParameterSETokenAttestationNonce = CFSTR("com.apple.security.seckey.setoken.attestation-nonce");
511 SecKeyRef SecKeyCopyAttestationKey(SecKeyAttestationKeyType keyType, CFErrorRef *error) {
512 CFDictionaryRef attributes = NULL;
513 CFDataRef object_id = NULL;
514 SecKeyRef key = NULL;
516 // [[TKTLVBERRecord alloc] initWithPropertyList:[@"com.apple.setoken.sik" dataUsingEncoding:NSUTF8StringEncoding]].data
517 static const uint8_t sikObjectIDBytes[] = { 0x04, 21, 'c', 'o', 'm', '.', 'a', 'p', 'p', 'l', 'e', '.', 's', 'e', 't', 'o', 'k', 'e', 'n', '.', 's', 'i', 'k' };
518 // [[TKTLVBERRecord alloc] initWithPropertyList:[@"com.apple.setoken.gid" dataUsingEncoding:NSUTF8StringEncoding]].data
519 static const uint8_t gidObjectIDBytes[] = { 0x04, 21, 'c', 'o', 'm', '.', 'a', 'p', 'p', 'l', 'e', '.', 's', 'e', 't', 'o', 'k', 'e', 'n', '.', 'g', 'i', 'd' };
520 // [[TKTLVBERRecord alloc] initWithPropertyList:[@"com.apple.setoken.uikc" dataUsingEncoding:NSUTF8StringEncoding]].data
521 static const uint8_t uikCommittedObjectIDBytes[] = { 0x04, 22, 'c', 'o', 'm', '.', 'a', 'p', 'p', 'l', 'e', '.', 's', 'e', 't', 'o', 'k', 'e', 'n', '.', 'u', 'i', 'k', 'c' };
522 // [[TKTLVBERRecord alloc] initWithPropertyList:[@"com.apple.setoken.uikp" dataUsingEncoding:NSUTF8StringEncoding]].data
523 static const uint8_t uikProposedObjectIDBytes[] = { 0x04, 22, 'c', 'o', 'm', '.', 'a', 'p', 'p', 'l', 'e', '.', 's', 'e', 't', 'o', 'k', 'e', 'n', '.', 'u', 'i', 'k', 'p' };
525 static const uint8_t casdObjectIDBytes[] = { 0x04, 27, 'c', 'o', 'm', '.', 'a', 'p', 'p', 'l', 'e', '.', 's', 'e', 'c', 'e', 'l', 'e', 'm', 't', 'o', 'k', 'e', 'n', '.', 'c', 'a', 's', 'd' };
527 CFStringRef token = kSecAttrTokenIDAppleKeyStore;
530 case kSecKeyAttestationKeyTypeSIK:
531 object_id = CFDataCreate(kCFAllocatorDefault, sikObjectIDBytes, sizeof(sikObjectIDBytes));
533 case kSecKeyAttestationKeyTypeGID:
534 object_id = CFDataCreate(kCFAllocatorDefault, gidObjectIDBytes, sizeof(gidObjectIDBytes));
536 case kSecKeyAttestationKeyTypeUIKCommitted:
537 object_id = CFDataCreate(kCFAllocatorDefault, uikCommittedObjectIDBytes, sizeof(uikCommittedObjectIDBytes));
539 case kSecKeyAttestationKeyTypeUIKProposed:
540 object_id = CFDataCreate(kCFAllocatorDefault, uikProposedObjectIDBytes, sizeof(uikProposedObjectIDBytes));
542 case kSecKeyAttestationKeyTypeSecureElement:
543 object_id = CFDataCreate(kCFAllocatorDefault, casdObjectIDBytes, sizeof(casdObjectIDBytes));
544 token = kSecAttrTokenIDSecureElement;
547 SecError(errSecParam, error, CFSTR("unexpected attestation key type %d"), (int)keyType);
551 attributes = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
552 kSecAttrTokenOID, object_id,
553 kSecAttrTokenID, token,
555 key = SecKeyCreateCTKKey(kCFAllocatorDefault, attributes, error);
558 CFReleaseSafe(attributes);
559 CFReleaseSafe(object_id);
563 CFDataRef SecKeyCreateAttestation(SecKeyRef key, SecKeyRef keyToAttest, CFErrorRef *error) {
564 __block CFDictionaryRef attributes = NULL, outputAttributes = NULL;
565 CFDataRef attestationData = NULL;
566 CFErrorRef localError = NULL;
567 SecCTKKeyData *attestingKeyData = key->key;
568 SecCTKKeyData *keyToAttestData = keyToAttest->key;
569 __block TKTokenRef token = NULL;
575 __block SecCFDictionaryCOW auth_params = { keyToAttestData->auth_params.dictionary };
577 require_action_quiet(key->key_class == &kSecCTKKeyDescriptor, out,
578 SecError(errSecUnsupportedOperation, error, CFSTR("attestation not supported by key %@"), key));
579 require_action_quiet(keyToAttest->key_class == &kSecCTKKeyDescriptor, out,
580 SecError(errSecUnsupportedOperation, error, CFSTR("attestation not supported for key %@"), keyToAttest));
582 attributes = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
583 CFSTR(kTKTokenControlAttribAttestingKey), attestingKeyData->object_id,
584 CFSTR(kTKTokenControlAttribKeyToAttest), keyToAttestData->object_id,
587 bool ok = SecItemAuthDo(&auth_params, error, ^SecItemAuthResult(CFArrayRef *ac_pairs, CFErrorRef *error) {
588 if (auth_params.mutable_dictionary != NULL || token == NULL) {
589 CFAssignRetained(token, SecCTKKeyCopyToken(key, error));
591 return kSecItemAuthResultError;
595 outputAttributes = TKTokenControl(token, attributes, error);
596 return outputAttributes ? kSecItemAuthResultOK : SecCTKProcessError(kAKSKeyOpAttest, keyToAttestData->token, keyToAttestData->object_id, ac_pairs, error);
598 require_quiet(ok, out);
599 require_action_quiet(attestationData = CFRetainSafe(CFDictionaryGetValue(outputAttributes, CFSTR(kTKTokenControlAttribAttestationData))),
600 out, SecError(errSecInternal, error, CFSTR("could not get attestation data")));
603 CFReleaseSafe(attributes);
604 CFReleaseSafe(outputAttributes);
605 CFReleaseSafe(localError);
606 CFReleaseSafe(auth_params.mutable_dictionary);
607 CFReleaseSafe(token);
608 return attestationData;
611 Boolean SecKeyControlLifetime(SecKeyRef key, SecKeyControlLifetimeType type, CFErrorRef *error) {
615 error = (void *)&localError;
618 SecCTKKeyData *keyData = key->key;
619 NSDictionary *attributes = @{
620 @kTKTokenControlAttribLifetimeControlKey: (__bridge NSData *)keyData->object_id,
621 @kTKTokenControlAttribLifetimeType: @(type),
624 if (key->key_class != &kSecCTKKeyDescriptor) {
625 return SecError(errSecUnsupportedOperation, error, CFSTR("lifetimecontrol not supported for key %@"), key);
628 __block SecCFDictionaryCOW auth_params = { keyData->auth_params.dictionary };
629 return SecItemAuthDo(&auth_params, error, ^SecItemAuthResult(CFArrayRef *ac_pairs, CFErrorRef *error) {
630 if (auth_params.mutable_dictionary != NULL || token == NULL) {
631 token = CFBridgingRelease(SecCTKKeyCopyToken(key, error));
633 return kSecItemAuthResultError;
637 NSDictionary *outputAttributes = CFBridgingRelease(TKTokenControl((__bridge TKTokenRef)token, (__bridge CFDictionaryRef)attributes, error));
638 return outputAttributes ? kSecItemAuthResultOK : kSecItemAuthResultError;
642 #if TKTOKEN_CLIENT_INTERFACE_VERSION < 5
643 #define kTKTokenCreateAttributeTestMode "testmode"
646 void SecCTKKeySetTestMode(CFStringRef tokenID, CFTypeRef enable) {
647 CFErrorRef error = NULL;
648 CFDictionaryRef options = CFDictionaryCreateForCFTypes(kCFAllocatorDefault, kSecAttrTokenID, tokenID, @kTKTokenCreateAttributeTestMode, enable, nil);
649 TKTokenRef token = TKTokenCreate(options, &error);
651 secerror("Failed to set token attributes %@: error %@", options, error);
653 CFReleaseNull(options);
654 CFReleaseNull(error);
655 CFReleaseNull(token);