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 (readonly) NSObject<KCJoiningAcceptSecretDelegate>* secretDelegate;
46 @property (readonly) NSObject<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 // We handle failure, don't capture the error.
277 NSData* confirmation = [self.context copyConfirmationFor:message.firstData error:NULL];
279 // Find out what kind of error we should send.
280 NSData* errorData = nil;
282 KCRetryOrNot status = [self.secretDelegate verificationFailed: error];
283 secerror("processResponse: handle error: %d", (int)status);
287 // We fill in an error if they didn't, but if they did this wont bother.
288 KCJoiningErrorCreate(kInternalError, error, @"Delegate returned error without filling in error: %@", self.secretDelegate);
290 case kKCRetryWithSameChallenge:
291 errorData = [NSData data];
293 case kKCRetryWithNewChallenge:
294 if ([self.context resetWithPassword:[self.secretDelegate secret] error:error]) {
295 errorData = [self copyChallengeMessage: error];
299 if (errorData == nil) return nil;
301 return [[KCJoiningMessage messageWithType:kError
306 NSData* encoded = [NSData dataWithEncodedString:[self.secretDelegate accountCode] error:error];
310 NSData* encrypted = [self.session encrypt:encoded error:error];
311 if (encrypted == nil) return nil;
313 self->_state = kExpectingPeerInfo;
315 return [[KCJoiningMessage messageWithType:kVerification
321 - (NSData*) processSOSApplication: (NSData*) message error:(NSError**) error
323 NSData* decryptedPayload = [self.session decryptAndVerify:message error:error];
324 if (decryptedPayload == nil) return nil;
326 CFErrorRef cfError = NULL;
327 SOSPeerInfoRef ref = SOSPeerInfoCreateFromData(NULL, &cfError, (__bridge CFDataRef) decryptedPayload);
329 if (error) *error = (__bridge_transfer NSError*) cfError;
334 NSData* joinData = [self.circleDelegate circleJoinDataFor:ref error:error];
340 if (joinData == nil) return nil;
342 if(self->_piggy_version == kPiggyV1){
343 //grab iCloud Identities, TLKs
344 secnotice("acceptor", "piggy version is 1");
345 NSError *localV1Error = nil;
346 NSData* initialSyncData = [self.circleDelegate circleGetInitialSyncViews:&localV1Error];
348 secnotice("piggy", "PB v1 threw an error: %@", localV1Error);
351 NSMutableData* growPacket = [[NSMutableData alloc] initWithData:joinData];
352 [growPacket appendData:initialSyncData];
353 joinData = growPacket;
357 NSData* encryptedOutgoing = [self.session encrypt:joinData error:error];
358 if (encryptedOutgoing == nil) return nil;
359 return encryptedOutgoing;
363 - (OTPairingMessage *)createPairingMessageFromJoiningMessage:(KCJoiningMessage *)message error:(NSError**) error
365 NSData *decryptInitialMessage = [self.session decryptAndVerify:message.firstData error:error];
366 if(!decryptInitialMessage) {
367 secinfo("KeychainCircle", "Failed to decrypt message first data: %@. Trying legacy OTPairingMessage construction.", error ? *error : @"");
368 return [[OTPairingMessage alloc] initWithData:message.firstData];
370 KCInitialMessageData *initialMessage = [[KCInitialMessageData alloc] initWithData:decryptInitialMessage];
371 if(!initialMessage) {
372 secerror("Failed to parse InitialMessageData from decrypted message data");
373 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Failed to parse InitialMessageData from decrypted message data");
377 if(!initialMessage.hasPrepareMessage) {
378 secerror("InitialMessageData does not contain prepare message");
379 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected prepare message inside InitialMessageData");
383 return [[OTPairingMessage alloc] initWithData:initialMessage.prepareMessage];
388 - (NSData*) processApplication: (KCJoiningMessage*) message error:(NSError**) error {
389 if ([message type] != kPeerInfo) {
390 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected peerInfo!");
394 if(self.piggy_version == kPiggyV2 && KCJoiningOctagonPiggybackingEnabled()){
395 __block NSData* next = nil;
396 __block NSError* localError = nil;
397 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
399 OTPairingMessage *pairingMessage = [self createPairingMessageFromJoiningMessage:message error:error];
400 if(!pairingMessage) {
401 secerror("octagon, failed to create pairing message from JoiningMessage");
402 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Failed to create pairing message from JoiningMessage");
406 if(!pairingMessage.hasPrepare) {
407 secerror("octagon, message does not contain prepare message");
408 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected prepare message!");
411 OTApplicantToSponsorRound2M1 *prepareMessage = pairingMessage.prepare;
413 //handle identity, fetch voucher
414 [self.otControl rpcVoucherWithConfiguration:self.joiningConfiguration
415 peerID:prepareMessage.peerID
416 permanentInfo:prepareMessage.permanentInfo
417 permanentInfoSig:prepareMessage.permanentInfoSig
418 stableInfo:prepareMessage.stableInfo
419 stableInfoSig:prepareMessage.stableInfoSig reply:^(NSData *voucher,
423 secerror("error producing octagon voucher: %@", err);
426 OTPairingMessage *pairingResponse = [[OTPairingMessage alloc] init];
427 pairingResponse.voucher = [[OTSponsorToApplicantRound2M2 alloc] init];
428 pairingResponse.voucher.voucher = voucher;
429 pairingResponse.voucher.voucherSignature = voucherSig;
430 next = pairingResponse.data;
432 dispatch_semaphore_signal(sema);
435 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 30)) != 0) {
436 secerror("octagon: timed out producing octagon voucher");
440 if(error && localError){
446 NSData* encryptedOutgoing = nil;
447 if (OctagonPlatformSupportsSOS() && message.secondData) {
448 secnotice("joining", "doing SOS processSOSApplication");
449 //note we are stuffing SOS into the payload "secondData"
450 encryptedOutgoing = [self processSOSApplication: message.secondData error:error];
452 secnotice("joining", "no platform support processSOSApplication, peer sent data: %s",
453 message.secondData ? "yes" : "no");
456 self->_state = kAcceptDone;
458 return [[KCJoiningMessage messageWithType:kCircleBlob
460 payload:encryptedOutgoing
464 NSData* encryptedOutgoing = [self processSOSApplication: message.firstData error:error];
466 self->_state = kAcceptDone;
468 secnotice("joining", "posting kSOSCCCircleOctagonKeysChangedNotification");
469 notify_post(kSOSCCCircleOctagonKeysChangedNotification);
471 return [[KCJoiningMessage messageWithType:kCircleBlob
472 data:encryptedOutgoing
477 - (nullable NSData*) processMessage: (NSData*) incomingMessage error: (NSError**) error {
478 NSData* result = nil;
480 secnotice("acceptor", "processMessages: %@", [self description]);
482 KCJoiningMessage *message = (self.state != kExpectingA) ? [KCJoiningMessage messageWithDER:incomingMessage error:error] : nil;
486 return [self processInitialMessage:incomingMessage error: error];
488 if (message == nil) return nil;
489 return [self processResponse:message error: error];
491 case kExpectingPeerInfo:
492 if (message == nil) return nil;
493 return [self processApplication:message error: error];
496 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Unexpected message while done");
503 return self.state == kAcceptDone;
508 - (void)setControlObject:(OTControl *)control
510 self.otControl = control;
513 - (void)setConfiguration:(OTJoiningConfiguration *)config
515 self.joiningConfiguration = config;