]> git.saurik.com Git - apple/security.git/blob - OSX/sec/securityd/SecDbItem.c
Security-57337.50.23.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, 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 if (value) {
938 CFDictionarySetValue(item->attributes, SecDbAttrGetHashName(attr), value);
939 CFRelease(value);
940 }
941 }
942
943 const SecDbAttr *data_attr = SecDbClassAttrWithKind(class, kSecDbEncryptedDataAttr, error);
944 if (data_attr != NULL && CFDictionaryGetValue(item->attributes, data_attr->name) != NULL) {
945 item->_edataState = kSecDbItemEncrypted;
946 }
947 }
948
949 return item;
950 }
951
952 SecDbItemRef SecDbItemCreateWithEncryptedData(CFAllocatorRef allocator, const SecDbClass *class,
953 CFDataRef edata, keybag_handle_t keybag, CFErrorRef *error) {
954 SecDbItemRef item = SecDbItemCreate(allocator, class, keybag);
955 const SecDbAttr *edata_attr = SecDbClassAttrWithKind(class, kSecDbEncryptedDataAttr, error);
956 if (edata_attr) {
957 if (!SecDbItemSetValue(item, edata_attr, edata, error))
958 CFReleaseNull(item);
959 }
960 return item;
961 }
962
963 // TODO: Hack -- Replace with real filtering
964
965 // Return true iff an item for which SecDbItemIsSyncable() already returns true should be part of the v2 view.
966 bool SecDbItemInV2(SecDbItemRef item) {
967 const SecDbClass *iclass = SecDbItemGetClass(item);
968 return (SecDbItemGetCachedValueWithName(item, kSecAttrSyncViewHint) == NULL &&
969 (iclass == &genp_class || iclass == &inet_class || iclass == &keys_class || iclass == &cert_class));
970 }
971
972 // Return true iff an item for which SecDbItemIsSyncable() and SecDbItemInV2() already return true should be part of the v0 view.
973 bool SecDbItemInV2AlsoInV0(SecDbItemRef item) {
974 return (SecDbItemGetCachedValueWithName(item, kSecAttrTokenID) == NULL && SecDbItemGetClass(item) != &cert_class);
975 }
976
977 SecDbItemRef SecDbItemCopyWithUpdates(SecDbItemRef item, CFDictionaryRef updates, CFErrorRef *error) {
978 SecDbItemRef new_item = SecDbItemCreate(CFGetAllocator(item), item->class, item->keybag);
979 SecDbItemSetCredHandle(new_item, item->credHandle);
980 SecDbForEachAttr(item->class, attr) {
981 // Copy each attribute, except the mod date attribute (it will be reset to now when needed),
982 // from the updates dict unless it's not there in which case we copy the attribute from the passed in item.
983 if (attr->kind != kSecDbModificationDateAttr && attr->kind != kSecDbEncryptedDataAttr && attr->kind != kSecDbSHA1Attr && attr->kind != kSecDbPrimaryKeyAttr) {
984 CFTypeRef value = NULL;
985 if (CFDictionaryGetValueIfPresent(updates, attr->name, &value)) {
986 if (!value)
987 SecError(errSecParam, error, CFSTR("NULL value in dictionary"));
988 } else {
989 value = SecDbItemGetValue(item, attr, error);
990 }
991 if (!value || !SecDbItemSetValue(new_item, attr, value, error)) {
992 CFReleaseNull(new_item);
993 break;
994 }
995 }
996 }
997 return new_item;
998 }
999
1000 // Ensure that the date value of attr of new_item is greater than that of old_item.
1001 static bool SecDbItemMakeAttrYounger(SecDbItemRef new_item, SecDbItemRef old_item, const SecDbAttr *attr, CFErrorRef *error) {
1002 CFDateRef old_date = SecDbItemGetValue(old_item, attr, error);
1003 if (!old_date)
1004 return false;
1005 CFDateRef new_date = SecDbItemGetValue(new_item, attr, error);
1006 if (!new_date)
1007 return false;
1008 bool ok = true;
1009 if (CFDateCompare(new_date, old_date, NULL) != kCFCompareGreaterThan) {
1010 CFDateRef adjusted_date = CFDateCreate(kCFAllocatorDefault, CFDateGetAbsoluteTime(old_date) + 0.001);
1011 if (adjusted_date) {
1012 ok = SecDbItemSetValue(new_item, attr, adjusted_date, error);
1013 CFRelease(adjusted_date);
1014 }
1015 }
1016 return ok;
1017 }
1018
1019 // Ensure that the mod date of new_item is greater than that of old_item.
1020 static bool SecDbItemMakeYounger(SecDbItemRef new_item, SecDbItemRef old_item, CFErrorRef *error) {
1021 const SecDbAttr *attr = SecDbClassAttrWithKind(new_item->class, kSecDbModificationDateAttr, error);
1022 return attr && SecDbItemMakeAttrYounger(new_item, old_item, attr, error);
1023 }
1024
1025 static SecDbItemRef SecDbItemCopyTombstone(SecDbItemRef item, CFBooleanRef makeTombStone, CFErrorRef *error) {
1026 SecDbItemRef new_item = SecDbItemCreate(CFGetAllocator(item), item->class, item->keybag);
1027 SecDbForEachAttr(item->class, attr) {
1028 if (attr->kind == kSecDbTombAttr) {
1029 // Set the tomb attr to true to indicate a tombstone.
1030 if (!SecDbItemSetValue(new_item, attr, kCFBooleanTrue, error)) {
1031 CFReleaseNull(new_item);
1032 break;
1033 }
1034 } else if (SecDbIsTombstoneDbUpdateAttr(attr)) {
1035 // Copy all primary key attributes and creation timestamps from the original item.
1036 CFTypeRef value = SecDbItemGetValue(item, attr, error);
1037 if (!value || (!CFEqual(kCFNull, value) && !SecDbItemSetValue(new_item, attr, value, error))) {
1038 CFReleaseNull(new_item);
1039 break;
1040 }
1041 } else if (attr->kind == kSecDbModificationDateAttr) {
1042 if (!SecDbItemMakeAttrYounger(new_item, item, attr, error)) {
1043 CFReleaseNull(new_item);
1044 break;
1045 }
1046 } else if (makeTombStone && attr->kind == kSecDbUTombAttr) {
1047 if (makeTombStone)
1048 SecDbItemSetValue(new_item, attr, makeTombStone, error);
1049 }
1050 }
1051
1052 return new_item;
1053 }
1054
1055 // MARK: -
1056 // MARK: SQL Construction helpers -- These should become private in the future
1057
1058 void SecDbAppendElement(CFMutableStringRef sql, CFStringRef value, bool *needComma) {
1059 assert(needComma);
1060 if (*needComma) {
1061 CFStringAppend(sql, CFSTR(","));
1062 } else {
1063 *needComma = true;
1064 }
1065 CFStringAppend(sql, value);
1066 }
1067
1068 static void SecDbAppendElementEquals(CFMutableStringRef sql, CFStringRef value, bool *needComma) {
1069 SecDbAppendElement(sql, value, needComma);
1070 CFStringAppend(sql, CFSTR("=?"));
1071 }
1072
1073 /* Append AND is needWhere is NULL or *needWhere is false. Append WHERE
1074 otherwise. Upon return *needWhere will be false. */
1075 void
1076 SecDbAppendWhereOrAnd(CFMutableStringRef sql, bool *needWhere) {
1077 if (!needWhere || !*needWhere) {
1078 CFStringAppend(sql, CFSTR(" AND "));
1079 } else {
1080 CFStringAppend(sql, CFSTR(" WHERE "));
1081 *needWhere = false;
1082 }
1083 }
1084
1085 void
1086 SecDbAppendWhereOrAndEquals(CFMutableStringRef sql, CFStringRef col, bool *needWhere) {
1087 SecDbAppendWhereOrAnd(sql, needWhere);
1088 CFStringAppend(sql, col);
1089 CFStringAppend(sql, CFSTR("=?"));
1090 }
1091
1092 void
1093 SecDbAppendWhereOrAndNotEquals(CFMutableStringRef sql, CFStringRef col, bool *needWhere) {
1094 SecDbAppendWhereOrAnd(sql, needWhere);
1095 CFStringAppend(sql, col);
1096 CFStringAppend(sql, CFSTR("!=?"));
1097 }
1098
1099 static void SecDbAppendCountArgsAndCloseParen(CFMutableStringRef sql, CFIndex count) {
1100 bool needComma = false;
1101 while (count-- > 0)
1102 SecDbAppendElement(sql, CFSTR("?"), &needComma);
1103 CFStringAppend(sql, CFSTR(")"));
1104 }
1105
1106 void
1107 SecDbAppendWhereOrAndIn(CFMutableStringRef sql, CFStringRef col, bool *needWhere, CFIndex count) {
1108 if (count == 1)
1109 return SecDbAppendWhereOrAndEquals(sql, col, needWhere);
1110 SecDbAppendWhereOrAnd(sql, needWhere);
1111 CFStringAppend(sql, col);
1112 CFStringAppend(sql, CFSTR(" IN ("));
1113 SecDbAppendCountArgsAndCloseParen(sql, count);
1114 }
1115
1116 void
1117 SecDbAppendWhereOrAndNotIn(CFMutableStringRef sql, CFStringRef col, bool *needWhere, CFIndex count) {
1118 if (count == 1)
1119 return SecDbAppendWhereOrAndNotEquals(sql, col, needWhere);
1120 SecDbAppendWhereOrAnd(sql, needWhere);
1121 CFStringAppend(sql, col);
1122 CFStringAppend(sql, CFSTR(" NOT IN ("));
1123 SecDbAppendCountArgsAndCloseParen(sql, count);
1124 }
1125
1126 static CFStringRef SecDbItemCopyInsertSQL(SecDbItemRef item, bool(^use_attr)(const SecDbAttr *attr)) {
1127 CFMutableStringRef sql = CFStringCreateMutable(CFGetAllocator(item), 0);
1128 CFStringAppend(sql, CFSTR("INSERT INTO "));
1129 CFStringAppend(sql, item->class->name);
1130 CFStringAppend(sql, CFSTR("("));
1131 bool needComma = false;
1132 CFIndex used_attr = 0;
1133 SecDbForEachAttr(item->class, attr) {
1134 if (use_attr(attr)) {
1135 ++used_attr;
1136 SecDbAppendElement(sql, attr->name, &needComma);
1137 }
1138 }
1139 CFStringAppend(sql, CFSTR(")VALUES(?"));
1140 while (used_attr-- > 1) {
1141 CFStringAppend(sql, CFSTR(",?"));
1142 }
1143 CFStringAppend(sql, CFSTR(")"));
1144 return sql;
1145
1146 }
1147
1148 static bool SecDbItemInsertBind(SecDbItemRef item, sqlite3_stmt *stmt, CFErrorRef *error, bool(^use_attr)(const SecDbAttr *attr)) {
1149 bool ok = true;
1150 int param = 0;
1151 SecDbForEachAttr(item->class, attr) {
1152 if (use_attr(attr)) {
1153 CFTypeRef value = SecDbItemCopyValueForDb(item, attr, error);
1154 ok = value && SecDbBindObject(stmt, ++param, value, error);
1155 CFReleaseSafe(value);
1156 if (!ok)
1157 break;
1158 }
1159 }
1160 return ok;
1161 }
1162
1163 sqlite3_int64 SecDbItemGetRowId(SecDbItemRef item, CFErrorRef *error) {
1164 sqlite3_int64 row_id = 0;
1165 const SecDbAttr *attr = SecDbClassAttrWithKind(item->class, kSecDbRowIdAttr, error);
1166 if (attr) {
1167 CFNumberRef number = SecDbItemGetValue(item, attr, error);
1168 if (!isNumber(number)|| !CFNumberGetValue(number, kCFNumberSInt64Type, &row_id))
1169 SecDbError(SQLITE_ERROR, error, CFSTR("rowid %@ is not a 64 bit number"), number);
1170 }
1171
1172 return row_id;
1173 }
1174
1175 static CFNumberRef SecDbItemCreateRowId(SecDbItemRef item, sqlite3_int64 rowid, CFErrorRef *error) {
1176 return CFNumberCreate(CFGetAllocator(item), kCFNumberSInt64Type, &rowid);
1177 }
1178
1179 bool SecDbItemSetRowId(SecDbItemRef item, sqlite3_int64 rowid, CFErrorRef *error) {
1180 bool ok = true;
1181 const SecDbAttr *attr = SecDbClassAttrWithKind(item->class, kSecDbRowIdAttr, error);
1182 if (attr) {
1183 CFNumberRef value = SecDbItemCreateRowId(item, rowid, error);
1184 if (!value)
1185 return false;
1186
1187 ok = SecDbItemSetValue(item, attr, value, error);
1188 CFRelease(value);
1189 }
1190 return ok;
1191 }
1192
1193 bool SecDbItemClearRowId(SecDbItemRef item, CFErrorRef *error) {
1194 bool ok = true;
1195 const SecDbAttr *attr = SecDbClassAttrWithKind(item->class, kSecDbRowIdAttr, error);
1196 if (attr) {
1197 CFDictionaryRemoveValue(item->attributes, attr->name);
1198 //ok = SecDbItemSetValue(item, attr, kCFNull, error);
1199 }
1200 return ok;
1201 }
1202
1203 static bool SecDbItemSetLastInsertRowId(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error) {
1204 sqlite3_int64 rowid = sqlite3_last_insert_rowid(SecDbHandle(dbconn));
1205 return SecDbItemSetRowId(item, rowid, error);
1206 }
1207
1208 bool SecDbItemIsSyncableOrCorrupted(SecDbItemRef item) {
1209 bool is_syncable_or_corrupted = false;
1210 CFErrorRef localError = NULL;
1211 if (!SecDbItemGetBoolValue(item, SecDbClassAttrWithKind(item->class, kSecDbSyncAttr, &localError),
1212 &is_syncable_or_corrupted, &localError)) {
1213 is_syncable_or_corrupted = SecErrorGetOSStatus(localError) == errSecDecode;
1214 }
1215 CFReleaseSafe(localError);
1216 return is_syncable_or_corrupted;
1217 }
1218
1219 bool SecDbItemIsSyncable(SecDbItemRef item) {
1220 bool is_syncable;
1221 if (SecDbItemGetBoolValue(item, SecDbClassAttrWithKind(item->class, kSecDbSyncAttr, NULL), &is_syncable, NULL))
1222 return is_syncable;
1223 return false;
1224 }
1225
1226 bool SecDbItemSetSyncable(SecDbItemRef item, bool sync, CFErrorRef *error)
1227 {
1228 return SecDbItemSetValue(item, SecDbClassAttrWithKind(item->class, kSecDbSyncAttr, error), sync ? kCFBooleanTrue : kCFBooleanFalse, error);
1229 }
1230
1231 bool SecDbItemIsTombstone(SecDbItemRef item) {
1232 bool is_tomb;
1233 if (SecDbItemGetBoolValue(item, SecDbClassAttrWithKind(item->class, kSecDbTombAttr, NULL), &is_tomb, NULL))
1234 return is_tomb;
1235 return false;
1236 }
1237
1238 CFDataRef SecDbItemGetPrimaryKey(SecDbItemRef item, CFErrorRef *error) {
1239 return SecDbItemGetValue(item, SecDbClassAttrWithKind(item->class, kSecDbPrimaryKeyAttr, error), error);
1240 }
1241
1242 CFDataRef SecDbItemGetSHA1(SecDbItemRef item, CFErrorRef *error) {
1243 return SecDbItemGetValue(item, SecDbClassAttrWithKind(item->class, kSecDbSHA1Attr, error), error);
1244 }
1245
1246 static SecDbQueryRef SecDbQueryCreateWithItemPrimaryKey(SecDbItemRef item, CFErrorRef *error) {
1247 CFMutableDictionaryRef dict = SecDbItemCopyPListWithMask(item, kSecDbPrimaryKeyFlag, error);
1248 if (!dict)
1249 return NULL;
1250
1251 SecDbQueryRef query = query_create(item->class, NULL, NULL, error);
1252 if (query) {
1253 CFReleaseSafe(query->q_item);
1254 query->q_item = dict;
1255 }
1256 else
1257 CFRelease(dict);
1258
1259 return query;
1260 }
1261
1262 static bool SecDbItemIsCorrupt(SecDbItemRef item, bool *is_corrupt, CFErrorRef *error) {
1263 CFErrorRef localError = NULL;
1264 // Cache the storedSHA1 digest so we use the one from the db not the recomputed one for notifications.
1265 const struct SecDbAttr *sha1attr = SecDbClassAttrWithKind(item->class, kSecDbSHA1Attr, &localError);
1266 CFDataRef storedSHA1 = CFRetainSafe(SecDbItemGetValue(item, sha1attr, &localError));
1267 bool akpu = false;
1268
1269 if (localError || !SecDbItemEnsureDecrypted(item, &localError)) {
1270 if (SecErrorGetOSStatus(localError) == errSecDecode) {
1271 // We failed to decrypt the item
1272 const SecDbAttr *desc = SecDbClassAttrWithKind(item->class, kSecDbAccessControlAttr, &localError);
1273 SecAccessControlRef accc = NULL;
1274 CFDataRef acccData = NULL;
1275
1276 acccData = (CFDataRef)SecDbItemGetValue(item, desc, &localError);
1277 if (isData(acccData)) {
1278 accc = SecAccessControlCreateFromData(CFGetAllocator(item), acccData, &localError);
1279 }
1280
1281 if (accc && CFEqualSafe(SecAccessControlGetProtection(accc), kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)) {
1282 akpu = true;
1283 secwarning("cannot decrypt item %@, item is irrecoverably lost with older passcode (error %@)", item, localError);
1284 } else {
1285 secerror("error %@ reading item %@ (corrupted)", localError, item);
1286 __security_simulatecrash(CFSTR("Corrupted item found in keychain"), __sec_exception_code_CorruptItem);
1287 }
1288 CFReleaseNull(localError);
1289 *is_corrupt = true;
1290 }
1291 }
1292
1293 // Recompute sha1 hash attribute and compare with the cached one.
1294 CFDataRef computedSHA1 = SecDbItemCopyValue(item, sha1attr, &localError);
1295 if (storedSHA1 && computedSHA1 && !CFEqual(storedSHA1, computedSHA1)) {
1296 CFStringRef storedHex = CFDataCopyHexString(storedSHA1), computedHex = CFDataCopyHexString(computedSHA1);
1297 secerror("error %@ %@ != %@ item %@ (corrupted)", sha1attr->name, storedHex, computedHex, item);
1298 __security_simulatecrash(CFSTR("Corrupted item (sha1 mismatch) found in keychain"), __sec_exception_code_CorruptItem);
1299 CFReleaseSafe(storedHex);
1300 CFReleaseSafe(computedHex);
1301 *is_corrupt = true;
1302 }
1303
1304 // Sanity check that all attributes that must not be NULL actually aren't
1305 if (!localError) SecDbForEachAttr(item->class, attr) {
1306 if (attr->flags & (kSecDbInCryptoDataFlag | kSecDbInAuthenticatedDataFlag)) {
1307 CFTypeRef value = SecDbItemGetValue(item, attr, &localError);
1308 if (value) {
1309 if (CFEqual(kCFNull, value) && attr->flags & kSecDbNotNullFlag) {
1310 secerror("error attribute %@ has NULL value in item %@ (corrupted)", attr->name, item);
1311 __security_simulatecrash(CFSTR("Corrupted item (attr NULL) found in keychain"), __sec_exception_code_CorruptItem);
1312 *is_corrupt = true;
1313 break;
1314 }
1315 } else {
1316 if (SecErrorGetOSStatus(localError) == errSecDecode) {
1317 // We failed to decrypt the item
1318 if (akpu) {
1319 secwarning("attribute %@: %@ item %@ (item lost with older passcode)", attr->name, localError, item);
1320 } else {
1321 secerror("error attribute %@: %@ item %@ (corrupted)", attr->name, localError, item);
1322 __security_simulatecrash(CFSTR("Corrupted item found in keychain"), __sec_exception_code_CorruptItem);
1323 }
1324 *is_corrupt = true;
1325 CFReleaseNull(localError);
1326 }
1327 break;
1328 }
1329 }
1330 }
1331
1332 CFReleaseSafe(computedSHA1);
1333 CFReleaseSafe(storedSHA1);
1334 return SecErrorPropagate(localError, error);
1335 }
1336
1337 static void SecDbItemRecordUpdate(SecDbConnectionRef dbconn, SecDbItemRef deleted, SecDbItemRef inserted) {
1338 SecDbRecordChange(dbconn, deleted, inserted);
1339 }
1340
1341 static bool SecDbItemDoInsert(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error) {
1342 bool (^use_attr)(const SecDbAttr *attr) = ^bool(const SecDbAttr *attr) {
1343 return (attr->flags & kSecDbInFlag);
1344 };
1345 CFStringRef sql = SecDbItemCopyInsertSQL(item, use_attr);
1346 __block bool ok = sql;
1347 if (sql) {
1348 ok &= SecDbPrepare(dbconn, sql, error, ^(sqlite3_stmt *stmt) {
1349 ok = (SecDbItemInsertBind(item, stmt, error, use_attr) &&
1350 SecDbStep(dbconn, stmt, error, NULL) &&
1351 SecDbItemSetLastInsertRowId(item, dbconn, error));
1352 });
1353 CFRelease(sql);
1354 }
1355 if (ok) {
1356 secnotice("item", "inserted %@", item);
1357 SecDbItemRecordUpdate(dbconn, NULL, item);
1358 }
1359
1360 return ok;
1361 }
1362
1363 bool SecDbItemInsertOrReplace(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error, void(^duplicate)(SecDbItemRef item, SecDbItemRef *replace)) {
1364 __block CFErrorRef localError = NULL;
1365 __block bool ok = SecDbItemDoInsert(item, dbconn, &localError);
1366 if (!ok && localError && CFErrorGetCode(localError) == SQLITE_CONSTRAINT && CFEqual(kSecDbErrorDomain, CFErrorGetDomain(localError))) {
1367 SecDbQueryRef query = SecDbQueryCreateWithItemPrimaryKey(item, error);
1368 if (query) {
1369 CFRetainAssign(query->q_use_cred_handle, item->credHandle);
1370 SecDbItemSelect(query, dbconn, error, NULL, ^bool(const SecDbAttr *attr) {
1371 return attr->flags & kSecDbPrimaryKeyFlag;
1372 }, NULL, NULL, ^(SecDbItemRef old_item, bool *stop) {
1373 bool is_corrupt = false;
1374 ok = SecDbItemIsCorrupt(old_item, &is_corrupt, error);
1375 SecDbItemRef replace = NULL;
1376 if (is_corrupt) {
1377 // If old_item is corrupted pretend it's not there and just replace it.
1378 replace = item;
1379 CFRetain(replace);
1380 if(error)
1381 CFReleaseNull(*error); //item is corrupted and will be replaced, so drop the error
1382 } else if (ok && duplicate) {
1383 duplicate(old_item, &replace);
1384 }
1385 if (replace) {
1386 const SecDbAttr *rowid_attr = SecDbClassAttrWithKind(old_item->class, kSecDbRowIdAttr, error);
1387 CFNumberRef oldrowid = SecDbItemGetCachedValue(old_item, rowid_attr);
1388 if (oldrowid) {
1389 ok = SecDbItemSetValue(replace, rowid_attr, oldrowid, &localError);
1390 if (ok && !is_corrupt) {
1391 ok = SecDbItemMakeYounger(replace, old_item, error);
1392 }
1393 ok = ok && SecDbItemDoUpdate(old_item, replace, dbconn, &localError, ^bool (const SecDbAttr *attr) {
1394 return attr->kind == kSecDbRowIdAttr;
1395 });
1396 } else {
1397 ok = SecError(errSecInternal, &localError, CFSTR("no rowid for %@"), old_item);
1398 }
1399 CFRelease(replace);
1400 if (ok)
1401 CFReleaseNull(localError); // Clear the error, since we replaced the item.
1402 }
1403 });
1404 SecDbItemSetCredHandle(item, query->q_use_cred_handle);
1405 ok &= query_destroy(query, error);
1406 }
1407 }
1408
1409 return ok & SecErrorPropagate(localError, error); // Don't use && here!
1410 }
1411
1412 bool SecDbItemInsert(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error) {
1413 return SecDbItemInsertOrReplace(item, dbconn, error, ^(SecDbItemRef old_item, SecDbItemRef *replace) {
1414 if (SecDbItemIsTombstone(old_item)) {
1415 CFRetain(item);
1416 *replace = item;
1417 }
1418 });
1419 }
1420
1421 static CFStringRef SecDbItemCopyUpdateSQL(SecDbItemRef old_item, SecDbItemRef new_item, bool(^use_attr_in_where)(const SecDbAttr *attr)) {
1422 CFMutableStringRef sql = CFStringCreateMutable(CFGetAllocator(new_item), 0);
1423 CFStringAppend(sql, CFSTR("UPDATE "));
1424 CFStringAppend(sql, new_item->class->name);
1425 CFStringAppend(sql, CFSTR(" SET "));
1426 bool needComma = false;
1427 CFIndex used_attr = 0;
1428 SecDbForEachAttrWithMask(new_item->class, attr, kSecDbInFlag) {
1429 ++used_attr;
1430 SecDbAppendElementEquals(sql, attr->name, &needComma);
1431 }
1432
1433 bool needWhere = true;
1434 SecDbForEachAttr(old_item->class, attr) {
1435 if (use_attr_in_where(attr)) {
1436 SecDbAppendWhereOrAndEquals(sql, attr->name, &needWhere);
1437 }
1438 }
1439
1440 return sql;
1441 }
1442
1443 static bool SecDbItemUpdateBind(SecDbItemRef old_item, SecDbItemRef new_item, sqlite3_stmt *stmt, CFErrorRef *error, bool(^use_attr_in_where)(const SecDbAttr *attr)) {
1444 bool ok = true;
1445 int param = 0;
1446 SecDbForEachAttrWithMask(new_item->class, attr, kSecDbInFlag) {
1447 CFTypeRef value = SecDbItemCopyValueForDb(new_item, attr, error);
1448 ok &= value && SecDbBindObject(stmt, ++param, value, error);
1449 CFReleaseSafe(value);
1450 if (!ok)
1451 break;
1452 }
1453 SecDbForEachAttr(old_item->class, attr) {
1454 if (use_attr_in_where(attr)) {
1455 CFTypeRef value = SecDbItemCopyValueForDb(old_item, attr, error);
1456 ok &= value && SecDbBindObject(stmt, ++param, value, error);
1457 CFReleaseSafe(value);
1458 if (!ok)
1459 break;
1460 }
1461 }
1462 return ok;
1463 }
1464
1465 // Primary keys are the same -- do an update
1466 bool SecDbItemDoUpdate(SecDbItemRef old_item, SecDbItemRef new_item, SecDbConnectionRef dbconn, CFErrorRef *error, bool (^use_attr_in_where)(const SecDbAttr *attr)) {
1467 CFStringRef sql = SecDbItemCopyUpdateSQL(old_item, new_item, use_attr_in_where);
1468 __block bool ok = sql;
1469 if (sql) {
1470 ok &= SecDbPrepare(dbconn, sql, error, ^(sqlite3_stmt *stmt) {
1471 ok = SecDbItemUpdateBind(old_item, new_item, stmt, error, use_attr_in_where) && SecDbStep(dbconn, stmt, error, NULL);
1472 });
1473 CFRelease(sql);
1474 }
1475 if (ok) {
1476 secnotice("item", "replaced %@ with %@ in %@", old_item, new_item, dbconn);
1477 SecDbItemRecordUpdate(dbconn, old_item, new_item);
1478 }
1479 return ok;
1480 }
1481
1482 static CFStringRef SecDbItemCopyDeleteSQL(SecDbItemRef item, bool(^use_attr_in_where)(const SecDbAttr *attr)) {
1483 CFMutableStringRef sql = CFStringCreateMutable(CFGetAllocator(item), 0);
1484 CFStringAppend(sql, CFSTR("DELETE FROM "));
1485 CFStringAppend(sql, item->class->name);
1486 bool needWhere = true;
1487 SecDbForEachAttr(item->class, attr) {
1488 if (use_attr_in_where(attr)) {
1489 SecDbAppendWhereOrAndEquals(sql, attr->name, &needWhere);
1490 }
1491 }
1492
1493 return sql;
1494 }
1495
1496 static bool SecDbItemDeleteBind(SecDbItemRef item, sqlite3_stmt *stmt, CFErrorRef *error, bool(^use_attr_in_where)(const SecDbAttr *attr)) {
1497 bool ok = true;
1498 int param = 0;
1499 SecDbForEachAttr(item->class, attr) {
1500 if (use_attr_in_where(attr)) {
1501 CFTypeRef value = SecDbItemCopyValueForDb(item, attr, error);
1502 ok &= value && SecDbBindObject(stmt, ++param, value, error);
1503 CFReleaseSafe(value);
1504 if (!ok)
1505 break;
1506 }
1507 }
1508 return ok;
1509 }
1510
1511 static bool SecDbItemDoDeleteOnly(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error, bool (^use_attr_in_where)(const SecDbAttr *attr)) {
1512 CFStringRef sql = SecDbItemCopyDeleteSQL(item, use_attr_in_where);
1513 __block bool ok = sql;
1514 if (sql) {
1515 ok &= SecDbPrepare(dbconn, sql, error, ^(sqlite3_stmt *stmt) {
1516 ok = SecDbItemDeleteBind(item, stmt, error, use_attr_in_where) && SecDbStep(dbconn, stmt, error, NULL);
1517 });
1518 CFRelease(sql);
1519 }
1520 return ok;
1521 }
1522
1523 bool SecDbItemDoDeleteSilently(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error) {
1524 return SecDbItemDoDeleteOnly(item, dbconn, error, ^bool(const SecDbAttr *attr) {
1525 return attr->kind == kSecDbRowIdAttr;
1526 });
1527 }
1528
1529 static bool SecDbItemDoDelete(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error, bool (^use_attr_in_where)(const SecDbAttr *attr)) {
1530 bool ok = SecDbItemDoDeleteOnly(item, dbconn, error, use_attr_in_where);
1531 if (ok) {
1532 secnotice("item", "deleted %@ from %@", item, dbconn);
1533 SecDbItemRecordUpdate(dbconn, item, NULL);
1534 }
1535 return ok;
1536 }
1537
1538 #if 0
1539 static bool SecDbItemDeleteTombstone(SecDbItemRef item, SecDbConnectionRef dbconn, CFErrorRef *error) {
1540 bool ok = true;
1541 // TODO: Treat non decryptable items like tombstones here too and delete them
1542 SecDbItemRef tombstone = SecDbItemCopyTombstone(item, error);
1543 ok = tombstone;
1544 if (tombstone) {
1545 ok = SecDbItemClearRowId(tombstone, error);
1546 if (ok) {
1547 ok = SecDbItemDoDelete(tombstone, dbconn, error, ^bool (const SecDbAttr *attr) {
1548 return SecDbIsTombstoneDbSelectAttr(attr);
1549 });
1550 }
1551 CFRelease(tombstone);
1552 }
1553 return ok;
1554 }
1555 #endif
1556
1557 // Replace old_item with new_item. If primary keys are the same this does an update otherwise it does a delete + add
1558 bool SecDbItemUpdate(SecDbItemRef old_item, SecDbItemRef new_item, SecDbConnectionRef dbconn, CFBooleanRef makeTombstone, CFErrorRef *error) {
1559 __block bool ok = true;
1560 __block CFErrorRef localError = NULL;
1561
1562 CFDataRef old_pk = SecDbItemGetPrimaryKey(old_item, error);
1563 CFDataRef new_pk = SecDbItemGetPrimaryKey(new_item, error);
1564
1565 ok = old_pk && new_pk;
1566
1567 bool pk_equal = ok && CFEqual(old_pk, new_pk);
1568 if (pk_equal) {
1569 ok = SecDbItemMakeYounger(new_item, old_item, error);
1570 }
1571 ok = ok && SecDbItemDoUpdate(old_item, new_item, dbconn, &localError, ^bool(const SecDbAttr *attr) {
1572 return attr->kind == kSecDbRowIdAttr;
1573 });
1574
1575 if (localError) {
1576 if(CFErrorGetCode(localError) == SQLITE_CONSTRAINT && CFEqual(kSecDbErrorDomain, CFErrorGetDomain(localError))) {
1577 /* Update failed because we changed the PrimaryKey and there was a dup.
1578 Find the dup and see if it is a tombstone or corrupted item. */
1579 SecDbQueryRef query = SecDbQueryCreateWithItemPrimaryKey(new_item, error);
1580 ok = query;
1581 if (query) {
1582 ok &= SecDbItemSelect(query, dbconn, error, NULL, ^bool(const SecDbAttr *attr) {
1583 return attr->flags & kSecDbPrimaryKeyFlag;
1584 }, NULL, NULL, ^(SecDbItemRef duplicate_item, bool *stop) {
1585 bool is_corrupt = false;
1586 bool is_tomb = false;
1587 ok = SecDbItemIsCorrupt(duplicate_item, &is_corrupt, error);
1588 if (ok && !is_corrupt) {
1589 if ((is_tomb = SecDbItemIsTombstone(duplicate_item)))
1590 ok = SecDbItemMakeYounger(new_item, duplicate_item, error);
1591 }
1592 if (ok && (is_corrupt || is_tomb)) {
1593 ok = SecDbItemDoDelete(old_item, dbconn, error, ^bool (const SecDbAttr *attr) {
1594 return attr->kind == kSecDbRowIdAttr;
1595 });
1596 ok = ok && SecDbItemDoUpdate(duplicate_item, new_item, dbconn, error, ^bool (const SecDbAttr *attr) {
1597 return attr->kind == kSecDbRowIdAttr;
1598 });
1599 CFReleaseNull(localError);
1600 }
1601 });
1602 ok &= query_destroy(query, error);
1603 }
1604 }
1605
1606 if (localError) {
1607 ok = false;
1608 if (error && *error == NULL) {
1609 *error = localError;
1610 localError = NULL;
1611 }
1612 CFReleaseSafe(localError);
1613 }
1614 }
1615
1616 if (ok && !pk_equal && !CFEqualSafe(makeTombstone, kCFBooleanFalse)) {
1617 /* The primary key of new_item is different than that of old_item, we
1618 have been asked to make a tombstone so leave one for the old_item. */
1619 SecDbItemRef tombstone = SecDbItemCopyTombstone(old_item, makeTombstone, error);
1620 ok = tombstone;
1621 if (tombstone) {
1622 ok = (SecDbItemClearRowId(tombstone, error) &&
1623 SecDbItemDoInsert(tombstone, dbconn, error));
1624 CFRelease(tombstone);
1625 }
1626 }
1627
1628 return ok;
1629 }
1630
1631 // Replace the object with a tombstone
1632 bool SecDbItemDelete(SecDbItemRef item, SecDbConnectionRef dbconn, CFBooleanRef makeTombstone, CFErrorRef *error) {
1633 bool ok = false;
1634 if (!CFEqualSafe(makeTombstone, kCFBooleanFalse)) {
1635 SecDbItemRef tombstone = SecDbItemCopyTombstone(item, makeTombstone, error);
1636 if (tombstone) {
1637 ok = SecDbItemDoUpdate(item, tombstone, dbconn, error, ^bool(const SecDbAttr *attr) {
1638 return attr->kind == kSecDbRowIdAttr;
1639 });
1640 CFRelease(tombstone);
1641 }
1642 } else {
1643 ok = SecDbItemDoDelete(item, dbconn, error, ^bool(const SecDbAttr *attr) {
1644 return attr->kind == kSecDbRowIdAttr;
1645 });
1646 }
1647 return ok;
1648 }
1649
1650 CFStringRef SecDbItemCopySelectSQL(SecDbQueryRef query,
1651 bool (^return_attr)(const SecDbAttr *attr),
1652 bool (^use_attr_in_where)(const SecDbAttr *attr),
1653 bool (^add_where_sql)(CFMutableStringRef sql, bool *needWhere)) {
1654 CFMutableStringRef sql = CFStringCreateMutable(kCFAllocatorDefault, 0);
1655 CFStringAppend(sql, CFSTR("SELECT "));
1656 // What are we selecting?
1657 bool needComma = false;
1658 SecDbForEachAttr(query->q_class, attr) {
1659 if (return_attr(attr))
1660 SecDbAppendElement(sql, attr->name, &needComma);
1661 }
1662
1663 // From which table?
1664 CFStringAppend(sql, CFSTR(" FROM "));
1665 CFStringAppend(sql, query->q_class->name);
1666
1667 // And which elements do we want to select
1668 bool needWhere = true;
1669 SecDbForEachAttr(query->q_class, attr) {
1670 if (use_attr_in_where(attr)) {
1671 CFTypeRef value = CFDictionaryGetValue(query->q_item, attr->name);
1672 if (isArray(value)) {
1673 CFArrayRef array = (CFArrayRef)value;
1674 CFIndex length = CFArrayGetCount(array);
1675 if (length > 0) {
1676 CFTypeRef head = CFArrayGetValueAtIndex(array, 0);
1677 if (CFEqualSafe(head, kCFNull)) {
1678 SecDbAppendWhereOrAndNotIn(sql, attr->name, &needWhere, length - 1);
1679 } else {
1680 SecDbAppendWhereOrAndIn(sql, attr->name, &needWhere, length);
1681 }
1682 }
1683 } else {
1684 SecDbAppendWhereOrAndEquals(sql, attr->name, &needWhere);
1685 }
1686 }
1687 }
1688 // Append SQL for access groups and limits.
1689 if (add_where_sql)
1690 add_where_sql(sql, &needWhere);
1691
1692 return sql;
1693 }
1694
1695 static bool SecDbItemSelectBindValue(SecDbQueryRef query, sqlite3_stmt *stmt, int param, const SecDbAttr *attr, CFTypeRef inValue, CFErrorRef *error) {
1696 bool ok = true;
1697 CFTypeRef value = NULL;
1698 if (attr->kind == kSecDbRowIdAttr) {
1699 // TODO: Ignores inValue and uses rowid directly instead HACK should go
1700 value = CFNumberCreate(NULL, kCFNumberSInt64Type, &query->q_row_id);
1701 } else {
1702 value = SecDbAttrCopyValueForDb(attr, inValue, error);
1703 }
1704 ok = ok && value != NULL && SecDbBindObject(stmt, ++param, value, error);
1705 CFReleaseSafe(value);
1706 return ok;
1707 }
1708
1709 bool SecDbItemSelectBind(SecDbQueryRef query, sqlite3_stmt *stmt, CFErrorRef *error,
1710 bool (^use_attr_in_where)(const SecDbAttr *attr),
1711 bool (^bind_added_where)(sqlite3_stmt *stmt, int col)) {
1712 __block bool ok = true;
1713 __block int param = 0;
1714 SecDbForEachAttr(query->q_class, attr) {
1715 if (use_attr_in_where(attr)) {
1716 CFTypeRef value = CFDictionaryGetValue(query->q_item, attr->name);
1717 if (isArray(value)) {
1718 CFArrayRef array = (CFArrayRef)value;
1719 CFRange range = {.location = 0, .length = CFArrayGetCount(array) };
1720 if (range.length > 0) {
1721 CFTypeRef head = CFArrayGetValueAtIndex(array, 0);
1722 if (CFEqualSafe(head, kCFNull)) {
1723 range.length--;
1724 range.location++;
1725 }
1726 }
1727 CFArrayApplyFunction(array, range, apply_block_1, (void (^)(const void *value)) ^(const void *value) {
1728 ok = SecDbItemSelectBindValue(query, stmt, param++, attr, value, error);
1729 });
1730 } else {
1731 ok = SecDbItemSelectBindValue(query, stmt, param++, attr, value, error);
1732 }
1733
1734 if (!ok)
1735 break;
1736 }
1737 }
1738 // TODO: Bind arguments for access groups and limits.
1739 if (bind_added_where)
1740 bind_added_where(stmt, ++param);
1741
1742 return ok;
1743 }
1744
1745 bool SecDbItemSelect(SecDbQueryRef query, SecDbConnectionRef dbconn, CFErrorRef *error,
1746 bool (^return_attr)(const SecDbAttr *attr),
1747 bool (^use_attr_in_where)(const SecDbAttr *attr),
1748 bool (^add_where_sql)(CFMutableStringRef sql, bool *needWhere),
1749 bool (^bind_added_where)(sqlite3_stmt *stmt, int col),
1750 void (^handle_row)(SecDbItemRef item, bool *stop)) {
1751 __block bool ok = true;
1752 if (return_attr == NULL) {
1753 return_attr = ^bool (const SecDbAttr * attr) {
1754 return attr->kind == kSecDbRowIdAttr || attr->kind == kSecDbEncryptedDataAttr || attr->kind == kSecDbSHA1Attr;
1755 };
1756 }
1757
1758 CFStringRef sql = SecDbItemCopySelectSQL(query, return_attr, use_attr_in_where, add_where_sql);
1759 if (sql) {
1760 ok &= SecDbPrepare(dbconn, sql, error, ^(sqlite3_stmt *stmt) {
1761 ok = (SecDbItemSelectBind(query, stmt, error, use_attr_in_where, bind_added_where) &&
1762 SecDbStep(dbconn, stmt, error, ^(bool *stop) {
1763 SecDbItemRef item = SecDbItemCreateWithStatement(kCFAllocatorDefault, query->q_class, stmt, query->q_keybag, error, return_attr);
1764 if (item) {
1765 CFRetainAssign(item->credHandle, query->q_use_cred_handle);
1766 handle_row(item, stop);
1767 CFRelease(item);
1768 } else {
1769 //*stop = true;
1770 //ok = false;
1771 }
1772 }));
1773 });
1774 CFRelease(sql);
1775 } else {
1776 ok = false;
1777 }
1778 return ok;
1779 }
1780