]> git.saurik.com Git - apple/security.git/blob - OSX/sec/SOSCircle/SecureObjectSync/SOSBackupSliceKeyBag.c
Security-57337.20.44.tar.gz
[apple/security.git] / OSX / sec / SOSCircle / SecureObjectSync / SOSBackupSliceKeyBag.c
1 /*
2 * Copyright (c) 2015 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24
25 // Our Header
26 #include <Security/SecureObjectSync/SOSBackupSliceKeyBag.h>
27
28
29 // Needed headers for implementation
30 #include "AssertMacros.h"
31 #include <utilities/SecCFWrappers.h>
32 #include <utilities/SecAKSWrappers.h>
33 #include <utilities/SecBuffer.h>
34 #include <utilities/SecCFError.h>
35 #include <utilities/der_set.h>
36 #include <utilities/der_plist_internal.h>
37 #include <Security/SecRandom.h>
38 #include <Security/SecureObjectSync/SOSPeerInfo.h>
39 #include <Security/SecureObjectSync/SOSPeerInfoCollections.h>
40 #include <Security/SecureObjectSync/SOSInternal.h>
41
42 #include <corecrypto/ccec.h>
43 #include <corecrypto/ccsha2.h>
44 #include <corecrypto/ccrng.h>
45
46 #include <limits.h>
47
48 #include "SOSInternal.h"
49
50 //
51 // MARK: Type creation
52 //
53
54 CFGiblisFor(SOSBackupSliceKeyBag);
55
56 const int kAKSBagSecretLength = 32;
57
58 struct __OpaqueSOSBackupSliceKeyBag {
59 CFRuntimeBase _base;
60
61 CFDataRef aks_bag;
62
63 CFSetRef peers;
64 CFDictionaryRef wrapped_keys;
65 };
66
67 static void SOSBackupSliceKeyBagDestroy(CFTypeRef aObj) {
68 SOSBackupSliceKeyBagRef vb = (SOSBackupSliceKeyBagRef) aObj;
69
70 CFReleaseNull(vb->aks_bag);
71 CFReleaseNull(vb->peers);
72 CFReleaseNull(vb->wrapped_keys);
73 }
74
75 static CFStringRef SOSBackupSliceKeyBagCopyFormatDescription(CFTypeRef aObj, CFDictionaryRef formatOptions) {
76 SOSBackupSliceKeyBagRef vb = (SOSBackupSliceKeyBagRef) aObj;
77
78 CFMutableStringRef description = CFStringCreateMutable(kCFAllocatorDefault, 0);
79
80 CFStringAppendFormat(description, NULL, CFSTR("<SOSBackupSliceKeyBag@%p %ld"), vb, vb->peers ? CFSetGetCount(vb->peers) : 0);
81 CFStringAppend(description, CFSTR(">"));
82
83 return description;
84 }
85
86
87 //
88 // MARK: Encode/Decode
89 //
90
91 const uint8_t* der_decode_BackupSliceKeyBag(CFAllocatorRef allocator,
92 SOSBackupSliceKeyBagRef* BackupSliceKeyBag, CFErrorRef *error,
93 const uint8_t* der, const uint8_t *der_end) {
94 if (der == NULL) return der;
95
96 const uint8_t *result = NULL;
97 SOSBackupSliceKeyBagRef vb = CFTypeAllocate(SOSBackupSliceKeyBag, struct __OpaqueSOSBackupSliceKeyBag, allocator);
98 require_quiet(SecAllocationError(vb, error, CFSTR("View bag allocation failed")), fail);
99
100 const uint8_t *sequence_end = NULL;
101 der = ccder_decode_sequence_tl(&sequence_end, der, der_end);
102 require_quiet(sequence_end == der_end, fail);
103
104 der = der_decode_data(kCFAllocatorDefault, kCFPropertyListImmutable, &vb->aks_bag, error, der, sequence_end);
105 vb->peers = SOSPeerInfoSetCreateFromArrayDER(kCFAllocatorDefault, &kSOSPeerSetCallbacks, error,
106 &der, der_end);
107 der = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListImmutable, &vb->wrapped_keys, error, der, sequence_end);
108
109 require_quiet(SecRequirementError(der == der_end, error, CFSTR("Extra space in sequence")), fail);
110
111 if (BackupSliceKeyBag)
112 CFTransferRetained(*BackupSliceKeyBag, vb);
113
114 result = der;
115
116 fail:
117 CFReleaseNull(vb);
118 return result;
119 }
120
121 size_t der_sizeof_BackupSliceKeyBag(SOSBackupSliceKeyBagRef BackupSliceKeyBag, CFErrorRef *error) {
122 size_t result = 0;
123
124 size_t bag_size = der_sizeof_data(BackupSliceKeyBag->aks_bag, error);
125 require_quiet(bag_size, fail);
126
127 size_t peers_size = SOSPeerInfoSetGetDEREncodedArraySize(BackupSliceKeyBag->peers, error);
128 require_quiet(peers_size, fail);
129
130 size_t wrapped_keys_size = der_sizeof_dictionary(BackupSliceKeyBag->wrapped_keys, error);
131 require_quiet(wrapped_keys_size, fail);
132
133 result = ccder_sizeof(CCDER_CONSTRUCTED_SEQUENCE, bag_size + peers_size + wrapped_keys_size);
134
135 fail:
136 return result;
137 }
138
139 uint8_t* der_encode_BackupSliceKeyBag(SOSBackupSliceKeyBagRef set, CFErrorRef *error,
140 const uint8_t *der, uint8_t *der_end) {
141 uint8_t *result = NULL;
142 if (der_end == NULL) return der_end;
143
144 require_quiet(SecRequirementError(set != NULL, error, CFSTR("Null set passed to encode")), fail);
145 require_quiet(set, fail); // This should be removed when SecRequirementError can squelch analyzer warnings
146
147 der_end = ccder_encode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, der_end, der,
148 der_encode_data(set->aks_bag, error, der,
149 SOSPeerInfoSetEncodeToArrayDER(set->peers, error, der,
150 der_encode_dictionary(set->wrapped_keys, error, der, der_end))));
151
152 require_quiet(der_end == der, fail);
153
154 result = der_end;
155 fail:
156 return result;
157 }
158
159
160 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagCreateFromData(CFAllocatorRef allocator, CFDataRef data, CFErrorRef *error) {
161 SOSBackupSliceKeyBagRef result = NULL;
162 SOSBackupSliceKeyBagRef decodedBag = NULL;
163
164 const uint8_t *der = CFDataGetBytePtr(data);
165 const uint8_t *der_end = der + CFDataGetLength(data);
166
167 der = der_decode_BackupSliceKeyBag(allocator, &decodedBag, error, der, der_end);
168
169 require_quiet(SecRequirementError(der == der_end, error, CFSTR("Didn't consume all data supplied")), fail);
170
171 CFTransferRetained(result, decodedBag);
172
173 fail:
174 CFReleaseNull(decodedBag);
175 return result;
176 }
177
178 //
179 // MARK: Construction
180 //
181
182 bool SOSBSKBIsGoodBackupPublic(CFDataRef publicKey, CFErrorRef *error) {
183 bool result = false;
184
185 ccec_pub_ctx_decl_cp(SOSGetBackupKeyCurveParameters(), pub_key);
186
187 int cc_result = ccec_compact_import_pub(SOSGetBackupKeyCurveParameters(), CFDataGetLength(publicKey), CFDataGetBytePtr(publicKey), pub_key);
188
189 require_action_quiet(cc_result == 0, exit, SOSErrorCreate(kSOSErrorDecodeFailure, error, NULL, CFSTR("Unable to decode public key: %@"), publicKey));
190
191 result = true;
192 exit:
193 return result;
194
195 }
196
197
198 static CFDataRef SOSCopyECWrapped(CFDataRef publicKey, CFDataRef secret, CFErrorRef *error) {
199 CFDataRef result = NULL;
200
201 ccec_pub_ctx_decl_cp(SOSGetBackupKeyCurveParameters(), pub_key);
202
203 int cc_result = ccec_compact_import_pub(SOSGetBackupKeyCurveParameters(), CFDataGetLength(publicKey), CFDataGetBytePtr(publicKey), pub_key);
204
205 require_action_quiet(cc_result == 0, exit, SOSErrorCreate(kSOSErrorDecodeFailure, error, NULL, CFSTR("Unable to decode public key: %@"), publicKey));
206
207 result = SOSCopyECWrappedData(pub_key, secret, error);
208
209 exit:
210 return result;
211 }
212
213
214 static CFDictionaryRef SOSBackupSliceKeyBagCopyWrappedKeys(SOSBackupSliceKeyBagRef vb, CFDataRef secret, CFErrorRef *error) {
215 CFDictionaryRef result = NULL;
216 CFMutableDictionaryRef wrappedKeys = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
217
218 __block bool success = true;
219 CFSetForEach(vb->peers, ^(const void *value) {
220 SOSPeerInfoRef pi = (SOSPeerInfoRef) value;
221 if (isSOSPeerInfo(pi)) {
222 CFStringRef id = SOSPeerInfoGetPeerID(pi);
223 CFDataRef backupKey = SOSPeerInfoCopyBackupKey(pi);
224
225 if (backupKey) {
226 CFDataRef wrappedKey = SOSCopyECWrapped(backupKey, secret, error);
227 if (wrappedKey) {
228 CFDictionaryAddValue(wrappedKeys, id, wrappedKey);
229 } else {
230 success = false;
231 }
232 CFReleaseNull(wrappedKey);
233 CFReleaseNull(backupKey);
234 }
235
236 }
237 });
238
239 if (success)
240 CFTransferRetained(result, wrappedKeys);
241
242 CFReleaseNull(wrappedKeys);
243 return result;
244 }
245
246 static bool SOSBackupSliceKeyBagCreateBackupBag(SOSBackupSliceKeyBagRef vb, CFErrorRef* error) {
247 CFReleaseNull(vb->aks_bag);
248
249 // Choose a random key.
250 PerformWithBufferAndClear(kAKSBagSecretLength, ^(size_t size, uint8_t *buffer) {
251 CFDataRef secret = NULL;
252
253 require_quiet(SecError(SecRandomCopyBytes(kSecRandomDefault, size, buffer), error, CFSTR("SecRandom falied!")), fail);
254
255 secret = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, buffer, size, kCFAllocatorNull);
256
257 CFAssignRetained(vb->wrapped_keys, SOSBackupSliceKeyBagCopyWrappedKeys(vb, secret, error));
258 CFAssignRetained(vb->aks_bag, SecAKSCopyBackupBagWithSecret(size, buffer, error));
259
260 fail:
261 CFReleaseSafe(secret);
262 });
263
264 return vb->aks_bag != NULL;
265 }
266
267
268 CFDataRef SOSBSKBCopyEncoded(SOSBackupSliceKeyBagRef BackupSliceKeyBag, CFErrorRef* error) {
269 CFDataRef result = NULL;
270 CFMutableDataRef encoded = NULL;
271
272 size_t encodedSize = der_sizeof_BackupSliceKeyBag(BackupSliceKeyBag, error);
273 require_quiet(encodedSize, fail);
274
275 encoded = CFDataCreateMutableWithScratch(kCFAllocatorDefault, encodedSize);
276 require_quiet(SecAllocationError(encoded, error, CFSTR("Faild to create scratch")), fail);
277
278 uint8_t *encode_to = CFDataGetMutableBytePtr(encoded);
279 uint8_t *encode_to_end = encode_to + CFDataGetLength(encoded);
280 require_quiet(encode_to == der_encode_BackupSliceKeyBag(BackupSliceKeyBag, error, encode_to, encode_to_end), fail);
281
282 CFTransferRetained(result, encoded);
283
284 fail:
285 CFReleaseSafe(encoded);
286 return result;
287 }
288
289 static CFSetRef SOSBackupSliceKeyBagCreatePeerSet(CFAllocatorRef allocator, CFSetRef peers) {
290 CFMutableSetRef result = CFSetCreateMutableForSOSPeerInfosByID(allocator);
291
292 CFSetForEach(peers, ^(const void *value) {
293 CFSetAddValue(result, value);
294 });
295
296 return result;
297 }
298
299 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagCreate(CFAllocatorRef allocator, CFSetRef peers, CFErrorRef* error) {
300 SOSBackupSliceKeyBagRef result = NULL;
301 SOSBackupSliceKeyBagRef vb = CFTypeAllocate(SOSBackupSliceKeyBag, struct __OpaqueSOSBackupSliceKeyBag, allocator);
302 require_quiet(SecAllocationError(vb, error, CFSTR("View bag allocation failed")), fail);
303
304 require_quiet(SecRequirementError(CFSetGetCount(peers) > 0, error, CFSTR("Need peers")), fail);
305
306 vb->peers = SOSBackupSliceKeyBagCreatePeerSet(allocator, peers);
307 vb->wrapped_keys = CFDictionaryCreateMutableForCFTypes(allocator);
308
309 require_quiet(SOSBackupSliceKeyBagCreateBackupBag(vb, error), fail);
310
311 CFTransferRetained(result, vb);
312
313 fail:
314 CFReleaseNull(vb);
315 return result;
316 }
317
318 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagCreateDirect(CFAllocatorRef allocator, CFDataRef aks_bag, CFErrorRef *error)
319 {
320 SOSBackupSliceKeyBagRef result = NULL;
321 SOSBackupSliceKeyBagRef vb = CFTypeAllocate(SOSBackupSliceKeyBag, struct __OpaqueSOSBackupSliceKeyBag, allocator);
322 require_quiet(SecAllocationError(vb, error, CFSTR("View bag allocation failed")), fail);
323
324 require_quiet(SecRequirementError(aks_bag, error, CFSTR("Need aks bag")), fail);
325
326 vb->aks_bag = CFRetainSafe(aks_bag);
327 vb->peers = CFSetCreateMutableForSOSPeerInfosByID(allocator);
328 vb->wrapped_keys = CFDictionaryCreateMutableForCFTypes(allocator);
329
330 CFTransferRetained(result, vb);
331
332 fail:
333 CFReleaseNull(vb);
334 return result;
335 }
336
337 //
338 // MARK: Use
339 //
340
341 bool SOSBSKBIsDirect(SOSBackupSliceKeyBagRef backupSliceKeyBag)
342 {
343 return 0 == CFSetGetCount(backupSliceKeyBag->peers);
344 }
345
346 CFDataRef SOSBSKBCopyAKSBag(SOSBackupSliceKeyBagRef backupSliceKeyBag, CFErrorRef* error)
347 {
348 return CFRetainSafe(backupSliceKeyBag->aks_bag);
349 }
350
351 CFSetRef SOSBSKBGetPeers(SOSBackupSliceKeyBagRef backupSliceKeyBag){
352 return backupSliceKeyBag->peers;
353 }
354
355 static keybag_handle_t SOSBSKBLoadAndUnlockBagWithSecret(SOSBackupSliceKeyBagRef backupSliceKeyBag,
356 size_t secretSize, const uint8_t *secret,
357 CFErrorRef *error)
358 {
359 #if !TARGET_HAS_KEYSTORE
360 return bad_keybag_handle;
361 #else
362 keybag_handle_t result = bad_keybag_handle;
363 keybag_handle_t bag_handle = bad_keybag_handle;
364
365 require_quiet(SecRequirementError(backupSliceKeyBag->aks_bag, error,
366 CFSTR("No aks bag to load")), exit);
367 require_quiet(SecRequirementError(CFDataGetLength(backupSliceKeyBag->aks_bag) < INT_MAX, error,
368 CFSTR("No aks bag to load")), exit);
369 require_quiet(SecRequirementError(secretSize <= INT_MAX, error,
370 CFSTR("secret too big")), exit);
371
372 kern_return_t aks_result;
373 aks_result = aks_load_bag(CFDataGetBytePtr(backupSliceKeyBag->aks_bag),
374 (int) CFDataGetLength(backupSliceKeyBag->aks_bag),
375 &bag_handle);
376 require_quiet(SecKernError(aks_result, error,
377 CFSTR("aks_load_bag failed: %d"), aks_result), exit);
378
379 aks_result = aks_unlock_bag(bag_handle, secret, (int) secretSize);
380 require_quiet(SecKernError(aks_result, error,
381 CFSTR("failed to unlock bag: %d"), aks_result), exit);
382
383 result = bag_handle;
384 bag_handle = bad_keybag_handle;
385
386 exit:
387 if (bag_handle != bad_keybag_handle) {
388 (void) aks_unload_bag(bag_handle);
389 }
390
391 return result;
392 #endif
393 }
394
395 keybag_handle_t SOSBSKBLoadAndUnlockWithPeerIDAndSecret(SOSBackupSliceKeyBagRef backupSliceKeyBag,
396 CFStringRef peerID, CFDataRef peerSecret,
397 CFErrorRef *error)
398 {
399 __block keybag_handle_t result = bad_keybag_handle;
400
401 CFDataRef lookedUpData = CFDictionaryGetValue(backupSliceKeyBag->wrapped_keys, peerID);
402 require_quiet(SecRequirementError(lookedUpData != NULL, error, CFSTR("%@ has no wrapped key in %@"), peerID, backupSliceKeyBag), exit);
403
404 require_quiet(SOSPerformWithDeviceBackupFullKey(SOSGetBackupKeyCurveParameters(), peerSecret, error, ^(ccec_full_ctx_t fullKey) {
405 SOSPerformWithUnwrappedData(fullKey, lookedUpData, error, ^(size_t size, uint8_t *buffer) {
406 result = SOSBSKBLoadAndUnlockBagWithSecret(backupSliceKeyBag, size, buffer, error);
407 });
408 }), exit);
409
410 exit:
411 return result;
412 }
413
414
415 keybag_handle_t SOSBSKBLoadAndUnlockWithPeerSecret(SOSBackupSliceKeyBagRef backupSliceKeyBag,
416 SOSPeerInfoRef peer, CFDataRef peerSecret,
417 CFErrorRef *error)
418 {
419 return SOSBSKBLoadAndUnlockWithPeerIDAndSecret(backupSliceKeyBag, SOSPeerInfoGetPeerID(peer), peerSecret, error);
420 }
421
422 keybag_handle_t SOSBSKBLoadAndUnlockWithDirectSecret(SOSBackupSliceKeyBagRef backupSliceKeyBag,
423 CFDataRef secret,
424 CFErrorRef *error)
425 {
426 keybag_handle_t result = bad_keybag_handle;
427 require_quiet(SecRequirementError(SOSBSKBIsDirect(backupSliceKeyBag), error, CFSTR("Not direct bag")), exit);
428
429 result = SOSBSKBLoadAndUnlockBagWithSecret(backupSliceKeyBag,
430 CFDataGetLength(secret),
431 CFDataGetBytePtr(secret),
432 error);
433
434 exit:
435 return result;
436 }