]> git.saurik.com Git - apple/security.git/blob - OSX/sec/Security/SecCTKKey.m
Security-59306.101.1.tar.gz
[apple/security.git] / OSX / sec / Security / SecCTKKey.m
1 /*
2 * Copyright (c) 2015 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #import <Foundation/Foundation.h>
25
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"
41
42 #include "SecECKey.h"
43 #include "SecRSAKey.h"
44 #include "SecCTKKeyPriv.h"
45
46 const CFStringRef kSecUseToken = CFSTR("u_Token");
47
48 typedef struct {
49 TKTokenRef token;
50 CFStringRef token_id;
51 CFDataRef object_id;
52 SecCFDictionaryCOW auth_params;
53 SecCFDictionaryCOW attributes;
54 CFMutableDictionaryRef params;
55 } SecCTKKeyData;
56
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);
65 }
66
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;
73 }
74 return kSecRSAAlgorithmID;
75 }
76
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 &&
80 operation != NULL) {
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));
85
86 CFReleaseNull(*error);
87 CFRelease(ac_pair);
88 CFRelease(access_control);
89 return kSecItemAuthResultNeedAuth;
90 }
91 }
92 return kSecItemAuthResultError;
93 }
94
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);
101 }
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);
105 }
106
107 out:
108 CFReleaseNull(attributes.mutable_dictionary);
109 return token;
110 }
111
112 static TKTokenRef SecCTKKeyCopyToken(SecKeyRef key, CFErrorRef *error) {
113 SecCTKKeyData *kd = key->key;
114 TKTokenRef token = CFRetainSafe(kd->token);
115 if (token == NULL) {
116 token = SecCTKKeyCreateToken(key, kd->auth_params.dictionary, NULL, error);
117 }
118 return token;
119 }
120
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;
129
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));
135 if (token == NULL) {
136 return kSecItemAuthResultError;
137 }
138 }
139
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);
149 }
150 if (in2 != NULL && CFGetTypeID(in2) == CFDataGetTypeID()) {
151 inputSize += CFDataGetLength(in2);
152 }
153 if (inputSize > 32 * 1024) {
154 result = TKTokenCopyOperationResult(token, kd->object_id, operation, algorithms, kSecKeyOperationModeCheckIfSupported,
155 NULL, NULL, error);
156 }
157 }
158
159 if (CFEqualSafe(result, kCFBooleanTrue)) {
160 result = TKTokenCopyOperationResult(token, kd->object_id, operation, algorithms, mode, in1, in2, error);
161 }
162
163 if (result != NULL) {
164 return kSecItemAuthResultOK;
165 }
166
167 CFStringRef AKSOperation = NULL;
168 switch (operation) {
169 case kSecKeyOperationTypeSign:
170 AKSOperation = kAKSKeyOpSign;
171 break;
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;
177 }
178 break;
179 }
180 case kSecKeyOperationTypeKeyExchange:
181 AKSOperation = kAKSKeyOpComputeKey;
182 break;
183 default:
184 break;;
185 }
186 return SecCTKProcessError(AKSOperation, token, kd->object_id, ac_pairs, error);
187 }, ^{
188 CFAssignRetained(token, SecCTKKeyCreateToken(key, auth_params.dictionary, &last_params, NULL));
189 });
190
191 CFErrorPropagate(localError, error);
192 CFReleaseNull(auth_params.mutable_dictionary);
193 CFReleaseNull(token);
194 CFReleaseNull(last_params);
195 return result;
196 }
197
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()) {
202 CFIndex bitSize;
203 if (CFNumberGetValue(keySize, kCFNumberCFIndexType, &bitSize))
204 return (bitSize + 7) / 8;
205 }
206
207 return 0;
208 }
209
210 static OSStatus SecCTKKeyCopyPublicOctets(SecKeyRef key, CFDataRef *data) {
211 OSStatus status = errSecSuccess;
212 CFErrorRef error = NULL;
213 CFDataRef publicData = NULL;
214 TKTokenRef token = NULL;
215
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));
220 *data = publicData;
221
222 out:
223 CFReleaseSafe(error);
224 CFReleaseSafe(token);
225 return status;
226 }
227
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);
232 }
233
234 // Attributes allowed to be exported from all internal key attributes.
235 static const CFStringRef *kSecExportableCTKKeyAttributes[] = {
236 &kSecClass,
237 &kSecAttrTokenID,
238 &kSecAttrKeyClass,
239 &kSecAttrAccessControl,
240 &kSecAttrIsPrivate,
241 &kSecAttrIsModifiable,
242 &kSecAttrKeyType,
243 &kSecAttrKeySizeInBits,
244 &kSecAttrEffectiveKeySize,
245 &kSecAttrIsSensitive,
246 &kSecAttrWasAlwaysSensitive,
247 &kSecAttrIsExtractable,
248 &kSecAttrWasNeverExtractable,
249 &kSecAttrCanEncrypt,
250 &kSecAttrCanDecrypt,
251 &kSecAttrCanDerive,
252 &kSecAttrCanSign,
253 &kSecAttrCanVerify,
254 &kSecAttrCanSignRecover,
255 &kSecAttrCanVerifyRecover,
256 &kSecAttrCanWrap,
257 &kSecAttrCanUnwrap,
258 NULL
259 };
260
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;
267
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);
271
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);
276
277 for (const CFStringRef **attrKey = &kSecExportableCTKKeyAttributes[0]; *attrKey != NULL; attrKey++) {
278 CFTypeRef value = CFDictionaryGetValue(kd->attributes.dictionary, **attrKey);
279 if (value != NULL) {
280 CFDictionarySetValue(attrs, **attrKey, value);
281 }
282 }
283
284 // Consistently with existing RSA and EC software keys implementation, mark all keys as permanent ones.
285 CFDictionarySetValue(attrs, kSecAttrIsPermanent, kCFBooleanTrue);
286
287 // Always export token_id and object_id.
288 CFDictionarySetValue(attrs, kSecAttrTokenID, kd->token_id);
289 CFDictionarySetValue(attrs, kSecAttrTokenOID, kd->object_id);
290
291 out:
292 CFReleaseSafe(error);
293 CFReleaseSafe(publicData);
294 CFReleaseSafe(digest);
295 CFReleaseSafe(token);
296 return attrs;
297 }
298
299 static SecKeyRef SecCTKKeyCreateDuplicate(SecKeyRef key);
300
301 static Boolean SecCTKKeySetParameter(SecKeyRef key, CFStringRef name, CFPropertyListRef value, CFErrorRef *error) {
302 SecCTKKeyData *kd = key->key;
303 CFTypeRef acm_reference = NULL;
304
305 static const CFStringRef *const knownUseFlags[] = {
306 &kSecUseOperationPrompt,
307 &kSecUseAuthenticationContext,
308 &kSecUseAuthenticationUI,
309 &kSecUseCallerName,
310 &kSecUseCredentialReference,
311 };
312
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)) {
317 isUseFlag = true;
318 break;
319 }
320 }
321
322 if (CFEqual(name, kSecUseAuthenticationContext)) {
323 // Preprocess LAContext to ACMRef value.
324 if (value != NULL) {
325 require_quiet(acm_reference = LACopyACMContext(value, error), out);
326 value = acm_reference;
327 }
328 name = kSecUseCredentialReference;
329 }
330
331 // Release existing token connection to enforce creation of new connection with new params.
332 CFReleaseNull(kd->token);
333
334 if (isUseFlag) {
335 if (value != NULL) {
336 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&kd->auth_params), name, value);
337 } else {
338 CFDictionaryRemoveValue(SecCFDictionaryCOWGetMutable(&kd->auth_params), name);
339 }
340 } else {
341 if (kd->params == NULL) {
342 kd->params = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
343 }
344 if (value != NULL) {
345 CFDictionarySetValue(kd->params, name, value);
346 } else {
347 CFDictionaryRemoveValue(kd->params, name);
348 }
349 }
350
351 out:
352 CFReleaseSafe(acm_reference);
353 return TRUE;
354 }
355
356 static SecKeyDescriptor kSecCTKKeyDescriptor = {
357 .version = kSecKeyDescriptorVersion,
358 .name = "CTKKey",
359 .extraBytes = sizeof(SecCTKKeyData),
360
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,
370 };
371
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);
381 }
382 if (kd->auth_params.dictionary != NULL) {
383 rd->auth_params.dictionary = kd->auth_params.dictionary;
384 SecCFDictionaryCOWGetMutable(&rd->auth_params);
385 }
386 return result;
387 }
388
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);
402 }
403
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[] = {
407 &kSecAttrKeyType,
408 &kSecAttrKeyClass,
409 NULL,
410 };
411
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);
421 });
422
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);
428 CFRelease(ac);
429 }
430 CFDictionaryRemoveValue(SecCFDictionaryCOWGetMutable(&kd->attributes), kSecAttrTokenOID);
431 }
432 require_quiet(kd->token != NULL && kd->object_id != NULL, out);
433 }
434
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()) {
438 CFIndex number;
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);
443 CFRelease(newValue);
444 }
445 }
446 }
447 }
448 result = (SecKeyRef)CFRetain(key);
449
450 out:
451 CFReleaseSafe(attrs);
452 CFReleaseSafe(key);
453 return result;
454 }
455
456 OSStatus SecCTKKeyGeneratePair(CFDictionaryRef parameters, SecKeyRef *publicKey, SecKeyRef *privateKey) {
457 OSStatus status;
458 __block SecCFDictionaryCOW attrs = { NULL };
459 CFDataRef publicData = NULL;
460
461 require_action_quiet(publicKey != NULL, out, status = errSecParam);
462 require_action_quiet(privateKey != NULL, out, status = errSecParam);
463
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);
467
468 CFDictionaryForEach(parameters, ^(const void *key, const void *value) {
469 if (!CFEqual(key, kSecPrivateKeyAttrs) && !CFEqual(key, kSecPublicKeyAttrs)) {
470 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&attrs), key, value);
471 }
472 });
473 CFDictionaryRemoveValue(SecCFDictionaryCOWGetMutable(&attrs), kSecValueData);
474 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&attrs), kSecClass, kSecClassKey);
475 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&attrs), kSecAttrKeyClass, kSecAttrKeyClassPrivate);
476 CFDictionarySetValue(SecCFDictionaryCOWGetMutable(&attrs), kSecReturnRef, kCFBooleanTrue);
477
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);
480
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);
483
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);
494 }
495
496 if (*publicKey != NULL) {
497 status = errSecSuccess;
498 } else {
499 status = errSecInvalidKey;
500 CFReleaseNull(*privateKey);
501 }
502
503 out:
504 CFReleaseSafe(attrs.mutable_dictionary);
505 CFReleaseSafe(publicData);
506 return status;
507 }
508
509 const CFStringRef kSecKeyParameterSETokenAttestationNonce = CFSTR("com.apple.security.seckey.setoken.attestation-nonce");
510
511 SecKeyRef SecKeyCopyAttestationKey(SecKeyAttestationKeyType keyType, CFErrorRef *error) {
512 CFDictionaryRef attributes = NULL;
513 CFDataRef object_id = NULL;
514 SecKeyRef key = NULL;
515
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' };
524
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' };
526
527 CFStringRef token = kSecAttrTokenIDAppleKeyStore;
528
529 switch (keyType) {
530 case kSecKeyAttestationKeyTypeSIK:
531 object_id = CFDataCreate(kCFAllocatorDefault, sikObjectIDBytes, sizeof(sikObjectIDBytes));
532 break;
533 case kSecKeyAttestationKeyTypeGID:
534 object_id = CFDataCreate(kCFAllocatorDefault, gidObjectIDBytes, sizeof(gidObjectIDBytes));
535 break;
536 case kSecKeyAttestationKeyTypeUIKCommitted:
537 object_id = CFDataCreate(kCFAllocatorDefault, uikCommittedObjectIDBytes, sizeof(uikCommittedObjectIDBytes));
538 break;
539 case kSecKeyAttestationKeyTypeUIKProposed:
540 object_id = CFDataCreate(kCFAllocatorDefault, uikProposedObjectIDBytes, sizeof(uikProposedObjectIDBytes));
541 break;
542 case kSecKeyAttestationKeyTypeSecureElement:
543 object_id = CFDataCreate(kCFAllocatorDefault, casdObjectIDBytes, sizeof(casdObjectIDBytes));
544 token = kSecAttrTokenIDSecureElement;
545 break;
546 default:
547 SecError(errSecParam, error, CFSTR("unexpected attestation key type %d"), (int)keyType);
548 goto out;
549 }
550
551 attributes = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
552 kSecAttrTokenOID, object_id,
553 kSecAttrTokenID, token,
554 NULL);
555 key = SecKeyCreateCTKKey(kCFAllocatorDefault, attributes, error);
556
557 out:
558 CFReleaseSafe(attributes);
559 CFReleaseSafe(object_id);
560 return key;
561 }
562
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;
570
571 if (error == NULL) {
572 error = &localError;
573 }
574
575 __block SecCFDictionaryCOW auth_params = { keyToAttestData->auth_params.dictionary };
576
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));
581
582 attributes = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
583 CFSTR(kTKTokenControlAttribAttestingKey), attestingKeyData->object_id,
584 CFSTR(kTKTokenControlAttribKeyToAttest), keyToAttestData->object_id,
585 NULL);
586
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));
590 if (token == NULL) {
591 return kSecItemAuthResultError;
592 }
593 }
594
595 outputAttributes = TKTokenControl(token, attributes, error);
596 return outputAttributes ? kSecItemAuthResultOK : SecCTKProcessError(kAKSKeyOpAttest, keyToAttestData->token, keyToAttestData->object_id, ac_pairs, error);
597 }, NULL);
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")));
601
602 out:
603 CFReleaseSafe(attributes);
604 CFReleaseSafe(outputAttributes);
605 CFReleaseSafe(localError);
606 CFReleaseSafe(auth_params.mutable_dictionary);
607 CFReleaseSafe(token);
608 return attestationData;
609 }
610
611 Boolean SecKeyControlLifetime(SecKeyRef key, SecKeyControlLifetimeType type, CFErrorRef *error) {
612 NSError *localError;
613 __block id token;
614 if (error == NULL) {
615 error = (void *)&localError;
616 }
617
618 SecCTKKeyData *keyData = key->key;
619 NSDictionary *attributes = @{
620 @kTKTokenControlAttribLifetimeControlKey: (__bridge NSData *)keyData->object_id,
621 @kTKTokenControlAttribLifetimeType: @(type),
622 };
623
624 if (key->key_class != &kSecCTKKeyDescriptor) {
625 return SecError(errSecUnsupportedOperation, error, CFSTR("lifetimecontrol not supported for key %@"), key);
626 }
627
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));
632 if (token == nil) {
633 return kSecItemAuthResultError;
634 }
635 }
636
637 NSDictionary *outputAttributes = CFBridgingRelease(TKTokenControl((__bridge TKTokenRef)token, (__bridge CFDictionaryRef)attributes, error));
638 return outputAttributes ? kSecItemAuthResultOK : kSecItemAuthResultError;
639 }, NULL);
640 }
641
642 #if TKTOKEN_CLIENT_INTERFACE_VERSION < 5
643 #define kTKTokenCreateAttributeTestMode "testmode"
644 #endif
645
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);
650 if (token == NULL) {
651 secerror("Failed to set token attributes %@: error %@", options, error);
652 }
653 CFReleaseNull(options);
654 CFReleaseNull(error);
655 CFReleaseNull(token);
656 }