5 // Created by Love Hörnquist Åstrand on 2017-02-28.
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"
20 @interface FakeNSXPCConnection : NSObject
21 - (instancetype) initWithControl:(id<SOSControlProtocol>)control;
22 - (id)remoteObjectProxyWithErrorHandler:(void(^)(NSError * _Nonnull error))failureHandler;
24 @interface FakeNSXPCConnection ()
25 @property id<SOSControlProtocol> control;
27 @implementation FakeNSXPCConnection
28 - (instancetype) initWithControl:(id<SOSControlProtocol>)control
36 - (id)remoteObjectProxyWithErrorHandler:(void(^)(NSError * _Nonnull error))failureHandler
44 @interface KCPairingTest : XCTestCase
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;
59 @implementation FCPairingFakeSOSControl
61 - (instancetype)initWithRandomAccountKey:(bool)randomAccountKey circle:(SOSCircleRef)circle
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,
75 (__bridge id)kSecPublicKeyAttrs : @{
76 (__bridge NSString*)kSecAttrLabel : @"delete me test case - public",
77 (__bridge NSString*)kSecAttrAccessible : (__bridge id)kSecAttrAccessibleAfterFirstUnlock,
80 if(SecKeyGeneratePair((__bridge CFDictionaryRef)parameters, &publicKey, &_deviceKey) != 0) {
81 NSLog(@"failed to create device key");
84 CFReleaseNull(publicKey);
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");
92 CFReleaseNull(publicKey);
94 if(SecKeyGeneratePair((__bridge CFDictionaryRef)octagonParameters, &publicKey, &_octagonEncryptionKey) != 0) {
95 NSLog(@"failed to create octagon signing key");
98 CFReleaseNull(publicKey);
101 _circle = (SOSCircleRef)CFRetain(circle);
103 CFErrorRef error = NULL;
105 CFDictionaryRef gestalt = (__bridge CFDictionaryRef)@{
106 @"ComputerName" : @"name",
109 _fullPeerInfo = SOSFullPeerInfoCreate(NULL, gestalt, NULL, _deviceKey, _octagonSigningKey, _octagonEncryptionKey, &error);
110 CFReleaseNull(error);
112 if (randomAccountKey) {
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,
121 if(SecKeyGeneratePair((__bridge CFDictionaryRef)accountParams, &publicKey, &_accountPrivateKey) != 0) {
122 NSLog(@"failed to create account signing key");
125 CFReleaseNull(publicKey);
127 _accountPublicKey = SecKeyCopyPublicKey(_accountPrivateKey);
129 [self signApplicationIfNeeded];
137 if (_accountPrivateKey) {
138 SecItemDelete((__bridge CFTypeRef)@{ (__bridge id)kSecValueRef : (__bridge id)_accountPrivateKey });
139 CFReleaseNull(_accountPrivateKey);
142 SecItemDelete((__bridge CFTypeRef)@{ (__bridge id)kSecValueRef : (__bridge id)_deviceKey });
143 CFReleaseNull(_deviceKey);
145 if (_octagonSigningKey) {
146 SecItemDelete((__bridge CFTypeRef)@{ (__bridge id)kSecValueRef : (__bridge id)_octagonSigningKey });
147 CFReleaseNull(_octagonSigningKey);
149 if (_octagonEncryptionKey) {
150 SecItemDelete((__bridge CFTypeRef)@{ (__bridge id)kSecValueRef : (__bridge id)_octagonEncryptionKey });
151 CFReleaseNull(_octagonEncryptionKey);
153 CFReleaseNull(_circle);
154 CFReleaseNull(_fullPeerInfo);
157 - (SOSPeerInfoRef)peerInfo
159 return SOSFullPeerInfoGetPeerInfo(_fullPeerInfo);
162 - (void)signApplicationIfNeeded
164 CFErrorRef error = NULL;
166 _application = SOSFullPeerInfoPromoteToApplication(_fullPeerInfo, _accountPrivateKey, &error);
171 - (void)initialSyncCredentials:(uint32_t)flags complete:(void (^)(NSArray *, NSError *))complete
176 - (void)importInitialSyncCredentials:(NSArray *)items complete:(void (^)(bool success, NSError *))complete
178 complete(true, NULL);
181 - (void)triggerSync:(NSArray<NSString *> *)peers complete:(void(^)(bool success, NSError *))complete
183 complete(true, NULL);
186 //MARK - FCPairingFakeSOSControl SOSControlProtocol
188 - (void)userPublicKey:(void ((^))(BOOL trusted, NSData *spki, NSError *error))complete
190 complete(false, NULL, NULL);
193 - (void)performanceCounters:(void(^)(NSDictionary <NSString *, NSNumber *> *))complete
197 - (void)kvsPerformanceCounters:(void(^)(NSDictionary <NSString *, NSNumber *> *))complete
202 - (void)rateLimitingPerformanceCounters:(void(^)(NSDictionary <NSString *, NSString *> *))complete
206 - (void)stashedCredentialPublicKey:(void(^)(NSData *, NSError *error))complete
208 NSData *publicKey = NULL;
209 NSError *error = NULL;
210 if (self.accountPrivateKey) {
211 publicKey = CFBridgingRelease(SecKeyCopySubjectPublicKeyInfo(self.accountPrivateKey));
213 error = [NSError errorWithDomain:@"FCPairingFakeSOSControl" code:2 userInfo:NULL];
215 complete(publicKey, error);
218 - (void)assertStashedAccountCredential:(void(^)(BOOL result, NSError *error))complete
220 complete(self.accountPrivateKey != NULL, NULL);
223 - (void)validatedStashedAccountCredential:(void(^)(NSData *credential, NSError *error))complete
226 CFErrorRef error = NULL;
227 if (self.accountPrivateKey) {
228 key = CFBridgingRelease(SecKeyCopyExternalRepresentation(self.accountPrivateKey, &error));
230 error = (CFErrorRef)CFBridgingRetain([NSError errorWithDomain:@"FCPairingFakeSOSControl" code:1 userInfo:NULL]);
232 complete(key, (__bridge NSError *)error);
233 CFReleaseNull(error);
236 - (void)stashAccountCredential:(NSData *)credential complete:(void(^)(bool success, NSError *error))complete
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,
245 accountPrivateKey = SecKeyCreateWithData((__bridge CFDataRef)credential, (__bridge CFDictionaryRef)attributes, &error);
246 if (accountPrivateKey == NULL) {
247 complete(false, (__bridge NSError *)error);
248 CFReleaseNull(error);
252 _accountPrivateKey = accountPrivateKey;
253 _accountPublicKey = SecKeyCopyPublicKey(_accountPrivateKey);
255 [self signApplicationIfNeeded];
257 complete(true, NULL);
260 - (void)myPeerInfo:(void(^)(NSData *application, NSError *error))complete
262 CFErrorRef error = NULL;
264 [self signApplicationIfNeeded];
266 NSData *application = CFBridgingRelease(SOSPeerInfoCopyEncodedData([self peerInfo], NULL, &error));
267 complete(application, (__bridge NSError *)error);
269 CFReleaseNull(error);
272 - (void)circleJoiningBlob:(NSData *)applicantData complete:(void (^)(NSData *blob, NSError *))complete
274 CFErrorRef error = NULL;
275 CFDataRef signature = NULL;
276 SOSCircleRef prunedCircle = SOSCircleCopyCircle(NULL, _circle, &error);
277 (void)SOSCirclePreGenerationSign(prunedCircle, _accountPublicKey, &error);
279 SOSGenCountRef gencount = SOSGenerationIncrementAndCreate(SOSCircleGetGeneration(prunedCircle));
280 if (gencount == NULL)
284 SOSPeerInfoRef applicant = SOSPeerInfoCreateFromData(NULL, &error, (__bridge CFDataRef)applicantData);
285 if (applicant == NULL)
288 signature = SOSCircleCopyNextGenSignatureWithPeerAdded(prunedCircle, applicant, _deviceKey, &error);
290 CFRelease(applicant);
294 NSData *pbblob = CFBridgingRelease(SOSPiggyBackBlobCopyEncodedData(gencount, _deviceKey, signature, &error));
296 CFReleaseNull(signature);
297 CFReleaseNull(gencount);
298 CFReleaseNull(prunedCircle);
300 complete(pbblob, NULL);
303 - (void)joinCircleWithBlob:(NSData *)blob version:(PiggyBackProtocolVersion)version complete:(void (^)(bool success, NSError *))complete
305 SOSGenCountRef gencount = NULL;
306 SecKeyRef pubKey = NULL;
307 CFDataRef signature = NULL;
308 CFErrorRef error = NULL;
309 bool setInitialSyncTimeoutToV0 = false;
311 if (!SOSPiggyBackBlobCreateFromData(&gencount, &pubKey, &signature, (__bridge CFDataRef)blob, kPiggyV1, &setInitialSyncTimeoutToV0, &error)) {
312 complete(true, (__bridge NSError *)error);
313 CFReleaseNull(error);
317 (void)SOSCircleAcceptPeerFromHSA2(_circle,
325 CFReleaseNull(gencount);
326 CFReleaseNull(pubKey);
327 CFReleaseNull(signature);
329 complete(true, (__bridge NSError *)error);
331 CFReleaseNull(error);
335 - (void)getWatchdogParameters:(void (^)(NSDictionary*, NSError*))complete
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
342 - (void)setWatchdogParmeters:(NSDictionary*)parameters complete:(void (^)(NSError*))complete
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
349 @implementation KCPairingTest
351 - (void)testSecPairBasicTest
353 if (![KCPairingChannel isSupportedPlatform]) {
357 bool sp1compete = false, sp2compete = false;
358 NSData *sp1data = NULL;
359 NSData *sp2data = NULL;
360 SOSCircleRef circle = NULL;
362 CFErrorRef cferror = NULL;
363 KCPairingChannel *sp1, *sp2;
365 circle = SOSCircleCreate(NULL, CFSTR("TEST DOMAIN"), NULL);
366 XCTAssert(circle, "circle");
368 FCPairingFakeSOSControl *fc1 = [[FCPairingFakeSOSControl alloc] initWithRandomAccountKey:false circle:circle];
369 XCTAssert(fc1, "create fake soscontrol 1");
371 FCPairingFakeSOSControl *fc2 = [[FCPairingFakeSOSControl alloc] initWithRandomAccountKey:true circle:circle];
372 XCTAssert(fc2, "create fake soscontrol 2");
375 XCTAssert(SOSCircleRequestAdmission(circle, fc2.accountPrivateKey, fc2.fullPeerInfo, &cferror), "SOSCircleRequestAdmission: %@", cferror);
376 CFReleaseNull(cferror);
378 XCTAssert(SOSCircleAcceptRequest(circle, fc2.accountPrivateKey, fc2.fullPeerInfo, [fc2 peerInfo], &cferror), "SOSCircleAcceptRequest device 1: %@", cferror);
379 CFReleaseNull(cferror);
381 XCTAssert(SOSCircleHasPeer(circle, [fc2 peerInfo], &cferror), "HasPeer 2: %@", cferror);
382 CFReleaseNull(cferror);
385 sp1 = [KCPairingChannel pairingChannelInitiator:NULL];
386 [sp1 setXPCConnectionObject:(NSXPCConnection *)[[FakeNSXPCConnection alloc] initWithControl:fc1]];
388 sp2 = [KCPairingChannel pairingChannelAcceptor:NULL];
389 [sp2 setXPCConnectionObject:(NSXPCConnection *)[[FakeNSXPCConnection alloc] initWithControl:fc2]] ;
392 NSError *error = NULL;
394 sp1data = [sp1 exchangePacket:sp2data complete:&sp1compete error:&error];
396 if (sp1compete && sp2compete) {
397 XCTAssert(sp1data == NULL, "sp1 done, yet there is data");
400 XCTAssert(!sp2compete, "sp2 completed w/o sp1");
402 XCTAssert(sp1data != NULL, "sp1 not done, yet there is no data: %@", error);
406 /* send sp1data to peer : BOB CHANNEL HERE */
408 sp2data = [sp2 exchangePacket:sp1data complete:&sp2compete error:&error];
409 XCTAssert(sp2data != NULL, "sp2 didn't return data: %@", error);
413 if (sp1compete && sp2compete)
416 XCTAssert(!sp1compete, "sp2 completed w/o sp1");
423 XCTAssert(sp1compete && sp2compete, "both parties not completed");
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");
429 if (sp1compete && sp2compete)
430 NSLog(@"pairing complete");
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);
437 XCTAssert(sp1.needInitialSync == false, "no longer need initial sync");