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