-
Notifications
You must be signed in to change notification settings - Fork 234
/
HAPPairingPairSetup.c
1453 lines (1314 loc) · 59.1 KB
/
HAPPairingPairSetup.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2015-2019 The HomeKit ADK Contributors
//
// Licensed under the Apache License, Version 2.0 (the “License”);
// you may not use this file except in compliance with the License.
// See [CONTRIBUTORS.md] for the list of HomeKit ADK project authors.
#include "HAP+Internal.h"
static const HAPLogObject logObject = { .subsystem = kHAP_LogSubsystem, .category = "PairingPairSetup" };
void HAPPairingPairSetupResetForSession(HAPAccessoryServerRef* server_, HAPSessionRef* session_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(session_);
HAPSession* session = (HAPSession*) session_;
// Reset session-specific Pair Setup procedure state that is stored in shared memory.
if (server->pairSetup.sessionThatIsCurrentlyPairing == session_) {
bool keepSetupInfo = server->pairSetup.keepSetupInfo;
HAPRawBufferZero(&server->pairSetup, sizeof server->pairSetup);
HAPAccessorySetupInfoHandlePairingStop(server_, keepSetupInfo);
}
// Reset session-specific Pair Setup procedure state.
HAPRawBufferZero(&session->state.pairSetup, sizeof session->state.pairSetup);
}
/**
* Pair Setup M1 TLVs.
*/
typedef struct {
HAPTLV* stateTLV; /**< kTLVType_State. */
HAPTLV* methodTLV; /**< kTLVType_Method. */
HAPTLV* flagsTLV; /**< kTLVType_Flags. */
} HAPPairingPairSetupM1TLVs;
/**
* Processes Pair Setup M1.
*
* @param server_ Accessory server.
* @param session_ The session over which the request has been received.
* @param tlvs TLVs.
*
* @return kHAPError_None If successful.
* @return kHAPError_InvalidState If a different request is expected in the current state.
* @return kHAPError_InvalidData If the controller sent a malformed request.
*/
HAP_RESULT_USE_CHECK
static HAPError HAPPairingPairSetupProcessM1(
HAPAccessoryServerRef* server_,
HAPSessionRef* session_,
const HAPPairingPairSetupM1TLVs* tlvs) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(session_);
HAPSession* session = (HAPSession*) session_;
HAPPrecondition(session->state.pairSetup.state == 1);
HAPPrecondition(!session->state.pairSetup.error);
HAPPrecondition(tlvs);
HAPPrecondition(tlvs->stateTLV);
HAPPrecondition(tlvs->stateTLV->type == kHAPPairingTLVType_State);
HAPPrecondition(tlvs->methodTLV);
HAPPrecondition(tlvs->methodTLV->type == kHAPPairingTLVType_Method);
HAPPrecondition(tlvs->flagsTLV);
HAPPrecondition(tlvs->flagsTLV->type == kHAPPairingTLVType_Flags);
// See HomeKit Accessory Protocol Specification R14
// Section 5.6.1 M1: iOS Device -> Accessory -- `SRP Start Request'
HAPLogDebug(&logObject, "Pair Setup M1: SRP Start Request.");
// Validate kTLVType_State.
if (!tlvs->stateTLV->value.bytes) {
HAPLog(&logObject, "Pair Setup M1: kTLVType_State missing.");
return kHAPError_InvalidData;
}
if (tlvs->stateTLV->value.numBytes != 1) {
HAPLog(&logObject, "Pair Setup M1: kTLVType_State has invalid length (%zu).", tlvs->stateTLV->value.numBytes);
return kHAPError_InvalidData;
}
uint8_t state = ((const uint8_t*) tlvs->stateTLV->value.bytes)[0];
if (state != 1) {
HAPLog(&logObject, "Pair Setup M1: kTLVType_State invalid: %u.", state);
return kHAPError_InvalidData;
}
// Validate kTLVType_Method.
if (!tlvs->methodTLV->value.bytes) {
HAPLog(&logObject, "Pair Setup M1: kTLVType_Method missing.");
return kHAPError_InvalidData;
}
if (tlvs->methodTLV->value.numBytes != 1) {
HAPLog(&logObject, "Pair Setup M1: kTLVType_Method has invalid length (%zu).", tlvs->methodTLV->value.numBytes);
return kHAPError_InvalidData;
}
uint8_t method = ((const uint8_t*) tlvs->methodTLV->value.bytes)[0];
if (method != kHAPPairingMethod_PairSetupWithAuth && method != kHAPPairingMethod_PairSetup) {
HAPLog(&logObject, "Pair Setup M1: kTLVType_Method invalid: %u.", method);
return kHAPError_InvalidData;
}
// Store method.
HAPLogDebug(&logObject, "Pair Setup M1: kTLVType_Method = %u.", method);
session->state.pairSetup.method = method;
// Validate and store kTLVType_Flags.
if (tlvs->flagsTLV->value.bytes) {
if (tlvs->flagsTLV->value.numBytes > sizeof(uint32_t)) {
HAPLog(&logObject,
"Pair Setup M1: kTLVType_Flags has invalid length (%zu).",
tlvs->flagsTLV->value.numBytes);
return kHAPError_InvalidData;
}
if (server->pairSetup.sessionThatIsCurrentlyPairing == session_) {
server->pairSetup.flagsPresent = true;
server->pairSetup.flags = HAPPairingReadFlags(tlvs->flagsTLV);
}
} else {
if (server->pairSetup.sessionThatIsCurrentlyPairing == session_) {
server->pairSetup.flagsPresent = false;
server->pairSetup.flags = 0;
}
}
return kHAPError_None;
}
/**
* Processes Pair Setup M2.
*
* @param server_ Accessory server.
* @param session_ The session over which the response will be sent.
* @param responseWriter TLV writer for serializing the response.
*
* @return kHAPError_None If successful.
* @return kHAPError_Unknown If persistent store access failed.
* @return kHAPError_InvalidState If a different request is expected in the current state.
* @return kHAPError_OutOfResources If response writer does not have enough capacity.
*/
HAP_RESULT_USE_CHECK
static HAPError HAPPairingPairSetupGetM2(
HAPAccessoryServerRef* server_,
HAPSessionRef* session_,
HAPTLVWriterRef* responseWriter) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(session_);
HAPSession* session = (HAPSession*) session_;
HAPPrecondition(session->state.pairSetup.state == 2);
HAPPrecondition(!session->state.pairSetup.error);
HAPPrecondition(responseWriter);
HAPError err;
// See HomeKit Accessory Protocol Specification R14
// Section 5.6.2 M2: Accessory -> iOS Device -- `SRP Start Response'
HAPLogDebug(&logObject, "Pair Setup M2: SRP Start Response.");
// Check if the accessory is already paired.
if (!server->pairSetup.sessionThatIsCurrentlyPairing || HAPAccessoryServerIsPaired(server_)) {
HAPLog(&logObject, "Pair Setup M2: Accessory is already paired.");
session->state.pairSetup.error = kHAPPairingError_Unavailable;
return kHAPError_None;
}
// Check if the accessory has received more than 100 unsuccessful authentication attempts.
bool found;
size_t numBytes;
uint8_t numAuthAttemptsBytes[sizeof(uint8_t)];
err = HAPPlatformKeyValueStoreGet(
server->platform.keyValueStore,
kHAPKeyValueStoreDomain_Configuration,
kHAPKeyValueStoreKey_Configuration_NumUnsuccessfulAuthAttempts,
numAuthAttemptsBytes,
sizeof numAuthAttemptsBytes,
&numBytes,
&found);
if (err) {
HAPAssert(err == kHAPError_Unknown);
return err;
}
if (!found) {
HAPRawBufferZero(numAuthAttemptsBytes, sizeof numAuthAttemptsBytes);
} else if (numBytes != sizeof numAuthAttemptsBytes) {
HAPLog(&logObject, "Invalid authentication attempts counter.");
return kHAPError_Unknown;
}
uint8_t numAuthAttempts = numAuthAttemptsBytes[0];
if (numAuthAttempts >= 100) {
HAPLog(&logObject, "Pair Setup M2: Accessory has received more than 100 unsuccessful authentication attempts.");
session->state.pairSetup.error = kHAPPairingError_MaxTries;
return kHAPError_None;
}
// Check if the accessory is currently performing a Pair Setup procedure with a different controller.
if (server->pairSetup.sessionThatIsCurrentlyPairing != session_) {
HAPLog(&logObject,
"Pair Setup M2: Accessory is performing a Pair Setup procedure with a different controller.");
session->state.pairSetup.error = kHAPPairingError_Busy;
return kHAPError_None;
}
// Get pairing flags.
uint32_t otherFlags = 0;
bool isTransient = false;
bool isSplit = false;
if (server->pairSetup.flagsPresent) {
uint32_t flags = server->pairSetup.flags;
if (flags & kHAPPairingFlag_Transient) {
if (session->state.pairSetup.method == kHAPPairingMethod_PairSetupWithAuth) {
HAPLog(&logObject,
"Pair Setup M2: Ignoring %s because Pair Setup with Auth was requested.",
"kPairingFlag_Transient");
} else {
HAPAssert(session->state.pairSetup.method == kHAPPairingMethod_PairSetup);
isTransient = true;
}
flags &= ~(uint32_t) kHAPPairingFlag_Transient;
}
if (flags & kHAPPairingFlag_Split) {
if (session->state.pairSetup.method == kHAPPairingMethod_PairSetupWithAuth) {
HAPLog(&logObject,
"Pair Setup M2: Ignoring %s because Pair Setup with Auth was requested.",
"kPairingFlag_Split");
} else {
HAPAssert(session->state.pairSetup.method == kHAPPairingMethod_PairSetup);
isSplit = true;
}
flags &= ~(uint32_t) kHAPPairingFlag_Split;
}
if (flags) {
HAPLog(&logObject, "Pair Setup M2: Ignoring unrecognized kTLVType_Flags: 0x%8lX.", (unsigned long) flags);
}
}
HAPLogDebug(
&logObject,
"Pair Setup M2: Processing using %s = %s / %s = %s.",
"kPairingFlag_Transient",
isTransient ? "true" : "false",
"kPairingFlag_Split",
isSplit ? "true" : "false");
// Recover setup info if requested.
HAPSetupInfo* _Nullable setupInfo =
HAPAccessorySetupInfoGetSetupInfo(server_, /* restorePrevious: */ !isTransient && isSplit);
if (!setupInfo) {
HAPLog(&logObject, "Pair Setup M2: kPairingFlag_Split requested but no previous setup info found.");
session->state.pairSetup.error = kHAPPairingError_Authentication;
return kHAPError_None;
}
HAPLogBufferDebug(&logObject, setupInfo->salt, sizeof setupInfo->salt, "Pair Setup M2: salt.");
HAPLogSensitiveBufferDebug(&logObject, setupInfo->verifier, sizeof setupInfo->verifier, "Pair Setup M2: verifier.");
// Generate private key b.
HAPPlatformRandomNumberFill(server->pairSetup.b, sizeof server->pairSetup.b);
HAPLogSensitiveBufferDebug(&logObject, server->pairSetup.b, sizeof server->pairSetup.b, "Pair Setup M2: b.");
// Derive public key B.
HAP_srp_public_key(server->pairSetup.B, server->pairSetup.b, setupInfo->verifier);
HAPLogBufferDebug(&logObject, server->pairSetup.B, sizeof server->pairSetup.B, "Pair Setup M2: B.");
// kTLVType_State.
err = HAPTLVWriterAppend(
responseWriter,
&(const HAPTLV) { .type = kHAPPairingTLVType_State,
.value = { .bytes = &session->state.pairSetup.state, .numBytes = 1 } });
if (err) {
HAPAssert(err == kHAPError_OutOfResources);
return err;
}
// kTLVType_PublicKey.
// Skip leading zeros.
size_t size = SRP_PUBLIC_KEY_BYTES;
uint8_t* B = server->pairSetup.B;
while (size && !(*B)) {
B++;
size--;
}
err = HAPTLVWriterAppend(
responseWriter,
&(const HAPTLV) { .type = kHAPPairingTLVType_PublicKey, .value = { .bytes = B, .numBytes = size } });
if (err) {
HAPAssert(err == kHAPError_OutOfResources);
return err;
}
// kTLVType_Salt.
err = HAPTLVWriterAppend(
responseWriter,
&(const HAPTLV) { .type = kHAPPairingTLVType_Salt,
.value = { .bytes = setupInfo->salt, .numBytes = sizeof setupInfo->salt } });
if (err) {
HAPAssert(err == kHAPError_OutOfResources);
return err;
}
// kTLVType_Flags.
uint32_t flags = otherFlags;
if (isTransient && isSplit) {
flags |= kHAPPairingFlag_Transient | kHAPPairingFlag_Split;
} else if (isSplit) {
flags |= kHAPPairingFlag_Split;
}
if (flags) {
uint8_t flagsBytes[] = { HAPExpandLittleUInt32(flags) };
err = HAPTLVWriterAppend(
responseWriter,
&(const HAPTLV) { .type = kHAPPairingTLVType_Flags,
.value = { .bytes = flagsBytes, .numBytes = HAPPairingGetNumBytes(flags) } });
if (err) {
HAPAssert(err == kHAPError_OutOfResources);
return err;
}
}
return kHAPError_None;
}
/**
* Pair Setup M3 TLVs.
*/
typedef struct {
HAPTLV* stateTLV; /**< kTLVType_State. */
HAPTLV* publicKeyTLV; /**< kTLVType_PublicKey. */
HAPTLV* proofTLV; /**< kTLVType_Proof. */
} HAPPairingPairSetupM3TLVs;
/**
* Processes Pair Setup M3.
*
* @param server_ Accessory server.
* @param session_ The session over which the request has been received.
* @param tlvs TLVs.
*
* @return kHAPError_None If successful.
* @return kHAPError_InvalidData If the controller sent a malformed request.
*/
HAP_RESULT_USE_CHECK
static HAPError HAPPairingPairSetupProcessM3(
HAPAccessoryServerRef* server_,
HAPSessionRef* session_,
const HAPPairingPairSetupM3TLVs* tlvs) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->pairSetup.sessionThatIsCurrentlyPairing == session_);
HAPPrecondition(session_);
HAPSession* session = (HAPSession*) session_;
HAPPrecondition(session->state.pairSetup.state == 3);
HAPPrecondition(!session->state.pairSetup.error);
HAPPrecondition(tlvs);
HAPPrecondition(tlvs->stateTLV);
HAPPrecondition(tlvs->stateTLV->type == kHAPPairingTLVType_State);
HAPPrecondition(tlvs->publicKeyTLV);
HAPPrecondition(tlvs->publicKeyTLV->type == kHAPPairingTLVType_PublicKey);
HAPPrecondition(tlvs->proofTLV);
HAPPrecondition(tlvs->proofTLV->type == kHAPPairingTLVType_Proof);
// See HomeKit Accessory Protocol Specification R14
// Section 5.6.3 M3: iOS Device -> Accessory -- `SRP Verify Request'
HAPLogDebug(&logObject, "Pair Setup M3: SRP Verify Request.");
// Validate kTLVType_State.
if (!tlvs->stateTLV->value.bytes) {
HAPLog(&logObject, "Pair Setup M3: kTLVType_State missing.");
return kHAPError_InvalidData;
}
if (tlvs->stateTLV->value.numBytes != 1) {
HAPLog(&logObject, "Pair Setup M3: kTLVType_State has invalid length (%zu).", tlvs->stateTLV->value.numBytes);
return kHAPError_InvalidData;
}
uint8_t state = ((const uint8_t*) tlvs->stateTLV->value.bytes)[0];
if (state != 3) {
HAPLog(&logObject, "Pair Setup M3: kTLVType_State invalid: %u.", state);
return kHAPError_InvalidData;
}
// Validate kTLVType_PublicKey.
if (!tlvs->publicKeyTLV->value.bytes) {
HAPLog(&logObject, "Pair Setup M3: kTLVType_PublicKey missing.");
return kHAPError_InvalidData;
}
if (tlvs->publicKeyTLV->value.numBytes > sizeof server->pairSetup.A) {
HAPLog(&logObject,
"Pair Setup M3: kTLVType_PublicKey has invalid length (%zu).",
tlvs->publicKeyTLV->value.numBytes);
return kHAPError_InvalidData;
}
// Validate kTLVType_Proof.
if (!tlvs->proofTLV->value.bytes) {
HAPLog(&logObject, "Pair Setup M3: kTLVType_Proof missing.");
return kHAPError_InvalidData;
}
if (tlvs->proofTLV->value.numBytes != sizeof server->pairSetup.M1) {
HAPLog(&logObject, "Pair Setup M3: kTLVType_Proof has invalid length (%zu).", tlvs->proofTLV->value.numBytes);
return kHAPError_InvalidData;
}
// Copy public key to A and zero-extend big-endian.
void* A = &server->pairSetup.A[sizeof server->pairSetup.A - tlvs->publicKeyTLV->value.numBytes];
HAPRawBufferZero(server->pairSetup.A, sizeof server->pairSetup.A - tlvs->publicKeyTLV->value.numBytes);
HAPRawBufferCopyBytes(A, HAPNonnullVoid(tlvs->publicKeyTLV->value.bytes), tlvs->publicKeyTLV->value.numBytes);
HAPLogBufferDebug(&logObject, server->pairSetup.A, sizeof server->pairSetup.A, "Pair Setup M3: A.");
// Copy proof.
HAPRawBufferCopyBytes(
server->pairSetup.M1, HAPNonnullVoid(tlvs->proofTLV->value.bytes), tlvs->proofTLV->value.numBytes);
HAPLogBufferDebug(&logObject, server->pairSetup.M1, sizeof server->pairSetup.M1, "Pair Setup M3: M1.");
return kHAPError_None;
}
/**
* Processes Pair Setup M4.
*
* @param server_ Accessory server.
* @param session_ The session over which the response will be sent.
* @param responseWriter TLV writer for serializing the response.
*
* @return kHAPError_None If successful.
* @return kHAPError_Unknown If communication with Apple Auth Coprocessor or persistent store access failed.
* @return kHAPError_InvalidState If a different request is expected in the current state.
* @return kHAPError_OutOfResources If response writer does not have enough capacity.
*/
HAP_RESULT_USE_CHECK
static HAPError HAPPairingPairSetupGetM4(
HAPAccessoryServerRef* server_,
HAPSessionRef* session_,
HAPTLVWriterRef* responseWriter) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->pairSetup.sessionThatIsCurrentlyPairing == session_);
HAPPrecondition(session_);
HAPSession* session = (HAPSession*) session_;
HAPPrecondition(session->state.pairSetup.state == 4);
HAPPrecondition(!session->state.pairSetup.error);
HAPPrecondition(responseWriter);
HAPError err;
// See HomeKit Accessory Protocol Specification R14
// Section 5.6.4 M4: Accessory -> iOS Device -- `SRP Verify Response'
HAPLogDebug(&logObject, "Pair Setup M4: SRP Verify Response.");
// Compute SRP shared secret key.
{
void* bytes;
size_t maxBytes;
HAPTLVWriterGetScratchBytes(responseWriter, &bytes, &maxBytes);
void* u = HAPTLVScratchBufferAlloc(&bytes, &maxBytes, SRP_SCRAMBLING_PARAMETER_BYTES);
void* S = HAPTLVScratchBufferAlloc(&bytes, &maxBytes, SRP_PREMASTER_SECRET_BYTES);
void* M1 = HAPTLVScratchBufferAlloc(&bytes, &maxBytes, SRP_PROOF_BYTES);
if (!u || !S || !M1) {
HAPLog(&logObject, "Pair Setup M4: Not enough memory to allocate u / S / M1.");
return kHAPError_OutOfResources;
}
HAP_srp_scrambling_parameter(u, server->pairSetup.A, server->pairSetup.B);
HAPLogSensitiveBufferDebug(&logObject, u, SRP_SCRAMBLING_PARAMETER_BYTES, "Pair Setup M4: u.");
bool restorePrevious = false;
if (server->pairSetup.flagsPresent) {
restorePrevious = !(server->pairSetup.flags & kHAPPairingFlag_Transient) &&
server->pairSetup.flags & kHAPPairingFlag_Split;
}
HAPSetupInfo* _Nullable setupInfo = HAPAccessorySetupInfoGetSetupInfo(server_, restorePrevious);
HAPAssert(setupInfo);
int e = HAP_srp_premaster_secret(S, server->pairSetup.A, server->pairSetup.b, u, setupInfo->verifier);
if (e) {
HAPAssert(e == 1);
// Illegal key A.
HAPLog(&logObject, "Pair Setup M4: Illegal key A.");
session->state.pairSetup.error = kHAPPairingError_Authentication;
return kHAPError_None;
}
HAPLogSensitiveBufferDebug(&logObject, S, SRP_PREMASTER_SECRET_BYTES, "Pair Setup M4: S.");
HAP_srp_session_key(server->pairSetup.K, S);
HAPLogSensitiveBufferDebug(&logObject, server->pairSetup.K, sizeof server->pairSetup.K, "Pair Setup M4: K.");
static const uint8_t userName[] = "Pair-Setup";
HAP_srp_proof_m1(
M1,
userName,
sizeof userName - 1,
setupInfo->salt,
server->pairSetup.A,
server->pairSetup.B,
server->pairSetup.K);
HAPLogSensitiveBufferDebug(&logObject, M1, SRP_PROOF_BYTES, "Pair Setup M4: M1");
// Verify the controller's SRP proof.
if (!HAPRawBufferAreEqual(M1, server->pairSetup.M1, SRP_PROOF_BYTES)) {
bool found;
size_t numBytes;
uint8_t numAuthAttemptsBytes[sizeof(uint8_t)];
err = HAPPlatformKeyValueStoreGet(
server->platform.keyValueStore,
kHAPKeyValueStoreDomain_Configuration,
kHAPKeyValueStoreKey_Configuration_NumUnsuccessfulAuthAttempts,
numAuthAttemptsBytes,
sizeof numAuthAttemptsBytes,
&numBytes,
&found);
if (err) {
HAPAssert(err == kHAPError_Unknown);
return err;
}
if (!found) {
HAPRawBufferZero(numAuthAttemptsBytes, sizeof numAuthAttemptsBytes);
} else if (numBytes != sizeof numAuthAttemptsBytes) {
HAPLog(&logObject, "Invalid authentication attempts counter.");
return kHAPError_Unknown;
}
uint8_t numAuthAttempts = numAuthAttemptsBytes[0];
HAPAssert(numAuthAttempts < UINT8_MAX);
numAuthAttempts++;
numAuthAttemptsBytes[0] = numAuthAttempts;
err = HAPPlatformKeyValueStoreSet(
server->platform.keyValueStore,
kHAPKeyValueStoreDomain_Configuration,
kHAPKeyValueStoreKey_Configuration_NumUnsuccessfulAuthAttempts,
numAuthAttemptsBytes,
sizeof numAuthAttemptsBytes);
if (err) {
HAPAssert(err == kHAPError_Unknown);
return err;
}
HAPLog(&logObject,
"Pair Setup M4: Incorrect setup code. Unsuccessful authentication attempts = %u / 100.",
numAuthAttempts);
session->state.pairSetup.error = kHAPPairingError_Authentication;
return kHAPError_None;
}
// Reset authentication attempts counter.
err = HAPPlatformKeyValueStoreRemove(
server->platform.keyValueStore,
kHAPKeyValueStoreDomain_Configuration,
kHAPKeyValueStoreKey_Configuration_NumUnsuccessfulAuthAttempts);
if (err) {
HAPAssert(err == kHAPError_Unknown);
return err;
}
// Generate accessory-side SRP proof.
HAP_srp_proof_m2(server->pairSetup.M2, server->pairSetup.A, M1, server->pairSetup.K);
HAPLogBufferDebug(&logObject, server->pairSetup.M2, sizeof server->pairSetup.M2, "Pair Setup M4: M2.");
// Derive the symmetric session encryption key.
static const uint8_t salt[] = "Pair-Setup-Encrypt-Salt";
static const uint8_t info[] = "Pair-Setup-Encrypt-Info";
HAP_hkdf_sha512(
server->pairSetup.SessionKey,
sizeof server->pairSetup.SessionKey,
server->pairSetup.K,
sizeof server->pairSetup.K,
salt,
sizeof salt - 1,
info,
sizeof info - 1);
HAPLogSensitiveBufferDebug(
&logObject,
server->pairSetup.SessionKey,
sizeof server->pairSetup.SessionKey,
"Pair Setup M4: SessionKey");
}
// kTLVType_State.
err = HAPTLVWriterAppend(
responseWriter,
&(const HAPTLV) { .type = kHAPPairingTLVType_State,
.value = { .bytes = &session->state.pairSetup.state, .numBytes = 1 } });
if (err) {
HAPAssert(err == kHAPError_OutOfResources);
return err;
}
// kTLVType_Proof.
err = HAPTLVWriterAppend(
responseWriter,
&(const HAPTLV) { .type = kHAPPairingTLVType_Proof,
.value = { .bytes = server->pairSetup.M2, .numBytes = sizeof server->pairSetup.M2 } });
if (err) {
HAPAssert(err == kHAPError_OutOfResources);
return err;
}
// kTLVType_EncryptedData.
if (session->state.pairSetup.method == kHAPPairingMethod_PairSetupWithAuth) {
// Construct sub-TLV writer.
HAPTLVWriterRef subWriter;
{
void* bytes;
size_t maxBytes;
HAPTLVWriterGetScratchBytes(responseWriter, &bytes, &maxBytes);
if (maxBytes < CHACHA20_POLY1305_TAG_BYTES) {
HAPLog(&logObject, "Pair Setup M4: Not enough memory for kTLVType_EncryptedData auth tag.");
return kHAPError_OutOfResources;
}
maxBytes -= CHACHA20_POLY1305_TAG_BYTES;
HAPTLVWriterCreate(&subWriter, bytes, maxBytes);
}
if (session->state.pairSetup.method == kHAPPairingMethod_PairSetupWithAuth) {
HAPMFiAuth mfiAuth;
{
if (!server->platform.authentication.mfiHWAuth || !HAPAccessoryServerSupportsMFiHWAuth(server_)) {
HAPLog(&logObject, "Pair Setup M4: Apple Authentication Coprocessor is not available.");
return kHAPError_InvalidState;
}
HAPLogInfo(&logObject, "Using Apple Authentication Coprocessor.");
mfiAuth.copyCertificate = HAPMFiHWAuthCopyCertificate;
mfiAuth.createSignature = HAPMFiHWAuthCreateSignature;
}
// kTLVType_Signature.
{
void* bytes;
size_t maxBytes;
HAPTLVWriterGetScratchBytes(&subWriter, &bytes, &maxBytes);
const size_t numChallengeBytes = 32;
void* challengeBytes = HAPTLVScratchBufferAlloc(&bytes, &maxBytes, numChallengeBytes);
const size_t maxMFiProofBytes = maxBytes;
void* mfiProofBytes = HAPTLVScratchBufferAllocUnaligned(&bytes, &maxBytes, maxMFiProofBytes);
if (!challengeBytes || !mfiProofBytes) {
HAPLog(&logObject, "Pair Setup M4: Not enough memory to allocate MFiChallenge / MFi Proof.");
return kHAPError_OutOfResources;
}
// Generate MFi challenge.
static const uint8_t salt[] = "MFi-Pair-Setup-Salt";
static const uint8_t info[] = "MFi-Pair-Setup-Info";
HAP_hkdf_sha512(
challengeBytes,
numChallengeBytes,
server->pairSetup.K,
sizeof server->pairSetup.K,
salt,
sizeof salt - 1,
info,
sizeof info - 1);
HAPLogSensitiveBufferDebug(
&logObject, challengeBytes, numChallengeBytes, "Pair Setup M4: MFiChallenge.");
// Generate the MFi proof.
size_t numMFiProofBytes;
err = mfiAuth.createSignature(
server_, challengeBytes, numChallengeBytes, mfiProofBytes, maxMFiProofBytes, &numMFiProofBytes);
if (err) {
HAPAssert(err == kHAPError_Unknown);
return err;
}
HAPLogSensitiveBufferDebug(
&logObject, mfiProofBytes, numMFiProofBytes, "Pair Setup M4: kTLVType_Signature.");
// kTLVType_Signature.
err = HAPTLVWriterAppend(
&subWriter,
&(const HAPTLV) { .type = kHAPPairingTLVType_Signature,
.value = { .bytes = mfiProofBytes, .numBytes = numMFiProofBytes } });
if (err) {
HAPAssert(err == kHAPError_OutOfResources);
return err;
}
}
// kTLVType_Certificate.
{
void* bytes;
size_t maxBytes;
HAPTLVWriterGetScratchBytes(&subWriter, &bytes, &maxBytes);
const size_t maxCertificateBytes = maxBytes;
void* certificateBytes = HAPTLVScratchBufferAllocUnaligned(&bytes, &maxBytes, maxCertificateBytes);
if (!certificateBytes) {
HAPLog(&logObject, "Pair Setup M4: Not enough memory to allocate Accessory Certificate.");
return kHAPError_OutOfResources;
}
// Read the Accessory Certificate.
size_t numCertificateBytes;
err = mfiAuth.copyCertificate(server_, certificateBytes, maxCertificateBytes, &numCertificateBytes);
if (err) {
HAPAssert(err == kHAPError_Unknown);
return err;
}
HAPLogSensitiveBufferDebug(
&logObject, certificateBytes, numCertificateBytes, "Pair Setup M4: kTLVType_Certificate.");
// kTLVType_Certificate.
err = HAPTLVWriterAppend(
&subWriter,
&(const HAPTLV) { .type = kHAPPairingTLVType_Certificate,
.value = { .bytes = certificateBytes, .numBytes = numCertificateBytes } });
if (err) {
HAPAssert(err == kHAPError_OutOfResources);
return err;
}
}
}
// Encrypt the sub-TLV.
void* bytes;
size_t numBytes;
HAPTLVWriterGetBuffer(&subWriter, &bytes, &numBytes);
static const uint8_t nonce[] = "PS-Msg04";
HAP_chacha20_poly1305_encrypt(
&((uint8_t*) bytes)[numBytes],
bytes,
bytes,
numBytes,
nonce,
sizeof nonce - 1,
server->pairSetup.SessionKey);
numBytes += CHACHA20_POLY1305_TAG_BYTES;
HAPLogBufferDebug(&logObject, bytes, numBytes, "Pair Setup M4: kTLVType_EncryptedData.");
// kTLVType_EncryptedData.
err = HAPTLVWriterAppend(
responseWriter,
&(const HAPTLV) { .type = kHAPPairingTLVType_EncryptedData,
.value = { .bytes = bytes, .numBytes = numBytes } });
if (err) {
HAPAssert(err == kHAPError_OutOfResources);
return err;
}
}
if (session->state.pairSetup.method == kHAPPairingMethod_PairSetup && server->pairSetup.flagsPresent &&
server->pairSetup.flags & kHAPPairingFlag_Transient) {
// Initialize HAP session.
HAPRawBufferZero(&session->hap, sizeof session->hap);
// Derive encryption keys.
static const uint8_t salt[] = "SplitSetupSalt";
{
static const uint8_t info[] = "AccessoryEncrypt-Control";
HAP_hkdf_sha512(
session->hap.accessoryToController.controlChannel.key.bytes,
sizeof session->hap.accessoryToController.controlChannel.key.bytes,
server->pairSetup.K,
sizeof server->pairSetup.K,
salt,
sizeof salt - 1,
info,
sizeof info - 1);
HAPLogSensitiveBufferDebug(
&logObject,
session->hap.accessoryToController.controlChannel.key.bytes,
sizeof session->hap.accessoryToController.controlChannel.key.bytes,
"Transient Pair Setup Start Session: AccessoryEncryptKey");
}
{
static const uint8_t info[] = "ControllerEncrypt-Control";
HAP_hkdf_sha512(
session->hap.controllerToAccessory.controlChannel.key.bytes,
sizeof session->hap.controllerToAccessory.controlChannel.key.bytes,
server->pairSetup.K,
sizeof server->pairSetup.K,
salt,
sizeof salt - 1,
info,
sizeof info - 1);
HAPLogSensitiveBufferDebug(
&logObject,
session->hap.controllerToAccessory.controlChannel.key.bytes,
sizeof session->hap.controllerToAccessory.controlChannel.key.bytes,
"Transient Pair Setup Start Session: ControllerEncryptKey");
}
session->hap.accessoryToController.controlChannel.nonce = 0;
session->hap.controllerToAccessory.controlChannel.nonce = 0;
// Activate session.
session->hap.isTransient = true;
session->hap.active = true;
// Persist setup info for next Pair Setup procedure if requested.
if (server->pairSetup.flags & kHAPPairingFlag_Split) {
server->pairSetup.keepSetupInfo = true;
} else {
HAPLog(&logObject, "Transient Pair Setup procedure requested without kHAPPairingFlag_Split.");
}
// Reset Pair Setup procedure.
HAPPairingPairSetupResetForSession(server_, session_);
HAPLogInfo(&logObject, "Transient Pair Setup procedure completed.");
// Inform application.
if (server->callbacks.handleSessionAccept) {
server->callbacks.handleSessionAccept(server_, session_, server->context);
}
if (server->transports.ble) {
HAPNonnull(server->transports.ble)->peripheralManager.handleSessionAccept(server_, session_);
}
}
return kHAPError_None;
}
/**
* Pair Setup M5 TLVs.
*/
typedef struct {
HAPTLV* stateTLV; /**< kTLVType_State. */
HAPTLV* encryptedDataTLV; /**< kTLVType_EncryptedData. */
} HAPPairingPairSetupM5TLVs;
/**
* Processes Pair Setup M5.
*
* @param server_ Accessory server.
* @param session_ The session over which the request has been received.
* @param scratchBytes Free memory.
* @param numScratchBytes Length of free memory buffer.
* @param tlvs TLVs.
*
* @return kHAPError_None If successful.
* @return kHAPError_InvalidState If a different request is expected in the current state.
* @return kHAPError_InvalidData If the controller sent a malformed request.
* @return kHAPError_OutOfResources If the free memory buffer does not have enough capacity.
*/
HAP_RESULT_USE_CHECK
static HAPError HAPPairingPairSetupProcessM5(
HAPAccessoryServerRef* server_,
HAPSessionRef* session_,
void* scratchBytes,
size_t numScratchBytes,
const HAPPairingPairSetupM5TLVs* tlvs) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->pairSetup.sessionThatIsCurrentlyPairing == session_);
HAPPrecondition(session_);
HAPSession* session = (HAPSession*) session_;
HAPPrecondition(session->state.pairSetup.state == 5);
HAPPrecondition(!session->state.pairSetup.error);
HAPPrecondition(tlvs);
HAPPrecondition(tlvs->stateTLV);
HAPPrecondition(tlvs->stateTLV->type == kHAPPairingTLVType_State);
HAPPrecondition(tlvs->encryptedDataTLV);
HAPPrecondition(tlvs->encryptedDataTLV->type == kHAPPairingTLVType_EncryptedData);
HAPError err;
// See HomeKit Accessory Protocol Specification R14
// Section 5.6.5 M5: iOS Device -> Accessory -- `Exchange Request'
HAPLogDebug(&logObject, "Pair Setup M5: Exchange Request.");
// Validate kTLVType_State.
if (!tlvs->stateTLV->value.bytes) {
HAPLog(&logObject, "Pair Setup M5: kTLVType_State missing.");
return kHAPError_InvalidData;
}
if (tlvs->stateTLV->value.numBytes != 1) {
HAPLog(&logObject, "Pair Setup M5: kTLVType_State has invalid length (%zu).", tlvs->stateTLV->value.numBytes);
return kHAPError_InvalidData;
}
uint8_t state = ((const uint8_t*) tlvs->stateTLV->value.bytes)[0];
if (state != 5) {
HAPLog(&logObject, "Pair Setup M5: kTLVType_State invalid: %u.", state);
return kHAPError_InvalidData;
}
// Validate kTLVType_EncryptedData.
if (!tlvs->encryptedDataTLV->value.bytes) {
HAPLog(&logObject, "Pair Setup M5: kTLVType_EncryptedData missing.");
return kHAPError_InvalidData;
}
if (tlvs->encryptedDataTLV->value.numBytes < CHACHA20_POLY1305_TAG_BYTES) {
HAPLog(&logObject,
"Pair Setup M5: kTLVType_EncryptedData has invalid length (%zu).",
tlvs->encryptedDataTLV->value.numBytes);
return kHAPError_InvalidData;
}
// Verify auth tag and decrypt.
HAPLogBufferDebug(
&logObject,
tlvs->encryptedDataTLV->value.bytes,
tlvs->encryptedDataTLV->value.numBytes,
"Pair Setup M5: kTLVType_EncryptedData.");
void* bytes = (void*) (uintptr_t) tlvs->encryptedDataTLV->value.bytes;
size_t numBytes = tlvs->encryptedDataTLV->value.numBytes - CHACHA20_POLY1305_TAG_BYTES;
static const uint8_t nonce[] = "PS-Msg05";
int e = HAP_chacha20_poly1305_decrypt(
&((uint8_t*) bytes)[numBytes],
bytes,
bytes,
numBytes,
nonce,
sizeof nonce - 1,
server->pairSetup.SessionKey);
if (e) {
HAPAssert(e == -1);
HAPLog(&logObject, "Pair Setup M5: Failed to decrypt kTLVType_EncryptedData.");
session->state.pairSetup.error = kHAPPairingError_Authentication;
return kHAPError_None;
}
HAPLogSensitiveBufferDebug(&logObject, bytes, numBytes, "Pair Setup M5: kTLVType_EncryptedData (decrypted).");
// Parse sub-TLV.
HAPTLV identifierTLV, publicKeyTLV, signatureTLV;
identifierTLV.type = kHAPPairingTLVType_Identifier;
publicKeyTLV.type = kHAPPairingTLVType_PublicKey;
signatureTLV.type = kHAPPairingTLVType_Signature;
{
HAPTLVReaderRef subReader;
HAPTLVReaderCreate(&subReader, bytes, numBytes);
err = HAPTLVReaderGetAll(&subReader, (HAPTLV* const[]) { &identifierTLV, &publicKeyTLV, &signatureTLV, NULL });
if (err) {
HAPAssert(err == kHAPError_InvalidData);
return err;
}
// Validate kTLVType_Identifier.
if (!identifierTLV.value.bytes) {
HAPLog(&logObject, "Pair Setup M5: kTLVType_Identifier missing.");
return kHAPError_InvalidData;
}
if (identifierTLV.value.numBytes > sizeof(HAPPairingID)) {
HAPLog(&logObject,
"Pair Setup M5: kTLVType_Identifier has invalid length (%zu).",
identifierTLV.value.numBytes);
return kHAPError_InvalidData;
}
// Validate kTLVType_PublicKey.
if (!publicKeyTLV.value.bytes) {
HAPLog(&logObject, "Pair Setup M5: kTLVType_PublicKey missing.");
return kHAPError_InvalidData;
}
if (publicKeyTLV.value.numBytes != sizeof(HAPPairingPublicKey)) {
HAPLog(&logObject,
"Pair Setup M5: kTLVType_PublicKey has invalid length (%zu).",
publicKeyTLV.value.numBytes);
return kHAPError_InvalidData;
}
// Validate kTLVType_Signature.
if (!signatureTLV.value.bytes) {
HAPLog(&logObject, "Pair Setup M5: kTLVType_Signature missing.");
return kHAPError_InvalidData;
}
if (signatureTLV.value.numBytes != ED25519_BYTES) {
HAPLog(&logObject,
"Pair Setup M5: kTLVType_Signature has invalid length (%zu).",
signatureTLV.value.numBytes);
return kHAPError_InvalidData;
}
}
const size_t XLength = 32;
void* X = HAPTLVScratchBufferAlloc(&scratchBytes, &numScratchBytes, XLength);
void* pairingID = HAPTLVScratchBufferAllocUnaligned(&scratchBytes, &numScratchBytes, identifierTLV.value.numBytes);
void* ltpk = HAPTLVScratchBufferAllocUnaligned(&scratchBytes, &numScratchBytes, ED25519_PUBLIC_KEY_BYTES);
if (!X || !pairingID || !ltpk) {
HAPLog(&logObject,
"Pair Setup M5: Not enough memory to allocate iOSDeviceX / iOSDevicePairingID / iOSDeviceLTPK.");
return kHAPError_OutOfResources;
}
// Derive iOSDeviceX from the SRP shared secret.
static const uint8_t salt[] = "Pair-Setup-Controller-Sign-Salt";
static const uint8_t info[] = "Pair-Setup-Controller-Sign-Info";
HAP_hkdf_sha512(
X, XLength, server->pairSetup.K, sizeof server->pairSetup.K, salt, sizeof salt - 1, info, sizeof info - 1);
// Construct iOSDeviceInfo: iOSDeviceX, iOSDevicePairingID, iOSDeviceLTPK.
HAPRawBufferCopyBytes(pairingID, HAPNonnullVoid(identifierTLV.value.bytes), identifierTLV.value.numBytes);
HAPRawBufferCopyBytes(ltpk, HAPNonnullVoid(publicKeyTLV.value.bytes), publicKeyTLV.value.numBytes);
// Finalize info.
void* infoBytes = X;
size_t numInfoBytes = XLength + identifierTLV.value.numBytes + ED25519_PUBLIC_KEY_BYTES;
HAPLogSensitiveBufferDebug(&logObject, infoBytes, numInfoBytes, "Pair Setup M5: iOSDeviceInfo.");
// Verify signature.
HAPLogSensitiveBufferDebug(
&logObject, signatureTLV.value.bytes, signatureTLV.value.numBytes, "Pair Setup M5: kTLVType_Signature.");
e = HAP_ed25519_verify(signatureTLV.value.bytes, infoBytes, numInfoBytes, ltpk);
if (e) {
HAPAssert(e == -1);
HAPLog(&logObject, "Pair Setup M5: iOSDeviceInfo signature is incorrect.");
session->state.pairSetup.error = kHAPPairingError_Authentication;
return kHAPError_None;
}
// Persistently save the iOSDevicePairingID and iOSDeviceLTPK as a pairing.
HAPPairing pairing;