7 #import <Foundation/Foundation.h>
9 #import <KeychainCircle/KCJoiningSession.h>
11 #import <KeychainCircle/KCError.h>
12 #import <KeychainCircle/KCDer.h>
13 #import <KeychainCircle/KCSRPContext.h>
15 #import <KeychainCircle/KCJoiningMessages.h>
17 #include <corecrypto/ccrng.h>
18 #include <corecrypto/ccsha2.h>
19 #include <corecrypto/ccdh_gp.h>
20 #include <corecrypto/ccder.h>
21 #include <CommonCrypto/CommonRandomSPI.h>
23 #include <utilities/debugging.h>
25 #import <KeychainCircle/NSError+KCCreationHelpers.h>
31 } KCJoiningRequestSecretSessionState;
36 } KCJoiningRequestCircleSessionState;
39 @interface KCJoiningRequestSecretSession ()
40 @property (readonly) NSObject<KCJoiningRequestSecretDelegate>* secretDelegate;
41 @property (readonly) KCSRPClientContext* context;
42 @property (readonly) uint64_t dsid;
43 @property (readonly) KCJoiningRequestSecretSessionState state;
44 @property (readwrite) NSString* piggy_uuid;
45 @property (readwrite) uint64_t piggy_version;
46 @property (readwrite) NSData* challenge;
47 @property (readwrite) NSData* salt;
50 static const uint64_t KCProtocolVersion = kPiggyV1;
52 @implementation KCJoiningRequestSecretSession : NSObject
54 - (nullable NSData*) initialMessage: (NSError**) error {
55 NSData* start = [self->_context copyStart: error];
56 if (start == nil) return nil;
58 NSMutableData* initialMessage = NULL;
61 if(KCProtocolVersion == kPiggyV1)
63 NSUUID *uuid = [NSUUID UUID];
66 self.piggy_uuid = [uuid UUIDString];
67 [uuid getUUIDBytes:uuidBytes];
68 NSData *uuidData = [NSData dataWithBytes:uuidBytes length:sizeof(uuid_t)];
70 initialMessage = [NSMutableData dataWithLength: sizeof_initialmessage_version1(start, KCProtocolVersion, uuidData)];
72 if (NULL == encode_initialmessage_version1(start, uuidData, KCProtocolVersion, error, initialMessage.mutableBytes, initialMessage.mutableBytes + initialMessage.length))
76 initialMessage = [NSMutableData dataWithLength: sizeof_initialmessage(start)];
77 if (NULL == encode_initialmessage(start, error, initialMessage.mutableBytes, initialMessage.mutableBytes + initialMessage.length))
81 return initialMessage;
85 return self->_state == kRequestSecretDone;
88 - (bool) setupSession: (NSError**) error {
89 NSData* key = [self->_context getKey];
92 KCJoiningErrorCreate(kInternalError, error, @"No session key available");
96 self->_session = [KCAESGCMDuplexSession sessionAsSender:key context:self.dsid];
98 return self.session != nil;
101 - (nullable NSData*) copyResponseForChallenge:(NSData*) challenge
103 secret: (NSString*) password
104 error: (NSError**) error {
105 NSData* response = [self->_context copyResposeToChallenge:challenge
111 // @@@ return error to other side???
114 if (![self setupSession: error]) return nil;
116 self.challenge = challenge;
119 self->_state = kExpectingHAMK;
120 return [[KCJoiningMessage messageWithType:kResponse
127 - (nullable NSData*) copyResponseForSecret: (NSString*) password
128 error: (NSError**) error {
129 return [self copyResponseForChallenge:self.challenge salt:self.salt secret:password error:error];
132 - (nullable NSData*) handleChallengeData: (NSData*) challengeData
133 secret: (NSString*) password
134 error: (NSError**) error {
135 NSData* challenge = nil;
138 if (![challengeData decodeSequenceData:&salt data:&challenge error:error]) return nil;
140 return [self copyResponseForChallenge:challenge salt:salt secret:password error:error];
144 - (nullable NSData*) handleChallenge: (KCJoiningMessage*) message
145 secret: (NSString*) password
146 error: (NSError**)error {
147 // Parse the challenge message
148 // Salt and Challenge packet
149 if ([message type] != kChallenge) {
150 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected challenge!");
154 return [self handleChallengeData:[message firstData] secret:password error:error];
157 - (NSData*) handleChallenge: (KCJoiningMessage*) message error: (NSError**)error {
158 return [self handleChallenge:message
159 secret:[self.secretDelegate secret]
164 - (NSData*) handleVerification: (KCJoiningMessage*) message error: (NSError**) error {
165 if ([message type] == kError) {
166 bool newCode = [[message firstData] length] == 0;
167 NSString* nextSecret = [self.secretDelegate verificationFailed: newCode];
171 return [self copyResponseForSecret:nextSecret error:error];
173 return [self handleChallengeData:[message firstData] secret:nextSecret error:error];
180 if ([message type] != kVerification) {
181 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected verification!");
185 if (![self.context verifyConfirmation:[message firstData] error:error]) {
186 // Sender thought we had it right, but he can't prove he has it right!
187 KCJoiningErrorCreate(kInternalError, error, @"Got verification but acceptor doesn't have matching secret: %@", self);
188 secnotice("request-session", "Verification failed: %@", self);
193 NSData* payload = [self.session decryptAndVerify:[message secondData] error:error];
194 if (payload == nil) return nil;
196 NSString* accountCode = [NSString decodeFromDER:payload error:error];
197 if (accountCode == nil) return nil;
199 if (![self.secretDelegate processAccountCode:accountCode error:error]) return nil;
202 self->_state = kRequestSecretDone;
204 return [NSData data];
210 // [self.delegate processCircleJoinData:circleData error:error];
212 - (NSData*) processMessage: (NSData*) incomingMessage error: (NSError**) error {
213 NSData* result = nil;
214 KCJoiningMessage* message = [KCJoiningMessage messageWithDER: incomingMessage error: error];
215 if (message == nil) return nil;
217 switch(self->_state) {
219 return [self handleChallenge:message error: error];
222 return [self handleVerification:message error:error];
224 case kRequestSecretDone:
225 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Done, no messages expected.");
232 + (nullable instancetype)sessionWithSecretDelegate: (NSObject<KCJoiningRequestSecretDelegate>*) secretDelegate
234 error: (NSError**) error {
235 return [[KCJoiningRequestSecretSession alloc] initWithSecretDelegate:secretDelegate
240 - (nullable instancetype)initWithSecretDelegate: (NSObject<KCJoiningRequestSecretDelegate>*) secretDelegate
242 error: (NSError**)error {
244 struct ccrng_state * rng = ccrng(&cc_error);
247 CoreCryptoError(cc_error, error, @"RNG fetch failed");
251 return [self initWithSecretDelegate: secretDelegate
257 - (nullable instancetype)initWithSecretDelegate: (NSObject<KCJoiningRequestSecretDelegate>*) secretDelegate
259 rng: (struct ccrng_state *)rng
260 error: (NSError**)error {
264 self->_secretDelegate = secretDelegate;
265 self->_state = kExpectingB;
268 NSString* name = [NSString stringWithFormat: @"%llu", dsid];
270 self->_context = [[KCSRPClientContext alloc] initWithUser: name
271 digestInfo: ccsha256_di()
272 group: ccsrp_gp_rfc5054_3072()
278 - (NSString*) stateString {
279 switch (self.state) {
280 case kExpectingB: return @"→B";
281 case kExpectingHAMK: return @"→HAMK";
282 case kRequestSecretDone: return @"SecretDone";
283 default: return [NSString stringWithFormat:@"%d", self.state];
287 - (NSString *)description {
288 return [NSString stringWithFormat: @"<KCJoiningAcceptSession@%p %lld %@ %@>", self, self.dsid, [self stateString], self.context];
293 @interface KCJoiningRequestCircleSession ()
294 @property (readonly) NSObject<KCJoiningRequestCircleDelegate>* circleDelegate;
295 @property (readonly) KCAESGCMDuplexSession* session;
296 @property (readwrite) KCJoiningRequestCircleSessionState state;
299 @implementation KCJoiningRequestCircleSession
300 - (nullable NSData*) encryptedPeerInfo: (NSError**) error {
301 // Get our peer info and send it along:
302 if (self->_session == nil) {
303 KCJoiningErrorCreate(kInternalError, error, @"Attempt to encrypt with no session");
307 SOSPeerInfoRef us = [self.circleDelegate copyPeerInfoError:error];
308 if (us == NULL) return nil;
309 CFErrorRef cfError = NULL;
310 NSData* piEncoded = (__bridge_transfer NSData*) SOSPeerInfoCopyEncodedData(us, NULL, &cfError);
316 if (piEncoded == nil) {
318 *error = (__bridge_transfer NSError*) cfError;
323 return [self->_session encrypt:piEncoded error:error];
326 - (nullable NSData*) initialMessage: (NSError**) error {
327 NSData* encryptedPi = [self encryptedPeerInfo:error];
328 if (encryptedPi == nil) return nil;
330 self->_state = kExpectingCircleBlob;
332 return [[KCJoiningMessage messageWithType:kPeerInfo
338 - (NSData*) handleCircleBlob: (KCJoiningMessage*) message error: (NSError**) error {
339 if ([message type] != kCircleBlob) {
340 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected CircleBlob!");
344 NSData* circleBlob = [self.session decryptAndVerify:message.firstData error:error];
345 if (circleBlob == nil) return nil;
347 if (![self.circleDelegate processCircleJoinData: circleBlob version:kPiggyV1 error:error])
350 self->_state = kRequestCircleDone;
352 return [NSData data]; // Success, an empty message.
355 - (NSData*) processMessage: (NSData*) incomingMessage error: (NSError**) error {
356 NSData* result = nil;
357 KCJoiningMessage* message = [KCJoiningMessage messageWithDER: incomingMessage error: error];
358 if (message == nil) return nil;
361 case kExpectingCircleBlob:
362 return [self handleCircleBlob:message error:error];
363 case kRequestCircleDone:
364 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Done, no messages expected.");
372 return self.state = kRequestCircleDone;
375 + (instancetype) sessionWithCircleDelegate: (NSObject<KCJoiningRequestCircleDelegate>*) circleDelegate
376 session: (KCAESGCMDuplexSession*) session
377 error: (NSError**) error {
378 return [[KCJoiningRequestCircleSession alloc] initWithCircleDelegate:circleDelegate
383 - (instancetype) initWithCircleDelegate: (NSObject<KCJoiningRequestCircleDelegate>*) circleDelegate
384 session: (KCAESGCMDuplexSession*) session
385 error: (NSError**) error {
388 self->_circleDelegate = circleDelegate;
389 self->_session = session;
390 self.state = kExpectingCircleBlob;