2 * Copyright (c) 2017 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
26 #import <OCMock/OCMock.h>
28 #import "keychain/ckks/tests/CloudKitMockXCTest.h"
29 #import "keychain/ckks/tests/CloudKitKeychainSyncingMockXCTest.h"
31 #import <securityd/SecItemServer.h>
32 #import <securityd/SecItemDb.h>
34 #import "keychain/ckks/CKKS.h"
35 #import "keychain/ckks/CKKSKeychainView.h"
36 #import "keychain/ckks/CKKSCurrentKeyPointer.h"
37 #import "keychain/ckks/CKKSItemEncrypter.h"
38 #import "keychain/ckks/CKKSKey.h"
39 #import "keychain/ckks/CKKSOutgoingQueueEntry.h"
40 #import "keychain/ckks/CKKSIncomingQueueEntry.h"
41 #import "keychain/ckks/CKKSSynchronizeOperation.h"
42 #import "keychain/ckks/CKKSViewManager.h"
43 #import "keychain/ckks/CKKSZoneStateEntry.h"
44 #import "keychain/ckks/CKKSManifest.h"
45 #import "keychain/ckks/CKKSPeer.h"
46 #import "keychain/categories/NSError+UsefulConstructors.h"
48 #import "keychain/ot/OTDefines.h"
50 #import "tests/secdmockaks/mockaks.h"
52 #pragma clang diagnostic push
53 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
54 #import "keychain/SecureObjectSync/SOSAccount.h"
55 #pragma clang diagnostic pop
57 @implementation ZoneKeys
58 - (instancetype)initLoadingRecordsFromZone:(FakeCKZone*)zone {
59 if((self = [super init])) {
60 CKRecordID* currentTLKPointerID = [[CKRecordID alloc] initWithRecordName:SecCKKSKeyClassTLK zoneID:zone.zoneID];
61 CKRecordID* currentClassAPointerID = [[CKRecordID alloc] initWithRecordName:SecCKKSKeyClassA zoneID:zone.zoneID];
62 CKRecordID* currentClassCPointerID = [[CKRecordID alloc] initWithRecordName:SecCKKSKeyClassC zoneID:zone.zoneID];
64 CKRecord* currentTLKPointerRecord = zone.currentDatabase[currentTLKPointerID];
65 CKRecord* currentClassAPointerRecord = zone.currentDatabase[currentClassAPointerID];
66 CKRecord* currentClassCPointerRecord = zone.currentDatabase[currentClassCPointerID];
68 self.currentTLKPointer = currentTLKPointerRecord ? [[CKKSCurrentKeyPointer alloc] initWithCKRecord: currentTLKPointerRecord] : nil;
69 self.currentClassAPointer = currentClassAPointerRecord ? [[CKKSCurrentKeyPointer alloc] initWithCKRecord: currentClassAPointerRecord] : nil;
70 self.currentClassCPointer = currentClassCPointerRecord ? [[CKKSCurrentKeyPointer alloc] initWithCKRecord: currentClassCPointerRecord] : nil;
72 CKRecordID* currentTLKID = self.currentTLKPointer.currentKeyUUID ? [[CKRecordID alloc] initWithRecordName:self.currentTLKPointer.currentKeyUUID zoneID:zone.zoneID] : nil;
73 CKRecordID* currentClassAID = self.currentClassAPointer.currentKeyUUID ? [[CKRecordID alloc] initWithRecordName:self.currentClassAPointer.currentKeyUUID zoneID:zone.zoneID] : nil;
74 CKRecordID* currentClassCID = self.currentClassCPointer.currentKeyUUID ? [[CKRecordID alloc] initWithRecordName:self.currentClassCPointer.currentKeyUUID zoneID:zone.zoneID] : nil;
76 CKRecord* currentTLKRecord = currentTLKID ? zone.currentDatabase[currentTLKID] : nil;
77 CKRecord* currentClassARecord = currentClassAID ? zone.currentDatabase[currentClassAID] : nil;
78 CKRecord* currentClassCRecord = currentClassCID ? zone.currentDatabase[currentClassCID] : nil;
80 self.tlk = currentTLKRecord ? [[CKKSKey alloc] initWithCKRecord: currentTLKRecord] : nil;
81 self.classA = currentClassARecord ? [[CKKSKey alloc] initWithCKRecord: currentClassARecord] : nil;
82 self.classC = currentClassCRecord ? [[CKKSKey alloc] initWithCKRecord: currentClassCRecord] : nil;
89 // No tests here, just helper functions
90 @implementation CloudKitKeychainSyncingMockXCTest
93 // Need to convince your tests to set these, no matter what the on-disk plist says? Uncomment.
94 (void)[CKKSManifest shouldSyncManifests]; // perfrom initialization
95 SecCKKSSetSyncManifests(false);
96 SecCKKSSetEnforceManifests(false);
98 // Check that your environment is set up correctly
99 XCTAssertFalse([CKKSManifest shouldSyncManifests], "Manifests syncing is disabled");
100 XCTAssertFalse([CKKSManifest shouldEnforceManifests], "Manifests enforcement is disabled");
102 // Use our superclass to create a fake keychain
105 self.automaticallyBeginCKKSViewCloudKitOperation = true;
106 self.suggestTLKUpload = OCMClassMock([CKKSNearFutureScheduler class]);
107 OCMStub([self.suggestTLKUpload trigger]);
109 self.ckksZones = [NSMutableSet set];
110 self.ckksViews = [NSMutableSet set];
111 self.keys = [[NSMutableDictionary alloc] init];
115 // Set up a remote peer with no keys
116 self.remoteSOSOnlyPeer = [[CKKSSOSPeer alloc] initWithSOSPeerID:@"remote-peer-with-no-keys"
117 encryptionPublicKey:nil
119 viewList:self.managedViewList];
120 NSMutableSet<id<CKKSSOSPeerProtocol>>* currentPeers = [NSMutableSet setWithObject:self.remoteSOSOnlyPeer];
121 self.mockSOSAdapter.trustedPeers = currentPeers;
123 // Fake out whether class A keys can be loaded from the keychain.
124 self.mockCKKSKeychainBackedKey = OCMClassMock([CKKSKeychainBackedKey class]);
125 __weak __typeof(self) weakSelf = self;
126 BOOL (^shouldFailKeychainQuery)(NSDictionary* query) = ^BOOL(NSDictionary* query) {
127 __strong __typeof(self) strongSelf = weakSelf;
128 return !!strongSelf.keychainFetchError;
131 OCMStub([self.mockCKKSKeychainBackedKey setKeyMaterialInKeychain:[OCMArg checkWithBlock:shouldFailKeychainQuery] error:[OCMArg anyObjectRef]]
132 ).andCall(self, @selector(handleFailedSetKeyMaterialInKeychain:error:));
134 OCMStub([self.mockCKKSKeychainBackedKey queryKeyMaterialInKeychain:[OCMArg checkWithBlock:shouldFailKeychainQuery] error:[OCMArg anyObjectRef]]
135 ).andCall(self, @selector(handleFailedLoadKeyMaterialFromKeychain:error:));
137 // Bring up a fake CKKSControl object
138 id mockConnection = OCMPartialMock([[NSXPCConnection alloc] init]);
139 OCMStub([mockConnection remoteObjectProxyWithErrorHandler:[OCMArg any]]).andCall(self, @selector(injectedManager));
140 self.ckksControl = [[CKKSControl alloc] initWithConnection:mockConnection];
141 XCTAssertNotNil(self.ckksControl, "Should have received control object");
143 self.accountMetaDataStore = OCMPartialMock([[OTCuttlefishAccountStateHolder alloc]init]);
144 OCMStub([self.accountMetaDataStore loadOrCreateAccountMetadata:[OCMArg anyObjectRef]]).andCall(self, @selector(loadOrCreateAccountMetadata:));
148 [self.mockCKKSKeychainBackedKey stopMocking];
149 self.mockCKKSKeychainBackedKey = nil;
151 // Make sure the key state machine won't be poked after teardown
152 for(CKKSKeychainView* view in self.ckksViews) {
153 [view.pokeKeyStateMachineScheduler cancel];
160 - (void)startCKKSSubsystem
162 [super startCKKSSubsystem];
163 if(self.mockSOSAdapter.circleStatus == kSOSCCInCircle) {
164 [self beginSOSTrustedOperationForAllViews];
166 [self endSOSTrustedOperationForAllViews];
170 - (void)beginSOSTrustedOperationForAllViews {
171 for(CKKSKeychainView* view in self.ckksViews) {
172 [self beginSOSTrustedViewOperation:view];
176 - (void)beginSOSTrustedViewOperation:(CKKSKeychainView*)view
178 if(self.automaticallyBeginCKKSViewCloudKitOperation) {
179 [view beginCloudKitOperation];
182 [view beginTrustedOperation:@[self.mockSOSAdapter] suggestTLKUpload:self.suggestTLKUpload];
185 - (void)endSOSTrustedOperationForAllViews {
186 for(CKKSKeychainView* view in self.ckksViews) {
187 [self endSOSTrustedViewOperation:view];
191 - (void)endSOSTrustedViewOperation:(CKKSKeychainView*)view
193 if(self.automaticallyBeginCKKSViewCloudKitOperation) {
194 [view beginCloudKitOperation];
196 [view endTrustedOperation];
199 - (void)verifyDatabaseMocks {
200 OCMVerifyAllWithDelay(self.mockDatabase, 20);
203 - (void)createClassCItemAndWaitForUpload:(CKRecordZoneID*)zoneID account:(NSString*)account {
204 [self expectCKModifyItemRecords:1
205 currentKeyPointerRecords:1
207 checkItem:[self checkClassCBlock:zoneID message:@"Object was encrypted under class C key in hierarchy"]];
208 [self addGenericPassword: @"data" account: account];
209 OCMVerifyAllWithDelay(self.mockDatabase, 20);
212 - (void)createClassAItemAndWaitForUpload:(CKRecordZoneID*)zoneID account:(NSString*)account {
213 [self expectCKModifyItemRecords:1
214 currentKeyPointerRecords:1
216 checkItem: [self checkClassABlock:zoneID message:@"Object was encrypted under class A key in hierarchy"]];
217 [self addGenericPassword:@"asdf"
220 access:(id)kSecAttrAccessibleWhenUnlocked
221 expecting:errSecSuccess
222 message:@"Adding class A item"];
223 OCMVerifyAllWithDelay(self.mockDatabase, 20);
226 // Helpers to handle 'failed' keychain loading and saving
227 - (bool)handleFailedLoadKeyMaterialFromKeychain:(NSDictionary*)query error:(NSError * __autoreleasing *) error {
228 NSAssert(self.keychainFetchError != nil, @"must have a keychain error to error with");
231 *error = self.keychainFetchError;
236 - (bool)handleFailedSetKeyMaterialInKeychain:(NSDictionary*)query error:(NSError * __autoreleasing *) error {
237 NSAssert(self.keychainFetchError != nil, @"must have a keychain error to error with");
240 *error = self.keychainFetchError;
246 - (ZoneKeys*)createFakeKeyHierarchy: (CKRecordZoneID*)zoneID oldTLK:(CKKSKey*) oldTLK {
247 if(self.keys[zoneID]) {
248 // Already created. Skip.
249 return self.keys[zoneID];
252 NSError* error = nil;
254 ZoneKeys* zonekeys = [[ZoneKeys alloc] init];
256 zonekeys.tlk = [self fakeTLK:zoneID];
257 [zonekeys.tlk CKRecordWithZoneID: zoneID]; // no-op here, but memoize in the object
258 zonekeys.currentTLKPointer = [[CKKSCurrentKeyPointer alloc] initForClass: SecCKKSKeyClassTLK currentKeyUUID: zonekeys.tlk.uuid zoneID:zoneID encodedCKRecord: nil];
259 [zonekeys.currentTLKPointer CKRecordWithZoneID: zoneID];
262 zonekeys.rolledTLK = oldTLK;
263 [zonekeys.rolledTLK wrapUnder: zonekeys.tlk error:&error];
264 XCTAssertNotNil(zonekeys.rolledTLK, "Created a rolled TLK");
265 XCTAssertNil(error, "No error creating rolled TLK");
268 zonekeys.classA = [CKKSKey randomKeyWrappedByParent: zonekeys.tlk keyclass:SecCKKSKeyClassA error:&error];
269 XCTAssertNotNil(zonekeys.classA, "make Class A key");
270 zonekeys.classA.currentkey = true;
271 [zonekeys.classA CKRecordWithZoneID: zoneID];
272 zonekeys.currentClassAPointer = [[CKKSCurrentKeyPointer alloc] initForClass: SecCKKSKeyClassA currentKeyUUID: zonekeys.classA.uuid zoneID:zoneID encodedCKRecord: nil];
273 [zonekeys.currentClassAPointer CKRecordWithZoneID: zoneID];
275 zonekeys.classC = [CKKSKey randomKeyWrappedByParent: zonekeys.tlk keyclass:SecCKKSKeyClassC error:&error];
276 XCTAssertNotNil(zonekeys.classC, "make Class C key");
277 zonekeys.classC.currentkey = true;
278 [zonekeys.classC CKRecordWithZoneID: zoneID];
279 zonekeys.currentClassCPointer = [[CKKSCurrentKeyPointer alloc] initForClass: SecCKKSKeyClassC currentKeyUUID: zonekeys.classC.uuid zoneID:zoneID encodedCKRecord: nil];
280 [zonekeys.currentClassCPointer CKRecordWithZoneID: zoneID];
282 self.keys[zoneID] = zonekeys;
286 - (void)saveFakeKeyHierarchyToLocalDatabase: (CKRecordZoneID*)zoneID {
287 NSError* error = nil;
288 ZoneKeys* zonekeys = [self createFakeKeyHierarchy: zoneID oldTLK:nil];
290 [zonekeys.tlk saveToDatabase:&error];
291 XCTAssertNil(error, "TLK saved to database successfully");
293 [zonekeys.classA saveToDatabase:&error];
294 XCTAssertNil(error, "Class A key saved to database successfully");
296 [zonekeys.classC saveToDatabase:&error];
297 XCTAssertNil(error, "Class C key saved to database successfully");
299 [zonekeys.currentTLKPointer saveToDatabase:&error];
300 XCTAssertNil(error, "Current TLK pointer saved to database successfully");
302 [zonekeys.currentClassAPointer saveToDatabase:&error];
303 XCTAssertNil(error, "Current Class A pointer saved to database successfully");
305 [zonekeys.currentClassCPointer saveToDatabase:&error];
306 XCTAssertNil(error, "Current Class C pointer saved to database successfully");
309 - (void)putFakeDeviceStatusInCloudKit:(CKRecordZoneID*)zoneID zonekeys:(ZoneKeys*)zonekeys {
310 // SOS peer IDs are written bare, missing the CKKSSOSPeerPrefix. Strip it here.
311 NSString* peerID = self.remoteSOSOnlyPeer.peerID;
312 if([peerID hasPrefix:CKKSSOSPeerPrefix]) {
313 peerID = [peerID substringFromIndex:CKKSSOSPeerPrefix.length];
316 CKKSDeviceStateEntry* dse = [[CKKSDeviceStateEntry alloc] initForDevice:self.remoteSOSOnlyPeer.peerID
317 osVersion:@"faux-version"
322 circleStatus:kSOSCCInCircle
323 keyState:SecCKKSZoneKeyStateReady
324 currentTLKUUID:zonekeys.tlk.uuid
325 currentClassAUUID:zonekeys.classA.uuid
326 currentClassCUUID:zonekeys.classC.uuid
328 encodedCKRecord:nil];
329 [self.zones[zoneID] addToZone:dse zoneID:zoneID];
332 - (void)putFakeDeviceStatusInCloudKit:(CKRecordZoneID*)zoneID {
333 [self putFakeDeviceStatusInCloudKit:zoneID zonekeys:self.keys[zoneID]];
336 - (void)putFakeOctagonOnlyDeviceStatusInCloudKit:(CKRecordZoneID*)zoneID zonekeys:(ZoneKeys*)zonekeys {
337 CKKSDeviceStateEntry* dse = [[CKKSDeviceStateEntry alloc] initForDevice:self.remoteSOSOnlyPeer.peerID
338 osVersion:@"faux-version"
340 octagonPeerID:@"octagon-fake-peer-id"
341 octagonStatus:[[OTCliqueStatusWrapper alloc] initWithStatus:CliqueStatusIn]
343 circleStatus:kSOSCCError
344 keyState:SecCKKSZoneKeyStateReady
345 currentTLKUUID:zonekeys.tlk.uuid
346 currentClassAUUID:zonekeys.classA.uuid
347 currentClassCUUID:zonekeys.classC.uuid
349 encodedCKRecord:nil];
350 [self.zones[zoneID] addToZone:dse zoneID:zoneID];
353 - (void)putFakeOctagonOnlyDeviceStatusInCloudKit:(CKRecordZoneID*)zoneID {
354 [self putFakeOctagonOnlyDeviceStatusInCloudKit:zoneID zonekeys:self.keys[zoneID]];
357 - (void)putFakeKeyHierarchyInCloudKit: (CKRecordZoneID*)zoneID {
358 ZoneKeys* zonekeys = [self createFakeKeyHierarchy: zoneID oldTLK:nil];
359 XCTAssertNotNil(zonekeys, "failed to create fake key hierarchy for zoneID=%@", zoneID);
361 FakeCKZone* zone = self.zones[zoneID];
362 XCTAssertNotNil(zone, "failed to find zone %@", zoneID);
364 dispatch_sync(zone.queue, ^{
365 [zone _onqueueAddToZone:zonekeys.tlk zoneID:zoneID];
366 [zone _onqueueAddToZone:zonekeys.classA zoneID:zoneID];
367 [zone _onqueueAddToZone:zonekeys.classC zoneID:zoneID];
369 [zone _onqueueAddToZone:zonekeys.currentTLKPointer zoneID:zoneID];
370 [zone _onqueueAddToZone:zonekeys.currentClassAPointer zoneID:zoneID];
371 [zone _onqueueAddToZone:zonekeys.currentClassCPointer zoneID:zoneID];
373 if(zonekeys.rolledTLK) {
374 [zone _onqueueAddToZone:zonekeys.rolledTLK zoneID:zoneID];
379 - (void)rollFakeKeyHierarchyInCloudKit: (CKRecordZoneID*)zoneID {
380 ZoneKeys* zonekeys = self.keys[zoneID];
381 self.keys[zoneID] = nil;
383 CKKSKey* oldTLK = zonekeys.tlk;
384 NSError* error = nil;
385 [oldTLK ensureKeyLoaded:&error];
386 XCTAssertNil(error, "shouldn't error ensuring that the oldTLK has its key material");
388 [self createFakeKeyHierarchy: zoneID oldTLK:oldTLK];
389 [self putFakeKeyHierarchyInCloudKit: zoneID];
392 - (void)ensureZoneDeletionAllowed:(FakeCKZone*)zone {
393 [super ensureZoneDeletionAllowed:zone];
395 // Here's a hack: if we're deleting this zone, also drop the keys that used to be in it
396 self.keys[zone.zoneID] = nil;
399 - (NSArray<CKRecord*>*)putKeySetInCloudKit:(CKKSCurrentKeySet*)keyset
401 XCTAssertNotNil(keyset.tlk, "Should have a TLK to put a key set in CloudKit");
402 CKRecordZoneID* zoneID = keyset.tlk.zoneID;
403 XCTAssertNotNil(zoneID, "Should have a zoneID to put a key set in CloudKit");
405 ZoneKeys* zonekeys = self.keys[zoneID];
406 XCTAssertNil(zonekeys, "Should not already have zone keys when putting keyset in cloudkit");
407 zonekeys = [[ZoneKeys alloc] initForZoneName:zoneID.zoneName];
409 FakeCKZone* zone = self.zones[zoneID];
410 // Cuttlefish makes this for you, but for now assert if there's an issue
411 XCTAssertNotNil(zone, "Should already have a fakeckzone before putting a keyset in it");
413 __block NSMutableArray<CKRecord*>* newRecords = [NSMutableArray array];
414 dispatch_sync(zone.queue, ^{
415 [newRecords addObject:[zone _onqueueAddToZone:keyset.tlk zoneID:zoneID]];
416 [newRecords addObject:[zone _onqueueAddToZone:keyset.classA zoneID:zoneID]];
417 [newRecords addObject:[zone _onqueueAddToZone:keyset.classC zoneID:zoneID]];
419 [newRecords addObject:[zone _onqueueAddToZone:keyset.currentTLKPointer zoneID:zoneID]];
420 [newRecords addObject:[zone _onqueueAddToZone:keyset.currentClassAPointer zoneID:zoneID]];
421 [newRecords addObject:[zone _onqueueAddToZone:keyset.currentClassCPointer zoneID:zoneID]];
423 // TODO handle a rolled TLK
424 //if(zonekeys.rolledTLK) {
425 // [zone _onqueueAddToZone:zonekeys.rolledTLK zoneID:zoneID];
428 zonekeys.tlk = keyset.tlk;
429 zonekeys.classA = keyset.classA;
430 zonekeys.classC = keyset.classC;
431 self.keys[zoneID] = zonekeys;
433 // Octagon uploads the pending TLKshares, not all of them
434 for(CKKSTLKShareRecord* tlkshare in keyset.pendingTLKShares) {
435 [newRecords addObject:[zone _onqueueAddToZone:tlkshare zoneID:zoneID]];
442 - (void)performOctagonTLKUpload:(NSSet<CKKSKeychainView*>*)views
444 [self performOctagonTLKUpload:views afterUpload:nil];
447 - (void)performOctagonTLKUpload:(NSSet<CKKSKeychainView*>*)views afterUpload:(void (^_Nullable)(void))afterUpload
449 NSMutableArray<CKKSResultOperation<CKKSKeySetProviderOperationProtocol>*>* keysetOps = [NSMutableArray array];
451 for(CKKSKeychainView* view in views) {
452 XCTAssertEqual(0, [view.keyHierarchyConditions[SecCKKSZoneKeyStateWaitForTLKCreation] wait:40*NSEC_PER_SEC], @"key state should enter 'waitfortlkcreation' (view %@)", view);
453 [keysetOps addObject: [view findKeySet]];
456 // Now that we've kicked them all off, wait for them to resolve
457 for(CKKSKeychainView* view in views) {
458 XCTAssertEqual(0, [view.keyHierarchyConditions[SecCKKSZoneKeyStateWaitForTLKUpload] wait:40*NSEC_PER_SEC], @"key state should enter 'waitfortlkupload'");
461 NSMutableArray<CKRecord*>* keyHierarchyRecords = [NSMutableArray array];
463 for(CKKSResultOperation<CKKSKeySetProviderOperationProtocol>* keysetOp in keysetOps) {
464 // Wait until finished is usually a bad idea. We could rip this out into an operation if we'd like.
465 [keysetOp waitUntilFinished];
466 XCTAssertNil(keysetOp.error, "Should be no error fetching keyset from CKKS");
468 NSArray<CKRecord*>* records = [self putKeySetInCloudKit:keysetOp.keyset];
469 [keyHierarchyRecords addObjectsFromArray:records];
476 // Tell our views about our shiny new records!
477 for(CKKSKeychainView* view in views) {
478 [view receiveTLKUploadRecords: keyHierarchyRecords];
482 - (void)saveTLKMaterialToKeychainSimulatingSOS: (CKRecordZoneID*)zoneID {
484 XCTAssertNotNil(self.keys[zoneID].tlk, "Have a TLK to save for zone %@", zoneID);
486 __block CFErrorRef cferror = NULL;
487 kc_with_dbt(true, &cferror, ^bool (SecDbConnectionRef dbt) {
488 bool ok = kc_transaction_type(dbt, kSecDbExclusiveRemoteSOSTransactionType, &cferror, ^bool {
489 NSError* error = nil;
490 [self.keys[zoneID].tlk saveKeyMaterialToKeychain: false error:&error];
491 XCTAssertNil(error, @"Saved TLK material to keychain");
497 XCTAssertNil( (__bridge NSError*)cferror, @"no error with transaction");
498 CFReleaseNull(cferror);
500 static SOSFullPeerInfoRef SOSCreateFullPeerInfoFromName(CFStringRef name,
501 SecKeyRef* outSigningKey,
502 SecKeyRef* outOctagonSigningKey,
503 SecKeyRef* outOctagonEncryptionKey,
506 SOSFullPeerInfoRef result = NULL;
507 SecKeyRef publicKey = NULL;
508 CFDictionaryRef gestalt = NULL;
510 *outSigningKey = GeneratePermanentFullECKey(256, name, error);
512 *outOctagonSigningKey = GeneratePermanentFullECKey(384, name, error);
513 *outOctagonEncryptionKey = GeneratePermanentFullECKey(384, name, error);
515 gestalt = SOSCreatePeerGestaltFromName(name);
517 result = SOSFullPeerInfoCreate(NULL, gestalt, NULL, *outSigningKey,
518 *outOctagonSigningKey, *outOctagonEncryptionKey,
521 CFReleaseNull(gestalt);
522 CFReleaseNull(publicKey);
526 - (NSMutableArray<NSData *>*) SOSPiggyICloudIdentities
528 SecKeyRef signingKey = NULL;
529 SecKeyRef octagonSigningKey = NULL;
530 SecKeyRef octagonEncryptionKey = NULL;
531 NSMutableArray<NSData *>* icloudidentities = [NSMutableArray array];
533 SOSFullPeerInfoRef fpi = SOSCreateFullPeerInfoFromName(CFSTR("Test Peer"), &signingKey, &octagonSigningKey, &octagonEncryptionKey, NULL);
535 NSData *data = CFBridgingRelease(SOSPeerInfoCopyData(SOSFullPeerInfoGetPeerInfo(fpi), NULL));
538 [icloudidentities addObject:data];
540 CFReleaseNull(signingKey);
541 CFReleaseNull(octagonSigningKey);
542 CFReleaseNull(octagonEncryptionKey);
544 return icloudidentities;
546 static CFDictionaryRef SOSCreatePeerGestaltFromName(CFStringRef name)
548 return CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
549 kPIUserDefinedDeviceNameKey, name,
552 -(NSMutableDictionary*)SOSPiggyBackCopyFromKeychain
554 __block NSMutableDictionary *piggybackdata = [[NSMutableDictionary alloc] init];
555 __block CFErrorRef cferror = NULL;
556 kc_with_dbt(true, &cferror, ^bool (SecDbConnectionRef dbt) {
557 bool ok = kc_transaction_type(dbt, kSecDbExclusiveRemoteSOSTransactionType, &cferror, ^bool {
558 piggybackdata[@"idents"] = [self SOSPiggyICloudIdentities];
559 piggybackdata[@"tlk"] = SOSAccountGetAllTLKs();
566 XCTAssertNil( (__bridge NSError*)cferror, @"no error with transaction");
567 CFReleaseNull(cferror);
568 return piggybackdata;
570 - (void)SOSPiggyBackAddToKeychain:(NSDictionary*)piggydata{
571 __block CFErrorRef cferror = NULL;
572 kc_with_dbt(true, &cferror, ^bool (SecDbConnectionRef dbt) {
573 bool ok = kc_transaction_type(dbt, kSecDbExclusiveRemoteSOSTransactionType, &cferror, ^bool {
574 NSError* error = nil;
575 NSArray* icloudidentities = piggydata[@"idents"];
576 NSArray* tlk = piggydata[@"tlk"];
578 SOSPiggyBackAddToKeychain(icloudidentities, tlk);
580 XCTAssertNil(error, @"Saved TLK-piggy material to keychain");
586 XCTAssertNil( (__bridge NSError*)cferror, @"no error with transaction");
587 CFReleaseNull(cferror);
590 - (void)saveTLKMaterialToKeychain: (CKRecordZoneID*)zoneID {
591 NSError* error = nil;
592 XCTAssertNotNil(self.keys[zoneID].tlk, "Have a TLK to save for zone %@", zoneID);
594 // Don't make the stashed local copy of the TLK
595 [self.keys[zoneID].tlk saveKeyMaterialToKeychain:false error:&error];
596 XCTAssertNil(error, @"Saved TLK material to keychain");
599 - (void)deleteTLKMaterialFromKeychain: (CKRecordZoneID*)zoneID {
600 NSError* error = nil;
601 XCTAssertNotNil(self.keys[zoneID].tlk, "Have a TLK to save for zone %@", zoneID);
602 [self.keys[zoneID].tlk deleteKeyMaterialFromKeychain:&error];
603 XCTAssertNil(error, @"Saved TLK material to keychain");
606 - (void)saveClassKeyMaterialToKeychain: (CKRecordZoneID*)zoneID {
607 NSError* error = nil;
608 XCTAssertNotNil(self.keys[zoneID].classA, "Have a Class A to save for zone %@", zoneID);
609 [self.keys[zoneID].classA saveKeyMaterialToKeychain:&error];
610 XCTAssertNil(error, @"Saved Class A material to keychain");
612 XCTAssertNotNil(self.keys[zoneID].classC, "Have a Class C to save for zone %@", zoneID);
613 [self.keys[zoneID].classC saveKeyMaterialToKeychain:&error];
614 XCTAssertNil(error, @"Saved Class C material to keychain");
618 - (void)putTLKShareInCloudKit:(CKKSKey*)key
619 from:(id<CKKSSelfPeer>)sharingPeer
620 to:(id<CKKSPeer>)receivingPeer
621 zoneID:(CKRecordZoneID*)zoneID
623 NSError* error = nil;
624 CKKSTLKShareRecord* share = [CKKSTLKShareRecord share:key
630 XCTAssertNil(error, "Should have been no error sharing a CKKSKey");
631 XCTAssertNotNil(share, "Should be able to create a share");
633 CKRecord* shareRecord = [share CKRecordWithZoneID: zoneID];
634 XCTAssertNotNil(shareRecord, "Should have been able to create a CKRecord");
636 FakeCKZone* zone = self.zones[zoneID];
637 XCTAssertNotNil(zone, "Should have a zone to put a TLKShare in");
638 [zone addToZone:shareRecord];
640 ZoneKeys* keys = self.keys[zoneID];
641 XCTAssertNotNil(keys, "Have a zonekeys object for this zone");
642 keys.tlkShares = keys.tlkShares ? [keys.tlkShares arrayByAddingObject:share] : @[share];
645 - (void)putTLKSharesInCloudKit:(CKKSKey*)key
646 from:(id<CKKSSelfPeer>)sharingPeer
647 zoneID:(CKRecordZoneID*)zoneID
649 NSSet* peers = [self.mockSOSAdapter.trustedPeers setByAddingObject:self.mockSOSAdapter.selfPeer];
651 for(id<CKKSPeer> peer in peers) {
652 // Can only send to peers with encryption keys
653 if(peer.publicEncryptionKey) {
654 [self putTLKShareInCloudKit:key from:sharingPeer to:peer zoneID:zoneID];
659 - (void)putSelfTLKSharesInCloudKit:(CKRecordZoneID*)zoneID {
660 CKKSKey* tlk = self.keys[zoneID].tlk;
661 XCTAssertNotNil(tlk, "Should have a TLK for zone %@", zoneID);
662 [self putTLKSharesInCloudKit:tlk from:self.mockSOSAdapter.selfPeer zoneID:zoneID];
665 - (void)saveTLKSharesInLocalDatabase:(CKRecordZoneID*)zoneID {
666 ZoneKeys* keys = self.keys[zoneID];
667 XCTAssertNotNil(keys, "Have a zonekeys object for this zone");
669 for(CKKSTLKShareRecord* share in keys.tlkShares) {
670 NSError* error = nil;
671 [share saveToDatabase:&error];
672 XCTAssertNil(error, "Shouldn't have been an error saving a TLKShare to the database");
676 - (void)createAndSaveFakeKeyHierarchy: (CKRecordZoneID*)zoneID {
677 // Put in CloudKit first, so the records on-disk will have the right change tags
678 [self putFakeKeyHierarchyInCloudKit: zoneID];
679 [self saveFakeKeyHierarchyToLocalDatabase: zoneID];
680 [self saveTLKMaterialToKeychain: zoneID];
681 [self saveClassKeyMaterialToKeychain: zoneID];
683 [self putSelfTLKSharesInCloudKit:zoneID];
684 [self saveTLKSharesInLocalDatabase:zoneID];
687 // Override our base class here, but only for Keychain Views
689 - (void)expectCKModifyRecords:(NSDictionary<NSString*, NSNumber*>*)expectedRecordTypeCounts
690 deletedRecordTypeCounts:(NSDictionary<NSString*, NSNumber*>*)expectedDeletedRecordTypeCounts
691 zoneID:(CKRecordZoneID*)zoneID
692 checkModifiedRecord:(BOOL (^)(CKRecord*))checkRecord
693 runAfterModification:(void (^) (void))afterModification
696 void (^newAfterModification)(void) = afterModification;
697 if([self.ckksZones containsObject:zoneID]) {
698 __weak __typeof(self) weakSelf = self;
699 newAfterModification = ^{
700 __strong __typeof(weakSelf) strongSelf = weakSelf;
701 XCTAssertNotNil(strongSelf, "self exists");
703 // Reach into our cloudkit database and extract the keys
704 CKRecordID* currentTLKPointerID = [[CKRecordID alloc] initWithRecordName:SecCKKSKeyClassTLK zoneID:zoneID];
705 CKRecordID* currentClassAPointerID = [[CKRecordID alloc] initWithRecordName:SecCKKSKeyClassA zoneID:zoneID];
706 CKRecordID* currentClassCPointerID = [[CKRecordID alloc] initWithRecordName:SecCKKSKeyClassC zoneID:zoneID];
708 ZoneKeys* zonekeys = strongSelf.keys[zoneID];
710 zonekeys = [[ZoneKeys alloc] init];
711 strongSelf.keys[zoneID] = zonekeys;
714 XCTAssertNotNil(strongSelf.zones[zoneID].currentDatabase[currentTLKPointerID], "Have a currentTLKPointer");
715 XCTAssertNotNil(strongSelf.zones[zoneID].currentDatabase[currentClassAPointerID], "Have a currentClassAPointer");
716 XCTAssertNotNil(strongSelf.zones[zoneID].currentDatabase[currentClassCPointerID], "Have a currentClassCPointer");
717 XCTAssertNotNil(strongSelf.zones[zoneID].currentDatabase[currentTLKPointerID][SecCKRecordParentKeyRefKey], "Have a currentTLKPointer parent");
718 XCTAssertNotNil(strongSelf.zones[zoneID].currentDatabase[currentClassAPointerID][SecCKRecordParentKeyRefKey], "Have a currentClassAPointer parent");
719 XCTAssertNotNil(strongSelf.zones[zoneID].currentDatabase[currentClassCPointerID][SecCKRecordParentKeyRefKey], "Have a currentClassCPointer parent");
720 XCTAssertNotNil([strongSelf.zones[zoneID].currentDatabase[currentTLKPointerID][SecCKRecordParentKeyRefKey] recordID].recordName, "Have a currentTLKPointer parent UUID");
721 XCTAssertNotNil([strongSelf.zones[zoneID].currentDatabase[currentClassAPointerID][SecCKRecordParentKeyRefKey] recordID].recordName, "Have a currentClassAPointer parent UUID");
722 XCTAssertNotNil([strongSelf.zones[zoneID].currentDatabase[currentClassCPointerID][SecCKRecordParentKeyRefKey] recordID].recordName, "Have a currentClassCPointer parent UUID");
724 zonekeys.currentTLKPointer = [[CKKSCurrentKeyPointer alloc] initWithCKRecord: strongSelf.zones[zoneID].currentDatabase[currentTLKPointerID]];
725 zonekeys.currentClassAPointer = [[CKKSCurrentKeyPointer alloc] initWithCKRecord: strongSelf.zones[zoneID].currentDatabase[currentClassAPointerID]];
726 zonekeys.currentClassCPointer = [[CKKSCurrentKeyPointer alloc] initWithCKRecord: strongSelf.zones[zoneID].currentDatabase[currentClassCPointerID]];
728 XCTAssertNotNil(zonekeys.currentTLKPointer.currentKeyUUID, "Have a currentTLKPointer current UUID");
729 XCTAssertNotNil(zonekeys.currentClassAPointer.currentKeyUUID, "Have a currentClassAPointer current UUID");
730 XCTAssertNotNil(zonekeys.currentClassCPointer.currentKeyUUID, "Have a currentClassCPointer current UUID");
732 CKRecordID* currentTLKID = [[CKRecordID alloc] initWithRecordName:zonekeys.currentTLKPointer.currentKeyUUID zoneID:zoneID];
733 CKRecordID* currentClassAID = [[CKRecordID alloc] initWithRecordName:zonekeys.currentClassAPointer.currentKeyUUID zoneID:zoneID];
734 CKRecordID* currentClassCID = [[CKRecordID alloc] initWithRecordName:zonekeys.currentClassCPointer.currentKeyUUID zoneID:zoneID];
736 zonekeys.tlk = [[CKKSKey alloc] initWithCKRecord: strongSelf.zones[zoneID].currentDatabase[currentTLKID]];
737 zonekeys.classA = [[CKKSKey alloc] initWithCKRecord: strongSelf.zones[zoneID].currentDatabase[currentClassAID]];
738 zonekeys.classC = [[CKKSKey alloc] initWithCKRecord: strongSelf.zones[zoneID].currentDatabase[currentClassCID]];
740 XCTAssertNotNil(zonekeys.tlk, "Have the current TLK");
741 XCTAssertNotNil(zonekeys.classA, "Have the current Class A key");
742 XCTAssertNotNil(zonekeys.classC, "Have the current Class C key");
744 NSMutableArray<CKKSTLKShareRecord*>* shares = [NSMutableArray array];
745 for(CKRecordID* recordID in strongSelf.zones[zoneID].currentDatabase.allKeys) {
746 if([recordID.recordName hasPrefix: [CKKSTLKShareRecord ckrecordPrefix]]) {
747 CKKSTLKShareRecord* share = [[CKKSTLKShareRecord alloc] initWithCKRecord:strongSelf.zones[zoneID].currentDatabase[recordID]];
748 XCTAssertNotNil(share, "Should be able to parse a CKKSTLKShare CKRecord into a CKKSTLKShare");
749 [shares addObject:share];
752 zonekeys.tlkShares = shares;
754 if(afterModification) {
760 [super expectCKModifyRecords:expectedRecordTypeCounts
761 deletedRecordTypeCounts:expectedDeletedRecordTypeCounts
763 checkModifiedRecord:checkRecord
764 runAfterModification:newAfterModification];
767 - (void)expectCKReceiveSyncKeyHierarchyError:(CKRecordZoneID*)zoneID {
769 __weak __typeof(self) weakSelf = self;
770 [[self.mockDatabase expect] addOperation:[OCMArg checkWithBlock:^BOOL(id obj) {
771 __strong __typeof(weakSelf) strongSelf = weakSelf;
772 XCTAssertNotNil(strongSelf, "self exists");
774 __block bool rejected = false;
775 if ([obj isKindOfClass:[CKModifyRecordsOperation class]]) {
776 CKModifyRecordsOperation *op = (CKModifyRecordsOperation *)obj;
779 // We only care about atomic operations
783 // We want to only match zone updates pertaining to this zone
784 for(CKRecord* record in op.recordsToSave) {
785 if(![record.recordID.zoneID isEqual: zoneID]) {
790 // we oly want to match updates that are updating a class C or class A CKP
791 bool updatingClassACKP = false;
792 bool updatingClassCCKP = false;
793 for(CKRecord* record in op.recordsToSave) {
794 if([record.recordID.recordName isEqualToString:SecCKKSKeyClassA]) {
795 updatingClassACKP = true;
797 if([record.recordID.recordName isEqualToString:SecCKKSKeyClassC]) {
798 updatingClassCCKP = true;
802 if(!updatingClassACKP && !updatingClassCCKP) {
806 FakeCKZone* zone = strongSelf.zones[zoneID];
807 XCTAssertNotNil(zone, "Should have a zone for these records");
809 // We only want to match if the synckeys aren't pointing correctly
811 ZoneKeys* zonekeys = [[ZoneKeys alloc] initLoadingRecordsFromZone:zone];
813 XCTAssertNotNil(zonekeys.currentTLKPointer, "Have a currentTLKPointer");
814 XCTAssertNotNil(zonekeys.currentClassAPointer, "Have a currentClassAPointer");
815 XCTAssertNotNil(zonekeys.currentClassCPointer, "Have a currentClassCPointer");
817 XCTAssertNotNil(zonekeys.tlk, "Have the current TLK");
818 XCTAssertNotNil(zonekeys.classA, "Have the current Class A key");
819 XCTAssertNotNil(zonekeys.classC, "Have the current Class C key");
821 // Ensure that either the Class A synckey or the class C synckey do not immediately wrap to the current TLK
822 bool classALinkBroken = ![zonekeys.classA.parentKeyUUID isEqualToString:zonekeys.tlk.uuid];
823 bool classCLinkBroken = ![zonekeys.classC.parentKeyUUID isEqualToString:zonekeys.tlk.uuid];
825 // Neither synckey link is broken. Don't match this operation.
826 if(!classALinkBroken && !classCLinkBroken) {
830 NSMutableDictionary<CKRecordID*, NSError*>* failedRecords = [[NSMutableDictionary alloc] init];
832 @synchronized(zone.currentDatabase) {
833 for(CKRecord* record in op.recordsToSave) {
834 if(classALinkBroken && [record.recordID.recordName isEqualToString:SecCKKSKeyClassA]) {
835 failedRecords[record.recordID] = [strongSelf ckInternalServerExtensionError:CKKSServerUnexpectedSyncKeyInChain description:@"synckey record: current classA synckey does not point to current tlk synckey"];
838 if(classCLinkBroken && [record.recordID.recordName isEqualToString:SecCKKSKeyClassC]) {
839 failedRecords[record.recordID] = [strongSelf ckInternalServerExtensionError:CKKSServerUnexpectedSyncKeyInChain description:@"synckey record: current classC synckey does not point to current tlk synckey"];
846 [strongSelf rejectWrite: op failedRecords:failedRecords];
849 return rejected ? YES : NO;
853 - (void)checkNoCKKSData: (CKKSKeychainView*) view {
854 // Test that there are no items in the database
855 [view dispatchSync:^bool{
856 NSError* error = nil;
857 NSArray<CKKSMirrorEntry*>* ckmes = [CKKSMirrorEntry all: view.zoneID error:&error];
858 XCTAssertNil(error, "No error fetching CKMEs");
859 XCTAssertEqual(ckmes.count, 0ul, "No CKMirrorEntries");
861 NSArray<CKKSOutgoingQueueEntry*>* oqes = [CKKSOutgoingQueueEntry all: view.zoneID error:&error];
862 XCTAssertNil(error, "No error fetching OQEs");
863 XCTAssertEqual(oqes.count, 0ul, "No OutgoingQueueEntries");
865 NSArray<CKKSIncomingQueueEntry*>* iqes = [CKKSIncomingQueueEntry all: view.zoneID error:&error];
866 XCTAssertNil(error, "No error fetching IQEs");
867 XCTAssertEqual(iqes.count, 0ul, "No IncomingQueueEntries");
869 NSArray<CKKSKey*>* keys = [CKKSKey all: view.zoneID error:&error];
870 XCTAssertNil(error, "No error fetching keys");
871 XCTAssertEqual(keys.count, 0ul, "No CKKSKeys");
873 NSArray<CKKSDeviceStateEntry*>* deviceStates = [CKKSDeviceStateEntry allInZone:view.zoneID error:&error];
874 XCTAssertNil(error, "should be no error fetching device states");
875 XCTAssertEqual(deviceStates.count, 0ul, "No Device State entries");
880 - (BOOL (^) (CKRecord*)) checkClassABlock: (CKRecordZoneID*) zoneID message:(NSString*) message {
881 __weak __typeof(self) weakSelf = self;
882 return ^BOOL(CKRecord* record) {
883 __strong __typeof(weakSelf) strongSelf = weakSelf;
884 XCTAssertNotNil(strongSelf, "self exists");
886 ZoneKeys* zoneKeys = strongSelf.keys[zoneID];
887 XCTAssertNotNil(zoneKeys, "Have zone keys for %@", zoneID);
888 XCTAssertEqualObjects([record[SecCKRecordParentKeyRefKey] recordID].recordName, zoneKeys.classA.uuid, "%@", message);
889 return [[record[SecCKRecordParentKeyRefKey] recordID].recordName isEqual: zoneKeys.classA.uuid];
893 - (BOOL (^) (CKRecord*)) checkClassCBlock: (CKRecordZoneID*) zoneID message:(NSString*) message {
894 __weak __typeof(self) weakSelf = self;
895 return ^BOOL(CKRecord* record) {
896 __strong __typeof(weakSelf) strongSelf = weakSelf;
897 XCTAssertNotNil(strongSelf, "self exists");
899 ZoneKeys* zoneKeys = strongSelf.keys[zoneID];
900 XCTAssertNotNil(zoneKeys, "Have zone keys for %@", zoneID);
901 XCTAssertEqualObjects([record[SecCKRecordParentKeyRefKey] recordID].recordName, zoneKeys.classC.uuid, "%@", message);
902 return [[record[SecCKRecordParentKeyRefKey] recordID].recordName isEqual: zoneKeys.classC.uuid];
906 - (BOOL (^) (CKRecord*)) checkPasswordBlock:(CKRecordZoneID*)zoneID
907 account:(NSString*)account
908 password:(NSString*)password {
909 __weak __typeof(self) weakSelf = self;
910 return ^BOOL(CKRecord* record) {
911 __strong __typeof(weakSelf) strongSelf = weakSelf;
912 XCTAssertNotNil(strongSelf, "self exists");
914 ZoneKeys* zoneKeys = strongSelf.keys[zoneID];
915 XCTAssertNotNil(zoneKeys, "Have zone keys for %@", zoneID);
916 XCTAssertNotNil([record[SecCKRecordParentKeyRefKey] recordID].recordName, "Have a wrapping key");
919 if([[record[SecCKRecordParentKeyRefKey] recordID].recordName isEqualToString: zoneKeys.classC.uuid]) {
920 key = zoneKeys.classC;
921 } else if([[record[SecCKRecordParentKeyRefKey] recordID].recordName isEqualToString: zoneKeys.classA.uuid]) {
922 key = zoneKeys.classA;
924 XCTAssertNotNil(key, "Found a key via UUID");
926 CKKSMirrorEntry* ckme = [[CKKSMirrorEntry alloc] initWithCKRecord: record];
928 NSError* error = nil;
929 NSDictionary* dict = [CKKSItemEncrypter decryptItemToDictionary:ckme.item error:&error];
930 XCTAssertNil(error, "No error decrypting item");
931 XCTAssertEqualObjects(account, dict[(id)kSecAttrAccount], "Account matches");
932 XCTAssertEqualObjects([password dataUsingEncoding:NSUTF8StringEncoding], dict[(id)kSecValueData], "Password matches");
937 - (NSDictionary*)fakeRecordDictionary:(NSString*) account zoneID:(CKRecordZoneID*)zoneID {
938 NSError* error = nil;
941 @"acct" : @"account-delete-me",
942 @"agrp" : @"com.apple.security.sos",
943 @"cdat" : @"2016-12-21 03:33:25 +0000",
945 @"mdat" : @"2016-12-21 03:33:25 +0000",
946 @"musr" : [[NSData alloc] init],
948 @"sha1" : [[NSData alloc] initWithBase64EncodedString: @"C3VWONaOIj8YgJjk/xwku4By1CY=" options:0],
950 @"tomb" : [NSNumber numberWithInt: 0],
951 @"v_Data" : [@"data" dataUsingEncoding: NSUTF8StringEncoding],
953 TODO: this should be binary encoded instead of expanded, but the plist encoder should handle it fine */
954 NSData* itemdata = [[NSData alloc] initWithBase64EncodedString:@"PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NUWVBFIHBsaXN0IFBVQkxJQyAiLS8vQXBwbGUvL0RURCBQTElTVCAxLjAvL0VOIiAiaHR0cDovL3d3dy5hcHBsZS5jb20vRFREcy9Qcm9wZXJ0eUxpc3QtMS4wLmR0ZCI+CjxwbGlzdCB2ZXJzaW9uPSIxLjAiPgo8ZGljdD4KCTxrZXk+YWNjdDwva2V5PgoJPHN0cmluZz5hY2NvdW50LWRlbGV0ZS1tZTwvc3RyaW5nPgoJPGtleT5hZ3JwPC9rZXk+Cgk8c3RyaW5nPmNvbS5hcHBsZS5zZWN1cml0eS5zb3M8L3N0cmluZz4KCTxrZXk+Y2RhdDwva2V5PgoJPGRhdGU+MjAxNi0xMi0yMVQwMzozMzoyNVo8L2RhdGU+Cgk8a2V5PmNsYXNzPC9rZXk+Cgk8c3RyaW5nPmdlbnA8L3N0cmluZz4KCTxrZXk+bWRhdDwva2V5PgoJPGRhdGU+MjAxNi0xMi0yMVQwMzozMzoyNVo8L2RhdGU+Cgk8a2V5Pm11c3I8L2tleT4KCTxkYXRhPgoJPC9kYXRhPgoJPGtleT5wZG1uPC9rZXk+Cgk8c3RyaW5nPmFrPC9zdHJpbmc+Cgk8a2V5PnNoYTE8L2tleT4KCTxkYXRhPgoJQzNWV09OYU9JajhZZ0pqay94d2t1NEJ5MUNZPQoJPC9kYXRhPgoJPGtleT5zdmNlPC9rZXk+Cgk8c3RyaW5nPjwvc3RyaW5nPgoJPGtleT50b21iPC9rZXk+Cgk8aW50ZWdlcj4wPC9pbnRlZ2VyPgoJPGtleT52X0RhdGE8L2tleT4KCTxkYXRhPgoJWkdGMFlRPT0KCTwvZGF0YT4KPC9kaWN0Pgo8L3BsaXN0Pgo=" options:0];
955 NSMutableDictionary * item = [[NSPropertyListSerialization propertyListWithData:itemdata
958 error:&error] mutableCopy];
960 item[@"agrp"] = @"com.apple.security.ckks";
961 item[@"vwht"] = @"keychain";
962 XCTAssertNil(error, "no error interpreting data as item");
963 XCTAssertNotNil(item, "interpreted data as item");
965 if(zoneID && ![zoneID.zoneName isEqualToString:@"keychain"]) {
966 [item setObject: zoneID.zoneName forKey: (__bridge id) kSecAttrSyncViewHint];
970 [item setObject: account forKey: (__bridge id) kSecAttrAccount];
975 - (CKRecord*)createFakeRecord: (CKRecordZoneID*)zoneID recordName:(NSString*)recordName {
976 return [self createFakeRecord: zoneID recordName:recordName withAccount: nil key:nil];
979 - (CKRecord*)createFakeRecord: (CKRecordZoneID*)zoneID recordName:(NSString*)recordName withAccount: (NSString*) account {
980 return [self createFakeRecord: zoneID recordName:recordName withAccount:account key:nil];
983 - (CKRecord*)createFakeRecord: (CKRecordZoneID*)zoneID recordName:(NSString*)recordName withAccount: (NSString*) account key:(CKKSKey*)key {
984 NSMutableDictionary* item = [[self fakeRecordDictionary: account zoneID:zoneID] mutableCopy];
986 // class c items should be class c
987 if([key.keyclass isEqualToString:SecCKKSKeyClassC]) {
988 item[(__bridge NSString*)kSecAttrAccessible] = @"ck";
991 CKRecordID* ckrid = [[CKRecordID alloc] initWithRecordName:recordName zoneID:zoneID];
993 return [self newRecord: ckrid withNewItemData:item key:key];
995 return [self newRecord: ckrid withNewItemData:item];
999 - (CKRecord*)newRecord: (CKRecordID*) recordID withNewItemData:(NSDictionary*) dictionary {
1000 ZoneKeys* zonekeys = self.keys[recordID.zoneID];
1001 XCTAssertNotNil(zonekeys, "Have zone keys for zone");
1002 XCTAssertNotNil(zonekeys.classC, "Have class C key for zone");
1004 return [self newRecord:recordID withNewItemData:dictionary key:zonekeys.classC];
1007 - (CKKSItem*)newItem:(CKRecordID*)recordID withNewItemData:(NSDictionary*)dictionary key:(CKKSKey*)key {
1008 NSError* error = nil;
1009 CKKSItem* cipheritem = [CKKSItemEncrypter encryptCKKSItem:[[CKKSItem alloc] initWithUUID:recordID.recordName
1010 parentKeyUUID:key.uuid
1011 zoneID:recordID.zoneID]
1012 dataDictionary:dictionary
1013 updatingCKKSItem:nil
1016 XCTAssertNil(error, "encrypted item with class c key");
1017 XCTAssertNotNil(cipheritem, "Have an encrypted item");
1022 - (CKRecord*)newRecord: (CKRecordID*) recordID withNewItemData:(NSDictionary*) dictionary key:(CKKSKey*)key {
1023 CKKSItem* item = [self newItem:recordID withNewItemData:dictionary key:key];
1025 CKRecord* ckr = [item CKRecordWithZoneID: recordID.zoneID];
1026 XCTAssertNotNil(ckr, "Created a CKRecord");
1030 - (NSDictionary*)decryptRecord: (CKRecord*) record {
1031 CKKSItem* item = [[CKKSItem alloc] initWithCKRecord: record];
1033 NSError* error = nil;
1035 NSDictionary* ret = [CKKSItemEncrypter decryptItemToDictionary: item error:&error];
1036 XCTAssertNil(error);
1037 XCTAssertNotNil(ret);
1041 - (void)addGenericPassword: (NSString*) password account: (NSString*) account viewHint: (NSString*) viewHint access: (NSString*) access expecting: (OSStatus) status message: (NSString*) message {
1042 NSMutableDictionary* query = [@{
1043 (id)kSecClass : (id)kSecClassGenericPassword,
1044 (id)kSecAttrAccessGroup : @"com.apple.security.ckks",
1045 (id)kSecAttrAccessible: access,
1046 (id)kSecAttrAccount : account,
1047 (id)kSecAttrSynchronizable : (id)kCFBooleanTrue,
1048 (id)kSecValueData : (id) [password dataUsingEncoding:NSUTF8StringEncoding],
1052 query[(id)kSecAttrSyncViewHint] = viewHint;
1054 // Fake it as 'keychain'. This lets CKKSScanLocalItemsOperation for the test-only 'keychain' view find items which would normally not have a view hint.
1055 query[(id)kSecAttrSyncViewHint] = @"keychain";
1058 XCTAssertEqual(status, SecItemAdd((__bridge CFDictionaryRef) query, NULL), @"%@", message);
1061 - (void)addGenericPassword: (NSString*) password account: (NSString*) account expecting: (OSStatus) status message: (NSString*) message {
1062 [self addGenericPassword:password account:account viewHint:nil access:(id)kSecAttrAccessibleAfterFirstUnlock expecting:errSecSuccess message:message];
1066 - (void)addGenericPassword: (NSString*) password account: (NSString*) account {
1067 [self addGenericPassword:password account:account viewHint:nil access:(id)kSecAttrAccessibleAfterFirstUnlock expecting:errSecSuccess message:@"Add item to keychain"];
1070 - (void)addGenericPassword: (NSString*) password account: (NSString*) account viewHint:(NSString*)viewHint {
1071 [self addGenericPassword:password account:account viewHint:viewHint access:(id)kSecAttrAccessibleAfterFirstUnlock expecting:errSecSuccess message:@"Add item to keychain with a viewhint"];
1074 - (void)updateGenericPassword: (NSString*) newPassword account: (NSString*)account {
1075 NSDictionary* query = @{
1076 (id)kSecClass : (id)kSecClassGenericPassword,
1077 (id)kSecAttrAccessGroup : @"com.apple.security.ckks",
1078 (id)kSecAttrAccount : account,
1079 (id)kSecAttrSynchronizable : (id)kCFBooleanTrue,
1082 NSDictionary* update = @{
1083 (id)kSecValueData : (id) [newPassword dataUsingEncoding:NSUTF8StringEncoding],
1085 XCTAssertEqual(errSecSuccess, SecItemUpdate((__bridge CFDictionaryRef) query, (__bridge CFDictionaryRef) update), @"Updating item %@ to %@", account, newPassword);
1088 - (void)updateAccountOfGenericPassword:(NSString*)newAccount
1089 account:(NSString*)account {
1090 NSDictionary* query = @{
1091 (id)kSecClass : (id)kSecClassGenericPassword,
1092 (id)kSecAttrAccessGroup : @"com.apple.security.ckks",
1093 (id)kSecAttrAccount : account,
1094 (id)kSecAttrSynchronizable : (id)kCFBooleanTrue,
1097 NSDictionary* update = @{
1098 (id)kSecAttrAccount : (id) newAccount,
1100 XCTAssertEqual(errSecSuccess, SecItemUpdate((__bridge CFDictionaryRef) query, (__bridge CFDictionaryRef) update), @"Updating item %@ to account %@", account, newAccount);
1103 - (void)deleteGenericPassword: (NSString*) account {
1104 NSDictionary* query = @{
1105 (id)kSecClass : (id)kSecClassGenericPassword,
1106 (id)kSecAttrAccount : account,
1107 (id)kSecAttrSynchronizable : (id)kCFBooleanTrue,
1110 XCTAssertEqual(errSecSuccess, SecItemDelete((__bridge CFDictionaryRef) query), @"Deleting item %@", account);
1113 - (void)deleteGenericPasswordWithoutTombstones:(NSString*)account {
1114 NSDictionary* query = @{
1115 (id)kSecClass : (id)kSecClassGenericPassword,
1116 (id)kSecAttrAccount : account,
1117 (id)kSecAttrSynchronizable : (id)kCFBooleanTrue,
1118 (id)kSecUseTombstones: @NO,
1121 XCTAssertEqual(errSecSuccess, SecItemDelete((__bridge CFDictionaryRef) query), @"Deleting item %@", account);
1124 - (void)findGenericPassword: (NSString*) account expecting: (OSStatus) status {
1125 NSDictionary *query = @{(id)kSecClass : (id)kSecClassGenericPassword,
1126 (id)kSecAttrAccessGroup : @"com.apple.security.ckks",
1127 (id)kSecAttrAccount : account,
1128 (id)kSecAttrSynchronizable : (id)kCFBooleanTrue,
1129 (id)kSecMatchLimit : (id)kSecMatchLimitOne,
1131 XCTAssertEqual(status, SecItemCopyMatching((__bridge CFDictionaryRef) query, NULL), "Finding item %@", account);
1134 - (void)checkGenericPassword: (NSString*) password account: (NSString*) account {
1135 NSDictionary *query = @{(id)kSecClass : (id)kSecClassGenericPassword,
1136 (id)kSecAttrAccessGroup : @"com.apple.security.ckks",
1137 (id)kSecAttrAccount : account,
1138 (id)kSecAttrSynchronizable : (id)kCFBooleanTrue,
1139 (id)kSecMatchLimit : (id)kSecMatchLimitOne,
1140 (id)kSecReturnData : (id)kCFBooleanTrue,
1142 CFTypeRef result = NULL;
1144 XCTAssertEqual(errSecSuccess, SecItemCopyMatching((__bridge CFDictionaryRef) query, &result), "Item %@ should exist", account);
1145 XCTAssertNotNil((__bridge id)result, "Should have received an item");
1147 NSString* storedPassword = [[NSString alloc] initWithData: (__bridge NSData*) result encoding: NSUTF8StringEncoding];
1148 XCTAssertNotNil(storedPassword, "Password should parse as a UTF8 password");
1150 XCTAssertEqualObjects(storedPassword, password, "Stored password should match received password");
1153 -(XCTestExpectation*)expectChangeForView:(NSString*)view {
1154 NSString* notification = [NSString stringWithFormat: @"com.apple.security.view-change.%@", view];
1155 return [self expectationForNotification:notification object:nil handler:^BOOL(NSNotification * _Nonnull nsnotification) {
1156 secnotice("ckks", "Got a notification for %@: %@", notification, nsnotification);
1161 - (void)expectCKKSTLKSelfShareUpload:(CKRecordZoneID*)zoneID {
1162 [self expectCKModifyKeyRecords:0 currentKeyPointerRecords:0 tlkShareRecords:1 zoneID:zoneID];
1165 - (void)checkNSyncableTLKsInKeychain:(size_t)n {
1166 NSDictionary *query = @{(id)kSecClass : (id)kSecClassInternetPassword,
1167 (id)kSecAttrAccessGroup : @"com.apple.security.ckks",
1168 (id)kSecAttrSynchronizable : (id)kCFBooleanTrue,
1169 (id)kSecAttrDescription: SecCKKSKeyClassTLK,
1170 (id)kSecMatchLimit : (id)kSecMatchLimitAll,
1171 (id)kSecReturnAttributes : (id)kCFBooleanTrue,
1173 CFTypeRef result = NULL;
1176 XCTAssertEqual(errSecItemNotFound, SecItemCopyMatching((__bridge CFDictionaryRef) query, &result), "Should have found no TLKs");
1178 XCTAssertEqual(errSecSuccess, SecItemCopyMatching((__bridge CFDictionaryRef) query, &result), "Should have found TLKs");
1179 NSArray* items = (NSArray*) CFBridgingRelease(result);
1181 XCTAssertEqual(items.count, n, "Should have received %lu items", (unsigned long)n);
1185 - (OTAccountMetadataClassC*)loadOrCreateAccountMetadata:(NSError**)error
1188 *error = [NSError errorWithDomain:@"securityd" code:errSecInteractionNotAllowed userInfo:nil];