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>
26 #include <sys/sysctl.h>
28 #import <CloudKit/CloudKit.h>
31 #include <utilities/debugging.h>
32 #include <securityd/SecItemServer.h>
33 #include <Security/SecItemPriv.h>
35 #import <Foundation/Foundation.h>
36 #import "keychain/ckks/CKKS.h"
37 #import "keychain/ckks/CKKSKeychainView.h"
38 #import "keychain/ckks/CKKSViewManager.h"
39 #import "keychain/ckks/CKKSKey.h"
41 #import "keychain/ot/OTManager.h"
42 const SecCKKSItemEncryptionVersion currentCKKSItemEncryptionVersion = CKKSItemEncryptionVersion2;
44 NSString* const SecCKKSActionAdd = @"add";
45 NSString* const SecCKKSActionDelete = @"delete";
46 NSString* const SecCKKSActionModify = @"modify";
48 CKKSItemState* const SecCKKSStateNew = (CKKSItemState*) @"new";
49 CKKSItemState* const SecCKKSStateUnauthenticated = (CKKSItemState*) @"unauthenticated";
50 CKKSItemState* const SecCKKSStateInFlight = (CKKSItemState*) @"inflight";
51 CKKSItemState* const SecCKKSStateReencrypt = (CKKSItemState*) @"reencrypt";
52 CKKSItemState* const SecCKKSStateError = (CKKSItemState*) @"error";
53 CKKSItemState* const SecCKKSStateDeleted = (CKKSItemState*) @"deleted";
55 CKKSProcessedState* const SecCKKSProcessedStateLocal = (CKKSProcessedState*) @"local";
56 CKKSProcessedState* const SecCKKSProcessedStateRemote = (CKKSProcessedState*) @"remote";
58 CKKSKeyClass* const SecCKKSKeyClassTLK = (CKKSKeyClass*) @"tlk";
59 CKKSKeyClass* const SecCKKSKeyClassA = (CKKSKeyClass*) @"classA";
60 CKKSKeyClass* const SecCKKSKeyClassC = (CKKSKeyClass*) @"classC";
62 NSString* SecCKKSContainerName = @"com.apple.security.keychain";
63 bool SecCKKSContainerUsePCS = false;
65 NSString* const SecCKKSSubscriptionID = @"keychain-changes";
66 NSString* const SecCKKSAPSNamedPort = @"com.apple.securityd.aps";
68 NSString* const SecCKRecordItemType = @"item";
69 NSString* const SecCKRecordHostOSVersionKey = @"uploadver";
70 NSString* const SecCKRecordEncryptionVersionKey = @"encver";
71 NSString* const SecCKRecordDataKey = @"data";
72 NSString* const SecCKRecordParentKeyRefKey = @"parentkeyref";
73 NSString* const SecCKRecordWrappedKeyKey = @"wrappedkey";
74 NSString* const SecCKRecordGenerationCountKey = @"gen";
76 NSString* const SecCKRecordPCSServiceIdentifier = @"pcsservice";
77 NSString* const SecCKRecordPCSPublicKey = @"pcspublickey";
78 NSString* const SecCKRecordPCSPublicIdentity = @"pcspublicidentity";
79 NSString* const SecCKRecordServerWasCurrent = @"server_wascurrent";
81 NSString* const SecCKRecordIntermediateKeyType = @"synckey";
82 NSString* const SecCKRecordKeyClassKey = @"class";
84 NSString* const SecCKRecordTLKShareType = @"tlkshare";
85 NSString* const SecCKRecordSenderPeerID = @"sender";
86 NSString* const SecCKRecordReceiverPeerID = @"receiver";
87 NSString* const SecCKRecordReceiverPublicEncryptionKey = @"receiverPublicEncryptionKey";
88 NSString* const SecCKRecordCurve = @"curve";
89 NSString* const SecCKRecordEpoch = @"epoch";
90 NSString* const SecCKRecordPoisoned = @"poisoned";
91 NSString* const SecCKRecordSignature = @"signature";
92 NSString* const SecCKRecordVersion = @"version";
94 NSString* const SecCKRecordCurrentKeyType = @"currentkey";
96 NSString* const SecCKRecordCurrentItemType = @"currentitem";
97 NSString* const SecCKRecordItemRefKey = @"item";
99 NSString* const SecCKRecordDeviceStateType = @"devicestate";
100 NSString* const SecCKRecordCirclePeerID = @"peerid";
101 NSString* const SecCKRecordCircleStatus = @"circle";
102 NSString* const SecCKRecordKeyState = @"keystate";
103 NSString* const SecCKRecordCurrentTLK = @"currentTLK";
104 NSString* const SecCKRecordCurrentClassA = @"currentClassA";
105 NSString* const SecCKRecordCurrentClassC = @"currentClassC";
106 NSString* const SecCKSRecordLastUnlockTime = @"lastunlock";
107 NSString* const SecCKSRecordOSVersionKey = @"osver";
109 NSString* const SecCKRecordManifestType = @"manifest";
110 NSString* const SecCKRecordManifestDigestValueKey = @"digest_value";
111 NSString* const SecCKRecordManifestGenerationCountKey = @"generation_count";
112 NSString* const SecCKRecordManifestLeafRecordIDsKey = @"leaf_records";
113 NSString* const SecCKRecordManifestPeerManifestRecordIDsKey = @"peer_manifests";
114 NSString* const SecCKRecordManifestCurrentItemsKey = @"current_items";
115 NSString* const SecCKRecordManifestSignaturesKey = @"signatures";
116 NSString* const SecCKRecordManifestSignerIDKey = @"signer_id";
117 NSString* const SecCKRecordManifestSchemaKey = @"schema";
119 NSString* const SecCKRecordManifestLeafType = @"manifest_leaf";
120 NSString* const SecCKRecordManifestLeafDERKey = @"der";
121 NSString* const SecCKRecordManifestLeafDigestKey = @"digest";
123 CKKSZoneKeyState* const SecCKKSZoneKeyStateReady = (CKKSZoneKeyState*) @"ready";
124 CKKSZoneKeyState* const SecCKKSZoneKeyStateReadyPendingUnlock = (CKKSZoneKeyState*) @"readypendingunlock";
125 CKKSZoneKeyState* const SecCKKSZoneKeyStateError = (CKKSZoneKeyState*) @"error";
126 CKKSZoneKeyState* const SecCKKSZoneKeyStateCancelled = (CKKSZoneKeyState*) @"cancelled";
128 CKKSZoneKeyState* const SecCKKSZoneKeyStateInitializing = (CKKSZoneKeyState*) @"initializing";
129 CKKSZoneKeyState* const SecCKKSZoneKeyStateInitialized = (CKKSZoneKeyState*) @"initialized";
130 CKKSZoneKeyState* const SecCKKSZoneKeyStateFetch = (CKKSZoneKeyState*) @"fetching";
131 CKKSZoneKeyState* const SecCKKSZoneKeyStateFetchComplete = (CKKSZoneKeyState*) @"fetchcomplete";
132 CKKSZoneKeyState* const SecCKKSZoneKeyStateNeedFullRefetch = (CKKSZoneKeyState*) @"needrefetch";
133 CKKSZoneKeyState* const SecCKKSZoneKeyStateWaitForTLK = (CKKSZoneKeyState*) @"waitfortlk";
134 CKKSZoneKeyState* const SecCKKSZoneKeyStateWaitForUnlock = (CKKSZoneKeyState*) @"waitforunlock";
135 CKKSZoneKeyState* const SecCKKSZoneKeyStateUnhealthy = (CKKSZoneKeyState*) @"unhealthy";
136 CKKSZoneKeyState* const SecCKKSZoneKeyStateBadCurrentPointers = (CKKSZoneKeyState*) @"badcurrentpointers";
137 CKKSZoneKeyState* const SecCKKSZoneKeyStateNewTLKsFailed = (CKKSZoneKeyState*) @"newtlksfailed";
138 CKKSZoneKeyState* const SecCKKSZoneKeyStateHealTLKShares = (CKKSZoneKeyState*) @"healtlkshares";
139 CKKSZoneKeyState* const SecCKKSZoneKeyStateHealTLKSharesFailed = (CKKSZoneKeyState*) @"healtlksharesfailed";
140 CKKSZoneKeyState* const SecCKKSZoneKeyStateWaitForFixupOperation = (CKKSZoneKeyState*) @"waitforfixupoperation";
141 CKKSZoneKeyState* const SecCKKSZoneKeyStateResettingZone = (CKKSZoneKeyState*) @"resetzone";
142 CKKSZoneKeyState* const SecCKKSZoneKeyStateResettingLocalData = (CKKSZoneKeyState*) @"resetlocal";
143 CKKSZoneKeyState* const SecCKKSZoneKeyStateLoggedOut = (CKKSZoneKeyState*) @"loggedout";
144 CKKSZoneKeyState* const SecCKKSZoneKeyStateZoneCreationFailed = (CKKSZoneKeyState*) @"zonecreationfailed";
145 CKKSZoneKeyState* const SecCKKSZoneKeyStateProcess = (CKKSZoneKeyState*) @"process";
147 NSDictionary<CKKSZoneKeyState*, NSNumber*>* CKKSZoneKeyStateMap(void) {
148 static NSDictionary<CKKSZoneKeyState*, NSNumber*>* map = nil;
149 static dispatch_once_t onceToken;
150 dispatch_once(&onceToken, ^{
152 SecCKKSZoneKeyStateReady: @0U,
153 SecCKKSZoneKeyStateError: @1U,
154 SecCKKSZoneKeyStateCancelled: @2U,
156 SecCKKSZoneKeyStateInitializing: @3U,
157 SecCKKSZoneKeyStateInitialized: @4U,
158 SecCKKSZoneKeyStateFetchComplete: @5U,
159 SecCKKSZoneKeyStateWaitForTLK: @6U,
160 SecCKKSZoneKeyStateWaitForUnlock: @7U,
161 SecCKKSZoneKeyStateUnhealthy: @8U,
162 SecCKKSZoneKeyStateBadCurrentPointers: @9U,
163 SecCKKSZoneKeyStateNewTLKsFailed: @10U,
164 SecCKKSZoneKeyStateNeedFullRefetch: @11U,
165 SecCKKSZoneKeyStateHealTLKShares: @12U,
166 SecCKKSZoneKeyStateHealTLKSharesFailed:@13U,
167 SecCKKSZoneKeyStateWaitForFixupOperation:@14U,
168 SecCKKSZoneKeyStateReadyPendingUnlock: @15U,
169 SecCKKSZoneKeyStateFetch: @16U,
170 SecCKKSZoneKeyStateResettingZone: @17U,
171 SecCKKSZoneKeyStateResettingLocalData: @18U,
172 SecCKKSZoneKeyStateLoggedOut: @19U,
173 SecCKKSZoneKeyStateZoneCreationFailed: @20U,
179 NSDictionary<NSNumber*, CKKSZoneKeyState*>* CKKSZoneKeyStateInverseMap(void) {
180 static NSDictionary<NSNumber*, CKKSZoneKeyState*>* backwardMap = nil;
181 static dispatch_once_t onceToken;
182 dispatch_once(&onceToken, ^{
183 NSDictionary<CKKSZoneKeyState*, NSNumber*>* forwardMap = CKKSZoneKeyStateMap();
184 backwardMap = [NSDictionary dictionaryWithObjects:[forwardMap allKeys] forKeys:[forwardMap allValues]];
189 NSNumber* CKKSZoneKeyToNumber(CKKSZoneKeyState* state) {
191 return CKKSZoneKeyStateMap()[SecCKKSZoneKeyStateError];
193 NSNumber* result = CKKSZoneKeyStateMap()[state];
197 return CKKSZoneKeyStateMap()[SecCKKSZoneKeyStateError];
199 CKKSZoneKeyState* CKKSZoneKeyRecover(NSNumber* stateNumber) {
201 return SecCKKSZoneKeyStateError;
203 CKKSZoneKeyState* result = CKKSZoneKeyStateInverseMap()[stateNumber];
207 return SecCKKSZoneKeyStateError;
210 bool CKKSKeyStateTransient(CKKSZoneKeyState* state) {
211 // Easier to compare against a blacklist of end states
212 bool nontransient = [state isEqualToString:SecCKKSZoneKeyStateReady] ||
213 [state isEqualToString:SecCKKSZoneKeyStateReadyPendingUnlock] ||
214 [state isEqualToString:SecCKKSZoneKeyStateWaitForTLK] ||
215 [state isEqualToString:SecCKKSZoneKeyStateWaitForUnlock] ||
216 [state isEqualToString:SecCKKSZoneKeyStateError] ||
217 [state isEqualToString:SecCKKSZoneKeyStateCancelled];
218 return !nontransient;
221 const NSUInteger SecCKKSItemPaddingBlockSize = 20;
223 NSString* const SecCKKSAggdPropagationDelay = @"com.apple.security.ckks.propagationdelay";
224 NSString* const SecCKKSAggdPrimaryKeyConflict = @"com.apple.security.ckks.pkconflict";
225 NSString* const SecCKKSAggdViewKeyCount = @"com.apple.security.ckks.keycount";
226 NSString* const SecCKKSAggdItemReencryption = @"com.apple.security.ckks.reencrypt";
228 NSString* const SecCKKSUserDefaultsSuite = @"com.apple.security.ckks";
230 NSString* const CKKSErrorDomain = @"CKKSErrorDomain";
231 NSString* const CKKSServerExtensionErrorDomain = @"CKKSServerExtensionErrorDomain";
234 static bool enableCKKS = true;
235 static bool testCKKS = false;
237 bool SecCKKSIsEnabled(void) {
238 if([CKDatabase class] == nil) {
239 // CloudKit is not linked. We cannot bring CKKS up; disable it with prejudice.
240 secerror("CKKS: CloudKit.framework appears to not be linked. Cannot enable CKKS (on pain of crash).");
247 bool SecCKKSEnable() {
252 bool SecCKKSDisable() {
257 bool SecCKKSResetSyncing(void) {
258 [CKKSViewManager resetManager: true setTo: nil];
259 return SecCKKSIsEnabled();
262 bool SecCKKSTestsEnabled(void) {
266 bool SecCKKSTestsEnable(void) {
267 if([CKDatabase class] == nil) {
268 // CloudKit is not linked. We cannot bring CKKS up; disable it with prejudice.
269 secerror("CKKS: CloudKit.framework appears to not be linked. Cannot enable CKKS testing.");
278 bool SecCKKSTestsDisable(void) {
283 // Feature flags to twiddle behavior
284 static bool CKKSSyncManifests = false;
285 bool SecCKKSSyncManifests(void) {
286 return CKKSSyncManifests;
288 bool SecCKKSEnableSyncManifests() {
289 CKKSSyncManifests = true;
290 return CKKSSyncManifests;
292 bool SecCKKSSetSyncManifests(bool value) {
293 CKKSSyncManifests = value;
294 return CKKSSyncManifests;
297 static bool CKKSEnforceManifests = false;
298 bool SecCKKSEnforceManifests(void) {
299 return CKKSEnforceManifests;
301 bool SecCKKSEnableEnforceManifests() {
302 CKKSEnforceManifests = true;
303 return CKKSEnforceManifests;
305 bool SecCKKSSetEnforceManifests(bool value) {
306 CKKSEnforceManifests = value;
307 return CKKSEnforceManifests;
310 // defaults write com.apple.security.ckks reduce-rate-limiting YES
311 static bool CKKSReduceRateLimiting = false;
312 bool SecCKKSReduceRateLimiting(void) {
313 static dispatch_once_t onceToken;
314 dispatch_once(&onceToken, ^{
315 // Use the default value as above, or apply the preferences value if it exists
316 NSUserDefaults* defaults = [[NSUserDefaults alloc] initWithSuiteName:SecCKKSUserDefaultsSuite];
317 NSString* key = @"reduce-rate-limiting";
318 [defaults registerDefaults: @{key: CKKSReduceRateLimiting ? @YES : @NO}];
320 CKKSReduceRateLimiting = !![defaults boolForKey:@"reduce-rate-limiting"];
321 secnotice("ckks", "reduce-rate-limiting is %@", CKKSReduceRateLimiting ? @"on" : @"off");
324 return CKKSReduceRateLimiting;
327 bool SecCKKSSetReduceRateLimiting(bool value) {
328 (void) SecCKKSReduceRateLimiting(); // Call this once to read the defaults write
329 CKKSReduceRateLimiting = value;
330 secnotice("ckks", "reduce-rate-limiting is now %@", CKKSReduceRateLimiting ? @"on" : @"off");
331 return CKKSReduceRateLimiting;
334 // Here's a mechanism for CKKS feature flags with default values from NSUserDefaults:
335 /*static bool CKKSShareTLKs = true;
336 bool SecCKKSShareTLKs(void) {
338 static dispatch_once_t onceToken;
339 dispatch_once(&onceToken, ^{
340 // Use the default value as above, or apply the preferences value if it exists
341 NSUserDefaults* defaults = [[NSUserDefaults alloc] initWithSuiteName:SecCKKSUserDefaultsSuite];
342 [defaults registerDefaults: @{@"tlksharing": CKKSShareTLKs ? @YES : @NO}];
344 CKKSShareTLKs = !![defaults boolForKey:@"tlksharing"];
345 secnotice("ckksshare", "TLK sharing is %@", CKKSShareTLKs ? @"on" : @"off");
348 return CKKSShareTLKs;
351 // Feature flags to twiddle behavior for tests
352 static bool CKKSDisableAutomaticUUID = false;
353 bool SecCKKSTestDisableAutomaticUUID(void) {
355 return CKKSDisableAutomaticUUID;
360 void SecCKKSTestSetDisableAutomaticUUID(bool set) {
361 CKKSDisableAutomaticUUID = set;
364 static bool CKKSDisableSOS = false;
365 bool SecCKKSTestDisableSOS(void) {
367 return CKKSDisableSOS;
372 void SecCKKSTestSetDisableSOS(bool set) {
373 CKKSDisableSOS = set;
377 static bool CKKSDisableKeyNotifications = false;
378 bool SecCKKSTestDisableKeyNotifications(void) {
380 return CKKSDisableKeyNotifications;
385 void SecCKKSTestSetDisableKeyNotifications(bool set) {
386 CKKSDisableKeyNotifications = set;
389 void SecCKKSTestResetFlags(void) {
390 SecCKKSTestSetDisableAutomaticUUID(false);
391 SecCKKSTestSetDisableSOS(false);
392 SecCKKSTestSetDisableKeyNotifications(false);
395 #else /* NO OCTAGON */
397 bool SecCKKSIsEnabled(void) {
398 secerror("CKKS was disabled at compile time.");
402 bool SecCKKSEnable() {
406 bool SecCKKSDisable() {
410 bool SecCKKSResetSyncing(void) {
411 return SecCKKSIsEnabled();
418 void SecCKKSInitialize(SecDbRef db) {
421 CKKSViewManager* manager = [CKKSViewManager manager];
422 [manager initializeZones];
424 SecDbAddNotifyPhaseBlock(db, ^(SecDbConnectionRef dbconn, SecDbTransactionPhase phase, SecDbTransactionSource source, CFArrayRef changes) {
425 SecCKKSNotifyBlock(dbconn, phase, source, changes);
428 [manager.completedSecCKKSInitialize fulfill];
433 void SecCKKSNotifyBlock(SecDbConnectionRef dbconn, SecDbTransactionPhase phase, SecDbTransactionSource source, CFArrayRef changes) {
435 if(phase == kSecDbTransactionDidRollback) {
439 // Ignore our own changes, otherwise we'd infinite-loop.
440 if(source == kSecDbCKKSTransaction) {
441 secinfo("ckks", "Ignoring kSecDbCKKSTransaction notification");
445 CFArrayForEach(changes, ^(CFTypeRef r) {
446 SecDbItemRef deleted = NULL;
447 SecDbItemRef added = NULL;
449 SecDbEventTranslateComponents(r, (CFTypeRef*) &deleted, (CFTypeRef*) &added);
451 if(!added && !deleted) {
452 secerror("CKKS: SecDbEvent gave us garbage: %@", r);
456 [[CKKSViewManager manager] handleKeychainEventDbConnection: dbconn source:source added: added deleted: deleted];
461 void SecCKKS24hrNotification() {
464 [[CKKSViewManager manager] xpc24HrNotification];
469 void CKKSRegisterSyncStatusCallback(CFStringRef cfuuid, SecBoolCFErrorCallback cfcallback) {
471 // Keep plumbing, but transition to NS.
472 SecBoolNSErrorCallback nscallback = ^(bool result, NSError* err) {
473 cfcallback(result, (__bridge CFErrorRef) err);
476 [[CKKSViewManager manager] registerSyncStatusCallback: (__bridge NSString*) cfuuid callback:nscallback];
480 void SecCKKSPerformLocalResync() {
482 secnotice("ckks", "Local keychain was reset; performing local resync");
483 [[CKKSViewManager manager] rpcResyncLocal:nil reply:^(NSError *result) {
485 secnotice("ckks", "Local keychain reset resync finished with an error: %@", result);
487 secnotice("ckks", "Local keychain reset resync finished successfully");
493 NSString* SecCKKSHostOSVersion()
496 // Use complicated macro magic to get the string value passed in as preprocessor define PLATFORM.
497 #define PLATFORM_VALUE(f) #f
498 #define PLATFORM_OBJCSTR(f) @PLATFORM_VALUE(f)
499 NSString* platform = (PLATFORM_OBJCSTR(PLATFORM));
500 #undef PLATFORM_OBJCSTR
501 #undef PLATFORM_VALUE
503 NSString* platform = "unknown";
504 #warning No PLATFORM defined; why?
507 NSString* osversion = nil;
509 // If we can get the build information from sysctl, use it.
511 size_t releasesize = sizeof(release);
512 bool haveSysctlInfo = true;
513 haveSysctlInfo &= (0 == sysctlbyname("kern.osrelease", release, &releasesize, NULL, 0));
516 size_t versionsize = sizeof(version);
517 haveSysctlInfo &= (0 == sysctlbyname("kern.osversion", version, &versionsize, NULL, 0));
520 // Null-terminate for extra safety
521 release[sizeof(release)-1] = '\0';
522 version[sizeof(version)-1] = '\0';
523 osversion = [NSString stringWithFormat:@"%s (%s)", release, version];
527 // Otherwise, use the not-really-supported fallback.
528 osversion = [[NSProcessInfo processInfo] operatingSystemVersionString];
530 // subtly improve osversion (but it's okay if that does nothing)
531 osversion = [osversion stringByReplacingOccurrencesOfString:@"Version" withString:@""];
534 return [NSString stringWithFormat:@"%@ %@", platform, osversion];