]> git.saurik.com Git - apple/security.git/blob - keychain/ot/OTClientStateMachine.m
Security-59306.11.20.tar.gz
[apple/security.git] / keychain / ot / OTClientStateMachine.m
1 /*
2 * Copyright (c) 2017 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23 #if OCTAGON
24
25 #import <CoreCDP/CDPAccount.h>
26
27 #import <Security/Security.h>
28
29 #include <utilities/SecFileLocations.h>
30 #include <Security/SecRandomP.h>
31
32 #import "keychain/TrustedPeersHelper/TrustedPeersHelperProtocol.h"
33
34 #import "keychain/ckks/CKKS.h"
35 #import "keychain/ckks/CKKSAnalytics.h"
36 #import "keychain/ckks/CKKSResultOperation.h"
37
38 #import "keychain/ckks/OctagonAPSReceiver.h"
39
40 #import "keychain/ot/proto/generated_source/OTAccountMetadataClassC.h"
41 #import "keychain/ot/ObjCImprovements.h"
42
43 #import "keychain/ot/OTConstants.h"
44 #import "keychain/ot/OTContext.h"
45 #import "keychain/ot/OTClientStateMachine.h"
46 #import "keychain/ot/OTPrepareOperation.h"
47 #import "keychain/ot/OTSOSAdapter.h"
48 #import "keychain/ot/OTEpochOperation.h"
49 #import "keychain/ot/OTClientVoucherOperation.h"
50 #import "keychain/ot/OTStates.h"
51
52 #import "keychain/ot/ObjCImprovements.h"
53 #import "keychain/ot/proto/generated_source/OTAccountMetadataClassC.h"
54
55 #import "keychain/categories/NSError+UsefulConstructors.h"
56 #import "keychain/ot/categories/OTAccountMetadataClassC+KeychainSupport.h"
57
58 #define otclientnotice(scope, format, ...) __extension__({ \
59 os_log(secLogObjForCFScope((__bridge CFStringRef)(scope)), format, ##__VA_ARGS__); \
60 })
61
62 /*Piggybacking and ProximitySetup as Acceptor Octagon only*/
63 OctagonState* const OctagonStateAcceptorBeginClientJoin = (OctagonState*)@"client_join";
64 OctagonState* const OctagonStateAcceptorBeginAwaitEpochRequest = (OctagonState*)@"await_epoch_request";
65 OctagonState* const OctagonStateAcceptorEpochPrepared = (OctagonState*)@"epoch_prepared";
66 OctagonState* const OctagonStateAcceptorAwaitingIdentity = (OctagonState*)@"await_identity";
67 OctagonState* const OctagonStateAcceptorVoucherPrepared = (OctagonState*)@"voucher_prepared";
68 OctagonState* const OctagonStateAcceptorDone = (OctagonState*)@"done";
69
70 NSDictionary<OctagonState*, NSNumber*>* OctagonClientStateMap(void) {
71 static NSDictionary<OctagonState*, NSNumber*>* map = nil;
72 static dispatch_once_t onceToken;
73 dispatch_once(&onceToken, ^{
74 map = @{
75 OctagonStateAcceptorBeginClientJoin: @0U,
76 OctagonStateAcceptorBeginAwaitEpochRequest: @1U,
77 OctagonStateAcceptorEpochPrepared: @2U,
78 OctagonStateAcceptorAwaitingIdentity: @3U,
79 OctagonStateAcceptorVoucherPrepared: @4U,
80 OctagonStateAcceptorDone: @5U,
81 };
82 });
83 return map;
84 }
85
86 @interface OTClientStateMachine ()
87 {
88 OctagonState* _currentState;
89 }
90
91 @property dispatch_queue_t queue;
92 @property NSOperationQueue* operationQueue;
93
94 // Make writable
95 @property OctagonState* currentState;
96 @property NSString* clientScope;
97
98 // Set this to an operation to pause the state machine in-flight
99 @property NSOperation* holdStateMachineOperation;
100
101 @property CKKSResultOperation* nextClientStateMachineCycleOperation;
102
103 @property NSMutableArray<OctagonStateTransitionRequest<CKKSResultOperation<OctagonStateTransitionOperationProtocol>*>*>* stateMachineClientRequests;
104
105 @end
106
107 @implementation OTClientStateMachine
108
109 - (instancetype)initWithContainerName:(NSString*)containerName
110 contextID:(NSString*)contextID
111 clientName:(NSString*)clientName
112 cuttlefish:(id<NSXPCProxyCreating>)cuttlefish
113 {
114 if ((self = [super init])) {
115 _containerName = containerName;
116 _clientName = clientName;
117 _contextID = contextID;
118
119 _queue = dispatch_queue_create("com.apple.security.otclientstatemachine", DISPATCH_QUEUE_SERIAL);
120 _operationQueue = [[NSOperationQueue alloc] init];
121
122 _stateConditions = [[NSMutableDictionary alloc] init];
123 [OctagonClientStateMap() enumerateKeysAndObjectsUsingBlock:^(OctagonState * _Nonnull key, NSNumber * _Nonnull obj, BOOL * _Nonnull stop) {
124 self.stateConditions[key] = [[CKKSCondition alloc] init];
125 }];
126
127 // Use the setter method to set the condition variables
128 self.currentState = OctagonStateMachineNotStarted;
129
130 _stateMachineClientRequests = [NSMutableArray array];
131 _holdStateMachineOperation = [NSBlockOperation blockOperationWithBlock:^{}];
132
133 OctagonStateTransitionOperation* beginClientJoin = [OctagonStateTransitionOperation named:@"initialize-client"
134 entering:OctagonStateAcceptorBeginClientJoin];
135 [beginClientJoin addDependency:_holdStateMachineOperation];
136 [_operationQueue addOperation:beginClientJoin];
137
138 CKKSResultOperation* startStateMachineOp = [self createOperationToFinishAttemptForClient:beginClientJoin clientName:clientName];
139 [_operationQueue addOperation:startStateMachineOp];
140
141 _cuttlefishXPCConnection = cuttlefish;
142
143 _clientScope = [NSString stringWithFormat:@"octagon-client-%@-state", clientName];
144 }
145 return self;
146 }
147
148 - (void)dealloc
149 {
150 // TODO: how to invalidate this?
151 //[self.cuttlefishXPCConnection invalidate];
152 }
153
154 - (OctagonState* _Nonnull)currentState {
155 return _currentState;
156 }
157
158 - (void)setCurrentState:(OctagonState* _Nonnull)state {
159 if((state == nil && _currentState == nil) || ([state isEqualToString:_currentState])) {
160 // No change, do nothing.
161 } else {
162 // Fixup the condition variables as part of setting this state
163 if(_currentState) {
164 self.stateConditions[_currentState] = [[CKKSCondition alloc] init];
165 }
166
167 _currentState = state;
168
169 if(state) {
170 [self.stateConditions[state] fulfill];
171 }
172 }
173 }
174
175 - (void)startOctagonStateMachine {
176 dispatch_sync(self.queue, ^{
177 if(self.holdStateMachineOperation) {
178 [self.operationQueue addOperation: self.holdStateMachineOperation];
179 self.holdStateMachineOperation = nil;
180 }
181 });
182 }
183
184 #pragma mark --- Client State Machine Machinery
185
186 - (CKKSResultOperation*)createOperationToFinishAttemptForClient:(CKKSResultOperation<OctagonStateTransitionOperationProtocol>*)attempt clientName:(NSString*)clientName
187 {
188 WEAKIFY(self);
189
190 CKKSResultOperation* followUp = [CKKSResultOperation named:@"octagon-state-follow-up" withBlock:^{
191 STRONGIFY(self);
192
193 dispatch_sync(self.queue, ^{
194 otclientnotice(self.clientScope, "Finishing state transition attempt %@", attempt);
195
196 self.currentState = attempt.nextState;
197 self.nextClientStateMachineCycleOperation = nil;
198
199 [self _onqueueStartNextClientStateMachineOperation:clientName];
200 });
201 }];
202 [followUp addNullableDependency:self.holdStateMachineOperation];
203 [followUp addNullableDependency:attempt];
204 return followUp;
205 }
206
207 - (void)_onqueuePokeClientStateMachine:(NSString*)clientName
208 {
209 dispatch_assert_queue(self.queue);
210 if(!self.nextClientStateMachineCycleOperation) {
211 [self _onqueueStartNextClientStateMachineOperation:clientName];
212 }
213 }
214
215 - (void)_onqueueStartNextClientStateMachineOperation:(NSString*)clientName {
216 dispatch_assert_queue(self.queue);
217
218 CKKSResultOperation<OctagonStateTransitionOperationProtocol>* nextAttempt = [self _onqueueNextClientStateMachineTransition:clientName];
219 if(nextAttempt) {
220 otclientnotice(self.clientScope, "Beginning client state transition attempt %@", nextAttempt);
221
222 self.nextClientStateMachineCycleOperation = [self createOperationToFinishAttemptForClient:nextAttempt clientName:clientName];
223 [self.operationQueue addOperation:self.nextClientStateMachineCycleOperation];
224
225 [nextAttempt addNullableDependency:self.holdStateMachineOperation];
226 [self.operationQueue addOperation:nextAttempt];
227 }
228 }
229
230 - (void)handleExternalClientStateMachineRequest:(OctagonStateTransitionRequest<CKKSResultOperation<OctagonStateTransitionOperationProtocol>*>*)request client:(NSString*)clientName
231 {
232 dispatch_sync(self.queue, ^{
233 [self.stateMachineClientRequests addObject:request];
234
235 [self _onqueuePokeClientStateMachine:clientName];
236 });
237 }
238 -(BOOL) isAcceptorWaitingForFirstMessage
239 {
240 BOOL isWaitingForFirstMessage = NO;
241
242 if([self.currentState isEqualToString:OctagonStateAcceptorBeginClientJoin] || [self.currentState isEqualToString:OctagonStateMachineNotStarted]){
243 isWaitingForFirstMessage = YES;
244 }
245 return isWaitingForFirstMessage;
246 }
247 #pragma mark --- Client State Machine Transitions
248 - (CKKSResultOperation<OctagonStateTransitionOperationProtocol>* _Nullable)_onqueueNextClientStateMachineTransition:(NSString*)clientName
249 {
250 dispatch_assert_queue(self.queue);
251
252 // Check requests: do any of them want to come from this state?
253 for(OctagonStateTransitionRequest<OctagonStateTransitionOperation*>* request in self.stateMachineClientRequests) {
254 if([request.sourceStates containsObject:self.currentState]) {
255 CKKSResultOperation<OctagonStateTransitionOperationProtocol>* attempt = [request _onqueueStart];
256
257 if(attempt) {
258 otclientnotice(self.clientScope, "Running client %@ state machine request %@ (from %@)", clientName, request, self.currentState);
259 return attempt;
260 }
261 }
262 }
263 if([self.currentState isEqualToString: OctagonStateAcceptorVoucherPrepared]){
264 return [OctagonStateTransitionOperation named:@"octagon-voucher-prepared"
265 intending:OctagonStateAcceptorDone
266 errorState:OctagonStateError
267 timeout:10*NSEC_PER_SEC
268 withBlockTakingSelf:^(OctagonStateTransitionOperation * _Nonnull op) {
269 otclientnotice(self.clientScope, "moving to state done for %@", clientName);
270 op.nextState = OctagonStateAcceptorDone;
271 }];
272 }else if([self.currentState isEqualToString: OctagonStateAcceptorDone]){
273 otclientnotice(self.clientScope, "removing client connection for %@", clientName);
274 }
275
276 return nil;
277 }
278
279 - (void)notifyContainerChange
280 {
281 secerror("OTCuttlefishContext: received a cuttlefish push notification (%@)", self.containerName);
282 [[self.cuttlefishXPCConnection synchronousRemoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) {
283 secerror("octagon: Can't talk with TrustedPeersHelper, update is lost: %@", error);
284
285 }] updateWithContainer:self.containerName
286 context:self.contextID
287 deviceName:nil
288 serialNumber:nil
289 osVersion:nil
290 policyVersion:nil
291 policySecrets:nil
292 reply:^(TrustedPeersHelperPeerState* peerState, NSError* error) {
293 if(error) {
294 secerror("OTCuttlefishContext: updating errored: %@", error);
295 } else {
296 secerror("OTCuttlefishContext: update complete");
297 }
298 }];
299 }
300
301 #pragma mark --- External Interfaces
302
303 - (void)rpcEpoch:(OTCuttlefishContext*)cuttlefishContext
304 reply:(void (^)(uint64_t epoch,
305 NSError * _Nullable error))reply
306 {
307 OTEpochOperation* pendingOp = [[OTEpochOperation alloc] initForCuttlefishContext:cuttlefishContext
308 intendedState:OctagonStateAcceptorAwaitingIdentity
309 errorState:OctagonStateAcceptorDone];
310
311 OctagonStateTransitionRequest<OTEpochOperation*>* request = [[OctagonStateTransitionRequest alloc] init:@"rpcEpoch"
312 sourceStates:[NSSet setWithArray:@[OctagonStateAcceptorBeginClientJoin]]
313 serialQueue:self.queue
314 timeout:2*NSEC_PER_SEC
315 transitionOp:pendingOp];
316
317 CKKSResultOperation* callback = [CKKSResultOperation named:@"rpcEpoch-callback"
318 withBlock:^{
319 secnotice("otrpc", "Returning an epoch call: %llu %@", pendingOp.epoch, pendingOp.error);
320 reply(pendingOp.epoch,
321 pendingOp.error);
322 }];
323 [callback addDependency:pendingOp];
324 [self.operationQueue addOperation: callback];
325
326 [self handleExternalClientStateMachineRequest:request client:self.clientName];
327
328 return;
329 }
330
331 - (void)rpcVoucher:(OTCuttlefishContext*)cuttlefishContext
332 peerID:(NSString*)peerID
333 permanentInfo:(NSData *)permanentInfo
334 permanentInfoSig:(NSData *)permanentInfoSig
335 stableInfo:(NSData *)stableInfo
336 stableInfoSig:(NSData *)stableInfoSig
337 reply:(void (^)(NSData* voucher, NSData* voucherSig, NSError * _Nullable error))reply
338 {
339 OTClientVoucherOperation* pendingOp = [[OTClientVoucherOperation alloc] initWithDependencies:cuttlefishContext.operationDependencies
340 intendedState:OctagonStateAcceptorVoucherPrepared
341 errorState:OctagonStateAcceptorDone
342 deviceInfo:[cuttlefishContext prepareInformation]
343 peerID:peerID
344 permanentInfo:permanentInfo
345 permanentInfoSig:permanentInfoSig
346 stableInfo:stableInfo
347 stableInfoSig:stableInfoSig];
348
349 OctagonStateTransitionRequest<OTClientVoucherOperation*>* request = [[OctagonStateTransitionRequest alloc] init:@"rpcVoucher"
350 sourceStates:[NSSet setWithArray:@[OctagonStateAcceptorAwaitingIdentity]]
351 serialQueue:self.queue
352 timeout:2*NSEC_PER_SEC
353
354 transitionOp:pendingOp];
355 CKKSResultOperation* callback = [CKKSResultOperation named:@"rpcVoucher-callback"
356 withBlock:^{
357 secnotice("otrpc", "Returning a voucher call: %@, %@, %@", pendingOp.voucher, pendingOp.voucherSig, pendingOp.error);
358 reply(pendingOp.voucher, pendingOp.voucherSig, pendingOp.error);
359 }];
360 [callback addDependency:pendingOp];
361 [self.operationQueue addOperation: callback];
362
363 [self handleExternalClientStateMachineRequest:request client:self.clientName];
364
365 return;
366 }
367
368 @end
369 #endif