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"
34 #include <securityd/SecItemServer.h>
35 #include <securityd/SecItemSchema.h>
36 #include <securityd/SecItemDb.h>
37 #include <Security/SecItemPriv.h>
38 #include <securityd/SecDbQuery.h>
39 #import <CloudKit/CloudKit.h>
41 @interface CKKSUpdateCurrentItemPointerOperation ()
42 @property (nullable) CKModifyRecordsOperation* modifyRecordsOperation;
43 @property (nullable) CKOperationGroup* ckoperationGroup;
45 @property (nonnull) NSString* accessGroup;
47 @property (nonnull) NSData* newerItemPersistentRef;
48 @property (nonnull) NSData* newerItemSHA1;
49 @property (nullable) NSData* oldItemPersistentRef;
50 @property (nullable) NSData* oldItemSHA1;
52 // Store these as properties, so we can release them in our -dealloc
53 @property (nullable) SecDbItemRef newItem;
54 @property (nullable) SecDbItemRef oldItem;
57 @implementation CKKSUpdateCurrentItemPointerOperation
59 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks
60 newItem:(NSData*)newItemPersistentRef
61 hash:(NSData*)newItemSHA1
62 accessGroup:(NSString*)accessGroup
63 identifier:(NSString*)identifier
64 replacing:(NSData* _Nullable)oldCurrentItemPersistentRef
65 hash:(NSData*)oldItemSHA1
66 ckoperationGroup:(CKOperationGroup*)ckoperationGroup
68 if((self = [super init])) {
71 _newerItemPersistentRef = newItemPersistentRef;
72 _newerItemSHA1 = newItemSHA1;
73 _oldItemPersistentRef = oldCurrentItemPersistentRef;
74 _oldItemSHA1 = oldItemSHA1;
76 _accessGroup = accessGroup;
78 _currentPointerIdentifier = [NSString stringWithFormat:@"%@-%@", accessGroup, identifier];
85 CFReleaseNull(self->_newItem);
86 CFReleaseNull(self->_oldItem);
91 CKKSKeychainView* ckks = self.ckks;
93 ckkserror("ckkscurrent", ckks, "no CKKS object");
94 self.error = [NSError errorWithDomain:CKKSErrorDomain
95 code:errSecInternalError
96 description:@"no CKKS object"];
100 __weak __typeof(self) weakSelf = self;
102 [ckks dispatchSyncWithAccountKeys:^bool {
104 ckksnotice("ckkscurrent", ckks, "CKKSUpdateCurrentItemPointerOperation cancelled, quitting");
108 NSError* error = nil;
109 CFErrorRef cferror = NULL;
111 NSString* newItemUUID = nil;
112 NSString* oldCurrentItemUUID = nil;
114 self.newItem = [self _onqueueFindSecDbItem:self.newerItemPersistentRef accessGroup:self.accessGroup error:&error];
115 if(!self.newItem || error) {
116 ckksnotice("ckkscurrent", ckks, "Couldn't fetch new item, quitting: %@", error);
121 // Now that we're on the db queue, ensure that the given hashes for the items match the hashes as they are now.
122 // That is, the items haven't changed since the caller knew about the item.
123 NSData* newItemComputedSHA1 = (NSData*) CFBridgingRelease(CFRetainSafe(SecDbItemGetSHA1(self.newItem, &cferror)));
124 if(!newItemComputedSHA1 || cferror ||
125 ![newItemComputedSHA1 isEqual:self.newerItemSHA1]) {
126 ckksnotice("ckkscurrent", ckks, "Hash mismatch for new item: %@ vs %@", newItemComputedSHA1, self.newerItemSHA1);
127 self.error = [NSError errorWithDomain:CKKSErrorDomain
129 description:@"New item has changed; hashes mismatch. Refetch and try again."
130 underlying:(NSError*)CFBridgingRelease(cferror)];
134 newItemUUID = (NSString*) CFBridgingRelease(CFRetainSafe(SecDbItemGetValue(self.newItem, &v10itemuuid, &cferror)));
135 if(!newItemUUID || cferror) {
136 ckkserror("ckkscurrent", ckks, "Error fetching UUID for new item: %@", cferror);
137 self.error = (NSError*) CFBridgingRelease(cferror);
141 // If the old item is nil, that's an indicator that the old item isn't expected to exist in the keychain anymore
142 NSData* oldCurrentItemHash = nil;
143 if(self.oldItemPersistentRef) {
144 self.oldItem = [self _onqueueFindSecDbItem:self.oldItemPersistentRef accessGroup:self.accessGroup error:&error];
145 if(!self.oldItem || error) {
146 ckksnotice("ckkscurrent", ckks, "Couldn't fetch old item, quitting: %@", error);
151 oldCurrentItemHash = (NSData*) CFBridgingRelease(CFRetainSafe(SecDbItemGetSHA1(self.oldItem, &cferror)));
152 if(!oldCurrentItemHash || cferror ||
153 ![oldCurrentItemHash isEqual:self.oldItemSHA1]) {
154 ckksnotice("ckkscurrent", ckks, "Hash mismatch for old item: %@ vs %@", oldCurrentItemHash, self.oldItemSHA1);
155 self.error = [NSError errorWithDomain:CKKSErrorDomain
157 description:@"Old item has changed; hashes mismatch. Refetch and try again."
158 underlying:(NSError*)CFBridgingRelease(cferror)];
162 oldCurrentItemUUID = (NSString*) CFBridgingRelease(CFRetainSafe(SecDbItemGetValue(self.oldItem, &v10itemuuid, &cferror)));
163 if(!oldCurrentItemUUID || cferror) {
164 ckkserror("ckkscurrent", ckks, "Error fetching UUID for old item: %@", cferror);
165 self.error = (NSError*) CFBridgingRelease(cferror);
170 //////////////////////////////
171 // At this point, we've completed all the checks we need for the SecDbItems. Try to launch this boat!
172 ckksnotice("ckkscurrent", ckks, "Setting current pointer for %@ to %@ (from %@)", self.currentPointerIdentifier, newItemUUID, oldCurrentItemUUID);
174 // Ensure that there's no pending pointer update
175 CKKSCurrentItemPointer* cipPending = [CKKSCurrentItemPointer tryFromDatabase:self.currentPointerIdentifier state:SecCKKSProcessedStateRemote zoneID:ckks.zoneID error:&error];
177 self.error = [NSError errorWithDomain:CKKSErrorDomain
178 code:CKKSRemoteItemChangePending
179 description:[NSString stringWithFormat:@"Update to current item pointer is pending."]];
180 ckkserror("ckkscurrent", ckks, "Attempt to set a new current item pointer when one exists: %@", self.error);
184 CKKSCurrentItemPointer* cip = [CKKSCurrentItemPointer tryFromDatabase:self.currentPointerIdentifier state:SecCKKSProcessedStateLocal zoneID:ckks.zoneID error:&error];
187 // Ensure that the itempointer matches the old item (and the old item exists)
189 // We might be in the dangling-pointer case, where the 'fetch' API has returned the client a nil value because we
190 // have a CIP, but it points to a deleted keychain item.
191 // In that case, we shouldn't error out.
193 if(oldCurrentItemHash && ![cip.currentItemUUID isEqualToString: oldCurrentItemUUID]) {
195 ckksnotice("ckkscurrent", ckks, "current item pointer(%@) doesn't match user-supplied UUID (%@); rejecting change of current", cip, oldCurrentItemUUID);
196 self.error = [NSError errorWithDomain:CKKSErrorDomain
198 description:[NSString stringWithFormat:@"Current pointer(%@) does not match user-supplied %@, aborting", cip, oldCurrentItemUUID]];
201 // Cool. Since you know what you're updating, you're allowed to update!
202 cip.currentItemUUID = newItemUUID;
204 } else if(oldCurrentItemUUID) {
205 // Error case: the client thinks there's a current pointer, but we don't have one
206 ckksnotice("ckkscurrent", ckks, "Requested to update a current item pointer but one doesn't exist at %@; rejecting change of current", self.currentPointerIdentifier);
207 self.error = [NSError errorWithDomain:CKKSErrorDomain
209 description:[NSString stringWithFormat:@"Current pointer(%@) does not match given value of '%@', aborting", cip, oldCurrentItemUUID]];
212 // No current item pointer? How exciting! Let's make you a nice new one.
213 cip = [[CKKSCurrentItemPointer alloc] initForIdentifier:self.currentPointerIdentifier
214 currentItemUUID:newItemUUID
215 state:SecCKKSProcessedStateLocal
217 encodedCKRecord:nil];
218 ckksnotice("ckkscurrent", ckks, "Creating a new current item pointer: %@", cip);
221 // Check if either item is currently in any sync queue, and fail if so
222 NSArray* oqes = [CKKSOutgoingQueueEntry allUUIDs:ckks.zoneID error:&error];
223 NSArray* iqes = [CKKSIncomingQueueEntry allUUIDs:ckks.zoneID error:&error];
224 if([oqes containsObject:newItemUUID] || [iqes containsObject:newItemUUID]) {
225 error = [NSError errorWithDomain:CKKSErrorDomain
226 code:CKKSLocalItemChangePending
227 description:[NSString stringWithFormat:@"New item(%@) is being synced; can't set current pointer.", newItemUUID]];
229 if([oqes containsObject:oldCurrentItemUUID] || [iqes containsObject:oldCurrentItemUUID]) {
230 error = [NSError errorWithDomain:CKKSErrorDomain
231 code:CKKSLocalItemChangePending
232 description:[NSString stringWithFormat:@"Old item(%@) is being synced; can't set current pointer.", oldCurrentItemUUID]];
236 ckkserror("ckkscurrent", ckks, "Error attempting to update current item pointer %@: %@", self.currentPointerIdentifier, error);
241 // Make sure the item is synced, though!
242 CKKSMirrorEntry* ckme = [CKKSMirrorEntry fromDatabase:cip.currentItemUUID zoneID:ckks.zoneID error:&error];
244 ckkserror("ckkscurrent", ckks, "Error attempting to set a current item pointer to an item that isn't synced: %@ %@", cip, ckme);
245 error = [NSError errorWithDomain:CKKSErrorDomain
246 code:errSecItemNotFound
247 description:[NSString stringWithFormat:@"No synced item matching (%@); can't set current pointer.", cip.currentItemUUID]
254 if ([CKKSManifest shouldSyncManifests]) {
255 [ckks.egoManifest setCurrentItemUUID:newItemUUID forIdentifier:self.currentPointerIdentifier];
258 ckksnotice("ckkscurrent", ckks, "Saving new current item pointer %@", cip);
260 NSMutableDictionary<CKRecordID*, CKRecord*>* recordsToSave = [[NSMutableDictionary alloc] init];
261 CKRecord* record = [cip CKRecordWithZoneID:ckks.zoneID];
262 recordsToSave[record.recordID] = record;
264 if([CKKSManifest shouldSyncManifests]) {
265 for(CKRecord* record in [ckks.egoManifest allCKRecordsWithZoneID:ckks.zoneID]) {
266 recordsToSave[record.recordID] = record;
270 // Start a CKModifyRecordsOperation to save this new/updated record.
271 NSBlockOperation* modifyComplete = [[NSBlockOperation alloc] init];
272 modifyComplete.name = @"updateCurrentItemPointer-modifyRecordsComplete";
273 [self dependOnBeforeGroupFinished: modifyComplete];
275 self.modifyRecordsOperation = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:recordsToSave.allValues recordIDsToDelete:nil];
276 self.modifyRecordsOperation.atomic = TRUE;
277 self.modifyRecordsOperation.qualityOfService = NSQualityOfServiceUserInitiated; // We're likely rolling a PCS identity, or creating a new one. User cares.
278 self.modifyRecordsOperation.savePolicy = CKRecordSaveIfServerRecordUnchanged;
279 self.modifyRecordsOperation.group = self.ckoperationGroup;
281 self.modifyRecordsOperation.perRecordCompletionBlock = ^(CKRecord *record, NSError * _Nullable error) {
282 __strong __typeof(weakSelf) strongSelf = weakSelf;
283 __strong __typeof(strongSelf.ckks) blockCKKS = strongSelf.ckks;
286 ckksnotice("ckkscurrent", blockCKKS, "Current pointer upload successful for %@: %@", record.recordID.recordName, record);
288 ckkserror("ckkscurrent", blockCKKS, "error on row: %@ %@", error, record);
292 self.modifyRecordsOperation.modifyRecordsCompletionBlock = ^(NSArray<CKRecord *> *savedRecords, NSArray<CKRecordID *> *deletedRecordIDs, NSError *ckerror) {
293 __strong __typeof(weakSelf) strongSelf = weakSelf;
294 __strong __typeof(strongSelf.ckks) strongCKKS = strongSelf.ckks;
295 if(!strongSelf || !strongCKKS) {
296 ckkserror("ckkscurrent", strongCKKS, "received callback for released object");
297 strongSelf.error = [NSError errorWithDomain:CKKSErrorDomain
298 code:errSecInternalError
299 description:@"no CKKS object"];
300 [strongCKKS scheduleOperation: modifyComplete];
305 ckkserror("ckkscurrent", strongCKKS, "CloudKit returned an error: %@", ckerror);
306 strongSelf.error = ckerror;
308 [strongCKKS dispatchSync:^bool {
309 return [strongCKKS _onqueueCKWriteFailed:ckerror attemptedRecordsChanged:recordsToSave];
312 [strongCKKS scheduleOperation: modifyComplete];
316 __block NSError* error = nil;
318 [strongCKKS dispatchSync: ^bool{
319 for(CKRecord* record in savedRecords) {
320 // Save the item records
321 if([record.recordType isEqualToString: SecCKRecordCurrentItemType]) {
322 if([cip matchesCKRecord: record]) {
323 cip.storedCKRecord = record;
324 [cip saveToDatabase:&error];
326 ckkserror("ckkscurrent", strongCKKS, "Couldn't save new current pointer to database: %@", error);
329 ckkserror("ckkscurrent", strongCKKS, "CloudKit record does not match saved record, ignoring: %@ %@", record, cip);
332 else if ([CKKSManifest shouldSyncManifests] && [record.recordType isEqualToString:SecCKRecordManifestType]) {
333 CKKSManifest* manifest = [[CKKSManifest alloc] initWithCKRecord:record];
334 [manifest saveToDatabase:&error];
336 ckkserror("ckkscurrent", strongCKKS, "Couldn't save %@ to manifest: %@", record.recordID.recordName, error);
337 strongSelf.error = error;
341 // Schedule a 'view changed' notification
342 [strongCKKS.notifyViewChangedScheduler trigger];
347 strongSelf.error = error;
348 [strongCKKS scheduleOperation: modifyComplete];
351 [self dependOnBeforeGroupFinished: self.modifyRecordsOperation];
352 [ckks.database addOperation: self.modifyRecordsOperation];
358 - (SecDbItemRef _Nullable)_onqueueFindSecDbItem:(NSData*)persistentRef accessGroup:(NSString*)accessGroup error:(NSError**)error {
359 __block SecDbItemRef blockItem = NULL;
360 CFErrorRef cferror = NULL;
361 __block NSError* localerror = NULL;
363 CKKSKeychainView* ckks = self.ckks;
364 bool ok = kc_with_dbt(true, &cferror, ^bool (SecDbConnectionRef dbt) {
365 // Find the items from their persistent refs.
366 CFErrorRef blockcfError = NULL;
367 Query *q = query_create_with_limit( (__bridge CFDictionaryRef) @{
368 (__bridge NSString *)kSecValuePersistentRef : persistentRef,
369 (__bridge NSString *)kSecAttrAccessGroup : accessGroup,
374 if(blockcfError || !q) {
375 ckkserror("ckkscurrent", ckks, "couldn't create query for item persistentRef: %@", blockcfError);
376 localerror = [NSError errorWithDomain:CKKSErrorDomain
378 description:@"couldn't create query for new item pref"
379 underlying:(NSError*)CFBridgingRelease(blockcfError)];
383 if(!SecDbItemQuery(q, NULL, dbt, &blockcfError, ^(SecDbItemRef item, bool *stop) {
384 blockItem = CFRetainSafe(item);
386 query_destroy(q, NULL);
387 ckkserror("ckkscurrent", ckks, "couldn't run query for item pref: %@", blockcfError);
388 localerror = [NSError errorWithDomain:CKKSErrorDomain
390 description:@"couldn't run query for new item pref"
391 underlying:(NSError*)CFBridgingRelease(blockcfError)];
395 if(!query_destroy(q, &blockcfError)) {
396 ckkserror("ckkscurrent", ckks, "couldn't destroy query for item pref: %@", blockcfError);
397 localerror = [NSError errorWithDomain:CKKSErrorDomain
399 description:@"couldn't destroy query for item pref"
400 underlying:(NSError*)CFBridgingRelease(blockcfError)];
406 if(!ok || localerror) {
408 ckkserror("ckkscurrent", ckks, "Query failed: %@", localerror);
413 ckkserror("ckkscurrent", ckks, "Query failed, cferror is %@", cferror);
414 localerror = [NSError errorWithDomain:CKKSErrorDomain
416 description:@"couldn't run query"
417 underlying:(NSError*)CFBridgingRelease(cferror)];
423 CFReleaseSafe(cferror);
427 CFReleaseSafe(cferror);