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@
27 #include <AssertMacros.h>
30 #include <utilities/SecCFWrappers.h>
31 #include <utilities/SecNSAdditions.h>
33 #include <utilities/SecCoreCrypto.h>
34 #include <utilities/SecBuffer.h>
36 #include "keychain/SecureObjectSync/SOSKVSKeys.h"
37 #include "keychain/SecureObjectSync/SOSPeerInfoDER.h"
39 #include "keychain/SecureObjectSync/SOSTransport.h"
41 #include "keychain/SecureObjectSync/SOSPeerInfoCollections.h"
42 #include <os/state_private.h>
44 #include "keychain/SecureObjectSync/SOSAccountPriv.h"
45 #import "keychain/SecureObjectSync/SOSAccountTrust.h"
46 #import "keychain/SecureObjectSync/SOSCircleDer.h"
47 #import "keychain/SecureObjectSync/SOSAccountTrustClassic.h"
49 @implementation SOSAccount (Persistence)
52 static SOSAccount* SOSAccountCreateFromRemainingDER_v6(CFAllocatorRef allocator,
53 SOSDataSourceFactoryRef factory,
55 const uint8_t** der_p, const uint8_t *der_end)
57 SOSAccount* result = NULL;
58 SOSAccount* account = NULL;
60 CFArrayRef array = NULL;
61 CFDictionaryRef retiredPeers = NULL;
63 CFStringRef circle_name = factory->copy_name(factory);
66 CFDictionaryRef decoded_gestalt = NULL;
67 *der_p = der_decode_dictionary(kCFAllocatorDefault, &decoded_gestalt, error,
73 account = SOSAccountCreate(allocator, decoded_gestalt, factory);
75 CFReleaseNull(decoded_gestalt);
77 SOSAccountTrustClassic *trust = account.trust;
79 *der_p = der_decode_array(kCFAllocatorDefault, &array, error, *der_p, der_end);
81 uint64_t tmp_departure_code = kSOSNeverAppliedToCircle;
82 *der_p = ccder_decode_uint64(&tmp_departure_code, *der_p, der_end);
83 [trust setDepartureCode:(enum DepartureReason)tmp_departure_code];
85 bool userPublicTrusted;
86 *der_p = ccder_decode_bool(&userPublicTrusted, *der_p, der_end);
87 account.accountKeyIsTrusted = userPublicTrusted;
89 SecKeyRef userPublic = NULL;
90 SecKeyRef previousUserPublic = NULL;
91 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &userPublic, error, *der_p, der_end);
92 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &previousUserPublic, error, *der_p, der_end);
93 account.accountKey = userPublic;
94 account.previousAccountKey = previousUserPublic;
95 CFReleaseNull(userPublic);
96 CFReleaseNull(previousUserPublic);
99 CFDataRef parms = NULL;
100 *der_p = der_decode_data_or_null(kCFAllocatorDefault, &parms, error, *der_p, der_end);
101 [account setAccountKeyDerivationParameters:(__bridge_transfer NSData*) parms];
104 *der_p = der_decode_dictionary(kCFAllocatorDefault, (CFDictionaryRef *) &retiredPeers, error, *der_p, der_end);
106 if(*der_p != der_end) {
112 CFMutableSetRef retirees = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
114 CFDictionaryForEach(retiredPeers, ^(const void *key, const void *value) {
116 SOSPeerInfoRef retiree = SOSPeerInfoCreateFromData(kCFAllocatorDefault, NULL, (CFDataRef) value);
118 CFSetAddValue(retirees, retiree);
120 CFReleaseNull(retiree);
124 [trust setRetirees:(__bridge NSMutableSet *)retirees];
125 CFReleaseNull(retirees);
128 if(!array || !*der_p)
131 CFArrayForEach(array, ^(const void *value) {
132 CFDataRef circleData = NULL;
133 CFDataRef fullPeerInfoData = NULL;
136 circleData = (CFDataRef) value;
137 } else if (isArray(value)) {
138 CFArrayRef pair = (CFArrayRef) value;
140 CFTypeRef circleObject = CFArrayGetValueAtIndex(pair, 0);
141 CFTypeRef fullPeerInfoObject = CFArrayGetValueAtIndex(pair, 1);
143 if (CFArrayGetCount(pair) == 2 && isData(circleObject) && isData(fullPeerInfoObject)) {
144 circleData = (CFDataRef) circleObject;
145 fullPeerInfoData = (CFDataRef) fullPeerInfoObject;
150 SOSCircleRef circle = SOSCircleCreateFromData(kCFAllocatorDefault, circleData, error);
151 require_quiet(circle && CFEqualSafe(circle_name, SOSCircleGetName(circle)), fail);
152 [trust setTrustedCircle:circle];
153 CFReleaseNull(circle);
155 if(fullPeerInfoData) {
156 SOSFullPeerInfoRef identity = SOSFullPeerInfoCreateFromData(kCFAllocatorDefault, fullPeerInfoData, NULL);
157 trust.fullPeerInfo = identity;
158 CFReleaseNull(identity);
162 CFReleaseNull(circle);
165 CFReleaseNull(array);
166 require_action_quiet([account ensureFactoryCircles], fail,
167 SOSCreateError(kSOSErrorBadFormat, CFSTR("Cannot EnsureFactoryCircles"), (error != NULL) ? *error : NULL, error));
175 static const uint8_t* der_decode_data_optional(CFAllocatorRef allocator,
176 CFDataRef* data, CFErrorRef *error,
177 const uint8_t* der, const uint8_t *der_end)
179 const uint8_t *dt_end = der_decode_data(allocator, data, NULL, der, der_end);
181 return dt_end ? dt_end : der;
184 static SOSAccount* SOSAccountCreateFromRemainingDER_v7(CFAllocatorRef allocator,
185 SOSDataSourceFactoryRef factory,
187 const uint8_t** der_p, const uint8_t *der_end)
189 SOSAccount* account = NULL;
190 SOSAccount* result = NULL;
193 CFDictionaryRef decoded_gestalt = NULL;
194 *der_p = der_decode_dictionary(kCFAllocatorDefault, &decoded_gestalt, error,
200 account = SOSAccountCreate(kCFAllocatorDefault, decoded_gestalt, factory);
201 CFReleaseNull(decoded_gestalt);
204 enum DepartureReason departure_code = 0;
205 SOSAccountTrustClassic *trust = account.trust;
208 SOSCircleRef circle = SOSCircleCreateFromDER(kCFAllocatorDefault, error, der_p, der_end);
209 [trust setTrustedCircle:circle];
210 CFReleaseNull(circle);
214 SOSFullPeerInfoRef identity = NULL;
215 *der_p = der_decode_fullpeer_or_null(kCFAllocatorDefault, &identity, error, *der_p, der_end);
216 trust.fullPeerInfo = identity;
217 CFReleaseNull(identity);
220 uint64_t tmp_departure_code = kSOSNeverAppliedToCircle;
221 *der_p = ccder_decode_uint64(&tmp_departure_code, *der_p, der_end);
222 bool userPublicTrusted;
224 *der_p = ccder_decode_bool(&userPublicTrusted, *der_p, der_end);
225 account.accountKeyIsTrusted = userPublicTrusted;
228 SecKeyRef userPublic = NULL;
229 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &userPublic, error, *der_p, der_end);
230 account.accountKey = userPublic;
231 CFReleaseNull(userPublic);
235 SecKeyRef previousUserPublic = NULL;
236 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &previousUserPublic, error, *der_p, der_end);
237 account.previousAccountKey = previousUserPublic;
238 CFReleaseNull(previousUserPublic);
242 CFDataRef parms = NULL;
243 *der_p = der_decode_data_or_null(kCFAllocatorDefault, &parms, error, *der_p, der_end);
244 account.accountKeyDerivationParameters = (__bridge_transfer NSData*)parms;
248 CFSetRef retirees = SOSPeerInfoSetCreateFromArrayDER(kCFAllocatorDefault, &kSOSPeerSetCallbacks, error, der_p, der_end);
249 [trust setRetirees:(__bridge NSMutableSet *)retirees];
253 CFDataRef bKey = NULL;
254 *der_p = der_decode_data_optional(kCFAllocatorDefault, &bKey, error, *der_p, der_end);
256 [account setBackup_key:(__bridge_transfer NSData *)bKey];
259 departure_code = (enum DepartureReason) tmp_departure_code;
261 [trust setDepartureCode:departure_code];
262 require_action_quiet(*der_p && *der_p == der_end, fail,
263 SOSCreateError(kSOSErrorBadFormat, CFSTR("Didn't consume all bytes v7"), (error != NULL) ? *error : NULL, error));
272 static SOSAccount* SOSAccountCreateFromRemainingDER_v8(CFAllocatorRef allocator,
273 SOSDataSourceFactoryRef factory,
275 const uint8_t** der_p, const uint8_t *der_end)
277 SOSAccount* account = NULL;
278 SOSAccount* result = NULL;
281 CFDictionaryRef decoded_gestalt = NULL;
282 *der_p = der_decode_dictionary(kCFAllocatorDefault, &decoded_gestalt, error,
286 CFReleaseNull(decoded_gestalt);
290 account = SOSAccountCreate(kCFAllocatorDefault, decoded_gestalt, factory);
291 CFReleaseNull(decoded_gestalt);
294 SOSAccountTrustClassic *trust = account.trust;
297 SOSCircleRef circle = SOSCircleCreateFromDER(kCFAllocatorDefault, error, der_p, der_end);
298 [trust setTrustedCircle:circle];
299 CFReleaseNull(circle);
303 SOSFullPeerInfoRef identity = NULL;
304 *der_p = der_decode_fullpeer_or_null(kCFAllocatorDefault, &identity, error, *der_p, der_end);
305 trust.fullPeerInfo = identity;
306 CFReleaseNull(identity);
309 uint64_t tmp_departure_code = kSOSNeverAppliedToCircle;
310 *der_p = ccder_decode_uint64(&tmp_departure_code, *der_p, der_end);
311 [trust setDepartureCode:(enum DepartureReason) tmp_departure_code];
313 bool userPublicTrusted;
314 *der_p = ccder_decode_bool(&userPublicTrusted, *der_p, der_end);
315 account.accountKeyIsTrusted = userPublicTrusted;
318 SecKeyRef userPublic = NULL;
319 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &userPublic, error, *der_p, der_end);
320 account.accountKey = userPublic;
321 CFReleaseNull(userPublic);
325 SecKeyRef previousUserPublic = NULL;
326 *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &previousUserPublic, error, *der_p, der_end);
327 account.previousAccountKey = previousUserPublic;
328 CFReleaseNull(previousUserPublic);
333 *der_p = der_decode_data_or_null(kCFAllocatorDefault, &parms, error, *der_p, der_end);
334 account.accountKeyDerivationParameters = (__bridge_transfer NSData*)parms;
339 CFMutableSetRef retirees = SOSPeerInfoSetCreateFromArrayDER(kCFAllocatorDefault, &kSOSPeerSetCallbacks, error, der_p, der_end);
340 [trust setRetirees:(__bridge NSMutableSet *)retirees];
341 CFReleaseNull(retirees);
344 CFDataRef bKey = NULL;
345 *der_p = der_decode_data_optional(kCFAllocatorDefault, &bKey, error, *der_p, der_end);
347 CFDictionaryRef expansion = NULL;
348 *der_p = der_decode_dictionary(kCFAllocatorDefault, &expansion, error,
353 CFReleaseNull(expansion);
358 [trust setExpansion:(__bridge NSMutableDictionary *)(expansion)];
360 CFReleaseNull(expansion);
363 [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(account.kvs_message_transport);
442 secnotice("account", "No private key associated with my_identity, resetting");
445 SecKeyRef ppk = SOSFullPeerInfoCopyPubKey(identity, NULL);
446 account.peerPublicKey = ppk;
451 if (![account ensureFactoryCircles]) {
452 SOSCreateError(kSOSErrorBadFormat, CFSTR("Cannot EnsureFactoryCircles"), (error != NULL) ? *error : NULL, error);
456 SOSPeerInfoRef oldPI = CFRetainSafe(account.peerInfo);
457 if (oldPI && [account isInCircle: nil] == kSOSCCInCircle) {
458 SOSAccountCheckForAlwaysOnViews(account);
460 CFReleaseNull(oldPI);
463 [account performTransaction:^(SOSAccountTransaction * _Nonnull txn) {
464 SOSAccountEnsureRecoveryRing(account);
466 secnotice("circleop", "Setting account.key_interests_need_updating to true in SOSAccountCreateFromDER");
467 account.key_interests_need_updating = true;
470 SOSAccountEnsureUUID(account);
475 +(instancetype) accountFromDER: (const uint8_t**) der
476 end: (const uint8_t*) der_end
477 factory: (SOSDataSourceFactoryRef) factory
478 error: (NSError**) error {
479 CFErrorRef failure = NULL;
480 SOSAccount* result = SOSAccountCreateFromDER(kCFAllocatorDefault, factory, &failure, der, der_end);
484 *error = (__bridge_transfer NSError*) failure;
488 CFReleaseNull(failure);
493 +(instancetype) accountFromData: (NSData*) data
494 factory: (SOSDataSourceFactoryRef) factory
495 error: (NSError**) error {
496 size_t size = [data length];
497 const uint8_t *der = [data bytes];
498 return [self accountFromDER: &der end: der+size factory: factory error: error];
501 CFMutableSetRef SOSPeerInfoSetCreateFromArrayDER(CFAllocatorRef allocator, const CFSetCallBacks *callbacks, CFErrorRef* error,
502 const uint8_t** der_p, const uint8_t *der_end);
503 size_t SOSPeerInfoSetGetDEREncodedArraySize(CFSetRef pia, CFErrorRef *error);
504 uint8_t* SOSPeerInfoSetEncodeToArrayDER(CFSetRef pia, CFErrorRef* error, const uint8_t* der, uint8_t* der_end);
506 /************************/
509 - (NSData*) encodedData: (NSError* __autoreleasing *) error {
510 NSUInteger expected = [self.trust getDEREncodedSize: self err:error];
511 if (expected == 0) return nil;
513 return [NSMutableData dataWithSpace:expected
514 DEREncode:^uint8_t *(size_t size, uint8_t *buffer) {
515 return [self.trust encodeToDER:self