2 * Copyright (c) 2016 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/CKKSNearFutureScheduler.h"
28 #import "keychain/ckks/CKKSScanLocalItemsOperation.h"
29 #import "keychain/ckks/CKKSMirrorEntry.h"
30 #import "keychain/ckks/CKKSOutgoingQueueEntry.h"
31 #import "keychain/ckks/CKKSGroupOperation.h"
32 #import "keychain/ckks/CKKSKey.h"
33 #import "keychain/ckks/CKKSViewManager.h"
34 #import "keychain/ckks/CKKSManifest.h"
36 #include <securityd/SecItemSchema.h>
37 #include <securityd/SecItemServer.h>
38 #include <securityd/SecItemDb.h>
39 #include <Security/SecItemPriv.h>
41 @interface CKKSScanLocalItemsOperation ()
42 @property CKOperationGroup* ckoperationGroup;
45 @implementation CKKSScanLocalItemsOperation
47 - (instancetype)init {
50 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks ckoperationGroup:(CKOperationGroup*)ckoperationGroup {
51 if(self = [super init]) {
53 _ckoperationGroup = ckoperationGroup;
61 // Take a strong reference.
62 CKKSKeychainView* ckks = self.ckks;
64 ckkserror("ckksscan", ckks, "no CKKS object");
68 [ckks dispatchSyncWithAccountKeys: ^bool{
70 ckksnotice("ckksscan", ckks, "CKKSScanLocalItemsOperation cancelled, quitting");
73 ckks.lastScanLocalItemsOperation = self;
75 NSMutableArray* itemsForManifest = [NSMutableArray array];
77 // First, query for all synchronizable items
78 __block CFErrorRef cferror = NULL;
79 __block NSError* error = nil;
80 __block bool newEntries = false;
82 // Must query per-class, so:
83 const SecDbSchema *newSchema = current_schema();
84 for (const SecDbClass *const *class = newSchema->classes; *class != NULL; class++) {
87 if(!((*class)->itemclass)) {
88 // Don't try to scan non-item 'classes'
92 NSDictionary* queryAttributes = @{(__bridge NSString*) kSecClass: (__bridge NSString*) (*class)->name,
93 (__bridge NSString*) kSecReturnRef: @(YES),
94 (__bridge NSString*) kSecAttrSynchronizable: @(YES),
95 (__bridge NSString*) kSecAttrTombstone: @(NO),
96 // This works ~as long as~ item views are chosen by view hint only. It's a significant perf win, though.
97 // <rdar://problem/32269541> SpinTracer: CKKSScanLocalItemsOperation expensive on M8 machines
98 (__bridge NSString*) kSecAttrSyncViewHint: ckks.zoneName,
100 ckksinfo("ckksscan", ckks, "Scanning all synchronizable items for: %@", queryAttributes);
102 Query *q = query_create_with_limit( (__bridge CFDictionaryRef) queryAttributes, NULL, kSecMatchUnlimited, &cferror);
106 ckkserror("ckksscan", ckks, "couldn't create query: %@", cferror);
107 SecTranslateError(&error, cferror);
112 ok = kc_with_dbt(true, &cferror, ^(SecDbConnectionRef dbt) {
113 return SecDbItemQuery(q, NULL, dbt, &cferror, ^(SecDbItemRef item, bool *stop) {
114 ckksnotice("ckksscan", ckks, "scanning item: %@", item);
116 SecDbItemRef itemToSave = NULL;
118 // First check: is this a tombstone? If so, skip with prejudice.
119 if(SecDbItemIsTombstone(item)) {
120 ckksinfo("ckksscan", ckks, "Skipping tombstone %@", item);
124 // Second check: is this item even for this view? If not, skip.
125 NSString* viewForItem = [[CKKSViewManager manager] viewNameForItem:item];
126 if(![viewForItem isEqualToString: ckks.zoneName]) {
127 ckksinfo("ckksscan", ckks, "Scanned item is for view %@, skipping", viewForItem);
131 // Third check: is this item one of our keys for a view? If not, skip.
132 if([CKKSKey isItemKeyForKeychainView: item] != nil) {
133 ckksinfo("ckksscan", ckks, "Scanned item is a CKKS internal key, skipping");
137 // Fourth check: does this item have a UUID? If not, ONBOARD!
138 NSString* uuid = (__bridge_transfer NSString*) CFRetain(SecDbItemGetValue(item, &v10itemuuid, &cferror));
139 if(!uuid || [uuid isEqual: [NSNull null]]) {
140 ckksnotice("ckksscan", ckks, "making new UUID for item %@", item);
142 uuid = [[NSUUID UUID] UUIDString];
143 NSDictionary* updates = @{(id) kSecAttrUUID: uuid};
145 SecDbItemRef new_item = SecDbItemCopyWithUpdates(item, (__bridge CFDictionaryRef) updates, &cferror);
146 if(SecErrorGetOSStatus(cferror) != errSecSuccess) {
147 ckkserror("ckksscan", ckks, "couldn't update item with new UUID: %@", cferror);
148 SecTranslateError(&error, cferror);
150 CFReleaseNull(new_item);
155 bool ok = kc_transaction_type(dbt, kSecDbExclusiveRemoteCKKSTransactionType, &cferror, ^{
156 return SecDbItemUpdate(item, new_item, dbt, kCFBooleanFalse, q->q_uuid_from_primary_key, &cferror);
159 if(!ok || SecErrorGetOSStatus(cferror) != errSecSuccess) {
160 ckkserror("ckksscan", ckks, "couldn't update item with new UUID: %@", cferror);
161 SecTranslateError(&error, cferror);
163 CFReleaseNull(new_item);
167 itemToSave = CFRetainSafe(new_item);
168 CFReleaseNull(new_item);
171 // Is there a known sync item with this UUID?
172 CKKSMirrorEntry* ckme = [CKKSMirrorEntry tryFromDatabase: uuid zoneID:ckks.zoneID error: &error];
174 if ([CKKSManifest shouldSyncManifests]) {
175 [itemsForManifest addObject:ckme.item];
177 ckksinfo("ckksscan", ckks, "Existing mirror entry with UUID %@", uuid);
181 // We don't care about the oqe state here, just that one exists
182 CKKSOutgoingQueueEntry* oqe = [CKKSOutgoingQueueEntry tryFromDatabase: uuid zoneID:ckks.zoneID error: &error];
184 ckksinfo("ckksscan", ckks, "Existing outgoing queue entry with UUID %@", uuid);
185 // If its state is 'new', mark down that we've seen new entries that need processing
186 newEntries |= !![oqe.state isEqualToString: SecCKKSStateNew];
190 itemToSave = CFRetainSafe(item);
193 // Hurray, we can help!
194 self.recordsFound += 1;
196 CKKSOutgoingQueueEntry* oqe = [CKKSOutgoingQueueEntry withItem: itemToSave action: SecCKKSActionAdd ckks:ckks error: &error];
199 ckkserror("ckksscan", ckks, "Need to upload %@, but can't create outgoing entry: %@", item, error);
201 CFReleaseNull(itemToSave);
205 ckksnotice("ckksscan", ckks, "Syncing new item: %@", oqe);
206 CFReleaseNull(itemToSave);
208 [oqe saveToDatabase: &error];
210 ckkserror("ckksscan", ckks, "Need to upload %@, but can't save to database: %@", oqe, error);
215 if ([CKKSManifest shouldSyncManifests]) {
216 [itemsForManifest addObject:oqe.item];
219 self.recordsAdded += 1;
224 ckkserror("ckksscan", ckks, "error processing or finding items: %@", cferror);
225 SecTranslateError(&error, cferror);
227 query_destroy(q, NULL);
231 ok = query_notify_and_destroy(q, ok, &cferror);
234 ckkserror("ckksscan", ckks, "couldn't delete query: %@", cferror);
235 SecTranslateError(&error, cferror);
241 if ([CKKSManifest shouldSyncManifests]) {
242 // TODO: this manifest needs to incorporate peer manifests
243 CKKSEgoManifest* manifest = [CKKSEgoManifest newManifestForZone:ckks.zoneName withItems:itemsForManifest peerManifestIDs:@[] currentItems:@{} error:&error];
244 if (!manifest || error) {
245 ckkserror("ckksscan", ckks, "could not create manifest: %@", error);
250 [manifest saveToDatabase:&error];
252 ckkserror("ckksscan", ckks, "could not save manifest to database: %@", error);
257 ckks.egoManifest = manifest;
261 // Schedule a "view changed" notification
262 [ckks.notifyViewChangedScheduler trigger];
264 // notify CKKS that it should process these new entries
265 [ckks processOutgoingQueue:self.ckoperationGroup];