2 // KCJoiningRequestCircleSession.m
6 #import <Foundation/Foundation.h>
8 #import <KeychainCircle/KCJoiningSession.h>
10 #import <KeychainCircle/KCError.h>
11 #import <KeychainCircle/KCDer.h>
12 #import <KeychainCircle/KCSRPContext.h>
14 #import <KeychainCircle/KCJoiningMessages.h>
16 #include <utilities/debugging.h>
17 #include "KCInitialMessageData.h"
20 #import <Security/OTConstants.h>
21 #import "keychain/ot/OTControl.h"
22 #import "keychain/ot/OTControlProtocol.h"
23 #import "keychain/ot/OctagonControlServer.h"
24 #import "keychain/ot/OTJoiningConfiguration.h"
25 #import "KeychainCircle/KCJoiningRequestSession+Internal.h"
26 #import "keychain/ot/proto/generated_source/OTApplicantToSponsorRound2M1.h"
27 #import "keychain/ot/proto/generated_source/OTSponsorToApplicantRound2M2.h"
28 #import "keychain/ot/proto/generated_source/OTSponsorToApplicantRound1M2.h"
29 #import "keychain/ot/proto/generated_source/OTPairingMessage.h"
31 #import <KeychainCircle/NSError+KCCreationHelpers.h>
36 } KCJoiningRequestCircleSessionState;
38 @interface KCJoiningRequestCircleSession ()
39 @property (readonly) NSObject<KCJoiningRequestCircleDelegate>* circleDelegate;
40 @property (readonly) KCAESGCMDuplexSession* session;
41 @property (readwrite) KCJoiningRequestCircleSessionState state;
42 @property (nonatomic) uint64_t piggy_version;
44 @property (nonatomic, strong) OTControl *otControl;
45 @property (nonatomic, strong) OTJoiningConfiguration* joiningConfiguration;
49 @implementation KCJoiningRequestCircleSession
52 - (void)setControlObject:(OTControl *)control{
53 self.otControl = control;
55 - (void)setContextIDOnJoiningConfiguration:(NSString*)contextID
57 self.joiningConfiguration.contextID = contextID;
59 - (KCAESGCMDuplexSession*)accessSession
66 - (nullable NSData*) encryptedPeerInfo: (NSError**) error {
67 // Get our peer info and send it along:
68 if (self->_session == nil) {
69 KCJoiningErrorCreate(kInternalError, error, @"Attempt to encrypt with no session");
73 SOSPeerInfoRef us = [self.circleDelegate copyPeerInfoError:error];
74 if (us == NULL) return nil;
75 CFErrorRef cfError = NULL;
76 NSData* piEncoded = (__bridge_transfer NSData*) SOSPeerInfoCopyEncodedData(us, NULL, &cfError);
82 if (piEncoded == nil) {
84 *error = (__bridge_transfer NSError*) cfError;
89 return [self->_session encrypt:piEncoded error:error];
92 - (nullable NSData*) encryptedInitialMessage:(NSData*)prepareMessage error:(NSError**) error {
94 if (self->_session == nil) {
95 KCJoiningErrorCreate(kInternalError, error, @"Attempt to encrypt with no session");
99 KCInitialMessageData *initialMessage = [[KCInitialMessageData alloc] init];
100 [initialMessage setPrepareMessage:prepareMessage];
102 return [self->_session encrypt:initialMessage.data error:error];
105 - (nullable NSData*) initialMessage: (NSError**) error {
106 secnotice("joining", "joining: KCJoiningRequestCircleSession initialMessage called");
109 if(KCJoiningOctagonPiggybackingEnabled() && self.piggy_version == kPiggyV2){
110 __block NSData* next = nil;
111 __block NSError* localError = nil;
113 if(!self.joiningConfiguration.epoch) {
114 secerror("octagon: expected epoch! returning from piggybacking.");
118 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
119 //giving securityd the epoch, expecting identity message
120 [self.otControl rpcPrepareIdentityAsApplicantWithConfiguration:self.joiningConfiguration
121 reply:^(NSString *peerID,
122 NSData *permanentInfo,
123 NSData *permanentInfoSig,
125 NSData *stableInfoSig,
128 secerror("octagon: error preparing identity: %@", err);
131 OTPairingMessage *pairingMessage = [[OTPairingMessage alloc]init];
132 OTApplicantToSponsorRound2M1 *prepareMessage = [[OTApplicantToSponsorRound2M1 alloc]init];
133 prepareMessage.peerID = peerID;
134 prepareMessage.permanentInfo = permanentInfo;
135 prepareMessage.permanentInfoSig = permanentInfoSig;
136 prepareMessage.stableInfo = stableInfo;
137 prepareMessage.stableInfoSig = stableInfoSig;
139 pairingMessage.prepare = prepareMessage;
140 next = pairingMessage.data;
142 dispatch_semaphore_signal(sema);
145 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 30)) != 0) {
146 secerror("octagon: timed out preparing identity");
153 NSData* encryptedPi = nil;
154 if (OctagonPlatformSupportsSOS()) {
155 secnotice("joining", "doing SOS encryptedPeerInfo");
156 encryptedPi = [self encryptedPeerInfo:error];
157 if (encryptedPi == nil) return nil;
159 secnotice("joining", "no platform support for encryptedPeerInfo");
162 self->_state = kExpectingCircleBlob;
163 NSData *encryptedInitialMessage = [self encryptedInitialMessage:next error:error];
165 return [[KCJoiningMessage messageWithType: kPeerInfo
166 data:encryptedInitialMessage
172 NSData* encryptedPi = [self encryptedPeerInfo:error];
173 if (encryptedPi == nil) return nil;
175 self->_state = kExpectingCircleBlob;
177 return [[KCJoiningMessage messageWithType:kPeerInfo
183 - (void) attemptSosUpgrade
185 [self.otControl attemptSosUpgrade:self.joiningConfiguration.containerName context:self.joiningConfiguration.contextID reply:^(NSError *error) {
187 secerror("pairing: failed to upgrade initiator into Octagon: %@", error);
192 - (NSData*) handleCircleBlob: (KCJoiningMessage*) message error: (NSError**) error {
193 secnotice("joining", "joining: KCJoiningRequestCircleSession handleCircleBlob called");
194 if ([message type] != kCircleBlob) {
195 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected CircleBlob!");
199 if(self.piggy_version == kPiggyV2 && KCJoiningOctagonPiggybackingEnabled() && message.firstData != nil){
200 __block NSData* nextMessage = nil;
201 __block NSError* localError = nil;
202 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
204 OTPairingMessage* pairingMessage = [[OTPairingMessage alloc]initWithData:message.firstData];
205 if(!pairingMessage.hasVoucher) {
206 secerror("octagon: expected voucher! returning from piggybacking.");
209 OTSponsorToApplicantRound2M2 *voucher = pairingMessage.voucher;
211 //handle voucher message then join octagon
212 [self.otControl rpcJoinWithConfiguration:self.joiningConfiguration
213 vouchData:voucher.voucher
214 vouchSig:voucher.voucherSignature
215 reply:^(NSError * _Nullable err) {
217 secerror("octagon: error joining octagon: %@", err);
220 secnotice("octagon", "successfully joined octagon");
222 dispatch_semaphore_signal(sema);
225 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 30)) != 0) {
227 secerror("octagon: timed out joining octagon");
231 if (OctagonPlatformSupportsSOS()) {
232 secnotice("joining", "doing SOS processCircleJoinData");
233 //note we are stuffing SOS into the payload "secondData"
234 NSData* circleBlob = [self.session decryptAndVerify:message.secondData error:error];
235 if (circleBlob == nil) return nil;
237 if (![self.circleDelegate processCircleJoinData: circleBlob version:kPiggyV1 error:error])
240 secnotice("joining", "platform doesn't support SOS");
243 self->_state = kRequestCircleDone;
246 if(nextMessage == nil){
247 final = [NSData data];
249 self->_state = kRequestCircleDone;
253 NSData* circleBlob = [self.session decryptAndVerify:message.firstData error:error];
254 if (circleBlob == nil) return nil;
256 if (![self.circleDelegate processCircleJoinData: circleBlob version:kPiggyV1 error:error]) {
259 secnotice("joining", "joined the SOS circle!");
260 if(OctagonIsEnabled()) {
261 secnotice("joining", "kicking off SOS Upgrade into Octagon!");
262 [self attemptSosUpgrade];
265 self->_state = kRequestCircleDone;
267 return [NSData data]; // Success, an empty message.
270 - (NSData*) processMessage: (NSData*) incomingMessage error: (NSError**) error {
271 secnotice("joining", "joining: KCJoiningRequestCircleSession processMessage called");
272 NSData* result = nil;
273 KCJoiningMessage* message = [KCJoiningMessage messageWithDER: incomingMessage error: error];
274 if (message == nil) return nil;
277 case kExpectingCircleBlob:
278 return [self handleCircleBlob:message error:error];
279 case kRequestCircleDone:
280 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Done, no messages expected.");
288 return self.state = kRequestCircleDone;
291 + (instancetype) sessionWithCircleDelegate: (NSObject<KCJoiningRequestCircleDelegate>*) circleDelegate
292 session: (KCAESGCMDuplexSession*) session
293 error: (NSError**) error {
294 return [[KCJoiningRequestCircleSession alloc] initWithCircleDelegate:circleDelegate
299 - (instancetype) initWithCircleDelegate: (NSObject<KCJoiningRequestCircleDelegate>*) circleDelegate
300 session: (KCAESGCMDuplexSession*) session
301 error: (NSError**) error {
302 return [self initWithCircleDelegate:circleDelegate
304 otcontrol:[OTControl controlObject:true error:error]
308 - (instancetype)initWithCircleDelegate:(NSObject<KCJoiningRequestCircleDelegate>*)circleDelegate
309 session:(KCAESGCMDuplexSession*) session
310 otcontrol:(OTControl*)otcontrol
311 error:(NSError**) error
313 secnotice("joining", "joining: KCJoiningRequestCircleSession initWithCircleDelegate called, uuid=%@", session.pairingUUID);
316 self->_circleDelegate = circleDelegate;
317 self->_session = session;
318 self.state = kExpectingCircleBlob;
320 self->_otControl = otcontrol;
321 self->_joiningConfiguration = [[OTJoiningConfiguration alloc]initWithProtocolType:@"OctagonPiggybacking"
322 uniqueDeviceID:@"requester-id"
323 uniqueClientID:@"requester-id"
324 pairingUUID:session.pairingUUID
326 contextID:OTDefaultContext
330 self->_piggy_version = session.piggybackingVersion;
332 self->_piggy_version = kPiggyV1;