2 // SOSTransportMessageIDS.c
6 #include <Security/SecBasePriv.h>
7 #include <Security/SecureObjectSync/SOSTransport.h>
8 #import <Security/SecureObjectSync/SOSTransportMessage.h>
9 #import <Security/SecureObjectSync/SOSAccountPriv.h>
10 #include <Security/SecureObjectSync/SOSKVSKeys.h>
11 #include <Security/SecureObjectSync/SOSPeerInfoV2.h>
13 #include <SOSCloudCircleServer.h>
14 #include <Security/SecureObjectSync/SOSAccountPriv.h>
15 #include <Security/SecureObjectSync/SOSTransportMessageIDS.h>
17 #include <utilities/SecCFWrappers.h>
18 #include <SOSInternal.h>
19 #include <AssertMacros.h>
21 #include <SOSCircle/CKBridge/SOSCloudKeychainClient.h>
22 #include <SOSCircle/CKBridge/SOSCloudKeychainConstants.h>
23 #include <Security/SecureObjectSync/SOSInternal.h>
24 #import "Security/SecureObjectSync/SOSAccountTrustClassic.h"
26 #define IDS "IDS transport"
28 @implementation SOSMessageIDS
30 @synthesize useFragmentation = useFragmentation;
32 -(CFIndex) SOSTransportMessageGetTransportType
37 -(void) SOSTransportMessageIDSSetFragmentationPreference:(SOSMessageIDS*) transport pref:(CFBooleanRef) preference
39 useFragmentation = preference;
42 -(CFBooleanRef) SOSTransportMessageIDSGetFragmentationPreference:(SOSMessageIDS*) transport
44 return useFragmentation;
47 -(id) initWithAcount:(SOSAccount*)acct circleName:(CFStringRef)name
52 self.useFragmentation = kCFBooleanTrue;
54 self.circleName = [[NSString alloc]initWithString:(__bridge NSString*)name];
55 [self SOSTransportMessageIDSGetIDSDeviceID:account];
56 SOSRegisterTransportMessage((SOSMessage*)self);
62 -(CFDictionaryRef) CF_RETURNS_RETAINED SOSTransportMessageHandlePeerMessageReturnsHandledCopy:(SOSMessage*) transport peerMessages:(CFMutableDictionaryRef) circle_peer_messages_table err:(CFErrorRef *)error
64 return CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
67 static HandleIDSMessageReason checkMessageValidity(SOSAccount* account, CFStringRef fromDeviceID, CFStringRef fromPeerID, CFStringRef *peerID, SOSPeerInfoRef *theirPeerInfo){
68 SOSAccountTrustClassic *trust = account.trust;
69 __block HandleIDSMessageReason reason = kHandleIDSMessageDontHandle;
71 SOSCircleForEachPeer(trust.trustedCircle, ^(SOSPeerInfoRef peer) {
72 CFStringRef deviceID = SOSPeerInfoCopyDeviceID(peer);
73 CFStringRef pID = SOSPeerInfoGetPeerID(peer);
75 if( deviceID && pID && fromPeerID && fromDeviceID && CFStringGetLength(fromPeerID) != 0 ){
76 if(CFStringCompare(pID, fromPeerID, 0) == 0){
77 if(CFStringGetLength(deviceID) == 0){
78 secnotice("ids transport", "device ID was empty in the peer list, holding on to message");
79 CFReleaseNull(deviceID);
80 reason = kHandleIDSMessageNotReady;
83 else if(CFStringCompare(fromDeviceID, deviceID, 0) != 0){ //IDSids do not match, ghost
84 reason = kHandleIDSmessageDeviceIDMismatch;
85 CFReleaseNull(deviceID);
88 else if(CFStringCompare(deviceID, fromDeviceID, 0) == 0){
90 *theirPeerInfo = peer;
91 CFReleaseNull(deviceID);
92 reason = kHandleIDSMessageSuccess;
97 CFReleaseNull(deviceID);
103 -(HandleIDSMessageReason) SOSTransportMessageIDSHandleMessage:(SOSAccount*)acct m:(CFDictionaryRef) message err:(CFErrorRef *)error
105 secnotice("IDS Transport", "SOSTransportMessageIDSHandleMessage!");
107 CFStringRef dataKey = CFStringCreateWithCString(kCFAllocatorDefault, kMessageKeyIDSDataMessage, kCFStringEncodingASCII);
108 CFStringRef deviceIDKey = CFStringCreateWithCString(kCFAllocatorDefault, kMessageKeyDeviceID, kCFStringEncodingASCII);
109 CFStringRef sendersPeerIDKey = CFStringCreateWithCString(kCFAllocatorDefault, kMessageKeySendersPeerID, kCFStringEncodingASCII);
110 CFStringRef ourPeerIdKey = CFStringCreateWithCString(kCFAllocatorDefault, kMessageKeyPeerID, kCFStringEncodingASCII);
112 HandleIDSMessageReason result = kHandleIDSMessageSuccess;
114 CFDataRef messageData = asData(CFDictionaryGetValue(message, dataKey), NULL);
115 __block CFStringRef fromDeviceID = asString(CFDictionaryGetValue(message, deviceIDKey), NULL);
116 __block CFStringRef fromPeerID = (CFStringRef)CFDictionaryGetValue(message, sendersPeerIDKey);
117 CFStringRef ourPeerID = asString(CFDictionaryGetValue(message, ourPeerIdKey), NULL);
119 CFStringRef peerID = NULL;
120 SOSPeerInfoRef theirPeer = NULL;
122 require_action_quiet(fromDeviceID, exit, result = kHandleIDSMessageDontHandle);
123 require_action_quiet(fromPeerID, exit, result = kHandleIDSMessageDontHandle);
124 require_action_quiet(messageData && CFDataGetLength(messageData) != 0, exit, result = kHandleIDSMessageDontHandle);
125 require_action_quiet(SOSAccountHasFullPeerInfo(account, error), exit, result = kHandleIDSMessageNotReady);
126 require_action_quiet(ourPeerID && [account.peerID isEqual: (__bridge NSString*) ourPeerID], exit, result = kHandleIDSMessageDontHandle; secnotice("IDS Transport","ignoring message for: %@", ourPeerID));
128 require_quiet((result = checkMessageValidity( account, fromDeviceID, fromPeerID, &peerID, &theirPeer)) == kHandleIDSMessageSuccess, exit);
130 if ([account.ids_message_transport SOSTransportMessageHandlePeerMessage:account.ids_message_transport id:peerID cm:messageData err:error]) {
131 CFMutableDictionaryRef peersToSyncWith = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
132 CFMutableSetRef peerIDs = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
133 CFSetAddValue(peerIDs, peerID);
134 SOSAccountTrustClassic* trust = account.trust;
135 //sync using fragmentation?
136 if(SOSPeerInfoShouldUseIDSMessageFragmentation(trust.peerInfo, theirPeer)){
137 //set useFragmentation bit
138 [account.ids_message_transport SOSTransportMessageIDSSetFragmentationPreference:account.ids_message_transport pref: kCFBooleanTrue];
141 [account.ids_message_transport SOSTransportMessageIDSSetFragmentationPreference:account.ids_message_transport pref: kCFBooleanFalse];
144 if(![account.ids_message_transport SOSTransportMessageSyncWithPeers:account.ids_message_transport p:peerIDs err:error]){
145 secerror("SOSTransportMessageIDSHandleMessage Could not sync with all peers: %@", *error);
147 secnotice("IDS Transport", "Synced with all peers!");
150 CFReleaseNull(peersToSyncWith);
151 CFReleaseNull(peerIDs);
153 if(error && *error != NULL){
154 CFStringRef errorMessage = CFErrorCopyDescription(*error);
155 if (-25308 == CFErrorGetCode(*error)) { // tell KeychainSyncingOverIDSProxy to call us back when device unlocks
156 result = kHandleIDSMessageLocked;
157 }else{ //else drop it, couldn't handle the message
158 result = kHandleIDSMessageDontHandle;
160 secerror("IDS Transport Could not handle message: %@, %@", messageData, *error);
161 CFReleaseNull(errorMessage);
164 else{ //no error but failed? drop it, log message
165 secerror("IDS Transport Could not handle message: %@", messageData);
166 result = kHandleIDSMessageDontHandle;
172 CFReleaseNull(ourPeerIdKey);
173 CFReleaseNull(sendersPeerIDKey);
174 CFReleaseNull(deviceIDKey);
175 CFReleaseNull(dataKey);
180 static bool sendToPeer(SOSMessageIDS* transport, bool shouldUseAckModel, CFStringRef circleName, CFStringRef deviceID, CFStringRef peerID,CFDictionaryRef message, CFErrorRef *error)
182 __block bool success = false;
183 CFStringRef errorMessage = NULL;
184 CFDictionaryRef userInfo;
185 CFStringRef operation = NULL;
186 CFDataRef operationData = NULL;
187 CFMutableDataRef mutableData = NULL;
188 SOSAccount* account = [transport SOSTransportMessageGetAccount];
189 CFStringRef ourPeerID = SOSPeerInfoGetPeerID(account.peerInfo);
190 CFStringRef operationToString = NULL;
192 CFDictionaryRef messagetoSend = NULL;
194 if(deviceID == NULL || CFStringGetLength(deviceID) == 0){
195 errorMessage = CFSTR("Need an IDS Device ID to sync");
196 userInfo = CFDictionaryCreateForCFTypes(kCFAllocatorDefault, kCFErrorLocalizedDescriptionKey, errorMessage, NULL);
198 *error =CFErrorCreate(kCFAllocatorDefault, CFSTR("com.apple.security.ids.error"), kSecIDSErrorNoDeviceID, userInfo);
199 secerror("%@", *error);
201 CFReleaseNull(messagetoSend);
202 CFReleaseNull(operation);
203 CFReleaseNull(operationData);
204 CFReleaseNull(mutableData);
205 CFReleaseNull(userInfo);
206 CFReleaseNull(operationToString);
211 if(CFDictionaryGetValue(message, kIDSOperationType) == NULL && [transport SOSTransportMessageIDSGetFragmentationPreference:transport] == kCFBooleanTrue){
212 //handle a keychain data blob using fragmentation!
213 secnotice("IDS Transport","sendToPeer: using fragmentation!");
215 operationToString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%d"), kIDSKeychainSyncIDSFragmentation);
216 messagetoSend = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
217 kIDSOperationType, operationToString,
218 kIDSMessageRecipientDeviceID, deviceID,
219 kIDSMessageRecipientPeerID, peerID,
220 kIDSMessageUsesAckModel, (shouldUseAckModel ? CFSTR("YES") : CFSTR("NO")),
221 kIDSMessageToSendKey, message,
224 else{ //otherhandle handle the test message without fragmentation
225 secnotice("IDS Transport","sendToPeer: not going to fragment message");
227 CFMutableDictionaryRef annotatedMessage = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, message);
228 CFDictionaryAddValue(annotatedMessage, kIDSMessageRecipientPeerID, peerID);
229 CFDictionaryAddValue(annotatedMessage, kIDSMessageRecipientDeviceID, deviceID);
230 CFDictionaryAddValue(annotatedMessage, kIDSMessageUsesAckModel, (shouldUseAckModel ? CFSTR("YES") : CFSTR("NO")));
231 CFTransferRetained(messagetoSend, annotatedMessage);
232 CFReleaseNull(annotatedMessage);
235 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
237 secnotice("IDS Transport", "Starting");
239 SOSCloudKeychainSendIDSMessage(messagetoSend, deviceID, ourPeerID, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), [transport SOSTransportMessageIDSGetFragmentationPreference:transport], ^(CFDictionaryRef returnedValues, CFErrorRef sync_error) {
240 success = (sync_error == NULL);
241 if (sync_error && error) {
242 CFRetainAssign(*error, sync_error);
245 dispatch_semaphore_signal(wait_for);
248 if (dispatch_semaphore_wait(wait_for, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 2)) != 0) {
249 secerror("IDS Transport: timed out waiting for message send to complete");
254 secerror("IDS Transport: Failed to send message to peer! %@", *error);
256 secerror("IDS Transport: Failed to send message to peer");
259 secnotice("IDS Transport", "Sent message to peer!");
262 CFReleaseNull(messagetoSend);
263 CFReleaseNull(operation);
264 CFReleaseNull(operationData);
265 CFReleaseNull(mutableData);
266 CFReleaseNull(operationToString);
271 -(bool) SOSTransportMessageSyncWithPeers:(SOSMessageIDS*) transport p:(CFSetRef) peers err:(CFErrorRef *)error
273 // Each entry is keyed by circle name and contains a list of peerIDs
274 __block bool result = true;
276 CFSetForEach(peers, ^(const void *value) {
277 CFStringRef peerID = asString(value, NULL);
279 result &= [transport SOSTransportMessageSendMessageIfNeeded:transport id:(__bridge CFStringRef)(transport.circleName) pID:peerID err:error];
285 -(bool) SOSTransportMessageSendMessages:(SOSMessageIDS*) transport pm:(CFDictionaryRef) peer_messages err:(CFErrorRef *)error
287 __block bool result = true;
289 SOSPeerInfoRef myPeer = transport->account.peerInfo;
290 CFStringRef myID = SOSPeerInfoGetPeerID(myPeer);
294 CFDictionaryForEach(peer_messages, ^(const void *key, const void *value) {
295 CFErrorRef error = NULL;
297 SOSPeerInfoRef peer = NULL;
298 CFStringRef deviceID = NULL;
299 CFDictionaryRef message = NULL;
301 CFStringRef peerID = asString(key, &error);
302 require_quiet(peerID, skip);
303 require_quiet(!CFEqualSafe(myID, key), skip);
305 message = CFRetainSafe(asDictionary(value, &error));
306 if (message == NULL) {
307 // If it's not a data, return the error
308 CFDataRef messageData = asData(value, NULL);
310 CFReleaseNull(error);
311 message = CFDictionaryCreateForCFTypes(kCFAllocatorDefault, peerID, messageData, NULL);
314 require_quiet(message, skip);
316 peer = SOSAccountCopyPeerWithID(transport->account, peerID, &error);
317 require_quiet(peer, skip);
319 deviceID = SOSPeerInfoCopyDeviceID(peer);
320 require_action_quiet(deviceID, skip, SOSErrorCreate(kSOSErrorSendFailure, &error, NULL, CFSTR("No IDS ID")));
322 [transport SOSTransportMessageIDSSetFragmentationPreference:transport
323 pref:SOSPeerInfoShouldUseIDSMessageFragmentation(myPeer, peer) ? kCFBooleanTrue : kCFBooleanFalse];
324 bool shouldUseAckModel = SOSPeerInfoShouldUseACKModel(myPeer, peer);
326 result &= sendToPeer(transport, shouldUseAckModel, (__bridge CFStringRef)(transport.circleName), deviceID, peerID, message, &error);
330 secerror("Failed to sync to %@ over IDS: %@", peerID, error);
334 CFReleaseNull(deviceID);
335 CFReleaseNull(message);
337 CFReleaseNull(error);
344 -(bool) SOSTransportMessageFlushChanges:(SOSMessageIDS*) transport err:(CFErrorRef *)error
349 -(bool) SOSTransportMessageCleanupAfterPeerMessages:(SOSMessageIDS*) transport peers:(CFDictionaryRef) peers err:(CFErrorRef*) error
354 -(bool) SOSTransportMessageIDSGetIDSDeviceID:(SOSAccount*)acct
356 SOSAccountTrustClassic* trust = acct.trust;
357 CFStringRef deviceID = SOSPeerInfoCopyDeviceID(trust.peerInfo);
358 bool hasDeviceID = deviceID != NULL && CFStringGetLength(deviceID) != 0;
359 CFReleaseNull(deviceID);
362 SOSCloudKeychainGetIDSDeviceID(^(CFDictionaryRef returnedValues, CFErrorRef sync_error){
363 bool success = (sync_error == NULL);
365 secerror("Could not ask KeychainSyncingOverIDSProxy for Device ID: %@", sync_error);
368 secnotice("IDS Transport", "Successfully attempting to retrieve the IDS Device ID");