2 #import "utilities/debugging.h"
4 #import "keychain/ot/OctagonStateMachine.h"
5 #import "keychain/ot/OTStates.h"
6 #import "keychain/escrowrequest/EscrowRequestController.h"
7 #import "keychain/escrowrequest/EscrowRequestServer.h"
9 #import "keychain/ckks/CKKSLockStateTracker.h"
11 #import "keychain/ot/ObjCImprovements.h"
13 #import "keychain/escrowrequest/operations/EscrowRequestInformCloudServicesOperation.h"
14 #import "keychain/escrowrequest/operations/EscrowRequestPerformEscrowEnrollOperation.h"
16 #import "keychain/escrowrequest/generated_source/SecEscrowPendingRecord.h"
17 #import "keychain/escrowrequest/SecEscrowPendingRecord+KeychainSupport.h"
19 OctagonState* const EscrowRequestStateNothingToDo = (OctagonState*)@"nothing_to_do";
20 OctagonState* const EscrowRequestStateTriggerCloudServices = (OctagonState*)@"trigger_cloudservices";
22 OctagonState* const EscrowRequestStateAttemptEscrowUpload = (OctagonState*)@"trigger_escrow_upload";
23 OctagonState* const EscrowRequestStateWaitForUnlock = (OctagonState*)@"wait_for_unlock";
25 @interface EscrowRequestController ()
26 @property dispatch_queue_t queue;
27 @property CKKSLockStateTracker* lockStateTracker;
28 @property bool haveRecordedDate;
31 @implementation EscrowRequestController
33 - (instancetype)initWithLockStateTracker:(CKKSLockStateTracker*)lockStateTracker
35 if((self = [super init])) {
36 _queue = dispatch_queue_create("EscrowRequestControllerQueue", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
37 _lockStateTracker = lockStateTracker;
39 _stateMachine = [[OctagonStateMachine alloc] initWithName:@"escrowrequest"
40 states:[NSSet setWithArray:@[EscrowRequestStateNothingToDo,
41 EscrowRequestStateTriggerCloudServices,
42 EscrowRequestStateAttemptEscrowUpload,
43 EscrowRequestStateWaitForUnlock]]
44 flags: [NSSet setWithArray:@[OctagonFlagEscrowRequestInformCloudServicesOperation]]
45 initialState:EscrowRequestStateNothingToDo
48 lockStateTracker:lockStateTracker];
50 _forceIgnoreCloudServicesRateLimiting = false;
56 - (CKKSResultOperation<OctagonStateTransitionOperationProtocol> * _Nullable)_onqueueNextStateMachineTransition:(nonnull OctagonState *)currentState
57 flags:(nonnull OctagonFlags *)flags
58 pendingFlags:(nonnull id<OctagonStateOnqueuePendingFlagHandler>)pendingFlagHandler
60 if([flags _onqueueContains:OctagonFlagEscrowRequestInformCloudServicesOperation]) {
61 [flags _onqueueRemoveFlag:OctagonFlagEscrowRequestInformCloudServicesOperation];
62 return [[EscrowRequestInformCloudServicesOperation alloc] initWithIntendedState:EscrowRequestStateNothingToDo
63 errorState:EscrowRequestStateNothingToDo
64 lockStateTracker:self.lockStateTracker];
67 if([currentState isEqualToString:EscrowRequestStateTriggerCloudServices]) {
68 return [[EscrowRequestInformCloudServicesOperation alloc] initWithIntendedState:EscrowRequestStateNothingToDo
69 errorState:EscrowRequestStateNothingToDo
70 lockStateTracker:self.lockStateTracker];
73 if([currentState isEqualToString:EscrowRequestStateAttemptEscrowUpload]) {
74 return [[EscrowRequestPerformEscrowEnrollOperation alloc] initWithIntendedState:EscrowRequestStateNothingToDo
75 errorState:EscrowRequestStateNothingToDo
76 enforceRateLimiting:true
77 lockStateTracker:self.lockStateTracker];
80 if([currentState isEqualToString:EscrowRequestStateWaitForUnlock]) {
81 secnotice("escrowrequest", "waiting for unlock before continuing with state machine");
82 OctagonStateTransitionOperation* op = [OctagonStateTransitionOperation named:@"wait-for-unlock"
83 entering:EscrowRequestStateNothingToDo];
84 [op addNullableDependency:self.lockStateTracker.unlockDependency];
89 NSArray<SecEscrowPendingRecord*>* records = [SecEscrowPendingRecord loadAllFromKeychain:&error];
91 if([self.lockStateTracker isLockedError:error]) {
92 return [OctagonStateTransitionOperation named:@"wait-for-unlock"
93 entering:EscrowRequestStateWaitForUnlock];
95 secnotice("escrowrequest", "failed to fetch records from keychain, nothing to do: %@", error);
99 // First, do we need to poke CloudServices?
100 for(SecEscrowPendingRecord* record in records) {
101 // Completed records don't need anything.
102 if(record.hasUploadCompleted && record.uploadCompleted) {
106 if (!self.haveRecordedDate) {
107 NSDate *date = [[CKKSAnalytics logger] datePropertyForKey:ESRPendingSince];
109 [[CKKSAnalytics logger] setDateProperty:[NSDate date] forKey:ESRPendingSince];
111 self.haveRecordedDate = true;
114 uint64_t fiveMinutesAgo = ((uint64_t)[[NSDate date] timeIntervalSince1970] * 1000) - (1000*60*5);
116 if(!record.certCached) {
117 if(!self.forceIgnoreCloudServicesRateLimiting && (record.hasLastCloudServicesTriggerTime && record.lastCloudServicesTriggerTime >= fiveMinutesAgo)) {
118 secnotice("escrowrequest", "Request %@ needs to cache a certificate, but that has been attempted recently. Holding off...", record.uuid);
122 secnotice("escrowrequest", "Request %@ needs a cached certififcate", record.uuid);
124 return [OctagonStateTransitionOperation named:@"escrow-request-cache-cert"
125 entering:EscrowRequestStateTriggerCloudServices];
128 if(record.hasSerializedPrerecord) {
129 if([record escrowAttemptedWithinLastSeconds:5*60]) {
130 secnotice("escrowrequest", "Request %@ needs to be stored, but has been attempted recently. Holding off...", record.uuid);
134 secnotice("escrowrequest", "Request %@ needs to be stored!", record.uuid);
136 return [OctagonStateTransitionOperation named:@"escrow-request-attempt-escrow-upload"
137 entering:EscrowRequestStateAttemptEscrowUpload];
145 - (void)triggerEscrowUpdateRPC:(nonnull NSString *)reason
146 reply:(nonnull void (^)(NSError * _Nullable))reply
148 [self.stateMachine startOperation];
150 NSError* error = nil;
151 NSArray<SecEscrowPendingRecord*>* records = [SecEscrowPendingRecord loadAllFromKeychain:&error];
152 if(error && !([error.domain isEqualToString:NSOSStatusErrorDomain] && error.code == errSecItemNotFound)) {
153 secnotice("escrowrequest", "failed to fetch records from keychain: %@", error);
159 secnotice("escrowrequest", "Investigating a new escrow request");
161 BOOL escrowRequestExists = NO;
162 for(SecEscrowPendingRecord* existingRecord in records) {
163 if(existingRecord.uploadCompleted) {
167 if (existingRecord.hasAltDSID) {
171 secnotice("escrowrequest", "Retriggering an existing escrow request: %@", existingRecord);
172 existingRecord.hasCertCached = false;
173 existingRecord.serializedPrerecord = nil;
175 [existingRecord saveToKeychain:&error];
177 secerror("escrowrequest: Unable to save modified request to keychain: %@", error);
182 secnotice("escrowrequest", "Retriggering an existing escrow request complete");
183 escrowRequestExists = YES;
186 if(escrowRequestExists == NO){
187 secnotice("escrowrequest", "Creating a new escrow request");
189 SecEscrowPendingRecord* record = [[SecEscrowPendingRecord alloc] init];
190 record.uuid = [[NSUUID UUID] UUIDString];
191 record.altDSID = nil;
192 record.triggerRequestTime = ((uint64_t)[[NSDate date] timeIntervalSince1970] * 1000);
193 secnotice("escrowrequest", "beginning a new escrow request (%@)", record.uuid);
195 [record saveToKeychain:&error];
198 secerror("escrowrequest: unable to save escrow update request: %@", error);
204 [[CKKSAnalytics logger] setDateProperty:[NSDate date] forKey:ESRPendingSince];
205 self.haveRecordedDate = true;
207 [self.stateMachine handleFlag:OctagonFlagEscrowRequestInformCloudServicesOperation];
212 - (void)storePrerecordsInEscrowRPC:(void (^)(uint64_t count, NSError* _Nullable error))reply
214 EscrowRequestPerformEscrowEnrollOperation* op = [[EscrowRequestPerformEscrowEnrollOperation alloc] initWithIntendedState:EscrowRequestStateNothingToDo
215 errorState:EscrowRequestStateNothingToDo
216 enforceRateLimiting:false
217 lockStateTracker:self.lockStateTracker];
218 [self.stateMachine startOperation];
219 [self.stateMachine doSimpleStateMachineRPC:@"trigger-escrow-store"
221 sourceStates:[NSSet setWithObject:EscrowRequestStateNothingToDo]
222 reply:^(NSError * _Nullable error) {
223 secnotice("escrowrequest", "Uploaded %d records with error %@", (int)op.numberOfRecordsUploaded, error);
224 reply(op.numberOfRecordsUploaded, error);