]> git.saurik.com Git - apple/security.git/blob - OSX/sec/securityd/SecKeybagSupport.c
Security-57337.50.23.tar.gz
[apple/security.git] / OSX / sec / securityd / SecKeybagSupport.c
1 /*
2 * Copyright (c) 2006-2014 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 /*
25 * SecKeybagSupport.c - CoreFoundation-based constants and functions for
26 access to Security items (certificates, keys, identities, and
27 passwords.)
28 */
29
30 #include <securityd/SecKeybagSupport.h>
31
32 #include <securityd/SecItemServer.h>
33
34 #if USE_KEYSTORE
35 #include <IOKit/IOKitLib.h>
36 #include <libaks.h>
37 #include <libaks_acl_cf_keys.h>
38 #include <utilities/der_plist.h>
39 #include <corecrypto/ccder.h>
40 #include <ACMLib.h>
41 #if TARGET_OS_EMBEDDED
42 #include <MobileKeyBag/MobileKeyBag.h>
43 #endif
44 #endif /* USE_KEYSTORE */
45
46 #include <CommonCrypto/CommonCryptor.h>
47 #include <CommonCrypto/CommonCryptorSPI.h>
48
49
50 /* g_keychain_handle is the keybag handle used for encrypting item in the keychain.
51 For testing purposes, it can be set to something other than the default, with SecItemServerSetKeychainKeybag */
52 #if USE_KEYSTORE
53 #if TARGET_OS_MAC && !TARGET_OS_EMBEDDED
54 keybag_handle_t g_keychain_keybag = session_keybag_handle;
55 #else
56 keybag_handle_t g_keychain_keybag = device_keybag_handle;
57 #endif
58 #else /* !USE_KEYSTORE */
59 keybag_handle_t g_keychain_keybag = 0; /* 0 == device_keybag_handle, constant dictated by AKS */
60 #endif /* USE_KEYSTORE */
61
62 const CFStringRef kSecKSKeyData1 = CFSTR("d1");
63 const CFStringRef kSecKSKeyData2 = CFSTR("d2");
64
65 void SecItemServerSetKeychainKeybag(int32_t keybag)
66 {
67 g_keychain_keybag=keybag;
68 }
69
70 void SecItemServerResetKeychainKeybag(void)
71 {
72 #if USE_KEYSTORE
73 #if TARGET_OS_MAC && !TARGET_OS_EMBEDDED
74 g_keychain_keybag = session_keybag_handle;
75 #else
76 g_keychain_keybag = device_keybag_handle;
77 #endif
78 #else /* !USE_KEYSTORE */
79 g_keychain_keybag = 0; /* 0 == device_keybag_handle, constant dictated by AKS */
80 #endif /* USE_KEYSTORE */
81 }
82
83 #if USE_KEYSTORE
84
85 static bool hwaes_key_available(void)
86 {
87 keybag_handle_t handle = bad_keybag_handle;
88 keybag_handle_t special_handle = bad_keybag_handle;
89 #if TARGET_OS_MAC && !TARGET_OS_EMBEDDED
90 special_handle = session_keybag_handle;
91 #elif TARGET_OS_EMBEDDED
92 special_handle = device_keybag_handle;
93 #endif
94 kern_return_t kr = aks_get_system(special_handle, &handle);
95 if (kr != kIOReturnSuccess) {
96 #if TARGET_OS_EMBEDDED
97 /* TODO: Remove this once the kext runs the daemon on demand if
98 there is no system keybag. */
99 int kb_state = MKBGetDeviceLockState(NULL);
100 asl_log(NULL, NULL, ASL_LEVEL_INFO, "AppleKeyStore lock state: %d", kb_state);
101 #endif
102 }
103 return true;
104 }
105
106 #else /* !USE_KEYSTORE */
107
108 static bool hwaes_key_available(void)
109 {
110 return false;
111 }
112
113 #endif /* USE_KEYSTORE */
114
115 /* Wrap takes a 128 - 256 bit key as input and returns output of
116 inputsize + 64 bits.
117 In bytes this means that a
118 16 byte (128 bit) key returns a 24 byte wrapped key
119 24 byte (192 bit) key returns a 32 byte wrapped key
120 32 byte (256 bit) key returns a 40 byte wrapped key */
121 bool ks_crypt(CFTypeRef operation, keybag_handle_t keybag,
122 keyclass_t keyclass, uint32_t textLength, const uint8_t *source, keyclass_t *actual_class, CFMutableDataRef dest, CFErrorRef *error) {
123 #if USE_KEYSTORE
124 kern_return_t kernResult = kIOReturnBadArgument;
125
126 int dest_len = (int)CFDataGetLength(dest);
127 if (CFEqual(operation, kAKSKeyOpEncrypt)) {
128 kernResult = aks_wrap_key(source, textLength, keyclass, keybag, CFDataGetMutableBytePtr(dest), &dest_len, actual_class);
129 } else if (CFEqual(operation, kAKSKeyOpDecrypt) || CFEqual(operation, kAKSKeyOpDelete)) {
130 kernResult = aks_unwrap_key(source, textLength, keyclass, keybag, CFDataGetMutableBytePtr(dest), &dest_len);
131 }
132
133 if (kernResult != KERN_SUCCESS) {
134 if ((kernResult == kIOReturnNotPermitted) || (kernResult == kIOReturnNotPrivileged)) {
135 /* Access to item attempted while keychain is locked. */
136 return SecError(errSecInteractionNotAllowed, error, CFSTR("ks_crypt: %x failed to '%@' item (class %"PRId32", bag: %"PRId32") Access to item attempted while keychain is locked."),
137 kernResult, operation, keyclass, keybag);
138 } else if (kernResult == kIOReturnError) {
139 /* Item can't be decrypted on this device, ever, so drop the item. */
140 return SecError(errSecDecode, error, CFSTR("ks_crypt: %x failed to '%@' item (class %"PRId32", bag: %"PRId32") Item can't be decrypted on this device, ever, so drop the item."),
141 kernResult, operation, keyclass, keybag);
142 } else {
143 return SecError(errSecNotAvailable, error, CFSTR("ks_crypt: %x failed to '%@' item (class %"PRId32", bag: %"PRId32")"),
144 kernResult, operation, keyclass, keybag);
145 }
146 }
147 else
148 CFDataSetLength(dest, dest_len);
149 return true;
150 #else /* !USE_KEYSTORE */
151 uint32_t dest_len = (uint32_t)CFDataGetLength(dest);
152 if (CFEqual(operation, kAKSKeyOpEncrypt)) {
153 /* The no encryption case. */
154 if (dest_len >= textLength + 8) {
155 memcpy(CFDataGetMutableBytePtr(dest), source, textLength);
156 memset(CFDataGetMutableBytePtr(dest) + textLength, 8, 8);
157 CFDataSetLength(dest, textLength + 8);
158 *actual_class = keyclass;
159 } else
160 return SecError(errSecNotAvailable, error, CFSTR("ks_crypt: failed to wrap item (class %"PRId32")"), keyclass);
161 } else if (CFEqual(operation, kAKSKeyOpDecrypt) || CFEqual(operation, kAKSKeyOpDelete)) {
162 if (dest_len + 8 >= textLength) {
163 memcpy(CFDataGetMutableBytePtr(dest), source, textLength - 8);
164 CFDataSetLength(dest, textLength - 8);
165 } else
166 return SecError(errSecNotAvailable, error, CFSTR("ks_crypt: failed to unwrap item (class %"PRId32")"), keyclass);
167 }
168 return true;
169 #endif /* USE_KEYSTORE */
170 }
171
172 #if USE_KEYSTORE
173 static bool ks_access_control_needed_error(CFErrorRef *error, CFDataRef access_control_data, CFTypeRef operation) {
174 if (error == NULL)
175 return false;
176
177 if (*error && CFErrorGetCode(*error) != errSecAuthNeeded) {
178 // If we already had an error there, just leave it, no access_control specific error is needed here.
179 return false;
180 }
181
182 // Create new error instance which adds new access control data appended to existing
183 CFMutableDictionaryRef user_info;
184 if (*error) {
185 CFDictionaryRef old_user_info = CFErrorCopyUserInfo(*error);
186 user_info = CFDictionaryCreateMutableCopy(NULL, 0, old_user_info);
187 CFRelease(old_user_info);
188 CFReleaseNull(*error);
189 } else {
190 user_info = CFDictionaryCreateMutableForCFTypes(NULL);
191 }
192
193 if (access_control_data) {
194 CFNumberRef key = CFNumberCreateWithCFIndex(NULL, errSecAuthNeeded);
195 CFMutableArrayRef acls;
196 CFArrayRef old_acls = CFDictionaryGetValue(user_info, key);
197 if (old_acls)
198 acls = CFArrayCreateMutableCopy(NULL, 0, old_acls);
199 else
200 acls = CFArrayCreateMutableForCFTypes(NULL);
201
202 CFArrayRef pair = CFArrayCreateForCFTypes(NULL, access_control_data, operation, NULL);
203 CFArrayAppendValue(acls, pair);
204 CFRelease(pair);
205
206 CFDictionarySetValue(user_info, key, acls);
207 CFRelease(key);
208 CFRelease(acls);
209
210 *error = CFErrorCreate(NULL, kSecErrorDomain, errSecAuthNeeded, user_info);
211 }
212 else
213 *error = CFErrorCreate(NULL, kSecErrorDomain, errSecAuthNeeded, NULL);
214
215 CFReleaseSafe(user_info);
216 return false;
217 }
218
219 static bool merge_der_in_to_data(const void *ed_blob, size_t ed_blob_len, const void *key_blob, size_t key_blob_len, CFMutableDataRef mergedData)
220 {
221 bool ok = false;
222 CFDataRef ed_data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, ed_blob, ed_blob_len, kCFAllocatorNull);
223 CFDataRef key_data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, key_blob, key_blob_len, kCFAllocatorNull);
224
225 if (ed_data && key_data) {
226 CFDictionaryRef result_dict = CFDictionaryCreateForCFTypes(kCFAllocatorDefault, kSecKSKeyData1, ed_data, kSecKSKeyData2, key_data, NULL);
227
228 CFDataSetLength(mergedData, 0);
229 CFDataRef der_data = CFPropertyListCreateDERData(kCFAllocatorDefault, result_dict, NULL);
230 if (der_data) {
231 CFDataAppend(mergedData, der_data);
232 CFRelease(der_data);
233 ok = CFDataGetLength(mergedData) > 0;
234 }
235 CFRelease(result_dict);
236 }
237
238 CFReleaseSafe(ed_data);
239 CFReleaseSafe(key_data);
240 return ok;
241 }
242
243 bool ks_separate_data_and_key(CFDictionaryRef blob_dict, CFDataRef *ed_data, CFDataRef *key_data)
244 {
245 bool ok = false;
246 CFDataRef tmp_ed_data = CFDictionaryGetValue(blob_dict, kSecKSKeyData1);
247 CFDataRef tmp_key_data = CFDictionaryGetValue(blob_dict, kSecKSKeyData2);
248
249 if (tmp_ed_data && tmp_key_data &&
250 CFDataGetTypeID() == CFGetTypeID(tmp_ed_data) &&
251 CFDataGetTypeID() == CFGetTypeID(tmp_key_data)) {
252 *ed_data = CFRetain(tmp_ed_data);
253 *key_data = CFRetain(tmp_key_data);
254 ok = true;
255 }
256
257 return ok;
258 }
259
260 static bool create_cferror_from_aks(int aks_return, CFTypeRef operation, keybag_handle_t keybag, keyclass_t keyclass, CFDataRef access_control_data, CFDataRef acm_context_data, CFErrorRef *error)
261 {
262 const char *operation_string = "";
263 if (CFEqual(operation, kAKSKeyOpDecrypt)) {
264 operation_string = "decrypt";
265 } else if (CFEqual(operation, kAKSKeyOpEncrypt)) {
266 operation_string = "encrypt";
267 } if (CFEqual(operation, kAKSKeyOpDelete)) {
268 operation_string = "delete";
269 }
270
271 if (aks_return == kAKSReturnNoPermission) {
272 /* Keychain is locked. */
273 SecError(errSecInteractionNotAllowed, error, CFSTR("aks_ref_key: %x failed to '%s' item (class %"PRId32", bag: %"PRId32") Access to item attempted while keychain is locked."),
274 aks_return, operation_string, keyclass, keybag);
275 } else if (aks_return == kAKSReturnPolicyError || aks_return == kAKSReturnBadPassword) {
276 if (aks_return == kAKSReturnBadPassword) {
277 ACMContextRef acm_context_ref = ACMContextCreateWithExternalForm(CFDataGetBytePtr(acm_context_data), CFDataGetLength(acm_context_data));
278 if (acm_context_ref) {
279 ACMContextRemovePassphraseCredentialsByPurposeAndScope(acm_context_ref, kACMPassphrasePurposeGeneral, kACMScopeContext);
280 ACMContextDelete(acm_context_ref, false);
281 }
282 }
283
284 /* Item needed authentication. */
285 ks_access_control_needed_error(error, access_control_data, operation);
286 } else if (aks_return == kAKSReturnError || aks_return == kAKSReturnPolicyInvalid) {
287 /* Item can't be decrypted on this device, ever, so drop the item. */
288 SecError(errSecDecode, error, CFSTR("aks_ref_key: %x failed to '%s' item (class %"PRId32", bag: %"PRId32") Item can't be decrypted on this device, ever, so drop the item."),
289 aks_return, operation_string, keyclass, keybag);
290 } else {
291 SecError(errSecNotAvailable, error, CFSTR("aks_ref_key: %x failed to '%s' item (class %"PRId32", bag: %"PRId32")"),
292 aks_return, operation_string, keyclass, keybag);
293 }
294
295 return false;
296 }
297
298 bool ks_encrypt_acl(keybag_handle_t keybag, keyclass_t keyclass, uint32_t textLength, const uint8_t *source,
299 CFMutableDataRef dest, CFDataRef auth_data, CFDataRef acm_context,
300 SecAccessControlRef access_control, CFErrorRef *error) {
301 void *params = NULL, *der = NULL;
302 size_t params_len = 0, der_len = 0;
303 CFDataRef access_control_data = SecAccessControlCopyData(access_control);
304 int aks_return = kAKSReturnSuccess;
305 aks_ref_key_t key_handle = NULL;
306
307 /* Verify that we have credential handle, otherwise generate proper error containing ACL and operation requested. */
308 bool ok = false;
309 if (!acm_context || !SecAccessControlIsBound(access_control)) {
310 require_quiet(ok = ks_access_control_needed_error(error, access_control_data, SecAccessControlIsBound(access_control) ? kAKSKeyOpEncrypt : CFSTR("")), out);
311 }
312
313 aks_operation_optional_params(0, 0, CFDataGetBytePtr(auth_data), CFDataGetLength(auth_data), CFDataGetBytePtr(acm_context), (int)CFDataGetLength(acm_context), &params, &params_len);
314 require_noerr_action_quiet(aks_return = aks_ref_key_create(keybag, keyclass, key_type_sym, params, params_len, &key_handle), out,
315 create_cferror_from_aks(aks_return, kAKSKeyOpEncrypt, keybag, keyclass, access_control_data, acm_context, error));
316 require_noerr_action_quiet(aks_return = aks_ref_key_encrypt(key_handle, params, params_len, source, textLength, &der, &der_len), out,
317 create_cferror_from_aks(aks_return, kAKSKeyOpEncrypt, keybag, keyclass, access_control_data, acm_context, error));
318 size_t key_blob_len;
319 const void *key_blob = aks_ref_key_get_blob(key_handle, &key_blob_len);
320 require_action_quiet(key_blob, out, SecError(errSecDecode, error, CFSTR("ks_crypt_acl: %x failed to '%s' item (class %"PRId32", bag: %"PRId32") Item can't be encrypted due to invalid key data, so drop the item."),
321 aks_return, "encrypt", keyclass, keybag));
322
323 require_action_quiet(merge_der_in_to_data(der, der_len, key_blob, key_blob_len, dest), out,
324 SecError(errSecDecode, error, CFSTR("ks_crypt_acl: %x failed to '%s' item (class %"PRId32", bag: %"PRId32") Item can't be encrypted due to merge failed, so drop the item."),
325 aks_return, "encrypt", keyclass, keybag));
326
327 ok = true;
328
329 out:
330 if (key_handle)
331 aks_ref_key_free(&key_handle);
332 if(params)
333 free(params);
334 if(der)
335 free(der);
336 CFReleaseSafe(access_control_data);
337 return ok;
338 }
339
340 bool ks_decrypt_acl(aks_ref_key_t ref_key, CFDataRef encrypted_data, CFMutableDataRef dest,
341 CFDataRef acm_context, CFDataRef caller_access_groups,
342 SecAccessControlRef access_control, CFErrorRef *error) {
343 void *params = NULL, *der = NULL;
344 const uint8_t *access_groups = caller_access_groups?CFDataGetBytePtr(caller_access_groups):NULL;
345 size_t params_len = 0, der_len = 0, access_groups_len = caller_access_groups?CFDataGetLength(caller_access_groups):0;
346 CFDataRef access_control_data = SecAccessControlCopyData(access_control);
347 int aks_return = kAKSReturnSuccess;
348
349 /* Verify that we have credential handle, otherwise generate proper error containing ACL and operation requested. */
350 bool ok = false;
351 if (!acm_context) {
352 require_quiet(ok = ks_access_control_needed_error(error, NULL, NULL), out);
353 }
354
355 aks_operation_optional_params(access_groups, access_groups_len, 0, 0, CFDataGetBytePtr(acm_context), (int)CFDataGetLength(acm_context), &params, &params_len);
356 require_noerr_action_quiet(aks_return = aks_ref_key_decrypt(ref_key, params, params_len, CFDataGetBytePtr(encrypted_data), CFDataGetLength(encrypted_data), &der, &der_len), out,
357 create_cferror_from_aks(aks_return, kAKSKeyOpDecrypt, 0, 0, access_control_data, acm_context, error));
358 require_action_quiet(der, out, SecError(errSecDecode, error, CFSTR("ks_crypt_acl: %x failed to '%s' item, Item can't be decrypted due to invalid der data, so drop the item."),
359 aks_return, "decrypt"));
360
361 CFPropertyListRef decoded_data = NULL;
362 der_decode_plist(kCFAllocatorDefault, kCFPropertyListImmutable, &decoded_data, NULL, der, der + der_len);
363 require_action_quiet(decoded_data, out, SecError(errSecDecode, error, CFSTR("ks_crypt_acl: %x failed to '%s' item, Item can't be decrypted due to failed decode der, so drop the item."),
364 aks_return, "decrypt"));
365 if (CFGetTypeID(decoded_data) == CFDataGetTypeID()) {
366 CFDataSetLength(dest, 0);
367 CFDataAppend(dest, decoded_data);
368 CFRelease(decoded_data);
369 }
370 else {
371 CFRelease(decoded_data);
372 require_action_quiet(false, out, SecError(errSecDecode, error, CFSTR("ks_crypt_acl: %x failed to '%s' item, Item can't be decrypted due to wrong data, so drop the item."),
373 aks_return, "decrypt"));
374 }
375
376 ok = true;
377
378 out:
379 if(params)
380 free(params);
381 if(der)
382 free(der);
383 CFReleaseSafe(access_control_data);
384 return ok;
385 }
386
387 bool ks_delete_acl(aks_ref_key_t ref_key, CFDataRef encrypted_data,
388 CFDataRef acm_context, CFDataRef caller_access_groups,
389 SecAccessControlRef access_control, CFErrorRef *error) {
390 void *params = NULL;
391 CFDataRef access_control_data = NULL;
392 int aks_return = kAKSReturnSuccess;
393 bool ok = false;
394
395 nrequire_action_quiet(CFEqual(SecAccessControlGetConstraint(access_control, kAKSKeyOpDelete), kCFBooleanTrue), out, ok = true);
396
397 /* Verify that we have credential handle, otherwise generate proper error containing ACL and operation requested. */
398 if (!acm_context) {
399 require_quiet(ok = ks_access_control_needed_error(error, NULL, NULL), out);
400 }
401
402 access_control_data = SecAccessControlCopyData(access_control);
403 const uint8_t *access_groups = caller_access_groups?CFDataGetBytePtr(caller_access_groups):NULL;
404 size_t params_len = 0, access_groups_len = caller_access_groups?CFDataGetLength(caller_access_groups):0;
405 aks_operation_optional_params(access_groups, access_groups_len, 0, 0, CFDataGetBytePtr(acm_context), (int)CFDataGetLength(acm_context), &params, &params_len);
406 require_noerr_action_quiet(aks_return = aks_ref_key_delete(ref_key, params, params_len), out,
407 create_cferror_from_aks(aks_return, kAKSKeyOpDelete, 0, 0, access_control_data, acm_context, error));
408
409 ok = true;
410
411 out:
412 if(params)
413 free(params);
414 CFReleaseSafe(access_control_data);
415 return ok;
416 }
417
418 const void* ks_ref_key_get_external_data(keybag_handle_t keybag, CFDataRef key_data, aks_ref_key_t *ref_key, size_t *external_data_len, CFErrorRef *error) {
419 const void* result = NULL;
420 int aks_return = kAKSReturnSuccess;
421 require_noerr_action_quiet(aks_ref_key_create_with_blob(keybag, CFDataGetBytePtr(key_data), CFDataGetLength(key_data), ref_key), out,
422 SecError(errSecNotAvailable, error, CFSTR("aks_ref_key: %x failed to '%s' item (bag: %"PRId32")"), aks_return, "create ref key with blob", keybag));
423 result = aks_ref_key_get_external_data(*ref_key, external_data_len);
424
425 out:
426 return result;
427 }
428 #endif
429
430 bool use_hwaes(void) {
431 static bool use_hwaes;
432 static dispatch_once_t check_once;
433 dispatch_once(&check_once, ^{
434 use_hwaes = hwaes_key_available();
435 if (use_hwaes) {
436 asl_log(NULL, NULL, ASL_LEVEL_INFO, "using hwaes key");
437 } else {
438 asl_log(NULL, NULL, ASL_LEVEL_ERR, "unable to access hwaes key");
439 }
440 });
441 return use_hwaes;
442 }
443
444 bool ks_open_keybag(CFDataRef keybag, CFDataRef password, keybag_handle_t *handle, CFErrorRef *error) {
445 #if USE_KEYSTORE
446 kern_return_t kernResult;
447 if (!asData(keybag, error)) return false;
448 kernResult = aks_load_bag(CFDataGetBytePtr(keybag), (int)CFDataGetLength(keybag), handle);
449 if (kernResult)
450 return SecKernError(kernResult, error, CFSTR("aks_load_bag failed: %@"), keybag);
451
452 if (password) {
453 kernResult = aks_unlock_bag(*handle, CFDataGetBytePtr(password), (int)CFDataGetLength(password));
454 if (kernResult) {
455 aks_unload_bag(*handle);
456 return SecKernError(kernResult, error, CFSTR("aks_unlock_bag failed"));
457 }
458 }
459 return true;
460 #else /* !USE_KEYSTORE */
461 *handle = KEYBAG_NONE;
462 return true;
463 #endif /* USE_KEYSTORE */
464 }
465
466 bool ks_close_keybag(keybag_handle_t keybag, CFErrorRef *error) {
467 #if USE_KEYSTORE
468 IOReturn kernResult = aks_unload_bag(keybag);
469 if (kernResult) {
470 return SecKernError(kernResult, error, CFSTR("aks_unload_bag failed"));
471 }
472 #endif /* USE_KEYSTORE */
473 return true;
474 }
475