]> git.saurik.com Git - apple/security.git/blob - OSX/sec/securityd/SFKeychainControlManager.m
Security-59306.11.20.tar.gz
[apple/security.git] / OSX / sec / securityd / SFKeychainControlManager.m
1 /*
2 * Copyright (c) 2017 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 "SFKeychainControlManager.h"
25 #import "SecCFError.h"
26 #import "builtin_commands.h"
27 #import "debugging.h"
28 #import <Security/SecItem.h>
29 #import <Security/SecItemPriv.h>
30 #import <Foundation/NSXPCConnection_Private.h>
31
32 NSString* kSecEntitlementKeychainControl = @"com.apple.private.keychain.keychaincontrol";
33
34 XPC_RETURNS_RETAINED xpc_endpoint_t SecServerCreateKeychainControlEndpoint(void)
35 {
36 return [[SFKeychainControlManager sharedManager] xpcControlEndpoint];
37 }
38
39 @implementation SFKeychainControlManager {
40 NSXPCListener* _listener;
41 }
42
43 + (instancetype)sharedManager
44 {
45 static SFKeychainControlManager* manager = nil;
46 static dispatch_once_t onceToken;
47 dispatch_once(&onceToken, ^{
48 manager = [[SFKeychainControlManager alloc] _init];
49 });
50
51 return manager;
52 }
53
54 - (instancetype)_init
55 {
56 if (self = [super init]) {
57 _listener = [NSXPCListener anonymousListener];
58 _listener.delegate = self;
59 [_listener resume];
60 }
61
62 return self;
63 }
64
65 - (xpc_endpoint_t)xpcControlEndpoint
66 {
67 return [_listener.endpoint _endpoint];
68 }
69
70 - (BOOL)listener:(NSXPCListener*)listener shouldAcceptNewConnection:(NSXPCConnection*)newConnection
71 {
72 NSNumber* entitlementValue = [newConnection valueForEntitlement:kSecEntitlementKeychainControl];
73 if (![entitlementValue isKindOfClass:[NSNumber class]] || !entitlementValue.boolValue) {
74 secerror("SFKeychainControl: Client pid (%d) doesn't have entitlement: %@", newConnection.processIdentifier, kSecEntitlementKeychainControl);
75 return NO;
76 }
77
78 NSXPCInterface* interface = [NSXPCInterface interfaceWithProtocol:@protocol(SFKeychainControl)];
79 [interface setClass:[NSError class] forSelector:@selector(rpcFindCorruptedItemsWithReply:) argumentIndex:1 ofReply:YES];
80 [interface setClass:[NSError class] forSelector:@selector(rpcDeleteCorruptedItemsWithReply:) argumentIndex:1 ofReply:YES];
81 newConnection.exportedInterface = interface;
82 newConnection.exportedObject = self;
83 [newConnection resume];
84 return YES;
85 }
86
87 - (NSArray<NSDictionary*>*)findCorruptedItemsWithError:(NSError**)error
88 {
89 NSMutableArray<NSDictionary*>* corruptedItems = [[NSMutableArray alloc] init];
90 NSMutableArray* underlyingErrors = [[NSMutableArray alloc] init];
91
92 CFTypeRef genericPasswords = NULL;
93 NSDictionary* genericPasswordsQuery = @{ (id)kSecClass : (id)kSecClassGenericPassword,
94 (id)kSecReturnPersistentRef : @(YES),
95 (id)kSecUseDataProtectionKeychain : @(YES),
96 (id)kSecMatchLimit : (id)kSecMatchLimitAll };
97 OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)genericPasswordsQuery, &genericPasswords);
98 CFErrorRef genericPasswordError = NULL;
99 if (status != errSecItemNotFound) {
100 SecError(status, &genericPasswordError, CFSTR("generic password query failed"));
101 if (genericPasswordError) {
102 [underlyingErrors addObject:CFBridgingRelease(genericPasswordError)];
103 }
104 }
105
106 CFTypeRef internetPasswords = NULL;
107 NSDictionary* internetPasswordsQuery = @{ (id)kSecClass : (id)kSecClassInternetPassword,
108 (id)kSecReturnPersistentRef : @(YES),
109 (id)kSecUseDataProtectionKeychain : @(YES),
110 (id)kSecMatchLimit : (id)kSecMatchLimitAll };
111 status = SecItemCopyMatching((__bridge CFDictionaryRef)internetPasswordsQuery, &internetPasswords);
112 CFErrorRef internetPasswordError = NULL;
113 if (status != errSecItemNotFound) {
114 SecError(status, &internetPasswordError, CFSTR("internet password query failed"));
115 if (internetPasswordError) {
116 [underlyingErrors addObject:CFBridgingRelease(internetPasswordError)];
117 }
118 }
119
120 CFTypeRef keys = NULL;
121 NSDictionary* keysQuery = @{ (id)kSecClass : (id)kSecClassKey,
122 (id)kSecReturnPersistentRef : @(YES),
123 (id)kSecUseDataProtectionKeychain : @(YES),
124 (id)kSecMatchLimit : (id)kSecMatchLimitAll };
125 status = SecItemCopyMatching((__bridge CFDictionaryRef)keysQuery, &keys);
126 CFErrorRef keyError = NULL;
127 if (status != errSecItemNotFound) {
128 if (keyError) {
129 [underlyingErrors addObject:CFBridgingRelease(keyError)];
130 }
131 }
132
133 CFTypeRef certificates = NULL;
134 NSDictionary* certificateQuery = @{ (id)kSecClass : (id)kSecClassCertificate,
135 (id)kSecReturnPersistentRef : @(YES),
136 (id)kSecUseDataProtectionKeychain : @(YES),
137 (id)kSecMatchLimit : (id)kSecMatchLimitAll };
138 status = SecItemCopyMatching((__bridge CFDictionaryRef)certificateQuery, &certificates);
139 CFErrorRef certificateError = NULL;
140 if (status != errSecItemNotFound) {
141 SecError(status, &certificateError, CFSTR("certificate query failed"));
142 if (certificateError) {
143 [underlyingErrors addObject:CFBridgingRelease(certificateError)];
144 }
145 }
146
147 void (^scanArrayForCorruptedItem)(CFTypeRef, NSString*) = ^(CFTypeRef items, NSString* class) {
148 if ([(__bridge NSArray*)items isKindOfClass:[NSArray class]]) {
149 NSLog(@"scanning %d %@", (int)CFArrayGetCount(items), class);
150 for (NSData* persistentRef in (__bridge NSArray*)items) {
151 NSDictionary* itemQuery = @{ (id)kSecClass : class,
152 (id)kSecValuePersistentRef : persistentRef,
153 (id)kSecReturnAttributes : @(YES),
154 (id)kSecUseDataProtectionKeychain : @(YES) };
155 CFTypeRef itemAttributes = NULL;
156 OSStatus copyStatus = SecItemCopyMatching((__bridge CFDictionaryRef)itemQuery, &itemAttributes);
157 if (copyStatus != errSecSuccess && status != errSecInteractionNotAllowed) {
158 [corruptedItems addObject:itemQuery];
159 }
160 }
161 }
162 };
163
164 scanArrayForCorruptedItem(genericPasswords, (id)kSecClassGenericPassword);
165 scanArrayForCorruptedItem(internetPasswords, (id)kSecClassInternetPassword);
166 scanArrayForCorruptedItem(keys, (id)kSecClassKey);
167 scanArrayForCorruptedItem(certificates, (id)kSecClassCertificate);
168
169 if (underlyingErrors.count > 0 && error) {
170 *error = [NSError errorWithDomain:@"com.apple.security.keychainhealth" code:1 userInfo:@{ NSLocalizedDescriptionKey : [NSString stringWithFormat:@"encountered %d errors searching for corrupted items", (int)underlyingErrors.count], NSUnderlyingErrorKey : underlyingErrors.firstObject, @"searchingErrorCount" : @(underlyingErrors.count) }];
171 }
172
173 return corruptedItems;
174 }
175
176 - (bool)deleteCorruptedItemsWithError:(NSError**)error
177 {
178 NSError* findError = nil;
179 NSArray* corruptedItems = [self findCorruptedItemsWithError:&findError];
180 bool success = findError == nil;
181
182 NSMutableArray* deleteErrors = [[NSMutableArray alloc] init];
183 for (NSDictionary* corruptedItem in corruptedItems) {
184 OSStatus status = SecItemDelete((__bridge CFDictionaryRef)corruptedItem);
185 if (status != errSecSuccess) {
186 success = false;
187 CFErrorRef deleteError = NULL;
188 SecError(status, &deleteError, CFSTR("failed to delete corrupted item"));
189 [deleteErrors addObject:CFBridgingRelease(deleteError)];
190 }
191 }
192
193 if (error && (findError || deleteErrors.count > 0)) {
194 *error = [NSError errorWithDomain:@"com.apple.security.keychainhealth" code:2 userInfo:@{ NSLocalizedDescriptionKey : [NSString stringWithFormat:@"encountered %@ errors searching for corrupted items and %d errors attempting to delete corrupted items", findError.userInfo[@"searchingErrorCount"], (int)deleteErrors.count]}];
195 }
196
197 return success;
198 }
199
200 - (void)rpcFindCorruptedItemsWithReply:(void (^)(NSArray* corruptedItems, NSError* error))reply
201 {
202 NSError* error = nil;
203 NSArray* corruptedItems = [self findCorruptedItemsWithError:&error];
204 reply(corruptedItems, error);
205 }
206
207 - (void)rpcDeleteCorruptedItemsWithReply:(void (^)(bool success, NSError* error))reply
208 {
209 NSError* error = nil;
210 bool success = [self deleteCorruptedItemsWithError:&error];
211 reply(success, error);
212 }
213
214 @end