2 * Copyright (c) 2012-2017 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@
25 #import <Foundation/NSArray.h>
26 #import <Foundation/Foundation.h>
28 #import <Security/SecBasePriv.h>
29 #import <Security/SecItemPriv.h>
30 #import <utilities/debugging.h>
33 #include <Security/CKBridge/SOSCloudKeychainConstants.h>
34 #include <Security/SecureObjectSync/SOSARCDefines.h>
35 #include <Security/SecureObjectSync/SOSCloudCircle.h>
36 #include <Security/SecureObjectSync/SOSCloudCircleInternal.h>
39 #import <os/activity.h>
41 #include <utilities/SecAKSWrappers.h>
42 #include <utilities/SecADWrapper.h>
43 #include <utilities/SecCFRelease.h>
44 #include <AssertMacros.h>
47 #import "IDSPersistentState.h"
48 #import "KeychainSyncingOverIDSProxy+SendMessage.h"
49 #include <Security/SecItemInternal.h>
52 static NSString *const IDSSendMessageOptionForceEncryptionOffKey = @"IDSSendMessageOptionForceEncryptionOff";
54 static NSString *const kIDSNumberOfFragments = @"NumberOfIDSMessageFragments";
55 static NSString *const kIDSFragmentIndex = @"kFragmentIndex";
56 static NSString *const kIDSMessageUseACKModel = @"UsesAckModel";
57 static NSString *const kIDSDeviceID = @"deviceID";
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;
63 static const NSUInteger kMaxIDSMessagePayloadSize = 64000;
66 @implementation KeychainSyncingOverIDSProxy (SendMessage)
69 -(bool) chunkAndSendKeychainPayload:(NSData*)keychainData deviceID:(NSString*)deviceName ourPeerID:(NSString*)ourPeerID theirPeerID:(NSString*) theirPeerID operation:(NSString*)operationTypeAsString uuid:(NSString*)uuidString error:(NSError**) error
71 __block BOOL result = true;
73 NSUInteger keychainDataLength = [keychainData length];
74 int fragmentIndex = 0;
75 int startingPosition = 0;
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,
88 NSUInteger remainingLength = keychainDataLength;
89 while(remainingLength > 0 && result == true){
90 NSUInteger fragmentLength = MIN(remainingLength, kMaxIDSMessagePayloadSize);
91 NSData *fragment = [keychainData subdataWithRange:NSMakeRange(startingPosition, fragmentLength)];
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];
100 result = [self sendIDSMessage:fragmentDictionary name:deviceName peer:ourPeerID];
102 secerror("Could not send fragmented message");
104 startingPosition+=fragmentLength;
105 remainingLength-=fragmentLength;
112 - (void)sendToKVS: (NSString*) theirPeerID message: (NSData*) message
114 [self sendKeysCallout:^NSMutableDictionary *(NSMutableDictionary *pending, NSError** error) {
115 CFErrorRef cf_error = NULL;
117 bool success = SOSCCRequestSyncWithPeerOverKVS(((__bridge CFStringRef)theirPeerID), (__bridge CFDataRef)message, &cf_error);
120 secnotice("IDSPing", "sent peerID: %@ to securityd to sync over KVS", theirPeerID);
123 secerror("Could not hand peerID: %@ to securityd, error: %@", theirPeerID, cf_error);
126 CFReleaseNull(cf_error);
131 - (void) sendMessageToKVS: (NSDictionary<NSString*, NSDictionary*>*) encapsulatedKeychainMessage
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];
138 secerror("Couldn't send to KVS key: %@ obj: %@", key, obj);
144 - (void)pingTimerFired:(NSString*)IDSid peerID:(NSString*)peerID identifier:(NSString*)identifier
146 //setting next time to send
147 [self updateNextTimeToSendFor5Minutes:IDSid];
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;
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];
161 [self sendKeysCallout:^NSMutableDictionary *(NSMutableDictionary *pending, NSError** error) {
163 success = SOSCCRequestSyncWithPeerOverKVSUsingIDOnly(((__bridge CFStringRef)IDSid), &cf_error);
166 secnotice("IDSPing", "sent peerID: %@ to securityd to sync over KVS", IDSid);
169 secerror("Could not hand peerID: %@ to securityd, error: %@", IDSid, cf_error);
174 CFReleaseSafe(cf_error);
177 -(void) pingDevices:(NSArray*)list peerID:(NSString*)peerID
179 NSDictionary *messageDictionary = @{(__bridge NSString*)kIDSOperationType : [NSString stringWithFormat:@"%d", kIDSPeerAvailability], (__bridge NSString*)kIDSMessageToSendKey : @"checking peers"};
181 [list enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL * top) {
182 NSString* IDSid = (NSString*)obj;
183 NSString* identifier = [NSString string];
185 secnotice("IDS Transport", "sending to id: %@", IDSid);
187 result = [self sendIDSMessage:messageDictionary name:IDSid peer:peerID];
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);
196 secnotice("IDSPing", "sent peerID: %@ to securityd to sync over KVS", IDSid);
199 secerror("Could not hand peerID: %@ to securityd, error: %@", IDSid, kvsError);
201 CFReleaseNull(kvsError);
206 dispatch_async(self.pingQueue, ^{
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];
214 dispatch_resume(timer);
216 [self.pingTimers setObject:timer forKey:IDSid];
223 -(BOOL) shouldProxySendMessage:(NSString*)deviceName
227 //checking peer cache to see if the message should be sent over IDS or back to KVS
228 if(self.peerNextSendCache == nil)
230 self.peerNextSendCache = [[NSMutableDictionary alloc]initWithCapacity:0];
232 NSDate *nextTimeToSend = [self.peerNextSendCache objectForKey:deviceName];
233 if(nextTimeToSend != nil)
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]){
242 else{ //next time to send is not set yet
248 -(BOOL) isMessageAPing:(NSDictionary*)data
250 NSDictionary *messageDictionary = [data objectForKey: (__bridge NSString*)kIDSMessageToSendKey];
251 BOOL isPingMessage = false;
253 if(messageDictionary && ![messageDictionary isKindOfClass:[NSDictionary class]])
255 NSString* messageString = [data objectForKey: (__bridge NSString*)kIDSMessageToSendKey];
256 if(messageString && [messageString isKindOfClass:[NSString class]])
257 isPingMessage = true;
259 else if(!messageDictionary){
260 secerror("IDS Transport: message is null?");
263 return isPingMessage;
266 -(BOOL) sendFragmentedIDSMessages:(NSDictionary*)data name:(NSString*) deviceName peer:(NSString*) ourPeerID error:(NSError**) error
269 BOOL isPingMessage = false;
271 NSError* localError = nil;
273 NSString* operationTypeAsString = [data objectForKey: (__bridge NSString*)kIDSOperationType];
274 NSMutableDictionary *messageDictionary = [data objectForKey: (__bridge NSString*)kIDSMessageToSendKey];
276 isPingMessage = [self isMessageAPing:data];
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])
284 secnotice("IDS Transport", "peer negative cache check: peer cannot send yet. not sending ping message");
288 secnotice("IDS Transport", "peer negative cache check: peer cannot send yet. rerouting message to be sent over KVS: %@", messageDictionary);
289 [self sendMessageToKVS:messageDictionary];
294 if(isPingMessage){ //foward the ping message, no processing
295 result = [self sendIDSMessage:data
299 secerror("Could not send ping message");
304 NSString *localMessageIdentifier = [[NSUUID UUID] UUIDString];
306 bool fragment = [operationTypeAsString intValue] == kIDSKeychainSyncIDSFragmentation;
307 bool useAckModel = fragment && [[data objectForKey:kIDSMessageUseACKModel] compare: @"YES"] == NSOrderedSame;
309 __block NSData *keychainData = nil;
310 __block NSString *theirPeerID = nil;
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;
320 if(fragment && keychainData && [keychainData length] >= kMaxIDSMessagePayloadSize){
321 secnotice("IDS Transport","sending chunked keychain messages");
322 result = [self chunkAndSendKeychainPayload:keychainData
325 theirPeerID:theirPeerID
326 operation:operationTypeAsString
327 uuid:localMessageIdentifier
331 NSMutableDictionary* dataCopy = [NSMutableDictionary dictionaryWithDictionary:data];
332 [dataCopy setObject:localMessageIdentifier forKey:(__bridge NSString*)kIDSMessageUniqueID];
333 result = [self sendIDSMessage:dataCopy
338 if(result && useAckModel){
339 secnotice("IDS Transport", "setting ack timer");
340 [self setMessageTimer:localMessageIdentifier deviceID:deviceName message:data];
343 secnotice("IDS Transport","returning result: %d, error: %@", result, error ? *error : nil);
347 -(void) updateNextTimeToSendFor5Minutes:(NSString*)ID
349 secnotice("IDS Transport", "Setting next time to send in 5 minutes for device: %@", ID);
351 NSTimeInterval backOffInterval = (KVS_BACKOFF * 60);
352 NSDate *nextTimeToTransmit = [NSDate dateWithTimeInterval:backOffInterval sinceDate:[NSDate date]];
354 [self.peerNextSendCache setObject:nextTimeToTransmit forKey:ID];
357 - (void)ackTimerFired:(NSString*)identifier deviceID:(NSString*)ID
359 secnotice("IDS Transport", "IDS device id: %@, Ping timeout is up for message identifier: %@", ID, identifier);
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];
370 NSDictionary *encapsulatedKeychainMessage = [message objectForKey:(__bridge NSString*)kIDSMessageToSendKey];
372 secnotice("IDS Transport", "Encapsulated message: %@", encapsulatedKeychainMessage);
374 dispatch_async(self.pingQueue, ^{
375 dispatch_source_t timer = [[KeychainSyncingOverIDSProxy idsProxy].pingTimers objectForKey:identifier]; //remove timer
377 dispatch_cancel(timer); //cancel timer
378 [[KeychainSyncingOverIDSProxy idsProxy].pingTimers removeObjectForKey:identifier];
381 [self sendMessageToKVS:encapsulatedKeychainMessage];
383 //setting next time to send
384 [self updateNextTimeToSendFor5Minutes:ID];
386 [[KeychainSyncingOverIDSProxy idsProxy] persistState];
389 -(void) setMessageTimer:(NSString*)identifier deviceID:(NSString*)ID message:(NSDictionary*)message
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);
394 dispatch_source_set_event_handler(timer, ^{
395 [self ackTimerFired:identifier deviceID:ID];
397 dispatch_resume(timer);
398 //restructure message in flight
402 //set the timer for message id
403 dispatch_async(self.pingQueue, ^{
404 [self.pingTimers setObject:timer forKey:identifier];
407 dispatch_sync(self.dataQueue, ^{
408 [[KeychainSyncingOverIDSProxy idsProxy].messagesInFlight setObject:message forKey:identifier];
410 [[KeychainSyncingOverIDSProxy idsProxy] persistState];
413 //had an immediate error, remove it from messages in flight, and immediately send it over KVS
414 -(void) cleanupAfterHardIDSError:(NSDictionary*)data
416 NSString *messageIdentifier = [data objectForKey:(__bridge NSString*)kIDSMessageUniqueID];
417 NSMutableDictionary * __block messageToSendToKVS = nil;
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];
425 if(!messageToSendToKVS){
426 secnotice("IDS Transport", "no message for identifier: %@", messageIdentifier);
429 secnotice("IDS Transport", "sending over KVS: %@", messageToSendToKVS);
433 //cleanup timer for message
434 dispatch_async(self.pingQueue, ^{
435 dispatch_source_t timer = [[KeychainSyncingOverIDSProxy idsProxy].pingTimers objectForKey:messageIdentifier]; //remove timer
437 dispatch_cancel(timer); //cancel timer
438 [[KeychainSyncingOverIDSProxy idsProxy].pingTimers removeObjectForKey:messageIdentifier];
442 NSDictionary *encapsulatedKeychainMessage = [messageToSendToKVS objectForKey:(__bridge NSString*)kIDSMessageToSendKey];
444 if([encapsulatedKeychainMessage isKindOfClass:[NSDictionary class]]){
445 secnotice("IDS Transport", "Encapsulated message: %@", encapsulatedKeychainMessage);
446 [self sendMessageToKVS:encapsulatedKeychainMessage];
451 -(BOOL) sendIDSMessage:(NSDictionary*)data name:(NSString*) deviceName peer:(NSString*) peerID
455 secerror("Could not send message to peer: %@: IDS delegate uninitialized, can't use IDS to send this message", deviceName);
459 dispatch_async(self.calloutQueue, ^{
461 IDSMessagePriority priority = IDSMessagePriorityHigh;
462 BOOL encryptionOff = YES;
463 NSString *sendersPeerIDKey = [ NSString stringWithUTF8String: kMessageKeySendersPeerID];
465 secnotice("backoff","!!writing these keys to IDS!!: %@", data);
467 NSDictionary *options = @{IDSSendMessageOptionForceEncryptionOffKey : [NSNumber numberWithBool:encryptionOff] };
469 NSMutableDictionary *dataCopy = [NSMutableDictionary dictionaryWithDictionary: data];
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);
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];
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]);
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)];
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));
497 bool result = [self->_service sendMessage:dataCopy toDestinations:destinations priority:priority options:options identifier:&identifier error:&localError ] ;
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));
502 secnotice("IDS Transport","successfully sent to peer:%@, message: %@", deviceName, dataCopy);
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];