2 // KCJoiningSessionTest.m
7 #import <XCTest/XCTest.h>
9 #import <Foundation/Foundation.h>
11 #import <KeychainCircle/KCJoiningSession.h>
12 #import <KeychainCircle/KCError.h>
13 #import <KeychainCircle/NSError+KCCreationHelpers.h>
14 #import <KeychainCircle/KCAESGCMDuplexSession.h>
16 #include <Security/SecBase.h>
17 #include <Security/SecureObjectSync/SOSFullPeerInfo.h>
18 #include <Security/SecureObjectSync/SOSPeerInfoInternal.h>
20 #include <CommonCrypto/CommonRandomSPI.h>
23 __unused static SOSFullPeerInfoRef SOSNSFullPeerInfoCreate(NSDictionary* gestalt,
24 NSData* backupKey, SecKeyRef signingKey, SecKeyRef octagonSigningKey,
27 CFErrorRef errorRef = NULL;
29 SOSFullPeerInfoRef result = SOSFullPeerInfoCreate(NULL, (__bridge CFDictionaryRef) gestalt, (__bridge CFDataRef) backupKey, signingKey, octagonSigningKey, &errorRef);
31 if (errorRef && error) {
32 *error = (__bridge_transfer NSError*) errorRef;
39 static SecKeyRef GenerateFullECKey_internal(int keySize, NSError** error)
41 SecKeyRef full_key = NULL;
43 NSDictionary* keygen_parameters = @{ (__bridge NSString*)kSecAttrKeyType:(__bridge NSString*) kSecAttrKeyTypeEC,
44 (__bridge NSString*)kSecAttrKeySizeInBits: [NSNumber numberWithInt: keySize] };
47 (void) OSStatusError(SecKeyGeneratePair((__bridge CFDictionaryRef)keygen_parameters, NULL, &full_key), error, @"Generate Key failed");
52 static SecKeyRef GenerateFullECKey(int keySize, NSError** error) {
53 return GenerateFullECKey_internal(keySize, error);
57 __unused static SOSFullPeerInfoRef SOSCreateFullPeerInfoFromName(NSString* name, SecKeyRef* outSigningKey, SecKeyRef* outOctagonSigningKey, NSError** error)
59 if (outSigningKey == NULL || outOctagonSigningKey == NULL)
62 *outSigningKey = GenerateFullECKey(256, error);
63 if (*outSigningKey == NULL)
66 *outOctagonSigningKey = GenerateFullECKey(384, error);
67 if (*outOctagonSigningKey == NULL) {
71 return SOSNSFullPeerInfoCreate(@{(__bridge NSString*)kPIUserDefinedDeviceNameKey:name}, nil, *outSigningKey, *outOctagonSigningKey, error);
75 @interface KCJoiningRequestTestDelegate : NSObject <KCJoiningRequestSecretDelegate, KCJoiningRequestCircleDelegate>
76 @property (readwrite) NSString* sharedSecret;
78 @property (readonly) NSString* accountCode;
79 @property (readonly) NSData* circleJoinData;
80 @property (readwrite) SOSPeerInfoRef peerInfo;
82 @property (readwrite) NSString* incorrectSecret;
83 @property (readwrite) int incorrectTries;
86 + (id) requestDelegateWithSecret:(NSString*) secret;
87 - (id) init NS_UNAVAILABLE;
88 - (id) initWithSecret: (NSString*) secret
89 incorrectSecret: (NSString*) wrongSecret
90 incorrectTries: (int) retries NS_DESIGNATED_INITIALIZER;
92 - (NSString*) verificationFailed: (bool) codeChanged;
93 - (SOSPeerInfoRef) copyPeerInfoError: (NSError**) error;
94 - (bool) processCircleJoinData: (NSData*) circleJoinData version:(PiggyBackProtocolVersion)version error: (NSError**)error ;
95 - (bool) processAccountCode: (NSString*) accountCode error: (NSError**)error;
99 @implementation KCJoiningRequestTestDelegate
101 + (id) requestDelegateWithSecret:(NSString*) secret {
102 return [[KCJoiningRequestTestDelegate alloc] initWithSecret:secret
107 + (id) requestDelegateWithSecret:(NSString*) secret
108 incorrectSecret:(NSString*) wrongSecret
109 incorrectTries:(int) retries {
110 return [[KCJoiningRequestTestDelegate alloc] initWithSecret:secret
111 incorrectSecret:wrongSecret
112 incorrectTries:retries];
116 - (id) initWithSecret: (NSString*) secret
117 incorrectSecret: (NSString*) incorrectSecret
118 incorrectTries: (int) retries {
121 SecKeyRef signingKey = GenerateFullECKey(256, NULL);
122 SecKeyRef octagonSigningKey = GenerateFullECKey(384, NULL);
124 self.peerInfo = SOSPeerInfoCreate(NULL, (__bridge CFDictionaryRef) @{(__bridge NSString*)kPIUserDefinedDeviceNameKey:@"Fakey"}, NULL, signingKey, octagonSigningKey, NULL);
126 if (self.peerInfo == NULL)
129 self.sharedSecret = secret;
130 self.incorrectSecret = incorrectSecret;
131 self.incorrectTries = retries;
136 - (NSString*) nextSecret {
137 if (self.incorrectTries > 0) {
138 self.incorrectTries -= 1;
139 return self.incorrectSecret;
141 return self.sharedSecret;
144 - (NSString*) secret {
145 return [self nextSecret];
148 - (NSString*) verificationFailed: (bool) codeChanged {
149 return [self nextSecret];
152 - (SOSPeerInfoRef) copyPeerInfoError: (NSError**) error {
153 return self.peerInfo;
156 - (bool) processCircleJoinData: (NSData*) circleJoinData version:(PiggyBackProtocolVersion)version error: (NSError**)error {
157 self->_circleJoinData = circleJoinData;
161 - (bool) processAccountCode: (NSString*) accountCode error: (NSError**)error {
162 self->_accountCode = accountCode;
168 @interface KCJoiningAcceptTestDelegate : NSObject <KCJoiningAcceptSecretDelegate, KCJoiningAcceptCircleDelegate>
169 @property (readonly) NSArray<NSString*>* secrets;
170 @property (readwrite) NSUInteger currentSecret;
171 @property (readwrite) int retriesLeft;
172 @property (readwrite) int retriesPerSecret;
174 @property (readonly) NSString* codeToUse;
175 @property (readonly) NSData* circleJoinData;
176 @property (readonly) SOSPeerInfoRef peerInfo;
178 + (id) acceptDelegateWithSecret: (NSString*) secret code: (NSString*) code;
179 + (id) acceptDelegateWithSecrets: (NSArray<NSString*>*) secrets retries: (int) retries code: (NSString*) code;
180 - (id) initWithSecrets: (NSArray<NSString*>*) secrets retries: (int) retries code: (NSString*) code NS_DESIGNATED_INITIALIZER;
183 - (NSString*) secret;
184 - (NSString*) accountCode;
186 - (KCRetryOrNot) verificationFailed: (NSError**) error;
187 - (NSData*) circleJoinDataFor: (SOSPeerInfoRef) peer
188 error: (NSError**) error;
190 - (id) init NS_UNAVAILABLE;
194 @implementation KCJoiningAcceptTestDelegate
196 + (id) acceptDelegateWithSecrets: (NSArray<NSString*>*) secrets retries: (int) retries code: (NSString*) code {
197 return [[KCJoiningAcceptTestDelegate alloc] initWithSecrets:secrets retries:retries code:code];
201 + (id) acceptDelegateWithSecret: (NSString*) secret code: (NSString*) code {
202 return [[KCJoiningAcceptTestDelegate alloc] initWithSecret:secret code:code];
205 - (id) initWithSecret: (NSString*) secret code: (NSString*) code {
206 return [self initWithSecrets:@[secret] retries:3 code:code];
209 - (id) initWithSecrets: (NSArray<NSString*>*) secrets retries: (int) retries code: (NSString*) code {
212 self->_secrets = secrets;
213 self.currentSecret = 0;
214 self->_retriesPerSecret = retries;
215 self->_retriesLeft = self.retriesPerSecret;
217 self->_codeToUse = code;
219 uint8_t joinDataBuffer[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
220 self->_circleJoinData = [NSData dataWithBytes: joinDataBuffer length: sizeof(joinDataBuffer) ];
225 - (KCRetryOrNot) advanceSecret {
226 if (self.retriesLeft == 0) {
227 self.currentSecret += 1;
228 if (self.currentSecret >= [self.secrets count]) {
229 self.currentSecret = [self.secrets count] - 1;
231 self.retriesLeft = self.retriesPerSecret;
232 return kKCRetryWithNewChallenge;
234 self.retriesLeft -= 1;
235 return kKCRetryWithSameChallenge;
239 - (NSString*) secret {
240 return self.secrets[self.currentSecret];
242 - (NSString*) accountCode {
243 return self.codeToUse;
246 - (KCRetryOrNot) verificationFailed: (NSError**) error {
247 return [self advanceSecret];
250 - (NSData*) circleJoinDataFor: (SOSPeerInfoRef) peer
251 error: (NSError**) error {
252 uint8_t joinDataBuffer[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
254 self->_peerInfo = peer;
255 return [NSData dataWithBytes: joinDataBuffer length: sizeof(joinDataBuffer) ];
258 -(NSData*) circleGetInitialSyncViews: (NSError**) error{
259 return [NSData data];
265 @interface KCJoiningSessionTest : XCTestCase
269 @implementation KCJoiningSessionTest
273 // Put setup code here. This method is called before the invocation of each test method in the class.
277 // Put teardown code here. This method is called after the invocation of each test method in the class.
281 - (void)testJoiningSession {
282 NSError* error = nil;
284 NSString* secret = @"123456";
285 NSString* code = @"987654";
287 uint64_t dsid = 0x1234567887654321;
289 KCJoiningRequestTestDelegate* requestDelegate = [KCJoiningRequestTestDelegate requestDelegateWithSecret: secret];
290 KCJoiningRequestSecretSession *requestSession = [[KCJoiningRequestSecretSession alloc] initWithSecretDelegate:requestDelegate
292 rng:ccDRBGGetRngState()
295 NSData* initialMessage = [requestSession initialMessage: &error];
297 XCTAssertNotNil(initialMessage, @"No initial message");
298 XCTAssertNil(error, @"Got error %@", error);
300 KCJoiningAcceptTestDelegate* acceptDelegate = [KCJoiningAcceptTestDelegate acceptDelegateWithSecret:secret code:code];
301 KCJoiningAcceptSession* acceptSession = [[KCJoiningAcceptSession alloc] initWithSecretDelegate:acceptDelegate
302 circleDelegate:acceptDelegate
304 rng:ccDRBGGetRngState()
308 NSData* challenge = [acceptSession processMessage: initialMessage error: &error];
310 XCTAssertNotNil(challenge, @"No initial message");
311 XCTAssertNil(error, @"Got error %@", error);
314 NSData* response = [requestSession processMessage: challenge error: &error];
316 XCTAssertNotNil(response, @"No response message");
317 XCTAssertNil(error, @"Got error %@", error);
320 NSData* verification = [acceptSession processMessage: response error: &error];
322 XCTAssertNotNil(verification, @"No verification message");
323 XCTAssertNil(error, @"Got error %@", error);
326 NSData* doneMessage = [requestSession processMessage: verification error: &error];
328 XCTAssertNotNil(doneMessage, @"No response message");
329 XCTAssertNil(error, @"Got error %@", error);
331 XCTAssertTrue([requestSession isDone], @"SecretSession done");
332 XCTAssertFalse([acceptSession isDone], @"Unexpected accept session done");
334 KCAESGCMDuplexSession* aesSession = [requestSession session];
335 requestSession = nil;
337 KCJoiningRequestCircleSession* requestSecretSession = [KCJoiningRequestCircleSession sessionWithCircleDelegate:requestDelegate session:aesSession error:&error];
339 XCTAssertNotNil(requestSecretSession, @"No request secret session");
340 XCTAssertNil(error, @"Got error %@", error);
343 NSData* peerInfoMessage = [requestSecretSession initialMessage: &error];
345 XCTAssertNotNil(peerInfoMessage, @"No peerInfo message");
346 XCTAssertNil(error, @"Got error %@", error);
348 XCTAssertEqualObjects(requestDelegate.accountCode, acceptDelegate.codeToUse, @"Code made it");
351 NSData* blobMessage = [acceptSession processMessage:peerInfoMessage error: &error];
353 XCTAssertNotNil(blobMessage, @"No blob message");
354 XCTAssertNil(error, @"Got error %@", error);
356 // We have different peer_info types due to wierd linking of our tests.
357 // Compare the der representations:
358 NSData* rp_der = requestDelegate.peerInfo != nil ? (__bridge_transfer NSData*) SOSPeerInfoCopyEncodedData(requestDelegate.peerInfo, NULL, NULL) : nil;
359 NSData* ap_der = acceptDelegate.peerInfo != nil ? (__bridge_transfer NSData*) SOSPeerInfoCopyEncodedData(acceptDelegate.peerInfo, NULL, NULL) : nil;
361 XCTAssertEqualObjects(rp_der, ap_der, @"Peer infos match");
364 NSData* nothing = [requestSecretSession processMessage:blobMessage error: &error];
366 XCTAssertEqualObjects(requestDelegate.circleJoinData, acceptDelegate.circleJoinData);
368 XCTAssertNotNil(nothing, @"No initial message");
369 XCTAssertNil(error, @"Got error %@", error);
371 XCTAssertTrue([requestSecretSession isDone], @"requesor done");
372 XCTAssertTrue([acceptSession isDone], @"acceptor done");
376 - (void)testJoiningSessionRetry {
377 NSError* error = nil;
379 NSString* secret = @"123456";
380 NSString* code = @"987654";
382 uint64_t dsid = 0x1234567887654321;
384 KCJoiningRequestTestDelegate* requestDelegate = [KCJoiningRequestTestDelegate requestDelegateWithSecret: secret incorrectSecret:@"777888" incorrectTries:3];
385 KCJoiningRequestSecretSession *requestSession = [[KCJoiningRequestSecretSession alloc] initWithSecretDelegate:requestDelegate
387 rng:ccDRBGGetRngState()
390 NSData* initialMessage = [requestSession initialMessage: &error];
392 XCTAssertNotNil(initialMessage, @"No initial message");
393 XCTAssertNil(error, @"Got error %@", error);
395 KCJoiningAcceptTestDelegate* acceptDelegate = [KCJoiningAcceptTestDelegate acceptDelegateWithSecret:secret code:code];
396 KCJoiningAcceptSession* acceptSession = [[KCJoiningAcceptSession alloc] initWithSecretDelegate:acceptDelegate
397 circleDelegate:acceptDelegate
399 rng:ccDRBGGetRngState()
403 NSData* challenge = [acceptSession processMessage: initialMessage error: &error];
405 XCTAssertNotNil(challenge, @"No initial message");
406 XCTAssertNil(error, @"Got error %@", error);
408 NSData* response = nil;
409 NSData* verification = nil;
411 NSData* nextChallenge = challenge;
412 for (int tries = 0; tries < 4; ++tries) {
414 response = [requestSession processMessage: nextChallenge error: &error];
416 XCTAssertNotNil(response, @"No response message");
417 XCTAssertNil(error, @"Got error %@", error);
419 XCTAssertNotEqualObjects(requestDelegate.accountCode, acceptDelegate.codeToUse, @"Code should not make it");
422 verification = [acceptSession processMessage: response error: &error];
424 XCTAssertNotNil(verification, @"No verification message");
425 XCTAssertNil(error, @"Got error %@", error);
427 nextChallenge = verification;
431 NSData* doneMessage = [requestSession processMessage: verification error: &error];
433 XCTAssertNotNil(doneMessage, @"No response message");
434 XCTAssertNil(error, @"Got error %@", error);
436 XCTAssertTrue([requestSession isDone], @"SecretSession done");
437 XCTAssertFalse([acceptSession isDone], @"Unexpected accept session done");
439 KCAESGCMDuplexSession* aesSession = [requestSession session];
440 requestSession = nil;
443 KCJoiningRequestCircleSession* requestSecretSession = [KCJoiningRequestCircleSession sessionWithCircleDelegate:requestDelegate session:aesSession error:&error];
445 XCTAssertNotNil(requestSecretSession, @"No request secret session");
446 XCTAssertNil(error, @"Got error %@", error);
449 NSData* peerInfoMessage = [requestSecretSession initialMessage: &error];
451 XCTAssertNotNil(peerInfoMessage, @"No peerInfo message");
452 XCTAssertNil(error, @"Got error %@", error);
454 XCTAssertEqualObjects(requestDelegate.accountCode, acceptDelegate.codeToUse, @"Code made it");
457 NSData* blobMessage = [acceptSession processMessage:peerInfoMessage error: &error];
459 XCTAssertNotNil(blobMessage, @"No blob message");
460 XCTAssertNil(error, @"Got error %@", error);
462 // We have different peer_info types due to wierd linking of our tests.
463 // Compare the der representations:
464 NSData* rp_der = requestDelegate.peerInfo != nil ? (__bridge_transfer NSData*) SOSPeerInfoCopyEncodedData(requestDelegate.peerInfo, NULL, NULL) : nil;
465 NSData* ap_der = acceptDelegate.peerInfo != nil ? (__bridge_transfer NSData*) SOSPeerInfoCopyEncodedData(acceptDelegate.peerInfo, NULL, NULL) : nil;
467 XCTAssertEqualObjects(rp_der, ap_der, @"Peer infos match");
470 NSData* nothing = [requestSecretSession processMessage:blobMessage error: &error];
472 XCTAssertEqualObjects(requestDelegate.circleJoinData, acceptDelegate.circleJoinData);
474 XCTAssertNotNil(nothing, @"No initial message");
475 XCTAssertNil(error, @"Got error %@", error);
477 XCTAssertTrue([requestSecretSession isDone], @"requesor done");
478 XCTAssertTrue([acceptSession isDone], @"acceptor done");
482 - (void)testJoiningSessionCodeChange {
483 NSError* error = nil;
485 NSString* secret = @"123456";
486 NSString* code = @"987654";
488 uint64_t dsid = 0x1234567887654321;
490 KCJoiningRequestTestDelegate* requestDelegate = [KCJoiningRequestTestDelegate requestDelegateWithSecret: secret];
491 KCJoiningRequestSecretSession *requestSession = [[KCJoiningRequestSecretSession alloc] initWithSecretDelegate:requestDelegate
493 rng:ccDRBGGetRngState()
496 NSData* initialMessage = [requestSession initialMessage: &error];
498 XCTAssertNotNil(initialMessage, @"No initial message");
499 XCTAssertNil(error, @"Got error %@", error);
501 KCJoiningAcceptTestDelegate* acceptDelegate = [KCJoiningAcceptTestDelegate acceptDelegateWithSecrets:@[@"222222", @"3333333", secret] retries:1 code:code];
502 KCJoiningAcceptSession* acceptSession = [[KCJoiningAcceptSession alloc] initWithSecretDelegate:acceptDelegate
503 circleDelegate:acceptDelegate
505 rng:ccDRBGGetRngState()
509 NSData* challenge = [acceptSession processMessage: initialMessage error: &error];
511 XCTAssertNotNil(challenge, @"No initial message");
512 XCTAssertNil(error, @"Got error %@", error);
514 NSData* response = nil;
515 NSData* verification = nil;
517 NSData* nextChallenge = challenge;
518 for (int tries = 0; tries < 5; ++tries) {
520 response = [requestSession processMessage: nextChallenge error: &error];
522 XCTAssertNotNil(response, @"No response message");
523 XCTAssertNil(error, @"Got error %@", error);
525 XCTAssertNotEqualObjects(requestDelegate.accountCode, acceptDelegate.codeToUse, @"Code should not make it");
528 verification = [acceptSession processMessage: response error: &error];
530 XCTAssertNotNil(verification, @"No verification message");
531 XCTAssertNil(error, @"Got error %@", error);
533 nextChallenge = verification;
537 NSData* doneMessage = [requestSession processMessage: verification error: &error];
539 XCTAssertNotNil(doneMessage, @"No response message");
540 XCTAssertNil(error, @"Got error %@", error);
542 XCTAssertTrue([requestSession isDone], @"SecretSession done");
543 XCTAssertFalse([acceptSession isDone], @"Unexpected accept session done");
545 KCAESGCMDuplexSession* aesSession = [requestSession session];
546 requestSession = nil;
549 KCJoiningRequestCircleSession* requestSecretSession = [KCJoiningRequestCircleSession sessionWithCircleDelegate:requestDelegate session:aesSession error:&error];
551 XCTAssertNotNil(requestSecretSession, @"No request secret session");
552 XCTAssertNil(error, @"Got error %@", error);
555 NSData* peerInfoMessage = [requestSecretSession initialMessage: &error];
557 XCTAssertNotNil(peerInfoMessage, @"No peerInfo message");
558 XCTAssertNil(error, @"Got error %@", error);
560 XCTAssertEqualObjects(requestDelegate.accountCode, acceptDelegate.codeToUse, @"Code made it");
563 NSData* blobMessage = [acceptSession processMessage:peerInfoMessage error: &error];
565 XCTAssertNotNil(blobMessage, @"No blob message");
566 XCTAssertNil(error, @"Got error %@", error);
568 // We have different peer_info types due to wierd linking of our tests.
569 // Compare the der representations:
570 NSData* rp_der = requestDelegate.peerInfo != nil ? (__bridge_transfer NSData*) SOSPeerInfoCopyEncodedData(requestDelegate.peerInfo, NULL, NULL) : nil;
571 NSData* ap_der = acceptDelegate.peerInfo != nil ? (__bridge_transfer NSData*) SOSPeerInfoCopyEncodedData(acceptDelegate.peerInfo, NULL, NULL) : nil;
573 XCTAssertEqualObjects(rp_der, ap_der, @"Peer infos match");
576 NSData* nothing = [requestSecretSession processMessage:blobMessage error: &error];
578 XCTAssertEqualObjects(requestDelegate.circleJoinData, acceptDelegate.circleJoinData);
580 XCTAssertNotNil(nothing, @"No initial message");
581 XCTAssertNil(error, @"Got error %@", error);
583 XCTAssertTrue([requestSecretSession isDone], @"requesor done");
584 XCTAssertTrue([acceptSession isDone], @"acceptor done");