2 * Copyright (c) 2018 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 "SecDbKeychainMetadataKeyStore.h"
25 #import <dispatch/dispatch.h>
26 #import <utilities/SecAKSWrappers.h>
28 #import "SecItemServer.h"
29 #import "SecAKSObjCWrappers.h"
30 #import "sec_action.h"
32 static SecDbKeychainMetadataKeyStore* sharedStore = nil;
33 static dispatch_queue_t sharedMetadataStoreQueue;
34 static void initializeSharedMetadataStoreQueue(void) {
35 static dispatch_once_t onceToken;
36 dispatch_once(&onceToken, ^{
37 sharedMetadataStoreQueue = dispatch_queue_create("metadata_store", DISPATCH_QUEUE_SERIAL);
41 @implementation SecDbKeychainMetadataKeyStore {
42 NSMutableDictionary* _keysDict;
43 dispatch_queue_t _queue;
46 + (void)resetSharedStore
48 initializeSharedMetadataStoreQueue();
49 dispatch_sync(sharedMetadataStoreQueue, ^{
51 dispatch_sync(sharedStore->_queue, ^{
52 [sharedStore _onQueueDropAllKeys];
59 + (instancetype)sharedStore
61 __block SecDbKeychainMetadataKeyStore* ret;
62 initializeSharedMetadataStoreQueue();
63 dispatch_sync(sharedMetadataStoreQueue, ^{
65 sharedStore = [[self alloc] _init];
74 + (bool)cachingEnabled
81 if (self = [super init]) {
82 _keysDict = [[NSMutableDictionary alloc] init];
83 _queue = dispatch_queue_create("SecDbKeychainMetadataKeyStore", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
85 __weak __typeof(self) weakSelf = self;
86 notify_register_dispatch(kUserKeybagStateChangeNotification, &token, _queue, ^(int inToken) {
88 CFErrorRef error = NULL;
89 if (!SecAKSGetIsLocked(&locked, &error)) {
90 secerror("SecDbKeychainMetadataKeyStore: error getting lock state: %@", error);
95 [weakSelf _onQueueDropClassAKeys];
103 - (void)dropClassAKeys
105 dispatch_sync(_queue, ^{
106 [self _onQueueDropClassAKeys];
110 - (void)_onQueueDropClassAKeys
112 dispatch_assert_queue(_queue);
114 secnotice("SecDbKeychainMetadataKeyStore", "dropping class A metadata keys");
115 _keysDict[@(key_class_ak)] = nil;
116 _keysDict[@(key_class_aku)] = nil;
117 _keysDict[@(key_class_akpu)] = nil;
120 - (void)_onQueueDropAllKeys
122 dispatch_assert_queue(_queue);
124 secnotice("SecDbKeychainMetadataKeyStore", "dropping all metadata keys");
125 [_keysDict removeAllObjects];
128 - (void)_updateActualKeyclassIfNeeded:(keyclass_t)actualKeyclassToWriteBackToDB keyclass:(keyclass_t)keyclass
130 __block CFErrorRef cfError = NULL;
132 secnotice("SecDbKeychainItemV7", "saving actualKeyclass %d for metadata keyclass %d", actualKeyclassToWriteBackToDB, keyclass);
134 kc_with_dbt_non_item_tables(true, &cfError, ^bool(SecDbConnectionRef dbt) {
135 __block bool actualKeyWriteBackOk = true;
137 // we did not find an actualKeyclass entry in the db, so let's add one in now.
138 NSString *sql = @"UPDATE metadatakeys SET actualKeyclass = ? WHERE keyclass = ? AND actualKeyclass IS NULL";
139 __block CFErrorRef actualKeyWriteBackError = NULL;
140 actualKeyWriteBackOk &= SecDbPrepare(dbt, (__bridge CFStringRef)sql, &actualKeyWriteBackError, ^(sqlite3_stmt* stmt) {
141 actualKeyWriteBackOk &= SecDbBindInt(stmt, 1, actualKeyclassToWriteBackToDB, &actualKeyWriteBackError);
142 actualKeyWriteBackOk &= SecDbBindInt(stmt, 2, keyclass, &actualKeyWriteBackError);
143 actualKeyWriteBackOk &= SecDbStep(dbt, stmt, &actualKeyWriteBackError, ^(bool* stop) {
148 if (actualKeyWriteBackOk) {
149 secnotice("SecDbKeychainItemV7", "successfully saved actualKeyclass %d for metadata keyclass %d", actualKeyclassToWriteBackToDB, keyclass);
153 // we can always try this again in the future if it failed
154 secerror("SecDbKeychainItemV7: failed to save actualKeyclass %d for metadata keyclass %d; error: %@", actualKeyclassToWriteBackToDB, keyclass, actualKeyWriteBackError);
156 return actualKeyWriteBackOk;
160 - (SFAESKey*)keyForKeyclass:(keyclass_t)keyclass
161 keybag:(keybag_handle_t)keybag
162 keySpecifier:(SFAESKeySpecifier*)keySpecifier
163 createKeyIfMissing:(bool)createIfMissing
164 overwriteCorruptKey:(bool)overwriteCorruptKey
165 error:(NSError**)error
167 __block SFAESKey* key = nil;
168 __block NSError* nsErrorLocal = nil;
169 __block CFErrorRef cfError = NULL;
170 static __thread BOOL reentrant = NO;
172 NSAssert(!reentrant, @"re-entering -[%@ %@] - that shouldn't happen!", NSStringFromClass(self.class), NSStringFromSelector(_cmd));
175 keyclass = SecAKSSanitizedKeyclass(keyclass);
177 dispatch_sync(_queue, ^{
178 // if we think we're locked, it's possible AKS will still give us access to keys, such as during backup,
179 // but we should force AKS to be the truth and not used cached class A keys while locked
180 bool allowKeyCaching = [SecDbKeychainMetadataKeyStore cachingEnabled];
182 // However, we must not cache a newly-created key, just in case someone above us in the stack rolls back our database transaction and the stored key is lost.
183 __block bool keyIsNewlyCreated = false;
185 // <rdar://problem/37523001> Fix keychain lock state check to be both secure and fast for EDU mode
186 if (![SecDbKeychainItemV7 isKeychainUnlocked]) {
187 [self _onQueueDropClassAKeys];
188 allowKeyCaching = !(keyclass == key_class_ak || keyclass == key_class_aku || keyclass == key_class_akpu);
192 key = allowKeyCaching ? self->_keysDict[@(keyclass)] : nil;
194 __block bool ok = true;
195 __block bool metadataKeyDoesntAuthenticate = false;
196 ok &= kc_with_dbt_non_item_tables(createIfMissing, &cfError, ^bool(SecDbConnectionRef dbt) {
197 __block NSString* sql = [NSString stringWithFormat:@"SELECT data, actualKeyclass FROM metadatakeys WHERE keyclass = %d", keyclass];
198 ok &= SecDbPrepare(dbt, (__bridge CFStringRef)sql, &cfError, ^(sqlite3_stmt *stmt) {
199 ok &= SecDbStep(dbt, stmt, &cfError, ^(bool *stop) {
200 NSData* wrappedKeyData = [[NSData alloc] initWithBytes:sqlite3_column_blob(stmt, 0) length:sqlite3_column_bytes(stmt, 0)];
201 NSMutableData* unwrappedKeyData = [NSMutableData dataWithLength:wrappedKeyData.length];
203 keyclass_t actualKeyclass = sqlite3_column_int(stmt, 1);
205 keyclass_t actualKeyclassToWriteBackToDB = 0;
206 keyclass_t keyclassForUnwrapping = actualKeyclass == 0 ? keyclass : actualKeyclass;
207 ok &= [SecAKSObjCWrappers aksDecryptWithKeybag:keybag keyclass:keyclassForUnwrapping ciphertext:wrappedKeyData outKeyclass:NULL plaintext:unwrappedKeyData error:&nsErrorLocal];
209 key = [[SFAESKey alloc] initWithData:unwrappedKeyData specifier:keySpecifier error:&nsErrorLocal];
212 os_log_fault(secLogObjForScope("SecDbKeychainItemV7"), "Metadata class key (%d) decrypted, but didn't become a key: %@", keyclass, nsErrorLocal);
215 if (actualKeyclass == 0) {
216 actualKeyclassToWriteBackToDB = keyclassForUnwrapping;
220 else if (actualKeyclass == 0 && keyclass <= key_class_last) {
221 // in this case we might have luck decrypting with a key-rolled keyclass
222 keyclass_t keyrolledKeyclass = keyclass | (key_class_last + 1);
223 secerror("SecDbKeychainItemV7: failed to decrypt metadata key for class %d, but trying keyrolled keyclass (%d); error: %@", keyclass, keyrolledKeyclass, nsErrorLocal);
225 // we don't want to pollute subsequent error-handling logic with what happens on our retry
226 // we'll give it a shot, and if it works, great - if it doesn't work, we'll just report that error in the log and move on
227 NSError* retryError = nil;
228 ok = [SecAKSObjCWrappers aksDecryptWithKeybag:keybag keyclass:keyrolledKeyclass ciphertext:wrappedKeyData outKeyclass:NULL plaintext:unwrappedKeyData error:&retryError];
231 secerror("SecDbKeychainItemV7: successfully decrypted metadata key using keyrolled keyclass %d", keyrolledKeyclass);
232 key = [[SFAESKey alloc] initWithData:unwrappedKeyData specifier:keySpecifier error:&retryError];
235 os_log_fault(secLogObjForScope("SecDbKeychainItemV7"), "Metadata class key (%d) decrypted using keyrolled keyclass %d, but didn't become a key: %@", keyclass, keyrolledKeyclass, retryError);
236 nsErrorLocal = retryError;
240 secerror("SecDbKeychainItemV7: failed to decrypt metadata key with keyrolled keyclass %d; error: %@", keyrolledKeyclass, retryError);
246 if (actualKeyclassToWriteBackToDB > 0) {
247 // check if we have updated this keyclass or not already
248 static NSMutableDictionary* updated = NULL;
250 updated = [NSMutableDictionary dictionary];
252 if (!updated[@(keyclass)]) {
253 updated[@(keyclass)] = @YES;
254 dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
255 [self _updateActualKeyclassIfNeeded:actualKeyclassToWriteBackToDB keyclass:keyclass];
261 if (nsErrorLocal && [nsErrorLocal.domain isEqualToString:(__bridge NSString*)kSecErrorDomain] && nsErrorLocal.code == errSecInteractionNotAllowed) {
262 static dispatch_once_t kclockedtoken;
263 static sec_action_t kclockedaction;
264 dispatch_once(&kclockedtoken, ^{
265 kclockedaction = sec_action_create("keychainlockedlogmessage", 1);
266 sec_action_set_handler(kclockedaction, ^{
267 secerror("SecDbKeychainItemV7: failed to decrypt metadata key because the keychain is locked (%d)", (int)errSecInteractionNotAllowed);
270 sec_action_perform(kclockedaction);
272 secerror("SecDbKeychainItemV7: failed to decrypt and create metadata key for class %d; error: %@", keyclass, nsErrorLocal);
274 // If this error is errSecDecode, then it's failed authentication and likely will forever. Other errors are scary.
275 metadataKeyDoesntAuthenticate = [nsErrorLocal.domain isEqualToString:NSOSStatusErrorDomain] && nsErrorLocal.code == errSecDecode;
276 if(metadataKeyDoesntAuthenticate) {
277 os_log_fault(secLogObjForScope("SecDbKeychainItemV7"), "Metadata class key (%d) failed to decrypt: %@", keyclass, nsErrorLocal);
284 bool keyNotYetCreated = ok && !key;
285 bool forceOverwriteBadKey = !key && metadataKeyDoesntAuthenticate && overwriteCorruptKey;
287 if (createIfMissing && (keyNotYetCreated || forceOverwriteBadKey)) {
288 // we completed the database query, but no key exists or it's broken - we should create one
289 if(forceOverwriteBadKey) {
290 secerror("SecDbKeychainItemV7: metadata key is irreparably corrupt; throwing away forever");
291 // TODO: track this in LocalKeychainAnalytics
294 ok = true; // Reset 'ok': we have a second chance
296 key = [[SFAESKey alloc] initRandomKeyWithSpecifier:keySpecifier error:&nsErrorLocal];
297 keyIsNewlyCreated = true;
300 NSMutableData* wrappedKey = [NSMutableData dataWithLength:key.keyData.length + 40];
301 keyclass_t outKeyclass = keyclass;
302 ok &= [SecAKSObjCWrappers aksEncryptWithKeybag:keybag keyclass:keyclass plaintext:key.keyData outKeyclass:&outKeyclass ciphertext:wrappedKey error:&nsErrorLocal];
304 secinfo("SecDbKeychainItemV7", "attempting to save new metadata key for keyclass %d with actualKeyclass %d", keyclass, outKeyclass);
305 NSString* insertString = forceOverwriteBadKey ? @"INSERT OR REPLACE" : @"INSERT";
306 sql = [NSString stringWithFormat:@"%@ into metadatakeys (keyclass, actualKeyclass, data) VALUES (?, ?, ?)", insertString];
307 ok &= SecDbPrepare(dbt, (__bridge CFStringRef)sql, &cfError, ^(sqlite3_stmt* stmt) {
308 ok &= SecDbBindInt(stmt, 1, keyclass, &cfError);
309 ok &= SecDbBindInt(stmt, 2, outKeyclass, &cfError);
310 ok &= SecDbBindBlob(stmt, 3, wrappedKey.bytes, wrappedKey.length, SQLITE_TRANSIENT, NULL);
311 ok &= SecDbStep(dbt, stmt, &cfError, ^(bool *stop) {
317 secnotice("SecDbKeychainItemV7", "successfully saved new metadata key for keyclass %d", keyclass);
320 secerror("SecDbKeychainItemV7: failed to save new metadata key for keyclass %d - probably there is already one in the database: %@", keyclass, cfError);
323 secerror("SecDbKeychainItemV7: unable to encrypt new metadata key(%d) with keybag(%d): %@", keyclass, keybag, nsErrorLocal);
330 // No key, but we're not supposed to make one. Make an error if one doesn't yet exist.
333 nsErrorLocal = [NSError errorWithDomain:(id)kSecErrorDomain code:errSecDecode userInfo:@{NSLocalizedDescriptionKey: @"Unable to find or create a suitable metadata key"}];
341 // We can't cache a newly-created key, just in case this db transaction is rolled back and we lose the persisted key.
342 // Don't worry, we'll cache it as soon as it's used again.
343 if (allowKeyCaching && !keyIsNewlyCreated) {
344 self->_keysDict[@(keyclass)] = key;
345 __weak __typeof(self) weakSelf = self;
346 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * 5 * NSEC_PER_SEC)), self->_queue, ^{
347 [weakSelf _onQueueDropClassAKeys];
359 if (error && nsErrorLocal) {
360 *error = nsErrorLocal;
361 CFReleaseNull(cfError);
364 BridgeCFErrorToNSErrorOut(error, cfError);