]> git.saurik.com Git - apple/security.git/blob - OSX/sec/ipc/server_xpc.m
Security-59306.41.2.tar.gz
[apple/security.git] / OSX / sec / ipc / server_xpc.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 <Foundation/Foundation.h>
25
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>
30
31 #if TARGET_DARWINOS
32 #undef OCTAGON
33 #undef SECUREOBJECTSYNC
34 #undef SHAREDWEBCREDENTIALS
35 #endif
36
37 #if OCTAGON
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
43 #else
44 // This is a no-op: XPCSanitizeError(error) turns into (error)
45 #define XPCSanitizeError
46 #endif // OCTAGON
47
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"
53
54 #include "keychain/ckks/CKKSViewManager.h"
55
56 #import "keychain/securityd/SecDbBackupManager.h"
57
58 @interface SecOSTransactionHolder : NSObject
59 @property os_transaction_t transaction;
60 - (instancetype)init:(os_transaction_t)transaction;
61 @end
62
63 @implementation SecOSTransactionHolder
64 - (instancetype)init:(os_transaction_t)transaction {
65 if((self = [super init])) {
66 _transaction = transaction;
67 }
68 return self;
69 }
70 @end
71
72 @implementation SecuritydXPCServer (SecuritydXPCProtocol)
73
74 - (void) SecItemAddAndNotifyOnSync:(NSDictionary*) attributes
75 syncCallback:(id<SecuritydXPCCallbackProtocol>) callback
76 complete:(void (^) (NSDictionary* opDictResult, NSArray* opArrayResult, NSError* operror))xpcComplete
77 {
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));
81 };
82
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);
89 return;
90 }
91
92 #if OCTAGON
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];
95 #endif
96
97 if(attributes[(id)kSecAttrDeriveSyncIDFromItemAttributes] ||
98 attributes[(id)kSecAttrPCSPlaintextServiceIdentifier] ||
99 attributes[(id)kSecAttrPCSPlaintextPublicKey] ||
100 attributes[(id)kSecAttrPCSPlaintextPublicIdentity]) {
101
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);
106 return;
107 }
108 }
109
110 CFTypeRef cfresult = NULL;
111
112 NSMutableDictionary* callbackQuery = [attributes mutableCopy];
113
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;
119 };
120
121 _SecItemAdd((__bridge CFDictionaryRef) callbackQuery, &_client, &cfresult, &cferror);
122
123 // SecItemAdd returns Some CF Object, but NSXPC is pretty adamant that everything be a specific NS type. Split it up here:
124 if(!cfresult) {
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));
130 } else {
131 // TODO: actually error here
132 complete(NULL, NULL, NULL);
133 }
134 CFReleaseNull(cfresult);
135 CFReleaseNull(cferror);
136 }
137
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
146 {
147 #if OCTAGON
148 // The calling client might not handle CK types well. Sanitize!
149 void (^complete)(NSError*) = ^(NSError* error){
150 xpcComplete(XPCSanitizeError(error));
151 };
152
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);
158 return;
159 }
160
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);
165 return;
166 }
167
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);
172 return;
173 }
174
175 #if OCTAGON
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"]);
180 return;
181 }
182 #endif
183
184 CKKSViewManager* manager = [CKKSViewManager manager];
185 if(!manager) {
186 secerror("SecItemSetCurrentItemAcrossAllDevices: no view manager?");
187 complete([NSError errorWithDomain:CKKSErrorDomain
188 code:CKKSNotInitialized
189 description:@"No view manager, cannot forward request"]);
190 return;
191 }
192
193 [manager setCurrentItemForAccessGroup:newItemPersistentRef
194 hash:newItemSHA1
195 accessGroup:accessGroup
196 identifier:identifier
197 viewHint:viewHint
198 replacing:oldCurrentItemPersistentRef
199 hash:oldItemSHA1
200 complete:complete];
201 return;
202 #else // ! OCTAGON
203 xpcComplete([NSError errorWithDomain:@"securityd" code:errSecParam userInfo:@{NSLocalizedDescriptionKey: @"SecItemSetCurrentItemAcrossAllDevices not implemented on this platform"}]);
204 #endif // OCTAGON
205 }
206
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
212 {
213 #if OCTAGON
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));
217 };
218
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);
224 return;
225 }
226
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);
231 return;
232 }
233
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);
238 return;
239 }
240
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"]);
245 return;
246 }
247
248 [[CKKSViewManager manager] getCurrentItemForAccessGroup:accessGroup
249 identifier:identifier
250 viewHint:viewHint
251 fetchCloudValue:fetchCloudValue
252 complete:^(NSString* uuid, NSError* error) {
253 if(error || !uuid) {
254 secnotice("ckkscurrent", "CKKS didn't find a current item for (%@,%@): %@ %@", accessGroup, identifier, uuid, error);
255 complete(NULL, error);
256 return;
257 }
258
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]
263 complete:complete];
264 }];
265 #else // ! OCTAGON
266 xpcComplete(NULL, [NSError errorWithDomain:@"securityd" code:errSecParam userInfo:@{NSLocalizedDescriptionKey: @"SecItemFetchCurrentItemAcrossAllDevices not implemented on this platform"}]);
267 #endif // OCTAGON
268 }
269
270 -(void)findItemPersistentRefByUUID:(NSString*)uuid
271 extraLoggingString:(NSString*)loggingStr
272 complete:(void (^) (NSData* persistentref, NSError* operror))xpcComplete
273 {
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));
277 };
278
279 CFErrorRef cferror = NULL;
280 CFTypeRef result = NULL;
281
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'
287 continue;
288 }
289
290 // Now that we're in an item class, reset any errSecItemNotFound errors from the last item class
291 CFReleaseNull(result);
292 CFReleaseNull(cferror);
293
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,
300 },
301 &self->_client,
302 &result,
303 &cferror);
304
305 if(cferror && CFErrorGetCode(cferror) != errSecItemNotFound) {
306 break;
307 }
308
309 if(result) {
310 // Found the persistent ref! Quit searching.
311 break;
312 }
313 }
314
315 if(result && !cferror) {
316 secinfo("ckkscurrent", "Found current item for (%@: %@)", loggingStr, uuid);
317 } else {
318 secerror("ckkscurrent: No current item for (%@,%@): %@ %@", loggingStr, uuid, result, cferror);
319 }
320
321 complete((__bridge NSData*) result, (__bridge NSError*) cferror);
322 CFReleaseNull(result);
323 CFReleaseNull(cferror);
324 }
325
326 - (void) secItemDigest:(NSString *)itemClass
327 accessGroup:(NSString *)accessGroup
328 complete:(void (^)(NSArray *digest, NSError* error))complete
329 {
330 CFArrayRef accessGroups = self->_client.accessGroups;
331 __block CFErrorRef cferror = NULL;
332 __block CFArrayRef result = NULL;
333
334 if (itemClass == NULL || accessGroup == NULL) {
335 SecError(errSecParam, &cferror, CFSTR("parameter missing: %@"), _client.task);
336 complete(NULL, (__bridge NSError*) cferror);
337 CFReleaseNull(cferror);
338 return;
339 }
340
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);
345 return;
346 }
347
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);
352 return;
353 }
354
355 if (CFArrayContainsValue(accessGroups, CFRangeMake(0, CFArrayGetCount(accessGroups)), CFSTR("*"))) {
356 /* Having the special accessGroup "*" allows access to all accessGroups. */
357 accessGroups = NULL;
358 }
359
360 NSDictionary *attributes = @{
361 (__bridge NSString *)kSecClass : itemClass,
362 (__bridge NSString *)kSecAttrAccessGroup : accessGroup,
363 (__bridge NSString *)kSecAttrSynchronizable : (__bridge NSString *)kSecAttrSynchronizableAny,
364 };
365
366 Query *q = query_create_with_limit((__bridge CFDictionaryRef)attributes, _client.musr, 0, &cferror);
367 if (q == NULL) {
368 SecError(errSecParam, &cferror, CFSTR("failed to build query: %@"), _client.task);
369 complete(NULL, (__bridge NSError*) cferror);
370 CFReleaseNull(cferror);
371 return;
372 }
373
374 bool ok = kc_with_dbt(false, &cferror, ^(SecDbConnectionRef dbt) {
375 return (bool)s3dl_copy_digest(dbt, q, &result, accessGroups, &cferror);
376 });
377
378 (void)ok;
379
380 complete((__bridge NSArray *)result, (__bridge NSError *)cferror);
381
382 (void)query_destroy(q, &cferror);
383
384 CFReleaseNull(result);
385 CFReleaseNull(cferror);
386 }
387
388
389 - (void) secKeychainDeleteMultiuser:(NSData *)uuid
390 complete:(void(^)(bool status, NSError* error))complete
391 {
392 __block CFErrorRef cferror = NULL;
393
394 #define SKDMUEntitlement @"com.apple.keychain.multiuser-admin"
395
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);
400 return;
401 }
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);
406 return;
407
408 }
409
410 #if TARGET_OS_IPHONE
411 bool status = kc_with_dbt(true, &cferror, ^(SecDbConnectionRef dbt) {
412 return SecServerDeleteAllForUser(dbt, (__bridge CFDataRef)uuid, false, &cferror);
413 });
414 #else
415 bool status = false;
416 #endif
417
418 complete(status, (__bridge NSError *)cferror);
419 CFReleaseNull(cferror);
420 }
421
422 - (void)secItemVerifyBackupIntegrity:(BOOL)lightweight
423 completion:(void (^)(NSDictionary<NSString*, NSString*>* results, NSError* error))completion
424 {
425 [[SecDbBackupManager manager] verifyBackupIntegrity:lightweight completion:completion];
426 }
427
428 @end