2 * Copyright (c) 2017 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 "SecDbKeychainItemV7.h"
25 #import "SecKeybagSupport.h"
26 #import "SecItemServer.h"
27 #import "SecAccessControl.h"
28 #import "SecDbKeychainSerializedItemV7.h"
29 #import "SecDbKeychainSerializedAKSWrappedKey.h"
30 #import "SecDbKeychainSerializedMetadata.h"
31 #import "SecDbKeychainSerializedSecretData.h"
32 #import <dispatch/dispatch.h>
33 #import <utilities/SecAKSWrappers.h>
34 #import "SecAKSObjCWrappers.h"
35 #import <utilities/der_plist.h>
36 #import <SecurityFoundation/SFEncryptionOperation.h>
37 #import <SecurityFoundation/SFKey_Private.h>
38 #import <SecurityFoundation/SFCryptoServicesErrors.h>
40 #import <Foundation/NSKeyedArchiver_Private.h>
42 #if USE_KEYSTORE && __has_include(<Kernel/IOKit/crypto/AppleKeyStoreDefs.h>)
43 #import <Kernel/IOKit/crypto/AppleKeyStoreDefs.h>
46 #import "SecDbKeychainMetadataKeyStore.h"
47 #import "SecDbBackupManager.h"
49 #define KEYCHAIN_ITEM_PADDING_MODULUS 20
51 // See corresponding "reasonable size" client-side limit(s) in SecItem.
53 // Generally the secret data dictionary contains a single key
54 // with the client's password/key NSData therein, so 4k feels extremely luxurious
55 #define REASONABLE_SECRET_DATA_SIZE 4096
57 // This feels similarly generous, but let's find out
58 #define REASONABLE_METADATA_SIZE 2048
60 NSString* const SecDbKeychainErrorDomain = @"SecDbKeychainErrorDomain";
61 const NSInteger SecDbKeychainErrorDeserializationFailed = 1;
63 static NSString* const SecDBTamperCheck = @"TamperCheck";
65 static NSDictionary* dictionaryFromDERData(NSData* data)
67 NSDictionary* dict = (__bridge_transfer NSDictionary*)CFPropertyListCreateWithDERData(NULL, (__bridge CFDataRef)data, 0, NULL, NULL);
68 return [dict isKindOfClass:[NSDictionary class]] ? dict : nil;
71 typedef NS_ENUM(uint32_t, SecDbKeychainAKSWrappedKeyType) {
72 SecDbKeychainAKSWrappedKeyTypeRegular,
73 SecDbKeychainAKSWrappedKeyTypeRefKey
76 @interface SecDbKeychainAKSWrappedKey : NSObject
78 @property (readonly) NSData* wrappedKey;
79 @property (readonly) NSData* refKeyBlob;
80 @property (readonly) SecDbKeychainAKSWrappedKeyType type;
82 @property (readonly) NSData* serializedRepresentation;
84 - (instancetype)initWithData:(NSData*)data;
85 - (instancetype)initRegularWrappedKeyWithData:(NSData*)wrappedKey;
86 - (instancetype)initRefKeyWrappedKeyWithData:(NSData*)wrappedKey refKeyBlob:(NSData*)refKeyBlob;
90 @interface SecDbKeychainMetadata : NSObject
92 @property (readonly) SFAuthenticatedCiphertext* ciphertext;
93 @property (readonly) SFAuthenticatedCiphertext* wrappedKey;
94 @property (readonly) NSString* tamperCheck;
96 @property (readonly) NSData* serializedRepresentation;
98 - (instancetype)initWithData:(NSData*)data;
99 - (instancetype)initWithCiphertext:(SFAuthenticatedCiphertext*)ciphertext wrappedKey:(SFAuthenticatedCiphertext*)wrappedKey tamperCheck:(NSString*)tamperCheck error:(NSError**)error;
103 @interface SecDbKeychainSecretData : NSObject
105 @property (readonly) SFAuthenticatedCiphertext* ciphertext;
106 @property (readonly) SecDbKeychainAKSWrappedKey* wrappedKey;
107 @property (readonly) NSString* tamperCheck;
109 @property (readonly) NSData* serializedRepresentation;
111 - (instancetype)initWithData:(NSData*)data;
112 - (instancetype)initWithCiphertext:(SFAuthenticatedCiphertext*)ciphertext wrappedKey:(SecDbKeychainAKSWrappedKey*)wrappedKey tamperCheck:(NSString*)tamperCheck backupWrappedKey:(SecDbBackupWrappedItemKey*)backupWrappedKey error:(NSError**)error;
116 @implementation SecDbKeychainAKSWrappedKey {
117 SecDbKeychainSerializedAKSWrappedKey* _serializedHolder;
120 - (instancetype)initRegularWrappedKeyWithData:(NSData*)wrappedKey
122 if (self = [super init]) {
123 _serializedHolder = [[SecDbKeychainSerializedAKSWrappedKey alloc] init];
124 _serializedHolder.wrappedKey = wrappedKey;
125 _serializedHolder.type = SecDbKeychainAKSWrappedKeyTypeRegular;
131 - (instancetype)initRefKeyWrappedKeyWithData:(NSData*)wrappedKey refKeyBlob:(NSData*)refKeyBlob
133 if (self = [super init]) {
134 _serializedHolder = [[SecDbKeychainSerializedAKSWrappedKey alloc] init];
135 _serializedHolder.wrappedKey = wrappedKey;
136 _serializedHolder.refKeyBlob = refKeyBlob;
137 _serializedHolder.type = SecDbKeychainAKSWrappedKeyTypeRefKey;
143 - (instancetype)initWithData:(NSData*)data
145 if (self = [super init]) {
146 _serializedHolder = [[SecDbKeychainSerializedAKSWrappedKey alloc] initWithData:data];
147 if (!_serializedHolder.wrappedKey || (_serializedHolder.type == SecDbKeychainAKSWrappedKeyTypeRefKey && !_serializedHolder.refKeyBlob)) {
155 - (NSData*)serializedRepresentation
157 return _serializedHolder.data;
160 - (NSData*)wrappedKey
162 return _serializedHolder.wrappedKey;
165 - (NSData*)refKeyBlob
167 return _serializedHolder.refKeyBlob;
170 - (SecDbKeychainAKSWrappedKeyType)type
172 return _serializedHolder.type;
177 @implementation SecDbKeychainMetadata {
178 SecDbKeychainSerializedMetadata* _serializedHolder;
181 - (instancetype)initWithCiphertext:(SFAuthenticatedCiphertext*)ciphertext
182 wrappedKey:(SFAuthenticatedCiphertext*)wrappedKey
183 tamperCheck:(NSString*)tamperCheck
184 error:(NSError**)error
186 if (self = [super init]) {
187 _serializedHolder = [[SecDbKeychainSerializedMetadata alloc] init];
188 _serializedHolder.ciphertext = [NSKeyedArchiver archivedDataWithRootObject:ciphertext requiringSecureCoding:YES error:error];
189 _serializedHolder.wrappedKey = [NSKeyedArchiver archivedDataWithRootObject:wrappedKey requiringSecureCoding:YES error:error];
190 _serializedHolder.tamperCheck = tamperCheck;
191 if (!_serializedHolder.ciphertext || !_serializedHolder.wrappedKey || !_serializedHolder.tamperCheck) {
199 - (instancetype)initWithData:(NSData*)data
201 if (self = [super init]) {
202 _serializedHolder = [[SecDbKeychainSerializedMetadata alloc] initWithData:data];
203 if (!_serializedHolder.ciphertext || !_serializedHolder.wrappedKey || !_serializedHolder.tamperCheck) {
211 - (NSData*)serializedRepresentation
213 return _serializedHolder.data;
216 - (SFAuthenticatedCiphertext*)ciphertext
218 NSError* error = nil;
219 SFAuthenticatedCiphertext* ciphertext = [NSKeyedUnarchiver unarchivedObjectOfClass:[SFAuthenticatedCiphertext class] fromData:_serializedHolder.ciphertext error:&error];
221 secerror("SecDbKeychainItemV7: error deserializing ciphertext from metadata: %@", error);
227 - (SFAuthenticatedCiphertext*)wrappedKey
229 NSError* error = nil;
230 SFAuthenticatedCiphertext* wrappedKey = [NSKeyedUnarchiver unarchivedObjectOfClass:[SFAuthenticatedCiphertext class] fromData:_serializedHolder.wrappedKey error:&error];
232 secerror("SecDbKeychainItemV7: error deserializing wrappedKey from metadata: %@", error);
238 - (NSString*)tamperCheck
240 return _serializedHolder.tamperCheck;
245 @implementation SecDbKeychainSecretData {
246 SecDbKeychainSerializedSecretData* _serializedHolder;
249 - (instancetype)initWithCiphertext:(SFAuthenticatedCiphertext*)ciphertext
250 wrappedKey:(SecDbKeychainAKSWrappedKey*)wrappedKey
251 tamperCheck:(NSString*)tamperCheck
252 backupWrappedKey:(SecDbBackupWrappedItemKey*)backupWrappedKey
253 error:(NSError**)error
255 if (self = [super init]) {
256 _serializedHolder = [[SecDbKeychainSerializedSecretData alloc] init];
257 _serializedHolder.ciphertext = [NSKeyedArchiver archivedDataWithRootObject:ciphertext requiringSecureCoding:YES error:error];
258 _serializedHolder.wrappedKey = wrappedKey.serializedRepresentation;
259 _serializedHolder.tamperCheck = tamperCheck;
260 _serializedHolder.secDbBackupWrappedItemKey = backupWrappedKey ? [NSKeyedArchiver archivedDataWithRootObject:backupWrappedKey requiringSecureCoding:YES error:error] : nil;
261 if (!_serializedHolder.ciphertext || !_serializedHolder.wrappedKey || !_serializedHolder.tamperCheck) {
269 - (instancetype)initWithData:(NSData*)data
271 if (self = [super init]) {
272 _serializedHolder = [[SecDbKeychainSerializedSecretData alloc] initWithData:data];
273 if (!_serializedHolder.ciphertext || !_serializedHolder.wrappedKey || !_serializedHolder.tamperCheck) {
281 - (NSData*)serializedRepresentation
283 return _serializedHolder.data;
286 - (SFAuthenticatedCiphertext*)ciphertext
288 NSError* error = nil;
289 SFAuthenticatedCiphertext* ciphertext = [NSKeyedUnarchiver unarchivedObjectOfClass:[SFAuthenticatedCiphertext class] fromData:_serializedHolder.ciphertext error:&error];
291 secerror("SecDbKeychainItemV7: error deserializing ciphertext from secret data: %@", error);
297 - (SecDbKeychainAKSWrappedKey*)wrappedKey
299 return [[SecDbKeychainAKSWrappedKey alloc] initWithData:_serializedHolder.wrappedKey];
302 - (NSString*)tamperCheck
304 return _serializedHolder.tamperCheck;
309 @interface SecDbKeychainItemV7 ()
310 @property (nonatomic) NSData* backupUUID;
313 @implementation SecDbKeychainItemV7 {
314 SecDbKeychainSecretData* _encryptedSecretData;
315 SecDbKeychainMetadata* _encryptedMetadata;
316 NSDictionary* _secretAttributes;
317 NSDictionary* _metadataAttributes;
318 NSString* _tamperCheck;
319 keyclass_t _keyclass;
320 keybag_handle_t _keybag;
323 @synthesize keyclass = _keyclass;
325 // bring back with <rdar://problem/37523001>
327 + (bool)isKeychainUnlocked
329 return kc_is_unlocked();
333 - (instancetype)initWithData:(NSData*)data decryptionKeybag:(keybag_handle_t)decryptionKeybag error:(NSError**)error
335 if (self = [super init]) {
336 SecDbKeychainSerializedItemV7* serializedItem = [[SecDbKeychainSerializedItemV7 alloc] initWithData:data];
337 if (serializedItem) {
339 // Add 10% for serializing overhead. We're trying to catch blatant overstuffing, not enforce hard limits
340 if (data.length > ((REASONABLE_SECRET_DATA_SIZE + REASONABLE_METADATA_SIZE) * 1.1)) {
341 secwarning("SecDbKeychainItemV7: serialized item exceeds reasonable size (%lu bytes)", (unsigned long)data.length);
344 _keybag = decryptionKeybag;
345 _encryptedSecretData = [[SecDbKeychainSecretData alloc] initWithData:serializedItem.encryptedSecretData];
346 _encryptedMetadata = [[SecDbKeychainMetadata alloc] initWithData:serializedItem.encryptedMetadata];
347 _keyclass = serializedItem.keyclass;
348 if (![_encryptedSecretData.tamperCheck isEqualToString:_encryptedMetadata.tamperCheck]) {
357 if (!self && error) {
358 *error = [NSError errorWithDomain:(id)kCFErrorDomainOSStatus code:errSecItemNotFound userInfo:@{NSLocalizedDescriptionKey : @"failed to deserialize keychain item blob"}];
364 - (instancetype)initWithSecretAttributes:(NSDictionary*)secretAttributes metadataAttributes:(NSDictionary*)metadataAttributes tamperCheck:(NSString*)tamperCheck keyclass:(keyclass_t)keyclass
366 NSParameterAssert(tamperCheck);
368 if (self = [super init]) {
369 _secretAttributes = secretAttributes ? secretAttributes.copy : [NSDictionary dictionary];
370 _metadataAttributes = metadataAttributes ? metadataAttributes.copy : [NSDictionary dictionary];
371 _tamperCheck = tamperCheck.copy;
372 _keyclass = keyclass;
378 + (SFAESKeySpecifier*)keySpecifier
380 static SFAESKeySpecifier* keySpecifier = nil;
381 static dispatch_once_t onceToken;
382 dispatch_once(&onceToken, ^{
383 keySpecifier = [[SFAESKeySpecifier alloc] initWithBitSize:SFAESKeyBitSize256];
389 + (SFAuthenticatedEncryptionOperation*)encryptionOperation
391 static SFAuthenticatedEncryptionOperation* encryptionOperation = nil;
392 static dispatch_once_t onceToken;
393 dispatch_once(&onceToken, ^{
394 encryptionOperation = [[SFAuthenticatedEncryptionOperation alloc] initWithKeySpecifier:[self keySpecifier]];
397 return encryptionOperation;
400 + (SFAuthenticatedEncryptionOperation*)decryptionOperation
402 static SFAuthenticatedEncryptionOperation* decryptionOperation = nil;
403 static dispatch_once_t onceToken;
404 dispatch_once(&onceToken, ^{
405 decryptionOperation = [[SFAuthenticatedEncryptionOperation alloc] initWithKeySpecifier:[self keySpecifier]];
408 return decryptionOperation;
411 - (NSDictionary*)metadataAttributesWithError:(NSError**)error
413 if (!_metadataAttributes) {
414 SFAESKey* metadataClassKey = [self metadataClassKeyWithKeybag:_keybag
415 createKeyIfMissing:false
416 overwriteCorruptKey:false
418 if (metadataClassKey) {
419 NSError* localError = nil;
420 NSData* keyData = [[self.class decryptionOperation] decrypt:_encryptedMetadata.wrappedKey withKey:metadataClassKey error:&localError];
422 secerror("SecDbKeychainItemV7: error unwrapping item metadata key (class %d, bag %d): %@", (int)self.keyclass, _keybag, localError);
423 // TODO: track this in LocalKeychainAnalytics
425 CFErrorRef secError = (CFErrorRef)CFBridgingRetain(localError); // this makes localError become the underlying error
426 SecError(errSecDecode, &secError, CFSTR("failed to unwrap item metadata key"));
427 *error = CFBridgingRelease(secError);
431 SFAESKey* key = [[SFAESKey alloc] initWithData:keyData specifier:[self.class keySpecifier] error:error];
436 NSData* metadata = [[self.class decryptionOperation] decrypt:_encryptedMetadata.ciphertext withKey:key error:&localError];
438 secerror("SecDbKeychainItemV7: error decrypting metadata content: %@", localError);
440 CFErrorRef secError = (CFErrorRef)CFBridgingRetain(localError); // this makes localError become the underlying error
441 SecError(errSecDecode, &secError, CFSTR("failed to decrypt item metadata contents"));
442 *error = CFBridgingRelease(secError);
446 NSMutableDictionary* decryptedAttributes = dictionaryFromDERData(metadata).mutableCopy;
447 NSString* tamperCheck = decryptedAttributes[SecDBTamperCheck];
448 if ([tamperCheck isEqualToString:_encryptedMetadata.tamperCheck]) {
449 [decryptedAttributes removeObjectForKey:SecDBTamperCheck];
450 _metadataAttributes = decryptedAttributes;
453 secerror("SecDbKeychainItemV7: tamper check failed for metadata decryption, expected %@ found %@", tamperCheck, _encryptedMetadata.tamperCheck);
455 CFErrorRef secError = NULL;
456 SecError(errSecDecode, &secError, CFSTR("tamper check failed for metadata decryption"));
457 *error = CFBridgingRelease(secError);
463 return _metadataAttributes;
466 - (NSDictionary*)secretAttributesWithAcmContext:(NSData*)acmContext accessControl:(SecAccessControlRef)accessControl callerAccessGroups:(NSArray*)callerAccessGroups error:(NSError**)error
468 if (!_secretAttributes) {
469 SFAESKey* key = [self unwrapFromAKS:_encryptedSecretData.wrappedKey accessControl:accessControl acmContext:acmContext callerAccessGroups:callerAccessGroups delete:NO error:error];
471 NSError* localError = nil;
472 NSData* secretDataWithPadding = [[self.class decryptionOperation] decrypt:_encryptedSecretData.ciphertext withKey:key error:&localError];
473 if (!secretDataWithPadding) {
474 secerror("SecDbKeychainItemV7: error decrypting item secret data contents: %@", localError);
476 CFErrorRef secError = (CFErrorRef)CFBridgingRetain(localError); // this makes localError become the underlying error
477 SecError(errSecDecode, &secError, CFSTR("error decrypting item secret data contents"));
478 *error = CFBridgingRelease(secError);
482 int8_t paddingLength = *((int8_t*)secretDataWithPadding.bytes + secretDataWithPadding.length - 1);
483 NSData* secretDataWithoutPadding = [secretDataWithPadding subdataWithRange:NSMakeRange(0, secretDataWithPadding.length - paddingLength)];
485 NSMutableDictionary* decryptedAttributes = dictionaryFromDERData(secretDataWithoutPadding).mutableCopy;
486 NSString* tamperCheck = decryptedAttributes[SecDBTamperCheck];
487 if ([tamperCheck isEqualToString:_encryptedSecretData.tamperCheck]) {
488 [decryptedAttributes removeObjectForKey:SecDBTamperCheck];
489 _secretAttributes = decryptedAttributes;
492 secerror("SecDbKeychainItemV7: tamper check failed for secret data decryption, expected %@ found %@", tamperCheck, _encryptedMetadata.tamperCheck);
497 return _secretAttributes;
500 - (BOOL)deleteWithAcmContext:(NSData*)acmContext accessControl:(SecAccessControlRef)accessControl callerAccessGroups:(NSArray*)callerAccessGroups error:(NSError**)error
502 NSError* localError = nil;
503 (void)[self unwrapFromAKS:_encryptedSecretData.wrappedKey accessControl:accessControl acmContext:acmContext callerAccessGroups:callerAccessGroups delete:YES error:&localError];
505 secerror("SecDbKeychainItemV7: failed to delete item secret key from aks");
516 - (NSData*)encryptedBlobWithKeybag:(keybag_handle_t)keybag accessControl:(SecAccessControlRef)accessControl acmContext:(NSData*)acmContext error:(NSError**)error
518 NSError* localError = nil;
519 BOOL success = [self encryptMetadataWithKeybag:keybag error:&localError];
520 if (!success || !_encryptedMetadata || localError) {
527 success = [self encryptSecretDataWithKeybag:keybag accessControl:accessControl acmContext:acmContext error:&localError];
528 if (!success || !_encryptedSecretData || localError) {
535 SecDbKeychainSerializedItemV7* serializedItem = [[SecDbKeychainSerializedItemV7 alloc] init];
536 serializedItem.encryptedMetadata = self.encryptedMetadataBlob;
537 serializedItem.encryptedSecretData = self.encryptedSecretDataBlob;
538 serializedItem.keyclass = _keyclass;
539 return serializedItem.data;
542 - (NSData*)encryptedMetadataBlob
544 return _encryptedMetadata.serializedRepresentation;
547 - (NSData*)encryptedSecretDataBlob
549 return _encryptedSecretData.serializedRepresentation;
552 - (BOOL)encryptMetadataWithKeybag:(keybag_handle_t)keybag error:(NSError**)error
554 SFAESKey* key = [[SFAESKey alloc] initRandomKeyWithSpecifier:[self.class keySpecifier] error:error];
558 SFAuthenticatedEncryptionOperation* encryptionOperation = [self.class encryptionOperation];
560 NSMutableDictionary* attributesToEncrypt = _metadataAttributes.mutableCopy;
561 attributesToEncrypt[SecDBTamperCheck] = _tamperCheck;
562 NSData* metadata = (__bridge_transfer NSData*)CFPropertyListCreateDERData(NULL, (__bridge CFDictionaryRef)attributesToEncrypt, NULL);
564 if (metadata.length > REASONABLE_METADATA_SIZE) {
565 NSString *agrp = _metadataAttributes[(__bridge NSString *)kSecAttrAccessGroup];
566 secwarning("SecDbKeychainItemV7: item's metadata exceeds reasonable size (%lu bytes) (%@)", (unsigned long)metadata.length, agrp);
569 SFAuthenticatedCiphertext* ciphertext = [encryptionOperation encrypt:metadata withKey:key error:error];
571 SFAESKey* metadataClassKey = [self metadataClassKeyWithKeybag:keybag
572 createKeyIfMissing:true
573 overwriteCorruptKey:true
575 if (metadataClassKey) {
576 SFAuthenticatedCiphertext* wrappedKey = [encryptionOperation encrypt:key.keyData withKey:metadataClassKey error:error];
577 _encryptedMetadata = [[SecDbKeychainMetadata alloc] initWithCiphertext:ciphertext wrappedKey:wrappedKey tamperCheck:_tamperCheck error:error];
580 return _encryptedMetadata != nil;
583 - (BOOL)encryptSecretDataWithKeybag:(keybag_handle_t)keybag accessControl:(SecAccessControlRef)accessControl acmContext:(NSData*)acmContext error:(NSError**)error
585 SFAESKey* key = [[SFAESKey alloc] initRandomKeyWithSpecifier:[self.class keySpecifier] error:error];
589 SFAuthenticatedEncryptionOperation* encryptionOperation = [self.class encryptionOperation];
591 NSMutableDictionary* attributesToEncrypt = _secretAttributes.mutableCopy;
592 attributesToEncrypt[SecDBTamperCheck] = _tamperCheck;
593 NSMutableData* secretData = [(__bridge_transfer NSData*)CFPropertyListCreateDERData(NULL, (__bridge CFDictionaryRef)attributesToEncrypt, NULL) mutableCopy];
595 if (secretData.length > REASONABLE_SECRET_DATA_SIZE) {
596 NSString *agrp = _metadataAttributes[(__bridge NSString *)kSecAttrAccessGroup];
597 secwarning("SecDbKeychainItemV7: item's secret data exceeds reasonable size (%lu bytes) (%@)", (unsigned long)secretData.length, agrp);
600 int8_t paddingLength = KEYCHAIN_ITEM_PADDING_MODULUS - (secretData.length % KEYCHAIN_ITEM_PADDING_MODULUS);
601 int8_t paddingBytes[KEYCHAIN_ITEM_PADDING_MODULUS];
602 for (int i = 0; i < KEYCHAIN_ITEM_PADDING_MODULUS; i++) {
603 paddingBytes[i] = paddingLength;
605 [secretData appendBytes:paddingBytes length:paddingLength];
607 SFAuthenticatedCiphertext* ciphertext = [encryptionOperation encrypt:secretData withKey:key error:error];
608 SecDbKeychainAKSWrappedKey* wrappedKey = [self wrapToAKS:key withKeybag:keybag accessControl:accessControl acmContext:acmContext error:error];
610 SecDbBackupWrappedItemKey* backupWrappedKey;
611 if (checkV12DevEnabled()) {
612 backupWrappedKey = [[SecDbBackupManager manager] wrapItemKey:key forKeyclass:_keyclass error:error];
613 if (backupWrappedKey) {
614 _backupUUID = backupWrappedKey.baguuid;
616 secwarning("SecDbKeychainItemV7: backup manager didn't return wrapped key: %@", error ? *error : nil);
623 _encryptedSecretData = [[SecDbKeychainSecretData alloc] initWithCiphertext:ciphertext
624 wrappedKey:wrappedKey
625 tamperCheck:_tamperCheck
626 backupWrappedKey:backupWrappedKey
628 return _encryptedSecretData != nil;
631 - (SFAESKey*)metadataClassKeyWithKeybag:(keybag_handle_t)keybag
632 createKeyIfMissing:(bool)createIfMissing
633 overwriteCorruptKey:(bool)force
634 error:(NSError**)error
636 return [[SecDbKeychainMetadataKeyStore sharedStore] keyForKeyclass:_keyclass
638 keySpecifier:[self.class keySpecifier]
639 createKeyIfMissing:(bool)createIfMissing
640 overwriteCorruptKey:force
644 - (SecDbKeychainAKSWrappedKey*)wrapToAKS:(SFAESKey*)key withKeybag:(keybag_handle_t)keybag accessControl:(SecAccessControlRef)accessControl acmContext:(NSData*)acmContext error:(NSError**)error
646 NSData* keyData = key.keyData;
649 NSDictionary* constraints = (__bridge NSDictionary*)SecAccessControlGetConstraints(accessControl);
651 aks_ref_key_t refKey = NULL;
652 CFErrorRef cfError = NULL;
653 NSData* authData = (__bridge_transfer NSData*)CFPropertyListCreateDERData(NULL, (__bridge CFDictionaryRef)@{(id)kAKSKeyAcl : constraints}, &cfError);
655 if (!acmContext || !SecAccessControlIsBound(accessControl)) {
656 secerror("SecDbKeychainItemV7: access control error");
658 CFDataRef accessControlData = SecAccessControlCopyData(accessControl);
659 ks_access_control_needed_error(&cfError, accessControlData, SecAccessControlIsBound(accessControl) ? kAKSKeyOpEncrypt : CFSTR(""));
660 CFReleaseNull(accessControlData);
663 BridgeCFErrorToNSErrorOut(error, cfError);
667 void* aksParams = NULL;
668 size_t aksParamsLength = 0;
669 aks_operation_optional_params(0, 0, authData.bytes, authData.length, acmContext.bytes, (int)acmContext.length, &aksParams, &aksParamsLength);
671 int aksResult = aks_ref_key_create(keybag, _keyclass, key_type_sym, aksParams, aksParamsLength, &refKey);
672 if (aksResult != 0) {
673 CFDataRef accessControlData = SecAccessControlCopyData(accessControl);
674 create_cferror_from_aks(aksResult, kAKSKeyOpEncrypt, keybag, _keyclass, accessControlData, (__bridge CFDataRef)acmContext, &cfError);
675 CFReleaseNull(accessControlData);
677 BridgeCFErrorToNSErrorOut(error, cfError);
681 size_t wrappedKeySize = 0;
682 void* wrappedKeyBytes = NULL;
683 aksResult = aks_ref_key_encrypt(refKey, aksParams, aksParamsLength, keyData.bytes, keyData.length, &wrappedKeyBytes, &wrappedKeySize);
684 if (aksResult != 0) {
685 CFDataRef accessControlData = SecAccessControlCopyData(accessControl);
686 create_cferror_from_aks(aksResult, kAKSKeyOpEncrypt, keybag, _keyclass, accessControlData, (__bridge CFDataRef)acmContext, &cfError);
687 CFReleaseNull(accessControlData);
689 aks_ref_key_free(&refKey);
690 BridgeCFErrorToNSErrorOut(error, cfError);
695 BridgeCFErrorToNSErrorOut(error, cfError);
697 NSData* wrappedKey = [[NSData alloc] initWithBytesNoCopy:wrappedKeyBytes length:wrappedKeySize];
699 size_t refKeyBlobLength = 0;
700 const void* refKeyBlobBytes = aks_ref_key_get_blob(refKey, &refKeyBlobLength);
701 NSData* refKeyBlob = [[NSData alloc] initWithBytesNoCopy:(void*)refKeyBlobBytes length:refKeyBlobLength];
702 aks_ref_key_free(&refKey);
703 return [[SecDbKeychainAKSWrappedKey alloc] initRefKeyWrappedKeyWithData:wrappedKey refKeyBlob:refKeyBlob];
706 NSMutableData* wrappedKey = [[NSMutableData alloc] initWithLength:(size_t)keyData.length + 40];
707 bool success = [SecAKSObjCWrappers aksEncryptWithKeybag:keybag keyclass:_keyclass plaintext:keyData outKeyclass:&_keyclass ciphertext:wrappedKey error:error];
708 return success ? [[SecDbKeychainAKSWrappedKey alloc] initRegularWrappedKeyWithData:wrappedKey] : nil;
711 NSMutableData* wrappedKey = [[NSMutableData alloc] initWithLength:(size_t)keyData.length + 40];
712 bool success = [SecAKSObjCWrappers aksEncryptWithKeybag:keybag keyclass:_keyclass plaintext:keyData outKeyclass:&_keyclass ciphertext:wrappedKey error:error];
713 return success ? [[SecDbKeychainAKSWrappedKey alloc] initRegularWrappedKeyWithData:wrappedKey] : nil;
717 - (SFAESKey*)unwrapFromAKS:(SecDbKeychainAKSWrappedKey*)wrappedKey accessControl:(SecAccessControlRef)accessControl acmContext:(NSData*)acmContext callerAccessGroups:(NSArray*)callerAccessGroups delete:(BOOL)delete error:(NSError**)error
719 NSData* wrappedKeyData = wrappedKey.wrappedKey;
721 if (wrappedKey.type == SecDbKeychainAKSWrappedKeyTypeRegular) {
722 NSMutableData* unwrappedKey = [NSMutableData dataWithCapacity:wrappedKeyData.length + 40];
723 unwrappedKey.length = wrappedKeyData.length + 40;
724 bool result = [SecAKSObjCWrappers aksDecryptWithKeybag:_keybag keyclass:_keyclass ciphertext:wrappedKeyData outKeyclass:&_keyclass plaintext:unwrappedKey error:error];
726 return [[SFAESKey alloc] initWithData:unwrappedKey specifier:[self.class keySpecifier] error:error];
733 else if (wrappedKey.type == SecDbKeychainAKSWrappedKeyTypeRefKey) {
734 aks_ref_key_t refKey = NULL;
735 aks_ref_key_create_with_blob(_keybag, wrappedKey.refKeyBlob.bytes, wrappedKey.refKeyBlob.length, &refKey);
737 CFErrorRef cfError = NULL;
738 size_t refKeyExternalDataLength = 0;
739 const uint8_t* refKeyExternalDataBytes = aks_ref_key_get_external_data(refKey, &refKeyExternalDataLength);
740 if (!refKeyExternalDataBytes) {
741 aks_ref_key_free(&refKey);
744 NSDictionary* aclDict = nil;
745 der_decode_plist(NULL, kCFPropertyListImmutable, (CFPropertyListRef*)(void*)&aclDict, &cfError, refKeyExternalDataBytes, refKeyExternalDataBytes + refKeyExternalDataLength);
747 SecError(errSecDecode, &cfError, CFSTR("SecDbKeychainItemV7: failed to decode acl dict"));
749 SecAccessControlSetConstraints(accessControl, (__bridge CFDictionaryRef)aclDict);
750 if (!SecAccessControlGetConstraint(accessControl, kAKSKeyOpEncrypt)) {
751 SecAccessControlAddConstraintForOperation(accessControl, kAKSKeyOpEncrypt, kCFBooleanTrue, &cfError);
754 size_t derPlistLength = der_sizeof_plist((__bridge CFPropertyListRef)callerAccessGroups, &cfError);
755 NSMutableData* accessGroupDERData = [[NSMutableData alloc] initWithLength:derPlistLength];
756 der_encode_plist((__bridge CFPropertyListRef)callerAccessGroups, &cfError, accessGroupDERData.mutableBytes, accessGroupDERData.mutableBytes + derPlistLength);
757 void* aksParams = NULL;
758 size_t aksParamsLength = 0;
759 aks_operation_optional_params(accessGroupDERData.bytes, derPlistLength, NULL, 0, acmContext.bytes, (int)acmContext.length, &aksParams, &aksParamsLength);
761 void* unwrappedKeyDERData = NULL;
762 size_t unwrappedKeyDERLength = 0;
763 int aksResult = aks_ref_key_decrypt(refKey, aksParams, aksParamsLength, wrappedKeyData.bytes, wrappedKeyData.length, &unwrappedKeyDERData, &unwrappedKeyDERLength);
764 if (aksResult != 0) {
765 CFDataRef accessControlData = SecAccessControlCopyData(accessControl);
766 create_cferror_from_aks(aksResult, kAKSKeyOpDecrypt, 0, 0, accessControlData, (__bridge CFDataRef)acmContext, &cfError);
767 CFReleaseNull(accessControlData);
768 aks_ref_key_free(&refKey);
770 BridgeCFErrorToNSErrorOut(error, cfError);
773 if (!unwrappedKeyDERData) {
774 SecError(errSecDecode, &cfError, CFSTR("SecDbKeychainItemV7: failed to decrypt item, Item can't be decrypted due to failed decode der, so drop the item."));
775 aks_ref_key_free(&refKey);
777 BridgeCFErrorToNSErrorOut(error, cfError);
781 CFPropertyListRef unwrappedKeyData = NULL;
782 der_decode_plist(NULL, kCFPropertyListImmutable, &unwrappedKeyData, &cfError, unwrappedKeyDERData, unwrappedKeyDERData + unwrappedKeyDERLength);
783 SFAESKey* result = nil;
784 if ([(__bridge NSData*)unwrappedKeyData isKindOfClass:[NSData class]]) {
785 result = [[SFAESKey alloc] initWithData:(__bridge NSData*)unwrappedKeyData specifier:[self.class keySpecifier] error:error];
786 CFReleaseNull(unwrappedKeyDERData);
789 SecError(errSecDecode, &cfError, CFSTR("SecDbKeychainItemV7: failed to decrypt item, Item can't be decrypted due to failed decode der, so drop the item."));
790 aks_ref_key_free(&refKey);
792 free(unwrappedKeyDERData);
793 BridgeCFErrorToNSErrorOut(error, cfError);
798 aksResult = aks_ref_key_delete(refKey, aksParams, aksParamsLength);
799 if (aksResult != 0) {
800 CFDataRef accessControlData = SecAccessControlCopyData(accessControl);
801 create_cferror_from_aks(aksResult, kAKSKeyOpDelete, 0, 0, accessControlData, (__bridge CFDataRef)acmContext, &cfError);
802 CFReleaseNull(accessControlData);
803 aks_ref_key_free(&refKey);
805 free(unwrappedKeyDERData);
806 BridgeCFErrorToNSErrorOut(error, cfError);
811 BridgeCFErrorToNSErrorOut(error, cfError);
812 aks_ref_key_free(&refKey);
814 free(unwrappedKeyDERData);