-
Notifications
You must be signed in to change notification settings - Fork 219
/
VALLegacySecureEnclaveValet.m
509 lines (399 loc) · 20.3 KB
/
VALLegacySecureEnclaveValet.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//
// VALLegacySecureEnclaveValet.m
// Valet
//
// Created by Dan Federman on 3/16/15.
// Copyright 2015 Square, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "VALLegacySecureEnclaveValet.h"
#import "VALLegacySecureEnclaveValet_Protected.h"
#import "VALLegacyValet_Protected.h"
#import "ValetDefines.h"
/// Compiler flag for building against an SDK where VALAccessControlTouchIDAnyFingerprint and VALAccessControlTouchIDCurrentFingerprintSet are available.
#define VAL_ACCESS_CONTROL_TOUCH_ID_SDK_AVAILABLE ((TARGET_OS_IPHONE && __IPHONE_9_0) || (TARGET_OS_MAC && __MAC_10_12))
/// Compiler flag for building against an SDK where VALAccessControlDevicePasscode is available.
#define VAL_ACCESS_CONTROL_DEVICE_PASSCODE_SDK_AVAILABLE ((TARGET_OS_IPHONE && __IPHONE_9_0) || (TARGET_OS_MAC && __MAC_10_11))
NSString *__nonnull VALStringForAccessControl(VALAccessControl accessControl)
{
switch (accessControl) {
case VALAccessControlUserPresence:
return @"AccessControlUserPresence";
case VALAccessControlTouchIDAnyFingerprint:
return @"AccessControlTouchIDAnyFingerprint";
case VALAccessControlTouchIDCurrentFingerprintSet:
return @"AccessControlTouchIDCurrentFingerprintSet";
case VALAccessControlDevicePasscode:
return @"AccessControlDevicePasscode";
}
return @"AccessControlInvalid";
}
#if VAL_SECURE_ENCLAVE_SDK_AVAILABLE
@implementation VALLegacySecureEnclaveValet
@synthesize baseQuery = _baseQuery;
#pragma mark - Class Methods
+ (BOOL)supportsSecureEnclaveKeychainItems;
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-compare"
return (&kSecAttrAccessControl != NULL && &kSecUseOperationPrompt != NULL);
#pragma clang diagnostic pop
}
#pragma mark - Private Class Methods
+ (BOOL)_macOSElCapitanOrLater;
{
#if TARGET_OS_MAC && __MAC_10_11
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-compare"
return (&kSecUseAuthenticationUI != NULL);
#pragma clang diagnostic pop
#else
return NO;
#endif
}
+ (BOOL)_macOSSierraOrLater;
{
#if TARGET_OS_MAC && __MAC_10_12
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-compare"
return (&kSecAttrTokenIDSecureEnclave != NULL);
#pragma clang diagnostic pop
#else
return NO;
#endif
}
+ (BOOL)_iOS8OrLater;
{
#if TARGET_OS_IPHONE
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-compare"
return (&kSecUseOperationPrompt != NULL);
#pragma clang diagnostic pop
#else
return NO;
#endif
}
+ (BOOL)_iOS9OrLater;
{
#if TARGET_OS_IPHONE && __IPHONE_9_0
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-compare"
return (&kSecUseAuthenticationUI != NULL);
#pragma clang diagnostic pop
#else
return NO;
#endif
}
+ (BOOL)_currentOSSupportedForAccessControl:(VALAccessControl)accessControl;
{
switch (accessControl) {
case VALAccessControlUserPresence:
return ([self _iOS8OrLater] || [self _macOSElCapitanOrLater]);
case VALAccessControlTouchIDAnyFingerprint:
case VALAccessControlTouchIDCurrentFingerprintSet:
return [self _iOS9OrLater] || [self _macOSSierraOrLater];
case VALAccessControlDevicePasscode:
return ([self _iOS9OrLater] || [self _macOSElCapitanOrLater]);
}
return NO;
}
+ (void)_augmentBaseQuery:(nonnull NSMutableDictionary *)mutableBaseQuery accessControl:(VALAccessControl)accessControl;
{
// Add the access control, which opts us in to Secure Element storage.
[mutableBaseQuery addEntriesFromDictionary:@{ (__bridge id)kSecAttrAccessControl : (__bridge_transfer id)SecAccessControlCreateWithFlags(NULL, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, ({
SecAccessControlCreateFlags accessControlFlag = 0;
switch (accessControl) {
case VALAccessControlUserPresence:
accessControlFlag = kSecAccessControlUserPresence;
break;
#if VAL_ACCESS_CONTROL_TOUCH_ID_SDK_AVAILABLE
case VALAccessControlTouchIDAnyFingerprint:
accessControlFlag = kSecAccessControlTouchIDAny;
break;
case VALAccessControlTouchIDCurrentFingerprintSet:
accessControlFlag = kSecAccessControlTouchIDCurrentSet;
break;
#else
case VALAccessControlTouchIDAnyFingerprint:
case VALAccessControlTouchIDCurrentFingerprintSet:
// This SDK does not support these access controls. But on this SDK we'll never reach this line, so just fake it.
break;
#endif
#if VAL_ACCESS_CONTROL_DEVICE_PASSCODE_SDK_AVAILABLE
case VALAccessControlDevicePasscode:
accessControlFlag = kSecAccessControlDevicePasscode;
break;
#else
case VALAccessControlDevicePasscode:
// This SDK does not support these access controls. But on this SDK we'll never reach this line, so just fake it.
break;
#endif
}
accessControlFlag;
}), NULL) }];
// kSecAttrAccessControl and kSecAttrAccessible are mutually exclusive, so remove kSecAttrAccessible from our query.
[mutableBaseQuery removeObjectForKey:(__bridge id)kSecAttrAccessible];
NSString *const service = mutableBaseQuery[(__bridge id)kSecAttrService];
NSString *const accessControlServiceSuffix = ({
NSString *accessControlServiceSuffix = @"";
switch (accessControl) {
case VALAccessControlUserPresence:
/*
VALLegacySecureEnclaveValet v1.0-v2.0.7 used UserPresence without a suffix – the concept of a customizable AccessControl was added in v2.1.
For backwards compatibility, do not append an access control suffix for UserPresence.
*/
break;
case VALAccessControlTouchIDAnyFingerprint:
case VALAccessControlTouchIDCurrentFingerprintSet:
case VALAccessControlDevicePasscode:
accessControlServiceSuffix = [@"_" stringByAppendingString:VALStringForAccessControl(accessControl)];
break;
}
accessControlServiceSuffix;
});
if (service.length > 0 && accessControlServiceSuffix.length > 0) {
// Ensure that our service identifier includes our access control suffix.
mutableBaseQuery[(__bridge id)kSecAttrService] = [service stringByAppendingString:accessControlServiceSuffix];
}
}
#pragma mark - Initialization
- (nullable instancetype)initWithIdentifier:(nonnull NSString *)identifier accessControl:(VALAccessControl)accessControl;
{
VALCheckCondition([[self class] supportsSecureEnclaveKeychainItems], nil, @"This device does not support storing data on the secure enclave.");
VALCheckCondition([[self class] _currentOSSupportedForAccessControl:accessControl], nil, @"This device does not support %@", VALStringForAccessControl(accessControl));
VALLegacyAccessibility const accessibility = VALLegacyAccessibilityWhenPasscodeSetThisDeviceOnly;
self = [super initWithIdentifier:identifier accessibility:accessibility];
SEL const backwardsCompatibleInitializer = @selector(initWithIdentifier:accessibility:);
NSMutableDictionary *const baseQuery = [[self class] mutableBaseQueryWithIdentifier:identifier
accessibility:accessibility
initializer:backwardsCompatibleInitializer];
[[self class] _augmentBaseQuery:baseQuery
accessControl:accessControl];
_baseQuery = baseQuery;
_accessControl = accessControl;
return [[self class] sharedValetForValet:self];
}
- (nullable instancetype)initWithSharedAccessGroupIdentifier:(nonnull NSString *)sharedAccessGroupIdentifier accessControl:(VALAccessControl)accessControl
{
VALCheckCondition([[self class] supportsSecureEnclaveKeychainItems], nil, @"This device does not support storing data on the secure enclave.");
VALCheckCondition([[self class] _currentOSSupportedForAccessControl:accessControl], nil, @"This device does not support %@", VALStringForAccessControl(accessControl));
VALLegacyAccessibility const accessibility = VALLegacyAccessibilityWhenPasscodeSetThisDeviceOnly;
self = [super initWithSharedAccessGroupIdentifier:sharedAccessGroupIdentifier accessibility:accessibility];
SEL const backwardsCompatibleInitializer = @selector(initWithSharedAccessGroupIdentifier:accessibility:);
NSMutableDictionary *const baseQuery = [[self class] mutableBaseQueryWithSharedAccessGroupIdentifier:sharedAccessGroupIdentifier
accessibility:accessibility
initializer:backwardsCompatibleInitializer];
[[self class] _augmentBaseQuery:baseQuery
accessControl:accessControl];
_baseQuery = baseQuery;
_accessControl = accessControl;
return [[self class] sharedValetForValet:self];
}
#pragma mark - VALValet
- (BOOL)canAccessKeychain;
{
// To avoid prompting the user for Touch ID or passcode, create a VALValet with our identifier and accessibility and ask it if it can access the keychain.
VALLegacyValet *noPromptValet = nil;
if ([self isSharedAcrossApplications]) {
noPromptValet = [[VALLegacyValet alloc] initWithSharedAccessGroupIdentifier:self.identifier accessibility:self.accessibility];
} else {
noPromptValet = [[VALLegacyValet alloc] initWithIdentifier:self.identifier accessibility:self.accessibility];
}
return [noPromptValet canAccessKeychain];
}
- (BOOL)containsObjectForKey:(nonnull NSString *)key;
{
OSStatus const status = [self containsObjectForKey:key options:nil];
BOOL const keyAlreadyInKeychain = (status == errSecInteractionNotAllowed || status == errSecSuccess);
return keyAlreadyInKeychain;
}
- (nonnull NSSet *)allKeys;
{
VALCheckCondition(NO, [NSSet new], @"%s is not supported on %@", __PRETTY_FUNCTION__, NSStringFromClass([self class]));
}
- (BOOL)removeAllObjects;
{
VALCheckCondition(NO, NO, @"%s is not supported on %@", __PRETTY_FUNCTION__, NSStringFromClass([self class]));
}
- (nullable NSError *)migrateObjectsMatchingQuery:(nonnull NSDictionary *)secItemQuery removeOnCompletion:(BOOL)remove;
{
if ([[self class] supportsSecureEnclaveKeychainItems]) {
VALCheckCondition(secItemQuery[(__bridge id)kSecUseOperationPrompt] == nil, [NSError errorWithDomain:VALMigrationErrorDomain code:VALMigrationErrorInvalidQuery userInfo:nil], @"kSecUseOperationPrompt is not supported in a migration query. Keychain items can not be migrated en masse from the Secure Enclave.");
}
return [super migrateObjectsMatchingQuery:secItemQuery removeOnCompletion:remove];
}
#pragma mark - Public Methods
- (nullable NSData *)objectForKey:(nonnull NSString *)key userPrompt:(nullable NSString *)userPrompt;
{
return [self objectForKey:key userPrompt:userPrompt userCancelled:NULL];
}
- (nullable NSData *)objectForKey:(nonnull NSString *)key userPrompt:(nullable NSString *)userPrompt userCancelled:(nullable inout BOOL *)userCancelled;
{
return [self objectForKey:key userPrompt:userPrompt userCancelled:userCancelled options:nil];
}
- (nullable NSString *)stringForKey:(nonnull NSString *)key userPrompt:(nullable NSString *)userPrompt;
{
return [self stringForKey:key userPrompt:userPrompt userCancelled:NULL];
}
- (nullable NSString *)stringForKey:(nonnull NSString *)key userPrompt:(nullable NSString *)userPrompt userCancelled:(nullable inout BOOL *)userCancelled;
{
return [self stringForKey:key userPrompt:userPrompt userCancelled:userCancelled options:nil];
}
#pragma mark - VALValet Protected Methods
- (BOOL)setObject:(nonnull NSData *)value forKey:(nonnull NSString *)key options:(nullable NSDictionary *)options;
{
// Remove the key before trying to set it. This will prevent us from calling SecItemUpdate on an item stored on the Secure Enclave, which would cause iOS to prompt the user for authentication.
[self removeObjectForKey:key];
return [super setObject:value forKey:key options:options];
}
- (OSStatus)containsObjectForKey:(nonnull NSString *)key options:(nullable NSDictionary *)options;
{
NSDictionary *baseOptions = nil;
// iOS 9 and macOS 10.11 use kSecUseAuthenticationUI, not kSecUseNoAuthenticationUI.
#if ((TARGET_OS_IPHONE && __IPHONE_9_0) || (TARGET_OS_MAC && __MAC_10_11))
if ([[self class] _iOS9OrLater] || [[self class] _macOSElCapitanOrLater]) {
baseOptions = @{ (__bridge id)kSecUseAuthenticationUI : (__bridge id)kSecUseAuthenticationUIFail };
} else {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
// kSecUseNoAuthenticationUI is deprecated in the iOS 9 SDK, but we still need it on iOS 8.
#if (TARGET_OS_IPHONE && __IPHONE_9_0)
options = @{ (__bridge id)kSecUseNoAuthenticationUI : @YES };
#endif
#pragma GCC diagnostic pop
}
#else
options = @{ (__bridge id)kSecUseNoAuthenticationUI : @YES };
#endif
NSMutableDictionary *const allOptions = [baseOptions mutableCopy];
[allOptions addEntriesFromDictionary:options];
return [super containsObjectForKey:key options:allOptions];
}
#pragma mark - VALLegacySecureEnclaveValet Protected Methods
- (nullable NSData *)objectForKey:(nonnull NSString *)key userPrompt:(nullable NSString *)userPrompt userCancelled:(nullable inout BOOL *)userCancelled options:(nullable NSDictionary *)options;
{
OSStatus status = errSecSuccess;
NSMutableDictionary *const allOptions = [[self _optionsDictionaryForUserPrompt:userPrompt] mutableCopy];
if (options.count > 0) {
[allOptions addEntriesFromDictionary:options];
}
NSData *const objectForKey = [self objectForKey:key options:allOptions status:&status];
if (userCancelled != NULL) {
*userCancelled = (status == errSecUserCanceled || status == errSecAuthFailed);
}
return objectForKey;
}
- (nullable NSString *)stringForKey:(nonnull NSString *)key userPrompt:(nullable NSString *)userPrompt userCancelled:(nullable inout BOOL *)userCancelled options:(nullable NSDictionary *)options;
{
OSStatus status = errSecSuccess;
NSMutableDictionary *const allOptions = [[self _optionsDictionaryForUserPrompt:userPrompt] mutableCopy];
if (options.count > 0) {
[allOptions addEntriesFromDictionary:options];
}
NSString *const stringForKey = [self stringForKey:key options:allOptions status:&status];
if (userCancelled != NULL) {
*userCancelled = (status == errSecUserCanceled || status == errSecAuthFailed);
}
return stringForKey;
}
#pragma mark - Private Methods
- (nullable NSDictionary *)_optionsDictionaryForUserPrompt:(nullable NSString *)userPrompt;
{
if (userPrompt.length == 0) {
return nil;
} else {
return @{ (__bridge id)kSecUseOperationPrompt : userPrompt };
}
}
@end
#pragma mark - Deprecated Category
@implementation VALLegacySecureEnclaveValet (Deprecated)
#pragma mark - Deprecated Initializers
- (nullable instancetype)initWithIdentifier:(nonnull NSString *)identifier;
{
return [self initWithIdentifier:identifier accessibility:VALLegacyAccessibilityWhenPasscodeSetThisDeviceOnly];
}
- (nullable instancetype)initWithIdentifier:(nonnull NSString *)identifier accessibility:(VALLegacyAccessibility)accessibility;
{
VALCheckCondition(accessibility == VALLegacyAccessibilityWhenPasscodeSetThisDeviceOnly, nil, @"Accessibility on SecureEnclaveValet must be VALLegacyAccessibilityWhenPasscodeSetThisDeviceOnly");
return [self initWithIdentifier:identifier accessControl:VALAccessControlUserPresence];
}
- (nullable instancetype)initWithSharedAccessGroupIdentifier:(nonnull NSString *)sharedAccessGroupIdentifier;
{
return [self initWithSharedAccessGroupIdentifier:sharedAccessGroupIdentifier accessibility:VALLegacyAccessibilityWhenPasscodeSetThisDeviceOnly];
}
- (nullable instancetype)initWithSharedAccessGroupIdentifier:(nonnull NSString *)sharedAccessGroupIdentifier accessibility:(VALLegacyAccessibility)accessibility;
{
VALCheckCondition(accessibility == VALLegacyAccessibilityWhenPasscodeSetThisDeviceOnly, nil, @"Accessibility on SecureEnclaveValet must be VALLegacyAccessibilityWhenPasscodeSetThisDeviceOnly");
return [self initWithSharedAccessGroupIdentifier:sharedAccessGroupIdentifier accessControl:VALAccessControlUserPresence];
}
@end
#else // Below this line we're in !VAL_SECURE_ENCLAVE_SDK_AVAILABLE, meaning none of our API is actually usable. Return NO or nil everywhere.
@implementation VALLegacySecureEnclaveValet
+ (BOOL)supportsSecureEnclaveKeychainItems;
{
VALCheckCondition(NO, NO, @"VALLegacySecureEnclaveValet unsupported on this SDK");
}
- (nullable instancetype)initWithIdentifier:(nonnull NSString *)identifier accessControl:(VALAccessControl)accessControl;
{
VALCheckCondition(NO, nil, @"VALLegacySecureEnclaveValet unsupported on this SDK");
}
- (nullable instancetype)initWithSharedAccessGroupIdentifier:(nonnull NSString *)sharedAccessGroupIdentifier accessControl:(VALAccessControl)accessControl;
{
VALCheckCondition(NO, nil, @"VALLegacySecureEnclaveValet unsupported on this SDK");
}
- (nullable NSData *)objectForKey:(nonnull NSString *)key userPrompt:(nullable NSString *)userPrompt;
{
VALCheckCondition(NO, nil, @"VALLegacySecureEnclaveValet unsupported on this SDK");
}
- (nullable NSData *)objectForKey:(nonnull NSString *)key userPrompt:(nullable NSString *)userPrompt userCancelled:(nullable inout BOOL *)userCancelled;
{
VALCheckCondition(NO, nil, @"VALLegacySecureEnclaveValet unsupported on this SDK");
}
- (nullable NSString *)stringForKey:(nonnull NSString *)key userPrompt:(nullable NSString *)userPrompt;
{
VALCheckCondition(NO, nil, @"VALLegacySecureEnclaveValet unsupported on this SDK");
}
- (nullable NSString *)stringForKey:(nonnull NSString *)key userPrompt:(nullable NSString *)userPrompt userCancelled:(nullable inout BOOL *)userCancelled;
{
VALCheckCondition(NO, nil, @"VALLegacySecureEnclaveValet unsupported on this SDK");
}
- (nullable NSData *)objectForKey:(nonnull NSString *)key userPrompt:(nullable NSString *)userPrompt userCancelled:(nullable inout BOOL *)userCancelled options:(nullable NSDictionary *)options;
{
VALCheckCondition(NO, nil, @"VALLegacySecureEnclaveValet unsupported on this SDK");
}
- (nullable NSString *)stringForKey:(nonnull NSString *)key userPrompt:(nullable NSString *)userPrompt userCancelled:(nullable inout BOOL *)userCancelled options:(nullable NSDictionary *)options;
{
VALCheckCondition(NO, nil, @"VALLegacySecureEnclaveValet unsupported on this SDK");
}
@end
@implementation VALLegacySecureEnclaveValet (Deprecated)
- (nullable instancetype)initWithIdentifier:(nonnull NSString *)identifier;
{
VALCheckCondition(NO, nil, @"VALLegacySecureEnclaveValet unsupported on this SDK");
}
- (nullable instancetype)initWithIdentifier:(nonnull NSString *)identifier accessibility:(VALLegacyAccessibility)accessibility;
{
VALCheckCondition(NO, nil, @"VALLegacySecureEnclaveValet unsupported on this SDK");
}
- (nullable instancetype)initWithSharedAccessGroupIdentifier:(nonnull NSString *)sharedAccessGroupIdentifier;
{
VALCheckCondition(NO, nil, @"VALLegacySecureEnclaveValet unsupported on this SDK");
}
- (nullable instancetype)initWithSharedAccessGroupIdentifier:(nonnull NSString *)sharedAccessGroupIdentifier accessibility:(VALLegacyAccessibility)accessibility;
{
VALCheckCondition(NO, nil, @"VALLegacySecureEnclaveValet unsupported on this SDK");
}
@end
#endif // VAL_SECURE_ENCLAVE_SDK_AVAILABLE