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 "SecCFAllocator.h"
54 CFStringRef bskbRkbgPrefix = CFSTR("RK");
56 CFDataRef SOSRKNullKey(void) {
57 static CFDataRef localNullKey = NULL;
58 static dispatch_once_t onceToken;
59 dispatch_once(&onceToken, ^{
60 localNullKey = CFDataCreate(kCFAllocatorDefault, (const UInt8*) "nullkey", 8);
66 // MARK: Type creation
69 CFGiblisFor(SOSBackupSliceKeyBag);
71 const int kAKSBagSecretLength = 32;
73 struct __OpaqueSOSBackupSliceKeyBag {
79 CFDictionaryRef wrapped_keys;
82 static void SOSBackupSliceKeyBagDestroy(CFTypeRef aObj) {
83 SOSBackupSliceKeyBagRef vb = (SOSBackupSliceKeyBagRef) aObj;
85 CFReleaseNull(vb->aks_bag);
86 CFReleaseNull(vb->peers);
87 CFReleaseNull(vb->wrapped_keys);
90 static CFSetRef SOSBackupSliceKeyBagCopyPeerNames(SOSBackupSliceKeyBagRef bksb) {
91 CFMutableSetRef retval = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
92 if(!retval) return NULL;
93 CFSetForEach(bksb->peers, ^(const void *value) {
94 SOSPeerInfoRef pi = (SOSPeerInfoRef) value;
95 CFSetAddValue(retval, SOSPeerInfoGetPeerName(pi));
100 static CFStringRef SOSBackupSliceKeyBagCopyFormatDescription(CFTypeRef aObj, CFDictionaryRef formatOptions) {
101 SOSBackupSliceKeyBagRef vb = (SOSBackupSliceKeyBagRef) aObj;
103 CFMutableStringRef retval = CFStringCreateMutable(kCFAllocatorDefault, 0);
105 CFSetRef peerIDs = SOSBackupSliceKeyBagCopyPeerNames(vb);
106 CFStringSetPerformWithDescription(peerIDs, ^(CFStringRef description) {
107 CFStringAppendFormat(retval, NULL, CFSTR("<SOSBackupSliceKeyBag@%p %ld %@"), vb, vb->peers ? CFSetGetCount(vb->peers) : 0, description);
109 CFReleaseNull(peerIDs);
110 CFStringAppend(retval, CFSTR(">"));
117 // MARK: Encode/Decode
120 const uint8_t* der_decode_BackupSliceKeyBag(CFAllocatorRef allocator,
121 SOSBackupSliceKeyBagRef* BackupSliceKeyBag, CFErrorRef *error,
122 const uint8_t* der, const uint8_t *der_end) {
123 if (der == NULL) return der;
125 const uint8_t *result = NULL;
126 SOSBackupSliceKeyBagRef vb = CFTypeAllocate(SOSBackupSliceKeyBag, struct __OpaqueSOSBackupSliceKeyBag, allocator);
127 require_quiet(SecAllocationError(vb, error, CFSTR("View bag allocation failed")), fail);
129 const uint8_t *sequence_end = NULL;
130 der = ccder_decode_sequence_tl(&sequence_end, der, der_end);
131 require_quiet(sequence_end == der_end, fail);
133 der = der_decode_data(kCFAllocatorDefault, &vb->aks_bag, error, der, sequence_end);
134 vb->peers = SOSPeerInfoSetCreateFromArrayDER(kCFAllocatorDefault, &kSOSPeerSetCallbacks, error,
136 der = der_decode_dictionary(kCFAllocatorDefault, &vb->wrapped_keys, error, der, sequence_end);
138 require_quiet(SecRequirementError(der == der_end, error, CFSTR("Extra space in sequence")), fail);
140 if (BackupSliceKeyBag)
141 CFTransferRetained(*BackupSliceKeyBag, vb);
150 size_t der_sizeof_BackupSliceKeyBag(SOSBackupSliceKeyBagRef BackupSliceKeyBag, CFErrorRef *error) {
153 require_quiet(SecRequirementError(BackupSliceKeyBag != NULL, error, CFSTR("Null BackupSliceKeyBag")), fail);
154 require_quiet(BackupSliceKeyBag != NULL, fail); // this is redundant with what happens in SecRequirementError, but the analyzer can't understand that.
155 require_quiet(SecRequirementError(BackupSliceKeyBag->aks_bag != NULL, error, CFSTR("null aks_bag in BackupSliceKeyBag")), fail);
156 require_quiet(BackupSliceKeyBag->aks_bag != NULL, fail); // this is redundant with what happens in SecRequirementError, but the analyzer can't understand that.
158 size_t bag_size = der_sizeof_data(BackupSliceKeyBag->aks_bag, error);
159 require_quiet(bag_size, fail);
161 size_t peers_size = SOSPeerInfoSetGetDEREncodedArraySize(BackupSliceKeyBag->peers, error);
162 require_quiet(peers_size, fail);
164 size_t wrapped_keys_size = der_sizeof_dictionary(BackupSliceKeyBag->wrapped_keys, error);
165 require_quiet(wrapped_keys_size, fail);
167 result = ccder_sizeof(CCDER_CONSTRUCTED_SEQUENCE, bag_size + peers_size + wrapped_keys_size);
173 uint8_t* der_encode_BackupSliceKeyBag(SOSBackupSliceKeyBagRef set, CFErrorRef *error,
174 const uint8_t *der, uint8_t *der_end) {
175 uint8_t *result = NULL;
176 if (der_end == NULL) return der_end;
178 require_quiet(SecRequirementError(set != NULL, error, CFSTR("Null set passed to encode")), fail);
179 require_quiet(set, fail); // Silence the NULL warning.
181 require_quiet(SecRequirementError(set->aks_bag != NULL, error, CFSTR("Null set passed to encode")), fail);
182 require_quiet(set->aks_bag, fail); // Silence the warning.
184 der_end = ccder_encode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, der_end, der,
185 der_encode_data(set->aks_bag, error, der,
186 SOSPeerInfoSetEncodeToArrayDER(set->peers, error, der,
187 der_encode_dictionary(set->wrapped_keys, error, der, der_end))));
189 require_quiet(der_end == der, fail);
198 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagCreateFromData(CFAllocatorRef allocator, CFDataRef data, CFErrorRef *error) {
199 SOSBackupSliceKeyBagRef result = NULL;
200 SOSBackupSliceKeyBagRef decodedBag = NULL;
202 const uint8_t *der = CFDataGetBytePtr(data);
203 const uint8_t *der_end = der + CFDataGetLength(data);
205 der = der_decode_BackupSliceKeyBag(allocator, &decodedBag, error, der, der_end);
207 require_quiet(SecRequirementError(der == der_end, error, CFSTR("Didn't consume all data supplied")), fail);
209 CFTransferRetained(result, decodedBag);
212 CFReleaseNull(decodedBag);
217 // MARK: Construction
220 bool SOSBSKBIsGoodBackupPublic(CFDataRef publicKey, CFErrorRef *error) {
223 ccec_pub_ctx_decl_cp(SOSGetBackupKeyCurveParameters(), pub_key);
225 int cc_result = ccec_compact_import_pub(SOSGetBackupKeyCurveParameters(), CFDataGetLength(publicKey), CFDataGetBytePtr(publicKey), pub_key);
227 require_action_quiet(cc_result == 0, exit, SOSErrorCreate(kSOSErrorDecodeFailure, error, NULL, CFSTR("Unable to decode public key: %@"), publicKey));
236 static CFDataRef SOSCopyECWrapped(CFDataRef publicKey, CFDataRef secret, CFErrorRef *error) {
237 CFDataRef result = NULL;
239 ccec_pub_ctx_decl_cp(SOSGetBackupKeyCurveParameters(), pub_key);
241 int cc_result = ccec_compact_import_pub(SOSGetBackupKeyCurveParameters(), CFDataGetLength(publicKey), CFDataGetBytePtr(publicKey), pub_key);
243 require_action_quiet(cc_result == 0, exit, SOSErrorCreate(kSOSErrorDecodeFailure, error, NULL, CFSTR("Unable to decode public key: %@"), publicKey));
245 result = SOSCopyECWrappedData(pub_key, secret, error);
252 static CFDictionaryRef SOSBackupSliceKeyBagCopyWrappedKeys(SOSBackupSliceKeyBagRef vb, CFDataRef secret, CFDictionaryRef additionalKeys, CFErrorRef *error) {
253 CFDictionaryRef result = NULL;
254 CFMutableDictionaryRef wrappedKeys = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
256 __block bool success = true;
257 CFSetForEach(vb->peers, ^(const void *value) {
258 SOSPeerInfoRef pi = (SOSPeerInfoRef) value;
259 if (isSOSPeerInfo(pi)) {
260 CFStringRef id = SOSPeerInfoGetPeerID(pi);
261 CFDataRef backupKey = SOSPeerInfoCopyBackupKey(pi);
264 CFErrorRef wrapError = NULL;
265 CFDataRef wrappedKey = SOSCopyECWrapped(backupKey, secret, &wrapError);
267 CFDictionaryAddValue(wrappedKeys, id, wrappedKey);
268 CFDataPerformWithHexString(backupKey, ^(CFStringRef backupKeyString) {
269 CFDataPerformWithHexString(wrappedKey, ^(CFStringRef wrappedKeyString) {
270 secnotice("bskb", "Add for id: %@, bk: %@, wrapped: %@", id, backupKeyString, wrappedKeyString);
274 CFDataPerformWithHexString(backupKey, ^(CFStringRef backupKeyString) {
275 secnotice("bskb", "Failed at id: %@, bk: %@ error: %@", id, backupKeyString, wrapError);
277 CFErrorPropagate(wrapError, error);
280 CFReleaseNull(wrappedKey);
281 CFReleaseNull(backupKey);
283 secnotice("bskb", "Skipping id %@, no backup key.", id);
289 CFDictionaryForEach(additionalKeys, ^(const void *key, const void *value) {
290 CFStringRef prefix = asString(key, NULL);
291 CFDataRef backupKey = asData(value, NULL);
293 CFDataRef wrappedKey = NULL;
294 CFErrorRef localError = NULL;
295 CFStringRef id = SOSKeyedPubKeyIdentifierCreateWithData(prefix, backupKey);
296 require_quiet(id, done);
298 wrappedKey = SOSCopyECWrapped(backupKey, secret, &localError);
299 require_quiet(wrappedKey, done);
301 CFDictionaryAddValue(wrappedKeys, id, wrappedKey);
305 CFDataPerformWithHexString(backupKey, ^(CFStringRef backupKeyString) {
306 CFDataPerformWithHexString(wrappedKey, ^(CFStringRef wrappedKeyString) {
307 secnotice("bskb", "Add for bk: %@, wrapped: %@", backupKeyString, wrappedKeyString);
311 CFDataPerformWithHexString(backupKey, ^(CFStringRef backupKeyString) {
312 secnotice("bskb", "Failed at bk: %@ error: %@", backupKeyString, localError);
314 CFErrorPropagate(localError, error);
317 CFReleaseNull(wrappedKey);
320 secnotice("bskb", "Skipping %@, not data.", value);
325 CFTransferRetained(result, wrappedKeys);
327 CFReleaseNull(wrappedKeys);
331 static bool SOSBackupSliceKeyBagCreateBackupBag(SOSBackupSliceKeyBagRef vb, CFDictionaryRef/*CFDataRef*/ additionalKeys, CFErrorRef* error) {
332 CFReleaseNull(vb->aks_bag);
334 // Choose a random key.
335 PerformWithBufferAndClear(kAKSBagSecretLength, ^(size_t size, uint8_t *buffer) {
336 CFDataRef secret = NULL;
338 require_quiet(SecError(SecRandomCopyBytes(kSecRandomDefault, size, buffer), error, CFSTR("SecRandom falied!")), fail);
340 secret = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, buffer, size, kCFAllocatorNull);
342 CFAssignRetained(vb->wrapped_keys, SOSBackupSliceKeyBagCopyWrappedKeys(vb, secret, additionalKeys, error));
343 CFAssignRetained(vb->aks_bag, SecAKSCopyBackupBagWithSecret(size, buffer, error));
346 CFReleaseSafe(secret);
349 return vb->aks_bag != NULL;
353 CFDataRef SOSBSKBCopyEncoded(SOSBackupSliceKeyBagRef BackupSliceKeyBag, CFErrorRef* error) {
354 CFDataRef result = NULL;
355 CFMutableDataRef encoded = NULL;
357 size_t encodedSize = der_sizeof_BackupSliceKeyBag(BackupSliceKeyBag, error);
358 require_quiet(encodedSize, fail);
360 encoded = CFDataCreateMutableWithScratch(kCFAllocatorDefault, encodedSize);
361 require_quiet(SecAllocationError(encoded, error, CFSTR("Faild to create scratch")), fail);
363 uint8_t *encode_to = CFDataGetMutableBytePtr(encoded);
364 uint8_t *encode_to_end = encode_to + CFDataGetLength(encoded);
365 require_quiet(encode_to == der_encode_BackupSliceKeyBag(BackupSliceKeyBag, error, encode_to, encode_to_end), fail);
367 CFTransferRetained(result, encoded);
370 CFReleaseSafe(encoded);
374 static CFSetRef SOSBackupSliceKeyBagCreatePeerSet(CFAllocatorRef allocator, CFSetRef peers) {
375 CFMutableSetRef result = CFSetCreateMutableForSOSPeerInfosByID(allocator);
377 CFSetForEach(peers, ^(const void *value) {
378 CFSetAddValue(result, value);
384 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagCreate(CFAllocatorRef allocator, CFSetRef peers, CFErrorRef* error) {
385 CFMutableDictionaryRef additionalKeys = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
387 SOSBackupSliceKeyBagRef result = SOSBackupSliceKeyBagCreateWithAdditionalKeys(allocator, peers, additionalKeys, NULL);
389 CFReleaseNull(additionalKeys);
394 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagCreateWithAdditionalKeys(CFAllocatorRef allocator,
395 CFSetRef /*SOSPeerInfoRef*/ peers,
396 CFDictionaryRef /*CFStringRef (prefix) CFDataRef (keydata) */ additionalKeys,
398 SOSBackupSliceKeyBagRef result = NULL;
399 SOSBackupSliceKeyBagRef vb = CFTypeAllocate(SOSBackupSliceKeyBag, struct __OpaqueSOSBackupSliceKeyBag, allocator);
400 require_quiet(SecAllocationError(vb, error, CFSTR("View bag allocation failed")), fail);
402 require_quiet(SecRequirementError(CFSetGetCount(peers) > 0, error, CFSTR("Need peers")), fail);
404 vb->peers = SOSBackupSliceKeyBagCreatePeerSet(allocator, peers);
405 vb->wrapped_keys = CFDictionaryCreateMutableForCFTypes(allocator);
407 require_quiet(SOSBackupSliceKeyBagCreateBackupBag(vb, additionalKeys, error), fail);
409 CFTransferRetained(result, vb);
417 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagCreateDirect(CFAllocatorRef allocator, CFDataRef aks_bag, CFErrorRef *error)
419 SOSBackupSliceKeyBagRef result = NULL;
420 SOSBackupSliceKeyBagRef vb = CFTypeAllocate(SOSBackupSliceKeyBag, struct __OpaqueSOSBackupSliceKeyBag, allocator);
421 require_quiet(SecAllocationError(vb, error, CFSTR("View bag allocation failed")), fail);
423 require_quiet(SecRequirementError(aks_bag, error, CFSTR("Need aks bag")), fail);
425 vb->aks_bag = CFRetainSafe(aks_bag);
426 vb->peers = CFSetCreateMutableForSOSPeerInfosByID(allocator);
427 vb->wrapped_keys = CFDictionaryCreateMutableForCFTypes(allocator);
429 CFTransferRetained(result, vb);
440 bool SOSBSKBIsDirect(SOSBackupSliceKeyBagRef backupSliceKeyBag)
442 return 0 == CFSetGetCount(backupSliceKeyBag->peers);
445 CFDataRef SOSBSKBCopyAKSBag(SOSBackupSliceKeyBagRef backupSliceKeyBag, CFErrorRef* error)
447 return CFRetainSafe(backupSliceKeyBag->aks_bag);
450 CFSetRef SOSBSKBGetPeers(SOSBackupSliceKeyBagRef backupSliceKeyBag){
451 return backupSliceKeyBag->peers;
454 int SOSBSKBCountPeers(SOSBackupSliceKeyBagRef backupSliceKeyBag) {
455 return (backupSliceKeyBag->peers) ? (int) CFSetGetCount(backupSliceKeyBag->peers): 0;
458 bool SOSBSKBPeerIsInKeyBag(SOSBackupSliceKeyBagRef backupSliceKeyBag, SOSPeerInfoRef pi) {
459 return CFSetGetValue(backupSliceKeyBag->peers, pi) != NULL;
464 bool SOSBKSBKeyIsInKeyBag(SOSBackupSliceKeyBagRef backupSliceKeyBag, CFDataRef publicKey) {
466 CFStringRef keyID = SOSCopyIDOfDataBuffer(publicKey, NULL);
467 require_quiet(keyID, done);
469 result = CFDictionaryContainsKey(backupSliceKeyBag->wrapped_keys, keyID);
472 CFReleaseSafe(keyID);
476 bool SOSBKSBPeerBackupKeyIsInKeyBag(SOSBackupSliceKeyBagRef backupSliceKeyBag, SOSPeerInfoRef pi) {
478 CFDataRef bskbBackupKey = NULL;
480 CFDataRef backupKey = SOSPeerInfoCopyBackupKey(pi);
481 SOSPeerInfoRef backupPI = asSOSPeerInfo(CFSetGetValue(backupSliceKeyBag->peers, pi));
483 bskbBackupKey = SOSPeerInfoCopyBackupKey(backupPI);
485 result = CFEqualSafe(backupKey, bskbBackupKey);
486 CFReleaseNull(bskbBackupKey);
487 CFReleaseNull(backupKey);
491 bool SOSBSKBAllPeersBackupKeysAreInKeyBag(SOSBackupSliceKeyBagRef backupSliceKeyBag, CFSetRef peers) {
492 // earlier we had to accept BSKBs listing peers without backup keys for compatibility. For that reason
493 // this routine will iterate over the peers given and only disqualify the BSKB if it doesn't include the backup key of a peer with one.
494 __block bool result = true;
495 if(backupSliceKeyBag && peers) {
496 CFSetForEach(peers, ^(const void *value) {
497 SOSPeerInfoRef pi = asSOSPeerInfo(value);
498 if(pi && SOSPeerInfoHasBackupKey(pi)) {
499 result &= SOSBKSBPeerBackupKeyIsInKeyBag(backupSliceKeyBag, pi);
506 bool SOSBKSBPrefixedKeyIsInKeyBag(SOSBackupSliceKeyBagRef backupSliceKeyBag, CFStringRef prefix, CFDataRef publicKey) {
508 CFStringRef kpkid = SOSKeyedPubKeyIdentifierCreateWithData(prefix, publicKey);
509 require_quiet(kpkid, done);
511 result = CFDictionaryContainsKey(backupSliceKeyBag->wrapped_keys, kpkid);
514 CFReleaseSafe(kpkid);
521 bskb_keybag_handle_t SOSBSKBLoadLocked(SOSBackupSliceKeyBagRef backupSliceKeyBag,
524 #if !TARGET_HAS_KEYSTORE
525 return bad_keybag_handle;
527 keybag_handle_t result = bad_keybag_handle;
528 keybag_handle_t bag_handle = bad_keybag_handle;
530 require_quiet(SecRequirementError(backupSliceKeyBag->aks_bag, error,
531 CFSTR("No aks bag to load")), exit);
532 require_quiet(SecRequirementError(CFDataGetLength(backupSliceKeyBag->aks_bag) < INT_MAX, error,
533 CFSTR("No aks bag to load")), exit);
535 kern_return_t aks_result;
536 aks_result = aks_load_bag(CFDataGetBytePtr(backupSliceKeyBag->aks_bag),
537 (int) CFDataGetLength(backupSliceKeyBag->aks_bag),
539 require_quiet(SecKernError(aks_result, error,
540 CFSTR("aks_load_bag failed: %d"), aks_result), exit);
543 bag_handle = bad_keybag_handle;
546 if (bag_handle != bad_keybag_handle) {
547 (void) aks_unload_bag(bag_handle);
555 static keybag_handle_t SOSBSKBLoadAndUnlockBagWithSecret(SOSBackupSliceKeyBagRef backupSliceKeyBag,
556 size_t secretSize, const uint8_t *secret,
559 #if !TARGET_HAS_KEYSTORE
560 return bad_keybag_handle;
562 keybag_handle_t result = bad_keybag_handle;
563 keybag_handle_t bag_handle = bad_keybag_handle;
565 require_quiet(SecRequirementError(backupSliceKeyBag->aks_bag, error,
566 CFSTR("No aks bag to load")), exit);
567 require_quiet(SecRequirementError(CFDataGetLength(backupSliceKeyBag->aks_bag) < INT_MAX, error,
568 CFSTR("No aks bag to load")), exit);
569 require_quiet(SecRequirementError(secretSize <= INT_MAX, error,
570 CFSTR("secret too big")), exit);
572 kern_return_t aks_result;
573 aks_result = aks_load_bag(CFDataGetBytePtr(backupSliceKeyBag->aks_bag),
574 (int) CFDataGetLength(backupSliceKeyBag->aks_bag),
576 require_quiet(SecKernError(aks_result, error,
577 CFSTR("aks_load_bag failed: %d"), aks_result), exit);
579 aks_result = aks_unlock_bag(bag_handle, secret, (int) secretSize);
580 require_quiet(SecKernError(aks_result, error,
581 CFSTR("failed to unlock bag: %d"), aks_result), exit);
584 bag_handle = bad_keybag_handle;
587 if (bag_handle != bad_keybag_handle) {
588 (void) aks_unload_bag(bag_handle);
595 keybag_handle_t SOSBSKBLoadAndUnlockWithPeerIDAndSecret(SOSBackupSliceKeyBagRef backupSliceKeyBag,
596 CFStringRef peerID, CFDataRef peerSecret,
599 __block keybag_handle_t result = bad_keybag_handle;
601 CFDataRef lookedUpData = CFDictionaryGetValue(backupSliceKeyBag->wrapped_keys, peerID);
602 require_quiet(SecRequirementError(lookedUpData != NULL, error, CFSTR("%@ has no wrapped key in %@"), peerID, backupSliceKeyBag), exit);
604 require_quiet(SOSPerformWithDeviceBackupFullKey(SOSGetBackupKeyCurveParameters(), peerSecret, error, ^(ccec_full_ctx_t fullKey) {
605 SOSPerformWithUnwrappedData(fullKey, lookedUpData, error, ^(size_t size, uint8_t *buffer) {
606 result = SOSBSKBLoadAndUnlockBagWithSecret(backupSliceKeyBag, size, buffer, error);
615 keybag_handle_t SOSBSKBLoadAndUnlockWithPeerSecret(SOSBackupSliceKeyBagRef backupSliceKeyBag,
616 SOSPeerInfoRef peer, CFDataRef peerSecret,
619 return SOSBSKBLoadAndUnlockWithPeerIDAndSecret(backupSliceKeyBag, SOSPeerInfoGetPeerID(peer), peerSecret, error);
622 keybag_handle_t SOSBSKBLoadAndUnlockWithDirectSecret(SOSBackupSliceKeyBagRef backupSliceKeyBag,
626 keybag_handle_t result = bad_keybag_handle;
627 require_quiet(SecRequirementError(SOSBSKBIsDirect(backupSliceKeyBag), error, CFSTR("Not direct bag")), exit);
629 result = SOSBSKBLoadAndUnlockBagWithSecret(backupSliceKeyBag,
630 CFDataGetLength(secret),
631 CFDataGetBytePtr(secret),
638 #include <Security/SecRecoveryKey.h>
640 static bool SOSPerformWithRecoveryKeyFullKey(CFDataRef wrappingSecret, CFErrorRef *error, void (^operation)(ccec_full_ctx_t fullKey, CFStringRef keyID)) {
643 CFStringRef keyID = NULL;
644 NSError *nserror = NULL;
645 SecRecoveryKey *sRecKey = NULL;
646 NSData* fullKeyBytes = NULL;
647 NSData* pubKeyBytes = NULL;
648 CFStringRef restoreKeySecret = CFStringCreateWithBytes(SecCFAllocatorZeroize(), CFDataGetBytePtr(wrappingSecret), CFDataGetLength(wrappingSecret), kCFStringEncodingUTF8, false);
649 require_action_quiet(restoreKeySecret, errOut, SOSErrorCreate(kSOSErrorDecodeFailure, error, NULL, CFSTR("Unable to create key string from data.")));
651 sRecKey = SecRKCreateRecoveryKeyWithError((__bridge NSString *)(restoreKeySecret), &nserror);
654 *error = (CFErrorRef)CFBridgingRetain(nserror);
658 require_action_quiet(sRecKey, errOut, SOSErrorCreate(kSOSErrorDecodeFailure, error, NULL, CFSTR("Unable to create recovery key from string.")));
660 fullKeyBytes = SecRKCopyBackupFullKey(sRecKey);
661 pubKeyBytes = SecRKCopyBackupPublicKey(sRecKey);
662 require_action_quiet(fullKeyBytes && pubKeyBytes, errOut, SOSErrorCreate(kSOSErrorDecodeFailure, error, NULL, CFSTR("Unable to get recovery key public and private keys.")));
663 keyID = SOSCopyIDOfDataBuffer(((__bridge CFDataRef) pubKeyBytes), error);
664 require_quiet(keyID, errOut);
666 size_t keysize = ccec_compact_import_priv_size(CFDataGetLength((__bridge CFDataRef)fullKeyBytes));
667 ccec_const_cp_t cp = ccec_curve_for_length_lookup(keysize, ccec_cp_256(), ccec_cp_384(), ccec_cp_521());
668 ccec_full_ctx_decl_cp(cp, fullKey);
669 int res = ccec_compact_import_priv(cp, CFDataGetLength((__bridge CFDataRef)fullKeyBytes), CFDataGetBytePtr((__bridge CFDataRef)fullKeyBytes), fullKey);
671 operation(fullKey, keyID);
673 ccec_full_ctx_clear_cp(cp, fullKey);
676 if(!result) SOSErrorCreate(kSOSErrorProcessingFailure, error, NULL, CFSTR("Unable to perform crypto operation from fullKeyBytes."));
679 CFReleaseNull(keyID);
680 CFReleaseNull(restoreKeySecret);
684 bskb_keybag_handle_t SOSBSKBLoadAndUnlockWithWrappingSecret(SOSBackupSliceKeyBagRef backupSliceKeyBag,
685 CFDataRef wrappingSecret,
687 __block keybag_handle_t result = bad_keybag_handle;
689 CFDataRef lookedUpData = SOSBSKBCopyRecoveryKey(backupSliceKeyBag);
690 require_quiet(SecRequirementError(lookedUpData != NULL, error, CFSTR("no recovery key found in %@"), backupSliceKeyBag), errOut);
692 SOSPerformWithRecoveryKeyFullKey(wrappingSecret, error, ^(ccec_full_ctx_t fullKey, CFStringRef keyID) {
693 SOSPerformWithUnwrappedData(fullKey, lookedUpData, error, ^(size_t size, uint8_t *buffer) {
694 result = SOSBSKBLoadAndUnlockBagWithSecret(backupSliceKeyBag, size, buffer, error);
699 CFReleaseSafe(lookedUpData);
703 // fixed for <rdar://problem/30918831> CrashTracer: secdtests at secdtests: SOSBSKBCopyAdditionalKeysWithPrefix
704 static CFDictionaryRef SOSBSKBCopyAdditionalKeysWithPrefix(CFAllocatorRef allocator, SOSBackupSliceKeyBagRef bskb, CFStringRef prefix) {
705 if(!bskb || !bskb->wrapped_keys) return NULL;
706 CFMutableDictionaryRef retval = CFDictionaryCreateMutableForCFTypes(allocator);
707 if(!retval) return NULL;
708 CFDictionaryForEach(bskb->wrapped_keys, ^(const void *key, const void *value) {
709 CFStringRef kpkid = asString(key, NULL);
710 CFDataRef keyData = asData(value, NULL);
711 if(kpkid && keyData && SOSKeyedPubKeyIdentifierIsPrefixed(kpkid)) {
712 CFStringRef idPrefix = SOSKeyedPubKeyIdentifierCopyPrefix(kpkid);
713 if(CFEqualSafe(idPrefix, prefix)) {
714 CFDictionaryAddValue(retval, kpkid, keyData);
716 CFReleaseNull(idPrefix);
722 static bool SOSBSKBHasPrefixedKey(SOSBackupSliceKeyBagRef bskb, CFStringRef prefix) {
723 CFDictionaryRef keyDict = SOSBSKBCopyAdditionalKeysWithPrefix(kCFAllocatorDefault, bskb, prefix);
724 bool haveKeys = keyDict && CFDictionaryGetCount(keyDict) > 0;
725 CFReleaseNull(keyDict);
729 CFDataRef SOSBSKBCopyRecoveryKey(SOSBackupSliceKeyBagRef bskb) {
730 if(!bskb) return NULL;
731 CFDictionaryRef keyDict = SOSBSKBCopyAdditionalKeysWithPrefix(kCFAllocatorDefault, bskb, bskbRkbgPrefix);
732 if(!keyDict) return NULL;
733 CFDataRef result = NULL;
734 if(CFDictionaryGetCount(keyDict) == 1) {
735 __block CFDataRef keyData = NULL;
736 CFDictionaryForEach(keyDict, ^(const void *key, const void *value) {
737 keyData = asData(value, NULL);
739 result = CFDataCreateCopy(kCFAllocatorDefault, keyData);
741 CFReleaseNull(keyDict);
745 bool SOSBSKBHasRecoveryKey(SOSBackupSliceKeyBagRef bskb) {
746 if(!bskb) return false;
747 if(SOSBSKBHasPrefixedKey(bskb, bskbRkbgPrefix)) {
750 // old way for RecoveryKeys
751 int keyCount = (bskb->wrapped_keys != NULL) ? (int) CFDictionaryGetCount(bskb->wrapped_keys): 0;
752 int peerCount = SOSBSKBCountPeers(bskb);
753 return !SOSBSKBIsDirect(bskb) && ((keyCount - peerCount) > 0);
756 bool SOSBSKBHasThisRecoveryKey(SOSBackupSliceKeyBagRef bskb, CFDataRef backupKey) {
758 CFStringRef id = SOSKeyedPubKeyIdentifierCreateWithData(bskbRkbgPrefix, backupKey);
759 bool result = (bskb && id && CFDictionaryContainsKey(bskb->wrapped_keys, id));
763 return CFDictionaryGetCount(bskb->wrapped_keys) == SOSBSKBCountPeers(bskb);