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 "SFKeychainControlManager.h"
25 #import "SecCFError.h"
26 #import "builtin_commands.h"
28 #import <Security/SecItem.h>
29 #import <Security/SecItemPriv.h>
30 #import <Foundation/NSXPCConnection_Private.h>
32 NSString* kSecEntitlementKeychainControl = @"com.apple.private.keychain.keychaincontrol";
34 XPC_RETURNS_RETAINED xpc_endpoint_t SecServerCreateKeychainControlEndpoint(void)
36 return [[SFKeychainControlManager sharedManager] xpcControlEndpoint];
39 @implementation SFKeychainControlManager {
40 NSXPCListener* _listener;
43 + (instancetype)sharedManager
45 static SFKeychainControlManager* manager = nil;
46 static dispatch_once_t onceToken;
47 dispatch_once(&onceToken, ^{
48 manager = [[SFKeychainControlManager alloc] _init];
56 if (self = [super init]) {
57 _listener = [NSXPCListener anonymousListener];
58 _listener.delegate = self;
65 - (xpc_endpoint_t)xpcControlEndpoint
67 return [_listener.endpoint _endpoint];
70 - (BOOL)listener:(NSXPCListener*)listener shouldAcceptNewConnection:(NSXPCConnection*)newConnection
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);
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];
87 - (NSArray<NSDictionary*>*)findCorruptedItemsWithError:(NSError**)error
89 NSMutableArray<NSDictionary*>* corruptedItems = [[NSMutableArray alloc] init];
90 NSMutableArray* underlyingErrors = [[NSMutableArray alloc] init];
92 CFTypeRef genericPasswords = NULL;
93 NSDictionary* genericPasswordsQuery = @{ (id)kSecClass : (id)kSecClassGenericPassword,
94 (id)kSecReturnPersistentRef : @(YES),
95 (id)kSecAttrNoLegacy : @(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)];
106 CFTypeRef internetPasswords = NULL;
107 NSDictionary* internetPasswordsQuery = @{ (id)kSecClass : (id)kSecClassInternetPassword,
108 (id)kSecReturnPersistentRef : @(YES),
109 (id)kSecAttrNoLegacy : @(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)];
120 CFTypeRef keys = NULL;
121 NSDictionary* keysQuery = @{ (id)kSecClass : (id)kSecClassKey,
122 (id)kSecReturnPersistentRef : @(YES),
123 (id)kSecAttrNoLegacy : @(YES),
124 (id)kSecMatchLimit : (id)kSecMatchLimitAll };
125 status = SecItemCopyMatching((__bridge CFDictionaryRef)keysQuery, &keys);
126 CFErrorRef keyError = NULL;
127 if (status != errSecItemNotFound) {
129 [underlyingErrors addObject:CFBridgingRelease(keyError)];
133 CFTypeRef certificates = NULL;
134 NSDictionary* certificateQuery = @{ (id)kSecClass : (id)kSecClassCertificate,
135 (id)kSecReturnPersistentRef : @(YES),
136 (id)kSecAttrNoLegacy : @(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)];
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)kSecAttrNoLegacy : @(YES) };
155 CFTypeRef itemAttributes = NULL;
156 OSStatus copyStatus = SecItemCopyMatching((__bridge CFDictionaryRef)itemQuery, &itemAttributes);
157 if (copyStatus != errSecSuccess && status != errSecInteractionNotAllowed) {
158 [corruptedItems addObject:itemQuery];
164 scanArrayForCorruptedItem(genericPasswords, (id)kSecClassGenericPassword);
165 scanArrayForCorruptedItem(internetPasswords, (id)kSecClassInternetPassword);
166 scanArrayForCorruptedItem(keys, (id)kSecClassKey);
167 scanArrayForCorruptedItem(certificates, (id)kSecClassCertificate);
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) }];
173 return corruptedItems;
176 - (bool)deleteCorruptedItemsWithError:(NSError**)error
178 NSError* findError = nil;
179 NSArray* corruptedItems = [self findCorruptedItemsWithError:&findError];
180 bool success = findError == nil;
182 NSMutableArray* deleteErrors = [[NSMutableArray alloc] init];
183 for (NSDictionary* corruptedItem in corruptedItems) {
184 OSStatus status = SecItemDelete((__bridge CFDictionaryRef)corruptedItem);
185 if (status != errSecSuccess) {
187 CFErrorRef deleteError = NULL;
188 SecError(status, &deleteError, CFSTR("failed to delete corrupted item"));
189 [deleteErrors addObject:CFBridgingRelease(deleteError)];
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]}];
200 - (void)rpcFindCorruptedItemsWithReply:(void (^)(NSArray* corruptedItems, NSError* error))reply
202 NSError* error = nil;
203 NSArray* corruptedItems = [self findCorruptedItemsWithError:&error];
204 reply(corruptedItems, error);
207 - (void)rpcDeleteCorruptedItemsWithReply:(void (^)(bool success, NSError* error))reply
209 NSError* error = nil;
210 bool success = [self deleteCorruptedItemsWithError:&error];
211 reply(success, error);