]> git.saurik.com Git - apple/security.git/blob - OSX/sec/SOSCircle/SecureObjectSync/SOSPiggyback.m
Security-58286.200.222.tar.gz
[apple/security.git] / OSX / sec / SOSCircle / SecureObjectSync / SOSPiggyback.m
1 /*
2 * Copyright (c) 2015 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #include <Security/SecureObjectSync/SOSCloudCircle.h>
25 #include <Security/SecureObjectSync/SOSInternal.h>
26 #include <Security/SecureObjectSync/SOSCircleDer.h>
27 #include <Security/SecureObjectSync/SOSAccountPriv.h>
28
29 #include <Security/Security.h>
30 #include <Security/SecKeyPriv.h>
31
32 #include <securityd/SecItemSchema.h>
33 #include <Security/SecItem.h>
34 #include <Security/SecItemPriv.h>
35
36 #include "SOSPiggyback.h"
37
38 #include "utilities/der_date.h"
39 #include "utilities/der_plist.h"
40 #include <utilities/der_plist_internal.h>
41 #include <corecrypto/ccder.h>
42
43 static size_t SOSPiggyBackBlobGetDEREncodedSize(SOSGenCountRef gencount, SecKeyRef pubKey, CFDataRef signature, CFErrorRef *error) {
44 size_t total_payload = 0;
45
46 CFDataRef publicBytes = NULL;
47 OSStatus result = SecKeyCopyPublicBytes(pubKey, &publicBytes);
48
49 if (result != errSecSuccess) {
50 SOSCreateError(kSOSErrorBadKey, CFSTR("Failed to export public bytes"), NULL, error);
51 return 0;
52 }
53
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);
59
60 errOut:
61 SecCFDERCreateError(kSecDERErrorUnknownEncoding, CFSTR("don't know how to encode"), NULL, error);
62 CFReleaseNull(publicBytes);
63 return 0;
64 }
65
66
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;
69
70 OSStatus result = SecKeyCopyPublicBytes(pubKey, &publicBytes);
71
72 if (result != errSecSuccess) {
73 SOSCreateError(kSOSErrorBadKey, CFSTR("Failed to export public bytes"), NULL, error);
74 return NULL;
75 }
76
77
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))));
82
83 CFReleaseNull(publicBytes);
84
85 return der_end;
86 }
87
88 CFDataRef SOSPiggyBackBlobCopyEncodedData(SOSGenCountRef gencount, SecKeyRef pubKey, CFDataRef signature, CFErrorRef *error)
89 {
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);
92 });
93 }
94
95 bool SOSPiggyBackAddToKeychain(NSArray<NSData*>* identities, NSArray<NSDictionary*>* tlks)
96 {
97 [tlks enumerateObjectsUsingBlock:^(NSDictionary* item, NSUInteger idx, BOOL * _Nonnull stop) {
98
99 NSData* v_data = item[(__bridge NSString*)kSecValueData];
100 NSString *acct = item[(__bridge NSString*)kSecAttrAccount];
101 NSString *srvr = item[(__bridge NSString*)kSecAttrServer];
102
103 NSData* base64EncodedVData = [v_data base64EncodedDataWithOptions:0];
104
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,
117 } mutableCopy];
118
119 OSStatus status = SecItemAdd((__bridge CFDictionaryRef) query, NULL);
120
121 if(status == errSecDuplicateItem) {
122 // Sure, okay, fine, we'll update.
123 NSMutableDictionary* update = [@{(id)kSecValueData: v_data,
124 } mutableCopy];
125
126 status = SecItemUpdate((__bridge CFDictionaryRef) query, (__bridge CFDictionaryRef)update);
127 }
128
129 if(status) {
130 secerror("Couldn't save tlks to keychain %d", (int)status);
131 }
132 }];
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;
139 OSStatus status;
140
141 NSDictionary *keyAttributes = @{
142 (__bridge id)kSecAttrKeyClass : (__bridge id)kSecAttrKeyClassPrivate,
143 (__bridge id)kSecAttrKeyType : (__bridge id)kSecAttrKeyTypeEC,
144 };
145 //create private key
146 privKey = SecKeyCreateWithData((__bridge CFDataRef)v_data, (__bridge CFDictionaryRef)keyAttributes, NULL);
147 require_action_quiet(privKey, exit, secnotice("piggy","privKey failed to be created"));
148 //create public key
149 publicKey = SecKeyCreatePublicFromPrivate(privKey);
150 require_action_quiet(privKey, exit, secnotice("piggy","public key failed to be created"));
151
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"));
155
156 peerid = SOSCopyIDOfKey(publicKey, NULL);
157
158 query = [@{
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,
167 } mutableCopy];
168
169 status = SecItemAdd((__bridge CFDictionaryRef) query, NULL);
170
171 if(status == errSecDuplicateItem) {
172 // Sure, okay, fine, we'll update.
173 NSMutableDictionary* update = [@{
174 (id)kSecValueData: v_data,
175 } mutableCopy];
176 query[(id)kSecValueData] = nil;
177 status = SecItemUpdate((__bridge CFDictionaryRef) query, (__bridge CFDictionaryRef)update);
178 }
179
180 if(status) {
181 secerror("Couldn't save backupV0 to keychain %d", (int)status);
182 }
183
184 exit:
185 CFReleaseNull(publicKey);
186 CFReleaseNull(privKey);
187 CFReleaseNull(peerid);
188 CFReleaseNull(public_key_hash);
189 secnotice("piggy","key not available");
190 }];
191
192 return true;
193 }
194
195 static const uint8_t *
196 piggy_decode_data(const uint8_t *der, const uint8_t *der_end, NSData **data)
197 {
198 size_t body_length = 0;
199 const uint8_t *body = ccder_decode_tl(CCDER_OCTET_STRING, &body_length, der, der_end);
200 if(body == NULL)
201 return NULL;
202 *data = [NSData dataWithBytes:body length:body_length];
203 return body + body_length;
204
205 }
206
207 static NSMutableArray *
208 parse_identies(const uint8_t *der, const uint8_t *der_end)
209 {
210 NSMutableArray<NSData *>* array = [NSMutableArray array];
211
212 while (der != der_end) {
213 NSData *data = NULL;
214
215 der = piggy_decode_data(der, der_end, &data);
216 if (der == NULL)
217 return NULL;
218 if (data)
219 [array addObject:data];
220 }
221
222 return array;
223 }
224
225 static NSMutableArray *
226 SOSPiggyCreateDecodedTLKs(const uint8_t *der, const uint8_t *der_end)
227 {
228 NSMutableArray *array = [NSMutableArray array];
229
230 while (der != der_end) {
231 NSMutableDictionary<NSString *,id> *item = [NSMutableDictionary dictionary];
232 NSData *data = NULL;
233 size_t item_size = 0;
234
235 const uint8_t *item_der = ccder_decode_tl(CCDER_CONSTRUCTED_SEQUENCE, &item_size, der, der_end);
236 if (item_der == NULL)
237 return NULL;
238 const uint8_t *end_item_der = item_der + item_size;
239
240 item_der = piggy_decode_data(item_der, end_item_der, &data);
241 if (der == NULL)
242 return NULL;
243
244 item[(__bridge id)kSecValueData] = data;
245 data = NULL;
246
247 item_der = piggy_decode_data(item_der, end_item_der, &data);
248 if (item_der == NULL)
249 return NULL;
250 if ([data length] != sizeof(uuid_t)) {
251 return NULL;
252 }
253
254 NSString *uuidString = [[[NSUUID alloc] initWithUUIDBytes:[data bytes]] UUIDString];
255 item[(__bridge id)kSecAttrAccount] = uuidString;
256
257 NSString *view = NULL;
258 uint64_t r = 0;
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;
265
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");
270 return NULL;
271 }
272 CFReleaseNull(localError);
273 item_der = choice_der;
274 view = CFBridgingRelease(string);
275 } else {
276 if (r == kTLKManatee)
277 view = @"Manatee";
278 else if (r == kTLKEngram)
279 view = @"Engram";
280 else if (r == kTLKAutoUnlock)
281 view = @"AutoUnlock";
282 else if (r == kTLKHealth)
283 view = @"Health";
284 else {
285 secnotice("piggy", "unexpected view number: %d", (int)r);
286 return NULL;
287 }
288 item_der = choice_der;
289 }
290 item[(__bridge id)kSecAttrServer] = view;
291
292 if (item_der != end_item_der) {
293 return NULL;
294 }
295 secnotice("piggy", "Adding %@ %@", view, uuidString);
296
297 [array addObject:item];
298
299 der = end_item_der;
300 }
301 return array;
302 }
303
304 NSDictionary *
305 SOSPiggyCopyInitialSyncData(const uint8_t** der, const uint8_t *der_end)
306 {
307 NSMutableDictionary *results = [NSMutableDictionary dictionary];
308 size_t seq_size;
309
310 const uint8_t *topSeq = ccder_decode_tl(CCDER_CONSTRUCTED_SEQUENCE, &seq_size, *der, der_end);
311 if(topSeq == NULL){
312 secnotice("piggy", "Failed to parse CONS SEQ");
313 return NULL;
314 }
315
316 /* parse idents */
317 const uint8_t *ider = ccder_decode_tl(CCDER_CONSTRUCTED_SEQUENCE, &seq_size, topSeq, der_end);
318 if (ider == NULL){
319 secnotice("piggy", "Failed to parse CONS SEQ of ident");
320 return NULL;
321 }
322 NSArray *idents = parse_identies(ider, ider + seq_size);
323 if (idents)
324 results[@"idents"] = idents;
325 topSeq = ider + seq_size;
326
327 /* parse tlks */
328 const uint8_t *tder = ccder_decode_tl(CCDER_CONSTRUCTED_SEQUENCE, &seq_size, topSeq, der_end);
329 if (tder == NULL){
330 secnotice("piggy", "Failed to parse CONS SEQ of TLKs");
331 return NULL;
332 }
333 NSMutableArray *tlks = SOSPiggyCreateDecodedTLKs(tder, tder + seq_size);
334 if (tlks)
335 results[@"tlks"] = tlks;
336 *der = tder + seq_size;
337
338 /* Don't check length here so we can add more data */
339
340 if(results.count == 0 || tlks.count == 0){
341 secnotice("piggy","NO DATA, falling back to waiting 5 minutes for initial sync to finish");
342 results = NULL;
343 }
344
345 return results;
346 }
347
348 bool
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,
355 CFErrorRef *error)
356 {
357 const uint8_t *sequence_end;
358 SOSGenCountRef gencount = NULL;
359 CFDataRef signature = NULL;
360 CFDataRef publicBytes = NULL;
361
362 bool res = true;
363
364 *setInitialSyncTimeoutToV0 = true;
365
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);
372
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;
380 }
381 /* Don't check length here so we can add more data */
382 }
383 else{ //V0
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));
388 }
389
390 *retPubKey = SecKeyCreateFromPublicData(kCFAllocatorDefault, kSecECDSAAlgorithmID, publicBytes);
391 require_quiet(*retPubKey, errOut);
392 *retGencount = gencount;
393 *retSignature = signature;
394
395 res = true;
396
397 errOut:
398 if(!res) {
399 CFReleaseNull(gencount);
400 CFReleaseNull(signature);
401 }
402 CFReleaseNull(publicBytes);
403
404 return res;
405 }
406
407 bool
408 SOSPiggyBackBlobCreateFromData(SOSGenCountRef *gencount,
409 SecKeyRef *pubKey,
410 CFDataRef *signature,
411 CFDataRef blobData,
412 PiggyBackProtocolVersion version,
413 bool *setInitialSyncTimeoutToV0,
414 CFErrorRef *error)
415 {
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);
419 }