2 * Copyright (c) 2016 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 #include <dispatch/dispatch.h>
25 #import <Foundation/Foundation.h>
27 #import <CloudKit/CloudKit.h>
30 #include <utilities/debugging.h>
31 #include "keychain/securityd/SecItemServer.h"
32 #include <Security/SecItemPriv.h>
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"
40 #import "keychain/ot/OTManager.h"
42 NSDictionary<CKKSZoneKeyState*, NSNumber*>* CKKSZoneKeyStateMap(void) {
43 static NSDictionary<CKKSZoneKeyState*, NSNumber*>* map = nil;
44 static dispatch_once_t onceToken;
45 dispatch_once(&onceToken, ^{
47 SecCKKSZoneKeyStateReady: @0U,
48 SecCKKSZoneKeyStateError: @1U,
49 SecCKKSZoneKeyStateCancelled: @2U,
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,
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]];
88 NSNumber* CKKSZoneKeyToNumber(CKKSZoneKeyState* state) {
90 return CKKSZoneKeyStateMap()[SecCKKSZoneKeyStateError];
92 NSNumber* result = CKKSZoneKeyStateMap()[state];
96 return CKKSZoneKeyStateMap()[SecCKKSZoneKeyStateError];
98 CKKSZoneKeyState* CKKSZoneKeyRecover(NSNumber* stateNumber) {
100 return SecCKKSZoneKeyStateError;
102 CKKSZoneKeyState* result = CKKSZoneKeyStateInverseMap()[stateNumber];
106 return SecCKKSZoneKeyStateError;
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;
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;
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).");
138 bool SecCKKSEnable() {
143 bool SecCKKSDisable() {
148 bool SecCKKSResetSyncing(void) {
149 [CKKSViewManager resetManager: true setTo: nil];
150 return SecCKKSIsEnabled();
153 bool SecCKKSTestsEnabled(void) {
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.");
169 bool SecCKKSTestsDisable(void) {
174 // Feature flags to twiddle behavior
175 static bool CKKSSyncManifests = false;
176 bool SecCKKSSyncManifests(void) {
177 return CKKSSyncManifests;
179 bool SecCKKSEnableSyncManifests() {
180 CKKSSyncManifests = true;
181 return CKKSSyncManifests;
183 bool SecCKKSSetSyncManifests(bool value) {
184 CKKSSyncManifests = value;
185 return CKKSSyncManifests;
188 static bool CKKSEnforceManifests = false;
189 bool SecCKKSEnforceManifests(void) {
190 return CKKSEnforceManifests;
192 bool SecCKKSEnableEnforceManifests() {
193 CKKSEnforceManifests = true;
194 return CKKSEnforceManifests;
196 bool SecCKKSSetEnforceManifests(bool value) {
197 CKKSEnforceManifests = value;
198 return CKKSEnforceManifests;
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}];
211 CKKSReduceRateLimiting = !![defaults boolForKey:@"reduce-rate-limiting"];
212 secnotice("ckks", "reduce-rate-limiting is %@", CKKSReduceRateLimiting ? @"on" : @"off");
215 return CKKSReduceRateLimiting;
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;
225 // Here's a mechanism for CKKS feature flags with default values from NSUserDefaults:
226 /*static bool CKKSShareTLKs = true;
227 bool SecCKKSShareTLKs(void) {
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}];
235 CKKSShareTLKs = !![defaults boolForKey:@"tlksharing"];
236 secnotice("ckksshare", "TLK sharing is %@", CKKSShareTLKs ? @"on" : @"off");
239 return CKKSShareTLKs;
242 // Feature flags to twiddle behavior for tests
243 static bool CKKSDisableAutomaticUUID = false;
244 bool SecCKKSTestDisableAutomaticUUID(void) {
246 return CKKSDisableAutomaticUUID;
251 void SecCKKSTestSetDisableAutomaticUUID(bool set) {
252 CKKSDisableAutomaticUUID = set;
255 static bool CKKSDisableSOS = false;
256 bool SecCKKSTestDisableSOS(void) {
258 return CKKSDisableSOS;
263 void SecCKKSTestSetDisableSOS(bool set) {
264 CKKSDisableSOS = set;
268 static bool CKKSDisableKeyNotifications = false;
269 bool SecCKKSTestDisableKeyNotifications(void) {
271 return CKKSDisableKeyNotifications;
276 void SecCKKSTestSetDisableKeyNotifications(bool set) {
277 CKKSDisableKeyNotifications = set;
280 void SecCKKSTestResetFlags(void) {
281 SecCKKSTestSetDisableAutomaticUUID(false);
282 SecCKKSTestSetDisableSOS(false);
283 SecCKKSTestSetDisableKeyNotifications(false);
286 #else /* NO OCTAGON */
288 bool SecCKKSIsEnabled(void) {
289 secerror("CKKS was disabled at compile time.");
293 bool SecCKKSEnable() {
297 bool SecCKKSDisable() {
301 bool SecCKKSResetSyncing(void) {
302 return SecCKKSIsEnabled();
309 void SecCKKSInitialize(SecDbRef db) {
312 CKKSViewManager* manager = [CKKSViewManager manager];
313 [manager createViews];
314 [manager setupAnalytics];
316 SecDbAddNotifyPhaseBlock(db, ^(SecDbConnectionRef dbconn, SecDbTransactionPhase phase, SecDbTransactionSource source, CFArrayRef changes) {
317 SecCKKSNotifyBlock(dbconn, phase, source, changes);
320 [manager.completedSecCKKSInitialize fulfill];
322 if(!SecCKKSTestsEnabled()) {
323 static dispatch_once_t onceToken;
324 dispatch_once(&onceToken, ^{
325 [OctagonAPSReceiver receiverForEnvironment:APSEnvironmentProduction namedDelegatePort:SecCKKSAPSNamedPort apsConnectionClass:[APSConnection class]];
332 void SecCKKSNotifyBlock(SecDbConnectionRef dbconn, SecDbTransactionPhase phase, SecDbTransactionSource source, CFArrayRef changes) {
334 if(phase == kSecDbTransactionDidRollback) {
338 // Ignore our own changes, otherwise we'd infinite-loop.
339 if(source == kSecDbCKKSTransaction) {
340 secinfo("ckks", "Ignoring kSecDbCKKSTransaction notification");
344 CFArrayForEach(changes, ^(CFTypeRef r) {
345 SecDbItemRef deleted = NULL;
346 SecDbItemRef added = NULL;
348 SecDbEventTranslateComponents(r, (CFTypeRef*) &deleted, (CFTypeRef*) &added);
350 if(!added && !deleted) {
351 secerror("CKKS: SecDbEvent gave us garbage: %@", r);
355 [[CKKSViewManager manager] handleKeychainEventDbConnection: dbconn source:source added: added deleted: deleted];
360 void SecCKKS24hrNotification() {
363 [[CKKSViewManager manager] xpc24HrNotification];
368 void CKKSRegisterSyncStatusCallback(CFStringRef cfuuid, SecBoolCFErrorCallback cfcallback) {
370 // Keep plumbing, but transition to NS.
371 SecBoolNSErrorCallback nscallback = ^(bool result, NSError* err) {
372 cfcallback(result, (__bridge CFErrorRef) err);
375 [[CKKSViewManager manager] registerSyncStatusCallback: (__bridge NSString*) cfuuid callback:nscallback];
379 void SecCKKSPerformLocalResync() {
381 secnotice("ckks", "Local keychain was reset; performing local resync");
382 [[CKKSViewManager manager] rpcResyncLocal:nil reply:^(NSError *result) {
384 secnotice("ckks", "Local keychain reset resync finished with an error: %@", result);
386 secnotice("ckks", "Local keychain reset resync finished successfully");