]> git.saurik.com Git - apple/security.git/blob - KeychainSyncingOverIDSProxy/KeychainSyncingOverIDSProxy+SendMessage.m
168f25183de60b03c6643459e1e3fe7cb15e2b92
[apple/security.git] / KeychainSyncingOverIDSProxy / KeychainSyncingOverIDSProxy+SendMessage.m
1 /*
2 * Copyright (c) 2012-2017 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
25 #import <Foundation/NSArray.h>
26 #import <Foundation/Foundation.h>
27
28 #import <Security/SecBasePriv.h>
29 #import <Security/SecItemPriv.h>
30 #import <utilities/debugging.h>
31 #import <notify.h>
32
33 #include <Security/CKBridge/SOSCloudKeychainConstants.h>
34 #include <Security/SecureObjectSync/SOSARCDefines.h>
35 #include <Security/SecureObjectSync/SOSCloudCircle.h>
36 #include <Security/SecureObjectSync/SOSCloudCircleInternal.h>
37
38 #import <IDS/IDS.h>
39 #import <os/activity.h>
40
41 #include <utilities/SecAKSWrappers.h>
42 #include <utilities/SecADWrapper.h>
43 #include <utilities/SecCFRelease.h>
44 #include <AssertMacros.h>
45
46 #import "IDSProxy.h"
47 #import "IDSPersistentState.h"
48 #import "KeychainSyncingOverIDSProxy+SendMessage.h"
49 #include <Security/SecItemInternal.h>
50
51
52 static NSString *const IDSSendMessageOptionForceEncryptionOffKey = @"IDSSendMessageOptionForceEncryptionOff";
53
54 static NSString *const kIDSNumberOfFragments = @"NumberOfIDSMessageFragments";
55 static NSString *const kIDSFragmentIndex = @"kFragmentIndex";
56 static NSString *const kIDSMessageUseACKModel = @"UsesAckModel";
57 static NSString *const kIDSDeviceID = @"deviceID";
58
59 static const int64_t kRetryTimerLeeway = (NSEC_PER_MSEC * 250); // 250ms leeway for handling unhandled messages.
60 static const int64_t timeout = 3ull;
61 static const int64_t KVS_BACKOFF = 5;
62
63 static const NSUInteger kMaxIDSMessagePayloadSize = 64000;
64
65
66 @implementation KeychainSyncingOverIDSProxy (SendMessage)
67
68
69 -(bool) chunkAndSendKeychainPayload:(NSData*)keychainData deviceID:(NSString*)deviceName ourPeerID:(NSString*)ourPeerID theirPeerID:(NSString*) theirPeerID operation:(NSString*)operationTypeAsString uuid:(NSString*)uuidString error:(NSError**) error
70 {
71 __block BOOL result = true;
72
73 NSUInteger keychainDataLength = [keychainData length];
74 int fragmentIndex = 0;
75 int startingPosition = 0;
76
77 NSUInteger totalNumberOfFragments = (keychainDataLength + kMaxIDSMessagePayloadSize - 1)/kMaxIDSMessagePayloadSize;
78 secnotice("IDS Transport", "sending %lu number of fragments to: %@", (unsigned long)totalNumberOfFragments, deviceName);
79 NSMutableDictionary* fragmentDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
80 deviceName, kIDSDeviceID,
81 [NSNumber numberWithUnsignedInteger:totalNumberOfFragments], kIDSNumberOfFragments,
82 [NSNumber numberWithInt:fragmentIndex], kIDSFragmentIndex,
83 deviceName, kIDSMessageRecipientDeviceID, theirPeerID, kIDSMessageRecipientPeerID,
84 operationTypeAsString, kIDSOperationType,
85 uuidString, kIDSMessageUniqueID,
86 nil];
87
88 NSUInteger remainingLength = keychainDataLength;
89 while(remainingLength > 0 && result == true){
90 NSUInteger fragmentLength = MIN(remainingLength, kMaxIDSMessagePayloadSize);
91 NSData *fragment = [keychainData subdataWithRange:NSMakeRange(startingPosition, fragmentLength)];
92
93 // Insert the current fragment data in dictionary with key peerID and message key.
94 [fragmentDictionary setObject:@{theirPeerID:fragment}
95 forKey:(__bridge NSString*)kIDSMessageToSendKey];
96 // Insert the fragment number in the dictionary
97 [fragmentDictionary setObject:[NSNumber numberWithInt:fragmentIndex]
98 forKey:kIDSFragmentIndex];
99
100 result = [self sendIDSMessage:fragmentDictionary name:deviceName peer:ourPeerID];
101 if(!result)
102 secerror("Could not send fragmented message");
103
104 startingPosition+=fragmentLength;
105 remainingLength-=fragmentLength;
106 fragmentIndex++;
107 }
108
109 return result;
110 }
111
112 - (void)sendToKVS: (NSString*) theirPeerID message: (NSData*) message
113 {
114 [self sendKeysCallout:^NSMutableDictionary *(NSMutableDictionary *pending, NSError** error) {
115 CFErrorRef cf_error = NULL;
116
117 bool success = SOSCCRequestSyncWithPeerOverKVS(((__bridge CFStringRef)theirPeerID), (__bridge CFDataRef)message, &cf_error);
118
119 if(success){
120 secnotice("IDSPing", "sent peerID: %@ to securityd to sync over KVS", theirPeerID);
121 }
122 else{
123 secerror("Could not hand peerID: %@ to securityd, error: %@", theirPeerID, cf_error);
124 }
125
126 CFReleaseNull(cf_error);
127 return NULL;
128 }];
129 }
130
131 - (void) sendMessageToKVS: (NSDictionary<NSString*, NSDictionary*>*) encapsulatedKeychainMessage
132 {
133 SecADAddValueForScalarKey(CFSTR("com.apple.security.sos.kvsreroute"), 1);
134 [encapsulatedKeychainMessage enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
135 if ([key isKindOfClass: [NSString class]] && [obj isKindOfClass:[NSData class]]) {
136 [self sendToKVS:key message:obj];
137 } else {
138 secerror("Couldn't send to KVS key: %@ obj: %@", key, obj);
139 }
140 }];
141 }
142
143
144 - (void)pingTimerFired:(NSString*)IDSid peerID:(NSString*)peerID identifier:(NSString*)identifier
145 {
146 //setting next time to send
147 [self updateNextTimeToSendFor5Minutes:IDSid];
148
149 secnotice("IDS Transport", "device ID: %@ !!!!!!!!!!!!!!!!Ping timeout is up!!!!!!!!!!!!", IDSid);
150 //call securityd to sync with device over KVS
151 __block CFErrorRef cf_error = NULL;
152 __block bool success = kHandleIDSMessageSuccess;
153
154 //cleanup timers
155 dispatch_async(self.pingQueue, ^{
156 dispatch_source_t timer = [[KeychainSyncingOverIDSProxy idsProxy].pingTimers objectForKey:IDSid]; //remove timer
157 dispatch_cancel(timer); //cancel timer
158 [[KeychainSyncingOverIDSProxy idsProxy].pingTimers removeObjectForKey:IDSid];
159 });
160
161 [self sendKeysCallout:^NSMutableDictionary *(NSMutableDictionary *pending, NSError** error) {
162
163 success = SOSCCRequestSyncWithPeerOverKVSUsingIDOnly(((__bridge CFStringRef)IDSid), &cf_error);
164
165 if(success){
166 secnotice("IDSPing", "sent peerID: %@ to securityd to sync over KVS", IDSid);
167 }
168 else{
169 secerror("Could not hand peerID: %@ to securityd, error: %@", IDSid, cf_error);
170 }
171
172 return NULL;
173 }];
174 CFReleaseSafe(cf_error);
175 }
176
177 -(void) pingDevices:(NSArray*)list peerID:(NSString*)peerID
178 {
179 NSDictionary *messageDictionary = @{(__bridge NSString*)kIDSOperationType : [NSString stringWithFormat:@"%d", kIDSPeerAvailability], (__bridge NSString*)kIDSMessageToSendKey : @"checking peers"};
180
181 [list enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL * top) {
182 NSString* IDSid = (NSString*)obj;
183 NSString* identifier = [NSString string];
184 bool result = false;
185 secnotice("IDS Transport", "sending to id: %@", IDSid);
186
187 result = [self sendIDSMessage:messageDictionary name:IDSid peer:peerID];
188
189 if(!result){
190 secerror("Could not send message over IDS");
191 [self sendKeysCallout:^NSMutableDictionary *(NSMutableDictionary *pending, NSError** error) {
192 CFErrorRef kvsError = nil;
193 bool success = SOSCCRequestSyncWithPeerOverKVSUsingIDOnly(((__bridge CFStringRef)IDSid), &kvsError);
194
195 if(success){
196 secnotice("IDSPing", "sent peerID: %@ to securityd to sync over KVS", IDSid);
197 }
198 else{
199 secerror("Could not hand peerID: %@ to securityd, error: %@", IDSid, kvsError);
200 }
201 CFReleaseNull(kvsError);
202 return NULL;
203 }];
204 }
205 else{
206 dispatch_async(self.pingQueue, ^{
207 //create a timer!
208 if( [self.pingTimers objectForKey:IDSid] == nil){
209 dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
210 dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, timeout * NSEC_PER_SEC), DISPATCH_TIME_FOREVER, kRetryTimerLeeway);
211 dispatch_source_set_event_handler(timer, ^{
212 [self pingTimerFired:IDSid peerID:peerID identifier:identifier];
213 });
214 dispatch_resume(timer);
215
216 [self.pingTimers setObject:timer forKey:IDSid];
217 }
218 });
219 }
220 }];
221 }
222
223 -(BOOL) shouldProxySendMessage:(NSString*)deviceName
224 {
225 BOOL result = false;
226
227 //checking peer cache to see if the message should be sent over IDS or back to KVS
228 if(self.peerNextSendCache == nil)
229 {
230 self.peerNextSendCache = [[NSMutableDictionary alloc]initWithCapacity:0];
231 }
232 NSDate *nextTimeToSend = [self.peerNextSendCache objectForKey:deviceName];
233 if(nextTimeToSend != nil)
234 {
235 //check if the timestamp is stale or set sometime in the future
236 NSDate *currentTime = [[NSDate alloc] init];
237 //if the current time is greater than the next time to send -> time to send!
238 if([[nextTimeToSend laterDate:currentTime] isEqual:currentTime]){
239 result = true;
240 }
241 }
242 else{ //next time to send is not set yet
243 result = true;
244 }
245 return result;
246 }
247
248 -(BOOL) isMessageAPing:(NSDictionary*)data
249 {
250 NSDictionary *messageDictionary = [data objectForKey: (__bridge NSString*)kIDSMessageToSendKey];
251 BOOL isPingMessage = false;
252
253 if(messageDictionary && ![messageDictionary isKindOfClass:[NSDictionary class]])
254 {
255 NSString* messageString = [data objectForKey: (__bridge NSString*)kIDSMessageToSendKey];
256 if(messageString && [messageString isKindOfClass:[NSString class]])
257 isPingMessage = true;
258 }
259 else if(!messageDictionary){
260 secerror("IDS Transport: message is null?");
261 }
262
263 return isPingMessage;
264 }
265
266 -(BOOL) sendFragmentedIDSMessages:(NSDictionary*)data name:(NSString*) deviceName peer:(NSString*) ourPeerID error:(NSError**) error
267 {
268 BOOL result = false;
269 BOOL isPingMessage = false;
270
271 NSError* localError = nil;
272
273 NSString* operationTypeAsString = [data objectForKey: (__bridge NSString*)kIDSOperationType];
274 NSMutableDictionary *messageDictionary = [data objectForKey: (__bridge NSString*)kIDSMessageToSendKey];
275
276 isPingMessage = [self isMessageAPing:data];
277
278 //check the peer cache for the next time to send timestamp
279 //if the timestamp is set in the future, reroute the message to KVS
280 //otherwise send the message over IDS
281 if(![self shouldProxySendMessage:deviceName])
282 {
283 if(isPingMessage){
284 secnotice("IDS Transport", "peer negative cache check: peer cannot send yet. not sending ping message");
285 return true;
286 }
287 else{
288 secnotice("IDS Transport", "peer negative cache check: peer cannot send yet. rerouting message to be sent over KVS: %@", messageDictionary);
289 [self sendMessageToKVS:messageDictionary];
290 return true;
291 }
292 }
293
294 if(isPingMessage){ //foward the ping message, no processing
295 result = [self sendIDSMessage:data
296 name:deviceName
297 peer:ourPeerID];
298 if(!result){
299 secerror("Could not send ping message");
300 }
301 return result;
302 }
303
304 NSString *localMessageIdentifier = [[NSUUID UUID] UUIDString];
305
306 bool fragment = [operationTypeAsString intValue] == kIDSKeychainSyncIDSFragmentation;
307 bool useAckModel = fragment && [[data objectForKey:kIDSMessageUseACKModel] compare: @"YES"] == NSOrderedSame;
308
309 __block NSData *keychainData = nil;
310 __block NSString *theirPeerID = nil;
311
312 [messageDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
313 if ([key isKindOfClass:[NSString class]] && [obj isKindOfClass:[NSData class]]) {
314 theirPeerID = (NSString*)key;
315 keychainData = (NSData*)obj;
316 }
317 *stop = YES;
318 }];
319
320 if(fragment && keychainData && [keychainData length] >= kMaxIDSMessagePayloadSize){
321 secnotice("IDS Transport","sending chunked keychain messages");
322 result = [self chunkAndSendKeychainPayload:keychainData
323 deviceID:deviceName
324 ourPeerID:ourPeerID
325 theirPeerID:theirPeerID
326 operation:operationTypeAsString
327 uuid:localMessageIdentifier
328 error:&localError];
329 }
330 else{
331 NSMutableDictionary* dataCopy = [NSMutableDictionary dictionaryWithDictionary:data];
332 [dataCopy setObject:localMessageIdentifier forKey:(__bridge NSString*)kIDSMessageUniqueID];
333 result = [self sendIDSMessage:dataCopy
334 name:deviceName
335 peer:ourPeerID];
336 }
337
338 if(result && useAckModel){
339 secnotice("IDS Transport", "setting ack timer");
340 [self setMessageTimer:localMessageIdentifier deviceID:deviceName message:data];
341 }
342
343 secnotice("IDS Transport","returning result: %d, error: %@", result, error ? *error : nil);
344 return result;
345 }
346
347 -(void) updateNextTimeToSendFor5Minutes:(NSString*)ID
348 {
349 secnotice("IDS Transport", "Setting next time to send in 5 minutes for device: %@", ID);
350
351 NSTimeInterval backOffInterval = (KVS_BACKOFF * 60);
352 NSDate *nextTimeToTransmit = [NSDate dateWithTimeInterval:backOffInterval sinceDate:[NSDate date]];
353
354 [self.peerNextSendCache setObject:nextTimeToTransmit forKey:ID];
355 }
356
357 - (void)ackTimerFired:(NSString*)identifier deviceID:(NSString*)ID
358 {
359 secnotice("IDS Transport", "IDS device id: %@, Ping timeout is up for message identifier: %@", ID, identifier);
360
361 //call securityd to sync with device over KVS
362 NSMutableDictionary * __block message;
363 dispatch_sync(self.dataQueue, ^{
364 message = [[KeychainSyncingOverIDSProxy idsProxy].messagesInFlight objectForKey:identifier];
365 [[KeychainSyncingOverIDSProxy idsProxy].messagesInFlight removeObjectForKey:identifier];
366 });
367 if(!message){
368 return;
369 }
370 NSDictionary *encapsulatedKeychainMessage = [message objectForKey:(__bridge NSString*)kIDSMessageToSendKey];
371
372 secnotice("IDS Transport", "Encapsulated message: %@", encapsulatedKeychainMessage);
373 //cleanup timers
374 dispatch_async(self.pingQueue, ^{
375 dispatch_source_t timer = [[KeychainSyncingOverIDSProxy idsProxy].pingTimers objectForKey:identifier]; //remove timer
376 if(timer != nil)
377 dispatch_cancel(timer); //cancel timer
378 [[KeychainSyncingOverIDSProxy idsProxy].pingTimers removeObjectForKey:identifier];
379 });
380
381 [self sendMessageToKVS:encapsulatedKeychainMessage];
382
383 //setting next time to send
384 [self updateNextTimeToSendFor5Minutes:ID];
385
386 [[KeychainSyncingOverIDSProxy idsProxy] persistState];
387 }
388
389 -(void) setMessageTimer:(NSString*)identifier deviceID:(NSString*)ID message:(NSDictionary*)message
390 {
391 dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
392 dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, timeout * NSEC_PER_SEC), DISPATCH_TIME_FOREVER, kRetryTimerLeeway);
393
394 dispatch_source_set_event_handler(timer, ^{
395 [self ackTimerFired:identifier deviceID:ID];
396 });
397 dispatch_resume(timer);
398 //restructure message in flight
399
400
401
402 //set the timer for message id
403 dispatch_async(self.pingQueue, ^{
404 [self.pingTimers setObject:timer forKey:identifier];
405 });
406
407 dispatch_sync(self.dataQueue, ^{
408 [[KeychainSyncingOverIDSProxy idsProxy].messagesInFlight setObject:message forKey:identifier];
409 });
410 [[KeychainSyncingOverIDSProxy idsProxy] persistState];
411 }
412
413 //had an immediate error, remove it from messages in flight, and immediately send it over KVS
414 -(void) cleanupAfterHardIDSError:(NSDictionary*)data
415 {
416 NSString *messageIdentifier = [data objectForKey:(__bridge NSString*)kIDSMessageUniqueID];
417 NSMutableDictionary * __block messageToSendToKVS = nil;
418
419 if(messageIdentifier != nil){
420 secerror("removing message id: %@ from message timers", messageIdentifier);
421 dispatch_sync(self.dataQueue, ^{
422 messageToSendToKVS = [[KeychainSyncingOverIDSProxy idsProxy].messagesInFlight objectForKey:messageIdentifier];
423 [[KeychainSyncingOverIDSProxy idsProxy].messagesInFlight removeObjectForKey:messageIdentifier];
424 });
425 if(!messageToSendToKVS){
426 secnotice("IDS Transport", "no message for identifier: %@", messageIdentifier);
427 return;
428 }
429 secnotice("IDS Transport", "sending over KVS: %@", messageToSendToKVS);
430
431
432
433 //cleanup timer for message
434 dispatch_async(self.pingQueue, ^{
435 dispatch_source_t timer = [[KeychainSyncingOverIDSProxy idsProxy].pingTimers objectForKey:messageIdentifier]; //remove timer
436 if(timer)
437 dispatch_cancel(timer); //cancel timer
438 [[KeychainSyncingOverIDSProxy idsProxy].pingTimers removeObjectForKey:messageIdentifier];
439 });
440 }
441
442 NSDictionary *encapsulatedKeychainMessage = [messageToSendToKVS objectForKey:(__bridge NSString*)kIDSMessageToSendKey];
443
444 if([encapsulatedKeychainMessage isKindOfClass:[NSDictionary class]]){
445 secnotice("IDS Transport", "Encapsulated message: %@", encapsulatedKeychainMessage);
446 [self sendMessageToKVS:encapsulatedKeychainMessage];
447
448 }
449 }
450
451 -(BOOL) sendIDSMessage:(NSDictionary*)data name:(NSString*) deviceName peer:(NSString*) peerID
452 {
453
454 if(!self->_service){
455 secerror("Could not send message to peer: %@: IDS delegate uninitialized, can't use IDS to send this message", deviceName);
456 return NO;
457 }
458
459 dispatch_async(self.calloutQueue, ^{
460
461 IDSMessagePriority priority = IDSMessagePriorityHigh;
462 BOOL encryptionOff = YES;
463 NSString *sendersPeerIDKey = [ NSString stringWithUTF8String: kMessageKeySendersPeerID];
464
465 secnotice("backoff","!!writing these keys to IDS!!: %@", data);
466
467 NSDictionary *options = @{IDSSendMessageOptionForceEncryptionOffKey : [NSNumber numberWithBool:encryptionOff] };
468
469 NSMutableDictionary *dataCopy = [NSMutableDictionary dictionaryWithDictionary: data];
470
471 //set our peer id and a unique id for this message
472 [dataCopy setObject:peerID forKey:sendersPeerIDKey];
473 secnotice("IDS Transport", "%@ sending message %@ to: %@", peerID, data, deviceName);
474
475 NSDictionary *info;
476 NSInteger errorCode = 0;
477 NSInteger numberOfDevices = 0;
478 NSString *errMessage = nil;
479 NSMutableSet *destinations = nil;
480 NSError *localError = nil;
481 NSString *identifier = nil;
482 IDSDevice *device = nil;
483 numberOfDevices = [self.listOfDevices count];
484
485 require_action_quiet(numberOfDevices > 0, fail, errorCode = kSecIDSErrorNotRegistered; errMessage=createErrorString(@"Could not send message to peer: %@: IDS devices are not registered yet", deviceName));
486 secnotice("IDS Transport","List of devices: %@", [self->_service devices]);
487
488 destinations = [NSMutableSet set];
489 for(NSUInteger i = 0; i < [ self.listOfDevices count ]; i++){
490 device = self.listOfDevices[i];
491 if( [ deviceName compare:device.uniqueID ] == 0){
492 [destinations addObject: IDSCopyIDForDevice(device)];
493 }
494 }
495 require_action_quiet([destinations count] != 0, fail, errorCode = kSecIDSErrorCouldNotFindMatchingAuthToken; errMessage = createErrorString(@"Could not send message to peer: %@: IDS device ID for peer does not match any devices within an IDS Account", deviceName));
496
497 bool result = [self->_service sendMessage:dataCopy toDestinations:destinations priority:priority options:options identifier:&identifier error:&localError ] ;
498
499 [KeychainSyncingOverIDSProxy idsProxy].outgoingMessages++;
500 require_action_quiet(localError == nil && result, fail, errorCode = kSecIDSErrorFailedToSend; errMessage = createErrorString(@"Had an error sending IDS message to peer: %@", deviceName));
501
502 secnotice("IDS Transport","successfully sent to peer:%@, message: %@", deviceName, dataCopy);
503 fail:
504
505 if(errMessage != nil){
506 info = [ NSDictionary dictionaryWithObjectsAndKeys:errMessage, NSLocalizedDescriptionKey, nil ];
507 localError = [[NSError alloc] initWithDomain:@"com.apple.security.ids.error" code:errorCode userInfo:info ];
508 secerror("%@", localError);
509 [self cleanupAfterHardIDSError: data];
510 }
511 });
512
513 return YES;
514 }
515
516 @end