2 * Copyright (c) 2013-2014 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@
28 #include <AssertMacros.h>
31 #include <utilities/SecCFWrappers.h>
32 #include <utilities/SecNSAdditions.h>
34 #include <utilities/SecCoreCrypto.h>
35 #include <utilities/SecBuffer.h>
37 #include <Security/SecureObjectSync/SOSKVSKeys.h>
38 #include <SOSPeerInfoDER.h>
40 #include <Security/SecureObjectSync/SOSTransport.h>
42 #include <Security/SecureObjectSync/SOSPeerInfoCollections.h>
43 #include <os/state_private.h>
45 #import <Security/SecureObjectSync/SOSAccountPriv.h>
46 #import <Security/SecureObjectSync/SOSAccountTrust.h>
47 #import <Security/SecureObjectSync/SOSCircleDer.h>
48 #import "Security/SecureObjectSync/SOSAccountTrustClassic.h"
50 #define kSecServerPeerInfoAvailable "com.apple.security.fpiAvailable"
52 @implementation SOSAccount (Persistence)
55 static SOSAccount* SOSAccountCreateFromRemainingDER_v6(CFAllocatorRef allocator,
56 SOSDataSourceFactoryRef factory,
58 const uint8_t** der_p, const uint8_t *der_end)
60 SOSAccount* result = NULL;
61 SOSAccount* account = NULL;
63 CFArrayRef array = NULL;
64 CFDictionaryRef retiredPeers = NULL;
66 CFStringRef circle_name = factory->copy_name(factory);
69 CFDictionaryRef decoded_gestalt = NULL;
70 *der_p = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListImmutable, &decoded_gestalt, error,
76 account = SOSAccountCreate(allocator, decoded_gestalt, factory);
78 CFReleaseNull(decoded_gestalt);
80 SOSAccountTrustClassic *trust = account.trust;
82 *der_p = der_decode_array(kCFAllocatorDefault, 0, &array, error, *der_p, der_end);
84 uint64_t tmp_departure_code = kSOSNeverAppliedToCircle;
85 *der_p = ccder_decode_uint64(&tmp_departure_code, *der_p, der_end);
86 [trust setDepartureCode:(enum DepartureReason)tmp_departure_code];
88 bool userPublicTrusted;
89 *der_p = ccder_decode_bool(&userPublicTrusted, *der_p, der_end);
90 account.accountKeyIsTrusted = userPublicTrusted;
92 SecKeyRef userPublic = NULL;
93 SecKeyRef previousUserPublic = NULL;
94 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &userPublic, error, *der_p, der_end);
95 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &previousUserPublic, error, *der_p, der_end);
96 account.accountKey = userPublic;
97 account.previousAccountKey = previousUserPublic;
98 CFReleaseNull(userPublic);
99 CFReleaseNull(previousUserPublic);
102 CFDataRef parms = NULL;
103 *der_p = der_decode_data_or_null(kCFAllocatorDefault, &parms, error, *der_p, der_end);
104 [account setAccountKeyDerivationParamters:(__bridge_transfer NSData*) parms];
107 *der_p = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListMutableContainers, (CFDictionaryRef *) &retiredPeers, error, *der_p, der_end);
109 if(*der_p != der_end) {
115 CFMutableSetRef retirees = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
117 CFDictionaryForEach(retiredPeers, ^(const void *key, const void *value) {
119 SOSPeerInfoRef retiree = SOSPeerInfoCreateFromData(kCFAllocatorDefault, NULL, (CFDataRef) value);
121 CFSetAddValue(retirees, retiree);
123 CFReleaseNull(retiree);
127 [trust setRetirees:(__bridge NSMutableSet *)retirees];
128 CFReleaseNull(retirees);
131 if(!array || !*der_p)
134 CFArrayForEach(array, ^(const void *value) {
135 CFDataRef circleData = NULL;
136 CFDataRef fullPeerInfoData = NULL;
139 circleData = (CFDataRef) value;
140 } else if (isArray(value)) {
141 CFArrayRef pair = (CFArrayRef) value;
143 CFTypeRef circleObject = CFArrayGetValueAtIndex(pair, 0);
144 CFTypeRef fullPeerInfoObject = CFArrayGetValueAtIndex(pair, 1);
146 if (CFArrayGetCount(pair) == 2 && isData(circleObject) && isData(fullPeerInfoObject)) {
147 circleData = (CFDataRef) circleObject;
148 fullPeerInfoData = (CFDataRef) fullPeerInfoObject;
153 SOSCircleRef circle = SOSCircleCreateFromData(kCFAllocatorDefault, circleData, error);
154 require_quiet(circle && CFEqualSafe(circle_name, SOSCircleGetName(circle)), fail);
155 [trust setTrustedCircle:circle];
156 CFReleaseNull(circle);
158 if(fullPeerInfoData) {
159 SOSFullPeerInfoRef identity = SOSFullPeerInfoCreateFromData(kCFAllocatorDefault, fullPeerInfoData, NULL);
160 trust.fullPeerInfo = identity;
161 CFReleaseNull(identity);
165 CFReleaseNull(circle);
168 CFReleaseNull(array);
169 require_action_quiet([account ensureFactoryCircles], fail,
170 SOSCreateError(kSOSErrorBadFormat, CFSTR("Cannot EnsureFactoryCircles"), (error != NULL) ? *error : NULL, error));
178 static const uint8_t* der_decode_data_optional(CFAllocatorRef allocator, CFOptionFlags mutability,
179 CFDataRef* data, CFErrorRef *error,
180 const uint8_t* der, const uint8_t *der_end)
182 const uint8_t *dt_end = der_decode_data(allocator, mutability, data, NULL, der, der_end);
184 return dt_end ? dt_end : der;
187 static SOSAccount* SOSAccountCreateFromRemainingDER_v7(CFAllocatorRef allocator,
188 SOSDataSourceFactoryRef factory,
190 const uint8_t** der_p, const uint8_t *der_end)
192 SOSAccount* account = NULL;
193 SOSAccount* result = NULL;
196 CFDictionaryRef decoded_gestalt = NULL;
197 *der_p = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListImmutable, &decoded_gestalt, error,
203 account = SOSAccountCreate(kCFAllocatorDefault, decoded_gestalt, factory);
204 CFReleaseNull(decoded_gestalt);
207 enum DepartureReason departure_code = 0;
208 SOSAccountTrustClassic *trust = account.trust;
211 SOSCircleRef circle = SOSCircleCreateFromDER(kCFAllocatorDefault, error, der_p, der_end);
212 [trust setTrustedCircle:circle];
213 CFReleaseNull(circle);
217 SOSFullPeerInfoRef identity = NULL;
218 *der_p = der_decode_fullpeer_or_null(kCFAllocatorDefault, &identity, error, *der_p, der_end);
219 trust.fullPeerInfo = identity;
220 CFReleaseNull(identity);
223 uint64_t tmp_departure_code = kSOSNeverAppliedToCircle;
224 *der_p = ccder_decode_uint64(&tmp_departure_code, *der_p, der_end);
225 bool userPublicTrusted;
227 *der_p = ccder_decode_bool(&userPublicTrusted, *der_p, der_end);
228 account.accountKeyIsTrusted = userPublicTrusted;
231 SecKeyRef userPublic = NULL;
232 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &userPublic, error, *der_p, der_end);
233 account.accountKey = userPublic;
234 CFReleaseNull(userPublic);
238 SecKeyRef previousUserPublic = NULL;
239 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &previousUserPublic, error, *der_p, der_end);
240 account.previousAccountKey = previousUserPublic;
241 CFReleaseNull(previousUserPublic);
245 CFDataRef parms = NULL;
246 *der_p = der_decode_data_or_null(kCFAllocatorDefault, &parms, error, *der_p, der_end);
247 account.accountKeyDerivationParamters = (__bridge_transfer NSData*)parms;
251 CFSetRef retirees = SOSPeerInfoSetCreateFromArrayDER(kCFAllocatorDefault, &kSOSPeerSetCallbacks, error, der_p, der_end);
252 [trust setRetirees:(__bridge NSMutableSet *)retirees];
256 CFDataRef bKey = NULL;
257 *der_p = der_decode_data_optional(kCFAllocatorDefault, kCFPropertyListImmutable, &bKey, error, *der_p, der_end);
259 [account setBackup_key:(__bridge_transfer NSData *)bKey];
262 departure_code = (enum DepartureReason) tmp_departure_code;
264 [trust setDepartureCode:departure_code];
265 require_action_quiet(*der_p && *der_p == der_end, fail,
266 SOSCreateError(kSOSErrorBadFormat, CFSTR("Didn't consume all bytes v7"), (error != NULL) ? *error : NULL, error));
275 static SOSAccount* SOSAccountCreateFromRemainingDER_v8(CFAllocatorRef allocator,
276 SOSDataSourceFactoryRef factory,
278 const uint8_t** der_p, const uint8_t *der_end)
280 SOSAccount* account = NULL;
281 SOSAccount* result = NULL;
284 CFDictionaryRef decoded_gestalt = NULL;
285 *der_p = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListImmutable, &decoded_gestalt, error,
289 CFReleaseNull(decoded_gestalt);
293 account = SOSAccountCreate(kCFAllocatorDefault, decoded_gestalt, factory);
294 CFReleaseNull(decoded_gestalt);
297 SOSAccountTrustClassic *trust = account.trust;
300 SOSCircleRef circle = SOSCircleCreateFromDER(kCFAllocatorDefault, error, der_p, der_end);
301 [trust setTrustedCircle:circle];
302 CFReleaseNull(circle);
306 SOSFullPeerInfoRef identity = NULL;
307 *der_p = der_decode_fullpeer_or_null(kCFAllocatorDefault, &identity, error, *der_p, der_end);
308 trust.fullPeerInfo = identity;
309 CFReleaseNull(identity);
312 uint64_t tmp_departure_code = kSOSNeverAppliedToCircle;
313 *der_p = ccder_decode_uint64(&tmp_departure_code, *der_p, der_end);
314 [trust setDepartureCode:(enum DepartureReason) tmp_departure_code];
316 bool userPublicTrusted;
317 *der_p = ccder_decode_bool(&userPublicTrusted, *der_p, der_end);
318 account.accountKeyIsTrusted = userPublicTrusted;
321 SecKeyRef userPublic = NULL;
322 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &userPublic, error, *der_p, der_end);
323 account.accountKey = userPublic;
324 CFReleaseNull(userPublic);
328 SecKeyRef previousUserPublic = NULL;
329 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &previousUserPublic, error, *der_p, der_end);
330 account.previousAccountKey = previousUserPublic;
331 CFReleaseNull(previousUserPublic);
336 *der_p = der_decode_data_or_null(kCFAllocatorDefault, &parms, error, *der_p, der_end);
337 account.accountKeyDerivationParamters = (__bridge_transfer NSData*)parms;
342 CFMutableSetRef retirees = SOSPeerInfoSetCreateFromArrayDER(kCFAllocatorDefault, &kSOSPeerSetCallbacks, error, der_p, der_end);
343 [trust setRetirees:(__bridge NSMutableSet *)retirees];
344 CFReleaseNull(retirees);
347 CFDataRef bKey = NULL;
348 *der_p = der_decode_data_optional(kCFAllocatorDefault, kCFPropertyListImmutable, &bKey, error, *der_p, der_end);
350 CFDictionaryRef expansion = NULL;
351 *der_p = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListImmutable, &expansion, error,
355 CFReleaseNull(expansion);
360 [trust setExpansion:(__bridge NSMutableDictionary *)(expansion)];
362 CFReleaseNull(expansion);
365 [account setBackup_key:[[NSData alloc] initWithData:(__bridge NSData * _Nonnull)(bKey)]];
367 require_action_quiet(*der_p && *der_p == der_end, fail,
368 SOSCreateError(kSOSErrorBadFormat, CFSTR("Didn't consume all bytes v7"), (error != NULL) ? *error : NULL, error));
377 // Version History for Account
379 // 1-5 - InnsbruckTaos/Cab; Never supported even for upgrading.
380 // 6 - First version used in the field.
381 // 7 - One Circle version
382 // 8 - Adding expansion dictionary
385 #define CURRENT_ACCOUNT_PERSISTENT_VERSION 8
387 static SOSAccount* SOSAccountCreateFromDER(CFAllocatorRef allocator,
388 SOSDataSourceFactoryRef factory,
390 const uint8_t** der_p, const uint8_t *der_end)
392 SOSAccount* account = NULL;
393 uint64_t version = 0;
395 SOSFullPeerInfoRef identity = NULL;
397 const uint8_t *sequence_end;
398 *der_p = ccder_decode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, &sequence_end, *der_p, der_end);
399 *der_p = ccder_decode_uint64(&version, *der_p, sequence_end);
400 if (*der_p == NULL) {
401 SOSCreateError(kSOSErrorBadFormat, CFSTR("Version parsing failed"), (error != NULL) ? *error : NULL, error);
406 case CURRENT_ACCOUNT_PERSISTENT_VERSION:
407 account = SOSAccountCreateFromRemainingDER_v8(allocator, factory, error, der_p, sequence_end);
411 account = SOSAccountCreateFromRemainingDER_v7(allocator, factory, error, der_p, sequence_end);
415 account = SOSAccountCreateFromRemainingDER_v6(allocator, factory, error, der_p, sequence_end);
419 SOSCreateErrorWithFormat(kSOSErrorBadFormat, (error != NULL) ? *error : NULL, error,
420 NULL, CFSTR("Unsupported version (%llu)"), version);
425 // Error should have been filled in above.
429 if (*der_p != sequence_end) {
430 SOSCreateError(kSOSErrorBadFormat, CFSTR("Extra data at the end of saved acount"), (error != NULL) ? *error : NULL, error);
434 identity = account.fullPeerInfo;
435 /* I may not always have an identity, but when I do, it has a private key */
437 if(!(SOSFullPeerInfoPrivKeyExists(identity)))
439 SOSUnregisterTransportKeyParameter(account.key_transport);
440 SOSUnregisterTransportCircle((SOSCircleStorageTransport*)account.circle_transport);
441 SOSUnregisterTransportMessage((SOSMessage*)account.ids_message_transport);
442 SOSUnregisterTransportMessage(account.kvs_message_transport);
444 secnotice("account", "No private key associated with my_identity, resetting");
447 notify_post(kSecServerPeerInfoAvailable);
448 if(account.deviceID && [account.deviceID length] != 0){
449 SOSFullPeerInfoUpdateDeviceID(identity, (__bridge CFStringRef)(account.deviceID), error);
450 account.trust.fullPeerInfo = identity;
454 if (![account ensureFactoryCircles]) {
455 SOSCreateError(kSOSErrorBadFormat, CFSTR("Cannot EnsureFactoryCircles"), (error != NULL) ? *error : NULL, error);
459 SOSPeerInfoRef oldPI = CFRetainSafe(account.peerInfo);
461 SOSAccountCheckForAlwaysOnViews(account);
462 // if UpdateFullPeerInfo did something - we need to make sure we have the right Ref
463 SOSPeerInfoRef myPI = account.peerInfo;
464 CFStringRef transportTypeInflatedFromDER = SOSPeerInfoCopyTransportType(myPI);
465 if (CFStringCompare(transportTypeInflatedFromDER, CFSTR("IDS"), 0) == 0 || CFStringCompare(transportTypeInflatedFromDER, CFSTR("KVS"), 0) == 0)
466 SOSFullPeerInfoUpdateTransportType(identity, SOSTransportMessageTypeIDSV2, NULL); //update the transport type to the current IDS V2 type
468 CFReleaseNull(transportTypeInflatedFromDER);
470 CFReleaseNull(oldPI);
472 SOSAccountEnsureRecoveryRing(account);
474 [account performTransaction:^(SOSAccountTransaction * _Nonnull txn) {
475 account.key_interests_need_updating = true;
478 SOSAccountEnsureUUID(account);
483 +(instancetype) accountFromDER: (const uint8_t**) der
484 end: (const uint8_t*) der_end
485 factory: (SOSDataSourceFactoryRef) factory
486 error: (NSError**) error {
487 CFErrorRef failure = NULL;
488 SOSAccount* result = SOSAccountCreateFromDER(kCFAllocatorDefault, factory, &failure, der, der_end);
492 *error = (__bridge_transfer NSError*) failure;
496 CFReleaseNull(failure);
501 +(instancetype) accountFromData: (NSData*) data
502 factory: (SOSDataSourceFactoryRef) factory
503 error: (NSError**) error {
504 size_t size = [data length];
505 const uint8_t *der = [data bytes];
506 return [self accountFromDER: &der end: der+size factory: factory error: error];
509 CFMutableSetRef SOSPeerInfoSetCreateFromArrayDER(CFAllocatorRef allocator, const CFSetCallBacks *callbacks, CFErrorRef* error,
510 const uint8_t** der_p, const uint8_t *der_end);
511 size_t SOSPeerInfoSetGetDEREncodedArraySize(CFSetRef pia, CFErrorRef *error);
512 uint8_t* SOSPeerInfoSetEncodeToArrayDER(CFSetRef pia, CFErrorRef* error, const uint8_t* der, uint8_t* der_end);
514 /************************/
517 - (NSData*) encodedData: (NSError* __autoreleasing *) error {
518 NSUInteger expected = [self.trust getDEREncodedSize: self err:error];
519 if (expected == 0) return nil;
521 return [NSMutableData dataWithSpace:expected
522 DEREncode:^uint8_t *(size_t size, uint8_t *buffer) {
523 return [self.trust encodeToDER:self