]> git.saurik.com Git - apple/security.git/blob - KeychainCircle/Tests/KCPairingTest.m
Security-58286.200.222.tar.gz
[apple/security.git] / KeychainCircle / Tests / KCPairingTest.m
1 //
2 // SecurityPairing.m
3 // Security_ios
4 //
5 // Created by Love Hörnquist Åstrand on 2017-02-28.
6 //
7
8 #import <Foundation/Foundation.h>
9 #import <Security/Security.h>
10 #import <Security/SecKeyPriv.h>
11 #import <Security/SecItemPriv.h>
12 #import <Security/SecureObjectSync/SOSAccount.h>
13 #import <Security/SecureObjectSync/SOSAccountPriv.h>
14 #import <Security/SecureObjectSync/SOSCircle.h>
15 #import <KeychainCircle/KeychainCircle.h>
16 #import <XCTest/XCTest.h>
17 #import "SecCFWrappers.h"
18 #import "SOSRegressionUtilities.h"
19
20 @interface FakeNSXPCConnection : NSObject
21 - (instancetype) initWithControl:(id<SOSControlProtocol>)control;
22 - (id)remoteObjectProxyWithErrorHandler:(void(^)(NSError * _Nonnull error))failureHandler;
23 @end
24 @interface FakeNSXPCConnection ()
25 @property id<SOSControlProtocol> control;
26 @end
27 @implementation FakeNSXPCConnection
28 - (instancetype) initWithControl:(id<SOSControlProtocol>)control
29 {
30 self = [super init];
31 if (self) {
32 _control = control;
33 }
34 return self;
35 }
36 - (id)remoteObjectProxyWithErrorHandler:(void(^)(NSError * _Nonnull error))failureHandler
37 {
38 (void)failureHandler;
39 return _control;
40 }
41 @end
42
43
44 @interface KCPairingTest : XCTestCase
45
46 @end
47
48 @interface FCPairingFakeSOSControl : NSObject <SOSControlProtocol>
49 @property (assign) SecKeyRef accountPrivateKey;
50 @property (assign) SecKeyRef accountPublicKey;
51 @property (assign) SecKeyRef deviceKey;
52 @property (assign) SecKeyRef octagonSigningKey;
53 @property (assign) SecKeyRef octagonEncryptionKey;
54 @property (assign) SOSCircleRef circle;
55 @property (assign) SOSFullPeerInfoRef fullPeerInfo;
56 @property (assign) bool application;
57 @end
58
59 @implementation FCPairingFakeSOSControl
60
61 - (instancetype)initWithRandomAccountKey:(bool)randomAccountKey circle:(SOSCircleRef)circle
62 {
63 if ((self = [super init])) {
64 SecKeyRef publicKey = NULL;
65 NSDictionary* parameters = @{
66 (__bridge NSString*)kSecAttrKeyType:(__bridge NSString*) kSecAttrKeyTypeEC,
67 (__bridge NSString*)kSecAttrKeySizeInBits: @(256),
68 (__bridge NSString*)kSecAttrNoLegacy : @YES,
69 (__bridge NSString*)kSecAttrAccessible : (__bridge id)kSecAttrAccessibleAfterFirstUnlock,
70 (__bridge id)kSecPrivateKeyAttrs : @{
71 (__bridge NSString*)kSecAttrLabel : @"delete me test case - private",
72 (__bridge NSString*)kSecAttrIsPermanent : @YES,
73 (__bridge NSString*)kSecAttrAccessible : (__bridge id)kSecAttrAccessibleAfterFirstUnlock,
74 },
75 (__bridge id)kSecPublicKeyAttrs : @{
76 (__bridge NSString*)kSecAttrLabel : @"delete me test case - public",
77 (__bridge NSString*)kSecAttrAccessible : (__bridge id)kSecAttrAccessibleAfterFirstUnlock,
78 }
79 };
80 if(SecKeyGeneratePair((__bridge CFDictionaryRef)parameters, &publicKey, &_deviceKey) != 0) {
81 NSLog(@"failed to create device key");
82 return nil;
83 }
84 CFReleaseNull(publicKey);
85
86 NSMutableDictionary* octagonParameters = [parameters mutableCopy];
87 octagonParameters[(__bridge NSString*)kSecAttrKeySizeInBits] = @(384);
88 if(SecKeyGeneratePair((__bridge CFDictionaryRef)octagonParameters, &publicKey, &_octagonSigningKey) != 0) {
89 NSLog(@"failed to create octagon signing key");
90 return nil;
91 }
92 CFReleaseNull(publicKey);
93
94 if(SecKeyGeneratePair((__bridge CFDictionaryRef)octagonParameters, &publicKey, &_octagonEncryptionKey) != 0) {
95 NSLog(@"failed to create octagon signing key");
96 return nil;
97 }
98 CFReleaseNull(publicKey);
99
100
101 _circle = (SOSCircleRef)CFRetain(circle);
102
103 CFErrorRef error = NULL;
104
105 CFDictionaryRef gestalt = (__bridge CFDictionaryRef)@{
106 @"ComputerName" : @"name",
107 };
108
109 _fullPeerInfo = SOSFullPeerInfoCreate(NULL, gestalt, NULL, _deviceKey, _octagonSigningKey, _octagonEncryptionKey, &error);
110 CFReleaseNull(error);
111
112 if (randomAccountKey) {
113
114 NSDictionary* accountParams = @{
115 (__bridge NSString*)kSecAttrKeyType:(__bridge NSString*) kSecAttrKeyTypeEC,
116 (__bridge NSString*)kSecAttrKeySizeInBits: @(256),
117 (__bridge NSString*)kSecAttrNoLegacy : @YES,
118 (__bridge NSString*)kSecAttrAccessible : (__bridge id)kSecAttrAccessibleAfterFirstUnlock,
119 };
120
121 if(SecKeyGeneratePair((__bridge CFDictionaryRef)accountParams, &publicKey, &_accountPrivateKey) != 0) {
122 NSLog(@"failed to create account signing key");
123 return nil;
124 }
125 CFReleaseNull(publicKey);
126
127 _accountPublicKey = SecKeyCopyPublicKey(_accountPrivateKey);
128
129 [self signApplicationIfNeeded];
130 }
131 }
132 return self;
133 }
134
135 - (void)dealloc
136 {
137 if (_accountPrivateKey) {
138 SecItemDelete((__bridge CFTypeRef)@{ (__bridge id)kSecValueRef : (__bridge id)_accountPrivateKey });
139 CFReleaseNull(_accountPrivateKey);
140 }
141 if (_deviceKey) {
142 SecItemDelete((__bridge CFTypeRef)@{ (__bridge id)kSecValueRef : (__bridge id)_deviceKey });
143 CFReleaseNull(_deviceKey);
144 }
145 if (_octagonSigningKey) {
146 SecItemDelete((__bridge CFTypeRef)@{ (__bridge id)kSecValueRef : (__bridge id)_octagonSigningKey });
147 CFReleaseNull(_octagonSigningKey);
148 }
149 if (_octagonEncryptionKey) {
150 SecItemDelete((__bridge CFTypeRef)@{ (__bridge id)kSecValueRef : (__bridge id)_octagonEncryptionKey });
151 CFReleaseNull(_octagonEncryptionKey);
152 }
153 CFReleaseNull(_circle);
154 CFReleaseNull(_fullPeerInfo);
155 }
156
157 - (SOSPeerInfoRef)peerInfo
158 {
159 return SOSFullPeerInfoGetPeerInfo(_fullPeerInfo);
160 }
161
162 - (void)signApplicationIfNeeded
163 {
164 CFErrorRef error = NULL;
165
166 _application = SOSFullPeerInfoPromoteToApplication(_fullPeerInfo, _accountPrivateKey, &error);
167 if (!_application)
168 abort();
169 }
170
171 - (void)initialSyncCredentials:(uint32_t)flags complete:(void (^)(NSArray *, NSError *))complete
172 {
173 complete(@[], NULL);
174 }
175
176 - (void)importInitialSyncCredentials:(NSArray *)items complete:(void (^)(bool success, NSError *))complete
177 {
178 complete(true, NULL);
179 }
180
181 - (void)triggerSync:(NSArray<NSString *> *)peers complete:(void(^)(bool success, NSError *))complete
182 {
183 complete(true, NULL);
184 }
185
186 //MARK - FCPairingFakeSOSControl SOSControlProtocol
187
188 - (void)userPublicKey:(void ((^))(BOOL trusted, NSData *spki, NSError *error))complete
189 {
190 complete(false, NULL, NULL);
191 }
192
193 - (void)performanceCounters:(void(^)(NSDictionary <NSString *, NSNumber *> *))complete
194 {
195 complete(@{});
196 }
197 - (void)kvsPerformanceCounters:(void(^)(NSDictionary <NSString *, NSNumber *> *))complete
198 {
199 complete(@{});
200 }
201
202 - (void)rateLimitingPerformanceCounters:(void(^)(NSDictionary <NSString *, NSString *> *))complete
203 {
204 complete(@{});
205 }
206 - (void)stashedCredentialPublicKey:(void(^)(NSData *, NSError *error))complete
207 {
208 NSData *publicKey = NULL;
209 NSError *error = NULL;
210 if (self.accountPrivateKey) {
211 publicKey = CFBridgingRelease(SecKeyCopySubjectPublicKeyInfo(self.accountPrivateKey));
212 } else {
213 error = [NSError errorWithDomain:@"FCPairingFakeSOSControl" code:2 userInfo:NULL];
214 }
215 complete(publicKey, error);
216 }
217
218 - (void)assertStashedAccountCredential:(void(^)(BOOL result, NSError *error))complete
219 {
220 complete(self.accountPrivateKey != NULL, NULL);
221 }
222
223 - (void)validatedStashedAccountCredential:(void(^)(NSData *credential, NSError *error))complete
224 {
225 NSData *key = NULL;
226 CFErrorRef error = NULL;
227 if (self.accountPrivateKey) {
228 key = CFBridgingRelease(SecKeyCopyExternalRepresentation(self.accountPrivateKey, &error));
229 } else {
230 error = (CFErrorRef)CFBridgingRetain([NSError errorWithDomain:@"FCPairingFakeSOSControl" code:1 userInfo:NULL]);
231 }
232 complete(key, (__bridge NSError *)error);
233 CFReleaseNull(error);
234 }
235
236 - (void)stashAccountCredential:(NSData *)credential complete:(void(^)(bool success, NSError *error))complete
237 {
238 SecKeyRef accountPrivateKey = NULL;
239 CFErrorRef error = NULL;
240 NSDictionary *attributes = @{
241 (__bridge id)kSecAttrKeyClass : (__bridge id)kSecAttrKeyClassPrivate,
242 (__bridge id)kSecAttrKeyType : (__bridge id)kSecAttrKeyTypeEC,
243 };
244
245 accountPrivateKey = SecKeyCreateWithData((__bridge CFDataRef)credential, (__bridge CFDictionaryRef)attributes, &error);
246 if (accountPrivateKey == NULL) {
247 complete(false, (__bridge NSError *)error);
248 CFReleaseNull(error);
249 return;
250 }
251
252 _accountPrivateKey = accountPrivateKey;
253 _accountPublicKey = SecKeyCopyPublicKey(_accountPrivateKey);
254
255 [self signApplicationIfNeeded];
256
257 complete(true, NULL);
258 }
259
260 - (void)myPeerInfo:(void(^)(NSData *application, NSError *error))complete
261 {
262 CFErrorRef error = NULL;
263
264 [self signApplicationIfNeeded];
265
266 NSData *application = CFBridgingRelease(SOSPeerInfoCopyEncodedData([self peerInfo], NULL, &error));
267 complete(application, (__bridge NSError *)error);
268
269 CFReleaseNull(error);
270 }
271
272 - (void)circleJoiningBlob:(NSData *)applicantData complete:(void (^)(NSData *blob, NSError *))complete
273 {
274 CFErrorRef error = NULL;
275 CFDataRef signature = NULL;
276 SOSCircleRef prunedCircle = SOSCircleCopyCircle(NULL, _circle, &error);
277 (void)SOSCirclePreGenerationSign(prunedCircle, _accountPublicKey, &error);
278
279 SOSGenCountRef gencount = SOSGenerationIncrementAndCreate(SOSCircleGetGeneration(prunedCircle));
280 if (gencount == NULL)
281 abort();
282
283
284 SOSPeerInfoRef applicant = SOSPeerInfoCreateFromData(NULL, &error, (__bridge CFDataRef)applicantData);
285 if (applicant == NULL)
286 abort();
287
288 signature = SOSCircleCopyNextGenSignatureWithPeerAdded(prunedCircle, applicant, _deviceKey, &error);
289 if(applicant) {
290 CFRelease(applicant);
291 applicant = NULL;
292 }
293
294 NSData *pbblob = CFBridgingRelease(SOSPiggyBackBlobCopyEncodedData(gencount, _deviceKey, signature, &error));
295
296 CFReleaseNull(signature);
297 CFReleaseNull(gencount);
298 CFReleaseNull(prunedCircle);
299
300 complete(pbblob, NULL);
301 }
302
303 - (void)joinCircleWithBlob:(NSData *)blob version:(PiggyBackProtocolVersion)version complete:(void (^)(bool success, NSError *))complete
304 {
305 SOSGenCountRef gencount = NULL;
306 SecKeyRef pubKey = NULL;
307 CFDataRef signature = NULL;
308 CFErrorRef error = NULL;
309 bool setInitialSyncTimeoutToV0 = false;
310
311 if (!SOSPiggyBackBlobCreateFromData(&gencount, &pubKey, &signature, (__bridge CFDataRef)blob, kPiggyV1, &setInitialSyncTimeoutToV0, &error)) {
312 complete(true, (__bridge NSError *)error);
313 CFReleaseNull(error);
314 return;
315 }
316
317 (void)SOSCircleAcceptPeerFromHSA2(_circle,
318 _accountPrivateKey,
319 gencount,
320 pubKey,
321 signature,
322 _fullPeerInfo,
323 &error);
324
325 CFReleaseNull(gencount);
326 CFReleaseNull(pubKey);
327 CFReleaseNull(signature);
328
329 complete(true, (__bridge NSError *)error);
330
331 CFReleaseNull(error);
332
333 }
334
335 - (void)getWatchdogParameters:(void (^)(NSDictionary*, NSError*))complete
336 {
337 // intentionally left blank
338 // these are used by the security/2 tool and are only declared here to make the compiler happy about conforming the protocol we shoved the methods into
339 }
340
341
342 - (void)setWatchdogParmeters:(NSDictionary*)parameters complete:(void (^)(NSError*))complete
343 {
344 // intentionally left blank
345 // these are used by the security/2 tool and are only declared here to make the compiler happy about conforming the protocol we shoved the methods into
346 }
347 @end
348
349 @implementation KCPairingTest
350
351 - (void)testSecPairBasicTest
352 {
353 if (![KCPairingChannel isSupportedPlatform]) {
354 return;
355 }
356
357 bool sp1compete = false, sp2compete = false;
358 NSData *sp1data = NULL;
359 NSData *sp2data = NULL;
360 SOSCircleRef circle = NULL;
361 unsigned count = 0;
362 CFErrorRef cferror = NULL;
363 KCPairingChannel *sp1, *sp2;
364
365 circle = SOSCircleCreate(NULL, CFSTR("TEST DOMAIN"), NULL);
366 XCTAssert(circle, "circle");
367
368 FCPairingFakeSOSControl *fc1 = [[FCPairingFakeSOSControl alloc] initWithRandomAccountKey:false circle:circle];
369 XCTAssert(fc1, "create fake soscontrol 1");
370
371 FCPairingFakeSOSControl *fc2 = [[FCPairingFakeSOSControl alloc] initWithRandomAccountKey:true circle:circle];
372 XCTAssert(fc2, "create fake soscontrol 2");
373
374
375 XCTAssert(SOSCircleRequestAdmission(circle, fc2.accountPrivateKey, fc2.fullPeerInfo, &cferror), "SOSCircleRequestAdmission: %@", cferror);
376 CFReleaseNull(cferror);
377
378 XCTAssert(SOSCircleAcceptRequest(circle, fc2.accountPrivateKey, fc2.fullPeerInfo, [fc2 peerInfo], &cferror), "SOSCircleAcceptRequest device 1: %@", cferror);
379 CFReleaseNull(cferror);
380
381 XCTAssert(SOSCircleHasPeer(circle, [fc2 peerInfo], &cferror), "HasPeer 2: %@", cferror);
382 CFReleaseNull(cferror);
383
384
385 sp1 = [KCPairingChannel pairingChannelInitiator:NULL];
386 [sp1 setXPCConnectionObject:(NSXPCConnection *)[[FakeNSXPCConnection alloc] initWithControl:fc1]];
387
388 sp2 = [KCPairingChannel pairingChannelAcceptor:NULL];
389 [sp2 setXPCConnectionObject:(NSXPCConnection *)[[FakeNSXPCConnection alloc] initWithControl:fc2]] ;
390
391 while(1) {
392 NSError *error = NULL;
393
394 sp1data = [sp1 exchangePacket:sp2data complete:&sp1compete error:&error];
395
396 if (sp1compete && sp2compete) {
397 XCTAssert(sp1data == NULL, "sp1 done, yet there is data");
398 break;
399 }
400 XCTAssert(!sp2compete, "sp2 completed w/o sp1");
401
402 XCTAssert(sp1data != NULL, "sp1 not done, yet there is no data: %@", error);
403 if (sp1data == NULL)
404 break;
405
406 /* send sp1data to peer : BOB CHANNEL HERE */
407
408 sp2data = [sp2 exchangePacket:sp1data complete:&sp2compete error:&error];
409 XCTAssert(sp2data != NULL, "sp2 didn't return data: %@", error);
410 if (sp2data == NULL)
411 break;
412
413 if (sp1compete && sp2compete)
414 break;
415
416 XCTAssert(!sp1compete, "sp2 completed w/o sp1");
417
418 count++;
419 if (count > 10)
420 abort();
421 };
422
423 XCTAssert(sp1compete && sp2compete, "both parties not completed");
424
425 XCTAssert(fc1.accountPrivateKey, "no accountPrivateKey in fc1");
426 XCTAssert(fc2.accountPrivateKey, "no accountPrivateKey in fc2");
427 XCTAssert(CFEqualSafe(fc1.accountPrivateKey, fc2.accountPrivateKey), "no accountPrivateKey not same in both");
428
429 if (sp1compete && sp2compete)
430 NSLog(@"pairing complete");
431
432 XCTAssert(SOSCircleHasPeer(circle, [fc1 peerInfo], &cferror), "HasPeer 1: %@", cferror);
433 CFReleaseNull(cferror);
434 XCTAssert(SOSCircleHasPeer(circle, [fc2 peerInfo], &cferror), "HasPeer 2: %@", cferror);
435 CFReleaseNull(cferror);
436
437 XCTAssert(sp1.needInitialSync == false, "no longer need initial sync");
438
439
440 }
441
442 @end