]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/CKKSUpdateCurrentItemPointerOperation.m
Security-59306.11.20.tar.gz
[apple/security.git] / keychain / ckks / CKKSUpdateCurrentItemPointerOperation.m
1 /*
2 * Copyright (c) 2017 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #if OCTAGON
25
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"
35
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>
42
43 @interface CKKSUpdateCurrentItemPointerOperation ()
44 @property (nullable) CKModifyRecordsOperation* modifyRecordsOperation;
45 @property (nullable) CKOperationGroup* ckoperationGroup;
46
47 @property (nonnull) NSString* accessGroup;
48
49 @property (nonnull) NSData* newerItemPersistentRef;
50 @property (nonnull) NSData* newerItemSHA1;
51 @property (nullable) NSData* oldItemPersistentRef;
52 @property (nullable) NSData* oldItemSHA1;
53
54 // Store these as properties, so we can release them in our -dealloc
55 @property (nullable) SecDbItemRef newItem;
56 @property (nullable) SecDbItemRef oldItem;
57 @end
58
59 @implementation CKKSUpdateCurrentItemPointerOperation
60
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
69 {
70 if((self = [super init])) {
71 _ckks = ckks;
72
73 _newerItemPersistentRef = newItemPersistentRef;
74 _newerItemSHA1 = newItemSHA1;
75 _oldItemPersistentRef = oldCurrentItemPersistentRef;
76 _oldItemSHA1 = oldItemSHA1;
77
78 _accessGroup = accessGroup;
79
80 _currentPointerIdentifier = [NSString stringWithFormat:@"%@-%@", accessGroup, identifier];
81 }
82 return self;
83 }
84
85 - (void)dealloc {
86 if(self) {
87 CFReleaseNull(self->_newItem);
88 CFReleaseNull(self->_oldItem);
89 }
90 }
91
92 - (void)groupStart {
93 CKKSKeychainView* ckks = self.ckks;
94 if(!ckks) {
95 ckkserror("ckkscurrent", ckks, "no CKKS object");
96 self.error = [NSError errorWithDomain:CKKSErrorDomain
97 code:errSecInternalError
98 description:@"no CKKS object"];
99 return;
100 }
101
102 WEAKIFY(self);
103
104 [ckks dispatchSyncWithAccountKeys:^bool {
105 if(self.cancelled) {
106 ckksnotice("ckkscurrent", ckks, "CKKSUpdateCurrentItemPointerOperation cancelled, quitting");
107 return false;
108 }
109
110 NSError* error = nil;
111 CFErrorRef cferror = NULL;
112
113 NSString* newItemUUID = nil;
114 NSString* oldCurrentItemUUID = nil;
115
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);
119 self.error = error;
120 return false;
121 }
122
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
130 code:CKKSItemChanged
131 description:@"New item has changed; hashes mismatch. Refetch and try again."
132 underlying:(NSError*)CFBridgingRelease(cferror)];
133 return false;
134 }
135
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);
140 return false;
141 }
142
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);
149 self.error = error;
150 return false;
151 }
152
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
158 code:CKKSItemChanged
159 description:@"Old item has changed; hashes mismatch. Refetch and try again."
160 underlying:(NSError*)CFBridgingRelease(cferror)];
161 return false;
162 }
163
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);
168 return false;
169 }
170 }
171
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);
175
176 // Ensure that there's no pending pointer update
177 CKKSCurrentItemPointer* cipPending = [CKKSCurrentItemPointer tryFromDatabase:self.currentPointerIdentifier state:SecCKKSProcessedStateRemote zoneID:ckks.zoneID error:&error];
178 if(cipPending) {
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);
183 return false;
184 }
185
186 CKKSCurrentItemPointer* cip = [CKKSCurrentItemPointer tryFromDatabase:self.currentPointerIdentifier state:SecCKKSProcessedStateLocal zoneID:ckks.zoneID error:&error];
187
188 if(cip) {
189 // Ensure that the itempointer matches the old item (and the old item exists)
190 //
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.
194 //
195 if(oldCurrentItemHash && ![cip.currentItemUUID isEqualToString: oldCurrentItemUUID]) {
196
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
199 code:CKKSItemChanged
200 description:[NSString stringWithFormat:@"Current pointer(%@) does not match user-supplied %@, aborting", cip, oldCurrentItemUUID]];
201 return false;
202 }
203 // Cool. Since you know what you're updating, you're allowed to update!
204 cip.currentItemUUID = newItemUUID;
205
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
210 code:CKKSItemChanged
211 description:[NSString stringWithFormat:@"Current pointer(%@) does not match given value of '%@', aborting", cip, oldCurrentItemUUID]];
212 return false;
213 } else {
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
218 zoneID:ckks.zoneID
219 encodedCKRecord:nil];
220 ckksnotice("ckkscurrent", ckks, "Creating a new current item pointer: %@", cip);
221 }
222
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]];
230 }
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]];
235 }
236
237 if(error) {
238 ckkserror("ckkscurrent", ckks, "Error attempting to update current item pointer %@: %@", self.currentPointerIdentifier, error);
239 self.error = error;
240 return false;
241 }
242
243 // Make sure the item is synced, though!
244 CKKSMirrorEntry* ckme = [CKKSMirrorEntry fromDatabase:cip.currentItemUUID zoneID:ckks.zoneID error:&error];
245 if(!ckme || 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]
250 underlying:error];
251
252 self.error = error;
253 return false;
254 }
255
256 if ([CKKSManifest shouldSyncManifests]) {
257 [ckks.egoManifest setCurrentItemUUID:newItemUUID forIdentifier:self.currentPointerIdentifier];
258 }
259
260 ckksnotice("ckkscurrent", ckks, "Saving new current item pointer %@", cip);
261
262 NSMutableDictionary<CKRecordID*, CKRecord*>* recordsToSave = [[NSMutableDictionary alloc] init];
263 CKRecord* record = [cip CKRecordWithZoneID:ckks.zoneID];
264 recordsToSave[record.recordID] = record;
265
266 if([CKKSManifest shouldSyncManifests]) {
267 for(CKRecord* record in [ckks.egoManifest allCKRecordsWithZoneID:ckks.zoneID]) {
268 recordsToSave[record.recordID] = record;
269 }
270 }
271
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];
276
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;
283
284 self.modifyRecordsOperation.savePolicy = CKRecordSaveIfServerRecordUnchanged;
285 self.modifyRecordsOperation.group = self.ckoperationGroup;
286
287 self.modifyRecordsOperation.perRecordCompletionBlock = ^(CKRecord *record, NSError * _Nullable error) {
288 STRONGIFY(self);
289 CKKSKeychainView* blockCKKS = self.ckks;
290
291 if(!error) {
292 ckksnotice("ckkscurrent", blockCKKS, "Current pointer upload successful for %@: %@", record.recordID.recordName, record);
293 } else {
294 ckkserror("ckkscurrent", blockCKKS, "error on row: %@ %@", error, record);
295 }
296 };
297
298 self.modifyRecordsOperation.modifyRecordsCompletionBlock = ^(NSArray<CKRecord *> *savedRecords, NSArray<CKRecordID *> *deletedRecordIDs, NSError *ckerror) {
299 STRONGIFY(self);
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];
307 return;
308 }
309
310 if(ckerror) {
311 ckkserror("ckkscurrent", strongCKKS, "CloudKit returned an error: %@", ckerror);
312 self.error = ckerror;
313
314 [strongCKKS dispatchSync:^bool {
315 return [strongCKKS _onqueueCKWriteFailed:ckerror attemptedRecordsChanged:recordsToSave];
316 }];
317
318 [strongCKKS scheduleOperation: modifyComplete];
319 return;
320 }
321
322 __block NSError* error = nil;
323
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];
331 if(error) {
332 ckkserror("ckkscurrent", strongCKKS, "Couldn't save new current pointer to database: %@", error);
333 }
334 } else {
335 ckkserror("ckkscurrent", strongCKKS, "CloudKit record does not match saved record, ignoring: %@ %@", record, cip);
336 }
337 }
338 else if ([CKKSManifest shouldSyncManifests] && [record.recordType isEqualToString:SecCKRecordManifestType]) {
339 CKKSManifest* manifest = [[CKKSManifest alloc] initWithCKRecord:record];
340 [manifest saveToDatabase:&error];
341 if (error) {
342 ckkserror("ckkscurrent", strongCKKS, "Couldn't save %@ to manifest: %@", record.recordID.recordName, error);
343 self.error = error;
344 }
345 }
346
347 // Schedule a 'view changed' notification
348 [strongCKKS.notifyViewChangedScheduler trigger];
349 }
350 return true;
351 }];
352
353 self.error = error;
354 [strongCKKS scheduleOperation: modifyComplete];
355 };
356
357 [self dependOnBeforeGroupFinished: self.modifyRecordsOperation];
358 [ckks.database addOperation: self.modifyRecordsOperation];
359
360 return true;
361 }];
362 }
363
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;
368
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,
376 },
377 NULL,
378 1,
379 &blockcfError);
380 if(blockcfError || !q) {
381 ckkserror("ckkscurrent", ckks, "couldn't create query for item persistentRef: %@", blockcfError);
382 localerror = [NSError errorWithDomain:CKKSErrorDomain
383 code:errSecParam
384 description:@"couldn't create query for new item pref"
385 underlying:(NSError*)CFBridgingRelease(blockcfError)];
386 return false;
387 }
388
389 if(!SecDbItemQuery(q, NULL, dbt, &blockcfError, ^(SecDbItemRef item, bool *stop) {
390 blockItem = CFRetainSafe(item);
391 })) {
392 query_destroy(q, NULL);
393 ckkserror("ckkscurrent", ckks, "couldn't run query for item pref: %@", blockcfError);
394 localerror = [NSError errorWithDomain:CKKSErrorDomain
395 code:errSecParam
396 description:@"couldn't run query for new item pref"
397 underlying:(NSError*)CFBridgingRelease(blockcfError)];
398 return false;
399 }
400
401 if(!query_destroy(q, &blockcfError)) {
402 ckkserror("ckkscurrent", ckks, "couldn't destroy query for item pref: %@", blockcfError);
403 localerror = [NSError errorWithDomain:CKKSErrorDomain
404 code:errSecParam
405 description:@"couldn't destroy query for item pref"
406 underlying:(NSError*)CFBridgingRelease(blockcfError)];
407 return false;
408 }
409 return true;
410 });
411
412 if(!ok || localerror) {
413 if(localerror) {
414 ckkserror("ckkscurrent", ckks, "Query failed: %@", localerror);
415 if(error) {
416 *error = localerror;
417 }
418 } else {
419 ckkserror("ckkscurrent", ckks, "Query failed, cferror is %@", cferror);
420 localerror = [NSError errorWithDomain:CKKSErrorDomain
421 code:errSecParam
422 description:@"couldn't run query"
423 underlying:(NSError*)CFBridgingRelease(cferror)];
424 if(*error) {
425 *error = localerror;
426 }
427 }
428
429 CFReleaseSafe(cferror);
430 return false;
431 }
432
433 CFReleaseSafe(cferror);
434 return blockItem;
435 }
436
437 @end
438
439 #endif // OCTAGON