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 SecCKKSStateZoneMismatch = (CKKSItemState*) @"zone_mismatch";
54 CKKSItemState* const SecCKKSStateDeleted = (CKKSItemState*) @"deleted";
56 CKKSProcessedState* const SecCKKSProcessedStateLocal = (CKKSProcessedState*) @"local";
57 CKKSProcessedState* const SecCKKSProcessedStateRemote = (CKKSProcessedState*) @"remote";
59 CKKSKeyClass* const SecCKKSKeyClassTLK = (CKKSKeyClass*) @"tlk";
60 CKKSKeyClass* const SecCKKSKeyClassA = (CKKSKeyClass*) @"classA";
61 CKKSKeyClass* const SecCKKSKeyClassC = (CKKSKeyClass*) @"classC";
63 NSString* SecCKKSContainerName = @"com.apple.security.keychain";
64 bool SecCKKSContainerUsePCS = false;
66 NSString* const SecCKKSSubscriptionID = @"keychain-changes";
67 NSString* const SecCKKSAPSNamedPort = @"com.apple.securityd.aps";
69 NSString* const SecCKRecordItemType = @"item";
70 NSString* const SecCKRecordHostOSVersionKey = @"uploadver";
71 NSString* const SecCKRecordEncryptionVersionKey = @"encver";
72 NSString* const SecCKRecordDataKey = @"data";
73 NSString* const SecCKRecordParentKeyRefKey = @"parentkeyref";
74 NSString* const SecCKRecordWrappedKeyKey = @"wrappedkey";
75 NSString* const SecCKRecordGenerationCountKey = @"gen";
77 NSString* const SecCKRecordPCSServiceIdentifier = @"pcsservice";
78 NSString* const SecCKRecordPCSPublicKey = @"pcspublickey";
79 NSString* const SecCKRecordPCSPublicIdentity = @"pcspublicidentity";
80 NSString* const SecCKRecordServerWasCurrent = @"server_wascurrent";
82 NSString* const SecCKRecordIntermediateKeyType = @"synckey";
83 NSString* const SecCKRecordKeyClassKey = @"class";
85 NSString* const SecCKRecordTLKShareType = @"tlkshare";
86 NSString* const SecCKRecordSenderPeerID = @"sender";
87 NSString* const SecCKRecordReceiverPeerID = @"receiver";
88 NSString* const SecCKRecordReceiverPublicEncryptionKey = @"receiverPublicEncryptionKey";
89 NSString* const SecCKRecordCurve = @"curve";
90 NSString* const SecCKRecordEpoch = @"epoch";
91 NSString* const SecCKRecordPoisoned = @"poisoned";
92 NSString* const SecCKRecordSignature = @"signature";
93 NSString* const SecCKRecordVersion = @"version";
95 NSString* const SecCKRecordCurrentKeyType = @"currentkey";
97 NSString* const SecCKRecordCurrentItemType = @"currentitem";
98 NSString* const SecCKRecordItemRefKey = @"item";
100 NSString* const SecCKRecordDeviceStateType = @"devicestate";
101 NSString* const SecCKRecordOctagonPeerID = @"octagonpeerid";
102 NSString* const SecCKRecordOctagonStatus = @"octagonstatus";
103 NSString* const SecCKRecordCirclePeerID = @"peerid";
104 NSString* const SecCKRecordCircleStatus = @"circle";
105 NSString* const SecCKRecordKeyState = @"keystate";
106 NSString* const SecCKRecordCurrentTLK = @"currentTLK";
107 NSString* const SecCKRecordCurrentClassA = @"currentClassA";
108 NSString* const SecCKRecordCurrentClassC = @"currentClassC";
109 NSString* const SecCKSRecordLastUnlockTime = @"lastunlock";
110 NSString* const SecCKSRecordOSVersionKey = @"osver";
112 NSString* const SecCKRecordManifestType = @"manifest";
113 NSString* const SecCKRecordManifestDigestValueKey = @"digest_value";
114 NSString* const SecCKRecordManifestGenerationCountKey = @"generation_count";
115 NSString* const SecCKRecordManifestLeafRecordIDsKey = @"leaf_records";
116 NSString* const SecCKRecordManifestPeerManifestRecordIDsKey = @"peer_manifests";
117 NSString* const SecCKRecordManifestCurrentItemsKey = @"current_items";
118 NSString* const SecCKRecordManifestSignaturesKey = @"signatures";
119 NSString* const SecCKRecordManifestSignerIDKey = @"signer_id";
120 NSString* const SecCKRecordManifestSchemaKey = @"schema";
122 NSString* const SecCKRecordManifestLeafType = @"manifest_leaf";
123 NSString* const SecCKRecordManifestLeafDERKey = @"der";
124 NSString* const SecCKRecordManifestLeafDigestKey = @"digest";
126 CKKSZoneKeyState* const SecCKKSZoneKeyStateReady = (CKKSZoneKeyState*) @"ready";
127 CKKSZoneKeyState* const SecCKKSZoneKeyStateReadyPendingUnlock = (CKKSZoneKeyState*) @"readypendingunlock";
128 CKKSZoneKeyState* const SecCKKSZoneKeyStateError = (CKKSZoneKeyState*) @"error";
129 CKKSZoneKeyState* const SecCKKSZoneKeyStateCancelled = (CKKSZoneKeyState*) @"cancelled";
131 CKKSZoneKeyState* const SecCKKSZoneKeyStateInitializing = (CKKSZoneKeyState*) @"initializing";
132 CKKSZoneKeyState* const SecCKKSZoneKeyStateInitialized = (CKKSZoneKeyState*) @"initialized";
133 CKKSZoneKeyState* const SecCKKSZoneKeyStateFetch = (CKKSZoneKeyState*) @"fetching";
134 CKKSZoneKeyState* const SecCKKSZoneKeyStateFetchComplete = (CKKSZoneKeyState*) @"fetchcomplete";
135 CKKSZoneKeyState* const SecCKKSZoneKeyStateNeedFullRefetch = (CKKSZoneKeyState*) @"needrefetch";
136 CKKSZoneKeyState* const SecCKKSZoneKeyStateWaitForTLK = (CKKSZoneKeyState*) @"waitfortlk";
137 CKKSZoneKeyState* const SecCKKSZoneKeyStateWaitForUnlock = (CKKSZoneKeyState*) @"waitforunlock";
138 CKKSZoneKeyState* const SecCKKSZoneKeyStateUnhealthy = (CKKSZoneKeyState*) @"unhealthy";
139 CKKSZoneKeyState* const SecCKKSZoneKeyStateBadCurrentPointers = (CKKSZoneKeyState*) @"badcurrentpointers";
140 CKKSZoneKeyState* const SecCKKSZoneKeyStateNewTLKsFailed = (CKKSZoneKeyState*) @"newtlksfailed";
141 CKKSZoneKeyState* const SecCKKSZoneKeyStateHealTLKShares = (CKKSZoneKeyState*) @"healtlkshares";
142 CKKSZoneKeyState* const SecCKKSZoneKeyStateHealTLKSharesFailed = (CKKSZoneKeyState*) @"healtlksharesfailed";
143 CKKSZoneKeyState* const SecCKKSZoneKeyStateWaitForFixupOperation = (CKKSZoneKeyState*) @"waitforfixupoperation";
144 CKKSZoneKeyState* const SecCKKSZoneKeyStateResettingZone = (CKKSZoneKeyState*) @"resetzone";
145 CKKSZoneKeyState* const SecCKKSZoneKeyStateResettingLocalData = (CKKSZoneKeyState*) @"resetlocal";
146 CKKSZoneKeyState* const SecCKKSZoneKeyStateLoggedOut = (CKKSZoneKeyState*) @"loggedout";
147 CKKSZoneKeyState* const SecCKKSZoneKeyStateZoneCreationFailed = (CKKSZoneKeyState*) @"zonecreationfailed";
148 CKKSZoneKeyState* const SecCKKSZoneKeyStateProcess = (CKKSZoneKeyState*) @"process";
150 NSDictionary<CKKSZoneKeyState*, NSNumber*>* CKKSZoneKeyStateMap(void) {
151 static NSDictionary<CKKSZoneKeyState*, NSNumber*>* map = nil;
152 static dispatch_once_t onceToken;
153 dispatch_once(&onceToken, ^{
155 SecCKKSZoneKeyStateReady: @0U,
156 SecCKKSZoneKeyStateError: @1U,
157 SecCKKSZoneKeyStateCancelled: @2U,
159 SecCKKSZoneKeyStateInitializing: @3U,
160 SecCKKSZoneKeyStateInitialized: @4U,
161 SecCKKSZoneKeyStateFetchComplete: @5U,
162 SecCKKSZoneKeyStateWaitForTLK: @6U,
163 SecCKKSZoneKeyStateWaitForUnlock: @7U,
164 SecCKKSZoneKeyStateUnhealthy: @8U,
165 SecCKKSZoneKeyStateBadCurrentPointers: @9U,
166 SecCKKSZoneKeyStateNewTLKsFailed: @10U,
167 SecCKKSZoneKeyStateNeedFullRefetch: @11U,
168 SecCKKSZoneKeyStateHealTLKShares: @12U,
169 SecCKKSZoneKeyStateHealTLKSharesFailed:@13U,
170 SecCKKSZoneKeyStateWaitForFixupOperation:@14U,
171 SecCKKSZoneKeyStateReadyPendingUnlock: @15U,
172 SecCKKSZoneKeyStateFetch: @16U,
173 SecCKKSZoneKeyStateResettingZone: @17U,
174 SecCKKSZoneKeyStateResettingLocalData: @18U,
175 SecCKKSZoneKeyStateLoggedOut: @19U,
176 SecCKKSZoneKeyStateZoneCreationFailed: @20U,
182 NSDictionary<NSNumber*, CKKSZoneKeyState*>* CKKSZoneKeyStateInverseMap(void) {
183 static NSDictionary<NSNumber*, CKKSZoneKeyState*>* backwardMap = nil;
184 static dispatch_once_t onceToken;
185 dispatch_once(&onceToken, ^{
186 NSDictionary<CKKSZoneKeyState*, NSNumber*>* forwardMap = CKKSZoneKeyStateMap();
187 backwardMap = [NSDictionary dictionaryWithObjects:[forwardMap allKeys] forKeys:[forwardMap allValues]];
192 NSNumber* CKKSZoneKeyToNumber(CKKSZoneKeyState* state) {
194 return CKKSZoneKeyStateMap()[SecCKKSZoneKeyStateError];
196 NSNumber* result = CKKSZoneKeyStateMap()[state];
200 return CKKSZoneKeyStateMap()[SecCKKSZoneKeyStateError];
202 CKKSZoneKeyState* CKKSZoneKeyRecover(NSNumber* stateNumber) {
204 return SecCKKSZoneKeyStateError;
206 CKKSZoneKeyState* result = CKKSZoneKeyStateInverseMap()[stateNumber];
210 return SecCKKSZoneKeyStateError;
213 bool CKKSKeyStateTransient(CKKSZoneKeyState* state) {
214 // Easier to compare against a blacklist of end states
215 bool nontransient = [state isEqualToString:SecCKKSZoneKeyStateReady] ||
216 [state isEqualToString:SecCKKSZoneKeyStateReadyPendingUnlock] ||
217 [state isEqualToString:SecCKKSZoneKeyStateWaitForTLK] ||
218 [state isEqualToString:SecCKKSZoneKeyStateWaitForUnlock] ||
219 [state isEqualToString:SecCKKSZoneKeyStateError] ||
220 [state isEqualToString:SecCKKSZoneKeyStateCancelled];
221 return !nontransient;
224 const NSUInteger SecCKKSItemPaddingBlockSize = 20;
226 NSString* const SecCKKSAggdPropagationDelay = @"com.apple.security.ckks.propagationdelay";
227 NSString* const SecCKKSAggdPrimaryKeyConflict = @"com.apple.security.ckks.pkconflict";
228 NSString* const SecCKKSAggdViewKeyCount = @"com.apple.security.ckks.keycount";
229 NSString* const SecCKKSAggdItemReencryption = @"com.apple.security.ckks.reencrypt";
231 NSString* const SecCKKSUserDefaultsSuite = @"com.apple.security.ckks";
233 NSString* const CKKSErrorDomain = @"CKKSErrorDomain";
234 NSString* const CKKSServerExtensionErrorDomain = @"CKKSServerExtensionErrorDomain";
237 static bool enableCKKS = true;
238 static bool testCKKS = false;
240 bool SecCKKSIsEnabled(void) {
241 if([CKDatabase class] == nil) {
242 // CloudKit is not linked. We cannot bring CKKS up; disable it with prejudice.
243 secerror("CKKS: CloudKit.framework appears to not be linked. Cannot enable CKKS (on pain of crash).");
250 bool SecCKKSEnable() {
255 bool SecCKKSDisable() {
260 bool SecCKKSResetSyncing(void) {
261 [CKKSViewManager resetManager: true setTo: nil];
262 return SecCKKSIsEnabled();
265 bool SecCKKSTestsEnabled(void) {
269 bool SecCKKSTestsEnable(void) {
270 if([CKDatabase class] == nil) {
271 // CloudKit is not linked. We cannot bring CKKS up; disable it with prejudice.
272 secerror("CKKS: CloudKit.framework appears to not be linked. Cannot enable CKKS testing.");
281 bool SecCKKSTestsDisable(void) {
286 // Feature flags to twiddle behavior
287 static bool CKKSSyncManifests = false;
288 bool SecCKKSSyncManifests(void) {
289 return CKKSSyncManifests;
291 bool SecCKKSEnableSyncManifests() {
292 CKKSSyncManifests = true;
293 return CKKSSyncManifests;
295 bool SecCKKSSetSyncManifests(bool value) {
296 CKKSSyncManifests = value;
297 return CKKSSyncManifests;
300 static bool CKKSEnforceManifests = false;
301 bool SecCKKSEnforceManifests(void) {
302 return CKKSEnforceManifests;
304 bool SecCKKSEnableEnforceManifests() {
305 CKKSEnforceManifests = true;
306 return CKKSEnforceManifests;
308 bool SecCKKSSetEnforceManifests(bool value) {
309 CKKSEnforceManifests = value;
310 return CKKSEnforceManifests;
313 // defaults write com.apple.security.ckks reduce-rate-limiting YES
314 static bool CKKSReduceRateLimiting = false;
315 bool SecCKKSReduceRateLimiting(void) {
316 static dispatch_once_t onceToken;
317 dispatch_once(&onceToken, ^{
318 // Use the default value as above, or apply the preferences value if it exists
319 NSUserDefaults* defaults = [[NSUserDefaults alloc] initWithSuiteName:SecCKKSUserDefaultsSuite];
320 NSString* key = @"reduce-rate-limiting";
321 [defaults registerDefaults: @{key: CKKSReduceRateLimiting ? @YES : @NO}];
323 CKKSReduceRateLimiting = !![defaults boolForKey:@"reduce-rate-limiting"];
324 secnotice("ckks", "reduce-rate-limiting is %@", CKKSReduceRateLimiting ? @"on" : @"off");
327 return CKKSReduceRateLimiting;
330 bool SecCKKSSetReduceRateLimiting(bool value) {
331 (void) SecCKKSReduceRateLimiting(); // Call this once to read the defaults write
332 CKKSReduceRateLimiting = value;
333 secnotice("ckks", "reduce-rate-limiting is now %@", CKKSReduceRateLimiting ? @"on" : @"off");
334 return CKKSReduceRateLimiting;
337 // Here's a mechanism for CKKS feature flags with default values from NSUserDefaults:
338 /*static bool CKKSShareTLKs = true;
339 bool SecCKKSShareTLKs(void) {
341 static dispatch_once_t onceToken;
342 dispatch_once(&onceToken, ^{
343 // Use the default value as above, or apply the preferences value if it exists
344 NSUserDefaults* defaults = [[NSUserDefaults alloc] initWithSuiteName:SecCKKSUserDefaultsSuite];
345 [defaults registerDefaults: @{@"tlksharing": CKKSShareTLKs ? @YES : @NO}];
347 CKKSShareTLKs = !![defaults boolForKey:@"tlksharing"];
348 secnotice("ckksshare", "TLK sharing is %@", CKKSShareTLKs ? @"on" : @"off");
351 return CKKSShareTLKs;
354 // Feature flags to twiddle behavior for tests
355 static bool CKKSDisableAutomaticUUID = false;
356 bool SecCKKSTestDisableAutomaticUUID(void) {
358 return CKKSDisableAutomaticUUID;
363 void SecCKKSTestSetDisableAutomaticUUID(bool set) {
364 CKKSDisableAutomaticUUID = set;
367 static bool CKKSDisableSOS = false;
368 bool SecCKKSTestDisableSOS(void) {
370 return CKKSDisableSOS;
375 void SecCKKSTestSetDisableSOS(bool set) {
376 CKKSDisableSOS = set;
380 static bool CKKSDisableKeyNotifications = false;
381 bool SecCKKSTestDisableKeyNotifications(void) {
383 return CKKSDisableKeyNotifications;
388 void SecCKKSTestSetDisableKeyNotifications(bool set) {
389 CKKSDisableKeyNotifications = set;
392 void SecCKKSTestResetFlags(void) {
393 SecCKKSTestSetDisableAutomaticUUID(false);
394 SecCKKSTestSetDisableSOS(false);
395 SecCKKSTestSetDisableKeyNotifications(false);
398 #else /* NO OCTAGON */
400 bool SecCKKSIsEnabled(void) {
401 secerror("CKKS was disabled at compile time.");
405 bool SecCKKSEnable() {
409 bool SecCKKSDisable() {
413 bool SecCKKSResetSyncing(void) {
414 return SecCKKSIsEnabled();
421 void SecCKKSInitialize(SecDbRef db) {
424 CKKSViewManager* manager = [CKKSViewManager manager];
425 [manager initializeZones];
427 SecDbAddNotifyPhaseBlock(db, ^(SecDbConnectionRef dbconn, SecDbTransactionPhase phase, SecDbTransactionSource source, CFArrayRef changes) {
428 SecCKKSNotifyBlock(dbconn, phase, source, changes);
431 [manager.completedSecCKKSInitialize fulfill];
436 void SecCKKSNotifyBlock(SecDbConnectionRef dbconn, SecDbTransactionPhase phase, SecDbTransactionSource source, CFArrayRef changes) {
438 if(phase == kSecDbTransactionDidRollback) {
442 // Ignore our own changes, otherwise we'd infinite-loop.
443 if(source == kSecDbCKKSTransaction) {
444 secinfo("ckks", "Ignoring kSecDbCKKSTransaction notification");
448 CFArrayForEach(changes, ^(CFTypeRef r) {
449 SecDbItemRef deleted = NULL;
450 SecDbItemRef added = NULL;
452 SecDbEventTranslateComponents(r, (CFTypeRef*) &deleted, (CFTypeRef*) &added);
454 if(!added && !deleted) {
455 secerror("CKKS: SecDbEvent gave us garbage: %@", r);
459 [[CKKSViewManager manager] handleKeychainEventDbConnection: dbconn source:source added: added deleted: deleted];
464 void SecCKKS24hrNotification() {
467 [[CKKSViewManager manager] xpc24HrNotification];
472 void CKKSRegisterSyncStatusCallback(CFStringRef cfuuid, SecBoolCFErrorCallback cfcallback) {
474 // Keep plumbing, but transition to NS.
475 SecBoolNSErrorCallback nscallback = ^(bool result, NSError* err) {
476 cfcallback(result, (__bridge CFErrorRef) err);
479 [[CKKSViewManager manager] registerSyncStatusCallback: (__bridge NSString*) cfuuid callback:nscallback];
483 void SecCKKSPerformLocalResync() {
485 secnotice("ckks", "Local keychain was reset; performing local resync");
486 [[CKKSViewManager manager] rpcResyncLocal:nil reply:^(NSError *result) {
488 secnotice("ckks", "Local keychain reset resync finished with an error: %@", result);
490 secnotice("ckks", "Local keychain reset resync finished successfully");
496 NSString* SecCKKSHostOSVersion()
499 // Use complicated macro magic to get the string value passed in as preprocessor define PLATFORM.
500 #define PLATFORM_VALUE(f) #f
501 #define PLATFORM_OBJCSTR(f) @PLATFORM_VALUE(f)
502 NSString* platform = (PLATFORM_OBJCSTR(PLATFORM));
503 #undef PLATFORM_OBJCSTR
504 #undef PLATFORM_VALUE
506 NSString* platform = "unknown";
507 #warning No PLATFORM defined; why?
510 NSString* osversion = nil;
512 // If we can get the build information from sysctl, use it.
514 size_t releasesize = sizeof(release);
515 bool haveSysctlInfo = true;
516 haveSysctlInfo &= (0 == sysctlbyname("kern.osrelease", release, &releasesize, NULL, 0));
519 size_t versionsize = sizeof(version);
520 haveSysctlInfo &= (0 == sysctlbyname("kern.osversion", version, &versionsize, NULL, 0));
523 // Null-terminate for extra safety
524 release[sizeof(release)-1] = '\0';
525 version[sizeof(version)-1] = '\0';
526 osversion = [NSString stringWithFormat:@"%s (%s)", release, version];
530 // Otherwise, use the not-really-supported fallback.
531 osversion = [[NSProcessInfo processInfo] operatingSystemVersionString];
533 // subtly improve osversion (but it's okay if that does nothing)
534 osversion = [osversion stringByReplacingOccurrencesOfString:@"Version" withString:@""];
537 return [NSString stringWithFormat:@"%@ %@", platform, osversion];