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::EventPacketView> 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::EventPacketView hci_event)80 PairingEvent(hci::EventPacketView 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 WaitEncryptionChanged()148 std::variant<PairingFailure, EncryptionChangeView, EncryptionKeyRefreshCompleteView> WaitEncryptionChanged() { 149 PairingEvent e = WaitForEvent(); 150 if (e.type != PairingEvent::HCI_EVENT) return PairingFailure("Was expecting HCI event but received something else"); 151 152 if (!e.hci_event->IsValid()) return PairingFailure("Received invalid HCI event"); 153 154 if (e.hci_event->GetEventCode() == hci::EventCode::ENCRYPTION_CHANGE) { 155 EncryptionChangeView enc_chg_packet = EncryptionChangeView::Create(*e.hci_event); 156 if (!enc_chg_packet.IsValid()) { 157 return PairingFailure("Invalid Encryption Change packet received"); 158 } 159 return enc_chg_packet; 160 } 161 162 if (e.hci_event->GetEventCode() == hci::EventCode::ENCRYPTION_KEY_REFRESH_COMPLETE) { 163 hci::EncryptionKeyRefreshCompleteView enc_packet = EncryptionKeyRefreshCompleteView::Create(*e.hci_event); 164 if (!enc_packet.IsValid()) { 165 return PairingFailure("Invalid Key Refresh packet received"); 166 } 167 return enc_packet; 168 } 169 170 return PairingFailure("Was expecting Encryption Change or Key Refresh Complete but received something else"); 171 } 172 IAmMaster(const InitialInformations & i)173 inline bool IAmMaster(const InitialInformations& i) { 174 return i.my_role == hci::Role::MASTER; 175 } 176 177 /* This function generates data that should be passed to remote device, except 178 the private key. */ 179 static MyOobData GenerateOobData(); 180 181 std::variant<PairingFailure, KeyExchangeResult> ExchangePublicKeys(const InitialInformations& i, 182 OobDataFlag remote_have_oob_data); 183 184 Stage1ResultOrFailure DoSecureConnectionsStage1(const InitialInformations& i, const EcdhPublicKey& PKa, 185 const EcdhPublicKey& PKb, const PairingRequestView& pairing_request, 186 const PairingResponseView& pairing_response); 187 188 Stage1ResultOrFailure SecureConnectionsNumericComparison(const InitialInformations& i, const EcdhPublicKey& PKa, 189 const EcdhPublicKey& PKb); 190 191 Stage1ResultOrFailure SecureConnectionsJustWorks(const InitialInformations& i, const EcdhPublicKey& PKa, 192 const EcdhPublicKey& PKb); 193 194 Stage1ResultOrFailure SecureConnectionsPasskeyEntry(const InitialInformations& i, const EcdhPublicKey& PKa, 195 const EcdhPublicKey& PKb, IoCapability my_iocaps, 196 IoCapability remote_iocaps); 197 198 Stage1ResultOrFailure SecureConnectionsOutOfBand(const InitialInformations& i, const EcdhPublicKey& Pka, 199 const EcdhPublicKey& Pkb, OobDataFlag my_oob_flag, 200 OobDataFlag remote_oob_flag); 201 202 Stage2ResultOrFailure DoSecureConnectionsStage2(const InitialInformations& i, const EcdhPublicKey& PKa, 203 const EcdhPublicKey& PKb, const PairingRequestView& pairing_request, 204 const PairingResponseView& pairing_response, 205 const Stage1Result stage1result, 206 const std::array<uint8_t, 32>& dhkey); 207 208 DistributedKeysOrFailure DistributeKeys(const InitialInformations& i, const PairingResponseView& pairing_response, 209 bool isSecureConnections); 210 211 DistributedKeysOrFailure ReceiveKeys(const uint8_t& keys_i_receive); 212 213 LegacyStage1ResultOrFailure DoLegacyStage1(const InitialInformations& i, const PairingRequestView& pairing_request, 214 const PairingResponseView& pairing_response); 215 LegacyStage1ResultOrFailure LegacyOutOfBand(const InitialInformations& i); 216 LegacyStage1ResultOrFailure LegacyJustWorks(); 217 LegacyStage1ResultOrFailure LegacyPasskeyEntry(const InitialInformations& i, const IoCapability& my_iocaps, 218 const IoCapability& remote_iocaps); 219 StkOrFailure DoLegacyStage2(const InitialInformations& i, const PairingRequestView& pairing_request, 220 const PairingResponseView& pairing_response, const Octet16& tk); 221 222 void SendKeys(const InitialInformations& i, const uint8_t& keys_i_send, Octet16 ltk, uint16_t ediv, 223 std::array<uint8_t, 8> rand, Octet16 irk, Address identity_address, AddrType identity_addres_type, 224 Octet16 signature_key); 225 226 /* This can be called from any thread to immediately finish the pairing in progress. */ SendExitSignal()227 void SendExitSignal() { 228 { 229 std::unique_lock<std::mutex> lock(queue_guard); 230 queue.push(PairingEvent(PairingEvent::EXIT)); 231 } 232 pairing_thread_blocker_.notify_one(); 233 } 234 235 /* SMP Command received from remote device */ OnCommandView(CommandView packet)236 void OnCommandView(CommandView packet) { 237 { 238 std::unique_lock<std::mutex> lock(queue_guard); 239 queue.push(PairingEvent(std::move(packet))); 240 } 241 pairing_thread_blocker_.notify_one(); 242 } 243 244 /* SMP Command received from remote device */ OnHciEvent(hci::EventPacketView hci_event)245 void OnHciEvent(hci::EventPacketView hci_event) { 246 { 247 std::unique_lock<std::mutex> lock(queue_guard); 248 queue.push(PairingEvent(std::move(hci_event))); 249 } 250 pairing_thread_blocker_.notify_one(); 251 } 252 253 /* Interaction from user */ OnUiAction(PairingEvent::UI_ACTION_TYPE ui_action,uint32_t ui_value)254 void OnUiAction(PairingEvent::UI_ACTION_TYPE ui_action, uint32_t ui_value) { 255 { 256 std::unique_lock<std::mutex> lock(queue_guard); 257 queue.push(PairingEvent(ui_action, ui_value)); 258 } 259 pairing_thread_blocker_.notify_one(); 260 } 261 262 /* Blocks the pairing process until some external interaction, or timeout happens */ WaitForEvent()263 PairingEvent WaitForEvent() { 264 std::unique_lock<std::mutex> lock(queue_guard); 265 do { 266 if (!queue.empty()) { 267 PairingEvent e = queue.front(); 268 queue.pop(); 269 return e; 270 } 271 // This releases the lock while blocking. 272 if (pairing_thread_blocker_.wait_for(lock, std::chrono::seconds(SMP_TIMEOUT)) == std::cv_status::timeout) { 273 return PairingEvent(PairingEvent::EXIT); 274 } 275 276 } while (true); 277 } 278 WaitUiPairingAccept()279 std::optional<PairingEvent> WaitUiPairingAccept() { 280 PairingEvent e = WaitForEvent(); 281 if (e.type == PairingEvent::UI & e.ui_action == PairingEvent::PAIRING_ACCEPTED) { 282 return e; 283 } else { 284 return std::nullopt; 285 } 286 } 287 WaitUiConfirmYesNo()288 std::optional<PairingEvent> WaitUiConfirmYesNo() { 289 PairingEvent e = WaitForEvent(); 290 if (e.type == PairingEvent::UI & e.ui_action == PairingEvent::CONFIRM_YESNO) { 291 return e; 292 } else { 293 return std::nullopt; 294 } 295 } 296 WaitUiPasskey()297 std::optional<PairingEvent> WaitUiPasskey() { 298 PairingEvent e = WaitForEvent(); 299 if (e.type == PairingEvent::UI & e.ui_action == PairingEvent::PASSKEY) { 300 return e; 301 } else { 302 return std::nullopt; 303 } 304 } 305 306 template <Code C> 307 struct CodeToPacketView; 308 template <> 309 struct CodeToPacketView<Code::PAIRING_REQUEST> { 310 typedef PairingRequestView type; 311 }; 312 template <> 313 struct CodeToPacketView<Code::PAIRING_RESPONSE> { 314 typedef PairingResponseView type; 315 }; 316 template <> 317 struct CodeToPacketView<Code::PAIRING_CONFIRM> { 318 typedef PairingConfirmView type; 319 }; 320 template <> 321 struct CodeToPacketView<Code::PAIRING_RANDOM> { 322 typedef PairingRandomView type; 323 }; 324 template <> 325 struct CodeToPacketView<Code::PAIRING_FAILED> { 326 typedef PairingFailedView type; 327 }; 328 template <> 329 struct CodeToPacketView<Code::ENCRYPTION_INFORMATION> { 330 typedef EncryptionInformationView type; 331 }; 332 template <> 333 struct CodeToPacketView<Code::MASTER_IDENTIFICATION> { 334 typedef MasterIdentificationView type; 335 }; 336 template <> 337 struct CodeToPacketView<Code::IDENTITY_INFORMATION> { 338 typedef IdentityInformationView type; 339 }; 340 template <> 341 struct CodeToPacketView<Code::IDENTITY_ADDRESS_INFORMATION> { 342 typedef IdentityAddressInformationView type; 343 }; 344 template <> 345 struct CodeToPacketView<Code::SIGNING_INFORMATION> { 346 typedef SigningInformationView type; 347 }; 348 template <> 349 struct CodeToPacketView<Code::SECURITY_REQUEST> { 350 typedef SecurityRequestView type; 351 }; 352 template <> 353 struct CodeToPacketView<Code::PAIRING_PUBLIC_KEY> { 354 typedef PairingPublicKeyView type; 355 }; 356 template <> 357 struct CodeToPacketView<Code::PAIRING_DH_KEY_CHECK> { 358 typedef PairingDhKeyCheckView type; 359 }; 360 template <> 361 struct CodeToPacketView<Code::PAIRING_KEYPRESS_NOTIFICATION> { 362 typedef PairingKeypressNotificationView type; 363 }; 364 365 template <Code CODE> 366 std::variant<typename CodeToPacketView<CODE>::type, PairingFailure> WaitPacket() { 367 PairingEvent e = WaitForEvent(); 368 switch (e.type) { 369 case PairingEvent::EXIT: 370 return PairingFailure( 371 /*FROM_HERE,*/ "Was expecting L2CAP Packet " + CodeText(CODE) + ", but received EXIT instead"); 372 373 case PairingEvent::HCI_EVENT: 374 return PairingFailure( 375 /*FROM_HERE,*/ "Was expecting L2CAP Packet " + CodeText(CODE) + ", but received HCI_EVENT instead"); 376 377 case PairingEvent::UI: 378 return PairingFailure( 379 /*FROM_HERE,*/ "Was expecting L2CAP Packet " + CodeText(CODE) + ", but received UI instead"); 380 381 case PairingEvent::L2CAP: { 382 auto l2cap_packet = e.l2cap_packet.value(); 383 if (!l2cap_packet.IsValid()) { 384 return PairingFailure("Malformed L2CAP packet received!"); 385 } 386 387 const auto& received_code = l2cap_packet.GetCode(); 388 if (received_code != CODE) { 389 if (received_code == Code::PAIRING_FAILED) { 390 auto pkt = PairingFailedView::Create(l2cap_packet); 391 if (!pkt.IsValid()) return PairingFailure("Malformed " + CodeText(CODE) + " packet"); 392 return PairingFailure(/*FROM_HERE,*/ 393 "Was expecting " + CodeText(CODE) + ", but received PAIRING_FAILED instead", 394 pkt.GetReason()); 395 } 396 397 return PairingFailure(/*FROM_HERE,*/ 398 "Was expecting " + CodeText(CODE) + ", but received " + CodeText(received_code) + 399 " instead", 400 received_code); 401 } 402 403 auto pkt = CodeToPacketView<CODE>::type::Create(l2cap_packet); 404 if (!pkt.IsValid()) return PairingFailure("Malformed " + CodeText(CODE) + " packet"); 405 return pkt; 406 } 407 } 408 } 409 410 auto WaitPairingRequest() { 411 return WaitPacket<Code::PAIRING_REQUEST>(); 412 } 413 414 auto WaitPairingResponse() { 415 return WaitPacket<Code::PAIRING_RESPONSE>(); 416 } 417 418 auto WaitPairingConfirm() { 419 return WaitPacket<Code::PAIRING_CONFIRM>(); 420 } 421 422 auto WaitPairingRandom() { 423 return WaitPacket<Code::PAIRING_RANDOM>(); 424 } 425 426 auto WaitPairingPublicKey() { 427 return WaitPacket<Code::PAIRING_PUBLIC_KEY>(); 428 } 429 430 auto WaitPairingDHKeyCheck() { 431 return WaitPacket<Code::PAIRING_DH_KEY_CHECK>(); 432 } 433 434 auto WaitEncryptionInformationRequest() { 435 return WaitPacket<Code::ENCRYPTION_INFORMATION>(); 436 } 437 438 auto WaitEncryptionInformation() { 439 return WaitPacket<Code::ENCRYPTION_INFORMATION>(); 440 } 441 442 auto WaitMasterIdentification() { 443 return WaitPacket<Code::MASTER_IDENTIFICATION>(); 444 } 445 446 auto WaitIdentityInformation() { 447 return WaitPacket<Code::IDENTITY_INFORMATION>(); 448 } 449 450 auto WaitIdentityAddressInformation() { 451 return WaitPacket<Code::IDENTITY_ADDRESS_INFORMATION>(); 452 } 453 454 auto WaitSigningInformation() { 455 return WaitPacket<Code::SIGNING_INFORMATION>(); 456 } 457 458 /* This is just for test, never use in production code! */ 459 void WaitUntilPairingFinished() { 460 thread_.join(); 461 } 462 463 private: 464 std::condition_variable pairing_thread_blocker_; 465 466 std::mutex queue_guard; 467 std::queue<PairingEvent> queue; 468 469 std::thread thread_; 470 }; 471 } // namespace security 472 } // namespace bluetooth 473