]> git.saurik.com Git - apple/security.git/blob - keychain/ot/OTClientStateMachine.m
Security-59306.61.1.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 withBlockTakingSelf:^(OctagonStateTransitionOperation * _Nonnull op) {
267 otclientnotice(self.clientScope, "moving to state done for %@", clientName);
268 op.nextState = OctagonStateAcceptorDone;
269 }];
270 }else if([self.currentState isEqualToString: OctagonStateAcceptorDone]){
271 otclientnotice(self.clientScope, "removing client connection for %@", clientName);
272 }
273
274 return nil;
275 }
276
277 - (void)notifyContainerChange
278 {
279 secerror("OTCuttlefishContext: received a cuttlefish push notification (%@)", self.containerName);
280 [[self.cuttlefishXPCConnection synchronousRemoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) {
281 secerror("octagon: Can't talk with TrustedPeersHelper, update is lost: %@", error);
282
283 }] updateWithContainer:self.containerName
284 context:self.contextID
285 deviceName:nil
286 serialNumber:nil
287 osVersion:nil
288 policyVersion:nil
289 policySecrets:nil
290 reply:^(TrustedPeersHelperPeerState* peerState, NSError* error) {
291 if(error) {
292 secerror("OTCuttlefishContext: updating errored: %@", error);
293 } else {
294 secerror("OTCuttlefishContext: update complete");
295 }
296 }];
297 }
298
299 #pragma mark --- External Interfaces
300
301 - (void)rpcEpoch:(OTCuttlefishContext*)cuttlefishContext
302 reply:(void (^)(uint64_t epoch,
303 NSError * _Nullable error))reply
304 {
305 OTEpochOperation* pendingOp = [[OTEpochOperation alloc] init:self.containerName
306 contextID:self.contextID
307 intendedState:OctagonStateAcceptorAwaitingIdentity
308 errorState:OctagonStateAcceptorDone
309 cuttlefishXPCWrapper:cuttlefishContext.cuttlefishXPCWrapper];
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