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) SOSCircleRef circle;
54 @property (assign) SOSFullPeerInfoRef fullPeerInfo;
55 @property (assign) bool application;
58 @implementation FCPairingFakeSOSControl
60 - (instancetype)initWithRandomAccountKey:(bool)randomAccountKey circle:(SOSCircleRef)circle
62 if ((self = [super init])) {
63 SecKeyRef publicKey = NULL;
64 NSDictionary* parameters = @{
65 (__bridge NSString*)kSecAttrKeyType:(__bridge NSString*) kSecAttrKeyTypeEC,
66 (__bridge NSString*)kSecAttrKeySizeInBits: @(256),
67 (__bridge NSString*)kSecAttrNoLegacy : @YES,
68 (__bridge NSString*)kSecAttrAccessible : (__bridge id)kSecAttrAccessibleAfterFirstUnlock,
69 (__bridge id)kSecPrivateKeyAttrs : @{
70 (__bridge NSString*)kSecAttrLabel : @"delete me test case - private",
71 (__bridge NSString*)kSecAttrIsPermanent : @YES,
72 (__bridge NSString*)kSecAttrAccessible : (__bridge id)kSecAttrAccessibleAfterFirstUnlock,
74 (__bridge id)kSecPublicKeyAttrs : @{
75 (__bridge NSString*)kSecAttrLabel : @"delete me test case - public",
76 (__bridge NSString*)kSecAttrAccessible : (__bridge id)kSecAttrAccessibleAfterFirstUnlock,
79 if(SecKeyGeneratePair((__bridge CFDictionaryRef)parameters, &publicKey, &_deviceKey) != 0) {
80 NSLog(@"failed to create device key");
83 CFReleaseNull(publicKey);
85 NSMutableDictionary* octagonParameters = [parameters mutableCopy];
86 octagonParameters[(__bridge NSString*)kSecAttrKeySizeInBits] = @(384);
87 if(SecKeyGeneratePair((__bridge CFDictionaryRef)octagonParameters, &publicKey, &_octagonSigningKey) != 0) {
88 NSLog(@"failed to create octagon signing key");
91 CFReleaseNull(publicKey);
93 _circle = (SOSCircleRef)CFRetain(circle);
95 CFErrorRef error = NULL;
97 CFDictionaryRef gestalt = (__bridge CFDictionaryRef)@{
98 @"ComputerName" : @"name",
101 _fullPeerInfo = SOSFullPeerInfoCreate(NULL, gestalt, NULL, _deviceKey, _octagonSigningKey, &error);
102 CFReleaseNull(error);
104 if (randomAccountKey) {
106 NSDictionary* accountParams = @{
107 (__bridge NSString*)kSecAttrKeyType:(__bridge NSString*) kSecAttrKeyTypeEC,
108 (__bridge NSString*)kSecAttrKeySizeInBits: @(256),
109 (__bridge NSString*)kSecAttrNoLegacy : @YES,
110 (__bridge NSString*)kSecAttrAccessible : (__bridge id)kSecAttrAccessibleAfterFirstUnlock,
113 if(SecKeyGeneratePair((__bridge CFDictionaryRef)accountParams, &publicKey, &_accountPrivateKey) != 0) {
114 NSLog(@"failed to create account signing key");
117 CFReleaseNull(publicKey);
119 _accountPublicKey = SecKeyCopyPublicKey(_accountPrivateKey);
121 [self signApplicationIfNeeded];
129 if (_accountPrivateKey) {
130 SecItemDelete((__bridge CFTypeRef)@{ (__bridge id)kSecValueRef : (__bridge id)_accountPrivateKey });
131 CFReleaseNull(_accountPrivateKey);
134 SecItemDelete((__bridge CFTypeRef)@{ (__bridge id)kSecValueRef : (__bridge id)_deviceKey });
135 CFReleaseNull(_deviceKey);
137 if (_octagonSigningKey) {
138 SecItemDelete((__bridge CFTypeRef)@{ (__bridge id)kSecValueRef : (__bridge id)_octagonSigningKey });
139 CFReleaseNull(_octagonSigningKey);
141 CFReleaseNull(_circle);
142 CFReleaseNull(_fullPeerInfo);
145 - (SOSPeerInfoRef)peerInfo
147 return SOSFullPeerInfoGetPeerInfo(_fullPeerInfo);
150 - (void)signApplicationIfNeeded
152 CFErrorRef error = NULL;
154 _application = SOSFullPeerInfoPromoteToApplication(_fullPeerInfo, _accountPrivateKey, &error);
159 - (void)initialSyncCredentials:(uint32_t)flags complete:(void (^)(NSArray *, NSError *))complete
164 - (void)importInitialSyncCredentials:(NSArray *)items complete:(void (^)(bool success, NSError *))complete
166 complete(true, NULL);
169 - (void)triggerSync:(NSArray<NSString *> *)peers complete:(void(^)(bool success, NSError *))complete
171 complete(true, NULL);
174 //MARK - FCPairingFakeSOSControl SOSControlProtocol
176 - (void)userPublicKey:(void ((^))(BOOL trusted, NSData *spki, NSError *error))complete
178 complete(false, NULL, NULL);
181 - (void)performanceCounters:(void(^)(NSDictionary <NSString *, NSNumber *> *))complete
185 - (void)kvsPerformanceCounters:(void(^)(NSDictionary <NSString *, NSNumber *> *))complete
189 - (void)idsPerformanceCounters:(void(^)(NSDictionary <NSString *, NSNumber *> *))complete
193 - (void)rateLimitingPerformanceCounters:(void(^)(NSDictionary <NSString *, NSString *> *))complete
197 - (void)stashedCredentialPublicKey:(void(^)(NSData *, NSError *error))complete
199 NSData *publicKey = NULL;
200 NSError *error = NULL;
201 if (self.accountPrivateKey) {
202 publicKey = CFBridgingRelease(SecKeyCopySubjectPublicKeyInfo(self.accountPrivateKey));
204 error = [NSError errorWithDomain:@"FCPairingFakeSOSControl" code:2 userInfo:NULL];
206 complete(publicKey, error);
209 - (void)assertStashedAccountCredential:(void(^)(BOOL result, NSError *error))complete
211 complete(self.accountPrivateKey != NULL, NULL);
214 - (void)validatedStashedAccountCredential:(void(^)(NSData *credential, NSError *error))complete
217 CFErrorRef error = NULL;
218 if (self.accountPrivateKey) {
219 key = CFBridgingRelease(SecKeyCopyExternalRepresentation(self.accountPrivateKey, &error));
221 error = (CFErrorRef)CFBridgingRetain([NSError errorWithDomain:@"FCPairingFakeSOSControl" code:1 userInfo:NULL]);
223 complete(key, (__bridge NSError *)error);
224 CFReleaseNull(error);
227 - (void)stashAccountCredential:(NSData *)credential complete:(void(^)(bool success, NSError *error))complete
229 SecKeyRef accountPrivateKey = NULL;
230 CFErrorRef error = NULL;
231 NSDictionary *attributes = @{
232 (__bridge id)kSecAttrKeyClass : (__bridge id)kSecAttrKeyClassPrivate,
233 (__bridge id)kSecAttrKeyType : (__bridge id)kSecAttrKeyTypeEC,
236 accountPrivateKey = SecKeyCreateWithData((__bridge CFDataRef)credential, (__bridge CFDictionaryRef)attributes, &error);
237 if (accountPrivateKey == NULL) {
238 complete(false, (__bridge NSError *)error);
239 CFReleaseNull(error);
243 _accountPrivateKey = accountPrivateKey;
244 _accountPublicKey = SecKeyCopyPublicKey(_accountPrivateKey);
246 [self signApplicationIfNeeded];
248 complete(true, NULL);
251 - (void)myPeerInfo:(void(^)(NSData *application, NSError *error))complete
253 CFErrorRef error = NULL;
255 [self signApplicationIfNeeded];
257 NSData *application = CFBridgingRelease(SOSPeerInfoCopyEncodedData([self peerInfo], NULL, &error));
258 complete(application, (__bridge NSError *)error);
260 CFReleaseNull(error);
263 - (void)circleJoiningBlob:(NSData *)applicantData complete:(void (^)(NSData *blob, NSError *))complete
265 CFErrorRef error = NULL;
266 CFDataRef signature = NULL;
267 SOSCircleRef prunedCircle = SOSCircleCopyCircle(NULL, _circle, &error);
268 (void)SOSCirclePreGenerationSign(prunedCircle, _accountPublicKey, &error);
270 SOSGenCountRef gencount = SOSGenerationIncrementAndCreate(SOSCircleGetGeneration(prunedCircle));
271 if (gencount == NULL)
275 SOSPeerInfoRef applicant = SOSPeerInfoCreateFromData(NULL, &error, (__bridge CFDataRef)applicantData);
276 if (applicant == NULL)
279 signature = SOSCircleCopyNextGenSignatureWithPeerAdded(prunedCircle, applicant, _deviceKey, &error);
281 NSData *pbblob = CFBridgingRelease(SOSPiggyBackBlobCopyEncodedData(gencount, _deviceKey, signature, &error));
283 CFReleaseNull(signature);
284 CFReleaseNull(gencount);
285 CFReleaseNull(prunedCircle);
287 complete(pbblob, NULL);
290 - (void)joinCircleWithBlob:(NSData *)blob version:(PiggyBackProtocolVersion)version complete:(void (^)(bool success, NSError *))complete
292 SOSGenCountRef gencount = NULL;
293 SecKeyRef pubKey = NULL;
294 CFDataRef signature = NULL;
295 CFErrorRef error = NULL;
296 bool setInitialSyncTimeoutToV0 = false;
298 if (!SOSPiggyBackBlobCreateFromData(&gencount, &pubKey, &signature, (__bridge CFDataRef)blob, kPiggyV1, &setInitialSyncTimeoutToV0, &error)) {
299 complete(true, (__bridge NSError *)error);
300 CFReleaseNull(error);
304 (void)SOSCircleAcceptPeerFromHSA2(_circle,
312 CFReleaseNull(gencount);
313 CFReleaseNull(pubKey);
314 CFReleaseNull(signature);
316 complete(true, (__bridge NSError *)error);
318 CFReleaseNull(error);
322 - (void)getWatchdogParameters:(void (^)(NSDictionary*, NSError*))complete
324 // intentionally left blank
325 // 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
329 - (void)setWatchdogParmeters:(NSDictionary*)parameters complete:(void (^)(NSError*))complete
331 // intentionally left blank
332 // 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
338 @implementation KCPairingTest
340 - (void)testSecPairBasicTest
342 bool sp1compete = false, sp2compete = false;
343 NSData *sp1data = NULL;
344 NSData *sp2data = NULL;
345 SOSCircleRef circle = NULL;
347 CFErrorRef cferror = NULL;
348 KCPairingChannel *sp1, *sp2;
350 circle = SOSCircleCreate(NULL, CFSTR("TEST DOMAIN"), NULL);
351 XCTAssert(circle, "circle");
353 FCPairingFakeSOSControl *fc1 = [[FCPairingFakeSOSControl alloc] initWithRandomAccountKey:false circle:circle];
354 XCTAssert(fc1, "create fake soscontrol 1");
356 FCPairingFakeSOSControl *fc2 = [[FCPairingFakeSOSControl alloc] initWithRandomAccountKey:true circle:circle];
357 XCTAssert(fc2, "create fake soscontrol 2");
360 XCTAssert(SOSCircleRequestAdmission(circle, fc2.accountPrivateKey, fc2.fullPeerInfo, &cferror), "SOSCircleRequestAdmission: %@", cferror);
361 CFReleaseNull(cferror);
363 XCTAssert(SOSCircleAcceptRequest(circle, fc2.accountPrivateKey, fc2.fullPeerInfo, [fc2 peerInfo], &cferror), "SOSCircleAcceptRequest device 1: %@", cferror);
364 CFReleaseNull(cferror);
366 XCTAssert(SOSCircleHasPeer(circle, [fc2 peerInfo], &cferror), "HasPeer 2: %@", cferror);
367 CFReleaseNull(cferror);
370 sp1 = [KCPairingChannel pairingChannelInitiator:NULL];
371 [sp1 setXPCConnectionObject:(NSXPCConnection *)[[FakeNSXPCConnection alloc] initWithControl:fc1]];
373 sp2 = [KCPairingChannel pairingChannelAcceptor:NULL];
374 [sp2 setXPCConnectionObject:(NSXPCConnection *)[[FakeNSXPCConnection alloc] initWithControl:fc2]] ;
377 NSError *error = NULL;
379 sp1data = [sp1 exchangePacket:sp2data complete:&sp1compete error:&error];
381 if (sp1compete && sp2compete) {
382 XCTAssert(sp1data == NULL, "sp1 done, yet there is data");
385 XCTAssert(!sp2compete, "sp2 completed w/o sp1");
387 XCTAssert(sp1data != NULL, "sp1 not done, yet there is no data: %@", error);
391 /* send sp1data to peer : BOB CHANNEL HERE */
393 sp2data = [sp2 exchangePacket:sp1data complete:&sp2compete error:&error];
394 XCTAssert(sp2data != NULL, "sp2 didn't return data: %@", error);
398 if (sp1compete && sp2compete)
401 XCTAssert(!sp1compete, "sp2 completed w/o sp1");
408 XCTAssert(sp1compete && sp2compete, "both parties not completed");
410 XCTAssert(fc1.accountPrivateKey, "no accountPrivateKey in fc1");
411 XCTAssert(fc2.accountPrivateKey, "no accountPrivateKey in fc2");
412 XCTAssert(CFEqualSafe(fc1.accountPrivateKey, fc2.accountPrivateKey), "no accountPrivateKey not same in both");
414 if (sp1compete && sp2compete)
415 NSLog(@"pairing complete");
417 XCTAssert(SOSCircleHasPeer(circle, [fc1 peerInfo], &cferror), "HasPeer 1: %@", cferror);
418 CFReleaseNull(cferror);
419 XCTAssert(SOSCircleHasPeer(circle, [fc2 peerInfo], &cferror), "HasPeer 2: %@", cferror);
420 CFReleaseNull(cferror);
422 XCTAssert(sp1.needInitialSync == false, "no longer need initial sync");