1 /****************************************************************************** 2 * 3 * Copyright 2019 The Android Open Source Project 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at: 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 ******************************************************************************/ 18 19 #pragma once 20 21 #include <array> 22 #include <chrono> 23 #include <condition_variable> 24 #include <mutex> 25 #include <optional> 26 #include <queue> 27 #include <thread> 28 #include <variant> 29 30 #include "common/bind.h" 31 #include "crypto_toolbox/crypto_toolbox.h" 32 #include "hci/hci_packets.h" 33 #include "hci/le_security_interface.h" 34 #include "packet/packet_view.h" 35 #include "security/ecdh_keys.h" 36 #include "security/initial_informations.h" 37 #include "security/pairing_failure.h" 38 #include "security/smp_packets.h" 39 #include "security/ui.h" 40 41 // Code generated by PDL does not allow us ot do || and && operations on bits 42 // efficiently. Use those masks on fields requiring them until this is solved 43 constexpr uint8_t AuthReqMaskBondingFlag = 0x01; 44 constexpr uint8_t AuthReqMaskMitm = 0x04; 45 constexpr uint8_t AuthReqMaskSc = 0x08; 46 constexpr uint8_t AuthReqMaskKeypress = 0x10; 47 constexpr uint8_t AuthReqMaskCt2 = 0x20; 48 49 constexpr uint8_t KeyMaskEnc = 0x01; 50 constexpr uint8_t KeyMaskId = 0x02; 51 constexpr uint8_t KeyMaskSign = 0x04; 52 constexpr uint8_t KeyMaskLink = 0x08; 53 54 using bluetooth::hci::EncryptionChangeView; 55 using bluetooth::hci::EncryptionKeyRefreshCompleteView; 56 57 namespace bluetooth { 58 namespace security { 59 60 using crypto_toolbox::Octet16; 61 62 /* This class represents an event send from other subsystems into SMP Pairing Handler, 63 * i.e. user request from the UI, L2CAP or HCI interaction */ 64 class PairingEvent { 65 public: 66 enum TYPE { EXIT, L2CAP, HCI_EVENT, UI }; 67 TYPE type; 68 69 std::optional<CommandView> l2cap_packet; 70 71 std::optional<hci::EventView> hci_event; 72 73 enum UI_ACTION_TYPE { PAIRING_ACCEPTED, CONFIRM_YESNO, PASSKEY }; 74 UI_ACTION_TYPE ui_action; 75 uint32_t ui_value; 76 PairingEvent(TYPE type)77 PairingEvent(TYPE type) : type(type) {} PairingEvent(CommandView l2cap_packet)78 PairingEvent(CommandView l2cap_packet) : type(L2CAP), l2cap_packet(l2cap_packet) {} PairingEvent(UI_ACTION_TYPE ui_action,uint32_t ui_value)79 PairingEvent(UI_ACTION_TYPE ui_action, uint32_t ui_value) : type(UI), ui_action(ui_action), ui_value(ui_value) {} PairingEvent(hci::EventView hci_event)80 PairingEvent(hci::EventView hci_event) : type(HCI_EVENT), hci_event(hci_event) {} 81 }; 82 83 constexpr int SMP_TIMEOUT = 30; 84 85 using CommandViewOrFailure = std::variant<CommandView, PairingFailure>; 86 using Phase1Result = std::pair<PairingRequestView /* pairning_request*/, PairingResponseView /* pairing_response */>; 87 using Phase1ResultOrFailure = std::variant<PairingFailure, Phase1Result>; 88 using KeyExchangeResult = 89 std::tuple<EcdhPublicKey /* PKa */, EcdhPublicKey /* PKb */, std::array<uint8_t, 32> /*dhkey*/>; 90 using Stage1Result = std::tuple<Octet16, Octet16, Octet16, Octet16>; 91 using Stage1ResultOrFailure = std::variant<PairingFailure, Stage1Result>; 92 using Stage2ResultOrFailure = std::variant<PairingFailure, Octet16 /* LTK */>; 93 using DistributedKeysOrFailure = std::variant<PairingFailure, DistributedKeys, std::monostate>; 94 95 using LegacyStage1Result = Octet16 /*TK*/; 96 using LegacyStage1ResultOrFailure = std::variant<PairingFailure, LegacyStage1Result>; 97 using StkOrFailure = std::variant<PairingFailure, Octet16 /* STK */>; 98 99 /* PairingHandlerLe takes care of the Pairing process. Pairing is strictly defined 100 * exchange of messages and UI interactions, divided into PHASES. 101 * 102 * Each PairingHandlerLe have a thread executing |PairingMain| method. Thread is 103 * blocked when waiting for UI/L2CAP/HCI interactions, and moves through all the 104 * phases. 105 */ 106 class PairingHandlerLe { 107 public: 108 // This is the phase of pairing as defined in BT Spec (with exception of 109 // accept prompt) 110 // * ACCEPT_PROMPT - we're waiting for the user to accept remotely initiated pairing 111 // * PHASE1 - feature exchange 112 // * PHASE2 - authentication 113 // * PHASE3 - key exchange 114 enum PAIRING_PHASE { ACCEPT_PROMPT, PHASE1, PHASE2, PHASE3 }; 115 PAIRING_PHASE phase; 116 117 // All the knowledge to initiate the pairing process must be passed into this function PairingHandlerLe(PAIRING_PHASE phase,InitialInformations informations)118 PairingHandlerLe(PAIRING_PHASE phase, InitialInformations informations) 119 : phase(phase), queue_guard(), thread_(&PairingHandlerLe::PairingMain, this, informations) {} 120 ~PairingHandlerLe()121 ~PairingHandlerLe() { 122 SendExitSignal(); 123 // we need ot check if thread is joinable, because tests call join form 124 // within WaitUntilPairingFinished 125 if (thread_.joinable()) thread_.join(); 126 } 127 128 void PairingMain(InitialInformations i); 129 130 Phase1ResultOrFailure ExchangePairingFeature(const InitialInformations& i); 131 SendL2capPacket(const InitialInformations & i,std::unique_ptr<bluetooth::security::CommandBuilder> command)132 void SendL2capPacket(const InitialInformations& i, std::unique_ptr<bluetooth::security::CommandBuilder> command) { 133 i.proper_l2cap_interface->Enqueue(std::move(command), i.l2cap_handler); 134 } 135 SendHciLeStartEncryption(const InitialInformations & i,uint16_t conn_handle,const std::array<uint8_t,8> & rand,const uint16_t & ediv,const Octet16 & ltk)136 void SendHciLeStartEncryption(const InitialInformations& i, uint16_t conn_handle, const std::array<uint8_t, 8>& rand, 137 const uint16_t& ediv, const Octet16& ltk) { 138 i.le_security_interface->EnqueueCommand(hci::LeStartEncryptionBuilder::Create(conn_handle, rand, ediv, ltk), 139 i.l2cap_handler->BindOnce([](hci::CommandStatusView) { 140 // TODO: handle command status. It's important - can show we are not 141 // connected any more. 142 143 // TODO: if anything useful must be done there, use some sort of proper 144 // handler, wait/notify, and execute on the handler thread 145 })); 146 } 147 SendHciLeLongTermKeyReply(const InitialInformations & i,uint16_t conn_handle,const Octet16 & ltk)148 void SendHciLeLongTermKeyReply(const InitialInformations& i, uint16_t conn_handle, const Octet16& ltk) { 149 i.le_security_interface->EnqueueCommand( 150 hci::LeLongTermKeyRequestReplyBuilder::Create(conn_handle, ltk), 151 i.l2cap_handler->BindOnce([](hci::CommandCompleteView) {})); 152 } 153 WaitEncryptionChanged()154 std::variant<PairingFailure, EncryptionChangeView, EncryptionKeyRefreshCompleteView> WaitEncryptionChanged() { 155 PairingEvent e = WaitForEvent(); 156 if (e.type != PairingEvent::HCI_EVENT) return PairingFailure("Was expecting HCI event but received something else"); 157 158 if (!e.hci_event->IsValid()) return PairingFailure("Received invalid HCI event"); 159 160 if (e.hci_event->GetEventCode() == hci::EventCode::ENCRYPTION_CHANGE) { 161 EncryptionChangeView enc_chg_packet = EncryptionChangeView::Create(*e.hci_event); 162 if (!enc_chg_packet.IsValid()) { 163 return PairingFailure("Invalid Encryption Change packet received"); 164 } 165 return enc_chg_packet; 166 } 167 168 if (e.hci_event->GetEventCode() == hci::EventCode::ENCRYPTION_KEY_REFRESH_COMPLETE) { 169 hci::EncryptionKeyRefreshCompleteView enc_packet = EncryptionKeyRefreshCompleteView::Create(*e.hci_event); 170 if (!enc_packet.IsValid()) { 171 return PairingFailure("Invalid Key Refresh packet received"); 172 } 173 return enc_packet; 174 } 175 176 return PairingFailure("Was expecting Encryption Change or Key Refresh Complete but received something else"); 177 } 178 WaitLeLongTermKeyRequest()179 std::variant<PairingFailure, hci::LeLongTermKeyRequestView> WaitLeLongTermKeyRequest() { 180 PairingEvent e = WaitForEvent(); 181 if (e.type != PairingEvent::HCI_EVENT) return PairingFailure("Was expecting HCI event but received something else"); 182 183 if (!e.hci_event->IsValid()) return PairingFailure("Received invalid HCI event"); 184 185 if (e.hci_event->GetEventCode() != hci::EventCode::LE_META_EVENT) return PairingFailure("Was expecting LE event"); 186 187 hci::LeMetaEventView le_event = hci::LeMetaEventView::Create(*e.hci_event); 188 if (!le_event.IsValid()) { 189 return PairingFailure("Invalid LE Event received"); 190 } 191 192 if (le_event.GetSubeventCode() != hci::SubeventCode::LONG_TERM_KEY_REQUEST) { 193 return PairingFailure("Was expecting Long Term Key Request"); 194 } 195 196 hci::LeLongTermKeyRequestView ltk_req_packet = hci::LeLongTermKeyRequestView::Create(le_event); 197 if (!ltk_req_packet.IsValid()) { 198 return PairingFailure("Invalid LE Long Term Key Request received"); 199 } 200 201 return ltk_req_packet; 202 } 203 IAmCentral(const InitialInformations & i)204 inline bool IAmCentral(const InitialInformations& i) { 205 return i.my_role == hci::Role::CENTRAL; 206 } 207 208 /* This function generates data that should be passed to remote device, except 209 the private key. */ 210 static MyOobData GenerateOobData(); 211 212 std::variant<PairingFailure, KeyExchangeResult> ExchangePublicKeys(const InitialInformations& i, 213 OobDataFlag remote_have_oob_data); 214 215 Stage1ResultOrFailure DoSecureConnectionsStage1(const InitialInformations& i, const EcdhPublicKey& PKa, 216 const EcdhPublicKey& PKb, const PairingRequestView& pairing_request, 217 const PairingResponseView& pairing_response); 218 219 Stage1ResultOrFailure SecureConnectionsNumericComparison(const InitialInformations& i, const EcdhPublicKey& PKa, 220 const EcdhPublicKey& PKb); 221 222 Stage1ResultOrFailure SecureConnectionsJustWorks(const InitialInformations& i, const EcdhPublicKey& PKa, 223 const EcdhPublicKey& PKb); 224 225 Stage1ResultOrFailure SecureConnectionsPasskeyEntry(const InitialInformations& i, const EcdhPublicKey& PKa, 226 const EcdhPublicKey& PKb, IoCapability my_iocaps, 227 IoCapability remote_iocaps); 228 229 Stage1ResultOrFailure SecureConnectionsOutOfBand(const InitialInformations& i, const EcdhPublicKey& Pka, 230 const EcdhPublicKey& Pkb, OobDataFlag my_oob_flag, 231 OobDataFlag remote_oob_flag); 232 233 Stage2ResultOrFailure DoSecureConnectionsStage2(const InitialInformations& i, const EcdhPublicKey& PKa, 234 const EcdhPublicKey& PKb, const PairingRequestView& pairing_request, 235 const PairingResponseView& pairing_response, 236 const Stage1Result stage1result, 237 const std::array<uint8_t, 32>& dhkey); 238 239 DistributedKeysOrFailure DistributeKeys(const InitialInformations& i, const PairingResponseView& pairing_response, 240 bool isSecureConnections); 241 242 DistributedKeysOrFailure ReceiveKeys(const uint8_t& keys_i_receive); 243 244 LegacyStage1ResultOrFailure DoLegacyStage1(const InitialInformations& i, const PairingRequestView& pairing_request, 245 const PairingResponseView& pairing_response); 246 LegacyStage1ResultOrFailure LegacyOutOfBand(const InitialInformations& i); 247 LegacyStage1ResultOrFailure LegacyJustWorks(); 248 LegacyStage1ResultOrFailure LegacyPasskeyEntry(const InitialInformations& i, const IoCapability& my_iocaps, 249 const IoCapability& remote_iocaps); 250 StkOrFailure DoLegacyStage2(const InitialInformations& i, const PairingRequestView& pairing_request, 251 const PairingResponseView& pairing_response, const Octet16& tk); 252 253 void SendKeys(const InitialInformations& i, const uint8_t& keys_i_send, Octet16 ltk, uint16_t ediv, 254 std::array<uint8_t, 8> rand, Octet16 irk, Address identity_address, AddrType identity_addres_type, 255 Octet16 signature_key); 256 257 /* This can be called from any thread to immediately finish the pairing in progress. */ SendExitSignal()258 void SendExitSignal() { 259 { 260 std::unique_lock<std::mutex> lock(queue_guard); 261 queue.push(PairingEvent(PairingEvent::EXIT)); 262 } 263 pairing_thread_blocker_.notify_one(); 264 } 265 266 /* SMP Command received from remote device */ OnCommandView(CommandView packet)267 void OnCommandView(CommandView packet) { 268 { 269 std::unique_lock<std::mutex> lock(queue_guard); 270 queue.push(PairingEvent(std::move(packet))); 271 } 272 pairing_thread_blocker_.notify_one(); 273 } 274 275 /* SMP Command received from remote device */ OnHciEvent(hci::EventView hci_event)276 void OnHciEvent(hci::EventView hci_event) { 277 { 278 std::unique_lock<std::mutex> lock(queue_guard); 279 queue.push(PairingEvent(std::move(hci_event))); 280 } 281 pairing_thread_blocker_.notify_one(); 282 } 283 284 /* Interaction from user */ OnUiAction(PairingEvent::UI_ACTION_TYPE ui_action,uint32_t ui_value)285 void OnUiAction(PairingEvent::UI_ACTION_TYPE ui_action, uint32_t ui_value) { 286 { 287 std::unique_lock<std::mutex> lock(queue_guard); 288 queue.push(PairingEvent(ui_action, ui_value)); 289 } 290 pairing_thread_blocker_.notify_one(); 291 } 292 293 /* HCI LE event received from remote device */ OnHciLeEvent(hci::LeMetaEventView hci_event)294 void OnHciLeEvent(hci::LeMetaEventView hci_event) { 295 { 296 std::unique_lock<std::mutex> lock(queue_guard); 297 queue.push(PairingEvent(std::move(hci_event))); 298 } 299 pairing_thread_blocker_.notify_one(); 300 } 301 302 /* Blocks the pairing process until some external interaction, or timeout happens */ WaitForEvent()303 PairingEvent WaitForEvent() { 304 std::unique_lock<std::mutex> lock(queue_guard); 305 do { 306 if (!queue.empty()) { 307 PairingEvent e = queue.front(); 308 queue.pop(); 309 return e; 310 } 311 // This releases the lock while blocking. 312 if (pairing_thread_blocker_.wait_for(lock, std::chrono::seconds(SMP_TIMEOUT)) == std::cv_status::timeout) { 313 return PairingEvent(PairingEvent::EXIT); 314 } 315 316 } while (true); 317 } 318 WaitUiPairingAccept()319 std::optional<PairingEvent> WaitUiPairingAccept() { 320 PairingEvent e = WaitForEvent(); 321 if (e.type == PairingEvent::UI && 322 e.ui_action == PairingEvent::PAIRING_ACCEPTED) { 323 return e; 324 } else { 325 return std::nullopt; 326 } 327 } 328 WaitUiConfirmYesNo()329 std::optional<PairingEvent> WaitUiConfirmYesNo() { 330 PairingEvent e = WaitForEvent(); 331 if (e.type == PairingEvent::UI && 332 e.ui_action == PairingEvent::CONFIRM_YESNO) { 333 return e; 334 } else { 335 return std::nullopt; 336 } 337 } 338 WaitUiPasskey()339 std::optional<PairingEvent> WaitUiPasskey() { 340 PairingEvent e = WaitForEvent(); 341 342 // It's possible to receive PAIRING_CONFIRM from remote device while waiting for the passkey. 343 // Store it until it's needed. 344 if (e.type == PairingEvent::L2CAP) { 345 auto l2cap_packet = e.l2cap_packet.value(); 346 if (!l2cap_packet.IsValid()) { 347 LOG_WARN("Malformed L2CAP packet received!"); 348 return std::nullopt; 349 } 350 351 const auto& received_code = l2cap_packet.GetCode(); 352 if (received_code != Code::PAIRING_CONFIRM) { 353 LOG_WARN("Was waiting for passkey, received bad packet instead!"); 354 return std::nullopt; 355 } 356 357 auto pkt = PairingConfirmView::Create(l2cap_packet); 358 if (!pkt.IsValid()) { 359 LOG_WARN("Malformed PAIRING_CONFIRM packet"); 360 return std::nullopt; 361 } 362 363 cached_pariring_confirm_view = std::make_unique<PairingConfirmView>(pkt); 364 e = WaitForEvent(); 365 } 366 367 if (e.type == PairingEvent::UI && 368 e.ui_action == PairingEvent::PASSKEY) { 369 return e; 370 } else { 371 return std::nullopt; 372 } 373 } 374 375 template <Code C> 376 struct CodeToPacketView; 377 template <> 378 struct CodeToPacketView<Code::PAIRING_REQUEST> { 379 typedef PairingRequestView type; 380 }; 381 template <> 382 struct CodeToPacketView<Code::PAIRING_RESPONSE> { 383 typedef PairingResponseView type; 384 }; 385 template <> 386 struct CodeToPacketView<Code::PAIRING_CONFIRM> { 387 typedef PairingConfirmView type; 388 }; 389 template <> 390 struct CodeToPacketView<Code::PAIRING_RANDOM> { 391 typedef PairingRandomView type; 392 }; 393 template <> 394 struct CodeToPacketView<Code::PAIRING_FAILED> { 395 typedef PairingFailedView type; 396 }; 397 template <> 398 struct CodeToPacketView<Code::ENCRYPTION_INFORMATION> { 399 typedef EncryptionInformationView type; 400 }; 401 template <> 402 struct CodeToPacketView<Code::CENTRAL_IDENTIFICATION> { 403 typedef CentralIdentificationView type; 404 }; 405 template <> 406 struct CodeToPacketView<Code::IDENTITY_INFORMATION> { 407 typedef IdentityInformationView type; 408 }; 409 template <> 410 struct CodeToPacketView<Code::IDENTITY_ADDRESS_INFORMATION> { 411 typedef IdentityAddressInformationView type; 412 }; 413 template <> 414 struct CodeToPacketView<Code::SIGNING_INFORMATION> { 415 typedef SigningInformationView type; 416 }; 417 template <> 418 struct CodeToPacketView<Code::SECURITY_REQUEST> { 419 typedef SecurityRequestView type; 420 }; 421 template <> 422 struct CodeToPacketView<Code::PAIRING_PUBLIC_KEY> { 423 typedef PairingPublicKeyView type; 424 }; 425 template <> 426 struct CodeToPacketView<Code::PAIRING_DH_KEY_CHECK> { 427 typedef PairingDhKeyCheckView type; 428 }; 429 template <> 430 struct CodeToPacketView<Code::PAIRING_KEYPRESS_NOTIFICATION> { 431 typedef PairingKeypressNotificationView type; 432 }; 433 434 template <Code CODE> 435 std::variant<typename CodeToPacketView<CODE>::type, PairingFailure> WaitPacket() { 436 PairingEvent e = WaitForEvent(); 437 switch (e.type) { 438 case PairingEvent::EXIT: 439 return PairingFailure( 440 /*FROM_HERE,*/ "Was expecting L2CAP Packet " + CodeText(CODE) + ", but received EXIT instead"); 441 442 case PairingEvent::HCI_EVENT: 443 return PairingFailure( 444 /*FROM_HERE,*/ "Was expecting L2CAP Packet " + CodeText(CODE) + ", but received HCI_EVENT instead"); 445 446 case PairingEvent::UI: 447 return PairingFailure( 448 /*FROM_HERE,*/ "Was expecting L2CAP Packet " + CodeText(CODE) + ", but received UI instead"); 449 450 case PairingEvent::L2CAP: { 451 auto l2cap_packet = e.l2cap_packet.value(); 452 if (!l2cap_packet.IsValid()) { 453 return PairingFailure("Malformed L2CAP packet received!"); 454 } 455 456 const auto& received_code = l2cap_packet.GetCode(); 457 if (received_code != CODE) { 458 if (received_code == Code::PAIRING_FAILED) { 459 auto pkt = PairingFailedView::Create(l2cap_packet); 460 if (!pkt.IsValid()) return PairingFailure("Malformed " + CodeText(CODE) + " packet"); 461 return PairingFailure(/*FROM_HERE,*/ 462 "Was expecting " + CodeText(CODE) + ", but received PAIRING_FAILED instead", 463 pkt.GetReason()); 464 } 465 466 return PairingFailure(/*FROM_HERE,*/ 467 "Was expecting " + CodeText(CODE) + ", but received " + CodeText(received_code) + 468 " instead", 469 received_code); 470 } 471 472 auto pkt = CodeToPacketView<CODE>::type::Create(l2cap_packet); 473 if (!pkt.IsValid()) return PairingFailure("Malformed " + CodeText(CODE) + " packet"); 474 return pkt; 475 } 476 } 477 } 478 479 auto WaitPairingRequest() { 480 return WaitPacket<Code::PAIRING_REQUEST>(); 481 } 482 483 auto WaitPairingResponse() { 484 return WaitPacket<Code::PAIRING_RESPONSE>(); 485 } 486 487 std::variant<bluetooth::security::PairingConfirmView, bluetooth::security::PairingFailure> WaitPairingConfirm() { 488 if (cached_pariring_confirm_view) { 489 PairingConfirmView pkt = *cached_pariring_confirm_view; 490 cached_pariring_confirm_view.release(); 491 return pkt; 492 } 493 return WaitPacket<Code::PAIRING_CONFIRM>(); 494 } 495 496 auto WaitPairingRandom() { 497 return WaitPacket<Code::PAIRING_RANDOM>(); 498 } 499 500 auto WaitPairingPublicKey() { 501 return WaitPacket<Code::PAIRING_PUBLIC_KEY>(); 502 } 503 504 auto WaitPairingDHKeyCheck() { 505 return WaitPacket<Code::PAIRING_DH_KEY_CHECK>(); 506 } 507 508 auto WaitEncryptionInformationRequest() { 509 return WaitPacket<Code::ENCRYPTION_INFORMATION>(); 510 } 511 512 auto WaitEncryptionInformation() { 513 return WaitPacket<Code::ENCRYPTION_INFORMATION>(); 514 } 515 516 auto WaitCentralIdentification() { 517 return WaitPacket<Code::CENTRAL_IDENTIFICATION>(); 518 } 519 520 auto WaitIdentityInformation() { 521 return WaitPacket<Code::IDENTITY_INFORMATION>(); 522 } 523 524 auto WaitIdentityAddressInformation() { 525 return WaitPacket<Code::IDENTITY_ADDRESS_INFORMATION>(); 526 } 527 528 auto WaitSigningInformation() { 529 return WaitPacket<Code::SIGNING_INFORMATION>(); 530 } 531 532 /* This is just for test, never use in production code! */ 533 void WaitUntilPairingFinished() { 534 thread_.join(); 535 } 536 537 private: 538 std::condition_variable pairing_thread_blocker_; 539 540 std::mutex queue_guard; 541 std::queue<PairingEvent> queue; 542 543 std::thread thread_; 544 545 // holds pairing_confirm, if received out of order 546 std::unique_ptr<PairingConfirmView> cached_pariring_confirm_view; 547 }; 548 } // namespace security 549 } // namespace bluetooth 550