]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/CKKS.m
Security-59306.80.4.tar.gz
[apple/security.git] / keychain / ckks / CKKS.m
1 /*
2 * Copyright (c) 2016 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 #include <dispatch/dispatch.h>
25 #import <Foundation/Foundation.h>
26 #if OCTAGON
27 #import <CloudKit/CloudKit.h>
28 #endif
29
30 #include <utilities/debugging.h>
31 #include "keychain/securityd/SecItemServer.h"
32 #include <Security/SecItemPriv.h>
33
34 #import <Foundation/Foundation.h>
35 #import "keychain/ckks/CKKS.h"
36 #import "keychain/ckks/CKKSKeychainView.h"
37 #import "keychain/ckks/CKKSViewManager.h"
38 #import "keychain/ckks/CKKSKey.h"
39
40 #import "keychain/ot/OTManager.h"
41
42 NSDictionary<CKKSZoneKeyState*, NSNumber*>* CKKSZoneKeyStateMap(void) {
43 static NSDictionary<CKKSZoneKeyState*, NSNumber*>* map = nil;
44 static dispatch_once_t onceToken;
45 dispatch_once(&onceToken, ^{
46 map = @{
47 SecCKKSZoneKeyStateReady: @0U,
48 SecCKKSZoneKeyStateError: @1U,
49 SecCKKSZoneKeyStateCancelled: @2U,
50
51 SecCKKSZoneKeyStateInitializing: @3U,
52 SecCKKSZoneKeyStateInitialized: @4U,
53 SecCKKSZoneKeyStateFetchComplete: @5U,
54 SecCKKSZoneKeyStateWaitForTLK: @6U,
55 SecCKKSZoneKeyStateWaitForUnlock: @7U,
56 SecCKKSZoneKeyStateUnhealthy: @8U,
57 SecCKKSZoneKeyStateBadCurrentPointers: @9U,
58 SecCKKSZoneKeyStateNewTLKsFailed: @10U,
59 SecCKKSZoneKeyStateNeedFullRefetch: @11U,
60 SecCKKSZoneKeyStateHealTLKShares: @12U,
61 SecCKKSZoneKeyStateHealTLKSharesFailed:@13U,
62 SecCKKSZoneKeyStateWaitForFixupOperation:@14U,
63 SecCKKSZoneKeyStateReadyPendingUnlock: @15U,
64 SecCKKSZoneKeyStateFetch: @16U,
65 SecCKKSZoneKeyStateResettingZone: @17U,
66 SecCKKSZoneKeyStateResettingLocalData: @18U,
67 SecCKKSZoneKeyStateLoggedOut: @19U,
68 SecCKKSZoneKeyStateZoneCreationFailed: @20U,
69 SecCKKSZoneKeyStateWaitForTrust: @21U,
70 SecCKKSZoneKeyStateWaitForTLKUpload: @22U,
71 SecCKKSZoneKeyStateWaitForTLKCreation: @23U,
72 SecCKKSZoneKeyStateProcess: @24U,
73 };
74 });
75 return map;
76 }
77
78 NSDictionary<NSNumber*, CKKSZoneKeyState*>* CKKSZoneKeyStateInverseMap(void) {
79 static NSDictionary<NSNumber*, CKKSZoneKeyState*>* backwardMap = nil;
80 static dispatch_once_t onceToken;
81 dispatch_once(&onceToken, ^{
82 NSDictionary<CKKSZoneKeyState*, NSNumber*>* forwardMap = CKKSZoneKeyStateMap();
83 backwardMap = [NSDictionary dictionaryWithObjects:[forwardMap allKeys] forKeys:[forwardMap allValues]];
84 });
85 return backwardMap;
86 }
87
88 NSNumber* CKKSZoneKeyToNumber(CKKSZoneKeyState* state) {
89 if(!state) {
90 return CKKSZoneKeyStateMap()[SecCKKSZoneKeyStateError];
91 }
92 NSNumber* result = CKKSZoneKeyStateMap()[state];
93 if(result) {
94 return result;
95 }
96 return CKKSZoneKeyStateMap()[SecCKKSZoneKeyStateError];
97 }
98 CKKSZoneKeyState* CKKSZoneKeyRecover(NSNumber* stateNumber) {
99 if(!stateNumber) {
100 return SecCKKSZoneKeyStateError;
101 }
102 CKKSZoneKeyState* result = CKKSZoneKeyStateInverseMap()[stateNumber];
103 if(result) {
104 return result;
105 }
106 return SecCKKSZoneKeyStateError;
107 }
108
109 bool CKKSKeyStateTransient(CKKSZoneKeyState* state) {
110 // Easier to compare against a blacklist of end states
111 bool nontransient = [state isEqualToString:SecCKKSZoneKeyStateReady] ||
112 [state isEqualToString:SecCKKSZoneKeyStateReadyPendingUnlock] ||
113 [state isEqualToString:SecCKKSZoneKeyStateWaitForTrust] ||
114 [state isEqualToString:SecCKKSZoneKeyStateWaitForTLK] ||
115 [state isEqualToString:SecCKKSZoneKeyStateWaitForTLKCreation] ||
116 [state isEqualToString:SecCKKSZoneKeyStateWaitForTLKUpload] ||
117 [state isEqualToString:SecCKKSZoneKeyStateWaitForUnlock] ||
118 [state isEqualToString:SecCKKSZoneKeyStateError] ||
119 [state isEqualToString:SecCKKSZoneKeyStateCancelled];
120 return !nontransient;
121 }
122
123 #if OCTAGON
124 // If you want CKKS to run in your daemon/tests, you must call SecCKKSEnable before bringing up the keychain db
125 static bool enableCKKS = false;
126 static bool testCKKS = false;
127
128 bool SecCKKSIsEnabled(void) {
129 if([CKDatabase class] == nil) {
130 // CloudKit is not linked. We cannot bring CKKS up; disable it with prejudice.
131 secerror("CKKS: CloudKit.framework appears to not be linked. Cannot enable CKKS (on pain of crash).");
132 return false;
133 }
134
135 return enableCKKS;
136 }
137
138 bool SecCKKSEnable() {
139 enableCKKS = true;
140 return enableCKKS;
141 }
142
143 bool SecCKKSDisable() {
144 enableCKKS = false;
145 return enableCKKS;
146 }
147
148 bool SecCKKSResetSyncing(void) {
149 [CKKSViewManager resetManager: true setTo: nil];
150 return SecCKKSIsEnabled();
151 }
152
153 bool SecCKKSTestsEnabled(void) {
154 return testCKKS;
155 }
156
157 bool SecCKKSTestsEnable(void) {
158 if([CKDatabase class] == nil) {
159 // CloudKit is not linked. We cannot bring CKKS up; disable it with prejudice.
160 secerror("CKKS: CloudKit.framework appears to not be linked. Cannot enable CKKS testing.");
161 testCKKS = false;
162 return false;
163 }
164
165 testCKKS = true;
166 return testCKKS;
167 }
168
169 bool SecCKKSTestsDisable(void) {
170 testCKKS = false;
171 return testCKKS;
172 }
173
174 // Feature flags to twiddle behavior
175 static bool CKKSSyncManifests = false;
176 bool SecCKKSSyncManifests(void) {
177 return CKKSSyncManifests;
178 }
179 bool SecCKKSEnableSyncManifests() {
180 CKKSSyncManifests = true;
181 return CKKSSyncManifests;
182 }
183 bool SecCKKSSetSyncManifests(bool value) {
184 CKKSSyncManifests = value;
185 return CKKSSyncManifests;
186 }
187
188 static bool CKKSEnforceManifests = false;
189 bool SecCKKSEnforceManifests(void) {
190 return CKKSEnforceManifests;
191 }
192 bool SecCKKSEnableEnforceManifests() {
193 CKKSEnforceManifests = true;
194 return CKKSEnforceManifests;
195 }
196 bool SecCKKSSetEnforceManifests(bool value) {
197 CKKSEnforceManifests = value;
198 return CKKSEnforceManifests;
199 }
200
201 // defaults write com.apple.security.ckks reduce-rate-limiting YES
202 static bool CKKSReduceRateLimiting = false;
203 bool SecCKKSReduceRateLimiting(void) {
204 static dispatch_once_t onceToken;
205 dispatch_once(&onceToken, ^{
206 // Use the default value as above, or apply the preferences value if it exists
207 NSUserDefaults* defaults = [[NSUserDefaults alloc] initWithSuiteName:SecCKKSUserDefaultsSuite];
208 NSString* key = @"reduce-rate-limiting";
209 [defaults registerDefaults: @{key: CKKSReduceRateLimiting ? @YES : @NO}];
210
211 CKKSReduceRateLimiting = !![defaults boolForKey:@"reduce-rate-limiting"];
212 secnotice("ckks", "reduce-rate-limiting is %@", CKKSReduceRateLimiting ? @"on" : @"off");
213 });
214
215 return CKKSReduceRateLimiting;
216 }
217
218 bool SecCKKSSetReduceRateLimiting(bool value) {
219 (void) SecCKKSReduceRateLimiting(); // Call this once to read the defaults write
220 CKKSReduceRateLimiting = value;
221 secnotice("ckks", "reduce-rate-limiting is now %@", CKKSReduceRateLimiting ? @"on" : @"off");
222 return CKKSReduceRateLimiting;
223 }
224
225 // Here's a mechanism for CKKS feature flags with default values from NSUserDefaults:
226 /*static bool CKKSShareTLKs = true;
227 bool SecCKKSShareTLKs(void) {
228 return true;
229 static dispatch_once_t onceToken;
230 dispatch_once(&onceToken, ^{
231 // Use the default value as above, or apply the preferences value if it exists
232 NSUserDefaults* defaults = [[NSUserDefaults alloc] initWithSuiteName:SecCKKSUserDefaultsSuite];
233 [defaults registerDefaults: @{@"tlksharing": CKKSShareTLKs ? @YES : @NO}];
234
235 CKKSShareTLKs = !![defaults boolForKey:@"tlksharing"];
236 secnotice("ckksshare", "TLK sharing is %@", CKKSShareTLKs ? @"on" : @"off");
237 });
238
239 return CKKSShareTLKs;
240 }*/
241
242 // Feature flags to twiddle behavior for tests
243 static bool CKKSDisableAutomaticUUID = false;
244 bool SecCKKSTestDisableAutomaticUUID(void) {
245 #if DEBUG
246 return CKKSDisableAutomaticUUID;
247 #else
248 return false;
249 #endif
250 }
251 void SecCKKSTestSetDisableAutomaticUUID(bool set) {
252 CKKSDisableAutomaticUUID = set;
253 }
254
255 static bool CKKSDisableSOS = false;
256 bool SecCKKSTestDisableSOS(void) {
257 #if DEBUG
258 return CKKSDisableSOS;
259 #else
260 return false;
261 #endif
262 }
263 void SecCKKSTestSetDisableSOS(bool set) {
264 CKKSDisableSOS = set;
265 }
266
267
268 static bool CKKSDisableKeyNotifications = false;
269 bool SecCKKSTestDisableKeyNotifications(void) {
270 #if DEBUG
271 return CKKSDisableKeyNotifications;
272 #else
273 return false;
274 #endif
275 }
276 void SecCKKSTestSetDisableKeyNotifications(bool set) {
277 CKKSDisableKeyNotifications = set;
278 }
279
280 void SecCKKSTestResetFlags(void) {
281 SecCKKSTestSetDisableAutomaticUUID(false);
282 SecCKKSTestSetDisableSOS(false);
283 SecCKKSTestSetDisableKeyNotifications(false);
284 }
285
286 #else /* NO OCTAGON */
287
288 bool SecCKKSIsEnabled(void) {
289 secerror("CKKS was disabled at compile time.");
290 return false;
291 }
292
293 bool SecCKKSEnable() {
294 return false;
295 }
296
297 bool SecCKKSDisable() {
298 return false;
299 }
300
301 bool SecCKKSResetSyncing(void) {
302 return SecCKKSIsEnabled();
303 }
304
305 #endif /* OCTAGON */
306
307
308
309 void SecCKKSInitialize(SecDbRef db) {
310 #if OCTAGON
311 @autoreleasepool {
312 CKKSViewManager* manager = [CKKSViewManager manager];
313 [manager createViews];
314 [manager setupAnalytics];
315
316 SecDbAddNotifyPhaseBlock(db, ^(SecDbConnectionRef dbconn, SecDbTransactionPhase phase, SecDbTransactionSource source, CFArrayRef changes) {
317 SecCKKSNotifyBlock(dbconn, phase, source, changes);
318 });
319
320 [manager.completedSecCKKSInitialize fulfill];
321
322 if(!SecCKKSTestsEnabled()) {
323 static dispatch_once_t onceToken;
324 dispatch_once(&onceToken, ^{
325 [OctagonAPSReceiver receiverForEnvironment:APSEnvironmentProduction namedDelegatePort:SecCKKSAPSNamedPort apsConnectionClass:[APSConnection class]];
326 });
327 }
328 }
329 #endif
330 }
331
332 void SecCKKSNotifyBlock(SecDbConnectionRef dbconn, SecDbTransactionPhase phase, SecDbTransactionSource source, CFArrayRef changes) {
333 #if OCTAGON
334 if(phase == kSecDbTransactionDidRollback) {
335 return;
336 }
337
338 // Ignore our own changes, otherwise we'd infinite-loop.
339 if(source == kSecDbCKKSTransaction) {
340 secinfo("ckks", "Ignoring kSecDbCKKSTransaction notification");
341 return;
342 }
343
344 CFArrayForEach(changes, ^(CFTypeRef r) {
345 SecDbItemRef deleted = NULL;
346 SecDbItemRef added = NULL;
347
348 SecDbEventTranslateComponents(r, (CFTypeRef*) &deleted, (CFTypeRef*) &added);
349
350 if(!added && !deleted) {
351 secerror("CKKS: SecDbEvent gave us garbage: %@", r);
352 return;
353 }
354
355 [[CKKSViewManager manager] handleKeychainEventDbConnection: dbconn source:source added: added deleted: deleted];
356 });
357 #endif
358 }
359
360 void SecCKKS24hrNotification() {
361 #if OCTAGON
362 @autoreleasepool {
363 [[CKKSViewManager manager] xpc24HrNotification];
364 }
365 #endif
366 }
367
368 void CKKSRegisterSyncStatusCallback(CFStringRef cfuuid, SecBoolCFErrorCallback cfcallback) {
369 #if OCTAGON
370 // Keep plumbing, but transition to NS.
371 SecBoolNSErrorCallback nscallback = ^(bool result, NSError* err) {
372 cfcallback(result, (__bridge CFErrorRef) err);
373 };
374
375 [[CKKSViewManager manager] registerSyncStatusCallback: (__bridge NSString*) cfuuid callback:nscallback];
376 #endif
377 }
378
379 void SecCKKSPerformLocalResync() {
380 #if OCTAGON
381 secnotice("ckks", "Local keychain was reset; performing local resync");
382 [[CKKSViewManager manager] rpcResyncLocal:nil reply:^(NSError *result) {
383 if(result) {
384 secnotice("ckks", "Local keychain reset resync finished with an error: %@", result);
385 } else {
386 secnotice("ckks", "Local keychain reset resync finished successfully");
387 }
388 }];
389 #endif
390 }