]> git.saurik.com Git - apple/security.git/blob - KeychainCircle/KCJoiningAcceptSession.m
Security-59306.11.20.tar.gz
[apple/security.git] / KeychainCircle / KCJoiningAcceptSession.m
1 //
2 // KCJoiningAcceptSession.m
3 // Security
4 //
5 //
6
7 #import <Foundation/Foundation.h>
8
9 #import <KeychainCircle/KCJoiningSession.h>
10
11 #import <KeychainCircle/KCError.h>
12 #import <KeychainCircle/KCDer.h>
13 #import <KeychainCircle/KCJoiningMessages.h>
14
15 #import <KeychainCircle/NSError+KCCreationHelpers.h>
16 #import "KCInitialMessageData.h"
17
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>
24 #include <notify.h>
25
26 #if OCTAGON
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"
34 #endif
35
36 typedef enum {
37 kExpectingA,
38 kExpectingM,
39 kExpectingPeerInfo,
40 kAcceptDone
41 } KCJoiningAcceptSessionState;
42
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;
54 #if OCTAGON
55 @property (nonatomic, strong) OTJoiningConfiguration* joiningConfiguration;
56 @property (nonatomic, strong) OTControl* otControl;
57 #endif
58 @property (nonatomic, strong) NSMutableDictionary *defaults;
59 @end
60
61 @implementation KCJoiningAcceptSession
62
63 + (nullable instancetype) sessionWithInitialMessage: (NSData*) message
64 secretDelegate: (NSObject<KCJoiningAcceptSecretDelegate>*) secretDelegate
65 circleDelegate: (NSObject<KCJoiningAcceptCircleDelegate>*) circleDelegate
66 dsid: (uint64_t) dsid
67 error: (NSError**) error {
68
69 int cc_error = 0;
70 struct ccrng_state * rng = ccrng(&cc_error);
71
72 if (rng == nil) {
73 CoreCryptoError(cc_error, error, @"RNG fetch failed");
74 return nil;
75 }
76
77 return [[KCJoiningAcceptSession alloc] initWithSecretDelegate: secretDelegate
78 circleDelegate: circleDelegate
79 dsid: dsid
80 rng: rng
81 error: error];
82 }
83
84 - (bool) setupSession: (NSError**) error {
85 NSData* key = [self->_context getKey];
86
87 if (key == nil) {
88 KCJoiningErrorCreate(kInternalError, error, @"No session key available");
89 return nil;
90 }
91
92 self->_session = [KCAESGCMDuplexSession sessionAsReceiver:key context:self.dsid];
93 #if OCTAGON
94 self.session.pairingUUID = self.joiningConfiguration.pairingUUID;
95 #endif
96 self.session.piggybackingVersion = self.piggy_version;
97
98 return self.session != nil;
99 }
100
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 {
106 self = [super init];
107
108 secnotice("accepting", "initWithSecretDelegate");
109
110 NSString* name = [NSString stringWithFormat: @"%llu", dsid];
111
112 self->_context = [[KCSRPServerContext alloc] initWithUser: name
113 password: [secretDelegate secret]
114 digestInfo: ccsha256_di()
115 group: ccsrp_gp_rfc5054_3072()
116 randomSource: rng];
117 self->_secretDelegate = secretDelegate;
118 self->_circleDelegate = circleDelegate;
119 self->_state = kExpectingA;
120 self->_dsid = dsid;
121 self->_piggy_uuid = nil;
122 self->_defaults = [NSMutableDictionary dictionary];
123
124 #if OCTAGON
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"
130 containerName:nil
131 contextID:OTDefaultContext
132 epoch:0
133 isInitiator:false];
134 #else
135 self->_piggy_version = kPiggyV1;
136 #endif
137
138 return self;
139 }
140
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];
148 }
149 }
150
151 - (NSString *)description {
152 return [NSString stringWithFormat: @"<KCJoiningAcceptSession: %lld %@ %@ uuid: %@>", self.dsid, [self stateString], self.context, self.piggy_uuid];
153 }
154
155 - (NSData*) copyChallengeMessage: (NSError**) error {
156 NSData* challenge = [self.context copyChallengeFor: self.startMessage error: error];
157 if (challenge == nil) return nil;
158
159 NSData* srpMessage = [NSData dataWithEncodedSequenceData:self.context.salt data:challenge error:error];
160
161 if (![self setupSession:error]) return nil;
162
163 return srpMessage;
164 }
165
166 #if OCTAGON
167 - (BOOL)shouldAcceptOctagonRequests {
168 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
169 __block BOOL result = NO;
170
171 OTOperationConfiguration* configuration = [[OTOperationConfiguration alloc] init];
172 configuration.discretionaryNetwork = TRUE;
173
174 [self.otControl fetchTrustStatus:self.joiningConfiguration.containerName context:self.joiningConfiguration.self.contextID
175 configuration:configuration
176 reply:^(CliqueStatus status,
177 NSString* peerID,
178 NSNumber * _Nullable numberOfPeersInOctagon,
179 BOOL isExcluded, NSError* _Nullable error)
180 {
181 secerror("octagon haveSelfEgo: status %d: %@ %@ %d: %@", (int)status,
182 peerID, numberOfPeersInOctagon, isExcluded, error);
183
184 if (status == CliqueStatusIn) {
185 result = YES;
186 }
187 dispatch_semaphore_signal(sema);
188 }];
189
190 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 30)) != 0) {
191 secerror("octagon: timed out fetching trust status");
192 return NO;
193 }
194 return result;
195 }
196 #endif
197
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;
203
204 self.startMessage = extractStartFromInitialMessage(initialMessage, &version, &uuid, &octagon, error);
205 if (self.startMessage == NULL) {
206 return nil;
207 }
208 #if OCTAGON
209 if(version == kPiggyV2 && KCJoiningOctagonPiggybackingEnabled()){
210 /* before we go ahead with octagon, let see if we are an octagon peer */
211
212 if (![self shouldAcceptOctagonRequests]) {
213 secerror("octagon refusing octagon acceptor since we don't have a selfEgo");
214 version = kPiggyV1;
215 } else {
216 self.octagon = octagon;
217 }
218 localError = nil;
219 }
220 #endif
221 self.piggy_uuid = uuid;
222 self.piggy_version = (PiggyBackProtocolVersion)version;
223
224 NSData* srpMessage = [self copyChallengeMessage: error];
225 if (srpMessage == nil) {
226 return nil;
227 }
228
229 self->_state = kExpectingM;
230 #if OCTAGON
231 NSString* piggyVersionMessage = [[NSString alloc]initWithData:self.octagon encoding:NSUTF8StringEncoding];
232 __block NSError *captureError = nil;
233
234 if(version == kPiggyV2 && KCJoiningOctagonPiggybackingEnabled() && piggyVersionMessage && [piggyVersionMessage isEqualToString:@"o"]) {
235 __block NSData* next = nil;
236 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
237
238 //fetch epoch
239 [self.otControl rpcEpochWithConfiguration:self.joiningConfiguration reply:^(uint64_t epoch, NSError * _Nullable epochError) {
240 if(epochError){
241 secerror("error retrieving next message! :%@", epochError);
242 captureError = epochError;
243 }else{
244 OTPairingMessage* responseMessage = [[OTPairingMessage alloc] init];
245 responseMessage.epoch = [[OTSponsorToApplicantRound1M2 alloc] init];
246 responseMessage.epoch.epoch = epoch;
247 next = responseMessage.data;
248 }
249 dispatch_semaphore_signal(sema);
250 }];
251
252 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 30)) != 0) {
253 secerror("octagon: timed out fetching epoch");
254 return nil;
255 }
256 if(error && captureError){
257 *error = captureError;
258 }
259 return [[KCJoiningMessage messageWithType:kChallenge
260 data:srpMessage
261 payload:next
262 error:error] der];
263 }
264 #endif
265 return [[KCJoiningMessage messageWithType:kChallenge
266 data:srpMessage
267 error:error] der];
268 }
269
270 - (NSData*) processResponse: (KCJoiningMessage*) message error:(NSError**) error {
271 if ([message type] != kResponse) {
272 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected response!");
273 return nil;
274 }
275
276 // We handle failure, don't capture the error.
277 NSData* confirmation = [self.context copyConfirmationFor:message.firstData error:NULL];
278 if (!confirmation) {
279 // Find out what kind of error we should send.
280 NSData* errorData = nil;
281
282 KCRetryOrNot status = [self.secretDelegate verificationFailed: error];
283 secerror("processResponse: handle error: %d", (int)status);
284
285 switch (status) {
286 case kKCRetryError:
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);
289 return nil;
290 case kKCRetryWithSameChallenge:
291 errorData = [NSData data];
292 break;
293 case kKCRetryWithNewChallenge:
294 if ([self.context resetWithPassword:[self.secretDelegate secret] error:error]) {
295 errorData = [self copyChallengeMessage: error];
296 }
297 break;
298 }
299 if (errorData == nil) return nil;
300
301 return [[KCJoiningMessage messageWithType:kError
302 data:errorData
303 error:error] der];
304 }
305
306 NSData* encoded = [NSData dataWithEncodedString:[self.secretDelegate accountCode] error:error];
307 if (encoded == nil)
308 return nil;
309
310 NSData* encrypted = [self.session encrypt:encoded error:error];
311 if (encrypted == nil) return nil;
312
313 self->_state = kExpectingPeerInfo;
314
315 return [[KCJoiningMessage messageWithType:kVerification
316 data:confirmation
317 payload:encrypted
318 error:error] der];
319 }
320
321 - (NSData*) processSOSApplication: (NSData*) message error:(NSError**) error
322 {
323 NSData* decryptedPayload = [self.session decryptAndVerify:message error:error];
324 if (decryptedPayload == nil) return nil;
325
326 CFErrorRef cfError = NULL;
327 SOSPeerInfoRef ref = SOSPeerInfoCreateFromData(NULL, &cfError, (__bridge CFDataRef) decryptedPayload);
328 if (ref == NULL) {
329 if (error) *error = (__bridge_transfer NSError*) cfError;
330 cfError = NULL;
331 return nil;
332 }
333
334 NSData* joinData = [self.circleDelegate circleJoinDataFor:ref error:error];
335 if(ref) {
336 CFRelease(ref);
337 ref = NULL;
338 }
339
340 if (joinData == nil) return nil;
341
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];
347 if(localV1Error){
348 secnotice("piggy", "PB v1 threw an error: %@", localV1Error);
349 }
350
351 NSMutableData* growPacket = [[NSMutableData alloc] initWithData:joinData];
352 [growPacket appendData:initialSyncData];
353 joinData = growPacket;
354
355 }
356
357 NSData* encryptedOutgoing = [self.session encrypt:joinData error:error];
358 if (encryptedOutgoing == nil) return nil;
359 return encryptedOutgoing;
360 }
361
362 #if OCTAGON
363 - (OTPairingMessage *)createPairingMessageFromJoiningMessage:(KCJoiningMessage *)message error:(NSError**) error
364 {
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];
369 } else {
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");
374 return nil;
375 }
376
377 if(!initialMessage.hasPrepareMessage) {
378 secerror("InitialMessageData does not contain prepare message");
379 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected prepare message inside InitialMessageData");
380 return nil;
381 }
382
383 return [[OTPairingMessage alloc] initWithData:initialMessage.prepareMessage];
384 }
385 }
386 #endif
387
388 - (NSData*) processApplication: (KCJoiningMessage*) message error:(NSError**) error {
389 if ([message type] != kPeerInfo) {
390 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected peerInfo!");
391 return nil;
392 }
393 #if OCTAGON
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);
398
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");
403 return nil;
404 }
405
406 if(!pairingMessage.hasPrepare) {
407 secerror("octagon, message does not contain prepare message");
408 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Expected prepare message!");
409 return nil;
410 }
411 OTApplicantToSponsorRound2M1 *prepareMessage = pairingMessage.prepare;
412
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,
420 NSData *voucherSig,
421 NSError *err) {
422 if(err){
423 secerror("error producing octagon voucher: %@", err);
424 localError = err;
425 }else{
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;
431 }
432 dispatch_semaphore_signal(sema);
433 }];
434
435 if(dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 30)) != 0) {
436 secerror("octagon: timed out producing octagon voucher");
437 return nil;
438 }
439 if (next == NULL) {
440 if(error && localError){
441 *error = localError;
442 }
443 return nil;
444 }
445
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];
451 } else {
452 secnotice("joining", "no platform support processSOSApplication, peer sent data: %s",
453 message.secondData ? "yes" : "no");
454 }
455
456 self->_state = kAcceptDone;
457
458 return [[KCJoiningMessage messageWithType:kCircleBlob
459 data:next
460 payload:encryptedOutgoing
461 error:error] der];
462 }
463 #endif
464 NSData* encryptedOutgoing = [self processSOSApplication: message.firstData error:error];
465
466 self->_state = kAcceptDone;
467
468 secnotice("joining", "posting kSOSCCCircleOctagonKeysChangedNotification");
469 notify_post(kSOSCCCircleOctagonKeysChangedNotification);
470
471 return [[KCJoiningMessage messageWithType:kCircleBlob
472 data:encryptedOutgoing
473 error:error] der];
474 }
475
476
477 - (nullable NSData*) processMessage: (NSData*) incomingMessage error: (NSError**) error {
478 NSData* result = nil;
479
480 secnotice("acceptor", "processMessages: %@", [self description]);
481
482 KCJoiningMessage *message = (self.state != kExpectingA) ? [KCJoiningMessage messageWithDER:incomingMessage error:error] : nil;
483
484 switch(self.state) {
485 case kExpectingA:
486 return [self processInitialMessage:incomingMessage error: error];
487 case kExpectingM:
488 if (message == nil) return nil;
489 return [self processResponse:message error: error];
490 break;
491 case kExpectingPeerInfo:
492 if (message == nil) return nil;
493 return [self processApplication:message error: error];
494 break;
495 case kAcceptDone:
496 KCJoiningErrorCreate(kUnexpectedMessage, error, @"Unexpected message while done");
497 break;
498 }
499 return result;
500 }
501
502 - (bool) isDone {
503 return self.state == kAcceptDone;
504 }
505
506 /* for test*/
507 #if OCTAGON
508 - (void)setControlObject:(OTControl *)control
509 {
510 self.otControl = control;
511 }
512
513 - (void)setConfiguration:(OTJoiningConfiguration *)config
514 {
515 self.joiningConfiguration = config;
516 }
517 #endif
518
519 @end