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@
25 #import <Foundation/Foundation.h>
26 #include <dispatch/dispatch.h>
28 #import "keychain/analytics/CKKSLaunchSequence.h"
29 #import "keychain/ckks/OctagonAPSReceiver.h"
30 #import "keychain/ckks/CKKSLockStateTracker.h"
31 #import "keychain/ckks/CKKSReachabilityTracker.h"
32 #import "keychain/ckks/CloudKitDependencies.h"
34 #include "keychain/securityd/SecDbItem.h"
35 #include <utilities/SecDb.h>
37 #import "keychain/ckks/CKKS.h"
38 #import "keychain/ckks/CKKSFetchAllRecordZoneChangesOperation.h"
39 #import "keychain/ckks/CKKSGroupOperation.h"
40 #import "keychain/ckks/CKKSIncomingQueueOperation.h"
41 #import "keychain/ckks/CKKSNearFutureScheduler.h"
42 #import "keychain/ckks/CKKSNewTLKOperation.h"
43 #import "keychain/ckks/CKKSNotifier.h"
44 #import "keychain/ckks/CKKSOutgoingQueueOperation.h"
45 #import "keychain/ckks/CKKSPeer.h"
46 #import "keychain/ckks/CKKSPeerProvider.h"
47 #import "keychain/ckks/CKKSProcessReceivedKeysOperation.h"
48 #import "keychain/ckks/CKKSReencryptOutgoingItemsOperation.h"
49 #import "keychain/ckks/CKKSScanLocalItemsOperation.h"
50 #import "keychain/ckks/CKKSTLKShareRecord.h"
51 #import "keychain/ckks/CKKSUpdateDeviceStateOperation.h"
52 #import "keychain/ckks/CKKSZone.h"
53 #import "keychain/ckks/CKKSZoneModifier.h"
54 #import "keychain/ckks/CKKSZoneChangeFetcher.h"
55 #import "keychain/ckks/CKKSSynchronizeOperation.h"
56 #import "keychain/ckks/CKKSLocalSynchronizeOperation.h"
57 #import "keychain/ckks/CKKSProvideKeySetOperation.h"
61 NS_ASSUME_NONNULL_BEGIN
65 @
class CKKSSynchronizeOperation
;
66 @
class CKKSRateLimiter
;
68 @
class CKKSEgoManifest
;
69 @
class CKKSOutgoingQueueEntry
;
70 @
class CKKSZoneChangeFetcher
;
71 @
class CKKSCurrentKeySet
;
73 @interface CKKSKeychainView
: CKKSZone
<CKKSZoneUpdateReceiver
,
74 CKKSChangeFetcherClient
,
75 CKKSPeerUpdateListener
>
77 CKKSZoneKeyState
* _keyHierarchyState
;
80 @property CKKSCondition
* loggedIn
;
81 @property CKKSCondition
* loggedOut
;
82 @property CKKSCondition
* accountStateKnown
;
84 @property CKKSAccountStatus trustStatus
;
85 @
property (nullable
) CKKSResultOperation
* trustDependency
;
87 @
property (nullable
) CKKSLaunchSequence
*launch
;
89 @property CKKSLockStateTracker
* lockStateTracker
;
91 @property CKKSZoneKeyState
* keyHierarchyState
;
92 @
property (nullable
) NSError
* keyHierarchyError
;
93 @
property (nullable
) CKOperationGroup
* keyHierarchyOperationGroup
;
94 @
property (nullable
) NSOperation
* keyStateMachineOperation
;
96 // If the key hierarchy isn't coming together, it might be because we're out of sync with cloudkit.
97 // Use this to track if we've completed a full refetch, so fix-up operations can be done.
98 @property
bool keyStateMachineRefetched
;
100 // Set this to request a key state refetch (tests only)
101 @property
bool keyStateFullRefetchRequested
;
103 @
property (nullable
) CKKSEgoManifest
* egoManifest
;
104 @
property (nullable
) CKKSManifest
* latestManifest
;
105 @
property (nullable
) CKKSResultOperation
* keyStateReadyDependency
;
107 // Wait for the key state to become 'nontransient': no pending operation is expected to advance it (at least until intervention)
108 @
property (nullable
) CKKSResultOperation
* keyStateNonTransientDependency
;
110 // True if we believe there's any items in the keychain which haven't been brought up in CKKS yet
111 @property
bool droppedItems
;
113 @
property (readonly
) NSString
* lastActiveTLKUUID
;
115 // Full of condition variables, if you'd like to try to wait until the key hierarchy is in some state
116 @property NSMutableDictionary
<CKKSZoneKeyState
*, CKKSCondition
*>* keyHierarchyConditions
;
118 @property CKKSZoneChangeFetcher
* zoneChangeFetcher
;
120 @
property (weak
) CKKSNearFutureScheduler
* savedTLKNotifier
;
122 @
property (nullable
) CKKSNearFutureScheduler
* suggestTLKUpload
;
125 /* Used for debugging: just what happened last time we ran this? */
126 @property CKKSIncomingQueueOperation
* lastIncomingQueueOperation
;
127 @property CKKSNewTLKOperation
* lastNewTLKOperation
;
128 @property CKKSOutgoingQueueOperation
* lastOutgoingQueueOperation
;
129 @property CKKSProcessReceivedKeysOperation
* lastProcessReceivedKeysOperation
;
130 @property CKKSReencryptOutgoingItemsOperation
* lastReencryptOutgoingItemsOperation
;
131 @property CKKSScanLocalItemsOperation
* lastScanLocalItemsOperation
;
132 @property CKKSSynchronizeOperation
* lastSynchronizeOperation
;
133 @property CKKSResultOperation
* lastFixupOperation
;
135 /* Used for testing: pause operation types by adding operations here */
136 @property NSOperation
* holdReencryptOutgoingItemsOperation
;
137 @property NSOperation
* holdOutgoingQueueOperation
;
138 @property NSOperation
* holdIncomingQueueOperation
;
139 @property NSOperation
* holdLocalSynchronizeOperation
;
140 @property CKKSResultOperation
* holdFixupOperation
;
142 /* Trigger this to tell the whole machine that this view has changed */
143 @property CKKSNearFutureScheduler
* notifyViewChangedScheduler
;
145 /* Trigger this to tell the whole machine that this view is more ready then before */
146 @property CKKSNearFutureScheduler
* notifyViewReadyScheduler
;
148 /* trigger this to request key state machine poking */
149 @property CKKSNearFutureScheduler
* pokeKeyStateMachineScheduler
;
151 // The current list of peer providers. If empty, CKKS will consider itself untrusted, and halt operation
152 @
property (readonly
) NSArray
<id
<CKKSPeerProvider
>>* currentPeerProviders
;
154 // These are available when you're in a dispatchSyncWithAccountKeys call, but at no other time
155 // These must be pre-fetched before you get on the CKKS queue, otherwise we end up with CKKS<->SQLite<->SOSAccountQueue deadlocks
157 // They will be in a parallel array with currentPeerProviders above
158 @
property (readonly
) NSArray
<CKKSPeerProviderState
*>* currentTrustStates
;
160 - (instancetype
)initWithContainer
:(CKContainer
*)container
161 zoneName
:(NSString
*)zoneName
162 accountTracker
:(CKKSAccountStateTracker
*)accountTracker
163 lockStateTracker
:(CKKSLockStateTracker
*)lockStateTracker
164 reachabilityTracker
:(CKKSReachabilityTracker
*)reachabilityTracker
165 changeFetcher
:(CKKSZoneChangeFetcher
*)fetcher
166 zoneModifier
:(CKKSZoneModifier
*)zoneModifier
167 savedTLKNotifier
:(CKKSNearFutureScheduler
*)savedTLKNotifier
168 cloudKitClassDependencies
:(CKKSCloudKitClassDependencies
*)cloudKitClassDependencies
;
170 /* Trust state management */
171 - (void)beginTrustedOperation
:(NSArray
<id
<CKKSPeerProvider
>>*)peerProviders
172 suggestTLKUpload
:(CKKSNearFutureScheduler
*)suggestTLKUpload
;
173 - (void)endTrustedOperation
;
175 /* Synchronous operations */
177 - (void)handleKeychainEventDbConnection
:(SecDbConnectionRef
)dbconn
178 added
:(SecDbItemRef _Nullable
)added
179 deleted
:(SecDbItemRef _Nullable
)deleted
180 rateLimiter
:(CKKSRateLimiter
*)rateLimiter
181 syncCallback
:(SecBoolNSErrorCallback
)syncCallback
;
183 - (void)setCurrentItemForAccessGroup
:(NSData
*)newItemPersistentRef
184 hash
:(NSData
*)newItemSHA1
185 accessGroup
:(NSString
*)accessGroup
186 identifier
:(NSString
*)identifier
187 replacing
:(NSData
* _Nullable
)oldCurrentItemPersistentRef
188 hash
:(NSData
* _Nullable
)oldItemSHA1
189 complete
:(void (^)(NSError
* operror
))complete
;
191 - (void)getCurrentItemForAccessGroup
:(NSString
*)accessGroup
192 identifier
:(NSString
*)identifier
193 fetchCloudValue
:(bool)fetchCloudValue
194 complete
:(void (^)(NSString
* uuid
, NSError
* operror
))complete
;
196 - (bool)outgoingQueueEmpty
:(NSError
* __autoreleasing
*)error
;
198 - (CKKSResultOperation
<CKKSKeySetProviderOperationProtocol
>*)findKeySet
;
199 - (void)receiveTLKUploadRecords
:(NSArray
<CKRecord
*>*)records
;
201 - (CKKSResultOperation
*)waitForFetchAndIncomingQueueProcessing
;
202 - (void)waitForKeyHierarchyReadiness
;
203 - (void)cancelAllOperations
;
205 - (CKKSKey
* _Nullable
)keyForItem
:(SecDbItemRef
)item error
:(NSError
* __autoreleasing
*)error
;
207 - (bool)_onqueueWithAccountKeysCheckTLK
:(CKKSKey
*)proposedTLK error
:(NSError
* __autoreleasing
*)error
;
209 - (BOOL
)otherDevicesReportHavingTLKs
:(CKKSCurrentKeySet
*)keyset
;
211 - (NSSet
<NSString
*>*)_onqueuePriorityOutgoingQueueUUIDs
;
213 /* Asynchronous kickoffs */
215 - (CKKSOutgoingQueueOperation
*)processOutgoingQueue
:(CKOperationGroup
* _Nullable
)ckoperationGroup
;
216 - (CKKSOutgoingQueueOperation
*)processOutgoingQueueAfter
:(CKKSResultOperation
* _Nullable
)after
217 ckoperationGroup
:(CKOperationGroup
* _Nullable
)ckoperationGroup
;
218 - (CKKSOutgoingQueueOperation
*)processOutgoingQueueAfter
:(CKKSResultOperation
*)after
219 requiredDelay
:(uint64_t)requiredDelay
220 ckoperationGroup
:(CKOperationGroup
*)ckoperationGroup
;
222 - (CKKSIncomingQueueOperation
*)processIncomingQueue
:(bool)failOnClassA
;
223 - (CKKSIncomingQueueOperation
*)processIncomingQueue
:(bool)failOnClassA after
:(CKKSResultOperation
* _Nullable
)after
;
225 - (CKKSScanLocalItemsOperation
*)scanLocalItems
:(NSString
*)name
;
227 // Schedules a process queueoperation to happen after the next device unlock. This may be Immediately, if the device is unlocked.
228 - (void)processIncomingQueueAfterNextUnlock
;
230 // This operation will complete directly after the next ProcessIncomingQueue, and should supply that IQO's result. Used mainly for testing; otherwise you'd just kick off a IQO directly.
231 - (CKKSResultOperation
*)resultsOfNextProcessIncomingQueueOperation
;
233 // Schedules an operation to update this device's state record in CloudKit
234 // If rateLimit is true, the operation will abort if it's updated the record in the past 3 days
235 - (CKKSUpdateDeviceStateOperation
*)updateDeviceState
:(bool)rateLimit
236 waitForKeyHierarchyInitialization
:(uint64_t)timeout
237 ckoperationGroup
:(CKOperationGroup
* _Nullable
)ckoperationGroup
;
239 - (CKKSSynchronizeOperation
*)resyncWithCloud
;
240 - (CKKSLocalSynchronizeOperation
*)resyncLocal
;
242 - (CKKSResultOperation
*)fetchAndProcessCKChanges
:(CKKSFetchBecause
*)because
;
244 - (CKKSResultOperation
*)resetLocalData
;
245 - (CKKSResultOperation
*)resetCloudKitZone
:(CKOperationGroup
*)operationGroup
;
247 // Call this to tell the key state machine that you think some new data has arrived that it is interested in
248 - (void)keyStateMachineRequestProcess
;
250 // For our serial queue to work with how handleKeychainEventDbConnection is called from the main thread,
251 // every block on our queue must have a SecDBConnectionRef available to it before it begins on the queue.
252 // Use these helper methods to make sure those exist.
253 - (void)dispatchSync
:(bool (^)(void))block
;
254 - (void)dispatchSyncWithAccountKeys
:(bool (^)(void))block
;
256 /* Synchronous operations which must be called from inside a dispatchAsyncWithAccountKeys or dispatchSync block */
258 // Call this to request the key hierarchy state machine to fetch new updates
259 - (void)_onqueueKeyStateMachineRequestFetch
;
261 // Call this to request the key hierarchy state machine to reprocess
262 - (void)_onqueueKeyStateMachineRequestProcess
;
264 // Call this from a key hierarchy operation to move the state machine, and record the results of the last move.
265 - (void)_onqueueAdvanceKeyStateMachineToState
:(CKKSZoneKeyState
* _Nullable
)state withError
:(NSError
* _Nullable
)error
;
267 // Since we might have people interested in the state transitions of objects, please do those transitions via these methods
268 - (bool)_onqueueChangeOutgoingQueueEntry
:(CKKSOutgoingQueueEntry
*)oqe
269 toState
:(NSString
*)state
270 error
:(NSError
* __autoreleasing
*)error
;
271 - (bool)_onqueueErrorOutgoingQueueEntry
:(CKKSOutgoingQueueEntry
*)oqe
272 itemError
:(NSError
*)itemError
273 error
:(NSError
* __autoreleasing
*)error
;
275 // Call this if you've done a write and received an error. It'll pull out any new records returned as CKErrorServerRecordChanged and pretend we received them in a fetch
277 // Note that you need to tell this function the records you wanted to save, so it can determine which record failed from its CKRecordID.
278 // I don't know why CKRecordIDs don't have record types, either.
279 - (bool)_onqueueCKWriteFailed
:(NSError
*)ckerror attemptedRecordsChanged
:(NSDictionary
<CKRecordID
*, CKRecord
*>*)savedRecords
;
281 - (bool)_onqueueCKRecordChanged
:(CKRecord
*)record resync
:(bool)resync
;
282 - (bool)_onqueueCKRecordDeleted
:(CKRecordID
*)recordID recordType
:(NSString
*)recordType resync
:(bool)resync
;
284 // For this key, who doesn't yet have a CKKSTLKShare for it, shared to their current Octagon keys?
285 // Note that we really want a record sharing the TLK to ourselves, so this function might return
286 // a non-empty set even if all peers have the TLK: it wants us to make a record for ourself.
287 // If you pass in a non-empty set in afterUploading, those records will be included in the calculation.
288 - (NSSet
<id
<CKKSPeer
>>*)_onqueueFindPeers
:(CKKSPeerProviderState
*)trustState
289 missingShare
:(CKKSKey
*)key
290 afterUploading
:(NSSet
<CKKSTLKShareRecord
*>* _Nullable
)newShares
291 error
:(NSError
* __autoreleasing
*)error
;
293 - (BOOL
)_onqueueAreNewSharesSufficient
:(NSSet
<CKKSTLKShareRecord
*>*)newShares
294 currentTLK
:(CKKSKey
*)key
295 error
:(NSError
* __autoreleasing
*)error
;
297 // For this key, share it to all trusted peers who don't have it yet
298 - (NSSet
<CKKSTLKShareRecord
*>* _Nullable
)_onqueueCreateMissingKeyShares
:(CKKSKey
*)key error
:(NSError
* __autoreleasing
*)error
;
300 - (bool)_onqueueUpdateLatestManifestWithError
:(NSError
**)error
;
302 - (CKKSDeviceStateEntry
* _Nullable
)_onqueueCurrentDeviceStateEntry
:(NSError
* __autoreleasing
*)error
;
304 // Please don't use these unless you're an Operation in this package
305 @property NSHashTable
<CKKSIncomingQueueOperation
*>* incomingQueueOperations
;
306 @property NSHashTable
<CKKSOutgoingQueueOperation
*>* outgoingQueueOperations
;
307 @property CKKSScanLocalItemsOperation
* initialScanOperation
;
309 // Returns the current state of this view, fastStatus is the same, but as name promise, no expensive calculations
310 - (NSDictionary
<NSString
*, NSString
*>*)status
;
311 - (NSDictionary
<NSString
*, NSString
*>*)fastStatus
;
314 NS_ASSUME_NONNULL_END
316 #import <Foundation/Foundation.h>
317 @interface CKKSKeychainView
: NSObject
319 NSString
* _containerName
;