2 * Copyright (c) 2017 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
25 #import <CoreCDP/CDPAccount.h>
27 #import <Security/Security.h>
29 #include <utilities/SecFileLocations.h>
30 #include <Security/SecRandomP.h>
32 #import "keychain/TrustedPeersHelper/TrustedPeersHelperProtocol.h"
34 #import "keychain/ckks/CKKS.h"
35 #import "keychain/ckks/CKKSAnalytics.h"
36 #import "keychain/ckks/CKKSResultOperation.h"
38 #import "keychain/ckks/OctagonAPSReceiver.h"
40 #import "keychain/ot/proto/generated_source/OTAccountMetadataClassC.h"
41 #import "keychain/ot/ObjCImprovements.h"
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"
52 #import "keychain/ot/ObjCImprovements.h"
53 #import "keychain/ot/proto/generated_source/OTAccountMetadataClassC.h"
55 #import "keychain/categories/NSError+UsefulConstructors.h"
56 #import "keychain/ot/categories/OTAccountMetadataClassC+KeychainSupport.h"
58 #define otclientnotice(scope, format, ...) __extension__({ \
59 os_log(secLogObjForCFScope((__bridge CFStringRef)(scope)), format, ##__VA_ARGS__); \
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";
70 NSDictionary<OctagonState*, NSNumber*>* OctagonClientStateMap(void) {
71 static NSDictionary<OctagonState*, NSNumber*>* map = nil;
72 static dispatch_once_t onceToken;
73 dispatch_once(&onceToken, ^{
75 OctagonStateAcceptorBeginClientJoin: @0U,
76 OctagonStateAcceptorBeginAwaitEpochRequest: @1U,
77 OctagonStateAcceptorEpochPrepared: @2U,
78 OctagonStateAcceptorAwaitingIdentity: @3U,
79 OctagonStateAcceptorVoucherPrepared: @4U,
80 OctagonStateAcceptorDone: @5U,
86 @interface OTClientStateMachine ()
88 OctagonState* _currentState;
91 @property dispatch_queue_t queue;
92 @property NSOperationQueue* operationQueue;
95 @property OctagonState* currentState;
96 @property NSString* clientScope;
98 // Set this to an operation to pause the state machine in-flight
99 @property NSOperation* holdStateMachineOperation;
101 @property CKKSResultOperation* nextClientStateMachineCycleOperation;
103 @property NSMutableArray<OctagonStateTransitionRequest<CKKSResultOperation<OctagonStateTransitionOperationProtocol>*>*>* stateMachineClientRequests;
107 @implementation OTClientStateMachine
109 - (instancetype)initWithContainerName:(NSString*)containerName
110 contextID:(NSString*)contextID
111 clientName:(NSString*)clientName
112 cuttlefish:(id<NSXPCProxyCreating>)cuttlefish
114 if ((self = [super init])) {
115 _containerName = containerName;
116 _clientName = clientName;
117 _contextID = contextID;
119 _queue = dispatch_queue_create("com.apple.security.otclientstatemachine", DISPATCH_QUEUE_SERIAL);
120 _operationQueue = [[NSOperationQueue alloc] init];
122 _stateConditions = [[NSMutableDictionary alloc] init];
123 [OctagonClientStateMap() enumerateKeysAndObjectsUsingBlock:^(OctagonState * _Nonnull key, NSNumber * _Nonnull obj, BOOL * _Nonnull stop) {
124 self.stateConditions[key] = [[CKKSCondition alloc] init];
127 // Use the setter method to set the condition variables
128 self.currentState = OctagonStateMachineNotStarted;
130 _stateMachineClientRequests = [NSMutableArray array];
131 _holdStateMachineOperation = [NSBlockOperation blockOperationWithBlock:^{}];
133 OctagonStateTransitionOperation* beginClientJoin = [OctagonStateTransitionOperation named:@"initialize-client"
134 entering:OctagonStateAcceptorBeginClientJoin];
135 [beginClientJoin addDependency:_holdStateMachineOperation];
136 [_operationQueue addOperation:beginClientJoin];
138 CKKSResultOperation* startStateMachineOp = [self createOperationToFinishAttemptForClient:beginClientJoin clientName:clientName];
139 [_operationQueue addOperation:startStateMachineOp];
141 _cuttlefishXPCConnection = cuttlefish;
143 _clientScope = [NSString stringWithFormat:@"octagon-client-%@-state", clientName];
150 // TODO: how to invalidate this?
151 //[self.cuttlefishXPCConnection invalidate];
154 - (OctagonState* _Nonnull)currentState {
155 return _currentState;
158 - (void)setCurrentState:(OctagonState* _Nonnull)state {
159 if((state == nil && _currentState == nil) || ([state isEqualToString:_currentState])) {
160 // No change, do nothing.
162 // Fixup the condition variables as part of setting this state
164 self.stateConditions[_currentState] = [[CKKSCondition alloc] init];
167 _currentState = state;
170 [self.stateConditions[state] fulfill];
175 - (void)startOctagonStateMachine {
176 dispatch_sync(self.queue, ^{
177 if(self.holdStateMachineOperation) {
178 [self.operationQueue addOperation: self.holdStateMachineOperation];
179 self.holdStateMachineOperation = nil;
184 #pragma mark --- Client State Machine Machinery
186 - (CKKSResultOperation*)createOperationToFinishAttemptForClient:(CKKSResultOperation<OctagonStateTransitionOperationProtocol>*)attempt clientName:(NSString*)clientName
190 CKKSResultOperation* followUp = [CKKSResultOperation named:@"octagon-state-follow-up" withBlock:^{
193 dispatch_sync(self.queue, ^{
194 otclientnotice(self.clientScope, "Finishing state transition attempt %@", attempt);
196 self.currentState = attempt.nextState;
197 self.nextClientStateMachineCycleOperation = nil;
199 [self _onqueueStartNextClientStateMachineOperation:clientName];
202 [followUp addNullableDependency:self.holdStateMachineOperation];
203 [followUp addNullableDependency:attempt];
207 - (void)_onqueuePokeClientStateMachine:(NSString*)clientName
209 dispatch_assert_queue(self.queue);
210 if(!self.nextClientStateMachineCycleOperation) {
211 [self _onqueueStartNextClientStateMachineOperation:clientName];
215 - (void)_onqueueStartNextClientStateMachineOperation:(NSString*)clientName {
216 dispatch_assert_queue(self.queue);
218 CKKSResultOperation<OctagonStateTransitionOperationProtocol>* nextAttempt = [self _onqueueNextClientStateMachineTransition:clientName];
220 otclientnotice(self.clientScope, "Beginning client state transition attempt %@", nextAttempt);
222 self.nextClientStateMachineCycleOperation = [self createOperationToFinishAttemptForClient:nextAttempt clientName:clientName];
223 [self.operationQueue addOperation:self.nextClientStateMachineCycleOperation];
225 [nextAttempt addNullableDependency:self.holdStateMachineOperation];
226 [self.operationQueue addOperation:nextAttempt];
230 - (void)handleExternalClientStateMachineRequest:(OctagonStateTransitionRequest<CKKSResultOperation<OctagonStateTransitionOperationProtocol>*>*)request client:(NSString*)clientName
232 dispatch_sync(self.queue, ^{
233 [self.stateMachineClientRequests addObject:request];
235 [self _onqueuePokeClientStateMachine:clientName];
238 -(BOOL) isAcceptorWaitingForFirstMessage
240 BOOL isWaitingForFirstMessage = NO;
242 if([self.currentState isEqualToString:OctagonStateAcceptorBeginClientJoin] || [self.currentState isEqualToString:OctagonStateMachineNotStarted]){
243 isWaitingForFirstMessage = YES;
245 return isWaitingForFirstMessage;
247 #pragma mark --- Client State Machine Transitions
248 - (CKKSResultOperation<OctagonStateTransitionOperationProtocol>* _Nullable)_onqueueNextClientStateMachineTransition:(NSString*)clientName
250 dispatch_assert_queue(self.queue);
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];
258 otclientnotice(self.clientScope, "Running client %@ state machine request %@ (from %@)", clientName, request, self.currentState);
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;
272 }else if([self.currentState isEqualToString: OctagonStateAcceptorDone]){
273 otclientnotice(self.clientScope, "removing client connection for %@", clientName);
279 - (void)notifyContainerChange
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);
285 }] updateWithContainer:self.containerName
286 context:self.contextID
292 reply:^(TrustedPeersHelperPeerState* peerState, NSError* error) {
294 secerror("OTCuttlefishContext: updating errored: %@", error);
296 secerror("OTCuttlefishContext: update complete");
301 #pragma mark --- External Interfaces
303 - (void)rpcEpoch:(OTCuttlefishContext*)cuttlefishContext
304 reply:(void (^)(uint64_t epoch,
305 NSError * _Nullable error))reply
307 OTEpochOperation* pendingOp = [[OTEpochOperation alloc] initForCuttlefishContext:cuttlefishContext
308 intendedState:OctagonStateAcceptorAwaitingIdentity
309 errorState:OctagonStateAcceptorDone];
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];
317 CKKSResultOperation* callback = [CKKSResultOperation named:@"rpcEpoch-callback"
319 secnotice("otrpc", "Returning an epoch call: %llu %@", pendingOp.epoch, pendingOp.error);
320 reply(pendingOp.epoch,
323 [callback addDependency:pendingOp];
324 [self.operationQueue addOperation: callback];
326 [self handleExternalClientStateMachineRequest:request client:self.clientName];
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
339 OTClientVoucherOperation* pendingOp = [[OTClientVoucherOperation alloc] initWithDependencies:cuttlefishContext.operationDependencies
340 intendedState:OctagonStateAcceptorVoucherPrepared
341 errorState:OctagonStateAcceptorDone
342 deviceInfo:[cuttlefishContext prepareInformation]
344 permanentInfo:permanentInfo
345 permanentInfoSig:permanentInfoSig
346 stableInfo:stableInfo
347 stableInfoSig:stableInfoSig];
349 OctagonStateTransitionRequest<OTClientVoucherOperation*>* request = [[OctagonStateTransitionRequest alloc] init:@"rpcVoucher"
350 sourceStates:[NSSet setWithArray:@[OctagonStateAcceptorAwaitingIdentity]]
351 serialQueue:self.queue
352 timeout:2*NSEC_PER_SEC
354 transitionOp:pendingOp];
355 CKKSResultOperation* callback = [CKKSResultOperation named:@"rpcVoucher-callback"
357 secnotice("otrpc", "Returning a voucher call: %@, %@, %@", pendingOp.voucher, pendingOp.voucherSig, pendingOp.error);
358 reply(pendingOp.voucher, pendingOp.voucherSig, pendingOp.error);
360 [callback addDependency:pendingOp];
361 [self.operationQueue addOperation: callback];
363 [self handleExternalClientStateMachineRequest:request client:self.clientName];