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 <CoreFoundation/CoreFoundation.h>
27 #include <Security/SecFramework.h>
28 #include <Security/SecBase.h>
29 #include <Security/SecItem.h>
30 #include <Security/SecItemPriv.h>
31 #include <Security/SecKey.h>
32 #include <Security/SecKeyPriv.h>
33 #include <Security/SecECKey.h>
34 #include <Security/SecAccessControl.h>
35 #include <Security/SecAccessControlPriv.h>
36 #include <Security/SecInternal.h>
37 #include <Security/SecCertificatePriv.h>
38 #include <utilities/SecFileLocations.h>
39 #include <utilities/SecCFWrappers.h>
40 #include <utilities/SecCFError.h>
41 #include <utilities/SecCFRelease.h>
42 #include <Security/SecBase64.h>
44 #include <libaks_acl_cf_keys.h>
46 #include <ctkclient/ctkclient_test.h>
47 #include <coreauthd_spi.h>
49 #include "secd_regressions.h"
51 #include "SecdTestKeychainUtilities.h"
52 #include "SecKeybagSupport.h"
54 const char *cert1 = "MIIFQzCCBCugAwIBAgIBAjANBgkqhkiG9w0BAQsFADAyMQswCQYDVQQGEwJVUzENMAsGA1UEChMETklTVDEUMBIGA1UEAxMLUElWIFRlc3QgQ0EwHhcNMTUwOTE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2lv6Ho0EsOrwPhaBRaO3EFUyjeNMxsvG8Dr9Y5u2B38ESB4OsLKHq0eD/WZjEAlyGx16Qi7YlLiHGfLMorgkg9Mbp73guNO1PItDTAnqHUUOlQ01ThNug0sR5ua1zlNFx6AIPoX4yAPrtlEMZtbsevsXlgDpO1zc26p5icBmQHYT7uzdTEEN4tmcxXg6Z/dGB63GCluf+Pc+ovRt/MMt2EbcIuwJ9C516H";
58 "MIICETCCAbigAwIBAgIJANiM7uTufLiKMAkGByqGSM49BAEwgZIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTESMBAGA1UEBxMJQ3VwZXJ0aW5vMRMwEQYDVQQKEwpBcHBsZSBJbmMuMQ8wDQYDVQQLEwZDb3JlT1MxGjAYBgNVBAMTEUFwcGxlIFRlc3QgQ0EyIEVDMSAwHgYJKoZIhvcNAQkBFhF2a3V6ZWxhQGFwcGxlLmNvbTAeFw0xNjA1MTIxMTMyMzlaFw0yNjA1MTAxMTMyMzlaMGYxEDAOBgNVBAMTB3NldG9rZW4xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTESMBAGA1UEBxMJQ3VwZXJ0aW5vMRMwEQYDVQQKEwpBcHBsZSBJbmMuMQ8wDQYDVQQLEwZDb3JlT1MwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQHKxfYgbqRHmThPnO9yQX5KrL/EPa6dZU52Wys5gC3/Mk0dNt9dLhpWblAVaeBzkos4juN3cxbnoB9MsC4bvoLoyMwITAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwICBDAJBgcqhkjOPQQBA0gAMEUCIQClcoYLhEA/xIGU94ZBcup26Pb7pXaWaaOM3+9z510TRwIgV/iprC051SuQzkqXA5weVliJOohFYjO+gUoH/6MJpDg=";
60 extern void LASetErrorCodeBlock(CFErrorRef (^newCreateErrorBlock)(void));
62 static void test_item_add(void) {
64 static const UInt8 data[] = { 0x01, 0x02, 0x03, 0x04 };
65 CFDataRef valueData = CFDataCreate(NULL, data, sizeof(data));
66 __block NSUInteger objIDIdx = 0;
68 CFMutableDictionaryRef attrs = CFDictionaryCreateMutableForCFTypesWith(NULL,
69 kSecClass, kSecClassGenericPassword,
70 kSecAttrTokenID, CFSTR("tokenid"),
71 kSecAttrService, CFSTR("ctktest-service"),
72 kSecValueData, valueData,
73 kSecReturnAttributes, kCFBooleanTrue,
76 __block int phase = 0;
77 TKTokenTestSetHook(^(CFDictionaryRef attributes, TKTokenTestBlocks *blocks) {
79 eq_cf(CFDictionaryGetValue(attributes, kSecAttrTokenID), CFSTR("tokenid"));
81 blocks->createOrUpdateObject = ^CFDataRef(CFDataRef objectID, CFMutableDictionaryRef at, CFErrorRef *error) {
84 eq_cf(CFDictionaryGetValue(at, kSecClass), kSecClassGenericPassword);
85 eq_cf(CFDictionaryGetValue(at, kSecAttrService), CFDictionaryGetValue(attrs, kSecAttrService));
86 eq_cf(CFDictionaryGetValue(at, kSecAttrTokenID), CFSTR("tokenid"));
87 eq_cf(CFDictionaryGetValue(at, kSecValueData), valueData);
88 CFDictionaryRemoveValue(at, kSecValueData);
90 return (__bridge_retained CFDataRef)[NSData dataWithBytes:&objIDIdx length:sizeof(objIDIdx)];
93 blocks->copyObjectAccessControl = ^CFDataRef(CFDataRef oid, CFErrorRef *error) {
95 SecAccessControlRef ac = SecAccessControlCreate(NULL, NULL);
96 SecAccessControlSetProtection(ac, kSecAttrAccessibleAlwaysPrivate, NULL);
97 test_IsTrue(SecAccessControlAddConstraintForOperation(ac, kAKSKeyOpDefaultAcl, kCFBooleanTrue, NULL));
98 CFDataRef acData = SecAccessControlCopyData(ac);
103 blocks->copyObjectData = ^CFTypeRef(CFDataRef oid, CFErrorRef *error) {
105 return CFRetain(valueData);
109 CFTypeRef result = NULL;
110 ok_status(SecItemAdd(attrs, &result));
111 eq_cf(CFDictionaryGetValue(result, kSecAttrService), CFSTR("ctktest-service"));
112 eq_cf(CFDictionaryGetValue(result, kSecAttrTokenID), CFSTR("tokenid"));
113 is(CFDictionaryGetValue(result, kSecValueData), NULL);
114 CFReleaseNull(result);
119 CFDictionarySetValue(attrs, kSecReturnData, kCFBooleanTrue);
120 CFDictionarySetValue(attrs, kSecAttrService, CFSTR("ctktest-service1"));
121 ok_status(SecItemAdd(attrs, &result));
122 eq_cf(CFDictionaryGetValue(result, kSecAttrService), CFSTR("ctktest-service1"));
123 eq_cf(CFDictionaryGetValue(result, kSecAttrTokenID), CFSTR("tokenid"));
124 eq_cf(CFDictionaryGetValue(result, kSecValueData), valueData);
125 CFReleaseNull(result);
130 CFDictionaryRemoveValue(attrs, kSecReturnAttributes);
131 CFDictionarySetValue(attrs, kSecAttrAccount, CFSTR("2nd"));
132 ok_status(SecItemAdd(attrs, &result));
133 eq_cf(result, valueData);
134 CFReleaseNull(result);
138 CFRelease(valueData);
141 static void test_item_query() {
142 static const UInt8 data[] = { 0x01, 0x02, 0x03, 0x04 };
143 CFDataRef valueData = CFDataCreate(NULL, data, sizeof(data));
144 CFDataRef valueData2 = CFDataCreate(NULL, data, sizeof(data) - 1);
146 __block int phase = 0;
147 TKTokenTestSetHook(^(CFDictionaryRef attributes, TKTokenTestBlocks *blocks) {
149 eq_cf(CFDictionaryGetValue(attributes, kSecAttrTokenID), CFSTR("tokenid"));
151 blocks->copyObjectData = ^CFTypeRef(CFDataRef oid, CFErrorRef *error) {
153 return CFRetain(valueData);
157 // Add non-token item with the same service, to test queries returning mixed results.
158 CFMutableDictionaryRef attrs = CFDictionaryCreateMutableForCFTypesWith(NULL,
159 kSecClass, kSecClassGenericPassword,
160 kSecAttrService, CFSTR("ctktest-service"),
161 kSecValueData, valueData2,
163 ok_status(SecItemAdd(attrs, NULL));
166 // Query with service.
167 CFMutableDictionaryRef query;
168 query = CFDictionaryCreateMutableForCFTypesWith(NULL,
169 kSecClass, kSecClassGenericPassword,
170 kSecAttrService, CFSTR("ctktest-service"),
171 kSecReturnAttributes, kCFBooleanTrue,
172 kSecReturnData, kCFBooleanTrue,
176 CFTypeRef result = NULL;
177 ok_status(SecItemCopyMatching(query, &result));
179 is(CFGetTypeID(result), CFDictionaryGetTypeID());
180 eq_cf(CFDictionaryGetValue(result, kSecValueData), valueData);
181 is(CFGetTypeID(CFDictionaryGetValue(result, kSecAttrAccessControl)), SecAccessControlGetTypeID());
182 eq_cf(CFDictionaryGetValue(result, kSecAttrService), CFSTR("ctktest-service"));
183 CFReleaseSafe(result);
186 CFDictionarySetValue(query, kSecMatchLimit, kSecMatchLimitAll);
187 ok_status(SecItemCopyMatching(query, &result));
189 is(CFGetTypeID(result), CFArrayGetTypeID());
190 is(CFArrayGetCount(result), 2);
191 CFReleaseSafe(result);
194 CFDictionaryRemoveValue(query, kSecMatchLimit);
195 CFDictionaryRemoveValue(query, kSecReturnData);
196 ok_status(SecItemCopyMatching(query, &result));
198 is(CFGetTypeID(result), CFDictionaryGetTypeID());
199 is(CFDictionaryGetValue(result, kSecValueData), NULL);
200 CFReleaseSafe(result);
203 CFDictionaryRemoveValue(query, kSecReturnAttributes);
204 CFDictionarySetValue(query, kSecReturnData, kCFBooleanTrue);
205 CFDictionarySetValue(query, kSecAttrTokenID, CFSTR("tokenid"));
206 ok_status(SecItemCopyMatching(query, &result));
208 eq_cf(result, valueData);
209 CFReleaseSafe(result);
211 static const uint8_t tk_persistent_ref_id[] = {'t', 'k', 'p', 'r'};
212 NSData *persistentRefId = [NSData dataWithBytes:tk_persistent_ref_id length:sizeof(tk_persistent_ref_id)];
214 ok_status(SecItemCopyMatching((__bridge CFDictionaryRef)@{ (id)kSecClass : (id)kSecClassGenericPassword,
215 (id)kSecAttrService : @"ctktest-service",
216 (id)kSecReturnPersistentRef : @YES }, &result));
218 NSData *persistentRef = (__bridge NSData *)result;
219 is(CFDataCompare((__bridge CFDataRef)persistentRefId, (__bridge CFDataRef)[persistentRef subdataWithRange:NSMakeRange(0, 4)]), kCFCompareEqualTo);
220 CFReleaseSafe(result);
223 ok_status(SecItemCopyMatching((__bridge CFDictionaryRef)@{ (id)kSecClass : (id)kSecClassGenericPassword,
224 (id)kSecAttrService : @"ctktest-service",
225 (id)kSecReturnData : @YES,
226 (id)kSecReturnPersistentRef : @YES }, &result));
228 persistentRef = ((__bridge NSDictionary *)result)[(id)kSecValuePersistentRef];
229 is(CFDataCompare((__bridge CFDataRef)persistentRefId, (__bridge CFDataRef)[persistentRef subdataWithRange:NSMakeRange(0, 4)]), kCFCompareEqualTo);
230 CFReleaseSafe(result);
233 ok_status(SecItemCopyMatching((__bridge CFDictionaryRef)@{ (id)kSecClass : (id)kSecClassGenericPassword,
234 (id)kSecAttrService : @"ctktest-service",
235 (id)kSecReturnAttributes : @YES,
236 (id)kSecReturnPersistentRef : @YES }, &result));
238 persistentRef = ((__bridge NSDictionary *)result)[(id)kSecValuePersistentRef];
239 is(CFDataCompare((__bridge CFDataRef)persistentRefId, (__bridge CFDataRef)[persistentRef subdataWithRange:NSMakeRange(0, 4)]), kCFCompareEqualTo);
240 CFReleaseSafe(result);
243 ok_status(SecItemCopyMatching((__bridge CFDictionaryRef)@{ (id)kSecClass : (id)kSecClassGenericPassword,
244 (id)kSecAttrService : @"ctktest-service",
245 (id)kSecReturnData : @YES,
246 (id)kSecReturnAttributes : @YES,
247 (id)kSecReturnPersistentRef : @YES }, &result));
249 persistentRef = ((__bridge NSDictionary *)result)[(id)kSecValuePersistentRef];
250 is(CFDataCompare((__bridge CFDataRef)persistentRefId, (__bridge CFDataRef)[persistentRef subdataWithRange:NSMakeRange(0, 4)]), kCFCompareEqualTo);
251 CFReleaseSafe(result);
254 CFRelease(valueData);
255 CFRelease(valueData2);
258 static void test_item_update() {
259 static const UInt8 data[] = { 0x01, 0x02, 0x03, 0x04 };
260 CFDataRef valueData2 = CFDataCreate(NULL, data, sizeof(data) - 1);
261 CFTypeRef result = NULL;
263 CFMutableDictionaryRef query, attrs;
266 __block int phase = 0;
267 __block bool store_value = false;
268 TKTokenTestSetHook(^(CFDictionaryRef attributes, TKTokenTestBlocks *blocks) {
270 eq_cf(CFDictionaryGetValue(attributes, kSecAttrTokenID), CFSTR("tokenid"));
272 blocks->createOrUpdateObject = ^CFDataRef(CFDataRef objectID, CFMutableDictionaryRef at, CFErrorRef *error) {
274 eq_cf(CFDictionaryGetValue(at, kSecValueData), valueData2);
276 CFDictionaryRemoveValue(at, kSecValueData);
278 return CFRetainSafe(objectID);
281 blocks->copyObjectAccessControl = ^CFDataRef(CFDataRef oid, CFErrorRef *error) {
283 SecAccessControlRef ac = SecAccessControlCreate(NULL, NULL);
284 SecAccessControlSetProtection(ac, kSecAttrAccessibleAlwaysPrivate, NULL);
285 test_IsTrue(SecAccessControlAddConstraintForOperation(ac, kAKSKeyOpDefaultAcl, kCFBooleanTrue, NULL));
286 CFDataRef acData = SecAccessControlCopyData(ac);
291 blocks->copyObjectData = ^CFTypeRef(CFDataRef oid, CFErrorRef *error) {
293 return CFRetain(valueData2);
297 query = CFDictionaryCreateMutableForCFTypesWith(NULL,
298 kSecClass, kSecClassGenericPassword,
299 kSecAttrTokenID, CFSTR("tokenid"),
300 kSecAttrService, CFSTR("ctktest-service"),
303 attrs = CFDictionaryCreateMutableForCFTypesWith(NULL,
304 kSecValueData, valueData2,
307 ok_status(SecItemUpdate(query, attrs));
311 CFDictionarySetValue(query, kSecReturnData, kCFBooleanTrue);
312 ok_status(SecItemCopyMatching(query, &result));
313 eq_cf(valueData2, result);
319 CFDictionaryRemoveValue(query, kSecReturnData);
320 ok_status(SecItemUpdate(query, attrs));
324 CFDictionarySetValue(query, kSecReturnData, kCFBooleanTrue);
325 ok_status(SecItemCopyMatching(query, &result));
326 eq_cf(valueData2, result);
331 CFDictionarySetValue(query, kSecAttrService, CFSTR("ctktest-service1"));
332 CFDictionaryRemoveValue(query, kSecReturnData);
333 ok_status(SecItemUpdate(query, attrs));
337 CFDictionarySetValue(query, kSecMatchLimit, kSecMatchLimitAll);
338 CFDictionarySetValue(query, kSecReturnData, kCFBooleanTrue);
339 ok_status(SecItemCopyMatching(query, &result));
341 is(CFGetTypeID(result), CFArrayGetTypeID());
342 is(CFArrayGetCount(result), 2);
343 eq_cf(CFArrayGetValueAtIndex(result, 0), valueData2);
344 eq_cf(CFArrayGetValueAtIndex(result, 1), valueData2);
348 CFRelease(valueData2);
351 static void test_item_delete(void) {
353 CFMutableDictionaryRef query;
356 __block int phase = 0;
357 __block CFErrorRef deleteError = NULL;
358 TKTokenTestSetHook(^(CFDictionaryRef attributes, TKTokenTestBlocks *blocks) {
360 eq_cf(CFDictionaryGetValue(attributes, kSecAttrTokenID), CFSTR("tokenid"));
362 blocks->copyObjectAccessControl = ^CFDataRef(CFDataRef oid, CFErrorRef *error) {
364 SecAccessControlRef ac = SecAccessControlCreate(NULL, NULL);
365 SecAccessControlSetProtection(ac, kSecAttrAccessibleAlwaysPrivate, NULL);
366 test_IsTrue(SecAccessControlAddConstraintForOperation(ac, kAKSKeyOpDefaultAcl, kCFBooleanTrue, NULL));
367 CFDataRef acData = SecAccessControlCopyData(ac);
372 blocks->deleteObject = ^bool(CFDataRef objectID, CFErrorRef *error) {
374 if (deleteError != NULL) {
375 CFAssignRetained(*error, deleteError);
383 query = CFDictionaryCreateMutableForCFTypesWith(NULL,
384 kSecClass, kSecClassGenericPassword,
385 kSecAttrTokenID, CFSTR("tokenid"),
386 kSecAttrService, CFSTR("ctktest-service"),
390 ok_status(SecItemDelete(query));
394 is_status(SecItemCopyMatching(query, &result), errSecItemNotFound);
398 CFDictionarySetValue(query, kSecAttrService, CFSTR("ctktest-service1"));
399 ok_status(SecItemCopyMatching(query, &result));
403 #if LA_CONTEXT_IMPLEMENTED
404 LASetErrorCodeBlock(^{ return (CFErrorRef)NULL; });
405 deleteError = CFErrorCreate(NULL, CFSTR(kTKErrorDomain), kTKErrorCodeAuthenticationNeeded, NULL);
406 ok_status(SecItemDelete(query), "delete multiple token items");
407 is(phase, 6, "connect + delete-auth-fail + copyAccess + connect + delete + delete-2nd");
409 ok_status(SecItemDelete(query), "delete multiple token items");
410 is(phase, 3, "connect + delete + delete");
414 is_status(SecItemCopyMatching(query, &result), errSecItemNotFound);
417 is_status(SecItemDelete(query), errSecItemNotFound);
420 CFReleaseSafe(deleteError);
423 static void test_key_generate(int globalPersistence, int privatePersistence, int publicPersistence,
424 bool privateIsPersistent, bool publicIsPersistent) {
425 __block int phase = 0;
426 TKTokenTestSetHook(^(CFDictionaryRef attributes, TKTokenTestBlocks *blocks) {
429 blocks->createOrUpdateObject = ^CFDataRef(CFDataRef objectID, CFMutableDictionaryRef at, CFErrorRef *error) {
431 CFTypeRef keyClass = CFDictionaryGetValue(at, kSecAttrKeyClass) ?: kSecAttrKeyClassPrivate;
432 eq_cf(keyClass, kSecAttrKeyClassPrivate, "only private keys can be created on token");
433 NSDictionary *params = @{ (id)kSecAttrKeyType: (id)kSecAttrKeyTypeECSECPrimeRandom, (id)kSecAttrKeySizeInBits: @256, (id)kSecAttrKeyClass: (id)kSecAttrKeyClassPrivate };
434 if (objectID != NULL) {
436 privateKey = CFBridgingRelease(SecKeyCreateWithData((CFDataRef)objectID, (CFDictionaryRef)params, NULL));
439 privateKey = CFBridgingRelease(SecKeyCreateRandomKey((__bridge CFDictionaryRef)params, error));
441 NSDictionary *privKeyAttrs = CFBridgingRelease(SecKeyCopyAttributes((SecKeyRef)privateKey));
442 CFDictionarySetValue(at, kSecClass, kSecClassKey);
443 CFDictionarySetValue(at, kSecAttrKeyType, kSecAttrKeyTypeECSECPrimeRandom);
444 CFDictionarySetValue(at, kSecAttrKeySizeInBits, CFSTR("256"));
445 CFDictionarySetValue(at, kSecAttrKeyClass, kSecAttrKeyClassPrivate);
446 return CFBridgingRetain(privKeyAttrs[(id)kSecValueData]);
449 blocks->copyObjectAccessControl = ^CFDataRef(CFDataRef oid, CFErrorRef *error) {
451 SecAccessControlRef ac = SecAccessControlCreate(NULL, NULL);
452 SecAccessControlSetProtection(ac, kSecAttrAccessibleAlwaysPrivate, NULL);
453 test_IsTrue(SecAccessControlAddConstraintForOperation(ac, kAKSKeyOpDefaultAcl, kCFBooleanTrue, NULL));
454 CFDataRef acData = SecAccessControlCopyData(ac);
459 blocks->copyPublicKeyData = ^CFDataRef(CFDataRef objectID, CFErrorRef *error) {
461 SecKeyRef privKey = SecKeyCreateECPrivateKey(NULL, CFDataGetBytePtr(objectID), CFDataGetLength(objectID), kSecKeyEncodingBytes);
462 CFDataRef publicData;
463 SecKeyCopyPublicBytes(privKey, &publicData);
468 blocks->copyObjectData = ^CFTypeRef(CFDataRef oid, CFErrorRef *error) {
474 NSMutableDictionary *params = @{ (id)kSecAttrKeyType: (id)kSecAttrKeyTypeEC,
475 (id)kSecAttrKeySizeInBits: @"256",
476 (id)kSecAttrTokenID: @"tokenid",
478 if (globalPersistence >= 0) {
479 params[(id)kSecAttrIsPermanent] = globalPersistence ? @YES : @NO;
481 if (publicPersistence >= 0) {
482 params[(id)kSecPublicKeyAttrs] = @{ (id)kSecAttrIsPermanent: publicPersistence ? @YES : @NO };
484 if (privatePersistence >= 0) {
485 params[(id)kSecPrivateKeyAttrs] = @{ (id)kSecAttrIsPermanent: privatePersistence ? @YES : @NO };
490 id privateKey = CFBridgingRelease(SecKeyCreateRandomKey((__bridge CFDictionaryRef)params, (void *)&error));
491 isnt(privateKey, nil, "failed to generate token key, error %@", error);
492 is(phase, privateIsPersistent ? 0x3f : 0x1f);
493 id publicKey = CFBridgingRelease(SecKeyCopyPublicKey((SecKeyRef)privateKey));
494 isnt(publicKey, nil, "failed to get public key from private key");
496 NSDictionary *query = @{ (id)kSecValueRef: privateKey,
497 (id)kSecReturnAttributes: @YES,
498 (id)kSecReturnRef: @YES,
499 (id)kSecReturnData: @YES };
501 NSDictionary *result;
502 if (privateIsPersistent) {
503 ok_status(SecItemCopyMatching((__bridge CFDictionaryRef)query, (void *)&result), "persistent private key not found in kc");
505 is(result[(id)kSecValueData], nil);
506 eq_cf((__bridge CFTypeRef)result[(id)kSecAttrTokenID], @"tokenid");
507 NSDictionary *keyAttrs = CFBridgingRelease(SecKeyCopyAttributes((SecKeyRef)result[(id)kSecValueRef]));
508 eq_cf((__bridge CFTypeRef)keyAttrs[(id)kSecAttrApplicationLabel], (__bridge CFTypeRef)result[(id)kSecAttrApplicationLabel]);
509 keyAttrs = CFBridgingRelease(SecKeyCopyAttributes((SecKeyRef)publicKey));
510 eq_cf((__bridge CFTypeRef)keyAttrs[(id)kSecAttrApplicationLabel], (__bridge CFTypeRef)result[(id)kSecAttrApplicationLabel]);
512 is_status(SecItemCopyMatching((__bridge CFDictionaryRef)query, (void *)&result), errSecItemNotFound, "ephemeral private key found in kc");
515 // Balancing test count from the branch above
522 query = @{ (id)kSecValueRef: publicKey,
523 (id)kSecReturnAttributes: @YES,
524 (id)kSecReturnRef: @YES,
525 (id)kSecReturnData: @YES };
528 if (publicIsPersistent) {
529 ok_status(SecItemCopyMatching((__bridge CFDictionaryRef)query, (void *)&result), "persistent public key not found in kc");
530 NSDictionary *keyAttrs = CFBridgingRelease(SecKeyCopyAttributes((SecKeyRef)publicKey));
531 eq_cf((__bridge CFTypeRef)keyAttrs[(id)kSecAttrApplicationLabel], (__bridge CFTypeRef)result[(id)kSecAttrApplicationLabel]);
533 is_status(SecItemCopyMatching((__bridge CFDictionaryRef)query, (void *)&result), errSecItemNotFound, "ephemeral public key found in kc");
535 // Balancing test count from the branch above
539 // Get OID from the private key and try to create duplicate of the key using its OID and attributes.
540 NSDictionary *attrs = CFBridgingRelease(SecKeyCopyAttributes((SecKeyRef)privateKey));
541 NSData *oid = attrs[(id)kSecAttrTokenOID];
542 ok(oid != nil, "private key attributes need OID");
544 id copyKey = CFBridgingRelease(SecKeyCreateWithData((CFDataRef)[NSData data],
545 (CFDictionaryRef)@{ (id)kSecAttrTokenID: @"tokenid", (id)kSecAttrTokenOID: oid },
547 ok(copyKey != nil, "copied key is created");
549 attrs = CFBridgingRelease(SecKeyCopyAttributes((SecKeyRef)copyKey));
552 eq_cf((__bridge CFTypeRef)attrs[(id)kSecClass], kSecClassKey);
553 eq_cf((__bridge CFTypeRef)attrs[(id)kSecAttrKeyClass], kSecAttrKeyClassPrivate);
554 eq_cf((__bridge CFTypeRef)attrs[(id)kSecAttrKeyType], kSecAttrKeyTypeECSECPrimeRandom);
555 eq_cf((__bridge CFTypeRef)attrs[(id)kSecAttrKeySizeInBits], CFSTR("256"));
556 eq_cf((__bridge CFTypeRef)attrs[(id)kSecAttrTokenID], CFSTR("tokenid"));
557 id copyPublicKey = CFBridgingRelease(SecKeyCopyPublicKey((SecKeyRef)copyKey));
558 ok(copyPublicKey != nil);
560 NSDictionary *pubAttrs = CFBridgingRelease(SecKeyCopyAttributes((SecKeyRef)copyPublicKey));
561 eq_cf((__bridge CFTypeRef)attrs[(id)kSecAttrApplicationLabel], (__bridge CFTypeRef)pubAttrs[(id)kSecAttrApplicationLabel]);
564 static void test_key_sign(void) {
566 static const UInt8 data[] = { 0x01, 0x02, 0x03, 0x04 };
567 CFDataRef valueData = CFDataCreate(NULL, data, sizeof(data));
569 __block int phase = 0;
570 __block CFErrorRef cryptoError = NULL;
571 __block SecKeyOperationType cryptoOperation = -1;
572 __block SecKeyAlgorithm cryptoAlgorithm = NULL;
573 TKTokenTestSetHook(^(CFDictionaryRef attributes, TKTokenTestBlocks *blocks) {
576 blocks->copyPublicKeyData = ^CFDataRef(CFDataRef objectID, CFErrorRef *error) {
578 SecKeyRef privKey = SecKeyCreateECPrivateKey(NULL, CFDataGetBytePtr(objectID), CFDataGetLength(objectID), kSecKeyEncodingBytes);
579 CFDataRef publicData;
580 ok_status(SecKeyCopyPublicBytes(privKey, &publicData));
585 blocks->copyObjectAccessControl = ^CFDataRef(CFDataRef oid, CFErrorRef *error) {
587 SecAccessControlRef ac = SecAccessControlCreate(NULL, NULL);
588 SecAccessControlSetProtection(ac, kSecAttrAccessibleAlwaysPrivate, NULL);
589 test_IsTrue(SecAccessControlAddConstraintForOperation(ac, kAKSKeyOpDefaultAcl, kCFBooleanTrue, NULL));
590 CFDataRef acData = SecAccessControlCopyData(ac);
595 blocks->copyOperationResult = ^CFTypeRef(CFDataRef objectID, CFIndex operation, CFArrayRef algorithms, CFIndex secKeyOperationMode, CFTypeRef in1, CFTypeRef in2, CFErrorRef *error) {
596 SecKeyAlgorithm algorithm = CFArrayGetValueAtIndex(algorithms, CFArrayGetCount(algorithms) - 1);
598 cryptoOperation = operation;
599 cryptoAlgorithm = algorithm;
600 if (cryptoError != NULL) {
601 CFAssignRetained(*error, cryptoError);
605 return CFRetainSafe(valueData);
608 blocks->copyObjectData = ^CFTypeRef(CFDataRef objectID, CFErrorRef *error) {
614 NSDictionary *query = @{ (id)kSecClass: (id)kSecClassKey, (id)kSecReturnRef: @YES };
617 SecKeyRef privateKey = NULL;
618 ok_status(SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef *)&privateKey));
622 CFMutableDataRef sig = CFDataCreateMutable(NULL, 0);
623 CFDataSetLength(sig, 256);
624 size_t sigLen = CFDataGetLength(sig);
625 ok_status(SecKeyRawSign(privateKey, kSecPaddingPKCS1, data, sizeof(data), CFDataGetMutableBytePtr(sig), &sigLen));
627 is(cryptoAlgorithm, kSecKeyAlgorithmECDSASignatureDigestX962);
628 is(cryptoOperation, kSecKeyOperationTypeSign);
629 CFDataSetLength(sig, sigLen);
630 is(CFDataGetLength(sig), CFDataGetLength(valueData));
631 eq_cf(valueData, sig);
633 #if LA_CONTEXT_IMPLEMENTED
635 CFDataSetLength(sig, 256);
636 sigLen = CFDataGetLength(sig);
637 LASetErrorCodeBlock(^{ return (CFErrorRef)NULL; });
638 cryptoError = CFErrorCreate(NULL, CFSTR(kTKErrorDomain), kTKErrorCodeAuthenticationNeeded, NULL);
639 ok_status(SecKeyRawSign(privateKey, kSecPaddingPKCS1, data, sizeof(data), CFDataGetMutableBytePtr(sig), &sigLen));
641 is(cryptoError, NULL);
642 CFDataSetLength(sig, sigLen);
643 is(CFDataGetLength(sig), CFDataGetLength(valueData));
644 eq_cf(valueData, sig);
649 result = CFBridgingRelease(SecKeyCreateDecryptedData(privateKey, kSecKeyAlgorithmRSAEncryptionRaw,
650 valueData, (void *)&error));
651 eq_cf((__bridge CFDataRef)result, valueData);
652 is(cryptoAlgorithm, kSecKeyAlgorithmRSAEncryptionRaw);
653 is(cryptoOperation, kSecKeyOperationTypeDecrypt);
655 NSDictionary *params = @{ (id)kSecAttrKeyType: (id)kSecAttrKeyTypeECSECPrimeRandom, (id)kSecAttrKeySizeInBits: @256 };
656 SecKeyRef otherPrivKey = NULL, otherPubKey = NULL;
657 ok_status(SecKeyGeneratePair((__bridge CFDictionaryRef)params, &otherPubKey, &otherPrivKey));
660 result = CFBridgingRelease(SecKeyCopyKeyExchangeResult(privateKey, kSecKeyAlgorithmECDHKeyExchangeCofactor,
661 otherPubKey, (CFDictionaryRef)@{}, (void *)&error));
662 eq_cf((__bridge CFDataRef)result, valueData);
663 is(cryptoAlgorithm, kSecKeyAlgorithmECDHKeyExchangeCofactor);
664 is(cryptoOperation, kSecKeyOperationTypeKeyExchange);
666 CFReleaseSafe(otherPrivKey);
667 CFReleaseSafe(otherPubKey);
668 CFReleaseSafe(cryptoError);
670 CFRelease(privateKey);
673 static void test_key_generate_with_params(void) {
675 const UInt8 data[] = "foo";
676 CFDataRef cred_ref = CFDataCreate(NULL, data, 4);
677 __block int phase = 0;
678 TKTokenTestSetHook(^(CFDictionaryRef attributes, TKTokenTestBlocks *blocks) {
680 eq_cf(CFDictionaryGetValue(attributes, kSecUseOperationPrompt), CFSTR("prompt"));
681 is(CFDictionaryGetValue(attributes, kSecUseAuthenticationUI), NULL);
682 eq_cf(CFDictionaryGetValue(attributes, kSecUseCredentialReference), cred_ref);
684 blocks->createOrUpdateObject = ^CFDataRef(CFDataRef objectID, CFMutableDictionaryRef at, CFErrorRef *error) {
686 SecCFCreateError(-4 /* kTKErrorCodeCanceledByUser */, CFSTR(kTKErrorDomain), CFSTR(""), NULL, error);
691 CFDictionaryRef prk_params = CFDictionaryCreateForCFTypes(NULL,
692 kSecAttrIsPermanent, kCFBooleanTrue,
695 CFMutableDictionaryRef params = CFDictionaryCreateMutableForCFTypesWith(NULL,
696 kSecAttrKeyType, kSecAttrKeyTypeEC,
697 kSecAttrKeySizeInBits, CFSTR("256"),
698 kSecAttrTokenID, CFSTR("tokenid"),
699 kSecPrivateKeyAttrs, prk_params,
700 kSecUseOperationPrompt, CFSTR("prompt"),
701 kSecUseAuthenticationUI, kSecUseAuthenticationUIAllow,
702 kSecUseCredentialReference, cred_ref,
704 CFRelease(prk_params);
706 SecKeyRef publicKey = NULL, privateKey = NULL;
708 is_status(SecKeyGeneratePair(params, &publicKey, &privateKey), errSecUserCanceled);
711 CFReleaseSafe(publicKey);
712 CFReleaseSafe(privateKey);
717 static void test_error_codes(void) {
719 CFMutableDictionaryRef attrs = CFDictionaryCreateMutableForCFTypesWith(NULL,
720 kSecClass, kSecClassGenericPassword,
721 kSecAttrTokenID, CFSTR("tokenid"),
724 __block OSStatus ctk_error = 0;
725 TKTokenTestSetHook(^(CFDictionaryRef attributes, TKTokenTestBlocks *blocks) {
726 blocks->createOrUpdateObject = ^CFDataRef(CFDataRef objectID, CFMutableDictionaryRef at, CFErrorRef *error) {
727 SecCFCreateError(ctk_error, CFSTR(kTKErrorDomain), CFSTR(""), NULL, error);
732 ctk_error = kTKErrorCodeBadParameter;
733 is_status(SecItemAdd(attrs, NULL), errSecParam);
735 ctk_error = kTKErrorCodeNotImplemented;
736 is_status(SecItemAdd(attrs, NULL), errSecUnimplemented);
738 ctk_error = kTKErrorCodeCanceledByUser;
739 is_status(SecItemAdd(attrs, NULL), errSecUserCanceled);
744 static CFDataRef copy_certificate_data(const char *base64Cert)
746 size_t size = SecBase64Decode(base64Cert, strnlen(base64Cert, 2048), NULL, 0);
748 CFMutableDataRef data = CFDataCreateMutable(kCFAllocatorDefault, size);
749 CFDataSetLength(data, size);
750 size = SecBase64Decode(base64Cert, strnlen(base64Cert, 2048), (char*)CFDataGetMutableBytePtr(data), CFDataGetLength(data));
752 CFDataSetLength(data, size);
757 static CFMutableDictionaryRef copy_certificate_attributes(const char *base64Cert)
759 CFDataRef data = copy_certificate_data(base64Cert);
761 SecCertificateRef cert = SecCertificateCreateWithData(kCFAllocatorDefault, data);
763 CFDictionaryRef certAttributes = SecCertificateCopyAttributeDictionary(cert);
765 CFMutableDictionaryRef result = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, certAttributes);
769 CFRelease(certAttributes);
778 static CFDictionaryRef copy_certificate_query(const char *base64cert, CFStringRef label, CFStringRef oid, CFStringRef tokenID)
780 CFMutableDictionaryRef certAttributes = copy_certificate_attributes(base64cert);
782 CFDictionarySetValue(certAttributes, kSecAttrLabel, label);
783 CFDictionarySetValue(certAttributes, kSecAttrAccessible, kSecAttrAccessibleAlwaysPrivate);
784 CFDictionarySetValue(certAttributes, kSecAttrTokenOID, oid);
785 CFDictionaryRemoveValue(certAttributes, kSecValueData);
787 SecAccessControlRef acl = SecAccessControlCreate(kCFAllocatorDefault, NULL);
789 CFTypeRef key[] = { kSecAttrTokenID };
790 CFTypeRef value[] = { tokenID };
791 CFDictionaryRef protection = CFDictionaryCreate(kCFAllocatorDefault, key, value, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
792 ok(SecAccessControlSetProtection(acl, protection, NULL));
793 CFRelease(protection);
794 ok(SecAccessControlAddConstraintForOperation(acl, kAKSKeyOpDefaultAcl, kCFBooleanTrue, NULL));
795 CFDataRef aclData = SecAccessControlCopyData(acl);
798 CFDictionarySetValue(certAttributes, kSecAttrAccessControl, aclData);
805 return certAttributes;
808 static CFDictionaryRef copy_key_query(CFDictionaryRef certAttributes, CFStringRef label, CFStringRef oid, CFStringRef tokenID)
810 CFMutableDictionaryRef keyAttributes = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks) ;
812 CFDictionarySetValue(keyAttributes, kSecClass, kSecClassKey);
813 CFDictionarySetValue(keyAttributes, kSecAttrKeyClass, kSecAttrKeyClassPrivate);
814 CFDictionarySetValue(keyAttributes, kSecAttrKeyType, kSecAttrKeyTypeRSA);
815 CFNumberRef keySize = CFNumberCreateWithCFIndex(kCFAllocatorDefault, 2048);
816 CFDictionarySetValue(keyAttributes, kSecAttrKeySizeInBits, keySize);
819 CFDictionarySetValue(keyAttributes, kSecAttrCanDecrypt, kCFBooleanTrue);
820 CFDictionarySetValue(keyAttributes, kSecAttrCanSign, kCFBooleanTrue);
821 CFDictionarySetValue(keyAttributes, kSecAttrCanUnwrap, kCFBooleanTrue);
822 CFDictionarySetValue(keyAttributes, kSecAttrCanDerive, kCFBooleanFalse);
823 CFDictionarySetValue(keyAttributes, kSecAttrIsPrivate, kCFBooleanTrue);
825 CFDictionarySetValue(keyAttributes, kSecAttrLabel, label);
826 CFDictionarySetValue(keyAttributes, kSecAttrAccessible, kSecAttrAccessibleAlwaysPrivate);
827 CFDictionarySetValue(keyAttributes, kSecAttrTokenOID, oid);
828 CFDictionarySetValue(keyAttributes, kSecAttrApplicationLabel, CFDictionaryGetValue(certAttributes, kSecAttrPublicKeyHash));
830 SecAccessControlRef acl = SecAccessControlCreate(kCFAllocatorDefault, NULL);
832 CFTypeRef key[] = { kSecAttrTokenID };
833 CFTypeRef value[] = { tokenID };
834 CFDictionaryRef protection = CFDictionaryCreate(kCFAllocatorDefault, key, value, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
835 ok(SecAccessControlSetProtection(acl, protection, NULL));
836 CFRelease(protection);
837 ok(SecAccessControlAddConstraintForOperation(acl, kAKSKeyOpDefaultAcl, kCFBooleanTrue, NULL));
838 CFDataRef aclData = SecAccessControlCopyData(acl);
841 CFDictionarySetValue(keyAttributes, kSecAttrAccessControl, aclData);
848 return keyAttributes;
851 static void check_array_for_type_id(CFArrayRef array, CFTypeID typeID)
853 if (array && CFGetTypeID(array) == CFArrayGetTypeID()) {
854 for (CFIndex i = 0; i < CFArrayGetCount(array); ++i) {
855 ok(CFGetTypeID(CFArrayGetValueAtIndex(array, i)) == typeID);
860 static void test_propagate_token_items()
862 CFStringRef cert1OID = CFSTR("oid1");
863 CFStringRef cert2OID = CFSTR("oid2");
864 CFStringRef key1OID = CFSTR("oid3");
865 CFStringRef key2OID = CFSTR("oid4");
867 TKTokenTestSetHook(^(CFDictionaryRef attributes, TKTokenTestBlocks *blocks) {
868 blocks->copyObjectData = ^CFTypeRef(CFDataRef oid, CFErrorRef *error) {
869 if (CFEqual(oid, cert1OID)) {
870 return copy_certificate_data(cert1);
872 else if (CFEqual(oid, cert2OID)) {
873 return copy_certificate_data(cert2);
875 else if (CFEqual(oid, key1OID) || CFEqual(oid, key2OID)) {
884 CFStringRef tokenID = CFSTR("com.apple.secdtest:propagate_test_token");
886 CFMutableArrayRef items = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
888 CFDictionaryRef certQuery = copy_certificate_query(cert1, CFSTR("test_cert1"), cert1OID, tokenID);
890 CFDictionaryRef keyQuery = copy_key_query(certQuery, CFSTR("test_key1"), key1OID, tokenID);
893 CFArrayAppendValue(items, certQuery);
894 CFArrayAppendValue(items, keyQuery);
895 CFReleaseSafe(certQuery);
896 CFReleaseSafe(keyQuery);
898 certQuery = copy_certificate_query(cert2, CFSTR("test_cert2"), cert2OID, tokenID);
900 keyQuery = copy_key_query(certQuery, CFSTR("test_key2"), key2OID, tokenID);
903 CFArrayAppendValue(items, certQuery);
904 CFArrayAppendValue(items, keyQuery);
905 CFReleaseSafe(certQuery);
906 CFReleaseSafe(keyQuery);
909 ok_status(result = SecItemUpdateTokenItems(tokenID, NULL), "Failed to delete items.");
911 ok_status(result = SecItemUpdateTokenItems(tokenID, items), "Failed to propagate items.");
914 CFMutableDictionaryRef query = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
915 CFDictionarySetValue(query, kSecClass, kSecClassCertificate);
916 CFDictionarySetValue(query, kSecAttrAccessGroup, CFSTR("com.apple.token"));
917 CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue);
918 CFDictionarySetValue(query, kSecMatchLimit, kSecMatchLimitAll);
919 CFTypeRef queryResult;
920 ok_status(SecItemCopyMatching(query, &queryResult));
921 ok(queryResult && CFGetTypeID(queryResult) == CFArrayGetTypeID() && CFArrayGetCount(queryResult) == 2, "Expect array with two certs");
922 check_array_for_type_id(queryResult, SecCertificateGetTypeID());
923 CFReleaseNull(queryResult);
925 CFDictionarySetValue(query, kSecReturnRef, kCFBooleanFalse);
926 CFDictionarySetValue(query, kSecReturnData, kCFBooleanTrue);
927 ok_status(SecItemCopyMatching(query, &queryResult));
928 ok(queryResult && CFGetTypeID(queryResult) == CFArrayGetTypeID() && CFArrayGetCount(queryResult) == 2, "Expect array with two certs");
929 check_array_for_type_id(queryResult, CFDataGetTypeID());
930 CFReleaseNull(queryResult);
932 CFDictionarySetValue(query, kSecClass, kSecClassKey);
933 CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue);
934 CFDictionarySetValue(query, kSecReturnData, kCFBooleanFalse);
935 ok_status(SecItemCopyMatching(query, &queryResult));
936 ok(queryResult && CFGetTypeID(queryResult) == CFArrayGetTypeID() && CFArrayGetCount(queryResult) == 2, "Expect array with two keys");
937 check_array_for_type_id(queryResult, SecKeyGetTypeID());
938 CFReleaseNull(queryResult);
940 CFDictionarySetValue(query, kSecReturnRef, kCFBooleanFalse);
941 CFDictionarySetValue(query, kSecReturnData, kCFBooleanTrue);
942 ok_status(SecItemCopyMatching(query, &queryResult));
943 ok(queryResult && CFGetTypeID(queryResult) == CFArrayGetTypeID() && CFArrayGetCount(queryResult) == 0, "Expect empty array");
944 CFReleaseNull(queryResult);
946 CFDictionarySetValue(query, kSecClass, kSecClassIdentity);
947 CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue);
948 CFDictionarySetValue(query, kSecReturnData, kCFBooleanFalse);
949 ok_status(SecItemCopyMatching(query, &queryResult));
950 ok(queryResult && CFGetTypeID(queryResult) == CFArrayGetTypeID() && CFArrayGetCount(queryResult) == 2, "Expect array with two identities");
951 check_array_for_type_id(queryResult, SecIdentityGetTypeID());
952 CFReleaseNull(queryResult);
954 CFDictionarySetValue(query, kSecReturnRef, kCFBooleanFalse);
955 CFDictionarySetValue(query, kSecReturnData, kCFBooleanTrue);
956 ok_status(SecItemCopyMatching(query, &queryResult));
957 ok(queryResult && CFGetTypeID(queryResult) == CFArrayGetTypeID() && CFArrayGetCount(queryResult) == 0, "Expect empty array");
958 CFReleaseNull(queryResult);
960 ok_status(result = SecItemUpdateTokenItems(tokenID, NULL), "Failed to delete items.");
962 CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue);
963 CFDictionarySetValue(query, kSecReturnData, kCFBooleanFalse);
964 is_status(SecItemCopyMatching(query, &queryResult), errSecItemNotFound);
965 CFReleaseNull(queryResult);
969 static void test_identity_on_two_tokens() {
970 CFStringRef cert3OID = CFSTR("oid1");
971 TKTokenTestSetHook(^(CFDictionaryRef attributes, TKTokenTestBlocks *blocks) {
973 blocks->copyObjectData = ^CFTypeRef(CFDataRef oid, CFErrorRef *error) {
974 if (CFEqual(oid, cert3OID))
975 return copy_certificate_data(cert3);
983 NSString *tokenID1 = @"com.apple.secdtest:identity_test_token1";
984 NSString *tokenID2 = @"com.apple.secdtest:identity_test_token2";
987 NSData *privKeyData = [[NSData alloc] initWithBase64EncodedString:@"BAcrF9iBupEeZOE+c73JBfkqsv8Q9rp1lTnZbKzmALf8yTR02310uGlZuUBVp4HOSiziO43dzFuegH0ywLhu+gtJj81RD8Rt+nLR6oTARkL+0l2/fzrIouleaEYpYmEp0A==" options:NSDataBase64DecodingIgnoreUnknownCharacters];
988 id privKey = CFBridgingRelease(SecKeyCreateWithData((CFDataRef)privKeyData, (CFDictionaryRef)@{(id)kSecAttrKeyType: (id)kSecAttrKeyTypeECSECPrimeRandom, (id)kSecAttrKeyClass: (id)kSecAttrKeyClassPrivate}, (void *)&error));
989 id publicKey = CFBridgingRelease(SecKeyCopyPublicKey((__bridge SecKeyRef)privKey));
990 NSData *pubKeyHash = CFBridgingRelease(SecKeyCopyPublicKeyHash((__bridge SecKeyRef)publicKey));
992 id ac = CFBridgingRelease(SecAccessControlCreateWithFlags(kCFAllocatorDefault, kSecAttrAccessibleWhenUnlocked, 0, NULL));
993 id acData = CFBridgingRelease(SecAccessControlCopyData((__bridge SecAccessControlRef)ac));
994 NSDictionary *keyQuery = @{ (id)kSecClass: (id)kSecClassKey,
995 (id)kSecAttrTokenID: tokenID1,
996 (id)kSecAttrKeyType : (id)kSecAttrKeyTypeECSECPrimeRandom,
997 (id)kSecAttrKeySizeInBits : @"256",
998 (id)kSecAttrKeyClass: (id)kSecAttrKeyClassPrivate,
999 (id)kSecAttrIsPrivate: @YES,
1000 (id)kSecAttrAccessControl: acData,
1001 (id)kSecAttrTokenOID : privKeyData,
1002 (id)kSecAttrApplicationLabel : pubKeyHash,
1005 ok_status(result = SecItemUpdateTokenItems((__bridge CFStringRef)tokenID1, (__bridge CFArrayRef)@[keyQuery]), "Failed to propagate key item.");
1008 ok_status(result = SecItemCopyMatching((__bridge CFDictionaryRef)@{(id)kSecClass: (id)kSecClassKey, (id)kSecAttrTokenID: tokenID1, (id)kSecAttrAccessGroup: (id)kSecAttrAccessGroupToken, (id)kSecReturnRef: @YES}, (void *)&privateKey));
1010 NSDictionary *certQuery = CFBridgingRelease(copy_certificate_query(cert3, CFSTR("test_cert3"), cert3OID, (__bridge CFStringRef)tokenID2));
1013 ok_status(result = SecItemUpdateTokenItems((__bridge CFStringRef)tokenID2, (__bridge CFArrayRef)@[certQuery]), "Failed to propagate cert item.");
1015 CFTypeRef resultRef;
1016 NSDictionary *query = @{ (id)kSecClass : (id)kSecClassKey, (id)kSecAttrApplicationLabel : pubKeyHash, (id)kSecReturnRef : @YES, (id)kSecReturnAttributes : @YES, (id)kSecAttrAccessGroup: (id)kSecAttrAccessGroupToken };
1017 ok_status(result = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef*)&resultRef));
1018 CFReleaseNull(resultRef);
1020 query = @{ (id)kSecClass : (id)kSecClassCertificate, (id)kSecAttrPublicKeyHash : pubKeyHash, (id)kSecReturnRef : @YES, (id)kSecReturnAttributes : @YES, (id)kSecAttrAccessGroup: (id)kSecAttrAccessGroupToken };
1021 ok_status(result = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef*)&resultRef));
1022 CFReleaseNull(resultRef);
1024 query = @{ (id)kSecClass : (id)kSecClassIdentity, (id)kSecAttrApplicationLabel : pubKeyHash, (id)kSecReturnRef : @YES, (id)kSecReturnAttributes : @YES, (id)kSecAttrAccessGroup: (id)kSecAttrAccessGroupToken };
1025 ok_status(result = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef*)&resultRef));
1026 CFReleaseNull(resultRef);
1030 static void test_ies(SecKeyRef privateKey, SecKeyAlgorithm algorithm) {
1031 TKTokenTestSetHook(^(CFDictionaryRef attributes, TKTokenTestBlocks *blocks) {
1033 blocks->createOrUpdateObject = ^CFDataRef(CFDataRef objectID, CFMutableDictionaryRef at, CFErrorRef *error) {
1034 return CFBridgingRetain([@"oid" dataUsingEncoding:NSUTF8StringEncoding]);
1037 blocks->copyPublicKeyData = ^CFDataRef(CFDataRef objectID, CFErrorRef *error) {
1038 SecKeyRef publicKey = SecKeyCopyPublicKey(privateKey);
1039 CFDataRef data = SecKeyCopyExternalRepresentation(publicKey, error);
1040 CFReleaseNull(publicKey);
1044 blocks->copyObjectData = ^CFTypeRef(CFDataRef oid, CFErrorRef *error) {
1048 blocks->copyObjectAccessControl = ^CFDataRef(CFDataRef oid, CFErrorRef *error) {
1049 SecAccessControlRef ac = SecAccessControlCreate(NULL, NULL);
1050 SecAccessControlSetProtection(ac, kSecAttrAccessibleAlwaysPrivate, NULL);
1051 test_IsTrue(SecAccessControlAddConstraintForOperation(ac, kAKSKeyOpDefaultAcl, kCFBooleanTrue, NULL));
1052 CFDataRef acData = SecAccessControlCopyData(ac);
1057 blocks->copyOperationResult = ^CFTypeRef(CFDataRef objectID, CFIndex operation, CFArrayRef algorithms, CFIndex secKeyOperationMode, CFTypeRef in1, CFTypeRef in2, CFErrorRef *error) {
1058 CFTypeRef result = kCFNull;
1059 CFTypeRef algorithm = CFArrayGetValueAtIndex(algorithms, CFArrayGetCount(algorithms) - 1);
1060 switch (operation) {
1061 case kSecKeyOperationTypeKeyExchange: {
1062 if (CFEqual(algorithm, kSecKeyAlgorithmECDHKeyExchangeStandard) ||
1063 CFEqual(algorithm, kSecKeyAlgorithmECDHKeyExchangeCofactor)) {
1064 NSDictionary *attrs = CFBridgingRelease(SecKeyCopyAttributes(privateKey));
1065 NSDictionary *params = @{
1066 (id)kSecAttrKeyType: attrs[(id)kSecAttrKeyType],
1067 (id)kSecAttrKeySizeInBits: attrs[(id)kSecAttrKeySizeInBits],
1068 (id)kSecAttrKeyClass: (id)kSecAttrKeyClassPublic,
1070 SecKeyRef pubKey = SecKeyCreateWithData(in1, (CFDictionaryRef)params, error);
1071 if (pubKey == NULL) {
1074 result = SecKeyCopyKeyExchangeResult(privateKey, algorithm, pubKey, in2, error);
1075 CFReleaseSafe(pubKey);
1079 case kSecKeyOperationTypeDecrypt: {
1080 if (CFEqual(algorithm, kSecKeyAlgorithmRSAEncryptionRaw)) {
1081 result = SecKeyCreateDecryptedData(privateKey, algorithm, in1, error);
1092 NSDictionary *privateParams = CFBridgingRelease(SecKeyCopyAttributes(privateKey));
1093 NSDictionary *params = @{ (id)kSecAttrKeyType : privateParams[(id)kSecAttrKeyType],
1094 (id)kSecAttrKeySizeInBits : privateParams[(id)kSecAttrKeySizeInBits],
1095 (id)kSecAttrTokenID : @"tid-ies",
1096 (id)kSecPrivateKeyAttrs : @{ (id)kSecAttrIsPermanent : @YES }
1099 SecKeyRef tokenKey = SecKeyCreateRandomKey((__bridge CFDictionaryRef)params, (void *)&error);
1100 ok(tokenKey != NULL, "create token-based key (err %@)", error);
1101 SecKeyRef tokenPublicKey = SecKeyCopyPublicKey(tokenKey);
1103 NSData *plaintext = [@"plaintext" dataUsingEncoding:NSUTF8StringEncoding];
1106 NSData *ciphertext = CFBridgingRelease(SecKeyCreateEncryptedData(tokenPublicKey, algorithm, (CFDataRef)plaintext, (void *)&error));
1107 ok(ciphertext, "failed to encrypt IES, err %@", error);
1109 NSData *decrypted = CFBridgingRelease(SecKeyCreateDecryptedData(tokenKey, algorithm, (CFDataRef)ciphertext, (void *)&error));
1110 ok(decrypted, "failed to decrypt IES, err %@", error);
1112 eq_cf((__bridge CFDataRef)plaintext, (__bridge CFDataRef)decrypted, "decrypted(%@) != plaintext(%@)", decrypted, plaintext);
1114 CFReleaseNull(tokenKey);
1115 CFReleaseNull(tokenPublicKey);
1118 static void test_ecies() {
1120 SecKeyRef privateKey = SecKeyCreateRandomKey((__bridge CFDictionaryRef)@{(id)kSecAttrKeyType: (id)kSecAttrKeyTypeECSECPrimeRandom, (id)kSecAttrKeySizeInBits: @256}, (void *)&error);
1121 ok(privateKey != NULL, "failed to generate CPU EC key: %@", error);
1123 test_ies(privateKey, kSecKeyAlgorithmECIESEncryptionCofactorX963SHA256AESGCM);
1125 CFReleaseNull(privateKey);
1128 static void test_rsawrap() {
1130 SecKeyRef privateKey = SecKeyCreateRandomKey((__bridge CFDictionaryRef)@{(id)kSecAttrKeyType: (id)kSecAttrKeyTypeRSA, (id)kSecAttrKeySizeInBits: @2048}, (void *)&error);
1131 ok(privateKey != NULL, "failed to generate CPU RSA key: %@", error);
1133 test_ies(privateKey, kSecKeyAlgorithmRSAEncryptionOAEPSHA256AESGCM);
1135 CFReleaseNull(privateKey);
1138 static void tests(void) {
1139 /* custom keychain dir */
1140 secd_test_setup_temp_keychain("secd_33_keychain_ctk", NULL);
1147 // params: int globalPersistence, int privatePersistence, int publicPersistence, bool privateIsPersistent, bool publicIsPersistent
1148 test_key_generate(-1, -1, -1, true, false);
1149 test_key_generate(0, -1, -1, false, false);
1150 test_key_generate(1, -1, -1, true, true);
1151 test_key_generate(-1, 0, 0, false, false);
1152 test_key_generate(-1, 1, 0, true, false);
1153 test_key_generate(-1, 0, 1, false, true);
1154 test_key_generate(-1, 1, 1, true, true);
1155 test_key_generate(0, 1, 1, true, true);
1156 test_key_generate(1, 1, 1, true, true);
1159 test_key_generate_with_params();
1161 test_propagate_token_items();
1162 test_identity_on_two_tokens();
1167 int secd_33_keychain_ctk(int argc, char *const *argv) {