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 @implementation SOSAccount (Persistence)
53 static SOSAccount* SOSAccountCreateFromRemainingDER_v6(CFAllocatorRef allocator,
54 SOSDataSourceFactoryRef factory,
56 const uint8_t** der_p, const uint8_t *der_end)
58 SOSAccount* result = NULL;
59 SOSAccount* account = NULL;
61 CFArrayRef array = NULL;
62 CFDictionaryRef retiredPeers = NULL;
64 CFStringRef circle_name = factory->copy_name(factory);
67 CFDictionaryRef decoded_gestalt = NULL;
68 *der_p = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListImmutable, &decoded_gestalt, error,
74 account = SOSAccountCreate(allocator, decoded_gestalt, factory);
76 CFReleaseNull(decoded_gestalt);
78 SOSAccountTrustClassic *trust = account.trust;
80 *der_p = der_decode_array(kCFAllocatorDefault, 0, &array, error, *der_p, der_end);
82 uint64_t tmp_departure_code = kSOSNeverAppliedToCircle;
83 *der_p = ccder_decode_uint64(&tmp_departure_code, *der_p, der_end);
84 [trust setDepartureCode:(enum DepartureReason)tmp_departure_code];
86 bool userPublicTrusted;
87 *der_p = ccder_decode_bool(&userPublicTrusted, *der_p, der_end);
88 account.accountKeyIsTrusted = userPublicTrusted;
90 SecKeyRef userPublic = NULL;
91 SecKeyRef previousUserPublic = NULL;
92 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &userPublic, error, *der_p, der_end);
93 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &previousUserPublic, error, *der_p, der_end);
94 account.accountKey = userPublic;
95 account.previousAccountKey = previousUserPublic;
96 CFReleaseNull(userPublic);
97 CFReleaseNull(previousUserPublic);
100 CFDataRef parms = NULL;
101 *der_p = der_decode_data_or_null(kCFAllocatorDefault, &parms, error, *der_p, der_end);
102 [account setAccountKeyDerivationParamters:(__bridge_transfer NSData*) parms];
105 *der_p = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListMutableContainers, (CFDictionaryRef *) &retiredPeers, error, *der_p, der_end);
107 if(*der_p != der_end) {
113 CFMutableSetRef retirees = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
115 CFDictionaryForEach(retiredPeers, ^(const void *key, const void *value) {
117 SOSPeerInfoRef retiree = SOSPeerInfoCreateFromData(kCFAllocatorDefault, NULL, (CFDataRef) value);
119 CFSetAddValue(retirees, retiree);
121 CFReleaseNull(retiree);
125 [trust setRetirees:(__bridge NSMutableSet *)retirees];
126 CFReleaseNull(retirees);
129 if(!array || !*der_p)
132 CFArrayForEach(array, ^(const void *value) {
133 CFDataRef circleData = NULL;
134 CFDataRef fullPeerInfoData = NULL;
137 circleData = (CFDataRef) value;
138 } else if (isArray(value)) {
139 CFArrayRef pair = (CFArrayRef) value;
141 CFTypeRef circleObject = CFArrayGetValueAtIndex(pair, 0);
142 CFTypeRef fullPeerInfoObject = CFArrayGetValueAtIndex(pair, 1);
144 if (CFArrayGetCount(pair) == 2 && isData(circleObject) && isData(fullPeerInfoObject)) {
145 circleData = (CFDataRef) circleObject;
146 fullPeerInfoData = (CFDataRef) fullPeerInfoObject;
151 SOSCircleRef circle = SOSCircleCreateFromData(kCFAllocatorDefault, circleData, error);
152 require_quiet(circle && CFEqualSafe(circle_name, SOSCircleGetName(circle)), fail);
153 [trust setTrustedCircle:circle];
154 CFReleaseNull(circle);
156 if(fullPeerInfoData) {
157 SOSFullPeerInfoRef identity = SOSFullPeerInfoCreateFromData(kCFAllocatorDefault, fullPeerInfoData, NULL);
158 trust.fullPeerInfo = identity;
159 CFReleaseNull(identity);
163 CFReleaseNull(circle);
166 CFReleaseNull(array);
167 require_action_quiet([account ensureFactoryCircles], fail,
168 SOSCreateError(kSOSErrorBadFormat, CFSTR("Cannot EnsureFactoryCircles"), (error != NULL) ? *error : NULL, error));
176 static const uint8_t* der_decode_data_optional(CFAllocatorRef allocator, CFOptionFlags mutability,
177 CFDataRef* data, CFErrorRef *error,
178 const uint8_t* der, const uint8_t *der_end)
180 const uint8_t *dt_end = der_decode_data(allocator, mutability, data, NULL, der, der_end);
182 return dt_end ? dt_end : der;
185 static SOSAccount* SOSAccountCreateFromRemainingDER_v7(CFAllocatorRef allocator,
186 SOSDataSourceFactoryRef factory,
188 const uint8_t** der_p, const uint8_t *der_end)
190 SOSAccount* account = NULL;
191 SOSAccount* result = NULL;
194 CFDictionaryRef decoded_gestalt = NULL;
195 *der_p = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListImmutable, &decoded_gestalt, error,
201 account = SOSAccountCreate(kCFAllocatorDefault, decoded_gestalt, factory);
202 CFReleaseNull(decoded_gestalt);
205 enum DepartureReason departure_code = 0;
206 SOSAccountTrustClassic *trust = account.trust;
209 SOSCircleRef circle = SOSCircleCreateFromDER(kCFAllocatorDefault, error, der_p, der_end);
210 [trust setTrustedCircle:circle];
211 CFReleaseNull(circle);
215 SOSFullPeerInfoRef identity = NULL;
216 *der_p = der_decode_fullpeer_or_null(kCFAllocatorDefault, &identity, error, *der_p, der_end);
217 trust.fullPeerInfo = identity;
218 CFReleaseNull(identity);
221 uint64_t tmp_departure_code = kSOSNeverAppliedToCircle;
222 *der_p = ccder_decode_uint64(&tmp_departure_code, *der_p, der_end);
223 bool userPublicTrusted;
225 *der_p = ccder_decode_bool(&userPublicTrusted, *der_p, der_end);
226 account.accountKeyIsTrusted = userPublicTrusted;
229 SecKeyRef userPublic = NULL;
230 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &userPublic, error, *der_p, der_end);
231 account.accountKey = userPublic;
232 CFReleaseNull(userPublic);
236 SecKeyRef previousUserPublic = NULL;
237 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &previousUserPublic, error, *der_p, der_end);
238 account.previousAccountKey = previousUserPublic;
239 CFReleaseNull(previousUserPublic);
243 CFDataRef parms = NULL;
244 *der_p = der_decode_data_or_null(kCFAllocatorDefault, &parms, error, *der_p, der_end);
245 account.accountKeyDerivationParamters = (__bridge_transfer NSData*)parms;
249 CFSetRef retirees = SOSPeerInfoSetCreateFromArrayDER(kCFAllocatorDefault, &kSOSPeerSetCallbacks, error, der_p, der_end);
250 [trust setRetirees:(__bridge NSMutableSet *)retirees];
254 CFDataRef bKey = NULL;
255 *der_p = der_decode_data_optional(kCFAllocatorDefault, kCFPropertyListImmutable, &bKey, error, *der_p, der_end);
257 [account setBackup_key:(__bridge_transfer NSData *)bKey];
260 departure_code = (enum DepartureReason) tmp_departure_code;
262 [trust setDepartureCode:departure_code];
263 require_action_quiet(*der_p && *der_p == der_end, fail,
264 SOSCreateError(kSOSErrorBadFormat, CFSTR("Didn't consume all bytes v7"), (error != NULL) ? *error : NULL, error));
273 static SOSAccount* SOSAccountCreateFromRemainingDER_v8(CFAllocatorRef allocator,
274 SOSDataSourceFactoryRef factory,
276 const uint8_t** der_p, const uint8_t *der_end)
278 SOSAccount* account = NULL;
279 SOSAccount* result = NULL;
282 CFDictionaryRef decoded_gestalt = NULL;
283 *der_p = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListImmutable, &decoded_gestalt, error,
287 CFReleaseNull(decoded_gestalt);
291 account = SOSAccountCreate(kCFAllocatorDefault, decoded_gestalt, factory);
292 CFReleaseNull(decoded_gestalt);
295 SOSAccountTrustClassic *trust = account.trust;
298 SOSCircleRef circle = SOSCircleCreateFromDER(kCFAllocatorDefault, error, der_p, der_end);
299 [trust setTrustedCircle:circle];
300 CFReleaseNull(circle);
304 SOSFullPeerInfoRef identity = NULL;
305 *der_p = der_decode_fullpeer_or_null(kCFAllocatorDefault, &identity, error, *der_p, der_end);
306 trust.fullPeerInfo = identity;
307 CFReleaseNull(identity);
310 uint64_t tmp_departure_code = kSOSNeverAppliedToCircle;
311 *der_p = ccder_decode_uint64(&tmp_departure_code, *der_p, der_end);
312 [trust setDepartureCode:(enum DepartureReason) tmp_departure_code];
314 bool userPublicTrusted;
315 *der_p = ccder_decode_bool(&userPublicTrusted, *der_p, der_end);
316 account.accountKeyIsTrusted = userPublicTrusted;
319 SecKeyRef userPublic = NULL;
320 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &userPublic, error, *der_p, der_end);
321 account.accountKey = userPublic;
322 CFReleaseNull(userPublic);
326 SecKeyRef previousUserPublic = NULL;
327 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &previousUserPublic, error, *der_p, der_end);
328 account.previousAccountKey = previousUserPublic;
329 CFReleaseNull(previousUserPublic);
334 *der_p = der_decode_data_or_null(kCFAllocatorDefault, &parms, error, *der_p, der_end);
335 account.accountKeyDerivationParamters = (__bridge_transfer NSData*)parms;
340 CFMutableSetRef retirees = SOSPeerInfoSetCreateFromArrayDER(kCFAllocatorDefault, &kSOSPeerSetCallbacks, error, der_p, der_end);
341 [trust setRetirees:(__bridge NSMutableSet *)retirees];
342 CFReleaseNull(retirees);
345 CFDataRef bKey = NULL;
346 *der_p = der_decode_data_optional(kCFAllocatorDefault, kCFPropertyListImmutable, &bKey, error, *der_p, der_end);
348 CFDictionaryRef expansion = NULL;
349 *der_p = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListImmutable, &expansion, error,
354 CFReleaseNull(expansion);
359 [trust setExpansion:(__bridge NSMutableDictionary *)(expansion)];
361 CFReleaseNull(expansion);
364 [account setBackup_key:[[NSData alloc] initWithData:(__bridge NSData * _Nonnull)(bKey)]];
368 require_action_quiet(*der_p && *der_p == der_end, fail,
369 SOSCreateError(kSOSErrorBadFormat, CFSTR("Didn't consume all bytes v7"), (error != NULL) ? *error : NULL, error));
378 // Version History for Account
380 // 1-5 - InnsbruckTaos/Cab; Never supported even for upgrading.
381 // 6 - First version used in the field.
382 // 7 - One Circle version
383 // 8 - Adding expansion dictionary
386 #define CURRENT_ACCOUNT_PERSISTENT_VERSION 8
388 static SOSAccount* SOSAccountCreateFromDER(CFAllocatorRef allocator,
389 SOSDataSourceFactoryRef factory,
391 const uint8_t** der_p, const uint8_t *der_end)
393 SOSAccount* account = NULL;
394 uint64_t version = 0;
396 SOSFullPeerInfoRef identity = NULL;
398 const uint8_t *sequence_end;
399 *der_p = ccder_decode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, &sequence_end, *der_p, der_end);
400 *der_p = ccder_decode_uint64(&version, *der_p, sequence_end);
401 if (*der_p == NULL) {
402 SOSCreateError(kSOSErrorBadFormat, CFSTR("Version parsing failed"), (error != NULL) ? *error : NULL, error);
407 case CURRENT_ACCOUNT_PERSISTENT_VERSION:
408 account = SOSAccountCreateFromRemainingDER_v8(allocator, factory, error, der_p, sequence_end);
412 account = SOSAccountCreateFromRemainingDER_v7(allocator, factory, error, der_p, sequence_end);
416 account = SOSAccountCreateFromRemainingDER_v6(allocator, factory, error, der_p, sequence_end);
420 SOSCreateErrorWithFormat(kSOSErrorBadFormat, (error != NULL) ? *error : NULL, error,
421 NULL, CFSTR("Unsupported version (%llu)"), version);
426 // Error should have been filled in above.
430 if (*der_p != sequence_end) {
431 SOSCreateError(kSOSErrorBadFormat, CFSTR("Extra data at the end of saved acount"), (error != NULL) ? *error : NULL, error);
435 identity = account.fullPeerInfo;
436 /* I may not always have an identity, but when I do, it has a private key */
438 if(!(SOSFullPeerInfoPrivKeyExists(identity)))
440 SOSUnregisterTransportKeyParameter(account.key_transport);
441 SOSUnregisterTransportCircle((SOSCircleStorageTransport*)account.circle_transport);
442 SOSUnregisterTransportMessage(account.kvs_message_transport);
444 secnotice("account", "No private key associated with my_identity, resetting");
449 if (![account ensureFactoryCircles]) {
450 SOSCreateError(kSOSErrorBadFormat, CFSTR("Cannot EnsureFactoryCircles"), (error != NULL) ? *error : NULL, error);
454 SOSPeerInfoRef oldPI = CFRetainSafe(account.peerInfo);
456 SOSAccountCheckForAlwaysOnViews(account);
458 CFReleaseNull(oldPI);
460 SOSAccountEnsureRecoveryRing(account);
462 [account performTransaction:^(SOSAccountTransaction * _Nonnull txn) {
463 secnotice("circleop", "Setting account.key_interests_need_updating to true in SOSAccountCreateFromDER");
464 account.key_interests_need_updating = true;
467 SOSAccountEnsureUUID(account);
472 +(instancetype) accountFromDER: (const uint8_t**) der
473 end: (const uint8_t*) der_end
474 factory: (SOSDataSourceFactoryRef) factory
475 error: (NSError**) error {
476 CFErrorRef failure = NULL;
477 SOSAccount* result = SOSAccountCreateFromDER(kCFAllocatorDefault, factory, &failure, der, der_end);
481 *error = (__bridge_transfer NSError*) failure;
485 CFReleaseNull(failure);
490 +(instancetype) accountFromData: (NSData*) data
491 factory: (SOSDataSourceFactoryRef) factory
492 error: (NSError**) error {
493 size_t size = [data length];
494 const uint8_t *der = [data bytes];
495 return [self accountFromDER: &der end: der+size factory: factory error: error];
498 CFMutableSetRef SOSPeerInfoSetCreateFromArrayDER(CFAllocatorRef allocator, const CFSetCallBacks *callbacks, CFErrorRef* error,
499 const uint8_t** der_p, const uint8_t *der_end);
500 size_t SOSPeerInfoSetGetDEREncodedArraySize(CFSetRef pia, CFErrorRef *error);
501 uint8_t* SOSPeerInfoSetEncodeToArrayDER(CFSetRef pia, CFErrorRef* error, const uint8_t* der, uint8_t* der_end);
503 /************************/
506 - (NSData*) encodedData: (NSError* __autoreleasing *) error {
507 NSUInteger expected = [self.trust getDEREncodedSize: self err:error];
508 if (expected == 0) return nil;
510 return [NSMutableData dataWithSpace:expected
511 DEREncode:^uint8_t *(size_t size, uint8_t *buffer) {
512 return [self.trust encodeToDER:self