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 "keychain/ckks/CKKSKeychainView.h"
27 #import "keychain/ckks/CKKSOutgoingQueueEntry.h"
28 #import "keychain/ckks/CKKSIncomingQueueEntry.h"
29 #import "keychain/ckks/CKKSCurrentItemPointer.h"
30 #import "keychain/ckks/CKKSUpdateCurrentItemPointerOperation.h"
31 #import "keychain/ckks/CKKSManifest.h"
32 #import "keychain/ckks/CloudKitCategories.h"
33 #import "keychain/categories/NSError+UsefulConstructors.h"
34 #import "keychain/ot/ObjCImprovements.h"
36 #include <securityd/SecItemServer.h>
37 #include <securityd/SecItemSchema.h>
38 #include <securityd/SecItemDb.h>
39 #include <Security/SecItemPriv.h>
40 #include <securityd/SecDbQuery.h>
41 #import <CloudKit/CloudKit.h>
43 @interface CKKSUpdateCurrentItemPointerOperation ()
44 @property (nullable) CKModifyRecordsOperation* modifyRecordsOperation;
45 @property (nullable) CKOperationGroup* ckoperationGroup;
47 @property (nonnull) NSString* accessGroup;
49 @property (nonnull) NSData* newerItemPersistentRef;
50 @property (nonnull) NSData* newerItemSHA1;
51 @property (nullable) NSData* oldItemPersistentRef;
52 @property (nullable) NSData* oldItemSHA1;
54 // Store these as properties, so we can release them in our -dealloc
55 @property (nullable) SecDbItemRef newItem;
56 @property (nullable) SecDbItemRef oldItem;
59 @implementation CKKSUpdateCurrentItemPointerOperation
61 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks
62 newItem:(NSData*)newItemPersistentRef
63 hash:(NSData*)newItemSHA1
64 accessGroup:(NSString*)accessGroup
65 identifier:(NSString*)identifier
66 replacing:(NSData* _Nullable)oldCurrentItemPersistentRef
67 hash:(NSData*)oldItemSHA1
68 ckoperationGroup:(CKOperationGroup*)ckoperationGroup
70 if((self = [super init])) {
73 _newerItemPersistentRef = newItemPersistentRef;
74 _newerItemSHA1 = newItemSHA1;
75 _oldItemPersistentRef = oldCurrentItemPersistentRef;
76 _oldItemSHA1 = oldItemSHA1;
78 _accessGroup = accessGroup;
80 _currentPointerIdentifier = [NSString stringWithFormat:@"%@-%@", accessGroup, identifier];
87 CFReleaseNull(self->_newItem);
88 CFReleaseNull(self->_oldItem);
93 CKKSKeychainView* ckks = self.ckks;
95 ckkserror("ckkscurrent", ckks, "no CKKS object");
96 self.error = [NSError errorWithDomain:CKKSErrorDomain
97 code:errSecInternalError
98 description:@"no CKKS object"];
104 [ckks dispatchSyncWithAccountKeys:^bool {
106 ckksnotice("ckkscurrent", ckks, "CKKSUpdateCurrentItemPointerOperation cancelled, quitting");
110 NSError* error = nil;
111 CFErrorRef cferror = NULL;
113 NSString* newItemUUID = nil;
114 NSString* oldCurrentItemUUID = nil;
116 self.newItem = [self _onqueueFindSecDbItem:self.newerItemPersistentRef accessGroup:self.accessGroup error:&error];
117 if(!self.newItem || error) {
118 ckksnotice("ckkscurrent", ckks, "Couldn't fetch new item, quitting: %@", error);
123 // Now that we're on the db queue, ensure that the given hashes for the items match the hashes as they are now.
124 // That is, the items haven't changed since the caller knew about the item.
125 NSData* newItemComputedSHA1 = (NSData*) CFBridgingRelease(CFRetainSafe(SecDbItemGetSHA1(self.newItem, &cferror)));
126 if(!newItemComputedSHA1 || cferror ||
127 ![newItemComputedSHA1 isEqual:self.newerItemSHA1]) {
128 ckksnotice("ckkscurrent", ckks, "Hash mismatch for new item: %@ vs %@", newItemComputedSHA1, self.newerItemSHA1);
129 self.error = [NSError errorWithDomain:CKKSErrorDomain
131 description:@"New item has changed; hashes mismatch. Refetch and try again."
132 underlying:(NSError*)CFBridgingRelease(cferror)];
136 newItemUUID = (NSString*) CFBridgingRelease(CFRetainSafe(SecDbItemGetValue(self.newItem, &v10itemuuid, &cferror)));
137 if(!newItemUUID || cferror) {
138 ckkserror("ckkscurrent", ckks, "Error fetching UUID for new item: %@", cferror);
139 self.error = (NSError*) CFBridgingRelease(cferror);
143 // If the old item is nil, that's an indicator that the old item isn't expected to exist in the keychain anymore
144 NSData* oldCurrentItemHash = nil;
145 if(self.oldItemPersistentRef) {
146 self.oldItem = [self _onqueueFindSecDbItem:self.oldItemPersistentRef accessGroup:self.accessGroup error:&error];
147 if(!self.oldItem || error) {
148 ckksnotice("ckkscurrent", ckks, "Couldn't fetch old item, quitting: %@", error);
153 oldCurrentItemHash = (NSData*) CFBridgingRelease(CFRetainSafe(SecDbItemGetSHA1(self.oldItem, &cferror)));
154 if(!oldCurrentItemHash || cferror ||
155 ![oldCurrentItemHash isEqual:self.oldItemSHA1]) {
156 ckksnotice("ckkscurrent", ckks, "Hash mismatch for old item: %@ vs %@", oldCurrentItemHash, self.oldItemSHA1);
157 self.error = [NSError errorWithDomain:CKKSErrorDomain
159 description:@"Old item has changed; hashes mismatch. Refetch and try again."
160 underlying:(NSError*)CFBridgingRelease(cferror)];
164 oldCurrentItemUUID = (NSString*) CFBridgingRelease(CFRetainSafe(SecDbItemGetValue(self.oldItem, &v10itemuuid, &cferror)));
165 if(!oldCurrentItemUUID || cferror) {
166 ckkserror("ckkscurrent", ckks, "Error fetching UUID for old item: %@", cferror);
167 self.error = (NSError*) CFBridgingRelease(cferror);
172 //////////////////////////////
173 // At this point, we've completed all the checks we need for the SecDbItems. Try to launch this boat!
174 ckksnotice("ckkscurrent", ckks, "Setting current pointer for %@ to %@ (from %@)", self.currentPointerIdentifier, newItemUUID, oldCurrentItemUUID);
176 // Ensure that there's no pending pointer update
177 CKKSCurrentItemPointer* cipPending = [CKKSCurrentItemPointer tryFromDatabase:self.currentPointerIdentifier state:SecCKKSProcessedStateRemote zoneID:ckks.zoneID error:&error];
179 self.error = [NSError errorWithDomain:CKKSErrorDomain
180 code:CKKSRemoteItemChangePending
181 description:[NSString stringWithFormat:@"Update to current item pointer is pending."]];
182 ckkserror("ckkscurrent", ckks, "Attempt to set a new current item pointer when one exists: %@", self.error);
186 CKKSCurrentItemPointer* cip = [CKKSCurrentItemPointer tryFromDatabase:self.currentPointerIdentifier state:SecCKKSProcessedStateLocal zoneID:ckks.zoneID error:&error];
189 // Ensure that the itempointer matches the old item (and the old item exists)
191 // We might be in the dangling-pointer case, where the 'fetch' API has returned the client a nil value because we
192 // have a CIP, but it points to a deleted keychain item.
193 // In that case, we shouldn't error out.
195 if(oldCurrentItemHash && ![cip.currentItemUUID isEqualToString: oldCurrentItemUUID]) {
197 ckksnotice("ckkscurrent", ckks, "current item pointer(%@) doesn't match user-supplied UUID (%@); rejecting change of current", cip, oldCurrentItemUUID);
198 self.error = [NSError errorWithDomain:CKKSErrorDomain
200 description:[NSString stringWithFormat:@"Current pointer(%@) does not match user-supplied %@, aborting", cip, oldCurrentItemUUID]];
203 // Cool. Since you know what you're updating, you're allowed to update!
204 cip.currentItemUUID = newItemUUID;
206 } else if(oldCurrentItemUUID) {
207 // Error case: the client thinks there's a current pointer, but we don't have one
208 ckksnotice("ckkscurrent", ckks, "Requested to update a current item pointer but one doesn't exist at %@; rejecting change of current", self.currentPointerIdentifier);
209 self.error = [NSError errorWithDomain:CKKSErrorDomain
211 description:[NSString stringWithFormat:@"Current pointer(%@) does not match given value of '%@', aborting", cip, oldCurrentItemUUID]];
214 // No current item pointer? How exciting! Let's make you a nice new one.
215 cip = [[CKKSCurrentItemPointer alloc] initForIdentifier:self.currentPointerIdentifier
216 currentItemUUID:newItemUUID
217 state:SecCKKSProcessedStateLocal
219 encodedCKRecord:nil];
220 ckksnotice("ckkscurrent", ckks, "Creating a new current item pointer: %@", cip);
223 // Check if either item is currently in any sync queue, and fail if so
224 NSArray* oqes = [CKKSOutgoingQueueEntry allUUIDs:ckks.zoneID error:&error];
225 NSArray* iqes = [CKKSIncomingQueueEntry allUUIDs:ckks.zoneID error:&error];
226 if([oqes containsObject:newItemUUID] || [iqes containsObject:newItemUUID]) {
227 error = [NSError errorWithDomain:CKKSErrorDomain
228 code:CKKSLocalItemChangePending
229 description:[NSString stringWithFormat:@"New item(%@) is being synced; can't set current pointer.", newItemUUID]];
231 if([oqes containsObject:oldCurrentItemUUID] || [iqes containsObject:oldCurrentItemUUID]) {
232 error = [NSError errorWithDomain:CKKSErrorDomain
233 code:CKKSLocalItemChangePending
234 description:[NSString stringWithFormat:@"Old item(%@) is being synced; can't set current pointer.", oldCurrentItemUUID]];
238 ckkserror("ckkscurrent", ckks, "Error attempting to update current item pointer %@: %@", self.currentPointerIdentifier, error);
243 // Make sure the item is synced, though!
244 CKKSMirrorEntry* ckme = [CKKSMirrorEntry fromDatabase:cip.currentItemUUID zoneID:ckks.zoneID error:&error];
246 ckkserror("ckkscurrent", ckks, "Error attempting to set a current item pointer to an item that isn't synced: %@ %@", cip, ckme);
247 error = [NSError errorWithDomain:CKKSErrorDomain
248 code:errSecItemNotFound
249 description:[NSString stringWithFormat:@"No synced item matching (%@); can't set current pointer.", cip.currentItemUUID]
256 if ([CKKSManifest shouldSyncManifests]) {
257 [ckks.egoManifest setCurrentItemUUID:newItemUUID forIdentifier:self.currentPointerIdentifier];
260 ckksnotice("ckkscurrent", ckks, "Saving new current item pointer %@", cip);
262 NSMutableDictionary<CKRecordID*, CKRecord*>* recordsToSave = [[NSMutableDictionary alloc] init];
263 CKRecord* record = [cip CKRecordWithZoneID:ckks.zoneID];
264 recordsToSave[record.recordID] = record;
266 if([CKKSManifest shouldSyncManifests]) {
267 for(CKRecord* record in [ckks.egoManifest allCKRecordsWithZoneID:ckks.zoneID]) {
268 recordsToSave[record.recordID] = record;
272 // Start a CKModifyRecordsOperation to save this new/updated record.
273 NSBlockOperation* modifyComplete = [[NSBlockOperation alloc] init];
274 modifyComplete.name = @"updateCurrentItemPointer-modifyRecordsComplete";
275 [self dependOnBeforeGroupFinished: modifyComplete];
277 self.modifyRecordsOperation = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:recordsToSave.allValues recordIDsToDelete:nil];
278 self.modifyRecordsOperation.atomic = TRUE;
279 // We're likely rolling a PCS identity, or creating a new one. User cares.
280 self.modifyRecordsOperation.configuration.automaticallyRetryNetworkFailures = NO;
281 self.modifyRecordsOperation.configuration.discretionaryNetworkBehavior = CKOperationDiscretionaryNetworkBehaviorNonDiscretionary;
282 self.modifyRecordsOperation.configuration.isCloudKitSupportOperation = YES;
284 self.modifyRecordsOperation.savePolicy = CKRecordSaveIfServerRecordUnchanged;
285 self.modifyRecordsOperation.group = self.ckoperationGroup;
287 self.modifyRecordsOperation.perRecordCompletionBlock = ^(CKRecord *record, NSError * _Nullable error) {
289 CKKSKeychainView* blockCKKS = self.ckks;
292 ckksnotice("ckkscurrent", blockCKKS, "Current pointer upload successful for %@: %@", record.recordID.recordName, record);
294 ckkserror("ckkscurrent", blockCKKS, "error on row: %@ %@", error, record);
298 self.modifyRecordsOperation.modifyRecordsCompletionBlock = ^(NSArray<CKRecord *> *savedRecords, NSArray<CKRecordID *> *deletedRecordIDs, NSError *ckerror) {
300 CKKSKeychainView* strongCKKS = self.ckks;
301 if(!self || !strongCKKS) {
302 ckkserror("ckkscurrent", strongCKKS, "received callback for released object");
303 self.error = [NSError errorWithDomain:CKKSErrorDomain
304 code:errSecInternalError
305 description:@"no CKKS object"];
306 [strongCKKS scheduleOperation: modifyComplete];
311 ckkserror("ckkscurrent", strongCKKS, "CloudKit returned an error: %@", ckerror);
312 self.error = ckerror;
314 [strongCKKS dispatchSync:^bool {
315 return [strongCKKS _onqueueCKWriteFailed:ckerror attemptedRecordsChanged:recordsToSave];
318 [strongCKKS scheduleOperation: modifyComplete];
322 __block NSError* error = nil;
324 [strongCKKS dispatchSync: ^bool{
325 for(CKRecord* record in savedRecords) {
326 // Save the item records
327 if([record.recordType isEqualToString: SecCKRecordCurrentItemType]) {
328 if([cip matchesCKRecord: record]) {
329 cip.storedCKRecord = record;
330 [cip saveToDatabase:&error];
332 ckkserror("ckkscurrent", strongCKKS, "Couldn't save new current pointer to database: %@", error);
335 ckkserror("ckkscurrent", strongCKKS, "CloudKit record does not match saved record, ignoring: %@ %@", record, cip);
338 else if ([CKKSManifest shouldSyncManifests] && [record.recordType isEqualToString:SecCKRecordManifestType]) {
339 CKKSManifest* manifest = [[CKKSManifest alloc] initWithCKRecord:record];
340 [manifest saveToDatabase:&error];
342 ckkserror("ckkscurrent", strongCKKS, "Couldn't save %@ to manifest: %@", record.recordID.recordName, error);
347 // Schedule a 'view changed' notification
348 [strongCKKS.notifyViewChangedScheduler trigger];
354 [strongCKKS scheduleOperation: modifyComplete];
357 [self dependOnBeforeGroupFinished: self.modifyRecordsOperation];
358 [ckks.database addOperation: self.modifyRecordsOperation];
364 - (SecDbItemRef _Nullable)_onqueueFindSecDbItem:(NSData*)persistentRef accessGroup:(NSString*)accessGroup error:(NSError**)error {
365 __block SecDbItemRef blockItem = NULL;
366 CFErrorRef cferror = NULL;
367 __block NSError* localerror = NULL;
369 CKKSKeychainView* ckks = self.ckks;
370 bool ok = kc_with_dbt(true, &cferror, ^bool (SecDbConnectionRef dbt) {
371 // Find the items from their persistent refs.
372 CFErrorRef blockcfError = NULL;
373 Query *q = query_create_with_limit( (__bridge CFDictionaryRef) @{
374 (__bridge NSString *)kSecValuePersistentRef : persistentRef,
375 (__bridge NSString *)kSecAttrAccessGroup : accessGroup,
380 if(blockcfError || !q) {
381 ckkserror("ckkscurrent", ckks, "couldn't create query for item persistentRef: %@", blockcfError);
382 localerror = [NSError errorWithDomain:CKKSErrorDomain
384 description:@"couldn't create query for new item pref"
385 underlying:(NSError*)CFBridgingRelease(blockcfError)];
389 if(!SecDbItemQuery(q, NULL, dbt, &blockcfError, ^(SecDbItemRef item, bool *stop) {
390 blockItem = CFRetainSafe(item);
392 query_destroy(q, NULL);
393 ckkserror("ckkscurrent", ckks, "couldn't run query for item pref: %@", blockcfError);
394 localerror = [NSError errorWithDomain:CKKSErrorDomain
396 description:@"couldn't run query for new item pref"
397 underlying:(NSError*)CFBridgingRelease(blockcfError)];
401 if(!query_destroy(q, &blockcfError)) {
402 ckkserror("ckkscurrent", ckks, "couldn't destroy query for item pref: %@", blockcfError);
403 localerror = [NSError errorWithDomain:CKKSErrorDomain
405 description:@"couldn't destroy query for item pref"
406 underlying:(NSError*)CFBridgingRelease(blockcfError)];
412 if(!ok || localerror) {
414 ckkserror("ckkscurrent", ckks, "Query failed: %@", localerror);
419 ckkserror("ckkscurrent", ckks, "Query failed, cferror is %@", cferror);
420 localerror = [NSError errorWithDomain:CKKSErrorDomain
422 description:@"couldn't run query"
423 underlying:(NSError*)CFBridgingRelease(cferror)];
429 CFReleaseSafe(cferror);
433 CFReleaseSafe(cferror);