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