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 CFReleaseNull(publicBytes);
58 return ccder_sizeof(CCDER_CONSTRUCTED_SEQUENCE, total_payload);
61 SecCFDERCreateError(kSecDERErrorUnknownEncoding, CFSTR("don't know how to encode"), NULL, error);
62 CFReleaseNull(publicBytes);
67 static uint8_t* SOSPiggyBackBlobEncodeToDER(SOSGenCountRef gencount, SecKeyRef pubKey, CFDataRef signature, CFErrorRef* error, const uint8_t* der, uint8_t* der_end) {
68 CFDataRef publicBytes = NULL;
70 OSStatus result = SecKeyCopyPublicBytes(pubKey, &publicBytes);
72 if (result != errSecSuccess) {
73 SOSCreateError(kSOSErrorBadKey, CFSTR("Failed to export public bytes"), NULL, error);
78 der_end = ccder_encode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, der_end, der,
79 der_encode_number(gencount, error, der,
80 der_encode_data_or_null(publicBytes, error, der,
81 der_encode_data_or_null(signature, error, der, der_end))));
83 CFReleaseNull(publicBytes);
88 CFDataRef SOSPiggyBackBlobCopyEncodedData(SOSGenCountRef gencount, SecKeyRef pubKey, CFDataRef signature, CFErrorRef *error)
90 return CFDataCreateWithDER(kCFAllocatorDefault, SOSPiggyBackBlobGetDEREncodedSize(gencount, pubKey, signature, error), ^uint8_t*(size_t size, uint8_t *buffer) {
91 return SOSPiggyBackBlobEncodeToDER(gencount, pubKey, signature, error, buffer, (uint8_t *) buffer + size);
95 bool SOSPiggyBackAddToKeychain(NSArray<NSData*>* identities, NSArray<NSDictionary*>* tlks)
97 [tlks enumerateObjectsUsingBlock:^(NSDictionary* item, NSUInteger idx, BOOL * _Nonnull stop) {
99 NSData* v_data = item[(__bridge NSString*)kSecValueData];
100 NSString *acct = item[(__bridge NSString*)kSecAttrAccount];
101 NSString *srvr = item[(__bridge NSString*)kSecAttrServer];
103 NSData* base64EncodedVData = [v_data base64EncodedDataWithOptions:0];
105 NSMutableDictionary* query = [@{
106 (id)kSecClass : (id)kSecClassInternetPassword,
107 (id)kSecAttrNoLegacy : @YES,
108 (id)kSecAttrAccessGroup: @"com.apple.security.ckks",
109 (id)kSecAttrDescription: @"tlk-piggy",
110 (id)kSecAttrSynchronizable : (id)kCFBooleanFalse,
111 (id)kSecAttrSyncViewHint : (id)kSecAttrViewHintPCSMasterKey,
112 (id)kSecAttrServer: srvr,
113 (id)kSecAttrAccount: [NSString stringWithFormat: @"%@-piggy", acct],
114 (id)kSecAttrPath: acct,
115 (id)kSecAttrIsInvisible: @YES,
116 (id)kSecValueData : base64EncodedVData,
119 OSStatus status = SecItemAdd((__bridge CFDictionaryRef) query, NULL);
121 if(status == errSecDuplicateItem) {
122 // Sure, okay, fine, we'll update.
123 NSMutableDictionary* update = [@{(id)kSecValueData: v_data,
126 status = SecItemUpdate((__bridge CFDictionaryRef) query, (__bridge CFDictionaryRef)update);
130 secerror("Couldn't save tlks to keychain %d", (int)status);
133 [identities enumerateObjectsUsingBlock:^(NSData *v_data, NSUInteger idx, BOOL *stop) {
134 SecKeyRef publicKey = NULL;
135 SecKeyRef privKey = NULL;
136 CFDataRef public_key_hash = NULL;
137 NSMutableDictionary* query = NULL;
138 CFStringRef peerid = NULL;
141 NSDictionary *keyAttributes = @{
142 (__bridge id)kSecAttrKeyClass : (__bridge id)kSecAttrKeyClassPrivate,
143 (__bridge id)kSecAttrKeyType : (__bridge id)kSecAttrKeyTypeEC,
146 privKey = SecKeyCreateWithData((__bridge CFDataRef)v_data, (__bridge CFDictionaryRef)keyAttributes, NULL);
147 require_action_quiet(privKey, exit, secnotice("piggy","privKey failed to be created"));
149 publicKey = SecKeyCreatePublicFromPrivate(privKey);
150 require_action_quiet(privKey, exit, secnotice("piggy","public key failed to be created"));
152 //create public_key_hash
153 public_key_hash = SecKeyCopyPublicKeyHash(publicKey);
154 require_action_quiet(privKey, exit, secnotice("piggy","can't create public key hash"));
156 peerid = SOSCopyIDOfKey(publicKey, NULL);
159 (id)kSecClass : (id)kSecClassKey,
160 (id)kSecAttrNoLegacy : @YES,
161 (id)kSecAttrAccessGroup: @"com.apple.security.sos",
162 (id)kSecAttrApplicationLabel : (__bridge NSData*)public_key_hash,
163 (id)kSecAttrLabel : [NSString stringWithFormat: @"Cloud Identity-piggy-%@", peerid],
164 (id)kSecAttrSynchronizable : (id)kCFBooleanTrue,
165 (id)kSecUseTombstones : (id)kCFBooleanTrue,
166 (id)kSecValueData : v_data,
169 status = SecItemAdd((__bridge CFDictionaryRef) query, NULL);
171 if(status == errSecDuplicateItem) {
172 // Sure, okay, fine, we'll update.
173 NSMutableDictionary* update = [@{
174 (id)kSecValueData: v_data,
176 query[(id)kSecValueData] = nil;
177 status = SecItemUpdate((__bridge CFDictionaryRef) query, (__bridge CFDictionaryRef)update);
181 secerror("Couldn't save backupV0 to keychain %d", (int)status);
185 CFReleaseNull(publicKey);
186 CFReleaseNull(privKey);
187 CFReleaseNull(peerid);
188 CFReleaseNull(public_key_hash);
189 secnotice("piggy","key not available");
195 static const uint8_t *
196 piggy_decode_data(const uint8_t *der, const uint8_t *der_end, NSData **data)
198 size_t body_length = 0;
199 const uint8_t *body = ccder_decode_tl(CCDER_OCTET_STRING, &body_length, der, der_end);
202 *data = [NSData dataWithBytes:body length:body_length];
203 return body + body_length;
207 static NSMutableArray *
208 parse_identies(const uint8_t *der, const uint8_t *der_end)
210 NSMutableArray<NSData *>* array = [NSMutableArray array];
212 while (der != der_end) {
215 der = piggy_decode_data(der, der_end, &data);
219 [array addObject:data];
225 static NSMutableArray *
226 SOSPiggyCreateDecodedTLKs(const uint8_t *der, const uint8_t *der_end)
228 NSMutableArray *array = [NSMutableArray array];
230 while (der != der_end) {
231 NSMutableDictionary<NSString *,id> *item = [NSMutableDictionary dictionary];
233 size_t item_size = 0;
235 const uint8_t *item_der = ccder_decode_tl(CCDER_CONSTRUCTED_SEQUENCE, &item_size, der, der_end);
236 if (item_der == NULL)
238 const uint8_t *end_item_der = item_der + item_size;
240 item_der = piggy_decode_data(item_der, end_item_der, &data);
244 item[(__bridge id)kSecValueData] = data;
247 item_der = piggy_decode_data(item_der, end_item_der, &data);
248 if (item_der == NULL)
250 if ([data length] != sizeof(uuid_t)) {
254 NSString *uuidString = [[[NSUUID alloc] initWithUUIDBytes:[data bytes]] UUIDString];
255 item[(__bridge id)kSecAttrAccount] = uuidString;
257 NSString *view = NULL;
259 const uint8_t *choice_der = NULL;
260 choice_der = ccder_decode_uint64(&r, item_der, end_item_der);
261 if (choice_der == NULL) {
262 /* try other branch of CHOICE, a string */
263 CFErrorRef localError = NULL;
264 CFStringRef string = NULL;
266 choice_der = der_decode_string(NULL, 0, &string, &localError, item_der, end_item_der);
267 if (choice_der == NULL || string == NULL) {
268 CFReleaseNull(string);
269 secnotice("piggy", "Failed to parse view name");
272 CFReleaseNull(localError);
273 item_der = choice_der;
274 view = CFBridgingRelease(string);
276 if (r == kTLKManatee)
278 else if (r == kTLKEngram)
280 else if (r == kTLKAutoUnlock)
281 view = @"AutoUnlock";
282 else if (r == kTLKHealth)
285 secnotice("piggy", "unexpected view number: %d", (int)r);
288 item_der = choice_der;
290 item[(__bridge id)kSecAttrServer] = view;
292 if (item_der != end_item_der) {
295 secnotice("piggy", "Adding %@ %@", view, uuidString);
297 [array addObject:item];
305 SOSPiggyCopyInitialSyncData(const uint8_t** der, const uint8_t *der_end)
307 NSMutableDictionary *results = [NSMutableDictionary dictionary];
310 const uint8_t *topSeq = ccder_decode_tl(CCDER_CONSTRUCTED_SEQUENCE, &seq_size, *der, der_end);
312 secnotice("piggy", "Failed to parse CONS SEQ");
317 const uint8_t *ider = ccder_decode_tl(CCDER_CONSTRUCTED_SEQUENCE, &seq_size, topSeq, der_end);
319 secnotice("piggy", "Failed to parse CONS SEQ of ident");
322 NSArray *idents = parse_identies(ider, ider + seq_size);
324 results[@"idents"] = idents;
325 topSeq = ider + seq_size;
328 const uint8_t *tder = ccder_decode_tl(CCDER_CONSTRUCTED_SEQUENCE, &seq_size, topSeq, der_end);
330 secnotice("piggy", "Failed to parse CONS SEQ of TLKs");
333 NSMutableArray *tlks = SOSPiggyCreateDecodedTLKs(tder, tder + seq_size);
335 results[@"tlks"] = tlks;
336 *der = tder + seq_size;
338 /* Don't check length here so we can add more data */
340 if(results.count == 0 || tlks.count == 0){
341 secnotice("piggy","NO DATA, falling back to waiting 5 minutes for initial sync to finish");
349 SOSPiggyBackBlobCreateFromDER(SOSGenCountRef *retGencount,
350 SecKeyRef *retPubKey,
351 CFDataRef *retSignature,
352 const uint8_t** der_p, const uint8_t *der_end,
353 PiggyBackProtocolVersion version,
354 bool *setInitialSyncTimeoutToV0,
357 const uint8_t *sequence_end;
358 SOSGenCountRef gencount = NULL;
359 CFDataRef signature = NULL;
360 CFDataRef publicBytes = NULL;
364 *setInitialSyncTimeoutToV0 = true;
366 *der_p = ccder_decode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, &sequence_end, *der_p, der_end);
367 require_action_quiet(sequence_end != NULL, errOut,
368 SOSCreateError(kSOSErrorBadFormat, CFSTR("Bad Blob DER"), (error != NULL) ? *error : NULL, error));
369 *der_p = der_decode_number(kCFAllocatorDefault, 0, &gencount, error, *der_p, sequence_end);
370 *der_p = der_decode_data_or_null(kCFAllocatorDefault, &publicBytes, error, *der_p, sequence_end);
371 *der_p = der_decode_data_or_null(kCFAllocatorDefault, &signature, error, *der_p, sequence_end);
373 if(version == kPiggyV1){
374 NSDictionary* initialSyncDict = SOSPiggyCopyInitialSyncData(der_p, der_end);
375 if (initialSyncDict) {
376 NSArray* idents = initialSyncDict[@"idents"];
377 NSArray* tlks = initialSyncDict[@"tlks"];
378 SOSPiggyBackAddToKeychain(idents, tlks);
379 *setInitialSyncTimeoutToV0 = false;
381 /* Don't check length here so we can add more data */
384 secnotice("piggy","Piggybacking version 0, setting initial sync timeout to 5 minutes");
385 *setInitialSyncTimeoutToV0 = true;
386 require_action_quiet(*der_p && *der_p == der_end, errOut,
387 SOSCreateError(kSOSErrorBadFormat, CFSTR("Didn't consume all bytes for pbblob"), (error != NULL) ? *error : NULL, error));
390 *retPubKey = SecKeyCreateFromPublicData(kCFAllocatorDefault, kSecECDSAAlgorithmID, publicBytes);
391 require_quiet(*retPubKey, errOut);
392 *retGencount = gencount;
393 *retSignature = signature;
399 CFReleaseNull(gencount);
400 CFReleaseNull(signature);
402 CFReleaseNull(publicBytes);
408 SOSPiggyBackBlobCreateFromData(SOSGenCountRef *gencount,
410 CFDataRef *signature,
412 PiggyBackProtocolVersion version,
413 bool *setInitialSyncTimeoutToV0,
416 size_t size = CFDataGetLength(blobData);
417 const uint8_t *der = CFDataGetBytePtr(blobData);
418 return SOSPiggyBackBlobCreateFromDER(gencount, pubKey, signature, &der, der + size, version, setInitialSyncTimeoutToV0, error);