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 <Foundation/Foundation.h>
26 #include <ipc/securityd_client.h>
27 #include <ipc/server_security_helpers.h>
28 #include <ipc/server_endpoint.h>
29 #include <os/transaction_private.h>
33 #undef SECUREOBJECTSYNC
34 #undef SHAREDWEBCREDENTIALS
38 #import "keychain/categories/NSError+UsefulConstructors.h"
39 #include <CloudKit/CloudKit_Private.h>
40 // If your callbacks might pass back a CK error, you should use the XPCSanitizeError() spi on all branches at this layer.
41 // Otherwise, XPC might crash on the other side if they haven't linked CloudKit.framework.
42 #define XPCSanitizeError CKXPCSuitableError
44 // This is a no-op: XPCSanitizeError(error) turns into (error)
45 #define XPCSanitizeError
48 #include <Security/SecEntitlements.h>
49 #include <Security/SecItemPriv.h>
50 #include "keychain/securityd/SecItemServer.h"
51 #include "keychain/securityd/SecItemSchema.h"
52 #include "keychain/securityd/SecItemDb.h"
54 #include "keychain/ckks/CKKSViewManager.h"
56 #import "keychain/securityd/SecDbBackupManager.h"
58 @interface SecOSTransactionHolder : NSObject
59 @property os_transaction_t transaction;
60 - (instancetype)init:(os_transaction_t)transaction;
63 @implementation SecOSTransactionHolder
64 - (instancetype)init:(os_transaction_t)transaction {
65 if((self = [super init])) {
66 _transaction = transaction;
72 @implementation SecuritydXPCServer (SecuritydXPCProtocol)
74 - (void) SecItemAddAndNotifyOnSync:(NSDictionary*) attributes
75 syncCallback:(id<SecuritydXPCCallbackProtocol>) callback
76 complete:(void (^) (NSDictionary* opDictResult, NSArray* opArrayResult, NSError* operror))xpcComplete
78 // The calling client might not handle CK types well. Sanitize!
79 void (^complete)(NSDictionary*, NSArray*, NSError*) = ^(NSDictionary* opDictResult, NSArray* opArrayResult, NSError* operror){
80 xpcComplete(opDictResult, opArrayResult, XPCSanitizeError(operror));
83 CFErrorRef cferror = NULL;
84 if([self clientHasBooleanEntitlement: (__bridge NSString*) kSecEntitlementKeychainDeny]) {
85 SecError(errSecNotAvailable, &cferror, CFSTR("SecItemAddAndNotifyOnSync: %@ has entitlement %@"), _client.task, kSecEntitlementKeychainDeny);
86 //TODO: ensure cferror can transit xpc
87 complete(NULL, NULL, (__bridge NSError*) cferror);
88 CFReleaseNull(cferror);
93 // Wait a bit for CKKS initialization in case of daemon start, but don't bail if it isn't up
94 [[CKKSViewManager manager].completedSecCKKSInitialize wait:10];
97 if(attributes[(id)kSecAttrDeriveSyncIDFromItemAttributes] ||
98 attributes[(id)kSecAttrPCSPlaintextServiceIdentifier] ||
99 attributes[(id)kSecAttrPCSPlaintextPublicKey] ||
100 attributes[(id)kSecAttrPCSPlaintextPublicIdentity]) {
102 if(![self clientHasBooleanEntitlement: (__bridge NSString*) kSecEntitlementPrivateCKKSPlaintextFields]) {
103 SecError(errSecMissingEntitlement, &cferror, CFSTR("SecItemAddAndNotifyOnSync: %@ does not have entitlement %@, but is using SPI anyway"), _client.task, kSecEntitlementPrivateCKKSPlaintextFields);
104 complete(NULL, NULL, (__bridge NSError*) cferror);
105 CFReleaseNull(cferror);
110 CFTypeRef cfresult = NULL;
112 NSMutableDictionary* callbackQuery = [attributes mutableCopy];
114 // We probably need to figure out how to call os_transaction_needs_more_time on this transaction, but as this callback passes through C code, it's quite difficult
115 SecOSTransactionHolder* callbackTransaction = [[SecOSTransactionHolder alloc] init:os_transaction_create("com.apple.securityd.SecItemAddAndNotifyOnSync-callback")];
116 callbackQuery[@"f_ckkscallback"] = ^void (bool didSync, CFErrorRef syncerror) {
117 [callback callCallback:didSync error:XPCSanitizeError((__bridge NSError*)syncerror)];
118 callbackTransaction.transaction = nil;
121 _SecItemAdd((__bridge CFDictionaryRef) callbackQuery, &_client, &cfresult, &cferror);
123 // SecItemAdd returns Some CF Object, but NSXPC is pretty adamant that everything be a specific NS type. Split it up here:
125 complete(NULL, NULL, (__bridge NSError *)(cferror));
126 } else if( CFGetTypeID(cfresult) == CFDictionaryGetTypeID()) {
127 complete((__bridge NSDictionary *)(cfresult), NULL, (__bridge NSError *)(cferror));
128 } else if( CFGetTypeID(cfresult) == CFArrayGetTypeID()) {
129 complete(NULL, (__bridge NSArray *)cfresult, (__bridge NSError *)(cferror));
131 // TODO: actually error here
132 complete(NULL, NULL, NULL);
134 CFReleaseNull(cfresult);
135 CFReleaseNull(cferror);
138 - (void)secItemSetCurrentItemAcrossAllDevices:(NSData* _Nonnull)newItemPersistentRef
139 newCurrentItemHash:(NSData* _Nonnull)newItemSHA1
140 accessGroup:(NSString* _Nonnull)accessGroup
141 identifier:(NSString* _Nonnull)identifier
142 viewHint:(NSString* _Nonnull)viewHint
143 oldCurrentItemReference:(NSData* _Nullable)oldCurrentItemPersistentRef
144 oldCurrentItemHash:(NSData* _Nullable)oldItemSHA1
145 complete:(void (^) (NSError* _Nullable operror))xpcComplete
148 // The calling client might not handle CK types well. Sanitize!
149 void (^complete)(NSError*) = ^(NSError* error){
150 xpcComplete(XPCSanitizeError(error));
153 __block CFErrorRef cferror = NULL;
154 if([self clientHasBooleanEntitlement: (__bridge NSString*) kSecEntitlementKeychainDeny]) {
155 SecError(errSecNotAvailable, &cferror, CFSTR("SecItemSetCurrentItemAcrossAllDevices: %@ has entitlement %@"), _client.task, kSecEntitlementKeychainDeny);
156 complete((__bridge NSError*) cferror);
157 CFReleaseNull(cferror);
161 if(![self clientHasBooleanEntitlement: (__bridge NSString*) kSecEntitlementPrivateCKKSWriteCurrentItemPointers]) {
162 SecError(errSecMissingEntitlement, &cferror, CFSTR("SecItemSetCurrentItemAcrossAllDevices: %@ does not have entitlement %@"), _client.task, kSecEntitlementPrivateCKKSWriteCurrentItemPointers);
163 complete((__bridge NSError*) cferror);
164 CFReleaseNull(cferror);
168 if (!accessGroupsAllows(self->_client.accessGroups, (__bridge CFStringRef)accessGroup, &_client)) {
169 SecError(errSecMissingEntitlement, &cferror, CFSTR("SecItemSetCurrentItemAcrossAllDevices: client is missing access-group %@: %@"), accessGroup, _client.task);
170 complete((__bridge NSError*)cferror);
171 CFReleaseNull(cferror);
176 // Wait a bit for CKKS initialization in case of daemon start, and bail it doesn't come up
177 if([[CKKSViewManager manager].completedSecCKKSInitialize wait:10] != 0) {
178 secerror("SecItemSetCurrentItemAcrossAllDevices: CKKSViewManager not initialized?");
179 complete([NSError errorWithDomain:CKKSErrorDomain code:CKKSNotInitialized description:@"CKKS not yet initialized"]);
184 CKKSViewManager* manager = [CKKSViewManager manager];
186 secerror("SecItemSetCurrentItemAcrossAllDevices: no view manager?");
187 complete([NSError errorWithDomain:CKKSErrorDomain
188 code:CKKSNotInitialized
189 description:@"No view manager, cannot forward request"]);
193 [manager setCurrentItemForAccessGroup:newItemPersistentRef
195 accessGroup:accessGroup
196 identifier:identifier
198 replacing:oldCurrentItemPersistentRef
203 xpcComplete([NSError errorWithDomain:@"securityd" code:errSecParam userInfo:@{NSLocalizedDescriptionKey: @"SecItemSetCurrentItemAcrossAllDevices not implemented on this platform"}]);
207 -(void)secItemFetchCurrentItemAcrossAllDevices:(NSString*)accessGroup
208 identifier:(NSString*)identifier
209 viewHint:(NSString*)viewHint
210 fetchCloudValue:(bool)fetchCloudValue
211 complete:(void (^) (NSData* persistentref, NSError* operror))xpcComplete
214 // The calling client might not handle CK types well. Sanitize!
215 void (^complete)(NSData*, NSError*) = ^(NSData* persistentref, NSError* error){
216 xpcComplete(persistentref, XPCSanitizeError(error));
219 CFErrorRef cferror = NULL;
220 if([self clientHasBooleanEntitlement: (__bridge NSString*) kSecEntitlementKeychainDeny]) {
221 SecError(errSecNotAvailable, &cferror, CFSTR("SecItemFetchCurrentItemAcrossAllDevices: %@ has entitlement %@"), _client.task, kSecEntitlementKeychainDeny);
222 complete(NULL, (__bridge NSError*) cferror);
223 CFReleaseNull(cferror);
227 if(![self clientHasBooleanEntitlement: (__bridge NSString*) kSecEntitlementPrivateCKKSReadCurrentItemPointers]) {
228 SecError(errSecNotAvailable, &cferror, CFSTR("SecItemFetchCurrentItemAcrossAllDevices: %@ does not have entitlement %@"), _client.task, kSecEntitlementPrivateCKKSReadCurrentItemPointers);
229 complete(NULL, (__bridge NSError*) cferror);
230 CFReleaseNull(cferror);
234 if (!accessGroupsAllows(self->_client.accessGroups, (__bridge CFStringRef)accessGroup, &_client)) {
235 SecError(errSecMissingEntitlement, &cferror, CFSTR("SecItemFetchCurrentItemAcrossAllDevices: client is missing access-group %@: %@"), accessGroup, _client.task);
236 complete(NULL, (__bridge NSError*)cferror);
237 CFReleaseNull(cferror);
241 // Wait a bit for CKKS initialization in case of daemon start, and bail it doesn't come up
242 if([[CKKSViewManager manager].completedSecCKKSInitialize wait:10] != 0) {
243 secerror("SecItemFetchCurrentItemAcrossAllDevices: CKKSViewManager not initialized?");
244 complete(NULL, [NSError errorWithDomain:CKKSErrorDomain code:CKKSNotInitialized description:@"CKKS not yet initialized"]);
248 [[CKKSViewManager manager] getCurrentItemForAccessGroup:accessGroup
249 identifier:identifier
251 fetchCloudValue:fetchCloudValue
252 complete:^(NSString* uuid, NSError* error) {
254 secnotice("ckkscurrent", "CKKS didn't find a current item for (%@,%@): %@ %@", accessGroup, identifier, uuid, error);
255 complete(NULL, error);
259 // Find the persistent ref and return it.
260 secinfo("ckkscurrent", "CKKS believes current item UUID for (%@,%@) is %@. Looking up persistent ref...", accessGroup, identifier, uuid);
261 [self findItemPersistentRefByUUID:uuid
262 extraLoggingString:[NSString stringWithFormat:@"%@,%@", accessGroup, identifier]
266 xpcComplete(NULL, [NSError errorWithDomain:@"securityd" code:errSecParam userInfo:@{NSLocalizedDescriptionKey: @"SecItemFetchCurrentItemAcrossAllDevices not implemented on this platform"}]);
270 -(void)findItemPersistentRefByUUID:(NSString*)uuid
271 extraLoggingString:(NSString*)loggingStr
272 complete:(void (^) (NSData* persistentref, NSError* operror))xpcComplete
274 // The calling client might not handle CK types well. Sanitize!
275 void (^complete)(NSData*, NSError*) = ^(NSData* persistentref, NSError* error){
276 xpcComplete(persistentref, XPCSanitizeError(error));
279 CFErrorRef cferror = NULL;
280 CFTypeRef result = NULL;
282 // Must query per-class, so:
283 const SecDbSchema *newSchema = current_schema();
284 for (const SecDbClass *const *class = newSchema->classes; *class != NULL; class++) {
285 if(!((*class)->itemclass)) {
286 //Don't try to search non-item 'classes'
290 // Now that we're in an item class, reset any errSecItemNotFound errors from the last item class
291 CFReleaseNull(result);
292 CFReleaseNull(cferror);
294 _SecItemCopyMatching((__bridge CFDictionaryRef) @{
295 (__bridge NSString*) kSecClass: (__bridge NSString*) (*class)->name,
296 (id)kSecAttrSynchronizable: (id)kSecAttrSynchronizableAny,
297 (id)kSecMatchLimit : (id)kSecMatchLimitOne,
298 (id)kSecAttrUUID: uuid,
299 (id)kSecReturnPersistentRef: @YES,
305 if(cferror && CFErrorGetCode(cferror) != errSecItemNotFound) {
310 // Found the persistent ref! Quit searching.
315 if(result && !cferror) {
316 secinfo("ckkscurrent", "Found current item for (%@: %@)", loggingStr, uuid);
318 secerror("ckkscurrent: No current item for (%@,%@): %@ %@", loggingStr, uuid, result, cferror);
321 complete((__bridge NSData*) result, (__bridge NSError*) cferror);
322 CFReleaseNull(result);
323 CFReleaseNull(cferror);
326 - (void) secItemDigest:(NSString *)itemClass
327 accessGroup:(NSString *)accessGroup
328 complete:(void (^)(NSArray *digest, NSError* error))complete
330 CFArrayRef accessGroups = self->_client.accessGroups;
331 __block CFErrorRef cferror = NULL;
332 __block CFArrayRef result = NULL;
334 if (itemClass == NULL || accessGroup == NULL) {
335 SecError(errSecParam, &cferror, CFSTR("parameter missing: %@"), _client.task);
336 complete(NULL, (__bridge NSError*) cferror);
337 CFReleaseNull(cferror);
341 if (![itemClass isEqualToString:@"inet"] && ![itemClass isEqualToString:@"genp"]) {
342 SecError(errSecParam, &cferror, CFSTR("class %@ is not supported: %@"), itemClass, _client.task);
343 complete(NULL, (__bridge NSError*) cferror);
344 CFReleaseNull(cferror);
348 if (!accessGroupsAllows(accessGroups, (__bridge CFStringRef)accessGroup, &_client)) {
349 SecError(errSecMissingEntitlement, &cferror, CFSTR("Client is missing access-group %@: %@"), accessGroup, _client.task);
350 complete(NULL, (__bridge NSError*) cferror);
351 CFReleaseNull(cferror);
355 if (CFArrayContainsValue(accessGroups, CFRangeMake(0, CFArrayGetCount(accessGroups)), CFSTR("*"))) {
356 /* Having the special accessGroup "*" allows access to all accessGroups. */
360 NSDictionary *attributes = @{
361 (__bridge NSString *)kSecClass : itemClass,
362 (__bridge NSString *)kSecAttrAccessGroup : accessGroup,
363 (__bridge NSString *)kSecAttrSynchronizable : (__bridge NSString *)kSecAttrSynchronizableAny,
366 Query *q = query_create_with_limit((__bridge CFDictionaryRef)attributes, _client.musr, 0, &cferror);
368 SecError(errSecParam, &cferror, CFSTR("failed to build query: %@"), _client.task);
369 complete(NULL, (__bridge NSError*) cferror);
370 CFReleaseNull(cferror);
374 bool ok = kc_with_dbt(false, &cferror, ^(SecDbConnectionRef dbt) {
375 return (bool)s3dl_copy_digest(dbt, q, &result, accessGroups, &cferror);
380 complete((__bridge NSArray *)result, (__bridge NSError *)cferror);
382 (void)query_destroy(q, &cferror);
384 CFReleaseNull(result);
385 CFReleaseNull(cferror);
389 - (void) secKeychainDeleteMultiuser:(NSData *)uuid
390 complete:(void(^)(bool status, NSError* error))complete
392 __block CFErrorRef cferror = NULL;
394 #define SKDMUEntitlement @"com.apple.keychain.multiuser-admin"
396 if([self clientHasBooleanEntitlement: SKDMUEntitlement]) {
397 SecError(errSecNotAvailable, &cferror, CFSTR("secKeychainDeleteMultiuser: %@ need entitlement %@"), _client.task, SKDMUEntitlement);
398 complete(false, (__bridge NSError *)cferror);
399 CFReleaseNull(cferror);
402 if ([uuid length] != 16) {
403 SecError(errSecNotAvailable, &cferror, CFSTR("secKeychainDeleteMultiuser: %@ uuid have wrong length: %d"), _client.task, (int)[uuid length]);
404 complete(false, (__bridge NSError *)cferror);
405 CFReleaseNull(cferror);
411 bool status = kc_with_dbt(true, &cferror, ^(SecDbConnectionRef dbt) {
412 return SecServerDeleteAllForUser(dbt, (__bridge CFDataRef)uuid, false, &cferror);
418 complete(status, (__bridge NSError *)cferror);
419 CFReleaseNull(cferror);
422 - (void)secItemVerifyBackupIntegrity:(BOOL)lightweight
423 completion:(void (^)(NSDictionary<NSString*, NSString*>* results, NSError* error))completion
425 [[SecDbBackupManager manager] verifyBackupIntegrity:lightweight completion:completion];