• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #include "pw_bluetooth_sapphire/internal/host/sm/phase_3.h"
16 
17 #include <pw_assert/check.h>
18 #include <pw_bytes/endian.h>
19 
20 #include <cstdint>
21 #include <memory>
22 
23 #include "pw_bluetooth_sapphire/internal/host/common/byte_buffer.h"
24 #include "pw_bluetooth_sapphire/internal/host/common/device_address.h"
25 #include "pw_bluetooth_sapphire/internal/host/common/random.h"
26 #include "pw_bluetooth_sapphire/internal/host/common/uint128.h"
27 #include "pw_bluetooth_sapphire/internal/host/hci-spec/link_key.h"
28 #include "pw_bluetooth_sapphire/internal/host/hci/connection.h"
29 #include "pw_bluetooth_sapphire/internal/host/l2cap/fake_channel_test.h"
30 #include "pw_bluetooth_sapphire/internal/host/sm/fake_phase_listener.h"
31 #include "pw_bluetooth_sapphire/internal/host/sm/packet.h"
32 #include "pw_bluetooth_sapphire/internal/host/sm/smp.h"
33 #include "pw_bluetooth_sapphire/internal/host/sm/types.h"
34 #include "pw_bluetooth_sapphire/internal/host/sm/util.h"
35 #include "pw_bluetooth_sapphire/internal/host/testing/test_helpers.h"
36 #include "pw_unit_test/framework.h"
37 
38 namespace bt::sm {
39 namespace {
40 
41 using util::PacketSize;
42 
43 const PairingFeatures kDefaultFeatures = {
44     .initiator = true,
45     .secure_connections = false,
46     .will_bond = true,
47     .generate_ct_key = std::optional<CrossTransportKeyAlgo>{std::nullopt},
48     .method = PairingMethod::kJustWorks,
49     .encryption_key_size = kMaxEncryptionKeySize,
50     .local_key_distribution =
51         KeyDistGen::kEncKey,  // kEncKey because it lets Phase 3 "just work"
52     .remote_key_distribution = 0u};
53 
54 const SecurityProperties kDefaultProperties(SecurityLevel::kEncrypted,
55                                             kMaxEncryptionKeySize,
56                                             /*secure_connections=*/false);
57 
58 struct Phase3Args {
59   PairingFeatures features = kDefaultFeatures;
60   SecurityProperties le_props = kDefaultProperties;
61 };
62 
63 const hci_spec::LinkKey kSampleLinkKey(
64     /*value=*/UInt128{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
65     /*rand=*/0x1234,
66     /*ediv=*/0x5678);
67 
68 const DeviceAddress kSampleDeviceAddress(DeviceAddress::Type::kLEPublic, {1});
69 
70 class Phase3Test : public l2cap::testing::FakeChannelTest {
71  public:
72   Phase3Test() = default;
73   ~Phase3Test() override = default;
74 
heap_dispatcher()75   pw::async::HeapDispatcher& heap_dispatcher() { return heap_dispatcher_; }
76 
77  protected:
SetUp()78   void SetUp() override { NewPhase3(); }
79 
TearDown()80   void TearDown() override { phase_3_ = nullptr; }
81 
NewPhase3(Phase3Args phase_args=Phase3Args (),bt::LinkType ll_type=bt::LinkType::kLE)82   void NewPhase3(Phase3Args phase_args = Phase3Args(),
83                  bt::LinkType ll_type = bt::LinkType::kLE) {
84     l2cap::ChannelId cid = ll_type == bt::LinkType::kLE ? l2cap::kLESMPChannelId
85                                                         : l2cap::kSMPChannelId;
86     ChannelOptions options(cid);
87     options.link_type = ll_type;
88 
89     listener_ = std::make_unique<FakeListener>();
90     fake_chan_ = CreateFakeChannel(options);
91     sm_chan_ = std::make_unique<PairingChannel>(fake_chan_->GetWeakPtr());
92     auto role =
93         phase_args.features.initiator ? Role::kInitiator : Role::kResponder;
94     phase_3_ = std::make_unique<Phase3>(sm_chan_->GetWeakPtr(),
95                                         listener_->as_weak_ptr(),
96                                         role,
97                                         phase_args.features,
98                                         phase_args.le_props,
99                                         [this](PairingData pairing_results) {
100                                           phase_3_complete_count_++;
101                                           pairing_data_ = pairing_results;
102                                         });
103   }
104 
Make128BitCmd(Code cmd_code,const UInt128 & value)105   auto Make128BitCmd(Code cmd_code, const UInt128& value) {
106     StaticByteBuffer<PacketSize<UInt128>()> buffer;
107     PacketWriter writer(cmd_code, &buffer);
108     *writer.mutable_payload<UInt128>() = value;
109     return buffer;
110   }
111 
Receive128BitCmd(Code cmd_code,const UInt128 & value)112   void Receive128BitCmd(Code cmd_code, const UInt128& value) {
113     fake_chan()->Receive(Make128BitCmd(cmd_code, value));
114   }
115 
MakeCentralIdentification(uint64_t random,uint16_t ediv)116   auto MakeCentralIdentification(uint64_t random, uint16_t ediv) {
117     StaticByteBuffer<PacketSize<CentralIdentificationParams>()> buffer;
118     PacketWriter writer(kCentralIdentification, &buffer);
119     auto* params = writer.mutable_payload<CentralIdentificationParams>();
120     params->ediv = pw::bytes::ConvertOrderTo(cpp20::endian::little, ediv);
121     params->rand = pw::bytes::ConvertOrderTo(cpp20::endian::little, random);
122     return buffer;
123   }
124 
ReceiveCentralIdentification(uint64_t random,uint16_t ediv)125   void ReceiveCentralIdentification(uint64_t random, uint16_t ediv) {
126     fake_chan()->Receive(MakeCentralIdentification(random, ediv));
127   }
128 
MakeIdentityAddress(const DeviceAddress & address)129   auto MakeIdentityAddress(const DeviceAddress& address) {
130     StaticByteBuffer<PacketSize<IdentityAddressInformationParams>()> buffer;
131     PacketWriter writer(kIdentityAddressInformation, &buffer);
132     auto* params = writer.mutable_payload<IdentityAddressInformationParams>();
133     params->type = address.type() == DeviceAddress::Type::kLEPublic
134                        ? AddressType::kPublic
135                        : AddressType::kStaticRandom;
136     params->bd_addr = address.value();
137     return buffer;
138   }
139 
ReceiveIdentityAddress(const DeviceAddress & address)140   void ReceiveIdentityAddress(const DeviceAddress& address) {
141     fake_chan()->Receive(MakeIdentityAddress(address));
142   }
143 
ExtractCodeAnd128BitCmd(ByteBufferPtr sdu)144   static std::pair<Code, UInt128> ExtractCodeAnd128BitCmd(ByteBufferPtr sdu) {
145     PW_CHECK(sdu, "Tried to ExtractCodeAnd128BitCmd from nullptr in test");
146     auto maybe_reader = ValidPacketReader::ParseSdu(sdu);
147     PW_CHECK(maybe_reader.is_ok(),
148              "Tried to ExtractCodeAnd128BitCmd from invalid SMP packet");
149     return {maybe_reader.value().code(),
150             maybe_reader.value().payload<UInt128>()};
151   }
152 
ExpectEncryptionInfo(ByteBufferPtr sdu,std::optional<EncryptionInformationParams> * out_ltk_bytes,std::optional<CentralIdentificationParams> * out_central_id)153   static void ExpectEncryptionInfo(
154       ByteBufferPtr sdu,
155       std::optional<EncryptionInformationParams>* out_ltk_bytes,
156       std::optional<CentralIdentificationParams>* out_central_id) {
157     fit::result<ErrorCode, ValidPacketReader> reader =
158         ValidPacketReader::ParseSdu(sdu);
159     ASSERT_TRUE(reader.is_ok());
160     if (reader.value().code() == kEncryptionInformation) {
161       *out_ltk_bytes = reader.value().payload<EncryptionInformationParams>();
162     } else if (reader.value().code() == kCentralIdentification) {
163       *out_central_id = reader.value().payload<CentralIdentificationParams>();
164     } else {
165       ADD_FAILURE() << "Only expected LTK packets";
166     }
167   }
168 
ExpectIdentity(ByteBufferPtr sdu,std::optional<IRK> * out_irk,std::optional<IdentityAddressInformationParams> * out_id_address)169   static void ExpectIdentity(
170       ByteBufferPtr sdu,
171       std::optional<IRK>* out_irk,
172       std::optional<IdentityAddressInformationParams>* out_id_address) {
173     fit::result<ErrorCode, ValidPacketReader> reader =
174         ValidPacketReader::ParseSdu(sdu);
175     ASSERT_TRUE(reader.is_ok());
176     if (reader.value().code() == kIdentityInformation) {
177       *out_irk = reader.value().payload<IRK>();
178     } else if (reader.value().code() == kIdentityAddressInformation) {
179       *out_id_address =
180           reader.value().payload<IdentityAddressInformationParams>();
181     } else {
182       ADD_FAILURE() << "Only expected identity information packets";
183     }
184   }
185 
DestroyPhase3()186   void DestroyPhase3() { phase_3_.reset(nullptr); }
fake_chan() const187   l2cap::testing::FakeChannel* fake_chan() const { return fake_chan_.get(); }
phase_3()188   Phase3* phase_3() { return phase_3_.get(); }
listener()189   FakeListener* listener() { return listener_.get(); }
190 
phase_3_complete_count() const191   int phase_3_complete_count() const { return phase_3_complete_count_; }
pairing_data() const192   const PairingData& pairing_data() const { return pairing_data_; }
193 
194  private:
195   std::unique_ptr<FakeListener> listener_;
196   std::unique_ptr<l2cap::testing::FakeChannel> fake_chan_;
197   std::unique_ptr<PairingChannel> sm_chan_;
198   std::unique_ptr<Phase3> phase_3_;
199   int phase_3_complete_count_ = 0;
200   PairingData pairing_data_;
201   pw::async::HeapDispatcher heap_dispatcher_{dispatcher()};
202 
203   BT_DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(Phase3Test);
204 };
205 
206 using Phase3DeathTest = Phase3Test;
207 
TEST_F(Phase3DeathTest,NoLocalLtkDistributionDuringSecureConnections)208 TEST_F(Phase3DeathTest, NoLocalLtkDistributionDuringSecureConnections) {
209   Phase3Args args;
210   args.features.secure_connections = true;
211   args.features.local_key_distribution = KeyDistGen::kEncKey;
212   ASSERT_DEATH_IF_SUPPORTED(NewPhase3(args), ".*Secure Connections.*");
213 }
214 
TEST_F(Phase3DeathTest,NoRemoteLtkDistributionDuringSecureConnections)215 TEST_F(Phase3DeathTest, NoRemoteLtkDistributionDuringSecureConnections) {
216   Phase3Args args;
217   args.features.secure_connections = true;
218   args.features.remote_key_distribution = KeyDistGen::kEncKey;
219   ASSERT_DEATH_IF_SUPPORTED(NewPhase3(args), ".*Secure Connections.*");
220 }
221 
TEST_F(Phase3DeathTest,CannotDistributeKeysOnUnencryptedChannel)222 TEST_F(Phase3DeathTest, CannotDistributeKeysOnUnencryptedChannel) {
223   Phase3Args args;
224   args.le_props = SecurityProperties(SecurityLevel::kNoSecurity,
225                                      kMaxEncryptionKeySize,
226                                      /*secure_connections=*/false);
227   ASSERT_DEATH_IF_SUPPORTED(NewPhase3(args), ".*NoSecurity.*");
228 }
229 
TEST_F(Phase3DeathTest,Phase3MustDistributeKeys)230 TEST_F(Phase3DeathTest, Phase3MustDistributeKeys) {
231   Phase3Args args;
232   args.features.remote_key_distribution = args.features.local_key_distribution =
233       0;
234   // Phase 3 should only be instantiated if there are keys to distribute
235   ASSERT_DEATH_IF_SUPPORTED(NewPhase3(args), ".*HasKeysToDistribute.*");
236 }
237 
238 // The peer sends EDIV and Rand before LTK.
TEST_F(Phase3Test,EncryptionInformationReceivedTwice)239 TEST_F(Phase3Test, EncryptionInformationReceivedTwice) {
240   Phase3Args args;
241   args.features.initiator = true;
242   args.features.remote_key_distribution = KeyDistGen::kEncKey;
243   NewPhase3(args);
244   ByteBufferPtr sent = nullptr;
245   fake_chan()->SetSendCallback(
246       [&](ByteBufferPtr sdu) { sent = std::move(sdu); }, dispatcher());
247   phase_3()->Start();
248   Receive128BitCmd(kEncryptionInformation, UInt128());
249   RunUntilIdle();
250   ASSERT_FALSE(sent);
251   // When we receive the second Encryption Info packet, we should respond with
252   // pairing failed, as a device should only ever send one Encryption Info
253   // packet in Phase 3.
254   const auto kEncryptionInformationCmd =
255       Make128BitCmd(kEncryptionInformation, UInt128());
256   const StaticByteBuffer<PacketSize<ErrorCode>()> kExpectedFailure{
257       kPairingFailed, ErrorCode::kUnspecifiedReason};
258   ASSERT_TRUE(ReceiveAndExpect(kEncryptionInformationCmd, kExpectedFailure));
259   EXPECT_EQ(1, listener()->pairing_error_count());
260   EXPECT_EQ(Error(ErrorCode::kUnspecifiedReason), listener()->last_error());
261 }
262 
263 // The peer sends EDIV and Rand before LTK.
TEST_F(Phase3Test,CentralIdentificationReceivedInWrongOrder)264 TEST_F(Phase3Test, CentralIdentificationReceivedInWrongOrder) {
265   Phase3Args args;
266   args.features.initiator = true;
267   args.features.remote_key_distribution = KeyDistGen::kEncKey;
268   NewPhase3(args);
269   phase_3()->Start();
270 
271   // When we receive the second Encryption Info packet, we should respond with
272   // pairing failed, as a device should only ever send one Encryption Info
273   // packet in Phase 3.
274   StaticByteBuffer<PacketSize<CentralIdentificationParams>()> central_id_packet;
275   PacketWriter p(kCentralIdentification, &central_id_packet);
276   *p.mutable_payload<CentralIdentificationParams>() =
277       Random<CentralIdentificationParams>();
278   const StaticByteBuffer<PacketSize<ErrorCode>()> kExpectedFailure{
279       kPairingFailed, ErrorCode::kUnspecifiedReason};
280   ASSERT_TRUE(ReceiveAndExpect(central_id_packet, kExpectedFailure));
281   EXPECT_EQ(1, listener()->pairing_error_count());
282   EXPECT_EQ(Error(ErrorCode::kUnspecifiedReason), listener()->last_error());
283 }
284 
285 // The peer sends the sample Rand from the specification doc
TEST_F(Phase3Test,ReceiveExampleLtkAborts)286 TEST_F(Phase3Test, ReceiveExampleLtkAborts) {
287   Phase3Args args;
288   args.features.initiator = true;
289   args.features.remote_key_distribution = KeyDistGen::kEncKey;
290   NewPhase3(args);
291   // Sample data from spec V5.0 Vol. 6 Part C Section 1
292   const UInt128 kLtkSample = {0xBF,
293                               0x01,
294                               0xFB,
295                               0x9D,
296                               0x4E,
297                               0xF3,
298                               0xBC,
299                               0x36,
300                               0xD8,
301                               0x74,
302                               0xF5,
303                               0x39,
304                               0x41,
305                               0x38,
306                               0x68,
307                               0x4C};
308 
309   phase_3()->Start();
310 
311   // Pairing should abort when receiving sample LTK data
312   const auto kEncryptionInformationCmd =
313       Make128BitCmd(kEncryptionInformation, kLtkSample);
314   const StaticByteBuffer<PacketSize<ErrorCode>()> kExpectedFailure{
315       kPairingFailed, ErrorCode::kUnspecifiedReason};
316   ASSERT_TRUE(ReceiveAndExpect(kEncryptionInformationCmd, kExpectedFailure));
317 
318   EXPECT_EQ(1, listener()->pairing_error_count());
319   EXPECT_EQ(Error(ErrorCode::kUnspecifiedReason), listener()->last_error());
320 }
321 
322 // The peer sends the sample LTK from the specification doc
TEST_F(Phase3Test,ReceiveExampleRandAborts)323 TEST_F(Phase3Test, ReceiveExampleRandAborts) {
324   Phase3Args args;
325   args.features.initiator = true;
326   args.features.remote_key_distribution = KeyDistGen::kEncKey;
327   NewPhase3(args);
328   // Sample data from spec V5.0 Vol. 6 Part C Section 1
329   const uint64_t kRandSample = 0xABCDEF1234567890;
330   const uint16_t kEDiv = 20;
331 
332   phase_3()->Start();
333 
334   // Pairing should still proceed after accepting the LTK
335   Receive128BitCmd(kEncryptionInformation, UInt128());
336   RunUntilIdle();
337   ASSERT_EQ(0, listener()->pairing_error_count());
338   ASSERT_EQ(0, phase_3_complete_count());
339   // We disallow pairing with spec sample values as using known values for
340   // encryption parameters is inherently unsafe.
341   const auto kCentralIdentificationCmd =
342       MakeCentralIdentification(kRandSample, kEDiv);
343   const StaticByteBuffer<PacketSize<ErrorCode>()> kExpectedFailure{
344       kPairingFailed, ErrorCode::kUnspecifiedReason};
345   ASSERT_TRUE(ReceiveAndExpect(kCentralIdentificationCmd, kExpectedFailure));
346 
347   EXPECT_EQ(1, listener()->pairing_error_count());
348   EXPECT_EQ(Error(ErrorCode::kUnspecifiedReason), listener()->last_error());
349 }
350 
351 // The peer sends us an LTK that is longer than the negotiated maximum key size
TEST_F(Phase3Test,ReceiveTooLongLTK)352 TEST_F(Phase3Test, ReceiveTooLongLTK) {
353   Phase3Args args;
354   args.features.initiator = true;
355   args.features.remote_key_distribution = KeyDistGen::kEncKey;
356   args.features.encryption_key_size = 8;
357   NewPhase3(args);
358   // Ltk with 9 bytes set is longer than the negotiated max of 8 bytes.
359   const UInt128 kTooLongLtk{1, 2, 3, 4, 5, 6, 7, 8, 9};
360   // Pairing should abort when receiving sample LTK data
361   const auto kEncryptionInformationCmd =
362       Make128BitCmd(kEncryptionInformation, kTooLongLtk);
363   const StaticByteBuffer<PacketSize<ErrorCode>()> kExpectedFailure{
364       kPairingFailed, ErrorCode::kInvalidParameters};
365   ASSERT_TRUE(ReceiveAndExpect(kEncryptionInformationCmd, kExpectedFailure));
366   EXPECT_EQ(Error(ErrorCode::kInvalidParameters), listener()->last_error());
367 }
368 
TEST_F(Phase3Test,CentralIdentificationReceivedTwice)369 TEST_F(Phase3Test, CentralIdentificationReceivedTwice) {
370   Phase3Args args;
371   args.features.initiator = true;
372   // The local device must expect both an Encryption and ID key from the peer,
373   // or it would start sending messages after the first Central ID, which is not
374   // the behavior checked in this test.
375   args.features.remote_key_distribution =
376       KeyDistGen::kEncKey | KeyDistGen::kIdKey;
377   NewPhase3(args);
378   constexpr uint16_t kEdiv = 1;
379   constexpr uint64_t kRand = 2;
380 
381   phase_3()->Start();
382   // Send duplicate central identification. If Phase 3 receives multiple Central
383   // Identification commands before completing, it should abort the pairing.
384   Receive128BitCmd(kEncryptionInformation, UInt128());
385   const auto kCentralIdentificationCmd =
386       MakeCentralIdentification(kRand, kEdiv);
387   fake_chan()->Receive(kCentralIdentificationCmd);
388   const StaticByteBuffer<PacketSize<ErrorCode>()> kExpectedFailure{
389       kPairingFailed, ErrorCode::kUnspecifiedReason};
390   ASSERT_TRUE(ReceiveAndExpect(kCentralIdentificationCmd, kExpectedFailure));
391 
392   EXPECT_EQ(1, listener()->pairing_error_count());
393 }
394 
395 // Pairing completes after obtaining encryption information only.
TEST_F(Phase3Test,InitiatorReceivesEncKey)396 TEST_F(Phase3Test, InitiatorReceivesEncKey) {
397   const LTK kExpectedLtk = LTK(kDefaultProperties, kSampleLinkKey);
398   Phase3Args args;
399   args.features.initiator = true;
400   args.features.secure_connections = false;
401   args.features.local_key_distribution = 0u;
402   args.features.remote_key_distribution = KeyDistGen::kEncKey;
403   args.le_props = kExpectedLtk.security();
404   NewPhase3(args);
405   size_t sent_msg_count = 0;
406   fake_chan()->SetSendCallback(
407       [&](ByteBufferPtr /*ignore*/) { sent_msg_count++; }, dispatcher());
408 
409   phase_3()->Start();
410   Receive128BitCmd(kEncryptionInformation, kExpectedLtk.key().value());
411   ReceiveCentralIdentification(kExpectedLtk.key().rand(),
412                                kExpectedLtk.key().ediv());
413   RunUntilIdle();
414 
415   // We were not supposed to distribute any keys in Phase 3
416   EXPECT_EQ(0u, sent_msg_count);
417 
418   // Pairing should have succeeded
419   EXPECT_EQ(0, listener()->pairing_error_count());
420   EXPECT_EQ(1, phase_3_complete_count());
421   ASSERT_TRUE(pairing_data().peer_ltk.has_value());
422   EXPECT_EQ(kExpectedLtk, *pairing_data().peer_ltk);
423 }
424 
TEST_F(Phase3Test,InitiatorSendsLocalIdKey)425 TEST_F(Phase3Test, InitiatorSendsLocalIdKey) {
426   Phase3Args args;
427   args.features.initiator = true;
428   args.features.local_key_distribution = KeyDistGen::kIdKey;
429   args.features.remote_key_distribution = 0u;
430   args.le_props = kDefaultProperties;
431   NewPhase3(args);
432   std::optional<IRK> irk = std::nullopt;
433   std::optional<IdentityAddressInformationParams> identity_addr = std::nullopt;
434   fake_chan()->SetSendCallback(
435       [&](ByteBufferPtr sdu) {
436         ExpectIdentity(std::move(sdu), &irk, &identity_addr);
437       },
438       dispatcher());
439   IdentityInfo kLocalIdentity{.irk = Random<IRK>(),
440                               .address = kSampleDeviceAddress};
441   listener()->set_identity_info(kLocalIdentity);
442   phase_3()->Start();
443   RunUntilIdle();
444 
445   // Local ID Info should be sent to the peer & pairing should be complete
446   ASSERT_TRUE(irk.has_value());
447   ASSERT_EQ(kLocalIdentity.irk, *irk);
448   ASSERT_TRUE(identity_addr.has_value());
449   ASSERT_EQ(kLocalIdentity.address.value(), identity_addr->bd_addr);
450   EXPECT_EQ(1, phase_3_complete_count());
451   // We should have stored no PairingData, as the peer did not send us any
452   ASSERT_FALSE(pairing_data().identity_address.has_value());
453   ASSERT_FALSE(pairing_data().irk.has_value());
454   ASSERT_FALSE(pairing_data().peer_ltk.has_value());
455   ASSERT_FALSE(pairing_data().local_ltk.has_value());
456 }
457 
TEST_F(Phase3Test,InitiatorSendsEncKey)458 TEST_F(Phase3Test, InitiatorSendsEncKey) {
459   Phase3Args args;
460   args.features.initiator = true;
461   args.features.local_key_distribution = KeyDistGen::kEncKey;
462   args.features.remote_key_distribution = 0u;
463   args.le_props = kDefaultProperties;
464   NewPhase3(args);
465   std::optional<EncryptionInformationParams> ltk_bytes = std::nullopt;
466   std::optional<CentralIdentificationParams> central_id = std::nullopt;
467   fake_chan()->SetSendCallback(
468       [&](ByteBufferPtr sdu) {
469         ExpectEncryptionInfo(std::move(sdu), &ltk_bytes, &central_id);
470       },
471       dispatcher());
472   phase_3()->Start();
473   RunUntilIdle();
474 
475   // Local LTK should be sent to the peer & pairing should be complete
476   EXPECT_EQ(1, phase_3_complete_count());
477   ASSERT_TRUE(ltk_bytes.has_value());
478   ASSERT_TRUE(central_id.has_value());
479   ASSERT_TRUE(pairing_data().local_ltk.has_value());
480   EXPECT_EQ(pairing_data().local_ltk->key(),
481             hci_spec::LinkKey(*ltk_bytes, central_id->rand, central_id->ediv));
482 }
483 
TEST_F(Phase3Test,InitiatorReceivesThenSendsEncKey)484 TEST_F(Phase3Test, InitiatorReceivesThenSendsEncKey) {
485   const LTK kExpectedLtk = LTK(kDefaultProperties, kSampleLinkKey);
486   Phase3Args args;
487   args.features.initiator = true;
488   args.features.local_key_distribution = KeyDistGen::kEncKey;
489   args.features.remote_key_distribution = KeyDistGen::kEncKey;
490   args.le_props = kExpectedLtk.security();
491   NewPhase3(args);
492   std::optional<EncryptionInformationParams> ltk_bytes = std::nullopt;
493   std::optional<CentralIdentificationParams> central_id = std::nullopt;
494   fake_chan()->SetSendCallback(
495       [&](ByteBufferPtr sdu) {
496         ExpectEncryptionInfo(std::move(sdu), &ltk_bytes, &central_id);
497       },
498       dispatcher());
499   phase_3()->Start();
500   Receive128BitCmd(kEncryptionInformation, kExpectedLtk.key().value());
501   ReceiveCentralIdentification(kExpectedLtk.key().rand(),
502                                kExpectedLtk.key().ediv());
503   RunUntilIdle();
504 
505   // Local LTK should be sent to the peer & pairing should be complete
506   EXPECT_EQ(0, listener()->pairing_error_count());
507   EXPECT_EQ(1, phase_3_complete_count());
508 
509   ASSERT_TRUE(ltk_bytes.has_value());
510   ASSERT_TRUE(central_id.has_value());
511   ASSERT_TRUE(pairing_data().local_ltk.has_value());
512   EXPECT_EQ(pairing_data().local_ltk->key(),
513             hci_spec::LinkKey(*ltk_bytes, central_id->rand, central_id->ediv));
514 
515   ASSERT_TRUE(pairing_data().peer_ltk.has_value());
516   EXPECT_EQ(kExpectedLtk, *pairing_data().peer_ltk);
517 }
518 
519 // Tests that pairing aborts if the local ID key doesn't exist but we'd already
520 // agreed to send it.
TEST_F(Phase3Test,AbortsIfLocalIdKeyIsRemoved)521 TEST_F(Phase3Test, AbortsIfLocalIdKeyIsRemoved) {
522   Phase3Args args;
523   args.features.local_key_distribution = KeyDistGen::kIdKey;
524   NewPhase3(args);
525   listener()->set_identity_info(std::nullopt);
526 
527   (void)heap_dispatcher().Post(
528       [this](pw::async::Context /*ctx*/, pw::Status status) {
529         if (status.ok()) {
530           phase_3()->Start();
531         }
532       });
533   const StaticByteBuffer<PacketSize<ErrorCode>()> kExpectedFailure{
534       kPairingFailed, ErrorCode::kUnspecifiedReason};
535   ASSERT_TRUE(Expect(kExpectedFailure));
536 
537   EXPECT_EQ(1, listener()->pairing_error_count());
538   EXPECT_EQ(Error(ErrorCode::kUnspecifiedReason), listener()->last_error());
539 }
540 
TEST_F(Phase3Test,IRKReceivedTwice)541 TEST_F(Phase3Test, IRKReceivedTwice) {
542   Phase3Args args;
543   args.features.remote_key_distribution = KeyDistGen::kIdKey;
544   NewPhase3(args);
545 
546   Receive128BitCmd(kIdentityInformation, UInt128());
547   RunUntilIdle();
548 
549   // Should be waiting for identity address.
550   EXPECT_EQ(0, listener()->pairing_error_count());
551   EXPECT_EQ(0, phase_3_complete_count());
552 
553   // Send an IRK again. This should cause pairing to fail.
554   const auto kIdentityInformationCmd =
555       Make128BitCmd(kIdentityInformation, UInt128());
556   const StaticByteBuffer<PacketSize<ErrorCode>()> kExpectedFailure{
557       kPairingFailed, ErrorCode::kUnspecifiedReason};
558   ASSERT_TRUE(ReceiveAndExpect(kIdentityInformationCmd, kExpectedFailure));
559   EXPECT_EQ(1, listener()->pairing_error_count());
560 }
561 
562 // The responder sends its identity address before sending its IRK.
TEST_F(Phase3Test,IdentityAddressReceivedInWrongOrder)563 TEST_F(Phase3Test, IdentityAddressReceivedInWrongOrder) {
564   Phase3Args args;
565   args.features.remote_key_distribution = KeyDistGen::kIdKey;
566   NewPhase3(args);
567 
568   const auto kIdentityAddressCmd = MakeIdentityAddress(kSampleDeviceAddress);
569   const StaticByteBuffer<PacketSize<ErrorCode>()> kExpectedFailure{
570       kPairingFailed, ErrorCode::kUnspecifiedReason};
571   ASSERT_TRUE(ReceiveAndExpect(kIdentityAddressCmd, kExpectedFailure));
572   EXPECT_EQ(1, listener()->pairing_error_count());
573 }
574 
TEST_F(Phase3Test,IdentityAddressReceivedTwice)575 TEST_F(Phase3Test, IdentityAddressReceivedTwice) {
576   Phase3Args args;
577   // We tell Phase 3 to expect the sign key even though we don't yet support it
578   // so that pairing does not complete after receiving the first IdentityAddress
579   args.features.remote_key_distribution =
580       KeyDistGen::kIdKey | KeyDistGen::kSignKey;
581   NewPhase3(args);
582   phase_3()->Start();
583 
584   Receive128BitCmd(kIdentityInformation, UInt128());
585   ReceiveIdentityAddress(kSampleDeviceAddress);
586   RunUntilIdle();
587 
588   // Should not complete as we still have not obtained all the requested keys.
589   EXPECT_EQ(0, listener()->pairing_error_count());
590   EXPECT_EQ(0, phase_3_complete_count());
591 
592   // Send the IdentityAddress again. This should cause pairing to fail.
593   const auto kIdentityAddressCmd = MakeIdentityAddress(kSampleDeviceAddress);
594   const StaticByteBuffer<PacketSize<ErrorCode>()> kExpectedFailure{
595       kPairingFailed, ErrorCode::kUnspecifiedReason};
596   ASSERT_TRUE(ReceiveAndExpect(kIdentityAddressCmd, kExpectedFailure));
597   EXPECT_EQ(1, listener()->pairing_error_count());
598 }
599 
TEST_F(Phase3Test,BadIdentityAddressType)600 TEST_F(Phase3Test, BadIdentityAddressType) {
601   Phase3Args args;
602   args.features.remote_key_distribution = KeyDistGen::kIdKey;
603   NewPhase3(args);
604   phase_3()->Start();
605   // Receive a generic IdentityInfo packet so we are prepared for the Identity
606   // Addr pacekt
607   Receive128BitCmd(kIdentityInformation, UInt128());
608 
609   StaticByteBuffer<PacketSize<IdentityAddressInformationParams>()> addr;
610   PacketWriter writer(kIdentityAddressInformation, &addr);
611   auto* params = writer.mutable_payload<IdentityAddressInformationParams>();
612   // The only valid address type values are 0 or 1 (V5.0 Vol. 3 Part H 3.6.5)
613   const uint8_t kInvalidAddrType = 0xFF;
614   params->type = *reinterpret_cast<const AddressType*>(&kInvalidAddrType);
615   params->bd_addr = DeviceAddressBytes({1, 2, 3, 4, 5, 6});
616 
617   const StaticByteBuffer<PacketSize<ErrorCode>()> kExpectedFailure{
618       kPairingFailed, ErrorCode::kInvalidParameters};
619   ASSERT_TRUE(ReceiveAndExpect(addr, kExpectedFailure));
620   EXPECT_EQ(1, listener()->pairing_error_count());
621 }
622 
623 // Pairing completes after obtaining identity information only.
TEST_F(Phase3Test,InitiatorCompleteWithIdKey)624 TEST_F(Phase3Test, InitiatorCompleteWithIdKey) {
625   const Key kIrk =
626       Key(kDefaultProperties, {1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1, 0});
627   Phase3Args args;
628   args.features.local_key_distribution = 0u;
629   args.features.remote_key_distribution = KeyDistGen::kIdKey;
630   args.le_props = kIrk.security();
631   NewPhase3(args);
632   size_t sent_msg_count = 0;
633   fake_chan()->SetSendCallback(
634       [&](ByteBufferPtr /*ignore*/) { sent_msg_count++; }, dispatcher());
635 
636   phase_3()->Start();
637   Receive128BitCmd(kIdentityInformation, kIrk.value());
638   ReceiveIdentityAddress(kSampleDeviceAddress);
639   RunUntilIdle();
640 
641   // We were not supposed to distribute any keys in Phase 3
642   EXPECT_EQ(0u, sent_msg_count);
643 
644   // Pairing should have succeeded
645   EXPECT_EQ(0, listener()->pairing_error_count());
646   EXPECT_EQ(1, phase_3_complete_count());
647   ASSERT_TRUE(pairing_data().irk.has_value());
648   EXPECT_EQ(kIrk, *pairing_data().irk);
649 }
650 
651 // Pairing completes after obtaining identity information only.
TEST_F(Phase3Test,InitiatorCompleteWithEncAndIdKey)652 TEST_F(Phase3Test, InitiatorCompleteWithEncAndIdKey) {
653   const LTK kExpectedLtk = LTK(kDefaultProperties, kSampleLinkKey);
654   const Key kIrk =
655       Key(kDefaultProperties, {1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1, 0});
656   Phase3Args args;
657   args.features.initiator = true;
658   args.features.secure_connections = false;
659   args.features.local_key_distribution = 0u;
660   args.features.remote_key_distribution =
661       KeyDistGen::kEncKey | KeyDistGen::kIdKey;
662   args.le_props = kExpectedLtk.security();
663   NewPhase3(args);
664   size_t sent_msg_count = 0;
665   fake_chan()->SetSendCallback(
666       [&](ByteBufferPtr /*ignore*/) { sent_msg_count++; }, dispatcher());
667 
668   phase_3()->Start();
669   Receive128BitCmd(kEncryptionInformation, kExpectedLtk.key().value());
670   ReceiveCentralIdentification(kExpectedLtk.key().rand(),
671                                kExpectedLtk.key().ediv());
672   Receive128BitCmd(kIdentityInformation, kIrk.value());
673   ReceiveIdentityAddress(kSampleDeviceAddress);
674   RunUntilIdle();
675 
676   // We were not supposed to distribute any keys in Phase 3
677   EXPECT_EQ(0u, sent_msg_count);
678 
679   // Pairing should have succeeded
680   EXPECT_EQ(0, listener()->pairing_error_count());
681   EXPECT_EQ(1, phase_3_complete_count());
682   ASSERT_TRUE(pairing_data().peer_ltk.has_value());
683   EXPECT_EQ(kExpectedLtk, *pairing_data().peer_ltk);
684   ASSERT_TRUE(pairing_data().irk.has_value());
685   EXPECT_EQ(kIrk, *pairing_data().irk);
686 }
687 
TEST_F(Phase3Test,ResponderLTKDistributionNoRemoteKeys)688 TEST_F(Phase3Test, ResponderLTKDistributionNoRemoteKeys) {
689   Phase3Args args;
690   args.features.initiator = false;
691   args.features.secure_connections = false;
692   args.features.local_key_distribution = KeyDistGen::kEncKey;
693   args.features.remote_key_distribution = 0u;
694   args.le_props = kDefaultProperties;
695   NewPhase3(args);
696   std::optional<EncryptionInformationParams> ltk_bytes = std::nullopt;
697   std::optional<CentralIdentificationParams> central_id = std::nullopt;
698   fake_chan()->SetSendCallback(
699       [&](ByteBufferPtr sdu) {
700         ExpectEncryptionInfo(std::move(sdu), &ltk_bytes, &central_id);
701       },
702       dispatcher());
703   phase_3()->Start();
704   RunUntilIdle();
705   // We should have sent both the Encryption Info and Central ID to the peer
706   ASSERT_TRUE(ltk_bytes.has_value());
707   ASSERT_TRUE(central_id.has_value());
708 
709   // We should have notified the callback with the LTK
710   ASSERT_TRUE(pairing_data().local_ltk.has_value());
711   // The LTK we sent to the peer should match the one we notified callbacks with
712   ASSERT_EQ(hci_spec::LinkKey(*ltk_bytes, central_id->rand, central_id->ediv),
713             pairing_data().local_ltk->key());
714 }
715 
TEST_F(Phase3Test,ResponderAcceptsInitiatorEncKey)716 TEST_F(Phase3Test, ResponderAcceptsInitiatorEncKey) {
717   const LTK kExpectedLtk = LTK(kDefaultProperties, kSampleLinkKey);
718   Phase3Args args;
719   args.features.initiator = false;
720   args.features.secure_connections = false;
721   args.features.local_key_distribution = 0u;
722   args.features.remote_key_distribution = KeyDistGen::kEncKey;
723   args.le_props = kExpectedLtk.security();
724   NewPhase3(args);
725 
726   size_t sent_msg_count = 0;
727   fake_chan()->SetSendCallback(
728       [&](ByteBufferPtr /*ignore*/) { sent_msg_count++; }, dispatcher());
729 
730   phase_3()->Start();
731   Receive128BitCmd(kEncryptionInformation, kExpectedLtk.key().value());
732   ReceiveCentralIdentification(kExpectedLtk.key().rand(),
733                                kExpectedLtk.key().ediv());
734   RunUntilIdle();
735 
736   // We were not supposed to distribute any keys in Phase 3
737   EXPECT_EQ(0u, sent_msg_count);
738 
739   // Pairing should have succeeded
740   EXPECT_EQ(0, listener()->pairing_error_count());
741   EXPECT_EQ(1, phase_3_complete_count());
742   ASSERT_TRUE(pairing_data().peer_ltk.has_value());
743   EXPECT_EQ(kExpectedLtk, *pairing_data().peer_ltk);
744 }
745 
TEST_F(Phase3Test,ResponderLTKDistributionWithRemoteKeys)746 TEST_F(Phase3Test, ResponderLTKDistributionWithRemoteKeys) {
747   const Key kIrk =
748       Key(kDefaultProperties, {1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1, 0});
749   Phase3Args args;
750   args.features.initiator = false;
751   args.features.secure_connections = false;
752   args.features.local_key_distribution = KeyDistGen::kEncKey;
753   args.features.remote_key_distribution = KeyDistGen::kIdKey;
754   args.le_props = kDefaultProperties;
755   NewPhase3(args);
756   std::optional<EncryptionInformationParams> ltk_bytes = std::nullopt;
757   std::optional<CentralIdentificationParams> central_id = std::nullopt;
758   fake_chan()->SetSendCallback(
759       [&](ByteBufferPtr sdu) {
760         ExpectEncryptionInfo(std::move(sdu), &ltk_bytes, &central_id);
761       },
762       dispatcher());
763   phase_3()->Start();
764   RunUntilIdle();
765   // We should have sent the Encryption Info and Central ID & be waiting for the
766   // peer's IRK
767   ASSERT_TRUE(ltk_bytes.has_value());
768   ASSERT_TRUE(central_id.has_value());
769   ASSERT_EQ(0, phase_3_complete_count());
770 
771   const hci_spec::LinkKey kExpectedKey =
772       hci_spec::LinkKey(*ltk_bytes, central_id->rand, central_id->ediv);
773   // Reset ltk_bytes & central_id to verify that we don't send any further
774   // messages
775   ltk_bytes.reset();
776   central_id.reset();
777   Receive128BitCmd(kIdentityInformation, kIrk.value());
778   ReceiveIdentityAddress(kSampleDeviceAddress);
779   RunUntilIdle();
780 
781   ASSERT_FALSE(ltk_bytes.has_value());
782   ASSERT_FALSE(central_id.has_value());
783   // We should have notified the callback with the LTK & IRK
784   ASSERT_TRUE(pairing_data().local_ltk.has_value());
785   ASSERT_TRUE(pairing_data().irk.has_value());
786   // The LTK we sent to the peer should be equal to the one provided to the
787   // callback.
788   ASSERT_EQ(kExpectedKey, pairing_data().local_ltk->key());
789   // The IRK we notified the callback with should match the one we sent.
790   ASSERT_EQ(kIrk, *pairing_data().irk);
791 }
792 
793 // Locally generated ltk length should match max key length specified
TEST_F(Phase3Test,ResponderLocalLTKMaxLength)794 TEST_F(Phase3Test, ResponderLocalLTKMaxLength) {
795   const uint16_t kNegotiatedMaxKeySize = 7;
796   Phase3Args args;
797   args.features.initiator = false;
798   args.features.encryption_key_size = kNegotiatedMaxKeySize;
799   args.features.local_key_distribution = KeyDistGen::kEncKey;
800   args.features.remote_key_distribution = 0u;
801   NewPhase3(args);
802   std::optional<EncryptionInformationParams> ltk_bytes = std::nullopt;
803   std::optional<CentralIdentificationParams> central_id = std::nullopt;
804   fake_chan()->SetSendCallback(
805       [&](ByteBufferPtr sdu) {
806         ExpectEncryptionInfo(std::move(sdu), &ltk_bytes, &central_id);
807       },
808       dispatcher());
809   phase_3()->Start();
810   RunUntilIdle();
811 
812   // Local LTK, EDiv, and Rand should be sent to the peer & listener should be
813   // notified.
814   ASSERT_TRUE(ltk_bytes.has_value());
815   ASSERT_TRUE(central_id.has_value());
816   EXPECT_EQ(1, phase_3_complete_count());
817   EXPECT_EQ(hci_spec::LinkKey(*ltk_bytes, central_id->rand, central_id->ediv),
818             pairing_data().local_ltk->key());
819 
820   // Ensure that most significant (16 - kNegotiatedMaxKeySize) bytes are zero.
821   auto ltk = pairing_data().local_ltk->key().value();
822   for (auto i = kNegotiatedMaxKeySize; i < ltk.size(); i++) {
823     EXPECT_TRUE(ltk[i] == 0);
824   }
825 }
826 
TEST_F(Phase3Test,ResponderLocalIdKeyDistributionWithRemoteKeys)827 TEST_F(Phase3Test, ResponderLocalIdKeyDistributionWithRemoteKeys) {
828   Phase3Args args;
829   args.features.initiator = false;
830   args.features.local_key_distribution = KeyDistGen::kIdKey;
831   args.features.remote_key_distribution = KeyDistGen::kIdKey;
832   args.le_props = kDefaultProperties;
833   NewPhase3(args);
834   std::optional<IRK> irk = std::nullopt;
835   std::optional<IdentityAddressInformationParams> identity_addr = std::nullopt;
836   fake_chan()->SetSendCallback(
837       [&](ByteBufferPtr sdu) {
838         ExpectIdentity(std::move(sdu), &irk, &identity_addr);
839       },
840       dispatcher());
841   IdentityInfo kLocalIdentity{.irk = Random<IRK>(),
842                               .address = kSampleDeviceAddress};
843   listener()->set_identity_info(kLocalIdentity);
844   phase_3()->Start();
845   RunUntilIdle();
846 
847   // Local ID Info should be sent to the peer & we should be waiting for the
848   // peer's ID info
849   ASSERT_TRUE(irk.has_value());
850   ASSERT_TRUE(identity_addr.has_value());
851   EXPECT_EQ(0, phase_3_complete_count());
852   EXPECT_EQ(kLocalIdentity.irk, *irk);
853   EXPECT_EQ(kLocalIdentity.address.value(), identity_addr->bd_addr);
854 
855   // Ensure that most significant (16 - kNegotiatedMaxKeySize) bytes are zero.
856   const Key kIrk(kDefaultProperties, Random<UInt128>());
857   const DeviceAddress kPeerAddr(DeviceAddress::Type::kLEPublic, {2});
858   Receive128BitCmd(kIdentityInformation, kIrk.value());
859   ReceiveIdentityAddress(kPeerAddr);
860   RunUntilIdle();
861 
862   // Pairing should be complete with the peer's identity information.
863   ASSERT_EQ(1, phase_3_complete_count());
864   ASSERT_TRUE(pairing_data().irk.has_value());
865   EXPECT_EQ(kIrk, *pairing_data().irk);
866   ASSERT_TRUE(pairing_data().identity_address.has_value());
867   EXPECT_EQ(kPeerAddr, *pairing_data().identity_address);
868 }
869 
TEST_F(Phase3Test,ReceivePairingFailed)870 TEST_F(Phase3Test, ReceivePairingFailed) {
871   Phase3Args args;
872   args.features.remote_key_distribution = KeyDistGen::kEncKey;
873   NewPhase3(args);
874   phase_3()->Start();
875   fake_chan()->Receive(
876       StaticByteBuffer{kPairingFailed, ErrorCode::kPairingNotSupported});
877   RunUntilIdle();
878 
879   ASSERT_EQ(1, listener()->pairing_error_count());
880   EXPECT_EQ(Error(ErrorCode::kPairingNotSupported), listener()->last_error());
881 }
882 
TEST_F(Phase3Test,MalformedCommand)883 TEST_F(Phase3Test, MalformedCommand) {
884   Phase3Args args;
885   args.features.remote_key_distribution = KeyDistGen::kEncKey;
886   NewPhase3(args);
887   phase_3()->Start();
888   // The kEncryptionInformation packet is expected to have a 16 byte payload,
889   // not 1 byte.
890   const StaticByteBuffer<PacketSize<ErrorCode>()> kExpectedFailure{
891       kPairingFailed, ErrorCode::kInvalidParameters};
892   ReceiveAndExpect(StaticByteBuffer{kEncryptionInformation, 0x01},
893                    kExpectedFailure);
894 
895   ASSERT_EQ(1, listener()->pairing_error_count());
896   EXPECT_EQ(Error(ErrorCode::kInvalidParameters), listener()->last_error());
897 }
898 
TEST_F(Phase3Test,UnexpectedOpCode)899 TEST_F(Phase3Test, UnexpectedOpCode) {
900   phase_3()->Start();
901   // The Security Request is not expected during Phase 3.
902   const StaticByteBuffer<PacketSize<ErrorCode>()> kExpectedFailure{
903       kPairingFailed, ErrorCode::kUnspecifiedReason};
904   ReceiveAndExpect(StaticByteBuffer{kSecurityRequest, AuthReq::kBondingFlag},
905                    kExpectedFailure);
906   ASSERT_EQ(1, listener()->pairing_error_count());
907   EXPECT_EQ(Error(ErrorCode::kUnspecifiedReason), listener()->last_error());
908 }
909 
TEST_F(Phase3Test,BrEdrInitiatorIdKeysExchangedSuccessfully)910 TEST_F(Phase3Test, BrEdrInitiatorIdKeysExchangedSuccessfully) {
911   const Key kPeerIrk =
912       Key(kDefaultProperties, {1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1, 0});
913   Phase3Args args;
914   args.features.initiator = true;
915   args.features.local_key_distribution =
916       KeyDistGen::kIdKey | KeyDistGen::kEncKey;
917   args.features.remote_key_distribution =
918       KeyDistGen::kIdKey | KeyDistGen::kEncKey;
919   args.le_props = kDefaultProperties;
920   NewPhase3(args, LinkType::kACL);
921   std::optional<IRK> irk = std::nullopt;
922   std::optional<IdentityAddressInformationParams> identity_addr = std::nullopt;
923   fake_chan()->SetSendCallback(
924       [&](ByteBufferPtr sdu) {
925         ExpectIdentity(std::move(sdu), &irk, &identity_addr);
926       },
927       dispatcher());
928   IdentityInfo kLocalIdentity{.irk = Random<IRK>(),
929                               .address = kSampleDeviceAddress};
930   listener()->set_identity_info(kLocalIdentity);
931   phase_3()->Start();
932   Receive128BitCmd(kIdentityInformation, kPeerIrk.value());
933   ReceiveIdentityAddress(kSampleDeviceAddress);
934   RunUntilIdle();
935 
936   EXPECT_EQ(1, phase_3_complete_count());
937   ASSERT_TRUE(irk.has_value());
938   ASSERT_EQ(kLocalIdentity.irk, *irk);
939   ASSERT_TRUE(identity_addr.has_value());
940   ASSERT_EQ(kLocalIdentity.address.value(), identity_addr->bd_addr);
941   ASSERT_TRUE(pairing_data().irk.has_value());
942   EXPECT_EQ(kPeerIrk, *pairing_data().irk);
943   ASSERT_TRUE(pairing_data().identity_address.has_value());
944   EXPECT_EQ(kSampleDeviceAddress, *pairing_data().identity_address);
945 }
946 
TEST_F(Phase3Test,BrEdrResponderIdKeysExchangedSuccessfully)947 TEST_F(Phase3Test, BrEdrResponderIdKeysExchangedSuccessfully) {
948   Phase3Args args;
949   args.features.initiator = false;
950   args.features.local_key_distribution =
951       KeyDistGen::kIdKey | KeyDistGen::kEncKey;
952   args.features.remote_key_distribution =
953       KeyDistGen::kIdKey | KeyDistGen::kEncKey;
954   args.le_props = kDefaultProperties;
955   NewPhase3(args, LinkType::kACL);
956   std::optional<IRK> irk = std::nullopt;
957   std::optional<IdentityAddressInformationParams> identity_addr = std::nullopt;
958   fake_chan()->SetSendCallback(
959       [&](ByteBufferPtr sdu) {
960         ExpectIdentity(std::move(sdu), &irk, &identity_addr);
961       },
962       dispatcher());
963   IdentityInfo kLocalIdentity{.irk = Random<IRK>(),
964                               .address = kSampleDeviceAddress};
965   listener()->set_identity_info(kLocalIdentity);
966   phase_3()->Start();
967   RunUntilIdle();
968 
969   // Local ID Info should be sent to the peer & we should be waiting for the
970   // peer's ID info
971   ASSERT_TRUE(irk.has_value());
972   ASSERT_TRUE(identity_addr.has_value());
973   EXPECT_EQ(0, phase_3_complete_count());
974   EXPECT_EQ(kLocalIdentity.irk, *irk);
975   EXPECT_EQ(kLocalIdentity.address.value(), identity_addr->bd_addr);
976 
977   const Key kIrk(kDefaultProperties, Random<UInt128>());
978   const DeviceAddress kPeerAddr(DeviceAddress::Type::kLEPublic, {2});
979   Receive128BitCmd(kIdentityInformation, kIrk.value());
980   ReceiveIdentityAddress(kPeerAddr);
981   RunUntilIdle();
982 
983   // Pairing should be complete with the peer's identity information.
984   ASSERT_EQ(1, phase_3_complete_count());
985   ASSERT_TRUE(pairing_data().irk.has_value());
986   EXPECT_EQ(kIrk, *pairing_data().irk);
987   ASSERT_TRUE(pairing_data().identity_address.has_value());
988   EXPECT_EQ(kPeerAddr, *pairing_data().identity_address);
989 }
990 
991 }  // namespace
992 }  // namespace bt::sm
993