2 * Copyright (c) 2016 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
24 #import <Foundation/Foundation.h>
25 #import "CKKSSQLDatabaseObject.h"
26 #include "keychain/securityd/SecItemServer.h"
28 #import "keychain/ckks/CKKS.h"
29 #import "CKKSKeychainView.h"
31 @interface CKKSSQLResult ()
32 @property (nullable) NSString* stringValue;
35 @implementation CKKSSQLResult
36 - (instancetype)init:(NSString* _Nullable)value
38 if((self = [super init])) {
46 return [self.stringValue boolValue];
49 - (NSInteger)asNSInteger
51 return [self.stringValue integerValue];
54 - (NSString* _Nullable)asString
56 return self.stringValue;
59 - (NSNumber* _Nullable)asNSNumberInteger
61 if(self.stringValue == nil) {
64 return [NSNumber numberWithInteger: [self.stringValue integerValue]];
67 - (NSDate* _Nullable)asISO8601Date
69 if(self.stringValue == nil) {
73 NSISO8601DateFormatter* dateFormat = [[NSISO8601DateFormatter alloc] init];
74 return [dateFormat dateFromString:self.stringValue];
77 - (NSData* _Nullable)asBase64DecodedData
79 if(self.stringValue == nil) {
82 return [[NSData alloc] initWithBase64EncodedString:self.stringValue options:0];
86 @implementation CKKSSQLDatabaseObject
88 + (bool) saveToDatabaseTable: (NSString*) table row: (NSDictionary*) row connection: (SecDbConnectionRef) dbconn error: (NSError * __autoreleasing *) error {
89 __block CFErrorRef cferror = NULL;
91 bool (^doWithConnection)(SecDbConnectionRef) = ^bool (SecDbConnectionRef dbconn) {
92 NSString * columns = [row.allKeys componentsJoinedByString:@", "];
93 NSMutableString * values = [[NSMutableString alloc] init];
94 for(NSUInteger i = 0; i < [row.allKeys count]; i++) {
96 [values appendString: @",?"];
98 [values appendString: @"?"];
102 NSString *sql = [[NSString alloc] initWithFormat: @"INSERT OR REPLACE into %@ (%@) VALUES (%@);", table, columns, values];
104 SecDbPrepare(dbconn, (__bridge CFStringRef) sql, &cferror, ^void (sqlite3_stmt *stmt) {
105 [row.allKeys enumerateObjectsUsingBlock:^(id _Nonnull key, NSUInteger i, BOOL * _Nonnull stop) {
106 SecDbBindObject(stmt, (int)(i+1), (__bridge CFStringRef) row[key], &cferror);
109 SecDbStep(dbconn, stmt, &cferror, ^(bool *stop) {
110 // don't do anything, I guess?
118 doWithConnection(dbconn);
120 kc_with_dbt(true, &cferror, doWithConnection);
123 bool ret = cferror == NULL;
125 SecTranslateError(error, cferror);
130 + (NSString*) makeWhereClause: (NSDictionary*) whereDict {
134 NSMutableString * whereClause = [[NSMutableString alloc] init];
135 __block bool conjunction = false;
136 [whereDict enumerateKeysAndObjectsUsingBlock: ^(NSString* key, NSNumber* value, BOOL* stop) {
138 [whereClause appendFormat: @" WHERE "];
140 [whereClause appendFormat: @" AND "];
143 if([value class] == [CKKSSQLWhereValue class]) {
144 CKKSSQLWhereValue* obj = (CKKSSQLWhereValue*)value;
145 [whereClause appendFormat: @"%@%@(?)", key, CKKSSQLWhereComparatorAsString(obj.sqlOp)];
147 } else if([value class] == [CKKSSQLWhereColumn class]) {
148 CKKSSQLWhereColumn* obj = (CKKSSQLWhereColumn*)value;
149 [whereClause appendFormat: @"%@%@%@",
151 CKKSSQLWhereComparatorAsString(obj.sqlOp),
152 CKKSSQLWhereColumnNameAsString(obj.columnName)];
155 [whereClause appendFormat: @"%@=(?)", key];
163 + (NSString*) groupByClause: (NSArray*) columns {
167 NSMutableString * groupByClause = [[NSMutableString alloc] init];
168 __block bool conjunction = false;
169 [columns enumerateObjectsUsingBlock: ^(NSString* column, NSUInteger i, BOOL* stop) {
171 [groupByClause appendFormat: @" GROUP BY "];
173 [groupByClause appendFormat: @", "];
176 [groupByClause appendFormat: @"%@", column];
180 return groupByClause;
183 + (NSString*)orderByClause: (NSArray*) columns {
184 if(!columns || columns.count == 0u) {
187 NSMutableString * orderByClause = [[NSMutableString alloc] init];
188 __block bool conjunction = false;
189 [columns enumerateObjectsUsingBlock: ^(NSString* column, NSUInteger i, BOOL* stop) {
191 [orderByClause appendFormat: @" ORDER BY "];
193 [orderByClause appendFormat: @", "];
196 [orderByClause appendFormat: @"%@", column];
200 return orderByClause;
203 + (void)bindWhereClause:(sqlite3_stmt*)stmt whereDict:(NSDictionary*)whereDict cferror:(CFErrorRef*)cferror
205 __block int whereObjectsSkipped = 0;
206 [whereDict.allKeys enumerateObjectsUsingBlock:^(id _Nonnull key, NSUInteger i, BOOL * _Nonnull stop) {
207 if([whereDict[key] class] == [CKKSSQLWhereValue class]) {
208 CKKSSQLWhereValue* obj = (CKKSSQLWhereValue*)whereDict[key];
209 SecDbBindObject(stmt, (int)(i+1-whereObjectsSkipped), (__bridge CFStringRef)obj.value, cferror);
210 } else if([whereDict[key] class] == [CKKSSQLWhereColumn class]) {
212 whereObjectsSkipped += 1;
214 SecDbBindObject(stmt, (int)(i+1-whereObjectsSkipped), (__bridge CFStringRef) whereDict[key], cferror);
219 + (bool) deleteFromTable: (NSString*) table where: (NSDictionary*) whereDict connection:(SecDbConnectionRef) dbconn error: (NSError * __autoreleasing *) error {
220 __block CFErrorRef cferror = NULL;
222 bool (^doWithConnection)(SecDbConnectionRef) = ^bool (SecDbConnectionRef dbconn) {
223 NSString* whereClause = [CKKSSQLDatabaseObject makeWhereClause: whereDict];
225 NSString * sql = [[NSString alloc] initWithFormat: @"DELETE FROM %@%@;", table, whereClause];
226 SecDbPrepare(dbconn, (__bridge CFStringRef) sql, &cferror, ^void (sqlite3_stmt *stmt) {
227 [self bindWhereClause:stmt whereDict:whereDict cferror:&cferror];
229 SecDbStep(dbconn, stmt, &cferror, ^(bool *stop) {
236 doWithConnection(dbconn);
238 kc_with_dbt(true, &cferror, doWithConnection);
241 // Deletes finish in a single step, so if we didn't get an error, the delete 'happened'
242 bool status = (cferror == nil);
245 *error = (NSError*) CFBridgingRelease(cferror);
247 CFReleaseNull(cferror);
253 + (bool)queryDatabaseTable:(NSString*)table
254 where:(NSDictionary*)whereDict
255 columns:(NSArray*)names
256 groupBy:(NSArray*)groupColumns
257 orderBy:(NSArray*)orderColumns
259 processRow:(void (^)(NSDictionary<NSString*, CKKSSQLResult*>*)) processRow
260 error:(NSError * __autoreleasing *) error {
261 __block CFErrorRef cferror = NULL;
263 kc_with_dbt(true, &cferror, ^bool (SecDbConnectionRef dbconn) {
264 NSString * columns = [names componentsJoinedByString:@", "];
265 NSString * whereClause = [CKKSSQLDatabaseObject makeWhereClause: whereDict];
266 NSString * groupByClause = [CKKSSQLDatabaseObject groupByClause: groupColumns];
267 NSString * orderByClause = [CKKSSQLDatabaseObject orderByClause: orderColumns];
268 NSString * limitClause = (limit > 0 ? [NSString stringWithFormat:@" LIMIT %lu", limit] : @"");
270 NSString * sql = [[NSString alloc] initWithFormat: @"SELECT %@ FROM %@%@%@%@%@;", columns, table, whereClause, groupByClause, orderByClause, limitClause];
271 SecDbPrepare(dbconn, (__bridge CFStringRef) sql, &cferror, ^void (sqlite3_stmt *stmt) {
272 [self bindWhereClause:stmt whereDict:whereDict cferror:&cferror];
274 SecDbStep(dbconn, stmt, &cferror, ^(bool *stop) {
275 __block NSMutableDictionary<NSString*, CKKSSQLResult*>* row = [[NSMutableDictionary alloc] init];
277 [names enumerateObjectsUsingBlock:^(id _Nonnull name, NSUInteger i, BOOL * _Nonnull stop) {
278 const char * col = (const char *) sqlite3_column_text(stmt, (int)i);
279 row[name] = [[CKKSSQLResult alloc] init:col ? [NSString stringWithUTF8String:col] : nil];
288 bool ret = (cferror == NULL);
289 SecTranslateError(error, cferror);
293 + (NSString *)quotedString:(NSString *)string
295 char *quotedMaxField = sqlite3_mprintf("%q", [string UTF8String]);
296 if (quotedMaxField == NULL) {
299 NSString *rstring = [NSString stringWithUTF8String:quotedMaxField];
300 sqlite3_free(quotedMaxField);
304 + (bool)queryMaxValueForField:(NSString*)maxField
305 inTable:(NSString*)table
306 where:(NSDictionary*)whereDict
307 columns:(NSArray*)names
308 processRow:(void (^)(NSDictionary<NSString*, CKKSSQLResult*>*))processRow
310 __block CFErrorRef cferror = NULL;
312 kc_with_dbt(false, &cferror, ^bool(SecDbConnectionRef dbconn) {
313 NSString *quotedMaxField = [self quotedString:maxField];
314 NSString *quotedTable = [self quotedString:table];
316 NSMutableArray<NSString *>* quotedNames = [NSMutableArray array];
317 for (NSString *element in names) {
318 [quotedNames addObject:[self quotedString:element]];
321 NSString* columns = [[quotedNames componentsJoinedByString:@", "] stringByAppendingFormat:@", %@", quotedMaxField];
322 NSString* whereClause = [CKKSSQLDatabaseObject makeWhereClause:whereDict];
324 NSString* sql = [[NSString alloc] initWithFormat:@"SELECT %@ FROM %@%@", columns, quotedTable, whereClause];
325 SecDbPrepare(dbconn, (__bridge CFStringRef)sql, &cferror, ^(sqlite3_stmt* stmt) {
326 [self bindWhereClause:stmt whereDict:whereDict cferror:&cferror];
328 SecDbStep(dbconn, stmt, &cferror, ^(bool*stop) {
329 __block NSMutableDictionary<NSString*, CKKSSQLResult*>* row = [[NSMutableDictionary alloc] init];
331 [names enumerateObjectsUsingBlock:^(id _Nonnull name, NSUInteger i, BOOL * _Nonnull stop) {
332 const char * col = (const char *) sqlite3_column_text(stmt, (int)i);
333 row[name] = [[CKKSSQLResult alloc] init:col ? [NSString stringWithUTF8String:col] : nil];
343 bool ret = (cferror == NULL);
347 #pragma mark - Instance methods
349 - (bool) saveToDatabase: (NSError * __autoreleasing *) error {
350 return [self saveToDatabaseWithConnection:nil error: error];
353 - (bool) saveToDatabaseWithConnection: (SecDbConnectionRef) conn error: (NSError * __autoreleasing *) error {
354 // Todo: turn this into a transaction
356 NSDictionary* currentWhereClause = [self whereClauseToFindSelf];
358 // First, if we were loaded from the database and the where clause has changed, delete the old record.
359 if(self.originalSelfWhereClause && ![self.originalSelfWhereClause isEqualToDictionary: currentWhereClause]) {
360 secdebug("ckkssql", "Primary key changed; removing old row at %@", self.originalSelfWhereClause);
361 if(![CKKSSQLDatabaseObject deleteFromTable:[[self class] sqlTable] where: self.originalSelfWhereClause connection:conn error: error]) {
366 bool ok = [CKKSSQLDatabaseObject saveToDatabaseTable: [[self class] sqlTable]
367 row: [self sqlValues]
372 secdebug("ckkssql", "Saved %@", self);
374 secdebug("ckkssql", "Couldn't save %@: %@", self, error ? *error : @"unknown");
379 - (bool) deleteFromDatabase: (NSError * __autoreleasing *) error {
380 bool ok = [CKKSSQLDatabaseObject deleteFromTable:[[self class] sqlTable] where: [self whereClauseToFindSelf] connection:nil error: error];
383 secdebug("ckkssql", "Deleted %@", self);
385 secdebug("ckkssql", "Couldn't delete %@: %@", self, error ? *error : @"unknown");
390 + (bool) deleteAll: (NSError * __autoreleasing *) error {
391 bool ok = [CKKSSQLDatabaseObject deleteFromTable:[self sqlTable] where: nil connection:nil error: error];
394 secdebug("ckkssql", "Deleted all %@", self);
396 secdebug("ckkssql", "Couldn't delete all %@: %@", self, error ? *error : @"unknown");
401 + (instancetype) fromDatabaseWhere: (NSDictionary*) whereDict error: (NSError * __autoreleasing *) error {
402 id ret = [self tryFromDatabaseWhere: whereDict error:error];
405 *error = [NSError errorWithDomain:@"securityd"
406 code:errSecItemNotFound
407 userInfo:@{NSLocalizedDescriptionKey:
408 [NSString stringWithFormat: @"%@ does not exist in database where %@", [self class], whereDict]}];
414 + (instancetype _Nullable) tryFromDatabaseWhere: (NSDictionary*) whereDict error: (NSError * __autoreleasing *) error {
415 __block id ret = nil;
417 [CKKSSQLDatabaseObject queryDatabaseTable: [self sqlTable]
419 columns: [self sqlColumns]
423 processRow: ^(NSDictionary<NSString*, CKKSSQLResult*>* row) {
424 ret = [[self fromDatabaseRow: row] memoizeOriginalSelfWhereClause];
431 + (NSArray*) all: (NSError * __autoreleasing *) error {
432 return [self allWhere: nil error:error];
435 + (NSArray*) allWhere: (NSDictionary*) whereDict error: (NSError * __autoreleasing *) error {
436 __block NSMutableArray* items = [[NSMutableArray alloc] init];
438 [CKKSSQLDatabaseObject queryDatabaseTable: [self sqlTable]
440 columns: [self sqlColumns]
444 processRow: ^(NSDictionary<NSString*, CKKSSQLResult*>* row) {
445 [items addObject: [[self fromDatabaseRow: row] memoizeOriginalSelfWhereClause]];
452 + (NSArray*)fetch: (size_t)count error: (NSError * __autoreleasing *) error {
453 return [self fetch: count where:nil orderBy:nil error:error];
456 + (NSArray*)fetch: (size_t)count where:(NSDictionary*)whereDict error: (NSError * __autoreleasing *) error {
457 return [self fetch: count where:whereDict orderBy:nil error:error];
460 + (NSArray*)fetch:(size_t)count
461 where:(NSDictionary*)whereDict
462 orderBy:(NSArray*) orderColumns
463 error:(NSError * __autoreleasing *) error {
464 __block NSMutableArray* items = [[NSMutableArray alloc] init];
466 [CKKSSQLDatabaseObject queryDatabaseTable: [self sqlTable]
468 columns: [self sqlColumns]
471 limit: (ssize_t) count
472 processRow: ^(NSDictionary<NSString*, CKKSSQLResult*>* row) {
473 [items addObject: [[self fromDatabaseRow: row] memoizeOriginalSelfWhereClause]];
480 - (instancetype) memoizeOriginalSelfWhereClause {
481 _originalSelfWhereClause = [self whereClauseToFindSelf];
485 #pragma mark - Subclass methods
487 + (instancetype)fromDatabaseRow:(NSDictionary<NSString *, CKKSSQLResult*>*)row {
488 @throw [NSException exceptionWithName:NSInternalInconsistencyException
489 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
493 + (NSString*) sqlTable {
494 @throw [NSException exceptionWithName:NSInternalInconsistencyException
495 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
499 + (NSArray<NSString*>*) sqlColumns {
500 @throw [NSException exceptionWithName:NSInternalInconsistencyException
501 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
505 - (NSDictionary<NSString*,NSString*>*) sqlValues {
506 @throw [NSException exceptionWithName:NSInternalInconsistencyException
507 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
511 - (NSDictionary<NSString*,NSString*>*) whereClauseToFindSelf {
512 @throw [NSException exceptionWithName:NSInternalInconsistencyException
513 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
517 - (instancetype)copyWithZone:(NSZone *)zone {
518 CKKSSQLDatabaseObject *dbCopy = [[[self class] allocWithZone:zone] init];
519 dbCopy->_originalSelfWhereClause = _originalSelfWhereClause;
524 NSString* CKKSSQLWhereComparatorAsString(CKKSSQLWhereComparator comparator)
527 case CKKSSQLWhereComparatorEquals:
529 case CKKSSQLWhereComparatorNotEquals:
531 case CKKSSQLWhereComparatorGreaterThan:
533 case CKKSSQLWhereComparatorLessThan:
538 NSString* CKKSSQLWhereColumnNameAsString(CKKSSQLWhereColumnName columnName)
541 case CKKSSQLWhereColumnNameUUID:
543 case CKKSSQLWhereColumnNameParentKeyUUID:
544 return @"parentKeyUUID";
548 #pragma mark - CKKSSQLWhereColumn
550 @implementation CKKSSQLWhereColumn
551 - (instancetype)initWithOperation:(CKKSSQLWhereComparator)op columnName:(CKKSSQLWhereColumnName)column
553 if((self = [super init])) {
555 _columnName = column;
559 + (instancetype)op:(CKKSSQLWhereComparator)op column:(CKKSSQLWhereColumnName)columnName
561 return [[CKKSSQLWhereColumn alloc] initWithOperation:op columnName:columnName];
565 #pragma mark - CKKSSQLWhereObject
567 @implementation CKKSSQLWhereValue
568 - (instancetype)initWithOperation:(CKKSSQLWhereComparator)op value:(NSString*)value
570 if((self = [super init])) {
576 + (instancetype)op:(CKKSSQLWhereComparator)op value:(NSString*)value
578 return [[CKKSSQLWhereValue alloc] initWithOperation:op value:value];