]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/CKKSScanLocalItemsOperation.m
Security-58286.31.2.tar.gz
[apple/security.git] / keychain / ckks / CKKSScanLocalItemsOperation.m
1 /*
2 * Copyright (c) 2016 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/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"
35
36 #include <securityd/SecItemSchema.h>
37 #include <securityd/SecItemServer.h>
38 #include <securityd/SecItemDb.h>
39 #include <Security/SecItemPriv.h>
40
41 @interface CKKSScanLocalItemsOperation ()
42 @property CKOperationGroup* ckoperationGroup;
43 @end
44
45 @implementation CKKSScanLocalItemsOperation
46
47 - (instancetype)init {
48 return nil;
49 }
50 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks ckoperationGroup:(CKOperationGroup*)ckoperationGroup {
51 if(self = [super init]) {
52 _ckks = ckks;
53 _ckoperationGroup = ckoperationGroup;
54 _recordsFound = 0;
55 _recordsAdded = 0;
56 }
57 return self;
58 }
59
60 - (void) main {
61 // Take a strong reference.
62 CKKSKeychainView* ckks = self.ckks;
63 if(!ckks) {
64 ckkserror("ckksscan", ckks, "no CKKS object");
65 return;
66 }
67
68 [ckks dispatchSyncWithAccountKeys: ^bool{
69 if(self.cancelled) {
70 ckksnotice("ckksscan", ckks, "CKKSScanLocalItemsOperation cancelled, quitting");
71 return false;
72 }
73 ckks.lastScanLocalItemsOperation = self;
74
75 NSMutableArray* itemsForManifest = [NSMutableArray array];
76
77 // First, query for all synchronizable items
78 __block CFErrorRef cferror = NULL;
79 __block NSError* error = nil;
80 __block bool newEntries = false;
81
82 // Must query per-class, so:
83 const SecDbSchema *newSchema = current_schema();
84 for (const SecDbClass *const *class = newSchema->classes; *class != NULL; class++) {
85 cferror = NULL;
86
87 if(!((*class)->itemclass)) {
88 // Don't try to scan non-item 'classes'
89 continue;
90 }
91
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,
99 };
100 ckksinfo("ckksscan", ckks, "Scanning all synchronizable items for: %@", queryAttributes);
101
102 Query *q = query_create_with_limit( (__bridge CFDictionaryRef) queryAttributes, NULL, kSecMatchUnlimited, &cferror);
103 bool ok = false;
104
105 if(cferror) {
106 ckkserror("ckksscan", ckks, "couldn't create query: %@", cferror);
107 SecTranslateError(&error, cferror);
108 self.error = error;
109 continue;
110 }
111
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);
115
116 SecDbItemRef itemToSave = NULL;
117
118 // First check: is this a tombstone? If so, skip with prejudice.
119 if(SecDbItemIsTombstone(item)) {
120 ckksinfo("ckksscan", ckks, "Skipping tombstone %@", item);
121 return;
122 }
123
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);
128 return;
129 }
130
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");
134 return;
135 }
136
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);
141
142 uuid = [[NSUUID UUID] UUIDString];
143 NSDictionary* updates = @{(id) kSecAttrUUID: uuid};
144
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);
149 self.error = error;
150 CFReleaseNull(new_item);
151 return;
152 }
153
154 if (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);
157 });
158
159 if(!ok || SecErrorGetOSStatus(cferror) != errSecSuccess) {
160 ckkserror("ckksscan", ckks, "couldn't update item with new UUID: %@", cferror);
161 SecTranslateError(&error, cferror);
162 self.error = error;
163 CFReleaseNull(new_item);
164 return;
165 }
166 }
167 itemToSave = CFRetainSafe(new_item);
168 CFReleaseNull(new_item);
169
170 } else {
171 // Is there a known sync item with this UUID?
172 CKKSMirrorEntry* ckme = [CKKSMirrorEntry tryFromDatabase: uuid zoneID:ckks.zoneID error: &error];
173 if(ckme != nil) {
174 if ([CKKSManifest shouldSyncManifests]) {
175 [itemsForManifest addObject:ckme.item];
176 }
177 ckksinfo("ckksscan", ckks, "Existing mirror entry with UUID %@", uuid);
178 return;
179 }
180
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];
183 if(oqe != nil) {
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];
187 return;
188 }
189
190 itemToSave = CFRetainSafe(item);
191 }
192
193 // Hurray, we can help!
194 self.recordsFound += 1;
195
196 CKKSOutgoingQueueEntry* oqe = [CKKSOutgoingQueueEntry withItem: itemToSave action: SecCKKSActionAdd ckks:ckks error: &error];
197
198 if(error) {
199 ckkserror("ckksscan", ckks, "Need to upload %@, but can't create outgoing entry: %@", item, error);
200 self.error = error;
201 CFReleaseNull(itemToSave);
202 return;
203 }
204
205 ckksnotice("ckksscan", ckks, "Syncing new item: %@", oqe);
206 CFReleaseNull(itemToSave);
207
208 [oqe saveToDatabase: &error];
209 if(error) {
210 ckkserror("ckksscan", ckks, "Need to upload %@, but can't save to database: %@", oqe, error);
211 self.error = error;
212 return;
213 }
214 newEntries = true;
215 if ([CKKSManifest shouldSyncManifests]) {
216 [itemsForManifest addObject:oqe.item];
217 }
218
219 self.recordsAdded += 1;
220 });
221 });
222
223 if(cferror || !ok) {
224 ckkserror("ckksscan", ckks, "error processing or finding items: %@", cferror);
225 SecTranslateError(&error, cferror);
226 self.error = error;
227 query_destroy(q, NULL);
228 continue;
229 }
230
231 ok = query_notify_and_destroy(q, ok, &cferror);
232
233 if(cferror || !ok) {
234 ckkserror("ckksscan", ckks, "couldn't delete query: %@", cferror);
235 SecTranslateError(&error, cferror);
236 self.error = error;
237 continue;
238 }
239 }
240
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);
246 self.error = error;
247 return false;
248 }
249
250 [manifest saveToDatabase:&error];
251 if (error) {
252 ckkserror("ckksscan", ckks, "could not save manifest to database: %@", error);
253 self.error = error;
254 return false;
255 }
256
257 ckks.egoManifest = manifest;
258 }
259
260 if(newEntries) {
261 // Schedule a "view changed" notification
262 [ckks.notifyViewChangedScheduler trigger];
263
264 // notify CKKS that it should process these new entries
265 [ckks processOutgoingQueue:self.ckoperationGroup];
266 }
267
268 return true;
269 }];
270 }
271
272 @end;
273
274 #endif