]> git.saurik.com Git - apple/security.git/blob - OSX/sec/securityd/SecDbItem.c
Security-57740.1.18.tar.gz
[apple/security.git] / OSX / sec / securityd / SecDbItem.c
1 /*
2 * Copyright (c) 2012-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 * SecDbItem.c - CoreFoundation-based constants and functions representing
26 * database items (certificates, keys, identities, and passwords.)
27 */
28
29 #include <securityd/SecDbItem.h>
30 #include <securityd/SecDbKeychainItem.h>
31 #include <securityd/SecItemDb.h>
32 #include <utilities/SecCFWrappers.h>
33 #include <utilities/SecCFCCWrappers.h>
34 #include <utilities/der_date.h>
35 #include <utilities/der_plist.h>
36 #include <utilities/debugging.h>
37
38 #include <Security/SecBasePriv.h>
39 #include <Security/SecInternal.h>
40 #include <corecrypto/ccsha1.h>
41 #include <Security/SecItem.h>
42 #include <Security/SecItemPriv.h>
43 #include <Security/SecAccessControl.h>
44 #include <Security/SecAccessControlPriv.h>
45 #include <securityd/SecItemSchema.h>
46
47 // MARK: type converters
48
49 CFStringRef copyString(CFTypeRef obj) {
50 CFTypeID tid = CFGetTypeID(obj);
51 if (tid == CFStringGetTypeID())
52 return CFStringCreateCopy(0, obj);
53 else if (tid == CFDataGetTypeID())
54 return CFStringCreateFromExternalRepresentation(0, obj, kCFStringEncodingUTF8);
55 else
56 return NULL;
57 }
58
59 CFDataRef copyData(CFTypeRef obj) {
60 CFTypeID tid = CFGetTypeID(obj);
61 if (tid == CFDataGetTypeID()) {
62 return CFDataCreateCopy(0, obj);
63 } else if (tid == CFStringGetTypeID()) {
64 return CFStringCreateExternalRepresentation(0, obj, kCFStringEncodingUTF8, 0);
65 } else if (tid == CFNumberGetTypeID()) {
66 SInt32 value;
67 CFNumberGetValue(obj, kCFNumberSInt32Type, &value);
68 return CFDataCreate(0, (const UInt8 *)&value, sizeof(value));
69 } else {
70 return NULL;
71 }
72 }
73
74 CFTypeRef copyUUID(CFTypeRef obj) {
75 CFTypeID tid = CFGetTypeID(obj);
76 if (tid == CFDataGetTypeID()) {
77 CFIndex length = CFDataGetLength(obj);
78 if (length != 0 && length != 16)
79 return NULL;
80 return CFDataCreateCopy(NULL, obj);
81 } if (tid == CFNullGetTypeID()) {
82 return CFDataCreate(NULL, NULL, 0);
83 } else {
84 return NULL;
85 }
86 }
87
88
89 CFTypeRef copyBlob(CFTypeRef obj) {
90 CFTypeID tid = CFGetTypeID(obj);
91 if (tid == CFDataGetTypeID()) {
92 return CFDataCreateCopy(0, obj);
93 } else if (tid == CFStringGetTypeID()) {
94 return CFStringCreateCopy(0, obj);
95 } else if (tid == CFNumberGetTypeID()) {
96 CFRetain(obj);
97 return obj;
98 } else {
99 return NULL;
100 }
101 }
102
103 CFDataRef copySHA1(CFTypeRef obj) {
104 CFTypeID tid = CFGetTypeID(obj);
105 if (tid == CFDataGetTypeID() && CFDataGetLength(obj) == CCSHA1_OUTPUT_SIZE) {
106 return CFDataCreateCopy(CFGetAllocator(obj), obj);
107 } else {
108 return NULL;
109 }
110 }
111
112 CFTypeRef copyNumber(CFTypeRef obj) {
113 CFTypeID tid = CFGetTypeID(obj);
114 if (tid == CFNumberGetTypeID()) {
115 CFRetain(obj);
116 return obj;
117 } else if (tid == CFBooleanGetTypeID()) {
118 SInt32 value = CFBooleanGetValue(obj);
119 return CFNumberCreate(0, kCFNumberSInt32Type, &value);
120 } else if (tid == CFStringGetTypeID()) {
121 SInt32 value = CFStringGetIntValue(obj);
122 CFStringRef t = CFStringCreateWithFormat(0, 0, CFSTR("%ld"), (long) value);
123 /* If a string converted to an int isn't equal to the int printed as
124 a string, return a CFStringRef instead. */
125 if (!CFEqual(t, obj)) {
126 CFRelease(t);
127 return CFStringCreateCopy(0, obj);
128 }
129 CFRelease(t);
130 return CFNumberCreate(0, kCFNumberSInt32Type, &value);
131 } else
132 return NULL;
133 }
134
135 CFDateRef copyDate(CFTypeRef obj) {
136 CFTypeID tid = CFGetTypeID(obj);
137 if (tid == CFDateGetTypeID()) {
138 CFRetain(obj);
139 return obj;
140 } else
141 return NULL;
142 }
143
144 // MARK: SecDbColumn accessors, to retrieve values as CF types in SecDbStep.
145
146 static CFDataRef SecDbColumnCopyData(CFAllocatorRef allocator, sqlite3_stmt *stmt, int col, CFErrorRef *error) {
147 return CFDataCreate(allocator, sqlite3_column_blob(stmt, col),
148 sqlite3_column_bytes(stmt, col));
149 //return CFDataCreateWithBytesNoCopy(0, sqlite3_column_blob(stmt, col),
150 // sqlite3_column_bytes(stmt, col),
151 // kCFAllocatorNull);
152 }
153
154 static CFDateRef SecDbColumnCopyDate(CFAllocatorRef allocator, sqlite3_stmt *stmt, int col, CFErrorRef *error) {
155 return CFDateCreate(allocator, sqlite3_column_double(stmt, col));
156 }
157
158 static CFNumberRef SecDbColumnCopyDouble(CFAllocatorRef allocator, sqlite3_stmt *stmt, int col, CFErrorRef *error) {
159 double number = sqlite3_column_double(stmt, col);
160 return CFNumberCreate(allocator, kCFNumberDoubleType, &number);
161 }
162
163 static CFNumberRef SecDbColumnCopyNumber64(CFAllocatorRef allocator, sqlite3_stmt *stmt, int col, CFErrorRef *error) {
164 sqlite_int64 number = sqlite3_column_int64(stmt, col);
165 return CFNumberCreate(allocator, kCFNumberSInt64Type, &number);
166 }
167
168 static CFNumberRef SecDbColumnCopyNumber(CFAllocatorRef allocator, sqlite3_stmt *stmt, int col, CFErrorRef *error) {
169 sqlite_int64 number = sqlite3_column_int64(stmt, col);
170 if (INT32_MIN <= number && number <= INT32_MAX) {
171 int32_t num32 = (int32_t)number;
172 return CFNumberCreate(allocator, kCFNumberSInt32Type, &num32);
173 } else {
174 return CFNumberCreate(allocator, kCFNumberSInt64Type, &number);
175 }
176 }
177
178 static CFTypeRef SecDbColumnCopyString(CFAllocatorRef allocator, sqlite3_stmt *stmt, int col, CFErrorRef *error,
179 CFOptionFlags flags) {
180 const unsigned char *text = sqlite3_column_text(stmt, col);
181 if (!text || 0 == strlen((const char *)text)) {
182 if (flags & kSecDbDefaultEmptyFlag) {
183 return CFSTR("");
184 } else if (flags & kSecDbDefault0Flag) {
185 return CFSTR("0");
186 } else {
187 return kCFNull;
188 }
189 }
190 return CFStringCreateWithBytes(allocator, text, strlen((const char *)text), kCFStringEncodingUTF8, false);
191 }
192
193 // MARK: SecDbClass helpers
194
195 const SecDbAttr *SecDbClassAttrWithKind(const SecDbClass *class, SecDbAttrKind kind, CFErrorRef *error) {
196 const SecDbAttr *result = NULL;
197 SecDbForEachAttr(class, desc) {
198 if (desc->kind == kind)
199 result = desc;
200 }
201
202 if (!result)
203 SecError(errSecInternal, error, CFSTR("Can't find attribute of kind %d in class %@"), kind, class->name);
204
205 return result;
206 }
207
208 // MARK: SecDbAttr helpers
209
210 static bool SecDbIsTombstoneDbSelectAttr(const SecDbAttr *attr) {
211 return attr->flags & kSecDbPrimaryKeyFlag || attr->kind == kSecDbTombAttr;
212 }
213
214 #if 0
215 static bool SecDbIsTombstoneDbInsertAttr(const SecDbAttr *attr) {
216 return SecDbIsTombstoneDbSelectAttr(attr) || attr->kind == kSecDbAccessAttr || attr->kind == kSecDbCreationDateAttr || attr->kind == kSecDbModificationDateAttr;
217 }
218 #endif
219
220 static bool SecDbIsTombstoneDbUpdateAttr(const SecDbAttr *attr) {
221 return SecDbIsTombstoneDbSelectAttr(attr) || attr->kind == kSecDbAccessAttr || attr->kind == kSecDbCreationDateAttr || attr->kind == kSecDbRowIdAttr;
222 }
223
224 CFTypeRef SecDbAttrCopyDefaultValue(const SecDbAttr *attr, CFErrorRef *error) {
225 CFTypeRef value = NULL;
226 switch (attr->kind) {
227 case kSecDbAccessAttr:
228 case kSecDbStringAttr:
229 case kSecDbAccessControlAttr:
230 value = CFSTR("");
231 break;
232 case kSecDbBlobAttr:
233 case kSecDbDataAttr:
234 value = CFDataCreate(kCFAllocatorDefault, NULL, 0);
235 break;
236 case kSecDbUUIDAttr:
237 value = CFDataCreate(kCFAllocatorDefault, NULL, 0);
238 break;
239 case kSecDbNumberAttr:
240 case kSecDbSyncAttr:
241 case kSecDbTombAttr:
242 {
243 int32_t zero = 0;
244 value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &zero);
245 break;
246 }
247 case kSecDbDateAttr:
248 value = CFDateCreate(kCFAllocatorDefault, 0.0);
249 break;
250 case kSecDbCreationDateAttr:
251 case kSecDbModificationDateAttr:
252 value = CFDateCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent());
253 break;
254 default:
255 SecError(errSecInternal, error, CFSTR("attr %@ has no default value"), attr->name);
256 value = NULL;
257 }
258
259 return value;
260 }
261
262 static CFTypeRef SecDbAttrCopyValueForDb(const SecDbAttr *attr, CFTypeRef value, CFErrorRef *error) {
263 CFDataRef data = NULL;
264 CFTypeRef result = NULL;
265
266 if (value == NULL)
267 value = kCFNull;
268
269 if (CFEqual(value, kCFNull) && attr->flags & kSecDbPrimaryKeyFlag) {
270 // SQLITE3 doesn't like NULL for primary key attributes, pretend kSecDbDefaultEmptyFlag was specified
271 require_quiet(result = SecDbAttrCopyDefaultValue(attr, error), out);
272 } else {
273 result = CFRetain(value);
274 }
275
276 if (attr->flags & kSecDbSHA1ValueInFlag && !CFEqual(result, kCFNull)) {
277 require_action_quiet(data = copyData(result), out,
278 SecError(errSecInternal, error, CFSTR("failed to get attribute %@ data"), attr->name);
279 CFReleaseNull(result));
280 CFAssignRetained(result, CFDataCopySHA1Digest(data, error));
281 }
282
283 out:
284 CFReleaseSafe(data);
285 return result;
286 }
287
288 static CFStringRef SecDbAttrGetHashName(const SecDbAttr *attr) {
289 if ((attr->flags & kSecDbSHA1ValueInFlag) == 0) {
290 return attr->name;
291 }
292
293 static dispatch_once_t once;
294 static CFMutableDictionaryRef hash_store;
295 static dispatch_queue_t queue;
296 dispatch_once(&once, ^{
297 queue = dispatch_queue_create("secd-hash-name", NULL);
298 hash_store = CFDictionaryCreateMutableForCFTypes(NULL);
299 });
300
301 __block CFStringRef name;
302 dispatch_sync(queue, ^{
303 name = CFDictionaryGetValue(hash_store, attr->name);
304 if (name == NULL) {
305 name = CFStringCreateWithFormat(NULL, NULL, CFSTR("#%@"), attr->name);
306 CFDictionarySetValue(hash_store, attr->name, name);
307 CFRelease(name);
308 }
309 });
310 return name;
311 }
312
313 // MARK: SecDbItem
314
315 CFTypeRef SecDbItemGetCachedValueWithName(SecDbItemRef item, CFStringRef name) {
316 return CFDictionaryGetValue(item->attributes, name);
317 }
318
319 static CFTypeRef SecDbItemGetCachedValue(SecDbItemRef item, const SecDbAttr *desc) {
320 return CFDictionaryGetValue(item->attributes, desc->name);
321 }
322
323 CFMutableDictionaryRef SecDbItemCopyPListWithMask(SecDbItemRef item, CFOptionFlags mask, CFErrorRef *error) {
324 CFMutableDictionaryRef dict = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
325 SecDbForEachAttrWithMask(item->class, desc, mask) {
326 CFTypeRef value = SecDbItemGetValue(item, desc, error);
327 if (value) {
328 if (!CFEqual(kCFNull, value)) {
329 CFDictionarySetValue(dict, desc->name, value);
330 } else if (desc->flags & kSecDbNotNullFlag) {
331 SecError(errSecDecode, error, CFSTR("attribute %@ has NULL value"), desc->name);
332 secerror("%@", error ? *error : (CFErrorRef)CFSTR("error == NULL"));
333 CFReleaseNull(dict);
334 break;
335 }
336 } else {
337 CFReleaseNull(dict);
338 break;
339 }
340 }
341 return dict;
342 }
343
344 void SecDbItemSetCredHandle(SecDbItemRef item, CFTypeRef cred_handle) {
345 CFRetainAssign(item->credHandle, cred_handle);
346 }
347
348 void SecDbItemSetCallerAccessGroups(SecDbItemRef item, CFArrayRef caller_access_groups) {
349 CFRetainAssign(item->callerAccessGroups, caller_access_groups);
350 }
351
352 CFDataRef SecDbItemCopyEncryptedDataToBackup(SecDbItemRef item, uint64_t handle, CFErrorRef *error) {
353 CFDataRef edata = NULL;
354 keybag_handle_t keybag = (keybag_handle_t)handle;
355 CFMutableDictionaryRef attributes = SecDbItemCopyPListWithMask(item, kSecDbInCryptoDataFlag, error);
356 CFMutableDictionaryRef auth_attributes = SecDbItemCopyPListWithMask(item, kSecDbInAuthenticatedDataFlag, error);
357 if (attributes || auth_attributes) {
358 SecAccessControlRef access_control = SecDbItemCopyAccessControl(item, error);
359 if (access_control) {
360 if (ks_encrypt_data(keybag, access_control, item->credHandle, attributes, auth_attributes, &edata, false, error)) {
361 item->_edataState = kSecDbItemEncrypting;
362 } else {
363 seccritical("ks_encrypt_data (db): failed: %@", error ? *error : (CFErrorRef)CFSTR(""));
364 }
365 CFRelease(access_control);
366 }
367 CFReleaseSafe(attributes);
368 CFReleaseSafe(auth_attributes);
369 }
370 return edata;
371 }
372
373 bool SecDbItemEnsureDecrypted(SecDbItemRef item, CFErrorRef *error) {
374
375 // If we haven't yet decrypted the item, make sure we do so now
376 bool result = true;
377 if (item->_edataState == kSecDbItemEncrypted) {
378 const SecDbAttr *attr = SecDbClassAttrWithKind(item->class, kSecDbEncryptedDataAttr, error);
379 if (attr) {
380 CFDataRef edata = SecDbItemGetCachedValue(item, attr);
381 if (!edata)
382 return SecError(errSecInternal, error, CFSTR("state= encrypted but edata is NULL"));
383 // Decrypt calls set value a bunch of times which clears our edata and changes our state.
384 item->_edataState = kSecDbItemDecrypting;
385 result = SecDbItemDecrypt(item, edata, error);
386 if (result)
387 item->_edataState = kSecDbItemClean;
388 else
389 item->_edataState = kSecDbItemEncrypted;
390 }
391 }
392 return result;
393 }
394
395 // Only called if cached value is not found.
396 static CFTypeRef SecDbItemCopyValue(SecDbItemRef item, const SecDbAttr *attr, CFErrorRef *error) {
397 if (attr->copyValue)
398 return attr->copyValue(item, attr, error);
399
400 CFTypeRef value = NULL;
401 switch (attr->kind) {
402 // These have an explicit copyValue; here to shut up compiler
403 case kSecDbSHA1Attr:
404 case kSecDbEncryptedDataAttr:
405 case kSecDbPrimaryKeyAttr:
406 value = NULL;
407 break;
408 case kSecDbAccessAttr:
409 case kSecDbStringAttr:
410 case kSecDbBlobAttr:
411 case kSecDbAccessControlAttr:
412 if (attr->flags & kSecDbNotNullFlag) {
413 if (attr->flags & kSecDbDefault0Flag) {
414 value = CFSTR("0");
415 break;
416 } else if (attr->kind != kSecDbBlobAttr && attr->flags & kSecDbDefaultEmptyFlag) {
417 // blob drops through to data everything else is empty string
418 value = CFSTR("");
419 break;
420 }
421 }
422 //DROPTHROUGH
423 case kSecDbDataAttr:
424 if (attr->flags & kSecDbNotNullFlag && attr->flags & kSecDbDefaultEmptyFlag) {
425 value = CFDataCreate(CFGetAllocator(item), NULL, 0);
426 } else {
427 value = kCFNull;
428 }
429 break;
430 case kSecDbUUIDAttr:
431 value = CFDataCreate(CFGetAllocator(item), NULL, 0);
432 break;
433 case kSecDbNumberAttr:
434 case kSecDbSyncAttr:
435 case kSecDbTombAttr:
436 if (attr->flags & kSecDbNotNullFlag) {
437 int32_t zero = 0;
438 value = CFNumberCreate(CFGetAllocator(item), kCFNumberSInt32Type, &zero);
439 } else {
440 value = kCFNull;
441 }
442 break;
443 case kSecDbDateAttr:
444 if (attr->flags & kSecDbNotNullFlag && attr->flags & kSecDbDefault0Flag) {
445 value = CFDateCreate(kCFAllocatorDefault, 0.0);
446 } else {
447 value = kCFNull;
448 }
449 break;
450 case kSecDbRowIdAttr:
451 if (attr->flags & kSecDbNotNullFlag) {
452 // No can do, error?
453 }
454 value = kCFNull;
455 break;
456 case kSecDbCreationDateAttr:
457 case kSecDbModificationDateAttr:
458 value = CFDateCreate(CFGetAllocator(item), CFAbsoluteTimeGetCurrent());
459 break;
460 case kSecDbUTombAttr:
461 value = kCFNull;
462 break;
463 }
464
465 return value;
466 }
467
468 // SecDbItemGetValue will return kCFNull if there is no value for an attribute and this was not
469 // an error. It will return NULL and optionally set *error if there was an error computing an
470 // attribute, or if a required attribute was missing a value and had no known way to compute
471 // it's value.
472 CFTypeRef SecDbItemGetValue(SecDbItemRef item, const SecDbAttr *desc, CFErrorRef *error) {
473 // Propagate chained errors
474 if (!desc)
475 return NULL;
476
477 if (desc->flags & kSecDbInCryptoDataFlag || desc->flags & kSecDbInAuthenticatedDataFlag) {
478 if (!SecDbItemEnsureDecrypted(item, error))
479 return NULL;
480 }
481
482 CFTypeRef value = SecDbItemGetCachedValue(item, desc);
483 if (!value) {
484 value = SecDbItemCopyValue(item, desc, error);
485 if (value) {
486 if (CFEqual(kCFNull, value)) {
487 CFRelease(value); // This is redundant but it shuts clang's static analyzer up.
488 value = kCFNull;
489 } else {
490 SecDbItemSetValue(item, desc, value, error);
491 CFRelease(value);
492 value = SecDbItemGetCachedValue(item, desc);
493 }
494 }
495 }
496 return value;
497 }
498
499 // Similar as SecDbItemGetValue, but if attr represents attribute stored into DB field as hash, returns
500 // hashed value for the attribute.
501 static CFTypeRef SecDbItemCopyValueForDb(SecDbItemRef item, const SecDbAttr *desc, CFErrorRef *error) {
502 CFTypeRef value = NULL;
503 CFStringRef hash_name = NULL;
504 hash_name = SecDbAttrGetHashName(desc);
505 if ((desc->flags & kSecDbSHA1ValueInFlag) && (desc->flags & kSecDbInFlag)) {
506 value = CFRetainSafe(CFDictionaryGetValue(item->attributes, hash_name));
507 }
508
509 if (value == NULL) {
510 require_quiet(value = SecDbItemGetValue(item, desc, error), out);
511 require_action_quiet(value = SecDbAttrCopyValueForDb(desc, value, error), out, CFReleaseNull(value));
512 if ((desc->flags & kSecDbSHA1ValueInFlag) != 0) {
513 CFDictionarySetValue(item->attributes, hash_name, value);
514 }
515 }
516
517 out:
518 return value;
519 }
520
521 static bool SecDbItemGetBoolValue(SecDbItemRef item, const SecDbAttr *desc, bool *bvalue, CFErrorRef *error) {
522 CFTypeRef value = SecDbItemGetValue(item, desc, error);
523 if (!value)
524 return false;
525 char cvalue;
526 *bvalue = (isNumber(value) && CFNumberGetValue(value, kCFNumberCharType, &cvalue) && cvalue == 1);
527 return true;
528 }
529
530 static CFStringRef SecDbItemCopyFormatDescription(CFTypeRef cf, CFDictionaryRef formatOptions) {
531 CFStringRef desc;
532 if (isDictionary(formatOptions) && CFDictionaryContainsKey(formatOptions, kSecDebugFormatOption)) {
533 SecDbItemRef item = (SecDbItemRef)cf;
534 CFMutableStringRef mdesc = CFStringCreateMutable(CFGetAllocator(cf), 0);
535 CFStringAppendFormat(mdesc, NULL, CFSTR("<%@"), item->class->name);
536 SecDbForEachAttr(item->class, attr) {
537 CFTypeRef value = SecDbItemGetValue(item, attr, NULL);
538 if (value) {
539 CFStringAppend(mdesc, CFSTR(","));
540 CFStringAppend(mdesc, attr->name);
541 CFStringAppend(mdesc, CFSTR("="));
542 if (CFEqual(CFSTR("data"), attr->name)) {
543 CFStringAppendEncryptedData(mdesc, value);
544 } else if (CFEqual(CFSTR("v_Data"), attr->name)) {
545 CFStringAppend(mdesc, CFSTR("<?>"));
546 } else if (isData(value)) {
547 CFStringAppendHexData(mdesc, value);
548 } else {
549 CFStringAppendFormat(mdesc, 0, CFSTR("%@"), value);
550 }
551 }
552 }
553 CFStringAppend(mdesc, CFSTR(">"));
554 desc = mdesc;
555 } else {
556 SecDbItemRef item = (SecDbItemRef)cf;
557 const UInt8 zero4[4] = {};
558 const UInt8 *pk = &zero4[0], *sha1 = &zero4[0];
559 char sync = 0;
560 char tomb = 0;
561 SInt64 rowid = 0;
562 CFStringRef access = NULL;
563 uint8_t mdatbuf[32] = {};
564 uint8_t *mdat = &mdatbuf[0];
565 CFMutableStringRef attrs = CFStringCreateMutable(kCFAllocatorDefault, 0);
566 CFStringRef agrp = NULL;
567 CFBooleanRef utomb = NULL;
568
569 SecDbForEachAttr(item->class, attr) {
570 CFTypeRef value;
571 switch (attr->kind) {
572 case kSecDbBlobAttr:
573 case kSecDbDataAttr:
574 case kSecDbStringAttr:
575 case kSecDbNumberAttr:
576 case kSecDbDateAttr:
577 case kSecDbEncryptedDataAttr:
578 if (attr->flags & (kSecDbReturnAttrFlag | kSecDbReturnDataFlag) && (value = SecDbItemGetValue(item, attr, NULL)) && !CFEqual(value, kCFNull)) {
579 if (isString(value) && CFEqual(attr->name, kSecAttrAccessGroup)) {
580 agrp = value;
581 } else {
582 // We don't log these, just record that we saw the attribute.
583 CFStringAppend(attrs, CFSTR(","));
584 CFStringAppend(attrs, attr->name);
585 }
586 }
587 break;
588 case kSecDbUUIDAttr:
589 if ((value = SecDbItemGetValue(item, attr, NULL))) {
590 if (CFEqual(attr->name, kSecAttrMultiUser)) {
591 if (isData(value)) {
592 CFStringAppend(attrs, CFSTR(","));
593 if (CFDataGetLength(value)) {
594 CFStringAppendHexData(attrs, value);
595 } else {
596 CFStringAppend(attrs, attr->name);
597 }
598 }
599 }
600 }
601 break;
602 case kSecDbCreationDateAttr:
603 // We don't care about this and every object has one.
604 break;
605 case kSecDbModificationDateAttr:
606 value = SecDbItemGetValue(item, attr, NULL);
607 if (isDate(value))
608 mdat = der_encode_generalizedtime_body(CFDateGetAbsoluteTime(value), NULL, mdat, &mdatbuf[31]);
609 break;
610 case kSecDbSHA1Attr:
611 value = SecDbItemGetValue(item, attr, NULL);
612 if (isData(value) && CFDataGetLength(value) >= (CFIndex)sizeof(zero4))
613 sha1 = CFDataGetBytePtr(value);
614 break;
615 case kSecDbRowIdAttr:
616 value = SecDbItemGetValue(item, attr, NULL);
617 if (isNumber(value))
618 CFNumberGetValue(value, kCFNumberSInt64Type, &rowid);
619 break;
620 case kSecDbPrimaryKeyAttr:
621 value = SecDbItemGetValue(item, attr, NULL);
622 if (isData(value))
623 pk = CFDataGetBytePtr(value);
624 break;
625 case kSecDbSyncAttr:
626 value = SecDbItemGetValue(item, attr, NULL);
627 if (isNumber(value))
628 CFNumberGetValue(value, kCFNumberCharType, &sync);
629 break;
630 case kSecDbTombAttr:
631 value = SecDbItemGetValue(item, attr, NULL);
632 if (isNumber(value))
633 CFNumberGetValue(value, kCFNumberCharType, &tomb);
634 break;
635 case kSecDbAccessAttr:
636 value = SecDbItemGetValue(item, attr, NULL);
637 if (isString(value))
638 access = value;
639 break;
640 case kSecDbUTombAttr:
641 value = SecDbItemGetValue(item, attr, NULL);
642 if (isBoolean(value))
643 utomb = value;
644 case kSecDbAccessControlAttr:
645 /* TODO: Add formatting of ACLs. */
646 break;
647 }
648 }
649
650 desc = CFStringCreateWithFormat(CFGetAllocator(cf), NULL,
651 CFSTR(
652 "%s,"
653 "%@,"
654 "%02X%02X%02X%02X,"
655 "%s,"
656 "%@,"
657 "%@,"
658 "%"PRId64
659 "%@,"
660 "%s,"
661 "%s"
662 "%02X%02X%02X%02X"),
663 tomb ? "T" : "O",
664 item->class->name,
665 pk[0], pk[1], pk[2], pk[3],
666 sync ? "S" : "L",
667 access,
668 agrp,
669 rowid,
670 attrs,
671 mdat,
672 utomb ? (CFEqual(utomb, kCFBooleanFalse) ? "F," : "T,") : "",
673 sha1[0], sha1[1], sha1[2], sha1[3]);
674 CFReleaseSafe(attrs);
675 }
676
677 return desc;
678 }
679
680 static void SecDbItemDestroy(CFTypeRef cf) {
681 SecDbItemRef item = (SecDbItemRef)cf;
682 CFReleaseSafe(item->attributes);
683 CFReleaseSafe(item->credHandle);
684 CFReleaseSafe(item->callerAccessGroups);
685 CFReleaseSafe(item->cryptoOp);
686 }
687
688 static CFHashCode SecDbItemHash(CFTypeRef cf) {
689 SecDbItemRef item = (SecDbItemRef)cf;
690 CFDataRef digest = SecDbItemGetSHA1(item, NULL);
691 CFHashCode code;
692 const UInt8 *p = CFDataGetBytePtr(digest);
693 // Read first 8 bytes of digest in order
694 code = p[0] + ((p[1] + ((p[2] + ((p[3] + ((p[4] + ((p[5] + ((p[6] + (p[7] << 8)) << 8)) << 8)) << 8)) << 8)) << 8)) << 8);
695 return code;
696 }
697
698 static Boolean SecDbItemCompare(CFTypeRef cf1, CFTypeRef cf2) {
699 SecDbItemRef item1 = (SecDbItemRef)cf1;
700 SecDbItemRef item2 = (SecDbItemRef)cf2;
701 CFDataRef digest1 = NULL;
702 CFDataRef digest2 = NULL;
703 if (item1)
704 digest1 = SecDbItemGetSHA1(item1, NULL);
705 if (item2)
706 digest2 = SecDbItemGetSHA1(item2, NULL);
707 Boolean equal = CFEqual(digest1, digest2);
708 return equal;
709 }
710
711 CFGiblisWithHashFor(SecDbItem)
712
713 static SecDbItemRef SecDbItemCreate(CFAllocatorRef allocator, const SecDbClass *class, keybag_handle_t keybag) {
714 SecDbItemRef item = CFTypeAllocate(SecDbItem, struct SecDbItem, allocator);
715 item->class = class;
716 item->attributes = CFDictionaryCreateMutableForCFTypes(allocator);
717 item->keybag = keybag;
718 item->_edataState = kSecDbItemDirty;
719 item->cryptoOp = kAKSKeyOpDecrypt;
720 return item;
721 }
722
723 const SecDbClass *SecDbItemGetClass(SecDbItemRef item) {
724 return item->class;
725 }
726
727 keybag_handle_t SecDbItemGetKeybag(SecDbItemRef item) {
728 return item->keybag;
729 }
730
731 bool SecDbItemSetKeybag(SecDbItemRef item, keybag_handle_t keybag, CFErrorRef *error) {
732 if (!SecDbItemEnsureDecrypted(item, error))
733 return false;
734 if (item->keybag != keybag) {
735 item->keybag = keybag;
736 if (item->_edataState == kSecDbItemClean) {
737 SecDbItemSetValue(item, SecDbClassAttrWithKind(item->class, kSecDbEncryptedDataAttr, NULL), kCFNull, NULL);
738 }
739 }
740
741 return true;
742 }
743
744 bool SecDbItemSetValue(SecDbItemRef item, const SecDbAttr *desc, CFTypeRef value, CFErrorRef *error) {
745 // Propagate chained errors.
746 if (!desc)
747 return false;
748
749 if (!value)
750 value = kCFNull;
751
752 if (desc->setValue)
753 return desc->setValue(item, desc, value, error);
754
755 if (desc->flags & kSecDbInCryptoDataFlag || desc->flags & kSecDbInAuthenticatedDataFlag)
756 if (!SecDbItemEnsureDecrypted(item, error))
757 return false;
758
759 bool changed = false;
760 CFTypeRef attr = NULL;
761 switch (desc->kind) {
762 case kSecDbPrimaryKeyAttr:
763 case kSecDbDataAttr:
764 attr = copyData(value);
765 break;
766 case kSecDbEncryptedDataAttr:
767 attr = copyData(value);
768 if (attr) {
769 if (item->_edataState == kSecDbItemEncrypting)
770 item->_edataState = kSecDbItemClean;
771 else
772 item->_edataState = kSecDbItemEncrypted;
773 } else if (!value || CFEqual(kCFNull, value)) {
774 item->_edataState = kSecDbItemDirty;
775 }
776 break;
777 case kSecDbBlobAttr:
778 case kSecDbAccessControlAttr:
779 attr = copyBlob(value);
780 break;
781 case kSecDbDateAttr:
782 case kSecDbCreationDateAttr:
783 case kSecDbModificationDateAttr:
784 attr = copyDate(value);
785 break;
786 case kSecDbNumberAttr:
787 case kSecDbSyncAttr:
788 case kSecDbTombAttr:
789 case kSecDbRowIdAttr:
790 attr = copyNumber(value);
791 break;
792 case kSecDbAccessAttr:
793 case kSecDbStringAttr:
794 attr = copyString(value);
795 break;
796 case kSecDbSHA1Attr:
797 attr = copySHA1(value);
798 break;
799 case kSecDbUTombAttr:
800 attr = CFRetainSafe(asBoolean(value, NULL));
801 break;
802 case kSecDbUUIDAttr:
803 attr = copyUUID(value);
804 break;
805 }
806
807 if (attr) {
808 CFTypeRef ovalue = CFDictionaryGetValue(item->attributes, desc->name);
809 changed = (!ovalue || !CFEqual(ovalue, attr));
810 CFDictionarySetValue(item->attributes, desc->name, attr);
811 CFRelease(attr);
812 } else {
813 if (value && !CFEqual(kCFNull, value)) {
814 SecError(errSecItemInvalidValue, error, CFSTR("attribute %@: value: %@ failed to convert"), desc->name, value);
815 return false;
816 }
817 CFTypeRef ovalue = CFDictionaryGetValue(item->attributes, desc->name);
818 changed = (ovalue && !CFEqual(ovalue, kCFNull));
819 CFDictionaryRemoveValue(item->attributes, desc->name);
820 }
821
822 if (changed) {
823 if (desc->flags & kSecDbInHashFlag)
824 SecDbItemSetValue(item, SecDbClassAttrWithKind(item->class, kSecDbSHA1Attr, NULL), kCFNull, NULL);
825 if (desc->flags & kSecDbPrimaryKeyFlag)
826 SecDbItemSetValue(item, SecDbClassAttrWithKind(item->class, kSecDbPrimaryKeyAttr, NULL), kCFNull, NULL);
827 if ((desc->flags & kSecDbInCryptoDataFlag || desc->flags & kSecDbInAuthenticatedDataFlag) && item->_edataState == kSecDbItemClean)
828 SecDbItemSetValue(item, SecDbClassAttrWithKind(item->class, kSecDbEncryptedDataAttr, NULL), kCFNull, NULL);
829 if (desc->flags & kSecDbSHA1ValueInFlag)
830 CFDictionaryRemoveValue(item->attributes, SecDbAttrGetHashName(desc));
831 }
832
833 return true;
834 }
835
836 bool SecDbItemSetValues(SecDbItemRef item, CFDictionaryRef values, CFErrorRef *error) {
837 SecDbForEachAttr(item->class, attr) {
838 CFTypeRef value = CFDictionaryGetValue(values, attr->name);
839 if (value && !SecDbItemSetValue(item, attr, value, error))
840 return false;
841 }
842 return true;
843 }
844
845 bool SecDbItemSetValueWithName(SecDbItemRef item, CFStringRef name, CFTypeRef value, CFErrorRef *error) {
846 SecDbForEachAttr(item->class, attr) {
847 if (CFEqual(attr->name, name)) {
848 return SecDbItemSetValue(item, attr, value, error);
849 }
850 }
851 return false;
852 }
853
854 bool SecDbItemSetAccessControl(SecDbItemRef item, SecAccessControlRef access_control, CFErrorRef *error) {
855 bool ok = true;
856 if (item->_edataState == kSecDbItemClean)
857 ok = SecDbItemSetValue(item, SecDbClassAttrWithKind(item->class, kSecDbEncryptedDataAttr, error), kCFNull, error);
858 if (ok && access_control) { //added check for access_control because ks_decrypt_data can leave NULL in access_control in case of error
859 item->_edataState = kSecDbItemDirty;
860 CFDataRef data = SecAccessControlCopyData(access_control);
861 ok = SecDbItemSetValue(item, SecDbClassAttrWithKind(item->class, kSecDbAccessControlAttr, error), data, error);
862 CFRelease(data);
863 }
864 return ok;
865 }
866
867 SecDbItemRef SecDbItemCreateWithAttributes(CFAllocatorRef allocator, const SecDbClass *class, CFDictionaryRef attributes, keybag_handle_t keybag, CFErrorRef *error) {
868 SecDbItemRef item = SecDbItemCreate(kCFAllocatorDefault, class, keybag);
869 if (item && !SecDbItemSetValues(item, attributes, error))
870 CFReleaseNull(item);
871 return item;
872 }
873
874 static CFTypeRef
875 SecDbColumnCopyValueWithAttr(CFAllocatorRef allocator, sqlite3_stmt *stmt, const SecDbAttr *attr, int col, CFErrorRef *error) {
876 CFTypeRef value = NULL;
877 switch (attr->kind) {
878 case kSecDbDateAttr:
879 case kSecDbCreationDateAttr:
880 case kSecDbModificationDateAttr:
881 value = SecDbColumnCopyDate(allocator, stmt, col, error);
882 break;
883 case kSecDbBlobAttr:
884 case kSecDbNumberAttr:
885 switch (sqlite3_column_type(stmt, col)) {
886 case SQLITE_INTEGER:
887 value = SecDbColumnCopyNumber(allocator, stmt, col, error);
888 break;
889 case SQLITE_FLOAT:
890 value = SecDbColumnCopyDouble(allocator, stmt, col, error);
891 break;
892 case SQLITE_TEXT:
893 value = SecDbColumnCopyString(allocator, stmt, col, error,
894 attr->flags);
895 break;
896 case SQLITE_BLOB:
897 value = SecDbColumnCopyData(allocator, stmt, col, error);
898 break;
899 case SQLITE_NULL:
900 value = kCFNull;
901 break;
902 }
903 break;
904 case kSecDbAccessAttr:
905 case kSecDbStringAttr:
906 value = SecDbColumnCopyString(allocator, stmt, col, error,
907 attr->flags);
908 break;
909 case kSecDbDataAttr:
910 case kSecDbUUIDAttr:
911 case kSecDbSHA1Attr:
912 case kSecDbPrimaryKeyAttr:
913 case kSecDbEncryptedDataAttr:
914 value = SecDbColumnCopyData(allocator, stmt, col, error);
915 break;
916 case kSecDbSyncAttr:
917 case kSecDbTombAttr:
918 value = SecDbColumnCopyNumber(allocator, stmt, col, error);
919 break;
920 case kSecDbRowIdAttr:
921 value = SecDbColumnCopyNumber64(allocator, stmt, col, error);
922 break;
923 case kSecDbAccessControlAttr:
924 case kSecDbUTombAttr:
925 /* This attributes does not have any database column associated, exists only inside encrypted blob as metadata. */
926 break;
927 }
928 return value;
929 }
930
931 SecDbItemRef SecDbItemCreateWithStatement(CFAllocatorRef allocator, const SecDbClass *class, sqlite3_stmt *stmt, keybag_handle_t keybag, CFErrorRef *error, bool (^return_attr)(const SecDbAttr *attr)) {
932 SecDbItemRef item = SecDbItemCreate(allocator, class, keybag);
933 int col = 0;
934 SecDbForEachAttr(class, attr) {
935 if (return_attr(attr)) {
936 CFTypeRef value = SecDbColumnCopyValueWithAttr(allocator, stmt, attr, col++, error);
937 require_action_quiet(value, errOut, CFReleaseNull(item));
938
939 CFDictionarySetValue(item->attributes, SecDbAttrGetHashName(attr), value);
940 CFRelease(value);
941 }
942
943 const SecDbAttr *data_attr = SecDbClassAttrWithKind(class, kSecDbEncryptedDataAttr, NULL);
944 if (data_attr != NULL && CFDictionaryGetValue(item->attributes, data_attr->name) != NULL) {
945 item->_edataState = kSecDbItemEncrypted;
946 }
947 }
948
949 errOut:
950 return item;
951 }
952
953 SecDbItemRef SecDbItemCreateWithEncryptedData(CFAllocatorRef allocator, const SecDbClass *class,
954 CFDataRef edata, keybag_handle_t keybag, CFErrorRef *error) {
955 SecDbItemRef item = SecDbItemCreate(allocator, class, keybag);
956 const SecDbAttr *edata_attr = SecDbClassAttrWithKind(class, kSecDbEncryptedDataAttr, error);
957 if (edata_attr) {
958 if (!SecDbItemSetValue(item, edata_attr, edata, error))
959 CFReleaseNull(item);
960 }
961 return item;
962 }
963
964 // TODO: Hack -- Replace with real filtering
965
966 // Return true iff an item for which SecDbItemIsSyncable() already returns true should be part of the v2 view.
967 bool SecDbItemInV2(SecDbItemRef item) {
968 const SecDbClass *iclass = SecDbItemGetClass(item);
969 return (SecDbItemGetCachedValueWithName(item, kSecAttrSyncViewHint) == NULL &&
970 (iclass == &genp_class || iclass == &inet_class || iclass == &keys_class || iclass == &cert_class));
971 }
972
973 // Return true iff an item for which SecDbItemIsSyncable() and SecDbItemInV2() already return true should be part of the v0 view.
974 bool SecDbItemInV2AlsoInV0(SecDbItemRef item) {
975 return (SecDbItemGetCachedValueWithName(item, kSecAttrTokenID) == NULL && SecDbItemGetClass(item) != &cert_class);
976 }
977
978 SecDbItemRef SecDbItemCopyWithUpdates(SecDbItemRef item, CFDictionaryRef updates, CFErrorRef *error) {
979 SecDbItemRef new_item = SecDbItemCreate(CFGetAllocator(item), item->class, item->keybag);
980 SecDbItemSetCredHandle(new_item, item->credHandle);
981 SecDbForEachAttr(item->class, attr) {
982 // Copy each attribute, except the mod date attribute (it will be reset to now when needed),
983 // from the updates dict unless it's not there in which case we copy the attribute from the passed in item.
984 if (attr->kind != kSecDbModificationDateAttr && attr->kind != kSecDbEncryptedDataAttr && attr->kind != kSecDbSHA1Attr && attr->kind != kSecDbPrimaryKeyAttr) {
985 CFTypeRef value = NULL;
986 if (CFDictionaryGetValueIfPresent(updates, attr->name, &value)) {
987 if (!value)
988 SecError(errSecParam, error, CFSTR("NULL value in dictionary"));
989 } else {
990 value = SecDbItemGetValue(item, attr, error);
991 }
992 if (!value || !SecDbItemSetValue(new_item, attr, value, error)) {
993 CFReleaseNull(new_item);
994 break;
995 }
996 }
997 }
998 return new_item;
999 }
1000
1001 // Ensure that the date value of attr of new_item is greater than that of old_item.
1002 static bool SecDbItemMakeAttrYounger(SecDbItemRef new_item, SecDbItemRef old_item, const SecDbAttr *attr, CFErrorRef *error) {
1003 CFDateRef old_date = SecDbItemGetValue(old_item, attr, error);
1004 if (!old_date)
1005 return false;
1006 CFDateRef new_date = SecDbItemGetValue(new_item, attr, error);
1007 if (!new_date)
1008 return false;
1009 bool ok = true;
1010 if (CFDateCompare(new_date, old_date, NULL) != kCFCompareGreaterThan) {
1011 CFDateRef adjusted_date = CFDateCreate(kCFAllocatorDefault, CFDateGetAbsoluteTime(old_date) + 0.001);
1012 if (adjusted_date) {
1013 ok = SecDbItemSetValue(new_item, attr, adjusted_date, error);
1014 CFRelease(adjusted_date);
1015 }
1016 }
1017 return ok;
1018 }
1019
1020 // Ensure that the mod date of new_item is greater than that of old_item.
1021 static bool SecDbItemMakeYounger(SecDbItemRef new_item, SecDbItemRef old_item, CFErrorRef *error) {
1022 const SecDbAttr *attr = SecDbClassAttrWithKind(new_item->class, kSecDbModificationDateAttr, error);
1023 return attr && SecDbItemMakeAttrYounger(new_item, old_item, attr, error);
1024 }
1025
1026 static SecDbItemRef SecDbItemCopyTombstone(SecDbItemRef item, CFBooleanRef makeTombStone, CFErrorRef *error) {
1027 SecDbItemRef new_item = SecDbItemCreate(CFGetAllocator(item), item->class, item->keybag);
1028 SecDbForEachAttr(item->class, attr) {
1029 if (attr->kind == kSecDbTombAttr) {
1030 // Set the tomb attr to true to indicate a tombstone.
1031 if (!SecDbItemSetValue(new_item, attr, kCFBooleanTrue, error)) {
1032 CFReleaseNull(new_item);
1033 break;
1034 }
1035 } else if (SecDbIsTombstoneDbUpdateAttr(attr)) {
1036 // Copy all primary key attributes and creation timestamps from the original item.
1037 CFTypeRef value = SecDbItemGetValue(item, attr, error);
1038 if (!value || (!CFEqual(kCFNull, value) && !SecDbItemSetValue(new_item, attr, value, error))) {
1039 CFReleaseNull(new_item);
1040 break;
1041 }
1042 } else if (attr->kind == kSecDbModificationDateAttr) {
1043 if (!SecDbItemMakeAttrYounger(new_item, item, attr, error)) {
1044 CFReleaseNull(new_item);
1045 break;
1046 }
1047 } else if (makeTombStone && attr->kind == kSecDbUTombAttr) {
1048 if (makeTombStone)
1049 SecDbItemSetValue(new_item, attr, makeTombStone, error);
1050 }
1051 }
1052
1053 return new_item;
1054 }
1055
1056 // MARK: -
1057 // MARK: SQL Construction helpers -- These should become private in the future
1058
1059 void SecDbAppendElement(CFMutableStringRef sql, CFStringRef value, bool *needComma) {
1060 assert(needComma);
1061 if (*needComma) {
1062 CFStringAppend(sql, CFSTR(","));
1063 } else {
1064 *needComma = true;
1065 }
1066 CFStringAppend(sql, value);
1067 }
1068
1069 static void SecDbAppendElementEquals(CFMutableStringRef sql, CFStringRef value, bool *needComma) {
1070 SecDbAppendElement(sql, value, needComma);
1071 CFStringAppend(sql, CFSTR("=?"));
1072 }
1073
1074 /* Append AND is needWhere is NULL or *needWhere is false. Append WHERE
1075 otherwise. Upon return *needWhere will be false. */
1076 void
1077 SecDbAppendWhereOrAnd(CFMutableStringRef sql, bool *needWhere) {
1078 if (!needWhere || !*needWhere) {
1079 CFStringAppend(sql, CFSTR(" AND "));
1080 } else {
1081 CFStringAppend(sql, CFSTR(" WHERE "));
1082 *needWhere = false;
1083 }
1084 }
1085
1086 void
1087 SecDbAppendWhereOrAndEquals(CFMutableStringRef sql, CFStringRef col, bool *needWhere) {
1088 SecDbAppendWhereOrAnd(sql, needWhere);
1089 CFStringAppend(sql, col);
1090 CFStringAppend(sql, CFSTR("=?"));
1091 }
1092
1093 void
1094 SecDbAppendWhereOrAndNotEquals(CFMutableStringRef sql, CFStringRef col, bool *needWhere) {
1095 SecDbAppendWhereOrAnd(sql, needWhere);
1096 CFStringAppend(sql, col);
1097 CFStringAppend(sql, CFSTR("!=?"));
1098 }
1099
1100 static void SecDbAppendCountArgsAndCloseParen(CFMutableStringRef sql, CFIndex count) {
1101 bool needComma = false;
1102 while (count-- > 0)
1103 SecDbAppendElement(sql, CFSTR("?"), &needComma);
1104 CFStringAppend(sql, CFSTR(")"));
1105 }
1106
1107 void
1108 SecDbAppendWhereOrAndIn(CFMutableStringRef sql, CFStringRef col, bool *needWhere, CFIndex count) {
1109 if (count == 1)
1110 return SecDbAppendWhereOrAndEquals(sql, col, needWhere);
1111 SecDbAppendWhereOrAnd(sql, needWhere);
1112 CFStringAppend(sql, col);
1113 CFStringAppend(sql, CFSTR(" IN ("));
1114 SecDbAppendCountArgsAndCloseParen(sql, count);
1115 }
1116
1117 void
1118 SecDbAppendWhereOrAndNotIn(CFMutableStringRef sql, CFStringRef col, bool *needWhere, CFIndex count) {
1119 if (count == 1)
1120 return SecDbAppendWhereOrAndNotEquals(sql, col, needWhere);
1121 SecDbAppendWhereOrAnd(sql, needWhere);
1122 CFStringAppend(sql, col);
1123 CFStringAppend(sql, CFSTR(" NOT IN ("));
1124 SecDbAppendCountArgsAndCloseParen(sql, count);
1125 }
1126
1127 static CFStringRef SecDbItemCopyInsertSQL(SecDbItemRef item, bool(^use_attr)(const SecDbAttr *attr)) {
1128 CFMutableStringRef sql = CFStringCreateMutable(CFGetAllocator(item), 0);
1129 CFStringAppend(sql, CFSTR("INSERT INTO "));
1130 CFStringAppend(sql, item->class->name);
1131 CFStringAppend(sql, CFSTR("("));
1132 bool needComma = false;
1133 CFIndex used_attr = 0;
1134 SecDbForEachAttr(item->class, attr) {
1135 if (use_attr(attr)) {
1136 ++used_attr;
1137 SecDbAppendElement(sql, attr->name, &needComma);
1138 }
1139 }
1140 CFStringAppend(sql, CFSTR(")VALUES(?"));
1141 while (used_attr-- > 1) {
1142 CFStringAppend(sql, CFSTR(",?"));
1143 }
1144 CFStringAppend(sql, CFSTR(")"));
1145 return sql;
1146
1147 }
1148
1149 static bool SecDbItemInsertBind(SecDbItemRef item, sqlite3_stmt *stmt, CFErrorRef *error, bool(^use_attr)(const SecDbAttr *attr)) {
1150 bool ok = true;
1151 int param = 0;
1152 SecDbForEachAttr(item->class, attr) {
1153 if (use_attr(attr)) {
1154 CFTypeRef value = SecDbItemCopyValueForDb(item, attr, error);
1155 ok = value && SecDbBindObject(stmt, ++param, value, error);
1156 CFReleaseSafe(value);
1157 if (!ok)
1158 break;
1159 }
1160 }
1161 return ok;
1162 }
1163
1164 sqlite3_int64 SecDbItemGetRowId(SecDbItemRef item, CFErrorRef *error) {
1165 sqlite3_int64 row_id = 0;
1166 const SecDbAttr *attr = SecDbClassAttrWithKind(item->class, kSecDbRowIdAttr, error);
1167 if (attr) {
1168 CFNumberRef number = SecDbItemGetValue(item, attr, error);
1169 if (!isNumber(number)|| !CFNumberGetValue(number, kCFNumberSInt64Type, &row_id))
1170 SecDbError(SQLITE_ERROR, error, CFSTR("rowid %@ is not a 64 bit number"), number);
1171 }
1172
1173 return row_id;
1174 }
1175
1176 static CFNumberRef SecDbItemCreateRowId(SecDbItemRef item, sqlite3_int64 rowid, CFErrorRef *error) {
1177 return CFNumberCreate(CFGetAllocator(item), kCFNumberSInt64Type, &rowid);
1178 }
1179
1180 bool SecDbItemSetRowId(SecDbItemRef item, sqlite3_int64 rowid, CFErrorRef *error) {
1181 bool ok = true;
1182 const SecDbAttr *attr = SecDbClassAttrWithKind(item->class, kSecDbRowIdAttr, error);
1183 if (attr) {
1184 CFNumberRef value = SecDbItemCreateRowId(item, rowid, error);
1185 if (!value)
1186 return false;
1187
1188 ok = SecDbItemSetValue(item, attr, value, error);
1189 CFRelease(value);
1190 }
1191 return ok;
1192 }
1193
1194 bool SecDbItemClearRowId(SecDbItemRef item, CFErrorRef *error) {
1195 bool ok = true;
1196 const SecDbAttr *attr = SecDbClassAttrWithKind(item->class, kSecDbRowIdAttr, error);
1197 if (attr) {
1198 CFDictionaryRemoveValue(item->attributes, attr->name);
1199 //ok = SecDbItemSetValue(item, attr, kCFNull, error);
1200 }
1201 return ok;
1202 }
1203
1204 static bool SecDbItemSetLastInsertRowId(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error) {
1205 sqlite3_int64 rowid = sqlite3_last_insert_rowid(SecDbHandle(dbconn));
1206 return SecDbItemSetRowId(item, rowid, error);
1207 }
1208
1209 bool SecDbItemIsSyncableOrCorrupted(SecDbItemRef item) {
1210 bool is_syncable_or_corrupted = false;
1211 CFErrorRef localError = NULL;
1212 if (!SecDbItemGetBoolValue(item, SecDbClassAttrWithKind(item->class, kSecDbSyncAttr, &localError),
1213 &is_syncable_or_corrupted, &localError)) {
1214 is_syncable_or_corrupted = SecErrorGetOSStatus(localError) == errSecDecode;
1215 }
1216 CFReleaseSafe(localError);
1217 return is_syncable_or_corrupted;
1218 }
1219
1220 bool SecDbItemIsSyncable(SecDbItemRef item) {
1221 bool is_syncable;
1222 if (SecDbItemGetBoolValue(item, SecDbClassAttrWithKind(item->class, kSecDbSyncAttr, NULL), &is_syncable, NULL))
1223 return is_syncable;
1224 return false;
1225 }
1226
1227 bool SecDbItemSetSyncable(SecDbItemRef item, bool sync, CFErrorRef *error)
1228 {
1229 return SecDbItemSetValue(item, SecDbClassAttrWithKind(item->class, kSecDbSyncAttr, error), sync ? kCFBooleanTrue : kCFBooleanFalse, error);
1230 }
1231
1232 bool SecDbItemIsTombstone(SecDbItemRef item) {
1233 bool is_tomb;
1234 if (SecDbItemGetBoolValue(item, SecDbClassAttrWithKind(item->class, kSecDbTombAttr, NULL), &is_tomb, NULL))
1235 return is_tomb;
1236 return false;
1237 }
1238
1239 CFDataRef SecDbItemGetPrimaryKey(SecDbItemRef item, CFErrorRef *error) {
1240 return SecDbItemGetValue(item, SecDbClassAttrWithKind(item->class, kSecDbPrimaryKeyAttr, error), error);
1241 }
1242
1243 CFDataRef SecDbItemGetSHA1(SecDbItemRef item, CFErrorRef *error) {
1244 return SecDbItemGetValue(item, SecDbClassAttrWithKind(item->class, kSecDbSHA1Attr, error), error);
1245 }
1246
1247 static SecDbQueryRef SecDbQueryCreateWithItemPrimaryKey(SecDbItemRef item, CFErrorRef *error) {
1248 CFMutableDictionaryRef dict = SecDbItemCopyPListWithMask(item, kSecDbPrimaryKeyFlag, error);
1249 if (!dict)
1250 return NULL;
1251
1252 SecDbQueryRef query = query_create(item->class, NULL, NULL, error);
1253 if (query) {
1254 CFReleaseSafe(query->q_item);
1255 query->q_item = dict;
1256 }
1257 else
1258 CFRelease(dict);
1259
1260 return query;
1261 }
1262
1263 static bool SecDbItemIsCorrupt(SecDbItemRef item, bool *is_corrupt, CFErrorRef *error) {
1264 CFErrorRef localError = NULL;
1265 // Cache the storedSHA1 digest so we use the one from the db not the recomputed one for notifications.
1266 const struct SecDbAttr *sha1attr = SecDbClassAttrWithKind(item->class, kSecDbSHA1Attr, &localError);
1267 CFDataRef storedSHA1 = CFRetainSafe(SecDbItemGetValue(item, sha1attr, &localError));
1268 bool akpu = false;
1269
1270 if (localError || !SecDbItemEnsureDecrypted(item, &localError)) {
1271 if (SecErrorGetOSStatus(localError) == errSecDecode) {
1272 // We failed to decrypt the item
1273 const SecDbAttr *desc = SecDbClassAttrWithKind(item->class, kSecDbAccessControlAttr, &localError);
1274 SecAccessControlRef accc = NULL;
1275 CFDataRef acccData = NULL;
1276
1277 acccData = (CFDataRef)SecDbItemGetValue(item, desc, &localError);
1278 if (isData(acccData)) {
1279 accc = SecAccessControlCreateFromData(CFGetAllocator(item), acccData, &localError);
1280 }
1281
1282 if (accc && CFEqualSafe(SecAccessControlGetProtection(accc), kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)) {
1283 akpu = true;
1284 secwarning("cannot decrypt item %@, item is irrecoverably lost with older passcode (error %@)", item, localError);
1285 } else {
1286 secerror("error %@ reading item %@ (corrupted)", localError, item);
1287 __security_simulatecrash(CFSTR("Corrupted item found in keychain"), __sec_exception_code_CorruptItem);
1288 }
1289 CFReleaseNull(localError);
1290 *is_corrupt = true;
1291 }
1292 }
1293
1294 // Recompute sha1 hash attribute and compare with the cached one.
1295 CFDataRef computedSHA1 = SecDbItemCopyValue(item, sha1attr, &localError);
1296 if (storedSHA1 && computedSHA1 && !CFEqual(storedSHA1, computedSHA1)) {
1297 CFStringRef storedHex = CFDataCopyHexString(storedSHA1), computedHex = CFDataCopyHexString(computedSHA1);
1298 secerror("error %@ %@ != %@ item %@ (corrupted)", sha1attr->name, storedHex, computedHex, item);
1299 __security_simulatecrash(CFSTR("Corrupted item (sha1 mismatch) found in keychain"), __sec_exception_code_CorruptItem);
1300 CFReleaseSafe(storedHex);
1301 CFReleaseSafe(computedHex);
1302 *is_corrupt = true;
1303 }
1304
1305 // Sanity check that all attributes that must not be NULL actually aren't
1306 if (!localError) SecDbForEachAttr(item->class, attr) {
1307 if (attr->flags & (kSecDbInCryptoDataFlag | kSecDbInAuthenticatedDataFlag)) {
1308 CFTypeRef value = SecDbItemGetValue(item, attr, &localError);
1309 if (value) {
1310 if (CFEqual(kCFNull, value) && attr->flags & kSecDbNotNullFlag) {
1311 secerror("error attribute %@ has NULL value in item %@ (corrupted)", attr->name, item);
1312 __security_simulatecrash(CFSTR("Corrupted item (attr NULL) found in keychain"), __sec_exception_code_CorruptItem);
1313 *is_corrupt = true;
1314 break;
1315 }
1316 } else {
1317 if (SecErrorGetOSStatus(localError) == errSecDecode) {
1318 // We failed to decrypt the item
1319 if (akpu) {
1320 secwarning("attribute %@: %@ item %@ (item lost with older passcode)", attr->name, localError, item);
1321 } else {
1322 secerror("error attribute %@: %@ item %@ (corrupted)", attr->name, localError, item);
1323 __security_simulatecrash(CFSTR("Corrupted item found in keychain"), __sec_exception_code_CorruptItem);
1324 }
1325 *is_corrupt = true;
1326 CFReleaseNull(localError);
1327 }
1328 break;
1329 }
1330 }
1331 }
1332
1333 CFReleaseSafe(computedSHA1);
1334 CFReleaseSafe(storedSHA1);
1335 return SecErrorPropagate(localError, error);
1336 }
1337
1338 static void SecDbItemRecordUpdate(SecDbConnectionRef dbconn, SecDbItemRef deleted, SecDbItemRef inserted) {
1339 SecDbRecordChange(dbconn, deleted, inserted);
1340 }
1341
1342 static bool SecDbItemDoInsert(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error) {
1343 bool (^use_attr)(const SecDbAttr *attr) = ^bool(const SecDbAttr *attr) {
1344 return (attr->flags & kSecDbInFlag);
1345 };
1346 CFStringRef sql = SecDbItemCopyInsertSQL(item, use_attr);
1347 __block bool ok = sql;
1348 if (sql) {
1349 ok &= SecDbPrepare(dbconn, sql, error, ^(sqlite3_stmt *stmt) {
1350 ok = (SecDbItemInsertBind(item, stmt, error, use_attr) &&
1351 SecDbStep(dbconn, stmt, error, NULL) &&
1352 SecDbItemSetLastInsertRowId(item, dbconn, error));
1353 });
1354 CFRelease(sql);
1355 }
1356 if (ok) {
1357 secnotice("item", "inserted %@", item);
1358 SecDbItemRecordUpdate(dbconn, NULL, item);
1359 } else {
1360 secnotice("item", "insert failed for item %@ with %@", item, error ? *error : NULL);
1361 }
1362
1363 return ok;
1364 }
1365
1366 bool SecDbItemInsertOrReplace(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error, void(^duplicate)(SecDbItemRef item, SecDbItemRef *replace)) {
1367 __block CFErrorRef localError = NULL;
1368 __block bool ok = SecDbItemDoInsert(item, dbconn, &localError);
1369 if (!ok && localError && CFErrorGetCode(localError) == SQLITE_CONSTRAINT && CFEqual(kSecDbErrorDomain, CFErrorGetDomain(localError))) {
1370 SecDbQueryRef query = SecDbQueryCreateWithItemPrimaryKey(item, error);
1371 if (query) {
1372 CFRetainAssign(query->q_use_cred_handle, item->credHandle);
1373 SecDbItemSelect(query, dbconn, error, NULL, ^bool(const SecDbAttr *attr) {
1374 return attr->flags & kSecDbPrimaryKeyFlag;
1375 }, NULL, NULL, ^(SecDbItemRef old_item, bool *stop) {
1376 bool is_corrupt = false;
1377 ok = SecDbItemIsCorrupt(old_item, &is_corrupt, error);
1378 SecDbItemRef replace = NULL;
1379 if (is_corrupt) {
1380 // If old_item is corrupted pretend it's not there and just replace it.
1381 replace = item;
1382 CFRetain(replace);
1383 if(error)
1384 CFReleaseNull(*error); //item is corrupted and will be replaced, so drop the error
1385 } else if (ok && duplicate) {
1386 duplicate(old_item, &replace);
1387 }
1388 if (replace) {
1389 const SecDbAttr *rowid_attr = SecDbClassAttrWithKind(old_item->class, kSecDbRowIdAttr, error);
1390 CFNumberRef oldrowid = SecDbItemGetCachedValue(old_item, rowid_attr);
1391 if (oldrowid) {
1392 ok = SecDbItemSetValue(replace, rowid_attr, oldrowid, &localError);
1393 if (ok && !is_corrupt) {
1394 ok = SecDbItemMakeYounger(replace, old_item, error);
1395 }
1396 ok = ok && SecDbItemDoUpdate(old_item, replace, dbconn, &localError, ^bool (const SecDbAttr *attr) {
1397 return attr->kind == kSecDbRowIdAttr;
1398 });
1399 } else {
1400 ok = SecError(errSecInternal, &localError, CFSTR("no rowid for %@"), old_item);
1401 }
1402 CFRelease(replace);
1403 if (ok)
1404 CFReleaseNull(localError); // Clear the error, since we replaced the item.
1405 }
1406 });
1407 SecDbItemSetCredHandle(item, query->q_use_cred_handle);
1408 ok &= query_destroy(query, error);
1409 }
1410 }
1411
1412 return ok & SecErrorPropagate(localError, error); // Don't use && here!
1413 }
1414
1415 bool SecDbItemInsert(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error) {
1416 return SecDbItemInsertOrReplace(item, dbconn, error, ^(SecDbItemRef old_item, SecDbItemRef *replace) {
1417 if (SecDbItemIsTombstone(old_item)) {
1418 CFRetain(item);
1419 *replace = item;
1420 }
1421 });
1422 }
1423
1424 static CFStringRef SecDbItemCopyUpdateSQL(SecDbItemRef old_item, SecDbItemRef new_item, bool(^use_attr_in_where)(const SecDbAttr *attr)) {
1425 CFMutableStringRef sql = CFStringCreateMutable(CFGetAllocator(new_item), 0);
1426 CFStringAppend(sql, CFSTR("UPDATE "));
1427 CFStringAppend(sql, new_item->class->name);
1428 CFStringAppend(sql, CFSTR(" SET "));
1429 bool needComma = false;
1430 CFIndex used_attr = 0;
1431 SecDbForEachAttrWithMask(new_item->class, attr, kSecDbInFlag) {
1432 ++used_attr;
1433 SecDbAppendElementEquals(sql, attr->name, &needComma);
1434 }
1435
1436 bool needWhere = true;
1437 SecDbForEachAttr(old_item->class, attr) {
1438 if (use_attr_in_where(attr)) {
1439 SecDbAppendWhereOrAndEquals(sql, attr->name, &needWhere);
1440 }
1441 }
1442
1443 return sql;
1444 }
1445
1446 static bool SecDbItemUpdateBind(SecDbItemRef old_item, SecDbItemRef new_item, sqlite3_stmt *stmt, CFErrorRef *error, bool(^use_attr_in_where)(const SecDbAttr *attr)) {
1447 bool ok = true;
1448 int param = 0;
1449 SecDbForEachAttrWithMask(new_item->class, attr, kSecDbInFlag) {
1450 CFTypeRef value = SecDbItemCopyValueForDb(new_item, attr, error);
1451 ok &= value && SecDbBindObject(stmt, ++param, value, error);
1452 CFReleaseSafe(value);
1453 if (!ok)
1454 break;
1455 }
1456 SecDbForEachAttr(old_item->class, attr) {
1457 if (use_attr_in_where(attr)) {
1458 CFTypeRef value = SecDbItemCopyValueForDb(old_item, attr, error);
1459 ok &= value && SecDbBindObject(stmt, ++param, value, error);
1460 CFReleaseSafe(value);
1461 if (!ok)
1462 break;
1463 }
1464 }
1465 return ok;
1466 }
1467
1468 // Primary keys are the same -- do an update
1469 bool SecDbItemDoUpdate(SecDbItemRef old_item, SecDbItemRef new_item, SecDbConnectionRef dbconn, CFErrorRef *error, bool (^use_attr_in_where)(const SecDbAttr *attr)) {
1470 CFStringRef sql = SecDbItemCopyUpdateSQL(old_item, new_item, use_attr_in_where);
1471 __block bool ok = sql;
1472 if (sql) {
1473 ok &= SecDbPrepare(dbconn, sql, error, ^(sqlite3_stmt *stmt) {
1474 ok = SecDbItemUpdateBind(old_item, new_item, stmt, error, use_attr_in_where) && SecDbStep(dbconn, stmt, error, NULL);
1475 });
1476 CFRelease(sql);
1477 }
1478 if (ok) {
1479 secnotice("item", "replaced %@ with %@ in %@", old_item, new_item, dbconn);
1480 SecDbItemRecordUpdate(dbconn, old_item, new_item);
1481 }
1482 return ok;
1483 }
1484
1485 static CFStringRef SecDbItemCopyDeleteSQL(SecDbItemRef item, bool(^use_attr_in_where)(const SecDbAttr *attr)) {
1486 CFMutableStringRef sql = CFStringCreateMutable(CFGetAllocator(item), 0);
1487 CFStringAppend(sql, CFSTR("DELETE FROM "));
1488 CFStringAppend(sql, item->class->name);
1489 bool needWhere = true;
1490 SecDbForEachAttr(item->class, attr) {
1491 if (use_attr_in_where(attr)) {
1492 SecDbAppendWhereOrAndEquals(sql, attr->name, &needWhere);
1493 }
1494 }
1495
1496 return sql;
1497 }
1498
1499 static bool SecDbItemDeleteBind(SecDbItemRef item, sqlite3_stmt *stmt, CFErrorRef *error, bool(^use_attr_in_where)(const SecDbAttr *attr)) {
1500 bool ok = true;
1501 int param = 0;
1502 SecDbForEachAttr(item->class, attr) {
1503 if (use_attr_in_where(attr)) {
1504 CFTypeRef value = SecDbItemCopyValueForDb(item, attr, error);
1505 ok &= value && SecDbBindObject(stmt, ++param, value, error);
1506 CFReleaseSafe(value);
1507 if (!ok)
1508 break;
1509 }
1510 }
1511 return ok;
1512 }
1513
1514 static bool SecDbItemDoDeleteOnly(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error, bool (^use_attr_in_where)(const SecDbAttr *attr)) {
1515 CFStringRef sql = SecDbItemCopyDeleteSQL(item, use_attr_in_where);
1516 __block bool ok = sql;
1517 if (sql) {
1518 ok &= SecDbPrepare(dbconn, sql, error, ^(sqlite3_stmt *stmt) {
1519 ok = SecDbItemDeleteBind(item, stmt, error, use_attr_in_where) && SecDbStep(dbconn, stmt, error, NULL);
1520 });
1521 CFRelease(sql);
1522 }
1523 return ok;
1524 }
1525
1526 bool SecDbItemDoDeleteSilently(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error) {
1527 return SecDbItemDoDeleteOnly(item, dbconn, error, ^bool(const SecDbAttr *attr) {
1528 return attr->kind == kSecDbRowIdAttr;
1529 });
1530 }
1531
1532 static bool SecDbItemDoDelete(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error, bool (^use_attr_in_where)(const SecDbAttr *attr)) {
1533 bool ok = SecDbItemDoDeleteOnly(item, dbconn, error, use_attr_in_where);
1534 if (ok) {
1535 secnotice("item", "deleted %@ from %@", item, dbconn);
1536 SecDbItemRecordUpdate(dbconn, item, NULL);
1537 }
1538 return ok;
1539 }
1540
1541 #if 0
1542 static bool SecDbItemDeleteTombstone(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error) {
1543 bool ok = true;
1544 // TODO: Treat non decryptable items like tombstones here too and delete them
1545 SecDbItemRef tombstone = SecDbItemCopyTombstone(item, error);
1546 ok = tombstone;
1547 if (tombstone) {
1548 ok = SecDbItemClearRowId(tombstone, error);
1549 if (ok) {
1550 ok = SecDbItemDoDelete(tombstone, dbconn, error, ^bool (const SecDbAttr *attr) {
1551 return SecDbIsTombstoneDbSelectAttr(attr);
1552 });
1553 }
1554 CFRelease(tombstone);
1555 }
1556 return ok;
1557 }
1558 #endif
1559
1560 // Replace old_item with new_item. If primary keys are the same this does an update otherwise it does a delete + add
1561 bool SecDbItemUpdate(SecDbItemRef old_item, SecDbItemRef new_item, SecDbConnectionRef dbconn, CFBooleanRef makeTombstone, CFErrorRef *error) {
1562 __block bool ok = true;
1563 __block CFErrorRef localError = NULL;
1564
1565 CFDataRef old_pk = SecDbItemGetPrimaryKey(old_item, error);
1566 CFDataRef new_pk = SecDbItemGetPrimaryKey(new_item, error);
1567
1568 ok = old_pk && new_pk;
1569
1570 bool pk_equal = ok && CFEqual(old_pk, new_pk);
1571 if (pk_equal) {
1572 ok = SecDbItemMakeYounger(new_item, old_item, error);
1573 }
1574 ok = ok && SecDbItemDoUpdate(old_item, new_item, dbconn, &localError, ^bool(const SecDbAttr *attr) {
1575 return attr->kind == kSecDbRowIdAttr;
1576 });
1577
1578 if (localError) {
1579 if(CFErrorGetCode(localError) == SQLITE_CONSTRAINT && CFEqual(kSecDbErrorDomain, CFErrorGetDomain(localError))) {
1580 /* Update failed because we changed the PrimaryKey and there was a dup.
1581 Find the dup and see if it is a tombstone or corrupted item. */
1582 SecDbQueryRef query = SecDbQueryCreateWithItemPrimaryKey(new_item, error);
1583 ok = query;
1584 if (query) {
1585 ok &= SecDbItemSelect(query, dbconn, error, NULL, ^bool(const SecDbAttr *attr) {
1586 return attr->flags & kSecDbPrimaryKeyFlag;
1587 }, NULL, NULL, ^(SecDbItemRef duplicate_item, bool *stop) {
1588 bool is_corrupt = false;
1589 bool is_tomb = false;
1590 ok = SecDbItemIsCorrupt(duplicate_item, &is_corrupt, error);
1591 if (ok && !is_corrupt) {
1592 if ((is_tomb = SecDbItemIsTombstone(duplicate_item)))
1593 ok = SecDbItemMakeYounger(new_item, duplicate_item, error);
1594 }
1595 if (ok && (is_corrupt || is_tomb)) {
1596 ok = SecDbItemDoDelete(old_item, dbconn, error, ^bool (const SecDbAttr *attr) {
1597 return attr->kind == kSecDbRowIdAttr;
1598 });
1599 ok = ok && SecDbItemDoUpdate(duplicate_item, new_item, dbconn, error, ^bool (const SecDbAttr *attr) {
1600 return attr->kind == kSecDbRowIdAttr;
1601 });
1602 CFReleaseNull(localError);
1603 }
1604 });
1605 ok &= query_destroy(query, error);
1606 }
1607 }
1608
1609 if (localError) {
1610 ok = false;
1611 if (error && *error == NULL) {
1612 *error = localError;
1613 localError = NULL;
1614 }
1615 CFReleaseSafe(localError);
1616 }
1617 }
1618
1619 if (ok && !pk_equal && !CFEqualSafe(makeTombstone, kCFBooleanFalse)) {
1620 /* The primary key of new_item is different than that of old_item, we
1621 have been asked to make a tombstone so leave one for the old_item. */
1622 SecDbItemRef tombstone = SecDbItemCopyTombstone(old_item, makeTombstone, error);
1623 ok = tombstone;
1624 if (tombstone) {
1625 ok = (SecDbItemClearRowId(tombstone, error) &&
1626 SecDbItemDoInsert(tombstone, dbconn, error));
1627 CFRelease(tombstone);
1628 }
1629 }
1630
1631 return ok;
1632 }
1633
1634 // Replace the object with a tombstone
1635 bool SecDbItemDelete(SecDbItemRef item, SecDbConnectionRef dbconn, CFBooleanRef makeTombstone, CFErrorRef *error) {
1636 bool ok = false;
1637 if (!CFEqualSafe(makeTombstone, kCFBooleanFalse)) {
1638 SecDbItemRef tombstone = SecDbItemCopyTombstone(item, makeTombstone, error);
1639 if (tombstone) {
1640 ok = SecDbItemDoUpdate(item, tombstone, dbconn, error, ^bool(const SecDbAttr *attr) {
1641 return attr->kind == kSecDbRowIdAttr;
1642 });
1643 CFRelease(tombstone);
1644 }
1645 } else {
1646 ok = SecDbItemDoDelete(item, dbconn, error, ^bool(const SecDbAttr *attr) {
1647 return attr->kind == kSecDbRowIdAttr;
1648 });
1649 }
1650 return ok;
1651 }
1652
1653 CFStringRef SecDbItemCopySelectSQL(SecDbQueryRef query,
1654 bool (^return_attr)(const SecDbAttr *attr),
1655 bool (^use_attr_in_where)(const SecDbAttr *attr),
1656 bool (^add_where_sql)(CFMutableStringRef sql, bool *needWhere)) {
1657 CFMutableStringRef sql = CFStringCreateMutable(kCFAllocatorDefault, 0);
1658 CFStringAppend(sql, CFSTR("SELECT "));
1659 // What are we selecting?
1660 bool needComma = false;
1661 SecDbForEachAttr(query->q_class, attr) {
1662 if (return_attr(attr))
1663 SecDbAppendElement(sql, attr->name, &needComma);
1664 }
1665
1666 // From which table?
1667 CFStringAppend(sql, CFSTR(" FROM "));
1668 CFStringAppend(sql, query->q_class->name);
1669
1670 // And which elements do we want to select
1671 bool needWhere = true;
1672 SecDbForEachAttr(query->q_class, attr) {
1673 if (use_attr_in_where(attr)) {
1674 CFTypeRef value = CFDictionaryGetValue(query->q_item, attr->name);
1675 if (isArray(value)) {
1676 CFArrayRef array = (CFArrayRef)value;
1677 CFIndex length = CFArrayGetCount(array);
1678 if (length > 0) {
1679 CFTypeRef head = CFArrayGetValueAtIndex(array, 0);
1680 if (CFEqualSafe(head, kCFNull)) {
1681 SecDbAppendWhereOrAndNotIn(sql, attr->name, &needWhere, length - 1);
1682 } else {
1683 SecDbAppendWhereOrAndIn(sql, attr->name, &needWhere, length);
1684 }
1685 }
1686 } else {
1687 SecDbAppendWhereOrAndEquals(sql, attr->name, &needWhere);
1688 }
1689 }
1690 }
1691 // Append SQL for access groups and limits.
1692 if (add_where_sql)
1693 add_where_sql(sql, &needWhere);
1694
1695 return sql;
1696 }
1697
1698 static bool SecDbItemSelectBindValue(SecDbQueryRef query, sqlite3_stmt *stmt, int param, const SecDbAttr *attr, CFTypeRef inValue, CFErrorRef *error) {
1699 bool ok = true;
1700 CFTypeRef value = NULL;
1701 if (attr->kind == kSecDbRowIdAttr) {
1702 // TODO: Ignores inValue and uses rowid directly instead HACK should go
1703 value = CFNumberCreate(NULL, kCFNumberSInt64Type, &query->q_row_id);
1704 } else {
1705 value = SecDbAttrCopyValueForDb(attr, inValue, error);
1706 }
1707 ok = ok && value != NULL && SecDbBindObject(stmt, ++param, value, error);
1708 CFReleaseSafe(value);
1709 return ok;
1710 }
1711
1712 bool SecDbItemSelectBind(SecDbQueryRef query, sqlite3_stmt *stmt, CFErrorRef *error,
1713 bool (^use_attr_in_where)(const SecDbAttr *attr),
1714 bool (^bind_added_where)(sqlite3_stmt *stmt, int col)) {
1715 __block bool ok = true;
1716 __block int param = 0;
1717 SecDbForEachAttr(query->q_class, attr) {
1718 if (use_attr_in_where(attr)) {
1719 CFTypeRef value = CFDictionaryGetValue(query->q_item, attr->name);
1720 if (isArray(value)) {
1721 CFArrayRef array = (CFArrayRef)value;
1722 CFRange range = {.location = 0, .length = CFArrayGetCount(array) };
1723 if (range.length > 0) {
1724 CFTypeRef head = CFArrayGetValueAtIndex(array, 0);
1725 if (CFEqualSafe(head, kCFNull)) {
1726 range.length--;
1727 range.location++;
1728 }
1729 }
1730 CFArrayApplyFunction(array, range, apply_block_1, (void (^)(const void *value)) ^(const void *value) {
1731 ok = SecDbItemSelectBindValue(query, stmt, param++, attr, value, error);
1732 });
1733 } else {
1734 ok = SecDbItemSelectBindValue(query, stmt, param++, attr, value, error);
1735 }
1736
1737 if (!ok)
1738 break;
1739 }
1740 }
1741 // TODO: Bind arguments for access groups and limits.
1742 if (bind_added_where)
1743 bind_added_where(stmt, ++param);
1744
1745 return ok;
1746 }
1747
1748 bool SecDbItemSelect(SecDbQueryRef query, SecDbConnectionRef dbconn, CFErrorRef *error,
1749 bool (^return_attr)(const SecDbAttr *attr),
1750 bool (^use_attr_in_where)(const SecDbAttr *attr),
1751 bool (^add_where_sql)(CFMutableStringRef sql, bool *needWhere),
1752 bool (^bind_added_where)(sqlite3_stmt *stmt, int col),
1753 void (^handle_row)(SecDbItemRef item, bool *stop)) {
1754 __block bool ok = true;
1755 if (return_attr == NULL) {
1756 return_attr = ^bool (const SecDbAttr * attr) {
1757 return attr->kind == kSecDbRowIdAttr || attr->kind == kSecDbEncryptedDataAttr || attr->kind == kSecDbSHA1Attr;
1758 };
1759 }
1760
1761 CFStringRef sql = SecDbItemCopySelectSQL(query, return_attr, use_attr_in_where, add_where_sql);
1762 if (sql) {
1763 ok &= SecDbPrepare(dbconn, sql, error, ^(sqlite3_stmt *stmt) {
1764 ok = (SecDbItemSelectBind(query, stmt, error, use_attr_in_where, bind_added_where) &&
1765 SecDbStep(dbconn, stmt, error, ^(bool *stop) {
1766 SecDbItemRef item = SecDbItemCreateWithStatement(kCFAllocatorDefault, query->q_class, stmt, query->q_keybag, error, return_attr);
1767 if (item) {
1768 CFRetainAssign(item->credHandle, query->q_use_cred_handle);
1769 handle_row(item, stop);
1770 CFRelease(item);
1771 } else {
1772 //*stop = true;
1773 //ok = false;
1774 }
1775 }));
1776 });
1777 CFRelease(sql);
1778 } else {
1779 ok = false;
1780 }
1781 return ok;
1782 }
1783