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/ckks/CKKSAPSReceiver.h"
29 #import "keychain/ckks/CKKSLockStateTracker.h"
30 #import "keychain/ckks/CKKSReachabilityTracker.h"
31 #import "keychain/ckks/CloudKitDependencies.h"
33 #include <securityd/SecDbItem.h>
34 #include <utilities/SecDb.h>
36 #import "keychain/ckks/CKKS.h"
37 #import "keychain/ckks/CKKSFetchAllRecordZoneChangesOperation.h"
38 #import "keychain/ckks/CKKSGroupOperation.h"
39 #import "keychain/ckks/CKKSIncomingQueueOperation.h"
40 #import "keychain/ckks/CKKSNearFutureScheduler.h"
41 #import "keychain/ckks/CKKSNewTLKOperation.h"
42 #import "keychain/ckks/CKKSNotifier.h"
43 #import "keychain/ckks/CKKSOutgoingQueueOperation.h"
44 #import "keychain/ckks/CKKSPeer.h"
45 #import "keychain/ckks/CKKSProcessReceivedKeysOperation.h"
46 #import "keychain/ckks/CKKSReencryptOutgoingItemsOperation.h"
47 #import "keychain/ckks/CKKSScanLocalItemsOperation.h"
48 #import "keychain/ckks/CKKSTLKShare.h"
49 #import "keychain/ckks/CKKSUpdateDeviceStateOperation.h"
50 #import "keychain/ckks/CKKSZone.h"
51 #import "keychain/ckks/CKKSZoneChangeFetcher.h"
52 #import "keychain/ckks/CKKSSynchronizeOperation.h"
53 #import "keychain/ckks/CKKSLocalSynchronizeOperation.h"
57 NS_ASSUME_NONNULL_BEGIN
61 @
class CKKSSynchronizeOperation
;
62 @
class CKKSRateLimiter
;
64 @
class CKKSEgoManifest
;
65 @
class CKKSOutgoingQueueEntry
;
66 @
class CKKSZoneChangeFetcher
;
68 @interface CKKSKeychainView
: CKKSZone
<CKKSZoneUpdateReceiver
, CKKSChangeFetcherClient
, CKKSPeerUpdateListener
>
70 CKKSZoneKeyState
* _keyHierarchyState
;
73 @property CKKSCondition
* loggedIn
;
74 @property CKKSCondition
* loggedOut
;
75 @property CKKSCondition
* accountStateKnown
;
77 @property CKKSLockStateTracker
* lockStateTracker
;
79 @property CKKSZoneKeyState
* keyHierarchyState
;
80 @
property (nullable
) NSError
* keyHierarchyError
;
81 @
property (nullable
) CKOperationGroup
* keyHierarchyOperationGroup
;
82 @
property (nullable
) NSOperation
* keyStateMachineOperation
;
84 // If the key hierarchy isn't coming together, it might be because we're out of sync with cloudkit.
85 // Use this to track if we've completed a full refetch, so fix-up operations can be done.
86 @property
bool keyStateMachineRefetched
;
87 @
property (nullable
) CKKSEgoManifest
* egoManifest
;
88 @
property (nullable
) CKKSManifest
* latestManifest
;
89 @
property (nullable
) CKKSResultOperation
* keyStateReadyDependency
;
91 // Wait for the key state to become 'nontransient': no pending operation is expected to advance it (at least until user intervenes)
92 @
property (nullable
) CKKSResultOperation
* keyStateNonTransientDependency
;
94 // True if we believe there's any items in the keychain which haven't been brought up in CKKS yet
95 @property
bool droppedItems
;
97 @
property (readonly
) NSString
* lastActiveTLKUUID
;
99 // Full of condition variables, if you'd like to try to wait until the key hierarchy is in some state
100 @property NSMutableDictionary
<CKKSZoneKeyState
*, CKKSCondition
*>* keyHierarchyConditions
;
102 @property CKKSZoneChangeFetcher
* zoneChangeFetcher
;
104 @
property (weak
) CKKSNearFutureScheduler
* savedTLKNotifier
;
106 /* Used for debugging: just what happened last time we ran this? */
107 @property CKKSIncomingQueueOperation
* lastIncomingQueueOperation
;
108 @property CKKSNewTLKOperation
* lastNewTLKOperation
;
109 @property CKKSOutgoingQueueOperation
* lastOutgoingQueueOperation
;
110 @property CKKSProcessReceivedKeysOperation
* lastProcessReceivedKeysOperation
;
111 @property CKKSReencryptOutgoingItemsOperation
* lastReencryptOutgoingItemsOperation
;
112 @property CKKSScanLocalItemsOperation
* lastScanLocalItemsOperation
;
113 @property CKKSSynchronizeOperation
* lastSynchronizeOperation
;
114 @property CKKSResultOperation
* lastFixupOperation
;
116 /* Used for testing: pause operation types by adding operations here */
117 @property NSOperation
* holdReencryptOutgoingItemsOperation
;
118 @property NSOperation
* holdOutgoingQueueOperation
;
119 @property NSOperation
* holdIncomingQueueOperation
;
120 @property NSOperation
* holdLocalSynchronizeOperation
;
121 @property CKKSResultOperation
* holdFixupOperation
;
123 /* Trigger this to tell the whole machine that this view has changed */
124 @property CKKSNearFutureScheduler
* notifyViewChangedScheduler
;
126 /* trigger this to request key state machine poking */
127 @property CKKSNearFutureScheduler
* pokeKeyStateMachineScheduler
;
129 // These are available when you're in a dispatchSyncWithAccountKeys call, but at no other time
130 // These must be pre-fetched before you get on the CKKS queue, otherwise we end up with CKKS<->SQLite<->SOSAccountQueue deadlocks
131 @
property (nonatomic
, readonly
) CKKSSelves
* currentSelfPeers
;
132 @
property (nonatomic
, readonly
) NSError
* currentSelfPeersError
;
133 @
property (nonatomic
, readonly
) NSSet
<id
<CKKSPeer
>>* currentTrustedPeers
;
134 @
property (nonatomic
, readonly
) NSError
* currentTrustedPeersError
;
136 - (instancetype
)initWithContainer
:(CKContainer
*)container
137 zoneName
:(NSString
*)zoneName
138 accountTracker
:(CKKSCKAccountStateTracker
*)accountTracker
139 lockStateTracker
:(CKKSLockStateTracker
*)lockStateTracker
140 reachabilityTracker
:(CKKSReachabilityTracker
*)reachabilityTracker
141 changeFetcher
:(CKKSZoneChangeFetcher
*)fetcher
142 savedTLKNotifier
:(CKKSNearFutureScheduler
*)savedTLKNotifier
143 peerProvider
:(id
<CKKSPeerProvider
>)peerProvider
144 fetchRecordZoneChangesOperationClass
:(Class
<CKKSFetchRecordZoneChangesOperation
>)fetchRecordZoneChangesOperationClass
145 fetchRecordsOperationClass
:(Class
<CKKSFetchRecordsOperation
>)fetchRecordsOperationClass
146 queryOperationClass
:(Class
<CKKSQueryOperation
>)queryOperationClass
147 modifySubscriptionsOperationClass
:(Class
<CKKSModifySubscriptionsOperation
>)modifySubscriptionsOperationClass
148 modifyRecordZonesOperationClass
:(Class
<CKKSModifyRecordZonesOperation
>)modifyRecordZonesOperationClass
149 apsConnectionClass
:(Class
<CKKSAPSConnection
>)apsConnectionClass
150 notifierClass
:(Class
<CKKSNotifier
>)notifierClass
;
152 /* Synchronous operations */
154 - (void)handleKeychainEventDbConnection
:(SecDbConnectionRef
)dbconn
155 added
:(SecDbItemRef _Nullable
)added
156 deleted
:(SecDbItemRef _Nullable
)deleted
157 rateLimiter
:(CKKSRateLimiter
*)rateLimiter
158 syncCallback
:(SecBoolNSErrorCallback
)syncCallback
;
160 - (void)setCurrentItemForAccessGroup
:(NSData
*)newItemPersistentRef
161 hash
:(NSData
*)newItemSHA1
162 accessGroup
:(NSString
*)accessGroup
163 identifier
:(NSString
*)identifier
164 replacing
:(NSData
* _Nullable
)oldCurrentItemPersistentRef
165 hash
:(NSData
* _Nullable
)oldItemSHA1
166 complete
:(void (^)(NSError
* operror
))complete
;
168 - (void)getCurrentItemForAccessGroup
:(NSString
*)accessGroup
169 identifier
:(NSString
*)identifier
170 fetchCloudValue
:(bool)fetchCloudValue
171 complete
:(void (^)(NSString
* uuid
, NSError
* operror
))complete
;
173 - (bool)outgoingQueueEmpty
:(NSError
* __autoreleasing
*)error
;
175 - (CKKSResultOperation
*)waitForFetchAndIncomingQueueProcessing
;
176 - (void)waitForKeyHierarchyReadiness
;
177 - (void)cancelAllOperations
;
179 - (CKKSKey
* _Nullable
)keyForItem
:(SecDbItemRef
)item error
:(NSError
* __autoreleasing
*)error
;
181 - (bool)_onqueueWithAccountKeysCheckTLK
:(CKKSKey
*)proposedTLK error
:(NSError
* __autoreleasing
*)error
;
183 /* Asynchronous kickoffs */
185 - (CKKSOutgoingQueueOperation
*)processOutgoingQueue
:(CKOperationGroup
* _Nullable
)ckoperationGroup
;
186 - (CKKSOutgoingQueueOperation
*)processOutgoingQueueAfter
:(CKKSResultOperation
* _Nullable
)after
187 ckoperationGroup
:(CKOperationGroup
* _Nullable
)ckoperationGroup
;
189 - (CKKSIncomingQueueOperation
*)processIncomingQueue
:(bool)failOnClassA
;
190 - (CKKSIncomingQueueOperation
*)processIncomingQueue
:(bool)failOnClassA after
:(CKKSResultOperation
* _Nullable
)after
;
192 - (CKKSScanLocalItemsOperation
*)scanLocalItems
:(NSString
*)name
;
194 // Schedules a process queueoperation to happen after the next device unlock. This may be Immediately, if the device is unlocked.
195 - (void)processIncomingQueueAfterNextUnlock
;
197 // 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.
198 - (CKKSResultOperation
*)resultsOfNextProcessIncomingQueueOperation
;
200 // Schedules an operation to update this device's state record in CloudKit
201 // If rateLimit is true, the operation will abort if it's updated the record in the past 3 days
202 - (CKKSUpdateDeviceStateOperation
*)updateDeviceState
:(bool)rateLimit
203 waitForKeyHierarchyInitialization
:(uint64_t)timeout
204 ckoperationGroup
:(CKOperationGroup
* _Nullable
)ckoperationGroup
;
206 - (CKKSSynchronizeOperation
*)resyncWithCloud
;
207 - (CKKSLocalSynchronizeOperation
*)resyncLocal
;
209 - (CKKSResultOperation
*)fetchAndProcessCKChanges
:(CKKSFetchBecause
*)because
;
211 - (CKKSResultOperation
*)resetLocalData
;
212 - (CKKSResultOperation
*)resetCloudKitZone
:(CKOperationGroup
*)operationGroup
;
214 // Call this to tell the key state machine that you think some new data has arrived that it is interested in
215 - (void)keyStateMachineRequestProcess
;
217 // For our serial queue to work with how handleKeychainEventDbConnection is called from the main thread,
218 // every block on our queue must have a SecDBConnectionRef available to it before it begins on the queue.
219 // Use these helper methods to make sure those exist.
220 - (void)dispatchSync
:(bool (^)(void))block
;
221 - (void)dispatchSyncWithAccountKeys
:(bool (^)(void))block
;
223 /* Synchronous operations which must be called from inside a dispatchAsyncWithAccountKeys or dispatchSync block */
225 // Call this to request the key hierarchy state machine to fetch new updates
226 - (void)_onqueueKeyStateMachineRequestFetch
;
228 // Call this to request the key hierarchy state machine to reprocess
229 - (void)_onqueueKeyStateMachineRequestProcess
;
231 // Call this from a key hierarchy operation to move the state machine, and record the results of the last move.
232 - (void)_onqueueAdvanceKeyStateMachineToState
:(CKKSZoneKeyState
* _Nullable
)state withError
:(NSError
* _Nullable
)error
;
234 // Since we might have people interested in the state transitions of objects, please do those transitions via these methods
235 - (bool)_onqueueChangeOutgoingQueueEntry
:(CKKSOutgoingQueueEntry
*)oqe
236 toState
:(NSString
*)state
237 error
:(NSError
* __autoreleasing
*)error
;
238 - (bool)_onqueueErrorOutgoingQueueEntry
:(CKKSOutgoingQueueEntry
*)oqe
239 itemError
:(NSError
*)itemError
240 error
:(NSError
* __autoreleasing
*)error
;
242 // 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
244 // Note that you need to tell this function the records you wanted to save, so it can determine which record failed from its CKRecordID.
245 // I don't know why CKRecordIDs don't have record types, either.
246 - (bool)_onqueueCKWriteFailed
:(NSError
*)ckerror attemptedRecordsChanged
:(NSDictionary
<CKRecordID
*, CKRecord
*>*)savedRecords
;
248 - (bool)_onqueueCKRecordChanged
:(CKRecord
*)record resync
:(bool)resync
;
249 - (bool)_onqueueCKRecordDeleted
:(CKRecordID
*)recordID recordType
:(NSString
*)recordType resync
:(bool)resync
;
251 // For this key, who doesn't yet have a CKKSTLKShare for it, shared to their current Octagon keys?
252 // Note that we really want a record sharing the TLK to ourselves, so this function might return
253 // a non-empty set even if all peers have the TLK: it wants us to make a record for ourself.
254 - (NSSet
<id
<CKKSPeer
>>* _Nullable
)_onqueueFindPeersMissingShare
:(CKKSKey
*)key error
:(NSError
* __autoreleasing
*)error
;
256 // For this key, share it to all trusted peers who don't have it yet
257 - (NSSet
<CKKSTLKShare
*>* _Nullable
)_onqueueCreateMissingKeyShares
:(CKKSKey
*)key error
:(NSError
* __autoreleasing
*)error
;
259 - (bool)_onqueueUpdateLatestManifestWithError
:(NSError
**)error
;
261 - (CKKSDeviceStateEntry
* _Nullable
)_onqueueCurrentDeviceStateEntry
:(NSError
* __autoreleasing
*)error
;
263 // Please don't use these unless you're an Operation in this package
264 @property NSHashTable
<CKKSIncomingQueueOperation
*>* incomingQueueOperations
;
265 @property NSHashTable
<CKKSOutgoingQueueOperation
*>* outgoingQueueOperations
;
266 @property CKKSScanLocalItemsOperation
* initialScanOperation
;
268 // Returns the current state of this view, fastStatus is the same, but as name promise, no expensive calculations
269 - (NSDictionary
<NSString
*, NSString
*>*)status
;
270 - (NSDictionary
<NSString
*, NSString
*>*)fastStatus
;
273 NS_ASSUME_NONNULL_END
275 #import <Foundation/Foundation.h>
276 @interface CKKSKeychainView
: NSObject
278 NSString
* _containerName
;