2 * Copyright (c) 2015-2017 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@
27 #include <Security/SecureObjectSync/SOSBackupSliceKeyBag.h>
30 // Needed headers for implementation
31 #include "AssertMacros.h"
32 #include <utilities/SecCFWrappers.h>
33 #include <utilities/SecAKSWrappers.h>
34 #include <utilities/SecBuffer.h>
35 #include <utilities/SecCFError.h>
36 #include <utilities/der_set.h>
37 #include <utilities/der_plist_internal.h>
38 #include <Security/SecRandom.h>
39 #include <Security/SecureObjectSync/SOSPeerInfo.h>
40 #include "keychain/SecureObjectSync/SOSPeerInfoCollections.h"
41 #include "keychain/SecureObjectSync/SOSInternal.h"
43 #include <corecrypto/ccec.h>
44 #include <corecrypto/ccsha2.h>
45 #include <corecrypto/ccrng.h>
49 #include <Security/SecRecoveryKey.h>
50 #include "SOSKeyedPubKeyIdentifier.h"
51 #include "keychain/SecureObjectSync/SOSInternal.h"
52 #include "SecADWrapper.h"
53 #include "SecCFAllocator.h"
55 CFStringRef bskbRkbgPrefix = CFSTR("RK");
57 CFDataRef SOSRKNullKey(void) {
58 static CFDataRef localNullKey = NULL;
59 static dispatch_once_t onceToken;
60 dispatch_once(&onceToken, ^{
61 localNullKey = CFDataCreate(kCFAllocatorDefault, (const UInt8*) "nullkey", 8);
67 // MARK: Type creation
70 CFGiblisFor(SOSBackupSliceKeyBag);
72 const int kAKSBagSecretLength = 32;
74 struct __OpaqueSOSBackupSliceKeyBag {
80 CFDictionaryRef wrapped_keys;
83 static void SOSBackupSliceKeyBagDestroy(CFTypeRef aObj) {
84 SOSBackupSliceKeyBagRef vb = (SOSBackupSliceKeyBagRef) aObj;
86 CFReleaseNull(vb->aks_bag);
87 CFReleaseNull(vb->peers);
88 CFReleaseNull(vb->wrapped_keys);
91 static CFSetRef SOSBackupSliceKeyBagCopyPeerNames(SOSBackupSliceKeyBagRef bksb) {
92 CFMutableSetRef retval = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
93 if(!retval) return NULL;
94 CFSetForEach(bksb->peers, ^(const void *value) {
95 SOSPeerInfoRef pi = (SOSPeerInfoRef) value;
96 CFSetAddValue(retval, SOSPeerInfoGetPeerName(pi));
101 static CFStringRef SOSBackupSliceKeyBagCopyFormatDescription(CFTypeRef aObj, CFDictionaryRef formatOptions) {
102 SOSBackupSliceKeyBagRef vb = (SOSBackupSliceKeyBagRef) aObj;
104 CFMutableStringRef retval = CFStringCreateMutable(kCFAllocatorDefault, 0);
106 CFSetRef peerIDs = SOSBackupSliceKeyBagCopyPeerNames(vb);
107 CFStringSetPerformWithDescription(peerIDs, ^(CFStringRef description) {
108 CFStringAppendFormat(retval, NULL, CFSTR("<SOSBackupSliceKeyBag@%p %ld %@"), vb, vb->peers ? CFSetGetCount(vb->peers) : 0, description);
110 CFReleaseNull(peerIDs);
111 CFStringAppend(retval, CFSTR(">"));
118 // MARK: Encode/Decode
121 const uint8_t* der_decode_BackupSliceKeyBag(CFAllocatorRef allocator,
122 SOSBackupSliceKeyBagRef* BackupSliceKeyBag, CFErrorRef *error,
123 const uint8_t* der, const uint8_t *der_end) {
124 if (der == NULL) return der;
126 const uint8_t *result = NULL;
127 SOSBackupSliceKeyBagRef vb = CFTypeAllocate(SOSBackupSliceKeyBag, struct __OpaqueSOSBackupSliceKeyBag, allocator);
128 require_quiet(SecAllocationError(vb, error, CFSTR("View bag allocation failed")), fail);
130 const uint8_t *sequence_end = NULL;
131 der = ccder_decode_sequence_tl(&sequence_end, der, der_end);
132 require_quiet(sequence_end == der_end, fail);
134 der = der_decode_data(kCFAllocatorDefault, kCFPropertyListImmutable, &vb->aks_bag, error, der, sequence_end);
135 vb->peers = SOSPeerInfoSetCreateFromArrayDER(kCFAllocatorDefault, &kSOSPeerSetCallbacks, error,
137 der = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListImmutable, &vb->wrapped_keys, error, der, sequence_end);
139 require_quiet(SecRequirementError(der == der_end, error, CFSTR("Extra space in sequence")), fail);
141 if (BackupSliceKeyBag)
142 CFTransferRetained(*BackupSliceKeyBag, vb);
151 size_t der_sizeof_BackupSliceKeyBag(SOSBackupSliceKeyBagRef BackupSliceKeyBag, CFErrorRef *error) {
154 require_quiet(SecRequirementError(BackupSliceKeyBag != NULL, error, CFSTR("Null BackupSliceKeyBag")), fail);
155 require_quiet(BackupSliceKeyBag != NULL, fail); // this is redundant with what happens in SecRequirementError, but the analyzer can't understand that.
156 require_quiet(SecRequirementError(BackupSliceKeyBag->aks_bag != NULL, error, CFSTR("null aks_bag in BackupSliceKeyBag")), fail);
157 require_quiet(BackupSliceKeyBag->aks_bag != NULL, fail); // this is redundant with what happens in SecRequirementError, but the analyzer can't understand that.
159 size_t bag_size = der_sizeof_data(BackupSliceKeyBag->aks_bag, error);
160 require_quiet(bag_size, fail);
162 size_t peers_size = SOSPeerInfoSetGetDEREncodedArraySize(BackupSliceKeyBag->peers, error);
163 require_quiet(peers_size, fail);
165 size_t wrapped_keys_size = der_sizeof_dictionary(BackupSliceKeyBag->wrapped_keys, error);
166 require_quiet(wrapped_keys_size, fail);
168 result = ccder_sizeof(CCDER_CONSTRUCTED_SEQUENCE, bag_size + peers_size + wrapped_keys_size);
174 uint8_t* der_encode_BackupSliceKeyBag(SOSBackupSliceKeyBagRef set, CFErrorRef *error,
175 const uint8_t *der, uint8_t *der_end) {
176 uint8_t *result = NULL;
177 if (der_end == NULL) return der_end;
179 require_quiet(SecRequirementError(set != NULL, error, CFSTR("Null set passed to encode")), fail);
180 require_quiet(set, fail); // Silence the NULL warning.
182 require_quiet(SecRequirementError(set->aks_bag != NULL, error, CFSTR("Null set passed to encode")), fail);
183 require_quiet(set->aks_bag, fail); // Silence the warning.
185 der_end = ccder_encode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, der_end, der,
186 der_encode_data(set->aks_bag, error, der,
187 SOSPeerInfoSetEncodeToArrayDER(set->peers, error, der,
188 der_encode_dictionary(set->wrapped_keys, error, der, der_end))));
190 require_quiet(der_end == der, fail);
199 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagCreateFromData(CFAllocatorRef allocator, CFDataRef data, CFErrorRef *error) {
200 SOSBackupSliceKeyBagRef result = NULL;
201 SOSBackupSliceKeyBagRef decodedBag = NULL;
203 const uint8_t *der = CFDataGetBytePtr(data);
204 const uint8_t *der_end = der + CFDataGetLength(data);
206 der = der_decode_BackupSliceKeyBag(allocator, &decodedBag, error, der, der_end);
208 require_quiet(SecRequirementError(der == der_end, error, CFSTR("Didn't consume all data supplied")), fail);
210 CFTransferRetained(result, decodedBag);
213 CFReleaseNull(decodedBag);
218 // MARK: Construction
221 bool SOSBSKBIsGoodBackupPublic(CFDataRef publicKey, CFErrorRef *error) {
224 ccec_pub_ctx_decl_cp(SOSGetBackupKeyCurveParameters(), pub_key);
226 int cc_result = ccec_compact_import_pub(SOSGetBackupKeyCurveParameters(), CFDataGetLength(publicKey), CFDataGetBytePtr(publicKey), pub_key);
228 require_action_quiet(cc_result == 0, exit, SOSErrorCreate(kSOSErrorDecodeFailure, error, NULL, CFSTR("Unable to decode public key: %@"), publicKey));
237 static CFDataRef SOSCopyECWrapped(CFDataRef publicKey, CFDataRef secret, CFErrorRef *error) {
238 CFDataRef result = NULL;
240 ccec_pub_ctx_decl_cp(SOSGetBackupKeyCurveParameters(), pub_key);
242 int cc_result = ccec_compact_import_pub(SOSGetBackupKeyCurveParameters(), CFDataGetLength(publicKey), CFDataGetBytePtr(publicKey), pub_key);
244 require_action_quiet(cc_result == 0, exit, SOSErrorCreate(kSOSErrorDecodeFailure, error, NULL, CFSTR("Unable to decode public key: %@"), publicKey));
246 result = SOSCopyECWrappedData(pub_key, secret, error);
253 static CFDictionaryRef SOSBackupSliceKeyBagCopyWrappedKeys(SOSBackupSliceKeyBagRef vb, CFDataRef secret, CFDictionaryRef additionalKeys, CFErrorRef *error) {
254 CFDictionaryRef result = NULL;
255 CFMutableDictionaryRef wrappedKeys = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
257 __block bool success = true;
258 CFSetForEach(vb->peers, ^(const void *value) {
259 SOSPeerInfoRef pi = (SOSPeerInfoRef) value;
260 if (isSOSPeerInfo(pi)) {
261 CFStringRef id = SOSPeerInfoGetPeerID(pi);
262 CFDataRef backupKey = SOSPeerInfoCopyBackupKey(pi);
265 CFErrorRef wrapError = NULL;
266 CFDataRef wrappedKey = SOSCopyECWrapped(backupKey, secret, &wrapError);
268 CFDictionaryAddValue(wrappedKeys, id, wrappedKey);
269 CFDataPerformWithHexString(backupKey, ^(CFStringRef backupKeyString) {
270 CFDataPerformWithHexString(wrappedKey, ^(CFStringRef wrappedKeyString) {
271 secnotice("bskb", "Add for id: %@, bk: %@, wrapped: %@", id, backupKeyString, wrappedKeyString);
275 CFDataPerformWithHexString(backupKey, ^(CFStringRef backupKeyString) {
276 secnotice("bskb", "Failed at id: %@, bk: %@ error: %@", id, backupKeyString, wrapError);
278 CFErrorPropagate(wrapError, error);
281 CFReleaseNull(wrappedKey);
282 CFReleaseNull(backupKey);
284 secnotice("bskb", "Skipping id %@, no backup key.", id);
290 CFDictionaryForEach(additionalKeys, ^(const void *key, const void *value) {
291 CFStringRef prefix = asString(key, NULL);
292 CFDataRef backupKey = asData(value, NULL);
294 CFDataRef wrappedKey = NULL;
295 CFErrorRef localError = NULL;
296 CFStringRef id = SOSKeyedPubKeyIdentifierCreateWithData(prefix, backupKey);
297 require_quiet(id, done);
299 wrappedKey = SOSCopyECWrapped(backupKey, secret, &localError);
300 require_quiet(wrappedKey, done);
302 CFDictionaryAddValue(wrappedKeys, id, wrappedKey);
306 CFDataPerformWithHexString(backupKey, ^(CFStringRef backupKeyString) {
307 CFDataPerformWithHexString(wrappedKey, ^(CFStringRef wrappedKeyString) {
308 secnotice("bskb", "Add for bk: %@, wrapped: %@", backupKeyString, wrappedKeyString);
312 CFDataPerformWithHexString(backupKey, ^(CFStringRef backupKeyString) {
313 secnotice("bskb", "Failed at bk: %@ error: %@", backupKeyString, localError);
315 CFErrorPropagate(localError, error);
318 CFReleaseNull(wrappedKey);
321 secnotice("bskb", "Skipping %@, not data.", value);
326 CFTransferRetained(result, wrappedKeys);
328 CFReleaseNull(wrappedKeys);
332 static bool SOSBackupSliceKeyBagCreateBackupBag(SOSBackupSliceKeyBagRef vb, CFDictionaryRef/*CFDataRef*/ additionalKeys, CFErrorRef* error) {
333 CFReleaseNull(vb->aks_bag);
335 // Choose a random key.
336 PerformWithBufferAndClear(kAKSBagSecretLength, ^(size_t size, uint8_t *buffer) {
337 CFDataRef secret = NULL;
339 require_quiet(SecError(SecRandomCopyBytes(kSecRandomDefault, size, buffer), error, CFSTR("SecRandom falied!")), fail);
341 secret = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, buffer, size, kCFAllocatorNull);
343 CFAssignRetained(vb->wrapped_keys, SOSBackupSliceKeyBagCopyWrappedKeys(vb, secret, additionalKeys, error));
344 CFAssignRetained(vb->aks_bag, SecAKSCopyBackupBagWithSecret(size, buffer, error));
347 CFReleaseSafe(secret);
350 return vb->aks_bag != NULL;
354 CFDataRef SOSBSKBCopyEncoded(SOSBackupSliceKeyBagRef BackupSliceKeyBag, CFErrorRef* error) {
355 CFDataRef result = NULL;
356 CFMutableDataRef encoded = NULL;
358 size_t encodedSize = der_sizeof_BackupSliceKeyBag(BackupSliceKeyBag, error);
359 require_quiet(encodedSize, fail);
361 encoded = CFDataCreateMutableWithScratch(kCFAllocatorDefault, encodedSize);
362 require_quiet(SecAllocationError(encoded, error, CFSTR("Faild to create scratch")), fail);
364 uint8_t *encode_to = CFDataGetMutableBytePtr(encoded);
365 uint8_t *encode_to_end = encode_to + CFDataGetLength(encoded);
366 require_quiet(encode_to == der_encode_BackupSliceKeyBag(BackupSliceKeyBag, error, encode_to, encode_to_end), fail);
368 CFTransferRetained(result, encoded);
371 CFReleaseSafe(encoded);
375 static CFSetRef SOSBackupSliceKeyBagCreatePeerSet(CFAllocatorRef allocator, CFSetRef peers) {
376 CFMutableSetRef result = CFSetCreateMutableForSOSPeerInfosByID(allocator);
378 CFSetForEach(peers, ^(const void *value) {
379 CFSetAddValue(result, value);
385 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagCreate(CFAllocatorRef allocator, CFSetRef peers, CFErrorRef* error) {
386 CFMutableDictionaryRef additionalKeys = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
388 SOSBackupSliceKeyBagRef result = SOSBackupSliceKeyBagCreateWithAdditionalKeys(allocator, peers, additionalKeys, NULL);
390 CFReleaseNull(additionalKeys);
395 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagCreateWithAdditionalKeys(CFAllocatorRef allocator,
396 CFSetRef /*SOSPeerInfoRef*/ peers,
397 CFDictionaryRef /*CFStringRef (prefix) CFDataRef (keydata) */ additionalKeys,
399 SOSBackupSliceKeyBagRef result = NULL;
400 SOSBackupSliceKeyBagRef vb = CFTypeAllocate(SOSBackupSliceKeyBag, struct __OpaqueSOSBackupSliceKeyBag, allocator);
401 require_quiet(SecAllocationError(vb, error, CFSTR("View bag allocation failed")), fail);
403 require_quiet(SecRequirementError(CFSetGetCount(peers) > 0, error, CFSTR("Need peers")), fail);
405 vb->peers = SOSBackupSliceKeyBagCreatePeerSet(allocator, peers);
406 vb->wrapped_keys = CFDictionaryCreateMutableForCFTypes(allocator);
408 require_quiet(SOSBackupSliceKeyBagCreateBackupBag(vb, additionalKeys, error), fail);
410 CFTransferRetained(result, vb);
418 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagCreateDirect(CFAllocatorRef allocator, CFDataRef aks_bag, CFErrorRef *error)
420 SOSBackupSliceKeyBagRef result = NULL;
421 SOSBackupSliceKeyBagRef vb = CFTypeAllocate(SOSBackupSliceKeyBag, struct __OpaqueSOSBackupSliceKeyBag, allocator);
422 require_quiet(SecAllocationError(vb, error, CFSTR("View bag allocation failed")), fail);
424 require_quiet(SecRequirementError(aks_bag, error, CFSTR("Need aks bag")), fail);
426 vb->aks_bag = CFRetainSafe(aks_bag);
427 vb->peers = CFSetCreateMutableForSOSPeerInfosByID(allocator);
428 vb->wrapped_keys = CFDictionaryCreateMutableForCFTypes(allocator);
430 CFTransferRetained(result, vb);
441 bool SOSBSKBIsDirect(SOSBackupSliceKeyBagRef backupSliceKeyBag)
443 return 0 == CFSetGetCount(backupSliceKeyBag->peers);
446 CFDataRef SOSBSKBCopyAKSBag(SOSBackupSliceKeyBagRef backupSliceKeyBag, CFErrorRef* error)
448 return CFRetainSafe(backupSliceKeyBag->aks_bag);
451 CFSetRef SOSBSKBGetPeers(SOSBackupSliceKeyBagRef backupSliceKeyBag){
452 return backupSliceKeyBag->peers;
455 int SOSBSKBCountPeers(SOSBackupSliceKeyBagRef backupSliceKeyBag) {
456 return (backupSliceKeyBag->peers) ? (int) CFSetGetCount(backupSliceKeyBag->peers): 0;
459 bool SOSBSKBPeerIsInKeyBag(SOSBackupSliceKeyBagRef backupSliceKeyBag, SOSPeerInfoRef pi) {
460 return CFSetGetValue(backupSliceKeyBag->peers, pi) != NULL;
465 bool SOSBKSBKeyIsInKeyBag(SOSBackupSliceKeyBagRef backupSliceKeyBag, CFDataRef publicKey) {
467 CFStringRef keyID = SOSCopyIDOfDataBuffer(publicKey, NULL);
468 require_quiet(keyID, done);
470 result = CFDictionaryContainsKey(backupSliceKeyBag->wrapped_keys, keyID);
473 CFReleaseSafe(keyID);
477 bool SOSBKSBPeerBackupKeyIsInKeyBag(SOSBackupSliceKeyBagRef backupSliceKeyBag, SOSPeerInfoRef pi) {
479 CFDataRef bskbBackupKey = NULL;
481 CFDataRef backupKey = SOSPeerInfoCopyBackupKey(pi);
482 SOSPeerInfoRef backupPI = asSOSPeerInfo(CFSetGetValue(backupSliceKeyBag->peers, pi));
484 bskbBackupKey = SOSPeerInfoCopyBackupKey(backupPI);
486 result = CFEqualSafe(backupKey, bskbBackupKey);
487 CFReleaseNull(bskbBackupKey);
488 CFReleaseNull(backupKey);
492 // returns true if all peers in (peers) and only those peers have matching backupKeys in the BSKB
493 bool SOSBSKBAllPeersBackupKeysAreInKeyBag(SOSBackupSliceKeyBagRef backupSliceKeyBag, CFSetRef peers) {
494 __block bool result = false;
495 if(backupSliceKeyBag && peers) {
496 result = (SOSBSKBCountPeers(backupSliceKeyBag) == CFSetGetCount(peers));
498 CFSetForEach(peers, ^(const void *value) {
499 SOSPeerInfoRef pi = asSOSPeerInfo(value);
500 result &= pi && SOSBKSBPeerBackupKeyIsInKeyBag(backupSliceKeyBag, pi);
507 bool SOSBKSBPrefixedKeyIsInKeyBag(SOSBackupSliceKeyBagRef backupSliceKeyBag, CFStringRef prefix, CFDataRef publicKey) {
509 CFStringRef kpkid = SOSKeyedPubKeyIdentifierCreateWithData(prefix, publicKey);
510 require_quiet(kpkid, done);
512 result = CFDictionaryContainsKey(backupSliceKeyBag->wrapped_keys, kpkid);
515 CFReleaseSafe(kpkid);
522 bskb_keybag_handle_t SOSBSKBLoadLocked(SOSBackupSliceKeyBagRef backupSliceKeyBag,
525 #if !TARGET_HAS_KEYSTORE
526 return bad_keybag_handle;
528 keybag_handle_t result = bad_keybag_handle;
529 keybag_handle_t bag_handle = bad_keybag_handle;
531 require_quiet(SecRequirementError(backupSliceKeyBag->aks_bag, error,
532 CFSTR("No aks bag to load")), exit);
533 require_quiet(SecRequirementError(CFDataGetLength(backupSliceKeyBag->aks_bag) < INT_MAX, error,
534 CFSTR("No aks bag to load")), exit);
536 kern_return_t aks_result;
537 aks_result = aks_load_bag(CFDataGetBytePtr(backupSliceKeyBag->aks_bag),
538 (int) CFDataGetLength(backupSliceKeyBag->aks_bag),
540 require_quiet(SecKernError(aks_result, error,
541 CFSTR("aks_load_bag failed: %d"), aks_result), exit);
544 bag_handle = bad_keybag_handle;
547 if (bag_handle != bad_keybag_handle) {
548 (void) aks_unload_bag(bag_handle);
556 static keybag_handle_t SOSBSKBLoadAndUnlockBagWithSecret(SOSBackupSliceKeyBagRef backupSliceKeyBag,
557 size_t secretSize, const uint8_t *secret,
560 #if !TARGET_HAS_KEYSTORE
561 return bad_keybag_handle;
563 keybag_handle_t result = bad_keybag_handle;
564 keybag_handle_t bag_handle = bad_keybag_handle;
566 require_quiet(SecRequirementError(backupSliceKeyBag->aks_bag, error,
567 CFSTR("No aks bag to load")), exit);
568 require_quiet(SecRequirementError(CFDataGetLength(backupSliceKeyBag->aks_bag) < INT_MAX, error,
569 CFSTR("No aks bag to load")), exit);
570 require_quiet(SecRequirementError(secretSize <= INT_MAX, error,
571 CFSTR("secret too big")), exit);
573 kern_return_t aks_result;
574 aks_result = aks_load_bag(CFDataGetBytePtr(backupSliceKeyBag->aks_bag),
575 (int) CFDataGetLength(backupSliceKeyBag->aks_bag),
577 require_quiet(SecKernError(aks_result, error,
578 CFSTR("aks_load_bag failed: %d"), aks_result), exit);
580 aks_result = aks_unlock_bag(bag_handle, secret, (int) secretSize);
581 require_quiet(SecKernError(aks_result, error,
582 CFSTR("failed to unlock bag: %d"), aks_result), exit);
585 bag_handle = bad_keybag_handle;
588 if (bag_handle != bad_keybag_handle) {
589 (void) aks_unload_bag(bag_handle);
596 keybag_handle_t SOSBSKBLoadAndUnlockWithPeerIDAndSecret(SOSBackupSliceKeyBagRef backupSliceKeyBag,
597 CFStringRef peerID, CFDataRef peerSecret,
600 __block keybag_handle_t result = bad_keybag_handle;
602 CFDataRef lookedUpData = CFDictionaryGetValue(backupSliceKeyBag->wrapped_keys, peerID);
603 require_quiet(SecRequirementError(lookedUpData != NULL, error, CFSTR("%@ has no wrapped key in %@"), peerID, backupSliceKeyBag), exit);
605 require_quiet(SOSPerformWithDeviceBackupFullKey(SOSGetBackupKeyCurveParameters(), peerSecret, error, ^(ccec_full_ctx_t fullKey) {
606 SOSPerformWithUnwrappedData(fullKey, lookedUpData, error, ^(size_t size, uint8_t *buffer) {
607 result = SOSBSKBLoadAndUnlockBagWithSecret(backupSliceKeyBag, size, buffer, error);
616 keybag_handle_t SOSBSKBLoadAndUnlockWithPeerSecret(SOSBackupSliceKeyBagRef backupSliceKeyBag,
617 SOSPeerInfoRef peer, CFDataRef peerSecret,
620 return SOSBSKBLoadAndUnlockWithPeerIDAndSecret(backupSliceKeyBag, SOSPeerInfoGetPeerID(peer), peerSecret, error);
623 keybag_handle_t SOSBSKBLoadAndUnlockWithDirectSecret(SOSBackupSliceKeyBagRef backupSliceKeyBag,
627 keybag_handle_t result = bad_keybag_handle;
628 require_quiet(SecRequirementError(SOSBSKBIsDirect(backupSliceKeyBag), error, CFSTR("Not direct bag")), exit);
630 result = SOSBSKBLoadAndUnlockBagWithSecret(backupSliceKeyBag,
631 CFDataGetLength(secret),
632 CFDataGetBytePtr(secret),
639 #include <Security/SecRecoveryKey.h>
641 static bool SOSPerformWithRecoveryKeyFullKey(CFDataRef wrappingSecret, CFErrorRef *error, void (^operation)(ccec_full_ctx_t fullKey, CFStringRef keyID)) {
644 CFStringRef keyID = NULL;
645 NSError *nserror = NULL;
646 SecRecoveryKey *sRecKey = NULL;
647 NSData* fullKeyBytes = NULL;
648 NSData* pubKeyBytes = NULL;
649 CFStringRef restoreKeySecret = CFStringCreateWithBytes(SecCFAllocatorZeroize(), CFDataGetBytePtr(wrappingSecret), CFDataGetLength(wrappingSecret), kCFStringEncodingUTF8, false);
650 require_action_quiet(restoreKeySecret, errOut, SOSErrorCreate(kSOSErrorDecodeFailure, error, NULL, CFSTR("Unable to create key string from data.")));
652 sRecKey = SecRKCreateRecoveryKeyWithError((__bridge NSString *)(restoreKeySecret), &nserror);
655 *error = (CFErrorRef)CFBridgingRetain(nserror);
659 require_action_quiet(sRecKey, errOut, SOSErrorCreate(kSOSErrorDecodeFailure, error, NULL, CFSTR("Unable to create recovery key from string.")));
661 fullKeyBytes = SecRKCopyBackupFullKey(sRecKey);
662 pubKeyBytes = SecRKCopyBackupPublicKey(sRecKey);
663 require_action_quiet(fullKeyBytes && pubKeyBytes, errOut, SOSErrorCreate(kSOSErrorDecodeFailure, error, NULL, CFSTR("Unable to get recovery key public and private keys.")));
664 keyID = SOSCopyIDOfDataBuffer(((__bridge CFDataRef) pubKeyBytes), error);
665 require_quiet(keyID, errOut);
667 size_t keysize = ccec_compact_import_priv_size(CFDataGetLength((__bridge CFDataRef)fullKeyBytes));
668 ccec_const_cp_t cp = ccec_curve_for_length_lookup(keysize, ccec_cp_256(), ccec_cp_384(), ccec_cp_521());
669 ccec_full_ctx_decl_cp(cp, fullKey);
670 int res = ccec_compact_import_priv(cp, CFDataGetLength((__bridge CFDataRef)fullKeyBytes), CFDataGetBytePtr((__bridge CFDataRef)fullKeyBytes), fullKey);
672 operation(fullKey, keyID);
674 ccec_full_ctx_clear_cp(cp, fullKey);
677 if(!result) SOSErrorCreate(kSOSErrorProcessingFailure, error, NULL, CFSTR("Unable to perform crypto operation from fullKeyBytes."));
680 CFReleaseNull(keyID);
681 CFReleaseNull(restoreKeySecret);
685 bskb_keybag_handle_t SOSBSKBLoadAndUnlockWithWrappingSecret(SOSBackupSliceKeyBagRef backupSliceKeyBag,
686 CFDataRef wrappingSecret,
688 __block keybag_handle_t result = bad_keybag_handle;
690 CFDataRef lookedUpData = SOSBSKBCopyRecoveryKey(backupSliceKeyBag);
691 require_quiet(SecRequirementError(lookedUpData != NULL, error, CFSTR("no recovery key found in %@"), backupSliceKeyBag), errOut);
693 SOSPerformWithRecoveryKeyFullKey(wrappingSecret, error, ^(ccec_full_ctx_t fullKey, CFStringRef keyID) {
694 SOSPerformWithUnwrappedData(fullKey, lookedUpData, error, ^(size_t size, uint8_t *buffer) {
695 result = SOSBSKBLoadAndUnlockBagWithSecret(backupSliceKeyBag, size, buffer, error);
700 CFReleaseSafe(lookedUpData);
704 // fixed for <rdar://problem/30918831> CrashTracer: secdtests at secdtests: SOSBSKBCopyAdditionalKeysWithPrefix
705 static CFDictionaryRef SOSBSKBCopyAdditionalKeysWithPrefix(CFAllocatorRef allocator, SOSBackupSliceKeyBagRef bskb, CFStringRef prefix) {
706 if(!bskb || !bskb->wrapped_keys) return NULL;
707 CFMutableDictionaryRef retval = CFDictionaryCreateMutableForCFTypes(allocator);
708 if(!retval) return NULL;
709 CFDictionaryForEach(bskb->wrapped_keys, ^(const void *key, const void *value) {
710 CFStringRef kpkid = asString(key, NULL);
711 CFDataRef keyData = asData(value, NULL);
712 if(kpkid && keyData && SOSKeyedPubKeyIdentifierIsPrefixed(kpkid)) {
713 CFStringRef idPrefix = SOSKeyedPubKeyIdentifierCopyPrefix(kpkid);
714 if(CFEqualSafe(idPrefix, prefix)) {
715 CFDictionaryAddValue(retval, kpkid, keyData);
717 CFReleaseNull(idPrefix);
723 static bool SOSBSKBHasPrefixedKey(SOSBackupSliceKeyBagRef bskb, CFStringRef prefix) {
724 CFDictionaryRef keyDict = SOSBSKBCopyAdditionalKeysWithPrefix(kCFAllocatorDefault, bskb, prefix);
725 bool haveKeys = keyDict && CFDictionaryGetCount(keyDict) > 0;
726 CFReleaseNull(keyDict);
730 CFDataRef SOSBSKBCopyRecoveryKey(SOSBackupSliceKeyBagRef bskb) {
731 if(!bskb) return NULL;
732 CFDictionaryRef keyDict = SOSBSKBCopyAdditionalKeysWithPrefix(kCFAllocatorDefault, bskb, bskbRkbgPrefix);
733 if(!keyDict) return NULL;
734 CFDataRef result = NULL;
735 if(CFDictionaryGetCount(keyDict) == 1) {
736 __block CFDataRef keyData = NULL;
737 CFDictionaryForEach(keyDict, ^(const void *key, const void *value) {
738 keyData = asData(value, NULL);
740 result = CFDataCreateCopy(kCFAllocatorDefault, keyData);
742 CFReleaseNull(keyDict);
746 bool SOSBSKBHasRecoveryKey(SOSBackupSliceKeyBagRef bskb) {
747 if(!bskb) return false;
748 if(SOSBSKBHasPrefixedKey(bskb, bskbRkbgPrefix)) {
751 // old way for RecoveryKeys
752 int keyCount = (bskb->wrapped_keys != NULL) ? (int) CFDictionaryGetCount(bskb->wrapped_keys): 0;
753 int peerCount = SOSBSKBCountPeers(bskb);
754 return !SOSBSKBIsDirect(bskb) && ((keyCount - peerCount) > 0);
757 bool SOSBSKBHasThisRecoveryKey(SOSBackupSliceKeyBagRef bskb, CFDataRef backupKey) {
759 CFStringRef id = SOSKeyedPubKeyIdentifierCreateWithData(bskbRkbgPrefix, backupKey);
760 bool result = (bskb && id && CFDictionaryContainsKey(bskb->wrapped_keys, id));
764 return CFDictionaryGetCount(bskb->wrapped_keys) == SOSBSKBCountPeers(bskb);