5 #import "PairingChannel.h"
6 #import <Foundation/NSXPCConnection_Private.h>
7 #import <CoreFoundation/CoreFoundation.h>
8 #import <CoreFoundation/CFPropertyList_Private.h>
9 #import <Security/Security.h>
10 #import <Security/SecItemPriv.h>
11 #import <Security/SecureObjectSync/SOSTypes.h>
12 #import <utilities/debugging.h>
13 #import <utilities/SecCFWrappers.h>
14 #import <ipc/securityd_client.h>
15 #import "keychain/ot/OTManager.h"
16 #import "keychain/ot/OctagonControlServer.h"
17 #import "keychain/ot/OTControl.h"
18 #import "keychain/ot/OctagonControlServer.h"
19 #import "keychain/ot/OTJoiningConfiguration.h"
20 #import "keychain/ot/proto/generated_source/OTPairingMessage.h"
21 #import "keychain/ot/proto/generated_source/OTSOSMessage.h"
22 #import "keychain/ot/proto/generated_source/OTApplicantToSponsorRound2M1.h"
23 #import "keychain/ot/proto/generated_source/OTSponsorToApplicantRound2M2.h"
24 #import "keychain/ot/proto/generated_source/OTSponsorToApplicantRound1M2.h"
25 #import "keychain/ot/proto/generated_source/OTPairingMessage.h"
28 #import <compression.h>
29 #if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
30 #import <MobileGestalt.h>
33 #import "utilities/SecADWrapper.h"
35 KCPairingIntent_Type KCPairingIntent_Type_None = @"none";
36 KCPairingIntent_Type KCPairingIntent_Type_SilentRepair = @"repair";
37 KCPairingIntent_Type KCPairingIntent_Type_UserDriven = @"userdriven";
39 typedef void(^KCPairingInternalCompletion)(BOOL complete, NSDictionary *outdict, NSError *error);
40 typedef void(^KCNextState)(NSDictionary *indict, KCPairingInternalCompletion complete);
42 NSString *kKCPairingChannelErrorDomain = @"com.apple.security.kcparingchannel";
44 const char* pairingScope = "ot-pairing";
46 typedef void(^OTPairingInternalCompletion)(BOOL complete, NSData * _Nullable outData, NSError * _Nullable error);
47 typedef void(^OTNextState)(NSData *inData, OTPairingInternalCompletion complete);
49 @implementation KCPairingChannelContext
51 + (BOOL)supportsSecureCoding {
55 - (BOOL)isEqual:(id)object
57 KCPairingChannelContext *other = (KCPairingChannelContext *)object;
59 return [other isMemberOfClass:[self class]]
60 && ((!self->_model && !other->_model) || [self->_model isEqual:other->_model])
61 && ((!self->_modelVersion && !other->_modelVersion) || [self->_modelVersion isEqual:other->_modelVersion])
62 && ((!self->_modelClass && !other->_modelClass) || [self->_modelClass isEqual:other->_modelClass])
63 && ((!self->_osVersion && !other->_osVersion) || [self->_osVersion isEqual:other->_osVersion])
64 && ((!self->_uniqueDeviceID && !other->_uniqueDeviceID) || [self->_uniqueDeviceID isEqual:other->_uniqueDeviceID])
65 && ((!self->_uniqueClientID && !other->_uniqueClientID) || [self->_uniqueClientID isEqual:other->_uniqueClientID])
66 && ((!self->_intent && !other->_intent) || [self->_intent isEqual:other->_intent])
70 - (void)encodeWithCoder:(NSCoder *)coder {
71 [coder encodeObject:_model forKey:@"model"];
72 [coder encodeObject:_modelVersion forKey:@"modelVersion"];
73 [coder encodeObject:_modelClass forKey:@"modelClass"];
74 [coder encodeObject:_osVersion forKey:@"osVersion"];
75 [coder encodeObject:_uniqueDeviceID forKey:@"uniqueDeviceID"];
76 [coder encodeObject:_uniqueClientID forKey:@"uniqueClientID"];
77 [coder encodeObject:_intent forKey:@"intent"];
80 - (nullable instancetype)initWithCoder:(NSCoder *)decoder
84 _model = [decoder decodeObjectOfClass:[NSString class] forKey:@"model"];
85 _modelVersion = [decoder decodeObjectOfClass:[NSString class] forKey:@"modelVersion"];
86 _modelClass = [decoder decodeObjectOfClass:[NSString class] forKey:@"modelClass"];
87 _osVersion = [decoder decodeObjectOfClass:[NSString class] forKey:@"osVersion"];
88 _uniqueDeviceID = [decoder decodeObjectOfClass:[NSString class] forKey:@"uniqueDeviceID"];
89 _uniqueClientID = [decoder decodeObjectOfClass:[NSString class] forKey:@"uniqueClientID"];
90 _intent = [decoder decodeObjectOfClass:[NSString class] forKey:@"intent"];
92 /* validate intent if we have one */
93 if (_intent != NULL &&
94 !([_intent isEqualToString:KCPairingIntent_Type_None] ||
95 [_intent isEqualToString:KCPairingIntent_Type_SilentRepair] ||
96 [_intent isEqualToString:KCPairingIntent_Type_UserDriven]))
107 @interface KCPairingChannel ()
108 @property (assign) KCPairingChannelContext *peerVersionContext;
109 @property (assign) bool initiator;
110 @property (assign) unsigned counter;
111 @property (assign) bool acceptorWillSendInitialSyncCredentials;
112 @property (strong) NSXPCConnection *connection;
113 @property (strong) OTControl *otControl;
114 @property (strong) NSString* contextID;
115 @property (strong) OTNextState nextOctagonState;
116 @property (strong) KCNextState nextState;
117 @property (nonatomic, strong) OTJoiningConfiguration* joiningConfiguration;
118 @property (nonatomic) bool testFailSOS;
119 @property (nonatomic) bool testFailOctagon;
121 @property (assign) bool sessionSupportsSOS;
122 @property (assign) bool sessionSupportsOctagon;
126 @implementation KCPairingChannel
128 + (instancetype)pairingChannelInitiator:(KCPairingChannelContext *)peerVersionContext
130 return [[KCPairingChannel alloc] initAsInitiator:true version:peerVersionContext];
133 + (instancetype)pairingChannelAcceptor:(KCPairingChannelContext *)peerVersionContext
135 return [[KCPairingChannel alloc] initAsInitiator:false version:peerVersionContext];
138 - (instancetype)initAsInitiator:(bool)initiator version:(KCPairingChannelContext *)peerVersionContext
140 if (![KCPairingChannel isSupportedPlatform]) {
141 secerror("platform not supported for pairing");
145 if (self = [super init]) {
146 __weak typeof(self) weakSelf = self;
147 _initiator = initiator;
148 _peerVersionContext = peerVersionContext;
150 _nextState = ^(NSDictionary *nsdata, KCPairingInternalCompletion kscomplete){
151 [weakSelf initiatorFirstPacket:nsdata complete:kscomplete];
154 _nextState = ^(NSDictionary *nsdata, KCPairingInternalCompletion kscomplete){
155 [weakSelf acceptorFirstPacket:nsdata complete:kscomplete];
158 _needInitialSync = true;
159 _testFailSOS = false;
160 _contextID = OTDefaultContext;
162 /* only apply to acceptor right now */
163 _sessionSupportsSOS = OctagonPlatformSupportsSOS();
164 _sessionSupportsOctagon = OctagonIsEnabled();
165 NSError *localError = nil;
166 _otControl = [OTControl controlObject:true error:&localError];
168 secerror("could not stand up otcontrol connection");
170 _joiningConfiguration = [[OTJoiningConfiguration alloc]initWithProtocolType:OTProtocolPairing
171 uniqueDeviceID:peerVersionContext.uniqueDeviceID
172 uniqueClientID:peerVersionContext.uniqueClientID
174 contextID:OTDefaultContext
176 isInitiator:initiator];
181 + (bool)isSupportedPlatform
186 - (void)oneStepTooMany:(NSDictionary * __unused)indata complete:(KCPairingInternalCompletion)complete
188 secerror("pairingchannel: one step too many");
189 complete(false, NULL, [NSError errorWithDomain:kKCPairingChannelErrorDomain code:KCPairingErrorTooManySteps userInfo:NULL]);
192 - (void)setNextStateError:(NSError *)error complete:(KCPairingInternalCompletion)complete
194 __weak typeof(self) weakSelf = self;
195 self.nextState = ^(NSDictionary *nsdata, KCPairingInternalCompletion kscomplete){
196 [weakSelf oneStepTooMany:nsdata complete:kscomplete];
200 secerror("pairingchannel: failed pairing with: %@", error);
201 complete(false, NULL, error);
205 //MARK: - Compression
207 const compression_algorithm pairingCompression = COMPRESSION_LZFSE;
208 #define EXTRA_SIZE 100
210 - (NSData *)compressData:(NSData *)data
212 NSMutableData *scratch = [NSMutableData dataWithLength:compression_encode_scratch_buffer_size(pairingCompression)];
214 NSUInteger outLength = [data length];
215 if (outLength > NSUIntegerMax - EXTRA_SIZE)
217 outLength += EXTRA_SIZE;
219 NSMutableData *o = [NSMutableData dataWithLength:outLength];
220 size_t result = compression_encode_buffer([o mutableBytes], [o length], [data bytes], [data length], [scratch mutableBytes], pairingCompression);
224 [o setLength:result];
229 - (NSData *)decompressData:(NSData *)data
231 NSMutableData *scratch = [NSMutableData dataWithLength:compression_decode_scratch_buffer_size(pairingCompression)];
233 size_t outLength = [data length];
235 NSMutableData *o = NULL;
239 if (__builtin_umull_overflow(outLength, 2, &size))
242 o = [NSMutableData dataWithLength:outLength];
244 result = compression_decode_buffer([o mutableBytes], outLength, [data bytes], [data length], [scratch mutableBytes], pairingCompression);
247 } while(result == outLength);
249 [o setLength:result];
258 - (void) attemptSosUpgrade
260 [self.otControl attemptSosUpgrade:nil context:self.contextID reply:^(NSError *error) {
262 secerror("pairing: failed to upgrade initiator into Octagon: %@", error);
267 - (void)initiatorFirstPacket:(NSDictionary * __unused)indata complete:(KCPairingInternalCompletion)complete
269 secnotice("pairing", "initiator packet 1");
271 if (OctagonPlatformSupportsSOS() && ![self ensureControlChannel]) {
272 [self setNextStateError:[NSError errorWithDomain:kKCPairingChannelErrorDomain code:KCPairingErrorNoControlChannel userInfo:NULL] complete:complete];
276 if(OctagonIsEnabled() && self.sessionSupportsOctagon && !self.testFailOctagon) {
277 __weak typeof(self) weakSelf = self;
278 self.nextState = ^(NSDictionary *nsdata, KCPairingInternalCompletion kscomplete){
279 [weakSelf initiatorSecondPacket:nsdata complete:kscomplete];
281 complete(false, @{ @"d" : @YES, @"o" : @{@"v" : @"O"} }, NULL);
282 } else if (OctagonIsEnabled() && self.testFailOctagon) {
283 complete(true, nil, NULL);
286 __weak typeof(self) weakSelf = self;
287 self.nextState = ^(NSDictionary *nsdata, KCPairingInternalCompletion kscomplete){
288 [weakSelf initiatorSecondPacket:nsdata complete:kscomplete];
290 complete(false, @{ @"d" : @YES }, NULL);
294 - (void)initiatorSecondPacket:(NSDictionary *)indata complete:(KCPairingInternalCompletion)complete
296 secnotice("pairing", "initiator packet 2");
298 NSData *octagonData = indata[@"o"];
300 if(octagonData == nil) {
301 secnotice("pairing", "acceptor didn't send a octagon packet, so skipping all octagon flows");
302 self.sessionSupportsOctagon = false;
305 NSData *credential = indata[@"c"];
306 if (![credential isKindOfClass:[NSData class]]) {
307 if(!OctagonIsEnabled() && OctagonPlatformSupportsSOS()) {
308 secnotice("pairing", "no credential");
309 [self setNextStateError:[NSError errorWithDomain:kKCPairingChannelErrorDomain code:KCPairingErrorAccountCredentialMissing userInfo:NULL] complete:complete];
314 if (OctagonPlatformSupportsSOS() && indata[@"d"]) {
315 secnotice("pairing", "acceptor will send send initial credentials");
316 self.acceptorWillSendInitialSyncCredentials = true;
318 if(OctagonPlatformSupportsSOS()) {
319 [[self.connection remoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) {
320 complete(true, NULL, error);
321 }] stashAccountCredential:credential complete:^(bool success, NSError *error) {
322 [self setNextStateError:NULL complete:NULL];
323 if (!success || self.testFailSOS) {
324 secnotice("pairing", "failed stash credentials: %@", error);
325 if(!OctagonIsEnabled() || !self.sessionSupportsOctagon){
326 complete(true, NULL, error);
329 [self initiatorCompleteSecondPacketOctagon:indata application:nil complete:complete];
332 [self initiatorCompleteSecondPacketWithSOS:indata complete:complete];
335 } else if(OctagonIsEnabled() && self.sessionSupportsOctagon) {
336 [self initiatorCompleteSecondPacketOctagon:indata application:nil complete:complete];
342 - (void)initiatorCompleteSecondPacketWithSOS:(NSDictionary *)indata complete:(KCPairingInternalCompletion)complete
344 secnotice("pairing", "initiator complete second packet 2");
346 __weak typeof(self) weakSelf = self;
348 [self setNextStateError:NULL complete:NULL];
350 [[self.connection remoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) {
351 complete(true, NULL, error);
352 }] myPeerInfo:^(NSData *application, NSError *error) {
353 if (application && !self.testFailSOS) {
354 if(OctagonIsEnabled() && self.sessionSupportsOctagon) {
355 [self initiatorCompleteSecondPacketOctagon:indata application:application complete:complete];
357 complete(false, @{ @"p" : application }, error);
358 weakSelf.nextState = ^(NSDictionary *nsdata, KCPairingInternalCompletion kscomplete){
359 [weakSelf initiatorThirdPacket:nsdata complete:kscomplete];
363 if(OctagonIsEnabled() && self.sessionSupportsOctagon){
364 [self initiatorCompleteSecondPacketOctagon:indata application:application complete:complete];
366 secnotice("pairing", "failed getting application: %@", error);
367 complete(true, @{}, error);
373 - (void)initiatorCompleteSecondPacketOctagon:(NSDictionary*)indata application:(NSData*)application complete:(KCPairingInternalCompletion)complete
375 secnotice("pairing", "initiator complete second packet 2 with octagon");
377 __weak typeof(self) weakSelf = self;
378 NSData *octagonData = indata[@"o"];
380 if(![octagonData isKindOfClass:[NSData class]]) {
381 secnotice(pairingScope, "initiatorCompleteSecondPacketOctagon octagonData missing or wrong class");
382 [self setNextStateError:[NSError errorWithDomain:kKCPairingChannelErrorDomain code:KCPairingErrorOctagonMessageMissing userInfo:NULL] complete:complete];
386 //handle epoch and create identity message
387 [self.otControl rpcPrepareIdentityAsApplicantWithConfiguration:self.joiningConfiguration
388 reply:^(NSString *peerID,
389 NSData *permanentInfo,
390 NSData *permanentInfoSig,
392 NSData *stableInfoSig,
394 if (error || self.testFailOctagon) {
395 secerror("ot-pairing: failed to create %d message: %@", self.counter, error);
396 complete(true, nil, error);
399 OTPairingMessage *octagonMessage = [[OTPairingMessage alloc]init];
400 OTApplicantToSponsorRound2M1 *prepare = [[OTApplicantToSponsorRound2M1 alloc] init];
401 prepare.peerID = peerID;
402 prepare.permanentInfo = permanentInfo;
403 prepare.permanentInfoSig = permanentInfoSig;
404 prepare.stableInfo = stableInfo;
405 prepare.stableInfoSig = stableInfoSig;
406 octagonMessage.prepare = prepare;
408 secnotice(pairingScope, "initiatorCompleteSecondPacketOctagon returning octagon and sos data");
409 complete(false, @{ @"p" : application, @"o" : octagonMessage.data }, nil);
411 secnotice(pairingScope, "initiatorCompleteSecondPacketOctagon returning octagon data");
412 complete(false, @{ @"o" : octagonMessage.data }, nil);
414 weakSelf.nextState = ^(NSDictionary *nsdata, KCPairingInternalCompletion kscomplete){
415 [weakSelf initiatorThirdPacket:nsdata complete:kscomplete];
421 - (void)initiatorThirdPacket:(NSDictionary *)indata complete:(KCPairingInternalCompletion)complete
423 __weak typeof(self) weakSelf = self;
424 secnotice("pairing", "initiator packet 3");
426 [self setNextStateError:NULL complete:NULL];
428 NSData *circleBlob = indata[@"b"];
430 if (circleBlob == NULL) {
431 if(!OctagonIsEnabled() && OctagonPlatformSupportsSOS()) {
432 secnotice("pairing", "no sos circle");
433 complete(true, NULL, NULL);
436 } else if(OctagonPlatformSupportsSOS()) {
437 if(![circleBlob isKindOfClass:[NSData class]]) {
438 complete(true, NULL, [NSError errorWithDomain:kKCPairingChannelErrorDomain code:KCPairingErrorTypeConfusion userInfo:NULL]);
442 [[self.connection remoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) {
443 complete(true, NULL, error);
444 }] joinCircleWithBlob:circleBlob version:kPiggyV1 complete:^(bool success, NSError *error){
445 if(error || self.testFailSOS) {
446 if(OctagonIsEnabled() && self.sessionSupportsOctagon) {
447 secnotice("pairing", "failed to join circle with blob, continuing to handle octagon protocol");
449 secnotice("pairing", "failed to join circle with blob");
450 complete(true, NULL, NULL);
453 if(OctagonIsEnabled() && self.sessionSupportsOctagon) {
454 secnotice("pairing","initiator circle join complete");
456 //kick off SOS ugprade
457 if(OctagonIsEnabled() && !self.sessionSupportsOctagon) {
458 [self attemptSosUpgrade];
460 typeof(self) strongSelf = weakSelf;
461 secnotice("pairing", "initiator circle join complete, more data: %s: %@",
462 strongSelf->_acceptorWillSendInitialSyncCredentials ? "yes" : "no", error);
464 if (strongSelf->_acceptorWillSendInitialSyncCredentials) {
465 strongSelf.nextState = ^(NSDictionary *nsdata, KCPairingInternalCompletion kscomplete){
466 [weakSelf initiatorFourthPacket:nsdata complete:kscomplete];
469 complete(false, @{}, NULL);
471 complete(true, NULL, NULL);
477 if(OctagonIsEnabled() && self.sessionSupportsOctagon){
478 NSData *octagonData = indata[@"o"];
479 if(![octagonData isKindOfClass:[NSData class]]) {
480 secnotice(pairingScope, "initiatorThirdPacket octagonData missing or wrong class");
481 [self setNextStateError:[NSError errorWithDomain:kKCPairingChannelErrorDomain code:KCPairingErrorOctagonMessageMissing userInfo:NULL] complete:complete];
484 OTPairingMessage *pairingMessage = [[OTPairingMessage alloc] initWithData:octagonData];
485 if(!pairingMessage.hasVoucher){
486 secnotice(pairingScope, "initiatorThirdPacket pairingMessage has no voucher");
487 [self setNextStateError:[NSError errorWithDomain:kKCPairingChannelErrorDomain code:KCPairingErrorOctagonMessageMissing userInfo:NULL] complete:complete];
490 OTSponsorToApplicantRound2M2 *voucher = pairingMessage.voucher;
492 //handle voucher and join octagon
493 [self.otControl rpcJoinWithConfiguration:self.joiningConfiguration vouchData:voucher.voucher vouchSig:voucher.voucherSignature preapprovedKeys:voucher.preapprovedKeys reply:^(NSError *error) {
494 if (error || self.testFailOctagon) {
495 secerror("ot-pairing: failed to create %d message: %@", self.counter, error);
496 complete(true, NULL, error);
499 secnotice(pairingScope, "initiatorThirdPacket successfully joined Octagon");
500 typeof(self) strongSelf = weakSelf;
501 if(OctagonPlatformSupportsSOS() && strongSelf->_acceptorWillSendInitialSyncCredentials == true) {
502 strongSelf.nextState = ^(NSDictionary *nsdata, KCPairingInternalCompletion kscomplete){
503 [weakSelf initiatorFourthPacket:nsdata complete:kscomplete];
505 complete(false, @{}, nil);
508 complete(true, nil, nil);
516 - (void)initiatorFourthPacket:(NSDictionary *)indata complete:(KCPairingInternalCompletion)complete
518 secnotice("pairing", "initiator packet 4");
520 [self setNextStateError:NULL complete:NULL];
522 NSArray *items = indata[@"d"];
523 if (![items isKindOfClass:[NSArray class]]) {
524 secnotice("pairing", "initiator no items to import");
525 complete(true, NULL, NULL);
529 secnotice("pairing", "importing %lu items", (unsigned long)[items count]);
531 [[self.connection remoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) {
532 complete(true, NULL, error);
533 }] importInitialSyncCredentials:items complete:^(bool success, NSError *error) {
534 secnotice("pairing", "initiator importInitialSyncCredentials: %s: %@", success ? "yes" : "no", error);
536 self->_needInitialSync = false;
537 complete(true, nil, nil);
545 - (void)acceptorFirstPacket:(NSDictionary *)indata complete:(KCPairingInternalCompletion)complete
547 __weak typeof(self) weakSelf = self;
549 secnotice("pairing", "acceptor packet 1");
550 [self setNextStateError:NULL complete:NULL];
552 if (self.sessionSupportsSOS && ![self ensureControlChannel]) {
553 secnotice("pairing", "unable to establish a channel to sos control");
554 [self setNextStateError:[NSError errorWithDomain:kKCPairingChannelErrorDomain code:KCPairingErrorNoControlChannel userInfo:NULL] complete:complete];
558 if (self.sessionSupportsSOS && indata[@"d"]) {
559 secnotice("pairing", "acceptor initialSyncCredentials requested");
560 self.acceptorWillSendInitialSyncCredentials = true;
563 if (indata[@"o"] == nil) {
564 secnotice("pairing", "initiator didn't send a octagon packet, so skipping all octagon flows");
565 self.sessionSupportsOctagon = false;
567 // XXX Before we go here we should check if we are trusted or not, if we are not, there is no point proposing octagon
569 NSMutableDictionary *reply = [NSMutableDictionary dictionary];
571 if(self.sessionSupportsSOS) {
572 [[self.connection remoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) {
573 complete(true, NULL, error);
574 }] validatedStashedAccountCredential:^(NSData *credential, NSError *error) {
575 secnotice("pairing", "acceptor validatedStashedAccountCredential: %@ (%@)", credential != NULL ? @"yes" : @"no", error);
577 reply[@"c"] = credential;
579 if (self.acceptorWillSendInitialSyncCredentials) {
582 if(self.sessionSupportsOctagon) {
583 [self acceptorFirstOctagonPacket:indata reply:reply complete:complete];
585 self.nextState = ^(NSDictionary *nsdata, KCPairingInternalCompletion kscomplete){
586 [weakSelf acceptorSecondPacket:nsdata complete:kscomplete];
588 secnotice("pairing", "acceptor reply to packet 1");
589 complete(false, reply, NULL);
592 else if ((!credential && !self.sessionSupportsOctagon) || self.testFailSOS) {
593 secnotice("pairing", "acceptor doesn't have a stashed credential: %@", error);
594 NSError *noStashCredentail = [NSError errorWithDomain:kKCPairingChannelErrorDomain code:KCPairingErrorNoStashedCredential userInfo:NULL];
595 [self setNextStateError:noStashCredentail complete:complete];
598 else if(self.sessionSupportsOctagon) {
599 [self acceptorFirstOctagonPacket:indata reply:reply complete:complete];
602 } else if(self.sessionSupportsOctagon){
603 [self acceptorFirstOctagonPacket:indata reply:reply complete:complete];
605 secnotice("pairing", "acceptor neither of octagon nor SOS");
606 NSError *notSupported = [NSError errorWithDomain:kKCPairingChannelErrorDomain code:KCPairingErrorNoTrustAvailable userInfo:NULL];
607 [self setNextStateError:notSupported complete:complete];
610 - (void)acceptorFirstOctagonPacket:(NSDictionary *)indata reply:(NSMutableDictionary*)reply complete:(KCPairingInternalCompletion)complete
612 __weak typeof(self) weakSelf = self;
613 NSDictionary *octagonData = indata[@"o"];
615 if(![octagonData isKindOfClass:[NSDictionary class]]) {
616 secnotice(pairingScope, "acceptorFirstOctagonPacket octagon data missing");
617 [self setNextStateError:[NSError errorWithDomain:kKCPairingChannelErrorDomain code:KCPairingErrorOctagonMessageMissing userInfo:NULL] complete:complete];
621 NSDictionary *unpackedMessage = octagonData;
623 if(![unpackedMessage[@"v"] isEqualToString:@"O"]){
624 secnotice(pairingScope, "acceptorFirstOctagonPacket 'v' contents wrong");
625 [self setNextStateError:[NSError errorWithDomain:kKCPairingChannelErrorDomain code:KCPairingErrorOctagonMessageMissing userInfo:NULL] complete:complete];
629 //handle epoch request and fetch epoch
630 [self.otControl rpcEpochWithConfiguration:self.joiningConfiguration reply:^(uint64_t epoch, NSError * _Nullable error) {
631 secnotice("pairing", "acceptor rpcEpochWithConfiguration: %ld (%@)", (long)epoch, error);
632 if(error || self.testFailOctagon){
633 secerror("error acceptor handling packet %d", self.counter);
634 complete(true, nil, error);
636 secnotice(pairingScope, "acceptor handled packet %d", self.counter);
637 self.nextState = ^(NSDictionary *nsdata, KCPairingInternalCompletion kscomplete){
638 [weakSelf acceptorSecondPacket:nsdata complete:kscomplete];
640 OTPairingMessage *response = [[OTPairingMessage alloc] init];
641 response.epoch = [[OTSponsorToApplicantRound1M2 alloc] init];
642 response.epoch.epoch = epoch;
643 reply[@"o"] = response.data;
645 secnotice("pairing", "acceptor reply to packet 1");
646 complete(false, reply, error);
651 - (void)acceptorSecondPacket:(NSDictionary *)indata complete:(KCPairingInternalCompletion)complete
653 __weak typeof(self) weakSelf = self;
655 [self setNextStateError:NULL complete:NULL];
657 secnotice("pairing", "acceptor packet 2");
658 __block NSMutableDictionary *reply = [NSMutableDictionary dictionary];
660 NSData *peerJoinBlob = indata[@"p"];
662 if(self.sessionSupportsSOS && [peerJoinBlob isKindOfClass:[NSData class]]) {
663 [[self.connection remoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) {
664 complete(true, NULL, error);
665 }] circleJoiningBlob:peerJoinBlob complete:^(NSData *blob, NSError *error){
668 secnotice("pairing", "acceptor pairing complete (will send: %s): %@",
669 self.acceptorWillSendInitialSyncCredentials ? "YES" : "NO",
674 if(self.sessionSupportsOctagon) {
675 [self acceptorSecondOctagonPacket:indata reply:reply complete:complete];
677 secnotice("pairing", "posting kSOSCCCircleOctagonKeysChangedNotification");
678 notify_post(kSOSCCCircleOctagonKeysChangedNotification);
679 if (self.acceptorWillSendInitialSyncCredentials) {
680 self.nextState = ^(NSDictionary *nsdata, KCPairingInternalCompletion kscomplete){
681 [weakSelf acceptorThirdPacket:nsdata complete:kscomplete];
684 complete(false, reply, NULL);
686 complete(true, reply, NULL);
688 secnotice("pairing", "acceptor reply to packet 2");
691 } else if(self.sessionSupportsOctagon){
692 [self acceptorSecondOctagonPacket:indata reply:reply complete:complete];
696 - (void)acceptorSecondOctagonPacket:(NSDictionary*)indata reply:(NSMutableDictionary*)reply complete:(KCPairingInternalCompletion)complete
698 __weak typeof(self) weakSelf = self;
699 NSData *octagonData = indata[@"o"];
701 if(![octagonData isKindOfClass:[NSData class]]) {
702 secnotice(pairingScope, "acceptorSecondOctagonPacket octagon data missing");
703 [self setNextStateError:[NSError errorWithDomain:kKCPairingChannelErrorDomain code:KCPairingErrorOctagonMessageMissing userInfo:NULL] complete:complete];
707 OTPairingMessage *pairingMessage = [[OTPairingMessage alloc] initWithData:octagonData];
708 if(!pairingMessage.hasPrepare){
709 secerror("ot-pairing: acceptorSecondOctagonPacket: no octagon message");
710 [self setNextStateError:[NSError errorWithDomain:kKCPairingChannelErrorDomain code:KCPairingErrorOctagonMessageMissing userInfo:NULL] complete:complete];
713 OTApplicantToSponsorRound2M1 *prepare = pairingMessage.prepare;
715 //handle identity and fetch voucher
716 [self.otControl rpcVoucherWithConfiguration:self.joiningConfiguration
717 peerID:prepare.peerID
718 permanentInfo:prepare.permanentInfo
719 permanentInfoSig:prepare.permanentInfoSig
720 stableInfo:prepare.stableInfo
721 stableInfoSig:prepare.stableInfoSig
722 reply:^(NSData *voucher,
725 if(error || self.testFailOctagon){
726 secerror("error acceptor handling octagon packet %d", self.counter);
727 complete(true, nil, error);
730 bool finished = true;
732 secnotice(pairingScope, "acceptor handled octagon packet %d", self.counter);
733 if (OctagonPlatformSupportsSOS() && self.acceptorWillSendInitialSyncCredentials) {
734 self.nextState = ^(NSDictionary *nsdata, KCPairingInternalCompletion kscomplete){
735 [weakSelf acceptorThirdPacket:nsdata complete:kscomplete];
739 OTPairingMessage *response = [[OTPairingMessage alloc] init];
740 response.voucher = [[OTSponsorToApplicantRound2M2 alloc] init];
741 response.voucher.voucher = voucher;
742 response.voucher.voucherSignature = voucherSig;
743 reply[@"o"] = response.data;
745 secnotice("pairing", "acceptor reply to packet 2");
746 complete(finished ? true : false, reply, error);
751 - (void)acceptorThirdPacket:(NSDictionary *)indata complete:(KCPairingInternalCompletion)complete
753 secnotice("pairing", "acceptor packet 3");
755 const uint32_t initialSyncCredentialsFlags =
756 SOSControlInitialSyncFlagTLK|
757 SOSControlInitialSyncFlagPCS|
758 SOSControlInitialSyncFlagBluetoothMigration;
760 [[self.connection remoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) {
761 complete(true, NULL, error);
762 }] initialSyncCredentials:initialSyncCredentialsFlags complete:^(NSArray *items, NSError *error2) {
763 NSMutableDictionary *reply = [NSMutableDictionary dictionary];
765 secnotice("pairing", "acceptor initialSyncCredentials complete: items %u: %@", (unsigned)[items count], error2);
769 secnotice("pairing", "acceptor reply to packet 3");
770 complete(true, reply, NULL);
777 - (bool)ensureControlChannel
782 NSXPCInterface *interface = [NSXPCInterface interfaceWithProtocol:@protocol(SOSControlProtocol)];
784 self.connection = [[NSXPCConnection alloc] initWithMachServiceName:@(kSecuritydSOSServiceName) options:0];
785 if (self.connection == NULL){
788 self.connection.remoteObjectInterface = interface;
790 [self.connection resume];
795 - (void)validateStart:(void(^)(bool result, NSError *error))complete
797 if (!self.initiator) {
798 [[self.connection remoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) {
799 complete(false, error);
800 }] stashedCredentialPublicKey:^(NSData *publicKey, NSError *error) {
801 complete(publicKey != NULL, error);
804 dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^{
805 complete(true, NULL);
810 - (void)exchangePacket:(NSData *)inputCompressedData complete:(KCPairingChannelCompletion)complete
812 NSDictionary *indict = NULL;
813 secnotice("pairing", "Exchange packet: %u", self.counter);
816 if (inputCompressedData) {
818 NSData *data = [self decompressData:inputCompressedData];
820 secnotice("pairing", "failed to decompress");
821 complete(true, NULL, NULL);
824 NSError *error = NULL;
825 indict = [NSPropertyListSerialization propertyListWithData:data
826 options:(NSPropertyListReadOptions)kCFPropertyListSupportedFormatBinary_v1_0
829 if (indict == NULL) {
830 secnotice("pairing", "failed to deserialize");
831 complete(true, NULL, error);
835 self.nextState(indict, ^(BOOL completed, NSDictionary *outdict, NSError *error) {
836 NSData *outdata = NULL, *compressedData = NULL;
838 NSError *error2 = NULL;
839 outdata = [NSPropertyListSerialization dataWithPropertyList:outdict format:NSPropertyListBinaryFormat_v1_0 options:0 error:&error2];
840 if (outdata == NULL && error)
843 compressedData = [self compressData:outdata];
845 if (compressedData) {
846 NSString *key = [NSString stringWithFormat:@"com.apple.ckks.pairing.packet-size.%s.%u",
847 self->_initiator ? "initiator" : "acceptor", self->_counter];
848 SecADClientPushValueForDistributionKey((__bridge CFStringRef)key, [compressedData length]);
849 secnotice("pairing", "pairing packet size %lu", (unsigned long)[compressedData length]);
852 secnotice("pairing", "Exchange packet complete data: %@: %@", outdata ? @"YES" : @"NO", error);
853 complete(completed, compressedData, error);
857 - (NSData *)exchangePacket:(NSData *)data complete:(bool *)complete error:(NSError * __autoreleasing *)error
859 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
860 __block NSData *rData = NULL;
861 __block NSError* processingError;
862 [self exchangePacket:data complete:^(BOOL cComplete, NSData *cData, NSError *cError) {
863 *complete = cComplete;
865 processingError = cError;
866 dispatch_semaphore_signal(sema);
868 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
870 *error = processingError;
874 - (void)setXPCConnectionObject:(NSXPCConnection *)connection
876 self.connection = connection;
879 - (void)setControlObject:(OTControl *)control
881 self.otControl = control;
884 - (void)setConfiguration:(OTJoiningConfiguration *)config
886 self.joiningConfiguration = config;
889 - (void)setSOSMessageFailForTesting:(BOOL)value
891 self.testFailSOS = value;
893 - (void)setOctagonMessageFailForTesting:(BOOL)value
895 self.testFailOctagon = value;
898 - (void)setSessionSupportsOctagonForTesting:(bool)value
900 self.sessionSupportsOctagon = value;