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] == [CKKSSQLWhereObject class]) {
144 // Use this string verbatim
145 CKKSSQLWhereObject* whereob = (CKKSSQLWhereObject*) value;
146 [whereClause appendFormat: @"%@%@%@", key, whereob.sqlOp, whereob.contents];
148 [whereClause appendFormat: @"%@=(?)", key];
156 + (NSString*) groupByClause: (NSArray*) columns {
160 NSMutableString * groupByClause = [[NSMutableString alloc] init];
161 __block bool conjunction = false;
162 [columns enumerateObjectsUsingBlock: ^(NSString* column, NSUInteger i, BOOL* stop) {
164 [groupByClause appendFormat: @" GROUP BY "];
166 [groupByClause appendFormat: @", "];
169 [groupByClause appendFormat: @"%@", column];
173 return groupByClause;
176 + (NSString*)orderByClause: (NSArray*) columns {
177 if(!columns || columns.count == 0u) {
180 NSMutableString * orderByClause = [[NSMutableString alloc] init];
181 __block bool conjunction = false;
182 [columns enumerateObjectsUsingBlock: ^(NSString* column, NSUInteger i, BOOL* stop) {
184 [orderByClause appendFormat: @" ORDER BY "];
186 [orderByClause appendFormat: @", "];
189 [orderByClause appendFormat: @"%@", column];
193 return orderByClause;
196 + (bool) deleteFromTable: (NSString*) table where: (NSDictionary*) whereDict connection:(SecDbConnectionRef) dbconn error: (NSError * __autoreleasing *) error {
197 __block CFErrorRef cferror = NULL;
199 bool (^doWithConnection)(SecDbConnectionRef) = ^bool (SecDbConnectionRef dbconn) {
200 NSString* whereClause = [CKKSSQLDatabaseObject makeWhereClause: whereDict];
202 NSString * sql = [[NSString alloc] initWithFormat: @"DELETE FROM %@%@;", table, whereClause];
203 SecDbPrepare(dbconn, (__bridge CFStringRef) sql, &cferror, ^void (sqlite3_stmt *stmt) {
204 __block int whereObjectsSkipped = 0;
206 [whereDict.allKeys enumerateObjectsUsingBlock:^(id _Nonnull key, NSUInteger i, BOOL * _Nonnull stop) {
207 if([whereDict[key] class] != [CKKSSQLWhereObject class]) {
208 SecDbBindObject(stmt, (int)(i+1-whereObjectsSkipped), (__bridge CFStringRef) whereDict[key], &cferror);
210 whereObjectsSkipped += 1;
214 SecDbStep(dbconn, stmt, &cferror, ^(bool *stop) {
221 doWithConnection(dbconn);
223 kc_with_dbt(true, &cferror, doWithConnection);
226 // Deletes finish in a single step, so if we didn't get an error, the delete 'happened'
227 bool status = (cferror == nil);
230 *error = (NSError*) CFBridgingRelease(cferror);
232 CFReleaseNull(cferror);
238 + (bool)queryDatabaseTable:(NSString*)table
239 where:(NSDictionary*)whereDict
240 columns:(NSArray*)names
241 groupBy:(NSArray*)groupColumns
242 orderBy:(NSArray*)orderColumns
244 processRow:(void (^)(NSDictionary<NSString*, CKKSSQLResult*>*)) processRow
245 error:(NSError * __autoreleasing *) error {
246 __block CFErrorRef cferror = NULL;
248 kc_with_dbt(true, &cferror, ^bool (SecDbConnectionRef dbconn) {
249 NSString * columns = [names componentsJoinedByString:@", "];
250 NSString * whereClause = [CKKSSQLDatabaseObject makeWhereClause: whereDict];
251 NSString * groupByClause = [CKKSSQLDatabaseObject groupByClause: groupColumns];
252 NSString * orderByClause = [CKKSSQLDatabaseObject orderByClause: orderColumns];
253 NSString * limitClause = (limit > 0 ? [NSString stringWithFormat:@" LIMIT %lu", limit] : @"");
255 NSString * sql = [[NSString alloc] initWithFormat: @"SELECT %@ FROM %@%@%@%@%@;", columns, table, whereClause, groupByClause, orderByClause, limitClause];
256 SecDbPrepare(dbconn, (__bridge CFStringRef) sql, &cferror, ^void (sqlite3_stmt *stmt) {
257 __block int whereObjectsSkipped = 0;
258 [whereDict.allKeys enumerateObjectsUsingBlock:^(id _Nonnull key, NSUInteger i, BOOL * _Nonnull stop) {
259 if([whereDict[key] class] != [CKKSSQLWhereObject class]) {
260 SecDbBindObject(stmt, (int)(i+1-whereObjectsSkipped), (__bridge CFStringRef) whereDict[key], &cferror);
262 whereObjectsSkipped += 1;
266 SecDbStep(dbconn, stmt, &cferror, ^(bool *stop) {
267 __block NSMutableDictionary<NSString*, CKKSSQLResult*>* row = [[NSMutableDictionary alloc] init];
269 [names enumerateObjectsUsingBlock:^(id _Nonnull name, NSUInteger i, BOOL * _Nonnull stop) {
270 const char * col = (const char *) sqlite3_column_text(stmt, (int)i);
271 row[name] = [[CKKSSQLResult alloc] init:col ? [NSString stringWithUTF8String:col] : nil];
280 bool ret = (cferror == NULL);
281 SecTranslateError(error, cferror);
285 + (NSString *)quotedString:(NSString *)string
287 char *quotedMaxField = sqlite3_mprintf("%q", [string UTF8String]);
288 if (quotedMaxField == NULL) {
291 NSString *rstring = [NSString stringWithUTF8String:quotedMaxField];
292 sqlite3_free(quotedMaxField);
296 + (bool)queryMaxValueForField:(NSString*)maxField
297 inTable:(NSString*)table
298 where:(NSDictionary*)whereDict
299 columns:(NSArray*)names
300 processRow:(void (^)(NSDictionary<NSString*, CKKSSQLResult*>*))processRow
302 __block CFErrorRef cferror = NULL;
304 kc_with_dbt(false, &cferror, ^bool(SecDbConnectionRef dbconn) {
305 NSString *quotedMaxField = [self quotedString:maxField];
306 NSString *quotedTable = [self quotedString:table];
308 NSMutableArray<NSString *>* quotedNames = [NSMutableArray array];
309 for (NSString *element in names) {
310 [quotedNames addObject:[self quotedString:element]];
313 NSString* columns = [[quotedNames componentsJoinedByString:@", "] stringByAppendingFormat:@", %@", quotedMaxField];
314 NSString* whereClause = [CKKSSQLDatabaseObject makeWhereClause:whereDict];
316 NSString* sql = [[NSString alloc] initWithFormat:@"SELECT %@ FROM %@%@", columns, quotedTable, whereClause];
317 SecDbPrepare(dbconn, (__bridge CFStringRef)sql, &cferror, ^(sqlite3_stmt* stmt) {
318 [whereDict.allKeys enumerateObjectsUsingBlock:^(id _Nonnull key, NSUInteger i, BOOL* _Nonnull stop) {
319 if ([whereDict[key] class] != [CKKSSQLWhereObject class]) {
320 SecDbBindObject(stmt, (int)(i+1), (__bridge CFStringRef) whereDict[key], &cferror);
324 SecDbStep(dbconn, stmt, &cferror, ^(bool*stop) {
325 __block NSMutableDictionary<NSString*, CKKSSQLResult*>* row = [[NSMutableDictionary alloc] init];
327 [names enumerateObjectsUsingBlock:^(id _Nonnull name, NSUInteger i, BOOL * _Nonnull stop) {
328 const char * col = (const char *) sqlite3_column_text(stmt, (int)i);
329 row[name] = [[CKKSSQLResult alloc] init:col ? [NSString stringWithUTF8String:col] : nil];
339 bool ret = (cferror == NULL);
343 #pragma mark - Instance methods
345 - (bool) saveToDatabase: (NSError * __autoreleasing *) error {
346 return [self saveToDatabaseWithConnection:nil error: error];
349 - (bool) saveToDatabaseWithConnection: (SecDbConnectionRef) conn error: (NSError * __autoreleasing *) error {
350 // Todo: turn this into a transaction
352 NSDictionary* currentWhereClause = [self whereClauseToFindSelf];
354 // First, if we were loaded from the database and the where clause has changed, delete the old record.
355 if(self.originalSelfWhereClause && ![self.originalSelfWhereClause isEqualToDictionary: currentWhereClause]) {
356 secdebug("ckkssql", "Primary key changed; removing old row at %@", self.originalSelfWhereClause);
357 if(![CKKSSQLDatabaseObject deleteFromTable:[[self class] sqlTable] where: self.originalSelfWhereClause connection:conn error: error]) {
362 bool ok = [CKKSSQLDatabaseObject saveToDatabaseTable: [[self class] sqlTable]
363 row: [self sqlValues]
368 secdebug("ckkssql", "Saved %@", self);
370 secdebug("ckkssql", "Couldn't save %@: %@", self, error ? *error : @"unknown");
375 - (bool) deleteFromDatabase: (NSError * __autoreleasing *) error {
376 bool ok = [CKKSSQLDatabaseObject deleteFromTable:[[self class] sqlTable] where: [self whereClauseToFindSelf] connection:nil error: error];
379 secdebug("ckkssql", "Deleted %@", self);
381 secdebug("ckkssql", "Couldn't delete %@: %@", self, error ? *error : @"unknown");
386 + (bool) deleteAll: (NSError * __autoreleasing *) error {
387 bool ok = [CKKSSQLDatabaseObject deleteFromTable:[self sqlTable] where: nil connection:nil error: error];
390 secdebug("ckkssql", "Deleted all %@", self);
392 secdebug("ckkssql", "Couldn't delete all %@: %@", self, error ? *error : @"unknown");
397 + (instancetype) fromDatabaseWhere: (NSDictionary*) whereDict error: (NSError * __autoreleasing *) error {
398 id ret = [self tryFromDatabaseWhere: whereDict error:error];
401 *error = [NSError errorWithDomain:@"securityd"
402 code:errSecItemNotFound
403 userInfo:@{NSLocalizedDescriptionKey:
404 [NSString stringWithFormat: @"%@ does not exist in database where %@", [self class], whereDict]}];
410 + (instancetype _Nullable) tryFromDatabaseWhere: (NSDictionary*) whereDict error: (NSError * __autoreleasing *) error {
411 __block id ret = nil;
413 [CKKSSQLDatabaseObject queryDatabaseTable: [self sqlTable]
415 columns: [self sqlColumns]
419 processRow: ^(NSDictionary<NSString*, CKKSSQLResult*>* row) {
420 ret = [[self fromDatabaseRow: row] memoizeOriginalSelfWhereClause];
427 + (NSArray*) all: (NSError * __autoreleasing *) error {
428 return [self allWhere: nil error:error];
431 + (NSArray*) allWhere: (NSDictionary*) whereDict error: (NSError * __autoreleasing *) error {
432 __block NSMutableArray* items = [[NSMutableArray alloc] init];
434 [CKKSSQLDatabaseObject queryDatabaseTable: [self sqlTable]
436 columns: [self sqlColumns]
440 processRow: ^(NSDictionary<NSString*, CKKSSQLResult*>* row) {
441 [items addObject: [[self fromDatabaseRow: row] memoizeOriginalSelfWhereClause]];
448 + (NSArray*)fetch: (size_t)count error: (NSError * __autoreleasing *) error {
449 return [self fetch: count where:nil orderBy:nil error:error];
452 + (NSArray*)fetch: (size_t)count where:(NSDictionary*)whereDict error: (NSError * __autoreleasing *) error {
453 return [self fetch: count where:whereDict orderBy:nil error:error];
456 + (NSArray*)fetch:(size_t)count
457 where:(NSDictionary*)whereDict
458 orderBy:(NSArray*) orderColumns
459 error:(NSError * __autoreleasing *) error {
460 __block NSMutableArray* items = [[NSMutableArray alloc] init];
462 [CKKSSQLDatabaseObject queryDatabaseTable: [self sqlTable]
464 columns: [self sqlColumns]
467 limit: (ssize_t) count
468 processRow: ^(NSDictionary<NSString*, CKKSSQLResult*>* row) {
469 [items addObject: [[self fromDatabaseRow: row] memoizeOriginalSelfWhereClause]];
476 - (instancetype) memoizeOriginalSelfWhereClause {
477 _originalSelfWhereClause = [self whereClauseToFindSelf];
481 #pragma mark - Subclass methods
483 + (instancetype)fromDatabaseRow:(NSDictionary<NSString *, CKKSSQLResult*>*)row {
484 @throw [NSException exceptionWithName:NSInternalInconsistencyException
485 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
489 + (NSString*) sqlTable {
490 @throw [NSException exceptionWithName:NSInternalInconsistencyException
491 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
495 + (NSArray<NSString*>*) sqlColumns {
496 @throw [NSException exceptionWithName:NSInternalInconsistencyException
497 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
501 - (NSDictionary<NSString*,NSString*>*) sqlValues {
502 @throw [NSException exceptionWithName:NSInternalInconsistencyException
503 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
507 - (NSDictionary<NSString*,NSString*>*) whereClauseToFindSelf {
508 @throw [NSException exceptionWithName:NSInternalInconsistencyException
509 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
513 - (instancetype)copyWithZone:(NSZone *)zone {
514 CKKSSQLDatabaseObject *dbCopy = [[[self class] allocWithZone:zone] init];
515 dbCopy->_originalSelfWhereClause = _originalSelfWhereClause;
520 #pragma mark - CKKSSQLWhereObject
522 @implementation CKKSSQLWhereObject
523 - (instancetype)initWithOperation:(NSString*)op string: (NSString*) str {
524 if(self = [super init]) {
531 + (instancetype)op:(NSString*) op string: (NSString*) str {
532 return [[CKKSSQLWhereObject alloc] initWithOperation:op string: str];
535 + (instancetype)op:(NSString*) op stringValue: (NSString*) str {
536 return [[CKKSSQLWhereObject alloc] initWithOperation:op string:[NSString stringWithFormat:@"'%@'", str]];