]> git.saurik.com Git - apple/security.git/blob - keychain/SecureObjectSync/Regressions/SOSRegressionUtilities.m
Security-59306.11.20.tar.gz
[apple/security.git] / keychain / SecureObjectSync / Regressions / SOSRegressionUtilities.m
1 /*
2 * Copyright (c) 2012-2014 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 // SOSRegressionUtilities.c
26 //
27
28 #include <AssertMacros.h>
29 #include <stdio.h>
30 #include <Security/SecItem.h>
31
32 #include <utilities/SecCFWrappers.h>
33 #include <utilities/debugging.h>
34
35 #include "keychain/SecureObjectSync/SOSAccount.h"
36 #include "keychain/SecureObjectSync/SOSAccountPriv.h"
37 #include "keychain/SecureObjectSync/SOSCircle.h"
38 #include "keychain/SecureObjectSync/SOSInternal.h"
39 #include "keychain/SecureObjectSync/SOSPeerInfoInternal.h"
40
41 #include "keychain/SecureObjectSync/CKBridge/SOSCloudKeychainClient.h"
42 #include "SOSRegressionUtilities.h"
43 #include "keychain/SecureObjectSync/SOSInternal.h"
44
45 #if TARGET_OS_IPHONE
46 #include <MobileGestalt.h>
47 #endif
48
49 static const uint64_t maxTimeToWaitInSeconds = 30ull * NSEC_PER_SEC;
50
51 // MARK: ----- SOS General -----
52
53 const char *cloudKeychainProxyPath = "/System/Library/Frameworks/Security.framework/Resources/CloudKeychainProxy.bundle/CloudKeychainProxy";
54
55 static const char *basecfabsoluteTimeToString(CFAbsoluteTime abstime, CFTimeZoneRef tz)
56 {
57 CFGregorianDate greg = CFAbsoluteTimeGetGregorianDate(abstime, NULL);
58 char str[20];
59 if (19 != snprintf(str, 20, "%4.4d-%2.2d-%2.2d_%2.2d:%2.2d:%2.2d",
60 (int)greg.year, greg.month, greg.day, greg.hour, greg.minute, (int)greg.second))
61 str[0]=0;
62 char *data = (char *)malloc(20);
63 strncpy(data, str, 20);
64 return data;
65 }
66
67 const char *cfabsoluteTimeToString(CFAbsoluteTime abstime)
68 {
69 return basecfabsoluteTimeToString(abstime, NULL);
70 }
71
72 const char *cfabsoluteTimeToStringLocal(CFAbsoluteTime abstime)
73 {
74 // Caller must release using free
75 CFDateFormatterRef formatter = NULL;
76 CFTimeZoneRef tz = NULL;
77 CFLocaleRef locale = NULL;
78 CFDateRef date = NULL;
79 CFStringRef cftime_string = NULL;
80 char *time_string = NULL;
81 char buffer[1024] = {0,};
82 size_t sz;
83
84 require(tz = CFTimeZoneCopySystem(), xit);
85 require(locale = CFLocaleCreate(NULL, CFSTR("en_US")), xit);
86
87 require(formatter = CFDateFormatterCreate(kCFAllocatorDefault, locale, kCFDateFormatterShortStyle, kCFDateFormatterShortStyle), xit);
88 CFDateFormatterSetFormat(formatter, CFSTR("MM/dd/yy HH:mm:ss.SSS zzz"));
89 require(date = CFDateCreate(kCFAllocatorDefault, abstime), xit);
90 require(cftime_string = CFDateFormatterCreateStringWithDate(kCFAllocatorDefault, formatter, date), xit);
91
92 CFStringGetCString(cftime_string, buffer, 1024, kCFStringEncodingUTF8);
93 sz = strnlen(buffer, 1024);
94 time_string = (char *)malloc(sz);
95 strncpy(time_string, buffer, sz+1);
96 xit:
97 CFReleaseSafe(tz);
98 CFReleaseSafe(formatter);
99 CFReleaseSafe(locale);
100 CFReleaseSafe(date);
101 CFReleaseSafe(cftime_string);
102 return time_string;
103 }
104
105 #include <sys/stat.h>
106
107 static int file_exist (const char *filename)
108 {
109 struct stat buffer;
110 return (stat (filename, &buffer) == 0);
111 }
112
113 bool XPCServiceInstalled(void)
114 {
115 return file_exist(cloudKeychainProxyPath);
116 }
117
118 void registerForKVSNotifications(const void *observer, CFStringRef name, CFNotificationCallback callBack)
119 {
120 // observer is basically a context; name may not be null
121 CFNotificationCenterRef center = CFNotificationCenterGetDarwinNotifyCenter();
122 CFNotificationSuspensionBehavior suspensionBehavior = CFNotificationSuspensionBehaviorDeliverImmediately; //ignored?
123 CFNotificationCenterAddObserver(center, observer, callBack, name, NULL, suspensionBehavior);
124 }
125
126 bool testPutObjectInCloudAndSync(CFStringRef key, CFTypeRef object, CFErrorRef *error, dispatch_group_t dgroup, dispatch_queue_t processQueue)
127 {
128 bool result = testPutObjectInCloud(key, object, error, dgroup, processQueue);
129 testSynchronize(processQueue, dgroup);
130
131 return result;
132 }
133
134 bool testPutObjectInCloud(CFStringRef key, CFTypeRef object, CFErrorRef *error, dispatch_group_t dgroup, dispatch_queue_t processQueue)
135 {
136 secnotice("test", "testPutObjectInCloud: key: %@, %@", key, object);
137 CFDictionaryRef objects = CFDictionaryCreateForCFTypes(kCFAllocatorDefault, key, object, NULL);
138 if (objects)
139 {
140 dispatch_group_enter(dgroup);
141 SOSCloudKeychainPutObjectsInCloud(objects, processQueue, ^ (CFDictionaryRef returnedValues, CFErrorRef error)
142 {
143 secnotice("test", "testPutObjectInCloud returned: %@", returnedValues);
144 if (error)
145 {
146 secnotice("test", "testPutObjectInCloud returned: %@", error);
147 CFRelease(error);
148 }
149 dispatch_group_leave(dgroup);
150 });
151 CFRelease(objects);
152 }
153
154 return true;
155 }
156
157 CFTypeRef testGetObjectFromCloud(CFStringRef key, dispatch_queue_t processQueue, dispatch_group_t dgroup)
158 {
159 // TODO: make sure we return NULL, not CFNull
160 secnotice("test", "start");
161 CFMutableArrayRef keysToGet = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
162 CFArrayAppendValue(keysToGet, key);
163
164 __block CFTypeRef object = NULL;
165
166 dispatch_semaphore_t waitSemaphore = dispatch_semaphore_create(0);
167 dispatch_time_t finishTime = dispatch_time(DISPATCH_TIME_NOW, maxTimeToWaitInSeconds);
168
169 dispatch_group_enter(dgroup);
170 SOSCloudKeychainGetObjectsFromCloud(keysToGet, processQueue, ^ (CFDictionaryRef returnedValues, CFErrorRef error)
171 {
172 secnotice("test", "SOSCloudKeychainGetObjectsFromCloud returned: %@", returnedValues);
173 if (returnedValues)
174 {
175 object = (CFTypeRef)CFDictionaryGetValue(returnedValues, key);
176 if (object)
177 CFRetain(object);
178 }
179 if (error)
180 {
181 secerror("SOSCloudKeychainGetObjectsFromCloud returned error: %@", error);
182 // CFRelease(*error);
183 }
184 dispatch_group_leave(dgroup);
185 secnotice("test", "SOSCloudKeychainGetObjectsFromCloud block exit: %@", object);
186 dispatch_semaphore_signal(waitSemaphore);
187 });
188
189 dispatch_semaphore_wait(waitSemaphore, finishTime);
190 if (object && (CFGetTypeID(object) == CFNullGetTypeID())) // return a NULL instead of a CFNull
191 {
192 CFRelease(object);
193 object = NULL;
194 }
195 secnotice("test", "returned: %@", object);
196 return object;
197 }
198
199 CFTypeRef testGetObjectsFromCloud(CFArrayRef keysToGet, dispatch_queue_t processQueue, dispatch_group_t dgroup)
200 {
201 __block CFTypeRef object = NULL;
202
203 dispatch_semaphore_t waitSemaphore = dispatch_semaphore_create(0);
204 dispatch_time_t finishTime = dispatch_time(DISPATCH_TIME_NOW, maxTimeToWaitInSeconds);
205 dispatch_group_enter(dgroup);
206
207 CloudKeychainReplyBlock replyBlock =
208 ^ (CFDictionaryRef returnedValues, CFErrorRef error)
209 {
210 secnotice("test", "SOSCloudKeychainGetObjectsFromCloud returned: %@", returnedValues);
211 object = returnedValues;
212 if (object)
213 CFRetain(object);
214 if (error)
215 {
216 secerror("SOSCloudKeychainGetObjectsFromCloud returned error: %@", error);
217 }
218 dispatch_group_leave(dgroup);
219 secnotice("test", "SOSCloudKeychainGetObjectsFromCloud block exit: %@", object);
220 dispatch_semaphore_signal(waitSemaphore);
221 };
222
223 if (!keysToGet)
224 SOSCloudKeychainGetAllObjectsFromCloud(processQueue, replyBlock);
225 else
226 SOSCloudKeychainGetObjectsFromCloud(keysToGet, processQueue, replyBlock);
227
228 dispatch_semaphore_wait(waitSemaphore, finishTime);
229 if (object && (CFGetTypeID(object) == CFNullGetTypeID())) // return a NULL instead of a CFNull
230 {
231 CFRelease(object);
232 object = NULL;
233 }
234 secnotice("test", "returned: %@", object);
235 return object;
236 }
237
238 bool testSynchronize(dispatch_queue_t processQueue, dispatch_group_t dgroup)
239 {
240 __block bool result = false;
241 dispatch_semaphore_t waitSemaphore = dispatch_semaphore_create(0);
242 dispatch_time_t finishTime = dispatch_time(DISPATCH_TIME_NOW, maxTimeToWaitInSeconds);
243
244 dispatch_group_enter(dgroup);
245
246 SOSCloudKeychainSynchronize(processQueue, ^(CFDictionaryRef returnedValues, CFErrorRef error)
247 {
248 result = true;
249 dispatch_group_leave(dgroup);
250 dispatch_semaphore_signal(waitSemaphore);
251 });
252
253 dispatch_semaphore_wait(waitSemaphore, finishTime);
254 return result;
255 }
256
257 bool testClearAll(dispatch_queue_t processQueue, dispatch_group_t dgroup)
258 {
259 __block bool result = false;
260 dispatch_semaphore_t waitSemaphore = dispatch_semaphore_create(0);
261 dispatch_time_t finishTime = dispatch_time(DISPATCH_TIME_NOW, maxTimeToWaitInSeconds);
262
263 dispatch_group_enter(dgroup);
264
265 secnotice("circleOps", "SOSCloudKeychainClearAll called by testClearAll");
266 SOSCloudKeychainClearAll(processQueue, ^(CFDictionaryRef returnedValues, CFErrorRef error)
267 {
268 result = true;
269 secnotice("test", "SOSCloudKeychainClearAll returned: %@", error);
270 dispatch_group_leave(dgroup);
271 dispatch_semaphore_signal(waitSemaphore);
272 });
273
274 dispatch_semaphore_wait(waitSemaphore, finishTime);
275 secnotice("test", "SOSCloudKeychainClearAll exit");
276 return result;
277 }
278
279 void unregisterFromKVSNotifications(const void *observer)
280 {
281 CFNotificationCenterRemoveEveryObserver(CFNotificationCenterGetDarwinNotifyCenter(), observer);
282 }
283
284 //
285 // MARK: SOSPeerInfo creation helpers
286 //
287
288 CFDictionaryRef SOSCreatePeerGestaltFromName(CFStringRef name)
289 {
290 return CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
291 kPIUserDefinedDeviceNameKey, name,
292 NULL);
293 }
294
295
296 SOSPeerInfoRef SOSCreatePeerInfoFromName(CFStringRef name,
297 SecKeyRef* outSigningKey,
298 SecKeyRef* outOctagonSigningKey,
299 SecKeyRef* outOctagonEncryptionKey,
300 CFErrorRef *error)
301 {
302 SOSPeerInfoRef result = NULL;
303 SecKeyRef publicKey = NULL;
304 SecKeyRef octagonSigningPublicKey = NULL;
305 SecKeyRef octagonEncryptionPublicKey = NULL;
306 CFDictionaryRef gestalt = NULL;
307
308 require(outSigningKey, exit);
309
310 require_quiet(SecError(GeneratePermanentECPair(256, &publicKey, outSigningKey), error, CFSTR("Failed To Create Key")), exit);
311 require_quiet(SecError(GeneratePermanentECPair(384, &octagonSigningPublicKey, outOctagonSigningKey), error, CFSTR("Failed to Create Octagon Signing Key")), exit);
312 require_quiet(SecError(GeneratePermanentECPair(384, &octagonEncryptionPublicKey, outOctagonEncryptionKey), error, CFSTR("Failed to Create Octagon Encryption Key")), exit);
313
314 gestalt = SOSCreatePeerGestaltFromName(name);
315 require(gestalt, exit);
316
317 result = SOSPeerInfoCreate(NULL, gestalt, NULL, *outSigningKey,
318 *outOctagonSigningKey, *outOctagonEncryptionKey, error);
319
320 exit:
321 CFReleaseNull(gestalt);
322 CFReleaseNull(publicKey);
323 CFReleaseNull(octagonSigningPublicKey);
324 CFReleaseNull(octagonEncryptionPublicKey);
325
326 return result;
327 }
328
329 SOSFullPeerInfoRef SOSCreateFullPeerInfoFromName(CFStringRef name,
330 SecKeyRef* outSigningKey,
331 SecKeyRef* outOctagonSigningKey,
332 SecKeyRef* outOctagonEncryptionKey,
333 CFErrorRef *error)
334 {
335 SOSFullPeerInfoRef result = NULL;
336 SecKeyRef publicKey = NULL;
337 CFDictionaryRef gestalt = NULL;
338
339 require(outSigningKey, exit);
340 *outSigningKey = GeneratePermanentFullECKey(256, name, error);
341 require(*outSigningKey, exit);
342
343 require(outOctagonSigningKey, exit);
344 *outOctagonSigningKey = GeneratePermanentFullECKey(384, name, error);
345 require(*outOctagonSigningKey, exit);
346
347 require(outOctagonEncryptionKey, exit);
348 *outOctagonEncryptionKey = GeneratePermanentFullECKey(384, name, error);
349 require(*outOctagonEncryptionKey, exit);
350
351 gestalt = SOSCreatePeerGestaltFromName(name);
352 require(gestalt, exit);
353
354 result = SOSFullPeerInfoCreate(NULL, gestalt,
355 NULL,
356 *outSigningKey,
357 *outOctagonSigningKey,
358 *outOctagonEncryptionKey,
359 error);
360
361 exit:
362 CFReleaseNull(gestalt);
363 CFReleaseNull(publicKey);
364
365 return result;
366 }
367
368 // MARK: ----- MAC Address -----
369
370 /*
371 * Name: GetHardwareAdress
372 *
373 * Parameters: None.
374 *
375 * Returns: Nothing
376 *
377 * Description: Retrieve the hardare address for a specified network interface
378 *
379 */
380
381 #include <stdlib.h>
382 #include <string.h>
383
384 #include <sys/socket.h>
385 #include <netinet/in.h>
386 #include <sys/sysctl.h>
387 #include <net/if.h>
388 #include <net/if_dl.h>
389 #include <net/route.h>
390
391 #include <unistd.h>
392 #include <netdb.h>
393 #include <sys/stat.h>
394
395 static int getHardwareAddress(const char *interfaceName, size_t maxLenAllowed, size_t *outActualLength, char *outHardwareAddress)
396 {
397 char *end;
398 struct if_msghdr *ifm;
399 struct sockaddr_dl *sdl;
400 char *buf;
401 int result = -1;
402 size_t buffSize;
403 int mib[6] = {CTL_NET, AF_ROUTE, 0, AF_INET, NET_RT_IFLIST, 0 };
404
405 buf = 0;
406 *outActualLength = 0;
407 // see how much space is needed
408 require_noerr(result = sysctl(mib, 6, NULL, &buffSize, NULL, 0), xit);
409
410 // allocate the buffer
411 require(buf = malloc(buffSize), xit);
412
413 // get the interface info
414 require_noerr(result = sysctl(mib, 6, buf, &buffSize, NULL, 0), xit);
415
416 ifm = (struct if_msghdr *) buf;
417 end = buf + buffSize;
418 do
419 {
420 if (ifm->ifm_type == RTM_IFINFO) // should always be true
421 {
422 sdl = (struct sockaddr_dl *) (ifm + 1);
423 if ( sdl->sdl_nlen == strlen( interfaceName ) && ( bcmp( sdl->sdl_data, interfaceName, sdl->sdl_nlen ) == 0 ) )
424 {
425 if ( sdl->sdl_alen > 0 )
426 {
427 size_t hardwareLen;
428
429 result = 0; // indicate found the interface
430 hardwareLen = sdl->sdl_alen;
431 if ( hardwareLen > maxLenAllowed )
432 {
433 hardwareLen = maxLenAllowed;
434 result = -2; // indicate truncation of the address
435 }
436 memcpy( outHardwareAddress, sdl->sdl_data + sdl->sdl_nlen, hardwareLen );
437 *outActualLength = hardwareLen;
438 break;
439
440 }
441 }
442 }
443 ifm = (struct if_msghdr *) ((char*)ifm + ifm->ifm_msglen);
444 } while ( (char*)ifm < end );
445
446 xit:
447 if (buf)
448 free(buf);
449
450 return result;
451 }
452
453 // MARK: ----- cloudTransportTests -----
454
455 CFStringRef myMacAddress(void)
456 {
457 // 6 bytes, no ":"s
458 CFStringRef result = NULL;
459 const char *interfaceName = "en0";
460 size_t maxLenAllowed = 1024;
461 size_t outActualLength = 0;
462 char outHardwareAddress[1024];
463
464 require_noerr(getHardwareAddress(interfaceName, maxLenAllowed, &outActualLength, outHardwareAddress), xit);
465 require(outActualLength==6, xit);
466 unsigned char buf[32]={0,};
467
468 unsigned char *ps = (unsigned char *)buf;
469 unsigned char *pa = (unsigned char *)outHardwareAddress;
470 for (int ix = 0; ix < 6; ix++, pa++)
471 ps += sprintf((char *)ps, "%02x", *pa);
472
473 result = CFStringCreateWithCString(kCFAllocatorDefault, (const char *)buf, kCFStringEncodingUTF8);
474
475 xit:
476 return result;
477 }