]> git.saurik.com Git - apple/security.git/blob - keychain/escrowrequest/EscrowRequestController.m
Security-59306.61.1.tar.gz
[apple/security.git] / keychain / escrowrequest / EscrowRequestController.m
1
2 #import "utilities/debugging.h"
3
4 #import "keychain/ot/OctagonStateMachine.h"
5 #import "keychain/ot/OTStates.h"
6 #import "keychain/escrowrequest/EscrowRequestController.h"
7 #import "keychain/escrowrequest/EscrowRequestServer.h"
8
9 #import "keychain/ckks/CKKSLockStateTracker.h"
10
11 #import "keychain/ot/ObjCImprovements.h"
12
13 #import "keychain/escrowrequest/operations/EscrowRequestInformCloudServicesOperation.h"
14 #import "keychain/escrowrequest/operations/EscrowRequestPerformEscrowEnrollOperation.h"
15
16 #import "keychain/escrowrequest/generated_source/SecEscrowPendingRecord.h"
17 #import "keychain/escrowrequest/SecEscrowPendingRecord+KeychainSupport.h"
18
19 OctagonState* const EscrowRequestStateNothingToDo = (OctagonState*)@"nothing_to_do";
20 OctagonState* const EscrowRequestStateTriggerCloudServices = (OctagonState*)@"trigger_cloudservices";
21
22 OctagonState* const EscrowRequestStateAttemptEscrowUpload = (OctagonState*)@"trigger_escrow_upload";
23 OctagonState* const EscrowRequestStateWaitForUnlock = (OctagonState*)@"wait_for_unlock";
24
25 @interface EscrowRequestController ()
26 @property dispatch_queue_t queue;
27 @property CKKSLockStateTracker* lockStateTracker;
28 @property bool haveRecordedDate;
29 @end
30
31 @implementation EscrowRequestController
32
33 - (instancetype)initWithLockStateTracker:(CKKSLockStateTracker*)lockStateTracker
34 {
35 if((self = [super init])) {
36 _queue = dispatch_queue_create("EscrowRequestControllerQueue", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
37 _lockStateTracker = lockStateTracker;
38
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
46 queue:_queue
47 stateEngine:self
48 lockStateTracker:lockStateTracker];
49
50 _forceIgnoreCloudServicesRateLimiting = false;
51 }
52
53 return self;
54 }
55
56 - (CKKSResultOperation<OctagonStateTransitionOperationProtocol> * _Nullable)_onqueueNextStateMachineTransition:(nonnull OctagonState *)currentState
57 flags:(nonnull OctagonFlags *)flags
58 pendingFlags:(nonnull id<OctagonStateOnqueuePendingFlagHandler>)pendingFlagHandler
59 {
60 if([flags _onqueueContains:OctagonFlagEscrowRequestInformCloudServicesOperation]) {
61 [flags _onqueueRemoveFlag:OctagonFlagEscrowRequestInformCloudServicesOperation];
62 return [[EscrowRequestInformCloudServicesOperation alloc] initWithIntendedState:EscrowRequestStateNothingToDo
63 errorState:EscrowRequestStateNothingToDo
64 lockStateTracker:self.lockStateTracker];
65 }
66
67 if([currentState isEqualToString:EscrowRequestStateTriggerCloudServices]) {
68 return [[EscrowRequestInformCloudServicesOperation alloc] initWithIntendedState:EscrowRequestStateNothingToDo
69 errorState:EscrowRequestStateNothingToDo
70 lockStateTracker:self.lockStateTracker];
71 }
72
73 if([currentState isEqualToString:EscrowRequestStateAttemptEscrowUpload]) {
74 return [[EscrowRequestPerformEscrowEnrollOperation alloc] initWithIntendedState:EscrowRequestStateNothingToDo
75 errorState:EscrowRequestStateNothingToDo
76 enforceRateLimiting:true
77 lockStateTracker:self.lockStateTracker];
78 }
79
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];
85 return op;
86 }
87
88 NSError* error = nil;
89 NSArray<SecEscrowPendingRecord*>* records = [SecEscrowPendingRecord loadAllFromKeychain:&error];
90 if(error) {
91 if([self.lockStateTracker isLockedError:error]) {
92 return [OctagonStateTransitionOperation named:@"wait-for-unlock"
93 entering:EscrowRequestStateWaitForUnlock];
94 }
95 secnotice("escrowrequest", "failed to fetch records from keychain, nothing to do: %@", error);
96 return nil;
97 }
98
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) {
103 continue;
104 }
105
106 if (!self.haveRecordedDate) {
107 NSDate *date = [[CKKSAnalytics logger] datePropertyForKey:ESRPendingSince];
108 if (date == NULL) {
109 [[CKKSAnalytics logger] setDateProperty:[NSDate date] forKey:ESRPendingSince];
110 }
111 self.haveRecordedDate = true;
112 }
113
114 uint64_t fiveMinutesAgo = ((uint64_t)[[NSDate date] timeIntervalSince1970] * 1000) - (1000*60*5);
115
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);
119 continue;
120 }
121
122 secnotice("escrowrequest", "Request %@ needs a cached certififcate", record.uuid);
123
124 return [OctagonStateTransitionOperation named:@"escrow-request-cache-cert"
125 entering:EscrowRequestStateTriggerCloudServices];
126 }
127
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);
131 continue;
132 }
133
134 secnotice("escrowrequest", "Request %@ needs to be stored!", record.uuid);
135
136 return [OctagonStateTransitionOperation named:@"escrow-request-attempt-escrow-upload"
137 entering:EscrowRequestStateAttemptEscrowUpload];
138 }
139 }
140
141
142 return nil;
143 }
144
145 - (void)triggerEscrowUpdateRPC:(nonnull NSString *)reason
146 reply:(nonnull void (^)(NSError * _Nullable))reply
147 {
148 [self.stateMachine startOperation];
149
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);
154 reply(error);
155 return;
156 }
157 error = nil;
158
159 secnotice("escrowrequest", "Investigating a new escrow request");
160
161 BOOL escrowRequestExists = NO;
162 for(SecEscrowPendingRecord* existingRecord in records) {
163 if(existingRecord.uploadCompleted) {
164 continue;
165 }
166
167 if (existingRecord.hasAltDSID) {
168 continue;
169 }
170
171 secnotice("escrowrequest", "Retriggering an existing escrow request: %@", existingRecord);
172 existingRecord.hasCertCached = false;
173 existingRecord.serializedPrerecord = nil;
174
175 [existingRecord saveToKeychain:&error];
176 if(error) {
177 secerror("escrowrequest: Unable to save modified request to keychain: %@", error);
178 reply(error);
179 return;
180 }
181
182 secnotice("escrowrequest", "Retriggering an existing escrow request complete");
183 escrowRequestExists = YES;
184 }
185
186 if(escrowRequestExists == NO){
187 secnotice("escrowrequest", "Creating a new escrow request");
188
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);
194
195 [record saveToKeychain:&error];
196
197 if(error) {
198 secerror("escrowrequest: unable to save escrow update request: %@", error);
199 reply(error);
200 return;
201 }
202 }
203
204 [[CKKSAnalytics logger] setDateProperty:[NSDate date] forKey:ESRPendingSince];
205 self.haveRecordedDate = true;
206
207 [self.stateMachine handleFlag:OctagonFlagEscrowRequestInformCloudServicesOperation];
208
209 reply(nil);
210 }
211
212 - (void)storePrerecordsInEscrowRPC:(void (^)(uint64_t count, NSError* _Nullable error))reply
213 {
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"
220 op:op
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);
225 }];
226 }
227
228 @end