]> git.saurik.com Git - apple/security.git/blob - keychain/securityd/SecDbKeychainMetadataKeyStore.m
Security-59306.41.2.tar.gz
[apple/security.git] / keychain / securityd / SecDbKeychainMetadataKeyStore.m
1 /*
2 * Copyright (c) 2018 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 #import "SecDbKeychainMetadataKeyStore.h"
25 #import <dispatch/dispatch.h>
26 #import <utilities/SecAKSWrappers.h>
27 #import <notify.h>
28 #import "SecItemServer.h"
29 #import "SecAKSObjCWrappers.h"
30 #import "sec_action.h"
31
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);
38 });
39 }
40
41 @implementation SecDbKeychainMetadataKeyStore {
42 NSMutableDictionary* _keysDict;
43 dispatch_queue_t _queue;
44 }
45
46 + (void)resetSharedStore
47 {
48 initializeSharedMetadataStoreQueue();
49 dispatch_sync(sharedMetadataStoreQueue, ^{
50 if(sharedStore) {
51 dispatch_sync(sharedStore->_queue, ^{
52 [sharedStore _onQueueDropAllKeys];
53 });
54 }
55 sharedStore = nil;
56 });
57 }
58
59 + (instancetype)sharedStore
60 {
61 __block SecDbKeychainMetadataKeyStore* ret;
62 initializeSharedMetadataStoreQueue();
63 dispatch_sync(sharedMetadataStoreQueue, ^{
64 if(!sharedStore) {
65 sharedStore = [[self alloc] _init];
66 }
67
68 ret = sharedStore;
69 });
70
71 return ret;
72 }
73
74 + (bool)cachingEnabled
75 {
76 return true;
77 }
78
79 - (instancetype)_init
80 {
81 if (self = [super init]) {
82 _keysDict = [[NSMutableDictionary alloc] init];
83 _queue = dispatch_queue_create("SecDbKeychainMetadataKeyStore", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
84 int token = 0;
85 __weak __typeof(self) weakSelf = self;
86 notify_register_dispatch(kUserKeybagStateChangeNotification, &token, _queue, ^(int inToken) {
87 bool locked = true;
88 CFErrorRef error = NULL;
89 if (!SecAKSGetIsLocked(&locked, &error)) {
90 secerror("SecDbKeychainMetadataKeyStore: error getting lock state: %@", error);
91 CFReleaseNull(error);
92 }
93
94 if (locked) {
95 [weakSelf _onQueueDropClassAKeys];
96 }
97 });
98 }
99
100 return self;
101 }
102
103 - (void)dropClassAKeys
104 {
105 dispatch_sync(_queue, ^{
106 [self _onQueueDropClassAKeys];
107 });
108 }
109
110 - (void)_onQueueDropClassAKeys
111 {
112 dispatch_assert_queue(_queue);
113
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;
118 }
119
120 - (void)_onQueueDropAllKeys
121 {
122 dispatch_assert_queue(_queue);
123
124 secnotice("SecDbKeychainMetadataKeyStore", "dropping all metadata keys");
125 [_keysDict removeAllObjects];
126 }
127
128 - (void)_updateActualKeyclassIfNeeded:(keyclass_t)actualKeyclassToWriteBackToDB keyclass:(keyclass_t)keyclass
129 {
130 __block CFErrorRef cfError = NULL;
131
132 secnotice("SecDbKeychainItemV7", "saving actualKeyclass %d for metadata keyclass %d", actualKeyclassToWriteBackToDB, keyclass);
133
134 kc_with_dbt_non_item_tables(true, &cfError, ^bool(SecDbConnectionRef dbt) {
135 __block bool actualKeyWriteBackOk = true;
136
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) {
144 // woohoo
145 });
146 });
147
148 if (actualKeyWriteBackOk) {
149 secnotice("SecDbKeychainItemV7", "successfully saved actualKeyclass %d for metadata keyclass %d", actualKeyclassToWriteBackToDB, keyclass);
150
151 }
152 else {
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);
155 }
156 return actualKeyWriteBackOk;
157 });
158 }
159
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
166 {
167 __block SFAESKey* key = nil;
168 __block NSError* nsErrorLocal = nil;
169 __block CFErrorRef cfError = NULL;
170 static __thread BOOL reentrant = NO;
171
172 NSAssert(!reentrant, @"re-entering -[%@ %@] - that shouldn't happen!", NSStringFromClass(self.class), NSStringFromSelector(_cmd));
173 reentrant = YES;
174
175 keyclass = SecAKSSanitizedKeyclass(keyclass);
176
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];
181
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;
184 #if 0
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);
189 }
190 #endif
191
192 key = allowKeyCaching ? self->_keysDict[@(keyclass)] : nil;
193 if (!key) {
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];
202
203 keyclass_t actualKeyclass = sqlite3_column_int(stmt, 1);
204
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];
208 if (ok) {
209 key = [[SFAESKey alloc] initWithData:unwrappedKeyData specifier:keySpecifier error:&nsErrorLocal];
210
211 if(!key) {
212 if (__security_simulatecrash_enabled()) {
213 os_log_fault(secLogObjForScope("SecDbKeychainItemV7"), "Metadata class key (%d) decrypted, but didn't become a key: %@", keyclass, nsErrorLocal);
214 }
215 }
216
217 if (actualKeyclass == 0) {
218 actualKeyclassToWriteBackToDB = keyclassForUnwrapping;
219 }
220 }
221 #if USE_KEYSTORE
222 else if (actualKeyclass == 0 && keyclass <= key_class_last) {
223 // in this case we might have luck decrypting with a key-rolled keyclass
224 keyclass_t keyrolledKeyclass = keyclass | (key_class_last + 1);
225 secerror("SecDbKeychainItemV7: failed to decrypt metadata key for class %d, but trying keyrolled keyclass (%d); error: %@", keyclass, keyrolledKeyclass, nsErrorLocal);
226
227 // we don't want to pollute subsequent error-handling logic with what happens on our retry
228 // 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
229 NSError* retryError = nil;
230 ok = [SecAKSObjCWrappers aksDecryptWithKeybag:keybag keyclass:keyrolledKeyclass ciphertext:wrappedKeyData outKeyclass:NULL plaintext:unwrappedKeyData error:&retryError];
231
232 if (ok) {
233 secerror("SecDbKeychainItemV7: successfully decrypted metadata key using keyrolled keyclass %d", keyrolledKeyclass);
234 key = [[SFAESKey alloc] initWithData:unwrappedKeyData specifier:keySpecifier error:&retryError];
235
236 if(!key) {
237 if (__security_simulatecrash_enabled()) {
238 os_log_fault(secLogObjForScope("SecDbKeychainItemV7"),
239 "Metadata class key (%d) decrypted using keyrolled keyclass %d, but didn't become a key: %@",
240 keyclass, keyrolledKeyclass, retryError);
241 }
242 nsErrorLocal = retryError;
243 }
244 }
245 else {
246 secerror("SecDbKeychainItemV7: failed to decrypt metadata key with keyrolled keyclass %d; error: %@", keyrolledKeyclass, retryError);
247 }
248 }
249 #endif
250
251 if (ok && key) {
252 if (actualKeyclassToWriteBackToDB > 0) {
253 // check if we have updated this keyclass or not already
254 static NSMutableDictionary* updated = NULL;
255 if (!updated) {
256 updated = [NSMutableDictionary dictionary];
257 }
258 if (!updated[@(keyclass)]) {
259 updated[@(keyclass)] = @YES;
260 dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
261 [self _updateActualKeyclassIfNeeded:actualKeyclassToWriteBackToDB keyclass:keyclass];
262 });
263 }
264 }
265 }
266 else {
267 if (nsErrorLocal && [nsErrorLocal.domain isEqualToString:(__bridge NSString*)kSecErrorDomain] && nsErrorLocal.code == errSecInteractionNotAllowed) {
268 static dispatch_once_t kclockedtoken;
269 static sec_action_t kclockedaction;
270 dispatch_once(&kclockedtoken, ^{
271 kclockedaction = sec_action_create("keychainlockedlogmessage", 1);
272 sec_action_set_handler(kclockedaction, ^{
273 secerror("SecDbKeychainItemV7: failed to decrypt metadata key because the keychain is locked (%d)", (int)errSecInteractionNotAllowed);
274 });
275 });
276 sec_action_perform(kclockedaction);
277 } else {
278 secerror("SecDbKeychainItemV7: failed to decrypt and create metadata key for class %d; error: %@", keyclass, nsErrorLocal);
279
280 // If this error is errSecDecode, then it's failed authentication and likely will forever. Other errors are scary.
281 metadataKeyDoesntAuthenticate = [nsErrorLocal.domain isEqualToString:NSOSStatusErrorDomain] && nsErrorLocal.code == errSecDecode;
282 if(metadataKeyDoesntAuthenticate) {
283 if (__security_simulatecrash_enabled()) {
284 os_log_fault(secLogObjForScope("SecDbKeychainItemV7"), "Metadata class key (%d) failed to decrypt: %@", keyclass, nsErrorLocal);
285 }
286 }
287 }
288 }
289 });
290 });
291
292 bool keyNotYetCreated = ok && !key;
293 bool forceOverwriteBadKey = !key && metadataKeyDoesntAuthenticate && overwriteCorruptKey;
294
295 if (createIfMissing && (keyNotYetCreated || forceOverwriteBadKey)) {
296 // we completed the database query, but no key exists or it's broken - we should create one
297 if(forceOverwriteBadKey) {
298 secerror("SecDbKeychainItemV7: metadata key is irreparably corrupt; throwing away forever");
299 // TODO: track this in LocalKeychainAnalytics
300 }
301
302 ok = true; // Reset 'ok': we have a second chance
303
304 key = [[SFAESKey alloc] initRandomKeyWithSpecifier:keySpecifier error:&nsErrorLocal];
305 keyIsNewlyCreated = true;
306
307 if (key) {
308 NSMutableData* wrappedKey = [NSMutableData dataWithLength:key.keyData.length + 40];
309 keyclass_t outKeyclass = keyclass;
310 ok &= [SecAKSObjCWrappers aksEncryptWithKeybag:keybag keyclass:keyclass plaintext:key.keyData outKeyclass:&outKeyclass ciphertext:wrappedKey error:&nsErrorLocal];
311 if (ok) {
312 secinfo("SecDbKeychainItemV7", "attempting to save new metadata key for keyclass %d with actualKeyclass %d", keyclass, outKeyclass);
313 NSString* insertString = forceOverwriteBadKey ? @"INSERT OR REPLACE" : @"INSERT";
314 sql = [NSString stringWithFormat:@"%@ into metadatakeys (keyclass, actualKeyclass, data) VALUES (?, ?, ?)", insertString];
315 ok &= SecDbPrepare(dbt, (__bridge CFStringRef)sql, &cfError, ^(sqlite3_stmt* stmt) {
316 ok &= SecDbBindInt(stmt, 1, keyclass, &cfError);
317 ok &= SecDbBindInt(stmt, 2, outKeyclass, &cfError);
318 ok &= SecDbBindBlob(stmt, 3, wrappedKey.bytes, wrappedKey.length, SQLITE_TRANSIENT, NULL);
319 ok &= SecDbStep(dbt, stmt, &cfError, ^(bool *stop) {
320 // woohoo
321 });
322 });
323
324 if (ok) {
325 secnotice("SecDbKeychainItemV7", "successfully saved new metadata key for keyclass %d", keyclass);
326 }
327 else {
328 secerror("SecDbKeychainItemV7: failed to save new metadata key for keyclass %d - probably there is already one in the database: %@", keyclass, cfError);
329 }
330 } else {
331 secerror("SecDbKeychainItemV7: unable to encrypt new metadata key(%d) with keybag(%d): %@", keyclass, keybag, nsErrorLocal);
332 }
333 }
334 else {
335 ok = false;
336 }
337 } else if(!key) {
338 // No key, but we're not supposed to make one. Make an error if one doesn't yet exist.
339 ok = false;
340 if(!nsErrorLocal) {
341 nsErrorLocal = [NSError errorWithDomain:(id)kSecErrorDomain code:errSecDecode userInfo:@{NSLocalizedDescriptionKey: @"Unable to find or create a suitable metadata key"}];
342 }
343 }
344
345 return ok;
346 });
347
348 if (ok && key) {
349 // We can't cache a newly-created key, just in case this db transaction is rolled back and we lose the persisted key.
350 // Don't worry, we'll cache it as soon as it's used again.
351 if (allowKeyCaching && !keyIsNewlyCreated) {
352 self->_keysDict[@(keyclass)] = key;
353 __weak __typeof(self) weakSelf = self;
354 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * 5 * NSEC_PER_SEC)), self->_queue, ^{
355 [weakSelf _onQueueDropClassAKeys];
356 });
357 }
358 }
359 else {
360 key = nil;
361 }
362 }
363 });
364
365 reentrant = NO;
366
367 if (error && nsErrorLocal) {
368 *error = nsErrorLocal;
369 CFReleaseNull(cfError);
370 }
371 else {
372 BridgeCFErrorToNSErrorOut(error, cfError);
373 }
374
375 return key;
376 }
377
378 @end