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>
32 #import "keychain/categories/NSError+UsefulConstructors.h"
33 #include <CloudKit/CloudKit_Private.h>
34 // If your callbacks might pass back a CK error, you should use the XPCSanitizeError() spi on all branches at this layer.
35 // Otherwise, XPC might crash on the other side if they haven't linked CloudKit.framework.
36 #define XPCSanitizeError CKXPCSuitableError
38 // This is a no-op: XPCSanitizeError(error) turns into (error)
39 #define XPCSanitizeError
42 #include <Security/SecEntitlements.h>
43 #include <Security/SecItemPriv.h>
44 #include <securityd/SecItemServer.h>
45 #include <securityd/SecItemSchema.h>
46 #include <securityd/SecItemDb.h>
48 #include "keychain/ckks/CKKSViewManager.h"
50 @interface SecOSTransactionHolder : NSObject
51 @property os_transaction_t transaction;
52 - (instancetype)init:(os_transaction_t)transaction;
55 @implementation SecOSTransactionHolder
56 - (instancetype)init:(os_transaction_t)transaction {
57 if((self = [super init])) {
58 _transaction = transaction;
64 @implementation SecuritydXPCServer (SecuritydXPCProtocol)
66 - (void) SecItemAddAndNotifyOnSync:(NSDictionary*) attributes
67 syncCallback:(id<SecuritydXPCCallbackProtocol>) callback
68 complete:(void (^) (NSDictionary* opDictResult, NSArray* opArrayResult, NSError* operror))xpcComplete
70 // The calling client might not handle CK types well. Sanitize!
71 void (^complete)(NSDictionary*, NSArray*, NSError*) = ^(NSDictionary* opDictResult, NSArray* opArrayResult, NSError* operror){
72 xpcComplete(opDictResult, opArrayResult, XPCSanitizeError(operror));
75 CFErrorRef cferror = NULL;
76 if([self clientHasBooleanEntitlement: (__bridge NSString*) kSecEntitlementKeychainDeny]) {
77 SecError(errSecNotAvailable, &cferror, CFSTR("SecItemAddAndNotifyOnSync: %@ has entitlement %@"), _client.task, kSecEntitlementKeychainDeny);
78 //TODO: ensure cferror can transit xpc
79 complete(NULL, NULL, (__bridge NSError*) cferror);
80 CFReleaseNull(cferror);
85 // Wait a bit for CKKS initialization in case of daemon start, but don't bail if it isn't up
86 [[CKKSViewManager manager].completedSecCKKSInitialize wait:10];
89 if(attributes[(id)kSecAttrDeriveSyncIDFromItemAttributes] ||
90 attributes[(id)kSecAttrPCSPlaintextServiceIdentifier] ||
91 attributes[(id)kSecAttrPCSPlaintextPublicKey] ||
92 attributes[(id)kSecAttrPCSPlaintextPublicIdentity]) {
94 if(![self clientHasBooleanEntitlement: (__bridge NSString*) kSecEntitlementPrivateCKKSPlaintextFields]) {
95 SecError(errSecMissingEntitlement, &cferror, CFSTR("SecItemAddAndNotifyOnSync: %@ does not have entitlement %@, but is using SPI anyway"), _client.task, kSecEntitlementPrivateCKKSPlaintextFields);
96 complete(NULL, NULL, (__bridge NSError*) cferror);
97 CFReleaseNull(cferror);
102 CFTypeRef cfresult = NULL;
104 NSMutableDictionary* callbackQuery = [attributes mutableCopy];
106 // 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
107 SecOSTransactionHolder* callbackTransaction = [[SecOSTransactionHolder alloc] init:os_transaction_create("com.apple.securityd.SecItemAddAndNotifyOnSync-callback")];
108 callbackQuery[@"f_ckkscallback"] = ^void (bool didSync, CFErrorRef syncerror) {
109 [callback callCallback:didSync error:XPCSanitizeError((__bridge NSError*)syncerror)];
110 callbackTransaction.transaction = nil;
113 _SecItemAdd((__bridge CFDictionaryRef) callbackQuery, &_client, &cfresult, &cferror);
115 // SecItemAdd returns Some CF Object, but NSXPC is pretty adamant that everything be a specific NS type. Split it up here:
117 complete(NULL, NULL, (__bridge NSError *)(cferror));
118 } else if( CFGetTypeID(cfresult) == CFDictionaryGetTypeID()) {
119 complete((__bridge NSDictionary *)(cfresult), NULL, (__bridge NSError *)(cferror));
120 } else if( CFGetTypeID(cfresult) == CFArrayGetTypeID()) {
121 complete(NULL, (__bridge NSArray *)cfresult, (__bridge NSError *)(cferror));
123 // TODO: actually error here
124 complete(NULL, NULL, NULL);
126 CFReleaseNull(cfresult);
127 CFReleaseNull(cferror);
130 - (void)secItemSetCurrentItemAcrossAllDevices:(NSData* _Nonnull)newItemPersistentRef
131 newCurrentItemHash:(NSData* _Nonnull)newItemSHA1
132 accessGroup:(NSString* _Nonnull)accessGroup
133 identifier:(NSString* _Nonnull)identifier
134 viewHint:(NSString* _Nonnull)viewHint
135 oldCurrentItemReference:(NSData* _Nullable)oldCurrentItemPersistentRef
136 oldCurrentItemHash:(NSData* _Nullable)oldItemSHA1
137 complete:(void (^) (NSError* _Nullable operror))xpcComplete
140 // The calling client might not handle CK types well. Sanitize!
141 void (^complete)(NSError*) = ^(NSError* error){
142 xpcComplete(XPCSanitizeError(error));
145 __block CFErrorRef cferror = NULL;
146 if([self clientHasBooleanEntitlement: (__bridge NSString*) kSecEntitlementKeychainDeny]) {
147 SecError(errSecNotAvailable, &cferror, CFSTR("SecItemSetCurrentItemAcrossAllDevices: %@ has entitlement %@"), _client.task, kSecEntitlementKeychainDeny);
148 complete((__bridge NSError*) cferror);
149 CFReleaseNull(cferror);
153 if(![self clientHasBooleanEntitlement: (__bridge NSString*) kSecEntitlementPrivateCKKSWriteCurrentItemPointers]) {
154 SecError(errSecMissingEntitlement, &cferror, CFSTR("SecItemSetCurrentItemAcrossAllDevices: %@ does not have entitlement %@"), _client.task, kSecEntitlementPrivateCKKSWriteCurrentItemPointers);
155 complete((__bridge NSError*) cferror);
156 CFReleaseNull(cferror);
160 if (!accessGroupsAllows(self->_client.accessGroups, (__bridge CFStringRef)accessGroup, &_client)) {
161 SecError(errSecMissingEntitlement, &cferror, CFSTR("SecItemSetCurrentItemAcrossAllDevices: client is missing access-group %@: %@"), accessGroup, _client.task);
162 complete((__bridge NSError*)cferror);
163 CFReleaseNull(cferror);
168 // Wait a bit for CKKS initialization in case of daemon start, and bail it doesn't come up
169 if([[CKKSViewManager manager].completedSecCKKSInitialize wait:10] != 0) {
170 secerror("SecItemSetCurrentItemAcrossAllDevices: CKKSViewManager not initialized?");
171 complete([NSError errorWithDomain:CKKSErrorDomain code:CKKSNotInitialized description:@"CKKS not yet initialized"]);
176 CKKSViewManager* manager = [CKKSViewManager manager];
178 secerror("SecItemSetCurrentItemAcrossAllDevices: no view manager?");
179 complete([NSError errorWithDomain:CKKSErrorDomain
180 code:CKKSNotInitialized
181 description:@"No view manager, cannot forward request"]);
185 [manager setCurrentItemForAccessGroup:newItemPersistentRef
187 accessGroup:accessGroup
188 identifier:identifier
190 replacing:oldCurrentItemPersistentRef
195 xpcComplete([NSError errorWithDomain:@"securityd" code:errSecParam userInfo:@{NSLocalizedDescriptionKey: @"SecItemSetCurrentItemAcrossAllDevices not implemented on this platform"}]);
199 -(void)secItemFetchCurrentItemAcrossAllDevices:(NSString*)accessGroup
200 identifier:(NSString*)identifier
201 viewHint:(NSString*)viewHint
202 fetchCloudValue:(bool)fetchCloudValue
203 complete:(void (^) (NSData* persistentref, NSError* operror))xpcComplete
206 // The calling client might not handle CK types well. Sanitize!
207 void (^complete)(NSData*, NSError*) = ^(NSData* persistentref, NSError* error){
208 xpcComplete(persistentref, XPCSanitizeError(error));
211 CFErrorRef cferror = NULL;
212 if([self clientHasBooleanEntitlement: (__bridge NSString*) kSecEntitlementKeychainDeny]) {
213 SecError(errSecNotAvailable, &cferror, CFSTR("SecItemFetchCurrentItemAcrossAllDevices: %@ has entitlement %@"), _client.task, kSecEntitlementKeychainDeny);
214 complete(NULL, (__bridge NSError*) cferror);
215 CFReleaseNull(cferror);
219 if(![self clientHasBooleanEntitlement: (__bridge NSString*) kSecEntitlementPrivateCKKSReadCurrentItemPointers]) {
220 SecError(errSecNotAvailable, &cferror, CFSTR("SecItemFetchCurrentItemAcrossAllDevices: %@ does not have entitlement %@"), _client.task, kSecEntitlementPrivateCKKSReadCurrentItemPointers);
221 complete(NULL, (__bridge NSError*) cferror);
222 CFReleaseNull(cferror);
226 if (!accessGroupsAllows(self->_client.accessGroups, (__bridge CFStringRef)accessGroup, &_client)) {
227 SecError(errSecMissingEntitlement, &cferror, CFSTR("SecItemFetchCurrentItemAcrossAllDevices: client is missing access-group %@: %@"), accessGroup, _client.task);
228 complete(NULL, (__bridge NSError*)cferror);
229 CFReleaseNull(cferror);
233 // Wait a bit for CKKS initialization in case of daemon start, and bail it doesn't come up
234 if([[CKKSViewManager manager].completedSecCKKSInitialize wait:10] != 0) {
235 secerror("SecItemFetchCurrentItemAcrossAllDevices: CKKSViewManager not initialized?");
236 complete(NULL, [NSError errorWithDomain:CKKSErrorDomain code:CKKSNotInitialized description:@"CKKS not yet initialized"]);
240 [[CKKSViewManager manager] getCurrentItemForAccessGroup:accessGroup
241 identifier:identifier
243 fetchCloudValue:fetchCloudValue
244 complete:^(NSString* uuid, NSError* error) {
246 secnotice("ckkscurrent", "CKKS didn't find a current item for (%@,%@): %@ %@", accessGroup, identifier, uuid, error);
247 complete(NULL, error);
251 // Find the persistent ref and return it.
252 secinfo("ckkscurrent", "CKKS believes current item UUID for (%@,%@) is %@. Looking up persistent ref...", accessGroup, identifier, uuid);
253 [self findItemPersistentRefByUUID:uuid
254 extraLoggingString:[NSString stringWithFormat:@"%@,%@", accessGroup, identifier]
258 xpcComplete(NULL, [NSError errorWithDomain:@"securityd" code:errSecParam userInfo:@{NSLocalizedDescriptionKey: @"SecItemFetchCurrentItemAcrossAllDevices not implemented on this platform"}]);
262 -(void)findItemPersistentRefByUUID:(NSString*)uuid
263 extraLoggingString:(NSString*)loggingStr
264 complete:(void (^) (NSData* persistentref, NSError* operror))xpcComplete
266 // The calling client might not handle CK types well. Sanitize!
267 void (^complete)(NSData*, NSError*) = ^(NSData* persistentref, NSError* error){
268 xpcComplete(persistentref, XPCSanitizeError(error));
271 CFErrorRef cferror = NULL;
272 CFTypeRef result = NULL;
274 // Must query per-class, so:
275 const SecDbSchema *newSchema = current_schema();
276 for (const SecDbClass *const *class = newSchema->classes; *class != NULL; class++) {
277 if(!((*class)->itemclass)) {
278 //Don't try to search non-item 'classes'
282 // Now that we're in an item class, reset any errSecItemNotFound errors from the last item class
283 CFReleaseNull(result);
284 CFReleaseNull(cferror);
286 _SecItemCopyMatching((__bridge CFDictionaryRef) @{
287 (__bridge NSString*) kSecClass: (__bridge NSString*) (*class)->name,
288 (id)kSecAttrSynchronizable: (id)kSecAttrSynchronizableAny,
289 (id)kSecMatchLimit : (id)kSecMatchLimitOne,
290 (id)kSecAttrUUID: uuid,
291 (id)kSecReturnPersistentRef: @YES,
297 if(cferror && CFErrorGetCode(cferror) != errSecItemNotFound) {
302 // Found the persistent ref! Quit searching.
307 if(result && !cferror) {
308 secinfo("ckkscurrent", "Found current item for (%@: %@)", loggingStr, uuid);
310 secerror("ckkscurrent: No current item for (%@,%@): %@ %@", loggingStr, uuid, result, cferror);
313 complete((__bridge NSData*) result, (__bridge NSError*) cferror);
314 CFReleaseNull(result);
315 CFReleaseNull(cferror);
318 - (void) secItemDigest:(NSString *)itemClass
319 accessGroup:(NSString *)accessGroup
320 complete:(void (^)(NSArray *digest, NSError* error))complete
322 CFArrayRef accessGroups = self->_client.accessGroups;
323 __block CFErrorRef cferror = NULL;
324 __block CFArrayRef result = NULL;
326 if (itemClass == NULL || accessGroup == NULL) {
327 SecError(errSecParam, &cferror, CFSTR("parameter missing: %@"), _client.task);
328 complete(NULL, (__bridge NSError*) cferror);
329 CFReleaseNull(cferror);
333 if (![itemClass isEqualToString:@"inet"] && ![itemClass isEqualToString:@"genp"]) {
334 SecError(errSecParam, &cferror, CFSTR("class %@ is not supported: %@"), itemClass, _client.task);
335 complete(NULL, (__bridge NSError*) cferror);
336 CFReleaseNull(cferror);
340 if (!accessGroupsAllows(accessGroups, (__bridge CFStringRef)accessGroup, &_client)) {
341 SecError(errSecMissingEntitlement, &cferror, CFSTR("Client is missing access-group %@: %@"), accessGroup, _client.task);
342 complete(NULL, (__bridge NSError*) cferror);
343 CFReleaseNull(cferror);
347 if (CFArrayContainsValue(accessGroups, CFRangeMake(0, CFArrayGetCount(accessGroups)), CFSTR("*"))) {
348 /* Having the special accessGroup "*" allows access to all accessGroups. */
352 NSDictionary *attributes = @{
353 (__bridge NSString *)kSecClass : itemClass,
354 (__bridge NSString *)kSecAttrAccessGroup : accessGroup,
355 (__bridge NSString *)kSecAttrSynchronizable : (__bridge NSString *)kSecAttrSynchronizableAny,
358 Query *q = query_create_with_limit((__bridge CFDictionaryRef)attributes, _client.musr, 0, &cferror);
360 SecError(errSecParam, &cferror, CFSTR("failed to build query: %@"), _client.task);
361 complete(NULL, (__bridge NSError*) cferror);
362 CFReleaseNull(cferror);
366 bool ok = kc_with_dbt(false, &cferror, ^(SecDbConnectionRef dbt) {
367 return (bool)s3dl_copy_digest(dbt, q, &result, accessGroups, &cferror);
372 complete((__bridge NSArray *)result, (__bridge NSError *)cferror);
374 (void)query_destroy(q, &cferror);
376 CFReleaseNull(result);
377 CFReleaseNull(cferror);