2 * Copyright (c) 2015 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@
24 #include <Security/SecureObjectSync/SOSCloudCircle.h>
25 #include <Security/SecureObjectSync/SOSInternal.h>
26 #include <Security/SecureObjectSync/SOSCircleDer.h>
27 #include <Security/SecureObjectSync/SOSAccountPriv.h>
29 #include <Security/Security.h>
30 #include <Security/SecKeyPriv.h>
32 #include <securityd/SecItemSchema.h>
33 #include <Security/SecItem.h>
34 #include <Security/SecItemPriv.h>
36 #include "SOSPiggyback.h"
38 #include "utilities/der_date.h"
39 #include "utilities/der_plist.h"
40 #include <utilities/der_plist_internal.h>
41 #include <corecrypto/ccder.h>
43 static size_t SOSPiggyBackBlobGetDEREncodedSize(SOSGenCountRef gencount, SecKeyRef pubKey, CFDataRef signature, CFErrorRef *error) {
44 size_t total_payload = 0;
46 CFDataRef publicBytes = NULL;
47 OSStatus result = SecKeyCopyPublicBytes(pubKey, &publicBytes);
49 if (result != errSecSuccess) {
50 SOSCreateError(kSOSErrorBadKey, CFSTR("Failed to export public bytes"), NULL, error);
54 require_quiet(accumulate_size(&total_payload, der_sizeof_number(gencount, error)), errOut);
55 require_quiet(accumulate_size(&total_payload, der_sizeof_data_or_null(publicBytes, error)), errOut);
56 require_quiet(accumulate_size(&total_payload, der_sizeof_data_or_null(signature, error)), errOut);
57 return ccder_sizeof(CCDER_CONSTRUCTED_SEQUENCE, total_payload);
60 SecCFDERCreateError(kSecDERErrorUnknownEncoding, CFSTR("don't know how to encode"), NULL, error);
65 static uint8_t* SOSPiggyBackBlobEncodeToDER(SOSGenCountRef gencount, SecKeyRef pubKey, CFDataRef signature, CFErrorRef* error, const uint8_t* der, uint8_t* der_end) {
66 CFDataRef publicBytes = NULL;
68 OSStatus result = SecKeyCopyPublicBytes(pubKey, &publicBytes);
70 if (result != errSecSuccess) {
71 SOSCreateError(kSOSErrorBadKey, CFSTR("Failed to export public bytes"), NULL, error);
76 der_end = ccder_encode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, der_end, der,
77 der_encode_number(gencount, error, der,
78 der_encode_data_or_null(publicBytes, error, der,
79 der_encode_data_or_null(signature, error, der, der_end))));
83 CFDataRef SOSPiggyBackBlobCopyEncodedData(SOSGenCountRef gencount, SecKeyRef pubKey, CFDataRef signature, CFErrorRef *error)
85 return CFDataCreateWithDER(kCFAllocatorDefault, SOSPiggyBackBlobGetDEREncodedSize(gencount, pubKey, signature, error), ^uint8_t*(size_t size, uint8_t *buffer) {
86 return SOSPiggyBackBlobEncodeToDER(gencount, pubKey, signature, error, buffer, (uint8_t *) buffer + size);
90 bool SOSPiggyBackAddToKeychain(NSArray<NSData*>* identities, NSArray<NSDictionary*>* tlks)
92 [tlks enumerateObjectsUsingBlock:^(NSDictionary* item, NSUInteger idx, BOOL * _Nonnull stop) {
94 NSData* v_data = item[(__bridge NSString*)kSecValueData];
95 NSString *acct = item[(__bridge NSString*)kSecAttrAccount];
96 NSString *srvr = item[(__bridge NSString*)kSecAttrServer];
98 NSData* base64EncodedVData = [v_data base64EncodedDataWithOptions:0];
100 NSMutableDictionary* query = [@{
101 (id)kSecClass : (id)kSecClassInternetPassword,
102 (id)kSecAttrNoLegacy : @YES,
103 (id)kSecAttrAccessGroup: @"com.apple.security.ckks",
104 (id)kSecAttrDescription: @"tlk-piggy",
105 (id)kSecAttrSynchronizable : (id)kCFBooleanFalse,
106 (id)kSecAttrSyncViewHint : (id)kSecAttrViewHintPCSMasterKey,
107 (id)kSecAttrServer: srvr,
108 (id)kSecAttrAccount: [NSString stringWithFormat: @"%@-piggy", acct],
109 (id)kSecAttrPath: acct,
110 (id)kSecAttrIsInvisible: @YES,
111 (id)kSecValueData : base64EncodedVData,
114 OSStatus status = SecItemAdd((__bridge CFDictionaryRef) query, NULL);
116 if(status == errSecDuplicateItem) {
117 // Sure, okay, fine, we'll update.
118 NSMutableDictionary* update = [@{(id)kSecValueData: v_data,
121 status = SecItemUpdate((__bridge CFDictionaryRef) query, (__bridge CFDictionaryRef)update);
125 secerror("Couldn't save tlks to keychain %d", (int)status);
128 [identities enumerateObjectsUsingBlock:^(NSData *v_data, NSUInteger idx, BOOL *stop) {
129 SecKeyRef publicKey = NULL;
130 SecKeyRef privKey = NULL;
131 CFDataRef public_key_hash = NULL;
132 NSMutableDictionary* query = NULL;
133 CFStringRef peerid = NULL;
136 NSDictionary *keyAttributes = @{
137 (__bridge id)kSecAttrKeyClass : (__bridge id)kSecAttrKeyClassPrivate,
138 (__bridge id)kSecAttrKeyType : (__bridge id)kSecAttrKeyTypeEC,
141 privKey = SecKeyCreateWithData((__bridge CFDataRef)v_data, (__bridge CFDictionaryRef)keyAttributes, NULL);
142 require_action_quiet(privKey, exit, secnotice("piggy","privKey failed to be created"));
144 publicKey = SecKeyCreatePublicFromPrivate(privKey);
145 require_action_quiet(privKey, exit, secnotice("piggy","public key failed to be created"));
147 //create public_key_hash
148 public_key_hash = SecKeyCopyPublicKeyHash(publicKey);
149 require_action_quiet(privKey, exit, secnotice("piggy","can't create public key hash"));
151 peerid = SOSCopyIDOfKey(publicKey, NULL);
154 (id)kSecClass : (id)kSecClassKey,
155 (id)kSecAttrNoLegacy : @YES,
156 (id)kSecAttrAccessGroup: @"com.apple.security.sos",
157 (id)kSecAttrApplicationLabel : (__bridge NSData*)public_key_hash,
158 (id)kSecAttrLabel : [NSString stringWithFormat: @"Cloud Identity-piggy-%@", peerid],
159 (id)kSecAttrSynchronizable : (id)kCFBooleanTrue,
160 (id)kSecUseTombstones : (id)kCFBooleanTrue,
161 (id)kSecValueData : v_data,
164 status = SecItemAdd((__bridge CFDictionaryRef) query, NULL);
166 if(status == errSecDuplicateItem) {
167 // Sure, okay, fine, we'll update.
168 NSMutableDictionary* update = [@{
169 (id)kSecValueData: v_data,
171 query[(id)kSecValueData] = nil;
172 status = SecItemUpdate((__bridge CFDictionaryRef) query, (__bridge CFDictionaryRef)update);
176 secerror("Couldn't save backupV0 to keychain %d", (int)status);
180 CFReleaseNull(publicKey);
181 CFReleaseNull(privKey);
182 CFReleaseNull(peerid);
183 CFReleaseNull(public_key_hash);
184 secnotice("piggy","key not available");
190 static const uint8_t *
191 piggy_decode_data(const uint8_t *der, const uint8_t *der_end, NSData **data)
193 size_t body_length = 0;
194 const uint8_t *body = ccder_decode_tl(CCDER_OCTET_STRING, &body_length, der, der_end);
197 *data = [NSData dataWithBytes:body length:body_length];
198 return body + body_length;
202 static NSMutableArray *
203 parse_identies(const uint8_t *der, const uint8_t *der_end)
205 NSMutableArray<NSData *>* array = [NSMutableArray array];
207 while (der != der_end) {
210 der = piggy_decode_data(der, der_end, &data);
214 [array addObject:data];
220 static NSMutableArray *
221 SOSPiggyCreateDecodedTLKs(const uint8_t *der, const uint8_t *der_end)
223 NSMutableArray *array = [NSMutableArray array];
225 while (der != der_end) {
226 NSMutableDictionary<NSString *,id> *item = [NSMutableDictionary dictionary];
228 size_t item_size = 0;
230 const uint8_t *item_der = ccder_decode_tl(CCDER_CONSTRUCTED_SEQUENCE, &item_size, der, der_end);
231 if (item_der == NULL)
233 const uint8_t *end_item_der = item_der + item_size;
235 item_der = piggy_decode_data(item_der, end_item_der, &data);
239 item[(__bridge id)kSecValueData] = data;
242 item_der = piggy_decode_data(item_der, end_item_der, &data);
243 if (item_der == NULL)
245 if ([data length] != sizeof(uuid_t)) {
249 NSString *uuidString = [[[NSUUID alloc] initWithUUIDBytes:[data bytes]] UUIDString];
250 item[(__bridge id)kSecAttrAccount] = uuidString;
252 NSString *view = NULL;
254 const uint8_t *choice_der = NULL;
255 choice_der = ccder_decode_uint64(&r, item_der, end_item_der);
256 if (choice_der == NULL) {
257 /* try other branch of CHOICE, a string */
258 CFErrorRef localError = NULL;
259 CFStringRef string = NULL;
261 choice_der = der_decode_string(NULL, 0, &string, &localError, item_der, end_item_der);
262 if (choice_der == NULL || string == NULL) {
263 CFReleaseNull(string);
264 secnotice("piggy", "Failed to parse view name");
267 CFReleaseNull(localError);
268 item_der = choice_der;
269 view = CFBridgingRelease(string);
271 if (r == kTLKManatee)
273 else if (r == kTLKEngram)
275 else if (r == kTLKAutoUnlock)
276 view = @"AutoUnlock";
277 else if (r == kTLKHealth)
280 secnotice("piggy", "unexpected view number: %d", (int)r);
283 item_der = choice_der;
285 item[(__bridge id)kSecAttrServer] = view;
287 if (item_der != end_item_der) {
290 secnotice("piggy", "Adding %@ %@", view, uuidString);
292 [array addObject:item];
300 SOSPiggyCopyInitialSyncData(const uint8_t** der, const uint8_t *der_end)
302 NSMutableDictionary *results = [NSMutableDictionary dictionary];
305 const uint8_t *topSeq = ccder_decode_tl(CCDER_CONSTRUCTED_SEQUENCE, &seq_size, *der, der_end);
307 secnotice("piggy", "Failed to parse CONS SEQ");
312 const uint8_t *ider = ccder_decode_tl(CCDER_CONSTRUCTED_SEQUENCE, &seq_size, topSeq, der_end);
314 secnotice("piggy", "Failed to parse CONS SEQ of ident");
317 NSArray *idents = parse_identies(ider, ider + seq_size);
319 results[@"idents"] = idents;
320 topSeq = ider + seq_size;
323 const uint8_t *tder = ccder_decode_tl(CCDER_CONSTRUCTED_SEQUENCE, &seq_size, topSeq, der_end);
325 secnotice("piggy", "Failed to parse CONS SEQ of TLKs");
328 NSMutableArray *tlks = SOSPiggyCreateDecodedTLKs(tder, tder + seq_size);
330 results[@"tlks"] = tlks;
331 *der = tder + seq_size;
333 /* Don't check length here so we can add more data */
335 if(results.count == 0 || tlks.count == 0){
336 secnotice("piggy","NO DATA, falling back to waiting 5 minutes for initial sync to finish");
344 SOSPiggyBackBlobCreateFromDER(SOSGenCountRef *retGencount,
345 SecKeyRef *retPubKey,
346 CFDataRef *retSignature,
347 const uint8_t** der_p, const uint8_t *der_end,
348 PiggyBackProtocolVersion version,
349 bool *setInitialSyncTimeoutToV0,
352 const uint8_t *sequence_end;
353 SOSGenCountRef gencount = NULL;
354 CFDataRef signature = NULL;
355 CFDataRef publicBytes = NULL;
359 *setInitialSyncTimeoutToV0 = true;
361 *der_p = ccder_decode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, &sequence_end, *der_p, der_end);
362 require_action_quiet(sequence_end != NULL, errOut,
363 SOSCreateError(kSOSErrorBadFormat, CFSTR("Bad Blob DER"), (error != NULL) ? *error : NULL, error));
364 *der_p = der_decode_number(kCFAllocatorDefault, 0, &gencount, error, *der_p, sequence_end);
365 *der_p = der_decode_data_or_null(kCFAllocatorDefault, &publicBytes, error, *der_p, sequence_end);
366 *der_p = der_decode_data_or_null(kCFAllocatorDefault, &signature, error, *der_p, sequence_end);
368 if(version == kPiggyV1){
369 NSDictionary* initialSyncDict = SOSPiggyCopyInitialSyncData(der_p, der_end);
370 if (initialSyncDict) {
371 NSArray* idents = initialSyncDict[@"idents"];
372 NSArray* tlks = initialSyncDict[@"tlks"];
373 SOSPiggyBackAddToKeychain(idents, tlks);
374 *setInitialSyncTimeoutToV0 = false;
376 /* Don't check length here so we can add more data */
379 secnotice("piggy","Piggybacking version 0, setting initial sync timeout to 5 minutes");
380 *setInitialSyncTimeoutToV0 = true;
381 require_action_quiet(*der_p && *der_p == der_end, errOut,
382 SOSCreateError(kSOSErrorBadFormat, CFSTR("Didn't consume all bytes for pbblob"), (error != NULL) ? *error : NULL, error));
385 *retPubKey = SecKeyCreateFromPublicData(kCFAllocatorDefault, kSecECDSAAlgorithmID, publicBytes);
386 require_quiet(*retPubKey, errOut);
387 *retGencount = gencount;
388 *retSignature = signature;
394 CFReleaseNull(gencount);
395 CFReleaseNull(publicBytes);
396 CFReleaseNull(signature);
403 SOSPiggyBackBlobCreateFromData(SOSGenCountRef *gencount,
405 CFDataRef *signature,
407 PiggyBackProtocolVersion version,
408 bool *setInitialSyncTimeoutToV0,
411 size_t size = CFDataGetLength(blobData);
412 const uint8_t *der = CFDataGetBytePtr(blobData);
413 return SOSPiggyBackBlobCreateFromDER(gencount, pubKey, signature, &der, der + size, version, setInitialSyncTimeoutToV0, error);