2 // KCJoiningAcceptSession.m
7 #import <Foundation/Foundation.h>
9 #import <KeychainCircle/KCJoiningSession.h>
11 #import <KeychainCircle/KCError.h>
12 #import <KeychainCircle/KCDer.h>
13 #import <KeychainCircle/KCJoiningMessages.h>
15 #import <KeychainCircle/NSError+KCCreationHelpers.h>
16 #import "KCInitialMessageData.h"
18 #include <corecrypto/ccder.h>
19 #include <corecrypto/ccrng.h>
20 #include <corecrypto/ccsha2.h>
21 #include <corecrypto/ccdh_gp.h>
22 #include <utilities/debugging.h>
23 #include <CommonCrypto/CommonRandomSPI.h>
27 #import "keychain/ot/OTControl.h"
28 #import "keychain/ot/OTJoiningConfiguration.h"
29 #import "KeychainCircle/KCJoiningAcceptSession+Internal.h"
30 #import "keychain/ot/proto/generated_source/OTApplicantToSponsorRound2M1.h"
31 #import "keychain/ot/proto/generated_source/OTSponsorToApplicantRound2M2.h"
32 #import "keychain/ot/proto/generated_source/OTSponsorToApplicantRound1M2.h"
33 #import "keychain/ot/proto/generated_source/OTPairingMessage.h"
41 } KCJoiningAcceptSessionState;
43 @interface KCJoiningAcceptSession ()
44 @property (readonly) uint64_t dsid;
45 @property (weak) id<KCJoiningAcceptSecretDelegate> secretDelegate;
46 @property (weak) id<KCJoiningAcceptCircleDelegate> circleDelegate;
47 @property (readonly) KCSRPServerContext* context;
48 @property (readonly) KCAESGCMDuplexSession* session;
49 @property (readonly) KCJoiningAcceptSessionState state;
50 @property (readwrite) NSData* startMessage;
51 @property (readwrite) NSString *piggy_uuid;
52 @property (readwrite) PiggyBackProtocolVersion piggy_version;
53 @property (readwrite) NSData* octagon;
55 @property (nonatomic, strong) OTJoiningConfiguration* joiningConfiguration;
56 @property (nonatomic, strong) OTControl* otControl;
58 @property (nonatomic, strong) NSMutableDictionary *defaults;
61 @implementation KCJoiningAcceptSession
63 + (nullable instancetype) sessionWithInitialMessage: (NSData*) message
64 secretDelegate: (NSObject<KCJoiningAcceptSecretDelegate>*) secretDelegate
65 circleDelegate: (NSObject<KCJoiningAcceptCircleDelegate>*) circleDelegate
67 error: (NSError**) error {
70 struct ccrng_state * rng = ccrng(&cc_error);
73 CoreCryptoError(cc_error, error, @"RNG fetch failed");
77 return [[KCJoiningAcceptSession alloc] initWithSecretDelegate: secretDelegate
78 circleDelegate: circleDelegate
84 - (bool) setupSession: (NSError**) error {
85 NSData* key = [self->_context getKey];
88 KCJoiningErrorCreate(kInternalError, error, @"No session key available");
92 self->_session = [KCAESGCMDuplexSession sessionAsReceiver:key context:self.dsid];
94 self.session.pairingUUID = self.joiningConfiguration.pairingUUID;
96 self.session.piggybackingVersion = self.piggy_version;
98 return self.session != nil;
101 - (nullable instancetype) initWithSecretDelegate: (NSObject<KCJoiningAcceptSecretDelegate>*) secretDelegate
102 circleDelegate: (NSObject<KCJoiningAcceptCircleDelegate>*) circleDelegate
103 dsid: (uint64_t) dsid
104 rng: (struct ccrng_state *)rng
105 error: (NSError**) error {
108 secnotice("accepting", "initWithSecretDelegate");
110 NSString* name = [NSString stringWithFormat: @"%llu", dsid];
112 self->_context = [[KCSRPServerContext alloc] initWithUser: name
113 password: [secretDelegate secret]
114 digestInfo: ccsha256_di()
115 group: ccsrp_gp_rfc5054_3072()
117 self.secretDelegate = secretDelegate;
118 self.circleDelegate = circleDelegate;
119 self->_state = kExpectingA;
121 self->_piggy_uuid = nil;
122 self->_defaults = [NSMutableDictionary dictionary];
125 self->_otControl = [OTControl controlObject:true error:error];
126 self->_piggy_version = KCJoiningOctagonPiggybackingEnabled()? kPiggyV2 : kPiggyV1;
127 self->_joiningConfiguration = [[OTJoiningConfiguration alloc]initWithProtocolType:@"OctagonPiggybacking"
128 uniqueDeviceID:@"acceptor-deviceid"
129 uniqueClientID:@"requester-deviceid"
131 contextID:OTDefaultContext
135 self->_piggy_version = kPiggyV1;
141 - (NSString*) stateString {
142 switch (self.state) {
143 case kExpectingA: return @"→A";
144 case kExpectingM: return @"→M";
145 case kExpectingPeerInfo: return @"→PeerInfo";
146 case kAcceptDone: return @"done";
147 default: return [NSString stringWithFormat:@"%d", self.state];
151 - (NSString *)description {
152 return [NSString stringWithFormat: @"<KCJoiningAcceptSession: %lld %@ %@ uuid: %@>", self.dsid, [self stateString], self.context, self.piggy_uuid];
155 - (NSData*) copyChallengeMessage: (NSError**) error {
156 NSData* challenge = [self.context copyChallengeFor: self.startMessage error: error];
157 if (challenge == nil) return nil;
159 NSData* srpMessage = [NSData dataWithEncodedSequenceData:self.context.salt data:challenge error:error];
161 if (![self setupSession:error]) return nil;
167 - (BOOL)shouldAcceptOctagonRequests {
168 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
169 __block BOOL result = NO;
171 OTOperationConfiguration* configuration = [[OTOperationConfiguration alloc] init];
172 configuration.discretionaryNetwork = TRUE;
174 [self.otControl fetchTrustStatus:self.joiningConfiguration.containerName context:self.joiningConfiguration.self.contextID
175 configuration:configuration
176 reply:^(CliqueStatus status,
178 NSNumber * _Nullable numberOfPeersInOctagon,
179 BOOL isExcluded, NSError* _Nullable error)
181 secerror("octagon haveSelfEgo: status %d: %@ %@ %d: %@", (int)status,
182 peerID, numberOfPeersInOctagon, isExcluded, error);
184 if (status == CliqueStatusIn) {
187 dispatch_semaphore_signal(sema);
190 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 30)) != 0) {
191 secerror("octagon: timed out fetching trust status");
198 - (NSData*) processInitialMessage: (NSData*) initialMessage error: (NSError**) error {
199 __block uint64_t version = 0;
200 NSString *uuid = nil;
201 NSData *octagon = nil;
202 NSError* localError = nil;
204 self.startMessage = extractStartFromInitialMessage(initialMessage, &version, &uuid, &octagon, error);
205 if (self.startMessage == NULL) {
209 if(version == kPiggyV2 && KCJoiningOctagonPiggybackingEnabled()){
210 /* before we go ahead with octagon, let see if we are an octagon peer */
212 if (![self shouldAcceptOctagonRequests]) {
213 secerror("octagon refusing octagon acceptor since we don't have a selfEgo");
216 self.octagon = octagon;
221 self.piggy_uuid = uuid;
222 self.piggy_version = (PiggyBackProtocolVersion)version;
224 NSData* srpMessage = [self copyChallengeMessage: error];
225 if (srpMessage == nil) {
229 self->_state = kExpectingM;
231 NSString* piggyVersionMessage = [[NSString alloc]initWithData:self.octagon encoding:NSUTF8StringEncoding];
232 __block NSError *captureError = nil;
234 if(version == kPiggyV2 && KCJoiningOctagonPiggybackingEnabled() && piggyVersionMessage && [piggyVersionMessage isEqualToString:@"o"]) {
235 __block NSData* next = nil;
236 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
239 [self.otControl rpcEpochWithConfiguration:self.joiningConfiguration reply:^(uint64_t epoch, NSError * _Nullable epochError) {
241 secerror("error retrieving next message! :%@", epochError);
242 captureError = epochError;
244 OTPairingMessage* responseMessage = [[OTPairingMessage alloc] init];
245 responseMessage.epoch = [[OTSponsorToApplicantRound1M2 alloc] init];
246 responseMessage.epoch.epoch = epoch;
247 next = responseMessage.data;
249 dispatch_semaphore_signal(sema);
252 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 30)) != 0) {
253 secerror("octagon: timed out fetching epoch");
256 if(error && captureError){
257 *error = captureError;
259 return [[KCJoiningMessage messageWithType:kChallenge
265 return [[KCJoiningMessage messageWithType:kChallenge
270 - (NSData*) processResponse: (KCJoiningMessage*) message error:(NSError**) error {
271 if ([message type] != kResponse) {
272 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected response!");
276 id<KCJoiningAcceptSecretDelegate> secretDelegate = self.secretDelegate;
278 // We handle failure, don't capture the error.
279 NSData* confirmation = [self.context copyConfirmationFor:message.firstData error:NULL];
281 // Find out what kind of error we should send.
282 NSData* errorData = nil;
284 KCRetryOrNot status = [secretDelegate verificationFailed: error];
285 secerror("processResponse: handle error: %d", (int)status);
289 // We fill in an error if they didn't, but if they did this wont bother.
290 KCJoiningErrorCreate(kInternalError, error, @"Delegate returned error without filling in error: %@", secretDelegate);
292 case kKCRetryWithSameChallenge:
293 errorData = [NSData data];
295 case kKCRetryWithNewChallenge:
296 if ([self.context resetWithPassword:[secretDelegate secret] error:error]) {
297 errorData = [self copyChallengeMessage: error];
301 if (errorData == nil) return nil;
303 return [[KCJoiningMessage messageWithType:kError
308 NSData* encoded = [NSData dataWithEncodedString:[secretDelegate accountCode] error:error];
312 NSData* encrypted = [self.session encrypt:encoded error:error];
313 if (encrypted == nil) return nil;
315 self->_state = kExpectingPeerInfo;
317 return [[KCJoiningMessage messageWithType:kVerification
323 - (NSData*) processSOSApplication: (NSData*) message error:(NSError**) error
325 NSData* decryptedPayload = [self.session decryptAndVerify:message error:error];
326 if (decryptedPayload == nil) return nil;
328 id<KCJoiningAcceptCircleDelegate> circleDelegate = self.circleDelegate;
330 CFErrorRef cfError = NULL;
331 SOSPeerInfoRef ref = SOSPeerInfoCreateFromData(NULL, &cfError, (__bridge CFDataRef) decryptedPayload);
333 if (error) *error = (__bridge_transfer NSError*) cfError;
338 NSData* joinData = [circleDelegate circleJoinDataFor:ref error:error];
344 if (joinData == nil) return nil;
346 SOSInitialSyncFlags flags = 0;
347 switch (self.piggy_version) {
351 secnotice("acceptor", "piggy version is 1");
352 flags |= kSOSInitialSyncFlagTLKs | kSOSInitialSyncFlagiCloudIdentity;
355 secnotice("acceptor", "piggy version is 2");
356 flags |= kSOSInitialSyncFlagiCloudIdentity;
361 //grab iCloud Identities, TLKs
362 NSError *localISVError = nil;
363 NSData* initialSyncData = [circleDelegate circleGetInitialSyncViews:flags error:&localISVError];
364 if(initialSyncData == NULL){
365 secnotice("piggy", "PB threw an error: %@", localISVError);
368 NSMutableData* growPacket = [[NSMutableData alloc] initWithData:joinData];
369 [growPacket appendData:initialSyncData];
370 joinData = growPacket;
374 NSData* encryptedOutgoing = [self.session encrypt:joinData error:error];
375 if (encryptedOutgoing == nil) return nil;
376 return encryptedOutgoing;
380 - (OTPairingMessage *)createPairingMessageFromJoiningMessage:(KCJoiningMessage *)message error:(NSError**) error
382 NSData *decryptInitialMessage = [self.session decryptAndVerify:message.firstData error:error];
383 if(!decryptInitialMessage) {
384 secinfo("KeychainCircle", "Failed to decrypt message first data: %@. Trying legacy OTPairingMessage construction.", error ? *error : @"");
385 return [[OTPairingMessage alloc] initWithData:message.firstData];
387 KCInitialMessageData *initialMessage = [[KCInitialMessageData alloc] initWithData:decryptInitialMessage];
388 if(!initialMessage) {
389 secerror("Failed to parse InitialMessageData from decrypted message data");
390 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Failed to parse InitialMessageData from decrypted message data");
394 if(!initialMessage.hasPrepareMessage) {
395 secerror("InitialMessageData does not contain prepare message");
396 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected prepare message inside InitialMessageData");
400 return [[OTPairingMessage alloc] initWithData:initialMessage.prepareMessage];
405 - (NSData*) processApplication: (KCJoiningMessage*) message error:(NSError**) error {
406 if ([message type] != kPeerInfo) {
407 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected peerInfo!");
411 if(self.piggy_version == kPiggyV2 && KCJoiningOctagonPiggybackingEnabled()){
412 __block NSData* next = nil;
413 __block NSError* localError = nil;
414 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
416 OTPairingMessage *pairingMessage = [self createPairingMessageFromJoiningMessage:message error:error];
417 if(!pairingMessage) {
418 secerror("octagon, failed to create pairing message from JoiningMessage");
419 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Failed to create pairing message from JoiningMessage");
423 if(!pairingMessage.hasPrepare) {
424 secerror("octagon, message does not contain prepare message");
425 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected prepare message!");
428 OTApplicantToSponsorRound2M1 *prepareMessage = pairingMessage.prepare;
430 //handle identity, fetch voucher
431 [self.otControl rpcVoucherWithConfiguration:self.joiningConfiguration
432 peerID:prepareMessage.peerID
433 permanentInfo:prepareMessage.permanentInfo
434 permanentInfoSig:prepareMessage.permanentInfoSig
435 stableInfo:prepareMessage.stableInfo
436 stableInfoSig:prepareMessage.stableInfoSig reply:^(NSData *voucher,
440 secerror("error producing octagon voucher: %@", err);
443 OTPairingMessage *pairingResponse = [[OTPairingMessage alloc] init];
444 pairingResponse.voucher = [[OTSponsorToApplicantRound2M2 alloc] init];
445 pairingResponse.voucher.voucher = voucher;
446 pairingResponse.voucher.voucherSignature = voucherSig;
447 next = pairingResponse.data;
449 dispatch_semaphore_signal(sema);
452 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 30)) != 0) {
453 secerror("octagon: timed out producing octagon voucher");
457 if(error && localError){
463 NSData* encryptedOutgoing = nil;
464 if (OctagonPlatformSupportsSOS() && message.secondData) {
465 secnotice("joining", "doing SOS processSOSApplication");
466 //note we are stuffing SOS into the payload "secondData"
467 encryptedOutgoing = [self processSOSApplication: message.secondData error:error];
469 secnotice("joining", "no platform support processSOSApplication, peer sent data: %s",
470 message.secondData ? "yes" : "no");
473 self->_state = kAcceptDone;
475 return [[KCJoiningMessage messageWithType:kCircleBlob
477 payload:encryptedOutgoing
481 NSData* encryptedOutgoing = [self processSOSApplication: message.firstData error:error];
483 self->_state = kAcceptDone;
485 secnotice("joining", "posting kSOSCCCircleOctagonKeysChangedNotification");
486 notify_post(kSOSCCCircleOctagonKeysChangedNotification);
488 return [[KCJoiningMessage messageWithType:kCircleBlob
489 data:encryptedOutgoing
494 - (nullable NSData*) processMessage: (NSData*) incomingMessage error: (NSError**) error {
495 NSData* result = nil;
497 secnotice("acceptor", "processMessages: %@", [self description]);
499 KCJoiningMessage *message = (self.state != kExpectingA) ? [KCJoiningMessage messageWithDER:incomingMessage error:error] : nil;
503 return [self processInitialMessage:incomingMessage error: error];
505 if (message == nil) return nil;
506 return [self processResponse:message error: error];
508 case kExpectingPeerInfo:
509 if (message == nil) return nil;
510 return [self processApplication:message error: error];
513 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Unexpected message while done");
520 return self.state == kAcceptDone;
525 - (void)setControlObject:(OTControl *)control
527 self.otControl = control;
530 - (void)setConfiguration:(OTJoiningConfiguration *)config
532 self.joiningConfiguration = config;