]> git.saurik.com Git - apple/security.git/blob - OSX/sec/securityd/SecItemDataSource.c
Security-57336.1.9.tar.gz
[apple/security.git] / OSX / sec / securityd / SecItemDataSource.c
1 /*
2 * Copyright (c) 2006-2014 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 /*
25 * SecItemDataSource.c - CoreFoundation-based constants and functions for
26 access to Security items (certificates, keys, identities, and
27 passwords.)
28 */
29
30 #include <securityd/SecItemDataSource.h>
31
32 #include <securityd/SecItemDb.h>
33 #include <securityd/SecItemSchema.h>
34 #include <securityd/SOSCloudCircleServer.h>
35 #include <Security/SecureObjectSync/SOSDigestVector.h>
36 #include <Security/SecureObjectSync/SOSViews.h>
37 #include <Security/SecBasePriv.h>
38 #include <Security/SecItem.h>
39 #include <Security/SecItemBackup.h>
40 #include <Security/SecItemPriv.h>
41 #include <utilities/array_size.h>
42
43 /*
44 *
45 *
46 * SecItemDataSource
47 *
48 *
49 */
50 typedef struct SecItemDataSource *SecItemDataSourceRef;
51
52 struct SecItemDataSource {
53 struct SOSDataSource ds;
54 SecDbRef db; // The database we operate on
55 CFStringRef name; // The name of the slice of the database we represent.
56 };
57
58 static const SecDbClass *dsSyncedClassesV0[] = {
59 &genp_class,
60 &inet_class,
61 &keys_class,
62 };
63
64 static const SecDbClass *dsSyncedClasses[] = {
65 &genp_class, // genp must be first!
66 &inet_class,
67 &keys_class,
68 &cert_class,
69 };
70
71 static bool SecDbItemSelectSHA1(SecDbQueryRef query, SecDbConnectionRef dbconn, CFErrorRef *error,
72 bool (^use_attr_in_where)(const SecDbAttr *attr),
73 bool (^add_where_sql)(CFMutableStringRef sql, bool *needWhere),
74 bool (^bind_added_where)(sqlite3_stmt *stmt, int col),
75 void (^row)(sqlite3_stmt *stmt, bool *stop)) {
76 __block bool ok = true;
77 bool (^return_attr)(const SecDbAttr *attr) = ^bool (const SecDbAttr * attr) {
78 return attr->kind == kSecDbSHA1Attr;
79 };
80 CFStringRef sql = SecDbItemCopySelectSQL(query, return_attr, use_attr_in_where, add_where_sql);
81 if (sql) {
82 ok &= SecDbPrepare(dbconn, sql, error, ^(sqlite3_stmt *stmt) {
83 ok = (SecDbItemSelectBind(query, stmt, error, use_attr_in_where, bind_added_where) &&
84 SecDbStep(dbconn, stmt, error, ^(bool *stop){ row(stmt, stop); }));
85 });
86 CFRelease(sql);
87 } else {
88 ok = false;
89 }
90 return ok;
91 }
92
93 static SOSManifestRef SecItemDataSourceCopyManifestWithQueries(SecItemDataSourceRef ds, CFArrayRef queries, CFErrorRef *error) {
94 __block SOSManifestRef manifest = NULL;
95 __block CFErrorRef localError = NULL;
96 if (!SecDbPerformRead(ds->db, error, ^(SecDbConnectionRef dbconn) {
97 __block struct SOSDigestVector dv = SOSDigestVectorInit;
98 Query *q;
99 bool ok = true;
100 CFArrayForEachC(queries, q) {
101 if (!(ok &= SecDbItemSelectSHA1(q, dbconn, &localError, ^bool(const SecDbAttr *attr) {
102 return CFDictionaryContainsKey(q->q_item, attr->name);
103 }, NULL, NULL, ^(sqlite3_stmt *stmt, bool *stop) {
104 const uint8_t *digest = sqlite3_column_blob(stmt, 0);
105 size_t digestLen = sqlite3_column_bytes(stmt, 0);
106 if (digestLen != SOSDigestSize) {
107 secerror("digest %zu bytes", digestLen);
108 } else {
109 SOSDigestVectorAppend(&dv, digest);
110 }
111 }))) {
112 secerror("SecDbItemSelectSHA1 failed: %@", localError);
113 break;
114 }
115 }
116 if (ok) {
117 // TODO: This code assumes that the passed in queries do not overlap, otherwise we'd need something to eliminate dupes:
118 //SOSDigestVectorUniqueSorted(&dv);
119 manifest = SOSManifestCreateWithDigestVector(&dv, &localError);
120 }
121 SOSDigestVectorFree(&dv);
122 })) {
123 CFReleaseSafe(manifest);
124 }
125 CFErrorPropagate(localError, error);
126 return manifest;
127 }
128
129 static Query *SecItemDataSourceAppendQuery(CFMutableArrayRef queries, const SecDbClass *qclass, bool noTombstones, CFErrorRef *error) {
130 Query *q = query_create(qclass, NULL, error);
131 if (q) {
132 q->q_return_type = kSecReturnDataMask | kSecReturnAttributesMask;
133 q->q_limit = kSecMatchUnlimited;
134 q->q_keybag = KEYBAG_DEVICE;
135 query_add_attribute(kSecAttrSynchronizable, kCFBooleanTrue, q);
136 query_add_or_attribute(kSecAttrAccessible, kSecAttrAccessibleWhenUnlocked, q);
137 query_add_or_attribute(kSecAttrAccessible, kSecAttrAccessibleAfterFirstUnlock, q);
138 query_add_or_attribute(kSecAttrAccessible, kSecAttrAccessibleAlways, q);
139 query_add_or_attribute(kSecAttrAccessible, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, q);
140 query_add_or_attribute(kSecAttrAccessible, kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, q);
141 query_add_or_attribute(kSecAttrAccessible, kSecAttrAccessibleAlwaysThisDeviceOnly, q);
142
143 if (noTombstones) {
144 query_add_attribute(kSecAttrTombstone, kCFBooleanFalse, q);
145 }
146
147 CFArrayAppendValue(queries, q);
148 }
149 return q;
150 }
151
152 static Query *SecItemDataSourceAppendQueryWithClass(CFMutableArrayRef queries, const SecDbClass *qclass, bool noTombstones, bool allowTkid, CFErrorRef *error) {
153 Query *q = SecItemDataSourceAppendQuery(queries, qclass, noTombstones, error);
154 if (q) {
155 // For each attribute in current schema but not in v6, look for the
156 // default value of those attributes in the query, since old items
157 // will all have that as their values for these new attributes.
158 SecDbForEachAttr(qclass, attr) {
159 if ((attr->flags & (kSecDbPrimaryKeyFlag | kSecDbDefaultEmptyFlag | kSecDbDefault0Flag | kSecDbNotNullFlag)) == kSecDbPrimaryKeyFlag) {
160 // attr is a primary key attribute added in schema version 7 or later
161 if (!allowTkid || attr != &v7tkid) {
162 CFTypeRef value = SecDbAttrCopyDefaultValue(attr, &q->q_error);
163 if (value)
164 query_add_attribute_with_desc(attr, value, q);
165 CFReleaseSafe(value);
166 }
167 }
168 }
169 }
170 return q;
171 }
172
173 static Query *SecItemDataSourceAppendQueryWithClassAndAgrp(CFMutableArrayRef queries, const SecDbClass *qclass, bool noTombstones, bool allowTkid, CFStringRef agrp, CFErrorRef *error) {
174 Query *q = SecItemDataSourceAppendQueryWithClass(queries, qclass, noTombstones, allowTkid, error);
175 if (q && agrp) {
176 query_add_attribute(kSecAttrAccessGroup, agrp, q);
177 }
178 return q;
179 }
180
181 static bool SecItemDataSourceAppendQueriesForViewName(SecItemDataSourceRef ds, CFMutableArrayRef queries, CFStringRef compositeViewName, CFErrorRef *error) {
182 bool ok = true;
183 CFStringRef viewName;
184 bool noTombstones = CFStringHasSuffix(compositeViewName, CFSTR("-tomb"));
185 if (noTombstones) {
186 viewName = CFStringCreateWithSubstring(kCFAllocatorDefault, compositeViewName, CFRangeMake(0, CFStringGetLength(compositeViewName) - 5));
187 } else {
188 viewName = CFRetain(compositeViewName);
189 }
190
191 const bool noTKID = false;
192 const bool allowTKID = true;
193 if (CFEqual(viewName, kSOSViewKeychainV0)) {
194 for (size_t class_ix = 0; class_ix < array_size(dsSyncedClassesV0); ++class_ix) {
195 SecItemDataSourceAppendQueryWithClass(queries, dsSyncedClassesV0[class_ix], noTombstones, noTKID, error);
196 }
197 } else if (CFEqual(viewName, kSOSViewWiFi)) {
198 Query *q = SecItemDataSourceAppendQueryWithClassAndAgrp(queries, &genp_class, noTombstones, allowTKID, CFSTR("apple"), error);
199 if (q) {
200 query_add_attribute(kSecAttrService, CFSTR("AirPort"), q);
201 }
202 } else if (CFEqual(viewName, kSOSViewAutofillPasswords)) {
203 SecItemDataSourceAppendQueryWithClassAndAgrp(queries, &inet_class, noTombstones, allowTKID, CFSTR("com.apple.cfnetwork"), error);
204 } else if (CFEqual(viewName, kSOSViewSafariCreditCards)) {
205 SecItemDataSourceAppendQueryWithClassAndAgrp(queries, &genp_class, noTombstones, allowTKID, CFSTR("com.apple.safari.credit-cards"), error);
206 } else if (CFEqual(viewName, kSOSViewiCloudIdentity)) {
207 SecItemDataSourceAppendQueryWithClassAndAgrp(queries, &keys_class, noTombstones, allowTKID, CFSTR("com.apple.security.sos"), error);
208 } else if (CFEqual(viewName, kSOSViewBackupBagV0)) {
209 SecItemDataSourceAppendQueryWithClassAndAgrp(queries, &genp_class, noTombstones, allowTKID, CFSTR("com.apple.sbd"), error);
210 } else if (CFEqual(viewName, kSOSViewOtherSyncable)) {
211 SecItemDataSourceAppendQueryWithClass(queries, &cert_class, noTombstones, allowTKID, error);
212
213 Query *q1_genp = SecItemDataSourceAppendQueryWithClassAndAgrp(queries, &genp_class, noTombstones, allowTKID, CFSTR("apple"), error);
214 query_add_not_attribute(kSecAttrService, CFSTR("AirPort"), q1_genp);
215
216 Query *q2_genp = SecItemDataSourceAppendQueryWithClass(queries, &genp_class, noTombstones, allowTKID, error);
217 query_add_not_attribute(kSecAttrAccessGroup, CFSTR("apple"), q2_genp);
218 query_add_not_attribute(kSecAttrAccessGroup, CFSTR("com.apple.safari.credit-cards"), q2_genp);
219 query_add_not_attribute(kSecAttrAccessGroup, CFSTR("com.apple.sbd"), q2_genp);
220
221 Query *q_inet = SecItemDataSourceAppendQueryWithClass(queries, &inet_class, noTombstones, allowTKID, error);
222 query_add_not_attribute(kSecAttrAccessGroup, CFSTR("com.apple.cfnetwork"), q_inet);
223
224 Query *q_keys = SecItemDataSourceAppendQueryWithClass(queries, &keys_class, noTombstones, allowTKID, error);
225 query_add_not_attribute(kSecAttrAccessGroup, CFSTR("com.apple.security.sos"), q_keys);
226 }
227
228 CFReleaseSafe(viewName);
229 return ok;
230 }
231
232 static SOSManifestRef SecItemDataSourceCopyManifestWithViewNameSet(SecItemDataSourceRef ds, CFSetRef viewNames, CFErrorRef *error) {
233 CFMutableArrayRef queries = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
234 SOSManifestRef manifest = NULL;
235 __block bool ok = true;
236 CFSetForEach(viewNames, ^(const void *value) {
237 CFStringRef viewName = (CFStringRef)value;
238 ok &= SecItemDataSourceAppendQueriesForViewName(ds, queries, viewName, error);
239 });
240 if (ok)
241 manifest = SecItemDataSourceCopyManifestWithQueries(ds, queries, error);
242 Query *q;
243 CFArrayForEachC(queries, q) {
244 CFErrorRef localError = NULL;
245 if (!query_destroy(q, &localError)) {
246 secerror("query_destroy failed: %@", localError);
247 CFErrorPropagate(localError, error);
248 CFReleaseNull(manifest);
249 }
250 }
251 CFReleaseSafe(queries);
252 return manifest;
253 }
254
255 // Return the newest object (conflict resolver)
256 static SecDbItemRef SecItemDataSourceCopyMergedItem(SecDbItemRef item1, SecDbItemRef item2, CFErrorRef *error) {
257 CFErrorRef localError = NULL;
258 SecDbItemRef result = NULL;
259 CFDateRef m1, m2;
260 const SecDbAttr *desc = SecDbAttrWithKey(SecDbItemGetClass(item1), kSecAttrModificationDate, error);
261 m1 = SecDbItemGetValue(item1, desc, &localError);
262 m2 = SecDbItemGetValue(item2, desc, &localError);
263 if (m1 && m2) switch (CFDateCompare(m1, m2, NULL)) {
264 case kCFCompareGreaterThan:
265 result = item1;
266 break;
267 case kCFCompareLessThan:
268 result = item2;
269 break;
270 case kCFCompareEqualTo:
271 {
272 // Return the item with the smallest digest.
273 CFDataRef digest1 = SecDbItemGetSHA1(item1, &localError);
274 CFDataRef digest2 = SecDbItemGetSHA1(item2, &localError);
275 if (digest1 && digest2) switch (CFDataCompare(digest1, digest2)) {
276 case kCFCompareGreaterThan:
277 case kCFCompareEqualTo:
278 result = item2;
279 break;
280 case kCFCompareLessThan:
281 result = item1;
282 break;
283 } else if (SecErrorGetOSStatus(localError) == errSecDecode) {
284 if (digest1) result = item1;
285 if (digest2) result = item2;
286 }
287 break;
288 }
289 } else if (SecErrorGetOSStatus(localError) == errSecDecode) {
290 // If one of the two objects has an unparsable date,
291 // the object with the parsable date wins.
292 if (m1) result = item1;
293 if (m2) result = item2;
294 }
295
296 if (localError) {
297 if (!result && error && !*error)
298 *error = localError;
299 else
300 CFRelease(localError);
301 }
302 return CFRetainSafe(result);
303 }
304
305 //
306 // MARK: DataSource protocol implementation
307 //
308
309 static CFStringRef dsGetName(SOSDataSourceRef data_source) {
310 SecItemDataSourceRef ds = (SecItemDataSourceRef)data_source;
311 return ds->name;
312 }
313
314 static void dsSetNotifyPhaseBlock(SOSDataSourceRef data_source, dispatch_queue_t queue, SOSDataSourceNotifyBlock notifyBlock) {
315 SecItemDataSourceRef ds = (SecItemDataSourceRef)data_source;
316 SecDbSetNotifyPhaseBlock(ds->db, queue, notifyBlock
317 ? ^(SecDbConnectionRef dbconn, SecDbTransactionPhase phase, SecDbTransactionSource source, CFArrayRef changes) {
318 notifyBlock(&ds->ds, (SOSTransactionRef)dbconn, phase, source, changes);
319 }
320 : NULL);
321 }
322
323 static SOSManifestRef dsCopyManifestWithViewNameSet(SOSDataSourceRef data_source, CFSetRef viewNameSet, CFErrorRef *error) {
324 struct SecItemDataSource *ds = (struct SecItemDataSource *)data_source;
325 return SecItemDataSourceCopyManifestWithViewNameSet(ds, viewNameSet, error);
326 }
327
328 static bool dsForEachObject(SOSDataSourceRef data_source, SOSManifestRef manifest, CFErrorRef *error, void (^handle_object)(CFDataRef key, SOSObjectRef object, bool *stop)) {
329 struct SecItemDataSource *ds = (struct SecItemDataSource *)data_source;
330 __block bool result = true;
331 const SecDbAttr *sha1Attr = SecDbClassAttrWithKind(&genp_class, kSecDbSHA1Attr, error);
332 if (!sha1Attr) return false;
333 bool (^return_attr)(const SecDbAttr *attr) = ^bool (const SecDbAttr * attr) {
334 return attr->kind == kSecDbRowIdAttr || attr->kind == kSecDbEncryptedDataAttr;
335 };
336 bool (^use_attr_in_where)(const SecDbAttr *attr) = ^bool (const SecDbAttr * attr) {
337 return attr->kind == kSecDbSHA1Attr;
338 };
339 Query *select_queries[array_size(dsSyncedClasses)] = {};
340 CFStringRef select_sql[array_size(dsSyncedClasses)] = {};
341 sqlite3_stmt *select_stmts[array_size(dsSyncedClasses)] = {};
342
343 __block Query **queries = select_queries;
344 __block CFStringRef *sqls = select_sql;
345 __block sqlite3_stmt **stmts = select_stmts;
346
347 result &= SecDbPerformRead(ds->db, error, ^(SecDbConnectionRef dbconn) {
348 // Setup
349 for (size_t class_ix = 0; class_ix < array_size(dsSyncedClasses); ++class_ix) {
350 result = (result
351 && (queries[class_ix] = query_create(dsSyncedClasses[class_ix], NULL, error))
352 && (sqls[class_ix] = SecDbItemCopySelectSQL(queries[class_ix], return_attr, use_attr_in_where, NULL))
353 && (stmts[class_ix] = SecDbCopyStmt(dbconn, sqls[class_ix], NULL, error)));
354 }
355
356 if (result) SOSManifestForEach(manifest, ^(CFDataRef key, bool *stop) {
357 __block SecDbItemRef item = NULL;
358 for (size_t class_ix = 0; result && !item && class_ix < array_size(dsSyncedClasses); ++class_ix) {
359 CFDictionarySetValue(queries[class_ix]->q_item, sha1Attr->name, key);
360 result = (SecDbItemSelectBind(queries[class_ix], stmts[class_ix], error, use_attr_in_where, NULL) && SecDbStep(dbconn, stmts[class_ix], error, ^(bool *unused_stop) {
361 item = SecDbItemCreateWithStatement(kCFAllocatorDefault, queries[class_ix]->q_class, stmts[class_ix], KEYBAG_DEVICE, error, return_attr);
362 })) && SecDbReset(stmts[class_ix], error);
363 }
364 handle_object(key, (SOSObjectRef)item, stop);
365 CFReleaseSafe(item);
366 });
367
368 // Cleanup
369 for (size_t class_ix = 0; class_ix < array_size(dsSyncedClasses); ++class_ix) {
370 result &= SecDbReleaseCachedStmt(dbconn, sqls[class_ix], stmts[class_ix], error);
371 CFReleaseSafe(sqls[class_ix]);
372 result &= query_destroy(queries[class_ix], error);
373 }
374 });
375 return result;
376 }
377
378 static bool dsRelease(SOSDataSourceRef data_source, CFErrorRef *error) {
379 // We never release our dataSource since it's tracking changes
380 // to the keychain for the engine and its peers.
381 return true;
382 }
383
384 static SOSObjectRef objectCreateWithPropertyList(CFDictionaryRef plist, CFErrorRef *error) {
385 SecDbItemRef item = NULL;
386 const SecDbClass *class = NULL;
387 CFTypeRef cname = CFDictionaryGetValue(plist, kSecClass);
388 if (cname) {
389 class = kc_class_with_name(cname);
390 if (class) {
391 item = SecDbItemCreateWithAttributes(kCFAllocatorDefault, class, plist, KEYBAG_DEVICE, error);
392 } else {
393 SecError(errSecNoSuchClass, error, CFSTR("can find class named: %@"), cname);
394 }
395 } else {
396 SecError(errSecItemClassMissing, error, CFSTR("query missing %@ attribute"), kSecClass);
397 }
398 return (SOSObjectRef)item;
399 }
400
401 static CFDataRef copyObjectDigest(SOSObjectRef object, CFErrorRef *error) {
402 SecDbItemRef item = (SecDbItemRef) object;
403 CFDataRef digest = SecDbItemGetSHA1(item, error);
404 CFRetainSafe(digest);
405 return digest;
406 }
407
408 static CFDataRef objectCopyPrimaryKey(SOSObjectRef object, CFErrorRef *error) {
409 SecDbItemRef item = (SecDbItemRef) object;
410 CFDataRef pk = SecDbItemGetPrimaryKey(item, error);
411 CFRetainSafe(pk);
412 return pk;
413 }
414
415 static CFDictionaryRef objectCopyPropertyList(SOSObjectRef object, CFErrorRef *error) {
416 SecDbItemRef item = (SecDbItemRef) object;
417 CFMutableDictionaryRef cryptoDataDict = SecDbItemCopyPListWithMask(item, kSecDbInCryptoDataFlag, error);
418 CFMutableDictionaryRef authDataDict = SecDbItemCopyPListWithMask(item, kSecDbInAuthenticatedDataFlag, error);
419
420 if (cryptoDataDict) {
421 if (authDataDict) {
422 CFDictionaryForEach(authDataDict, ^(const void *key, const void *value) {
423 CFDictionarySetValue(cryptoDataDict, key, value);
424 });
425 }
426 CFDictionaryAddValue(cryptoDataDict, kSecClass, SecDbItemGetClass(item)->name);
427 }
428
429 CFReleaseSafe(authDataDict);
430 return cryptoDataDict;
431 }
432
433 static bool dsWith(SOSDataSourceRef data_source, CFErrorRef *error, SOSDataSourceTransactionSource source, void(^transaction)(SOSTransactionRef txn, bool *commit)) {
434 SecItemDataSourceRef ds = (SecItemDataSourceRef)data_source;
435 __block bool ok = true;
436 ok &= SecDbPerformWrite(ds->db, error, ^(SecDbConnectionRef dbconn) {
437 ok &= SecDbTransaction(dbconn,
438 source == kSOSDataSourceAPITransaction ? kSecDbExclusiveTransactionType : kSecDbExclusiveRemoteTransactionType,
439 error, ^(bool *commit) {
440 transaction((SOSTransactionRef)dbconn, commit);
441 });
442 });
443 return ok;
444 }
445
446 static SOSMergeResult dsMergeObject(SOSTransactionRef txn, SOSObjectRef peersObject, SOSObjectRef *mergedObject, CFErrorRef *error) {
447 SecDbConnectionRef dbconn = (SecDbConnectionRef)txn;
448 SecDbItemRef peersItem = (SecDbItemRef)peersObject;
449 __block SOSMergeResult mr = kSOSMergeFailure;
450 __block SecDbItemRef mergedItem = NULL;
451 __block SecDbItemRef replacedItem = NULL;
452 if (!peersItem || !dbconn || !SecDbItemSetKeybag(peersItem, KEYBAG_DEVICE, error)) return mr;
453 if (SecDbItemInsertOrReplace(peersItem, dbconn, error, ^(SecDbItemRef myItem, SecDbItemRef *replace) {
454 // An item with the same primary key as dbItem already exists in the the database. That item is old_item.
455 // Let the conflict resolver choose which item to keep.
456 mergedItem = SecItemDataSourceCopyMergedItem(peersItem, myItem, error);
457 if (mergedObject) *mergedObject = (SOSObjectRef)CFRetain(mergedItem);
458 if (!mergedItem) return;
459 if (CFEqual(mergedItem, myItem)) {
460 // Conflict resolver choose my (local) item
461 secnotice("ds", "Conflict resolver choose my (local) item: %@", myItem);
462 mr = kSOSMergeLocalObject;
463 } else {
464 CFRetainAssign(replacedItem, myItem);
465 *replace = CFRetainSafe(mergedItem);
466 if (CFEqual(mergedItem, peersItem)) {
467 // Conflict resolver choose peers item
468 secnotice("ds", "Conflict resolver choose peers item: %@", peersItem);
469 mr = kSOSMergePeersObject;
470 } else {
471 // Conflict resolver created a new item; return it to our caller
472 secnotice("ds", "Conflict resolver created a new item; return it to our caller: %@", mergedItem);
473 mr = kSOSMergeCreatedObject;
474 }
475 }
476 })) {
477 if (mr == kSOSMergeFailure)
478 {
479 secnotice("ds", "kSOSMergeFailure => kSOSMergePeersObject");
480 mr = kSOSMergePeersObject;
481 }
482 }
483
484 if (error && *error && mr != kSOSMergeFailure)
485 CFReleaseNull(*error);
486
487 CFReleaseSafe(mergedItem);
488 CFReleaseSafe(replacedItem);
489 return mr;
490 }
491
492 /*
493 Truthy backup format is a dictionary from sha1 => item.
494 Each item has class, hash and item data.
495
496 TODO: sha1 is included as binary blob to avoid parsing key.
497 */
498 enum {
499 kSecBackupIndexHash = 0,
500 kSecBackupIndexClass,
501 kSecBackupIndexData,
502 };
503
504 static const void *kSecBackupKeys[] = {
505 [kSecBackupIndexHash] = kSecItemBackupHashKey,
506 [kSecBackupIndexClass] = kSecItemBackupClassKey,
507 [kSecBackupIndexData] = kSecItemBackupDataKey
508 };
509
510 static CFDictionaryRef objectCopyBackup(SOSObjectRef object, uint64_t handle, CFErrorRef *error) {
511 const void *values[array_size(kSecBackupKeys)];
512 SecDbItemRef item = (SecDbItemRef)object;
513 CFDictionaryRef backup_item = NULL;
514
515 if ((values[kSecBackupIndexHash] = SecDbItemGetSHA1(item, error))) {
516 if ((values[kSecBackupIndexData] = SecDbItemCopyEncryptedDataToBackup(item, handle, error))) {
517 values[kSecBackupIndexClass] = SecDbItemGetClass(item)->name;
518 backup_item = CFDictionaryCreate(kCFAllocatorDefault, kSecBackupKeys, values, array_size(kSecBackupKeys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
519 CFRelease(values[kSecBackupIndexData]);
520 }
521 }
522
523 return backup_item;
524 }
525
526 static CFDataRef dsCopyStateWithKey(SOSDataSourceRef data_source, CFStringRef key, CFStringRef pdmn, CFErrorRef *error) {
527 SecItemDataSourceRef ds = (SecItemDataSourceRef)data_source;
528 CFStringRef dataSourceID = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("SOSDataSource-%@"), ds->name);
529 CFMutableDictionaryRef dict = CFDictionaryCreateMutableForCFTypesWith(kCFAllocatorDefault,
530 kSecAttrAccessGroup, kSOSInternalAccessGroup,
531 kSecAttrAccount, key,
532 kSecAttrService, dataSourceID,
533 kSecAttrAccessible, pdmn,
534 kSecAttrSynchronizable, kCFBooleanFalse,
535 NULL);
536 CFReleaseSafe(dataSourceID);
537 __block CFDataRef data = NULL;
538 SecDbQueryRef query = query_create(&genp_class, dict, error);
539 if (query) {
540 if (query->q_item) CFReleaseSafe(query->q_item);
541 query->q_item = dict;
542 SecDbPerformRead(ds->db, error, ^(SecDbConnectionRef dbconn) {
543 SecDbItemSelect(query, dbconn, error, NULL, ^bool(const SecDbAttr *attr) {
544 return CFDictionaryContainsKey(dict, attr->name);
545 }, NULL, NULL, ^(SecDbItemRef item, bool *stop) {
546 secnotice("ds", "found item for key %@@%@", key, pdmn);
547 data = CFRetainSafe(SecDbItemGetValue(item, &v6v_Data, error));
548 });
549 });
550 query_destroy(query, error);
551 } else {
552 CFReleaseSafe(dict);
553 }
554 if (!data) secnotice("ds", "failed to load %@@%@ state: %@", key, pdmn, error ? *error : NULL);
555 return data;
556 }
557
558 static CFDataRef dsCopyItemDataWithKeys(SOSDataSourceRef data_source, CFDictionaryRef keys, CFErrorRef *error) {
559 /*
560 Values for V0 are:
561 kSecAttrAccessGroup ==> CFSTR("com.apple.sbd")
562 kSecAttrAccessible ==> kSecAttrAccessibleWhenUnlocked
563 kSecAttrAccount ==> CFSTR("SecureBackupPublicKeybag")
564 kSecAttrService ==> CFSTR("SecureBackupService")
565
566 CFMutableDictionaryRef dict = CFDictionaryCreateMutableForCFTypesWith(kCFAllocatorDefault,
567 kSecAttrAccessGroup, CFSTR("com.apple.sbd"),
568 kSecAttrAccount, account,
569 kSecAttrService, service,
570 kSecAttrAccessible, pdmn,
571 kSecAttrSynchronizable, kCFBooleanTrue,
572 NULL);
573 */
574
575 SecItemDataSourceRef ds = (SecItemDataSourceRef)data_source;
576 CFMutableDictionaryRef dict = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, keys);
577 __block CFDataRef data = NULL;
578 SecDbQueryRef query = query_create(&genp_class, dict, error);
579 if (query) {
580 if (query->q_item) CFReleaseSafe(query->q_item);
581 query->q_item = dict;
582 SecDbPerformRead(ds->db, error, ^(SecDbConnectionRef dbconn) {
583 SecDbItemSelect(query, dbconn, error, NULL, ^bool(const SecDbAttr *attr) {
584 return CFDictionaryContainsKey(dict, attr->name);
585 }, NULL, NULL, ^(SecDbItemRef item, bool *stop) {
586 secnotice("ds", "found item for keys %@", keys);
587 data = CFRetainSafe(SecDbItemGetValue(item, &v6v_Data, error));
588 });
589 });
590 query_destroy(query, error);
591 } else {
592 CFReleaseSafe(dict);
593 }
594 if (!data) secnotice("ds", "failed to load item %@: %@", keys, error ? *error : NULL);
595 return data;
596 }
597
598 static bool dsSetStateWithKey(SOSDataSourceRef data_source, SOSTransactionRef txn, CFStringRef key, CFStringRef pdmn, CFDataRef state, CFErrorRef *error) {
599 SecItemDataSourceRef ds = (SecItemDataSourceRef)data_source;
600 CFStringRef dataSourceID = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("SOSDataSource-%@"), ds->name);
601 CFMutableDictionaryRef dict = CFDictionaryCreateMutableForCFTypesWith(kCFAllocatorDefault,
602 kSecAttrAccessGroup, kSOSInternalAccessGroup,
603 kSecAttrAccount, key,
604 kSecAttrService, dataSourceID,
605 kSecAttrAccessible, pdmn,
606 kSecAttrSynchronizable, kCFBooleanFalse,
607 kSecValueData, state,
608 NULL);
609 CFReleaseSafe(dataSourceID);
610 SecDbItemRef item = SecDbItemCreateWithAttributes(kCFAllocatorDefault, &genp_class, dict, KEYBAG_DEVICE, error);
611 SOSMergeResult mr = dsMergeObject(txn, (SOSObjectRef)item, NULL, error);
612 if (mr == kSOSMergeFailure) secerror("failed to save %@@%@ state: %@", key, pdmn, error ? *error : NULL);
613 CFReleaseSafe(item);
614 CFReleaseSafe(dict);
615 return mr != kSOSMergeFailure;
616 }
617
618 static bool dsRestoreObject(SOSTransactionRef txn, uint64_t handle, CFDictionaryRef item, CFErrorRef *error) {
619 CFStringRef item_class = CFDictionaryGetValue(item, kSecItemBackupClassKey);
620 CFDataRef data = CFDictionaryGetValue(item, kSecItemBackupDataKey);
621 const SecDbClass *dbclass = NULL;
622
623 if (!item_class || !data)
624 return SecError(errSecDecode, error, CFSTR("no class or data in object"));
625
626 dbclass = kc_class_with_name(item_class);
627 if (!dbclass)
628 return SecError(errSecDecode, error, CFSTR("no such class %@; update kc_class_with_name "), item_class);
629
630 SecDbItemRef dbitem = SecDbItemCreateWithEncryptedData(kCFAllocatorDefault, dbclass, data, (keybag_handle_t)handle, error);
631 bool ok = dbitem && (dsMergeObject(txn, (SOSObjectRef)dbitem, NULL, error) != kSOSMergeFailure);
632 CFReleaseSafe(dbitem);
633 return ok;
634 }
635
636 SOSDataSourceRef SecItemDataSourceCreate(SecDbRef db, CFStringRef name, CFErrorRef *error) {
637 SecItemDataSourceRef ds = calloc(1, sizeof(struct SecItemDataSource));
638 ds->ds.dsGetName = dsGetName;
639 ds->ds.dsSetNotifyPhaseBlock = dsSetNotifyPhaseBlock;
640 ds->ds.dsCopyManifestWithViewNameSet = dsCopyManifestWithViewNameSet;
641 ds->ds.dsCopyStateWithKey = dsCopyStateWithKey;
642 ds->ds.dsCopyItemDataWithKeys = dsCopyItemDataWithKeys;
643
644 ds->ds.dsForEachObject = dsForEachObject;
645 ds->ds.dsWith = dsWith;
646 ds->ds.dsRelease = dsRelease;
647
648 ds->ds.dsMergeObject = dsMergeObject;
649 ds->ds.dsSetStateWithKey = dsSetStateWithKey;
650 ds->ds.dsRestoreObject = dsRestoreObject;
651
652 // Object field accessors
653 ds->ds.objectCopyDigest = copyObjectDigest;
654 ds->ds.objectCopyPrimaryKey = objectCopyPrimaryKey;
655
656 // Object encode and decode.
657 ds->ds.objectCreateWithPropertyList = objectCreateWithPropertyList;
658 ds->ds.objectCopyPropertyList = objectCopyPropertyList;
659 ds->ds.objectCopyBackup = objectCopyBackup;
660
661 ds->db = CFRetainSafe(db);
662 ds->name = CFRetainSafe(name);
663
664 // Do this after the ds is fully setup so the engine can query us right away.
665 ds->ds.engine = SOSEngineCreate(&ds->ds, error);
666 if (!ds->ds.engine) {
667 free(ds);
668 ds = NULL;
669 }
670 return &ds->ds;
671 }
672
673 static CFStringRef SecItemDataSourceFactoryCopyName(SOSDataSourceFactoryRef factory)
674 {
675 // This is the name of the v0 datasource, a.k.a. "ak"
676 return kSecAttrAccessibleWhenUnlocked;
677 }
678
679 struct SecItemDataSourceFactory {
680 struct SOSDataSourceFactory factory;
681 CFMutableDictionaryRef dsCache;
682 dispatch_queue_t queue;
683 SecDbRef db;
684 };
685
686 static SOSDataSourceRef SecItemDataSourceFactoryCopyDataSource(SOSDataSourceFactoryRef factory, CFStringRef dataSourceName, CFErrorRef *error)
687 {
688 struct SecItemDataSourceFactory *f = (struct SecItemDataSourceFactory *)factory;
689 __block SOSDataSourceRef dataSource = NULL;
690 dispatch_sync(f->queue, ^{
691 dataSource = (SOSDataSourceRef)CFDictionaryGetValue(f->dsCache, dataSourceName);
692 if (!dataSource) {
693 dataSource = (SOSDataSourceRef)SecItemDataSourceCreate(f->db, dataSourceName, error);
694 CFDictionarySetValue(f->dsCache, dataSourceName, dataSource);
695 }
696 });
697 return dataSource;
698 }
699
700 static void SecItemDataSourceFactoryDispose(SOSDataSourceFactoryRef factory)
701 {
702 // Nothing to do here.
703 }
704
705 static void SecItemDataSourceFactoryCircleChanged(SOSDataSourceFactoryRef factory, CFStringRef myPeerID, CFArrayRef trustedPeerIDs, CFArrayRef untrustedPeerIDs) {
706 CFStringRef dsName = SOSDataSourceFactoryCopyName(factory);
707 SOSEngineRef engine = SOSDataSourceFactoryGetEngineForDataSourceName(factory, dsName, NULL);
708 if (engine)
709 SOSEngineCircleChanged(engine, myPeerID, trustedPeerIDs, untrustedPeerIDs);
710 CFReleaseSafe(dsName);
711 }
712
713 // Fire up the SOSEngines so they can
714 static bool SOSDataSourceFactoryStartYourEngines(SOSDataSourceFactoryRef factory) {
715 bool ok = true;
716 CFStringRef dsName = SOSDataSourceFactoryCopyName(factory);
717 CFErrorRef localError = NULL;
718 SOSDataSourceRef ds = SOSDataSourceFactoryCreateDataSource(factory, dsName, &localError);
719 if (!ds)
720 secerror("create_datasource %@ failed %@", dsName, localError);
721 CFReleaseNull(localError);
722 SOSDataSourceRelease(ds, &localError);
723 CFReleaseNull(localError);
724 CFReleaseNull(dsName);
725 return ok;
726 }
727
728 static SOSDataSourceFactoryRef SecItemDataSourceFactoryCreate(SecDbRef db) {
729 struct SecItemDataSourceFactory *dsf = calloc(1, sizeof(struct SecItemDataSourceFactory));
730 dsf->factory.copy_name = SecItemDataSourceFactoryCopyName;
731 dsf->factory.create_datasource = SecItemDataSourceFactoryCopyDataSource;
732 dsf->factory.release = SecItemDataSourceFactoryDispose;
733 dsf->factory.circle_changed = SecItemDataSourceFactoryCircleChanged;
734
735 dsf->dsCache = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, NULL);
736 dsf->queue = dispatch_queue_create("dsf queue", DISPATCH_QUEUE_SERIAL);
737 dsf->db = CFRetainSafe(db);
738 if (!SOSDataSourceFactoryStartYourEngines(&dsf->factory))
739 secerror("Failed to start engines, gonna lose the race.");
740 return &dsf->factory;
741 }
742
743 SOSDataSourceFactoryRef SecItemDataSourceFactoryGetShared(SecDbRef db) {
744 static dispatch_once_t sDSFQueueOnce;
745 static dispatch_queue_t sDSFQueue;
746 static CFMutableDictionaryRef sDSTable = NULL;
747
748 dispatch_once(&sDSFQueueOnce, ^{
749 sDSFQueue = dispatch_queue_create("dataSourceFactory queue", DISPATCH_QUEUE_SERIAL);
750 });
751
752 __block SOSDataSourceFactoryRef result = NULL;
753 dispatch_sync(sDSFQueue, ^{
754 CFStringRef dbPath = SecDbGetPath(db);
755 if (sDSTable) {
756 result = (SOSDataSourceFactoryRef) CFDictionaryGetValue(sDSTable, dbPath);
757 } else {
758 sDSTable = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, NULL);
759 }
760
761 if (!result) {
762 result = SecItemDataSourceFactoryCreate(db);
763
764 CFDictionaryAddValue(sDSTable, dbPath, result);
765 }
766 });
767
768 return result;
769 }
770
771 // TODO: These should move to SecItemServer.c
772
773 void SecItemServerAppendItemDescription(CFMutableStringRef desc, CFDictionaryRef object) {
774 SOSObjectRef item = objectCreateWithPropertyList(object, NULL);
775 if (item) {
776 CFStringRef itemDesc = CFCopyDescription(item);
777 if (itemDesc) {
778 CFStringAppend(desc, itemDesc);
779 CFReleaseSafe(itemDesc);
780 }
781 CFRelease(item);
782 }
783 }
784
785 SOSManifestRef SOSCreateManifestWithBackup(CFDictionaryRef backup, CFErrorRef *error)
786 {
787 __block struct SOSDigestVector dv = SOSDigestVectorInit;
788 if (backup) {
789 CFDictionaryForEach(backup, ^void (const void * key, const void * value) {
790 if (isDictionary(value)) {
791 /* converting key back to binary blob is horrible */
792 CFDataRef sha1 = CFDictionaryGetValue(value, kSecItemBackupHashKey);
793 if (isData(sha1) && CFDataGetLength(sha1) == CCSHA1_OUTPUT_SIZE)
794 SOSDigestVectorAppend(&dv, CFDataGetBytePtr(sha1));
795 }
796 });
797 }
798 SOSManifestRef manifest = SOSManifestCreateWithDigestVector(&dv, error);
799 SOSDigestVectorFree(&dv);
800 return manifest;
801 }