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 #include "security/pairing_handler_le.h"
20 
21 #include <bluetooth/log.h>
22 
23 #include "hci/octets.h"
24 #include "os/rand.h"
25 
26 namespace bluetooth {
27 namespace security {
28 
29 using hci::Octet16;
30 
GenerateOobData()31 MyOobData PairingHandlerLe::GenerateOobData() {
32   MyOobData data{};
33   std::tie(data.private_key, data.public_key) = GenerateECDHKeyPair();
34 
35   data.r = bluetooth::os::GenerateRandom<16>();
36   data.c = crypto_toolbox::f4(data.public_key.x.data(), data.public_key.x.data(), data.r, 0);
37   return data;
38 }
39 
PairingMain(InitialInformations i)40 void PairingHandlerLe::PairingMain(InitialInformations i) {
41   log::info("Pairing Started");
42 
43   if (i.remotely_initiated) {
44     log::info("Was remotely initiated, presenting user with the accept prompt");
45     i.user_interface_handler->Post(common::BindOnce(&UI::DisplayPairingPrompt, common::Unretained(i.user_interface),
46                                                     i.remote_connection_address, i.remote_name));
47 
48     // If pairing was initiated by remote device, wait for the user to accept
49     // the request from the UI.
50     log::info("Waiting for the prompt response");
51     std::optional<PairingEvent> pairingAccepted = WaitUiPairingAccept();
52     if (!pairingAccepted || pairingAccepted->ui_value == 0) {
53       log::info("User either did not accept the remote pairing, or the prompt timed out");
54       // TODO: Uncomment this one once we find a way to attempt to send packet when the link is down
55       // SendL2capPacket(i, PairingFailedBuilder::Create(PairingFailedReason::UNSPECIFIED_REASON));
56       i.OnPairingFinished(PairingFailure("User either did not accept the remote pairing, or the prompt timed out"));
57       return;
58     }
59 
60     log::info("Pairing prompt accepted");
61   }
62 
63   /************************************************ PHASE 1 *********************************************************/
64   Phase1ResultOrFailure phase_1_result = ExchangePairingFeature(i);
65   if (std::holds_alternative<PairingFailure>(phase_1_result)) {
66     log::warn("Pairing failed in phase 1");
67     // We already send pairing fialed in lower layer. Which one should do that ? how about disconneciton?
68     // SendL2capPacket(i, PairingFailedBuilder::Create(PairingFailedReason::UNSPECIFIED_REASON));
69     // TODO: disconnect?
70     i.OnPairingFinished(std::get<PairingFailure>(phase_1_result));
71     return;
72   }
73 
74   auto [pairing_request, pairing_response] = std::get<Phase1Result>(phase_1_result);
75 
76   uint8_t key_size =
77       std::min(pairing_request.GetMaximumEncryptionKeySize(), pairing_response.GetMaximumEncryptionKeySize());
78   if (key_size < 7 || key_size > 16) {
79     log::warn("Resulting key size is bad {}", key_size);
80     SendL2capPacket(i, PairingFailedBuilder::Create(PairingFailedReason::ENCRYPTION_KEY_SIZE));
81     i.OnPairingFinished(PairingFailure("Resulting key size is bad", PairingFailedReason::ENCRYPTION_KEY_SIZE));
82     return;
83   }
84   if (key_size != 16) {
85     log::warn("Resulting key size is less than 16 octets!");
86   }
87 
88   /************************************************ PHASE 2 *********************************************************/
89   bool isSecureConnections = pairing_request.GetAuthReq() & pairing_response.GetAuthReq() & AuthReqMaskSc;
90   if (isSecureConnections) {
91     // 2.3.5.6 LE Secure Connections pairing phase 2
92     log::info("Pairing Phase 2 LE Secure connections Started");
93 
94     /*
95     TODO: what to do with this piece of spec ?
96     If Secure Connections pairing has been initiated over BR/EDR, the
97     following fields of the SM Pairing Request PDU are reserved for future use:
98      • the IO Capability field,
99      • the OOB data flag field, and
100      • all bits in the Auth Req field except the CT2 bit.
101     */
102 
103     OobDataFlag remote_have_oob_data =
104         IAmCentral(i) ? pairing_response.GetOobDataFlag() : pairing_request.GetOobDataFlag();
105 
106     auto key_exchange_result = ExchangePublicKeys(i, remote_have_oob_data);
107     if (std::holds_alternative<PairingFailure>(key_exchange_result)) {
108       log::error("Public key exchange failed");
109       i.OnPairingFinished(std::get<PairingFailure>(key_exchange_result));
110       return;
111     }
112     auto [PKa, PKb, dhkey] = std::get<KeyExchangeResult>(key_exchange_result);
113 
114     // Public key exchange finished, Diffie-Hellman key computed.
115 
116     Stage1ResultOrFailure stage1result = DoSecureConnectionsStage1(i, PKa, PKb, pairing_request, pairing_response);
117     if (std::holds_alternative<PairingFailure>(stage1result)) {
118       i.OnPairingFinished(std::get<PairingFailure>(stage1result));
119       return;
120     }
121 
122     Stage2ResultOrFailure stage_2_result = DoSecureConnectionsStage2(i, PKa, PKb, pairing_request, pairing_response,
123                                                                      std::get<Stage1Result>(stage1result), dhkey);
124     if (std::holds_alternative<PairingFailure>(stage_2_result)) {
125       i.OnPairingFinished(std::get<PairingFailure>(stage_2_result));
126       return;
127     }
128 
129     Octet16 ltk = std::get<Octet16>(stage_2_result);
130     // Mask the key
131     std::fill(ltk.begin() + key_size, ltk.end(), 0x00);
132 
133     if (IAmCentral(i)) {
134       log::info("Sending start encryption request");
135       SendHciLeStartEncryption(i, i.connection_handle, {0}, {0}, ltk);
136     } else {
137       auto ltk_req = WaitLeLongTermKeyRequest();
138       SendHciLeLongTermKeyReply(i, i.connection_handle, ltk);
139     }
140   } else {
141     // 2.3.5.5 LE legacy pairing phase 2
142     log::info("Pairing Phase 2 LE legacy pairing Started");
143 
144     LegacyStage1ResultOrFailure stage1result = DoLegacyStage1(i, pairing_request, pairing_response);
145     if (std::holds_alternative<PairingFailure>(stage1result)) {
146       log::error("Phase 1 failed");
147       i.OnPairingFinished(std::get<PairingFailure>(stage1result));
148       return;
149     }
150 
151     Octet16 tk = std::get<Octet16>(stage1result);
152     StkOrFailure stage2result = DoLegacyStage2(i, pairing_request, pairing_response, tk);
153     if (std::holds_alternative<PairingFailure>(stage2result)) {
154       log::error("stage 2 failed");
155       i.OnPairingFinished(std::get<PairingFailure>(stage2result));
156       return;
157     }
158 
159     Octet16 stk = std::get<Octet16>(stage2result);
160     // Mask the key
161     std::fill(stk.begin() + key_size, stk.end(), 0x00);
162     if (IAmCentral(i)) {
163       log::info("Sending start encryption request");
164       SendHciLeStartEncryption(i, i.connection_handle, {0}, {0}, stk);
165     } else {
166       auto ltk_req = WaitLeLongTermKeyRequest();
167       SendHciLeLongTermKeyReply(i, i.connection_handle, stk);
168     }
169   }
170 
171   /************************************************ PHASE 3 *********************************************************/
172   log::info("Waiting for encryption changed");
173   auto encryption_change_result = WaitEncryptionChanged();
174   if (std::holds_alternative<PairingFailure>(encryption_change_result)) {
175     i.OnPairingFinished(std::get<PairingFailure>(encryption_change_result));
176     return;
177   } else if (std::holds_alternative<EncryptionChangeView>(encryption_change_result)) {
178     EncryptionChangeView encryption_changed = std::get<EncryptionChangeView>(encryption_change_result);
179     if (encryption_changed.GetStatus() != hci::ErrorCode::SUCCESS ||
180         encryption_changed.GetEncryptionEnabled() != hci::EncryptionEnabled::ON) {
181       i.OnPairingFinished(PairingFailure("Encryption change failed"));
182       return;
183     }
184   } else if (std::holds_alternative<EncryptionKeyRefreshCompleteView>(encryption_change_result)) {
185     EncryptionKeyRefreshCompleteView encryption_changed =
186         std::get<EncryptionKeyRefreshCompleteView>(encryption_change_result);
187     if (encryption_changed.GetStatus() != hci::ErrorCode::SUCCESS) {
188       i.OnPairingFinished(PairingFailure("Encryption key refresh failed"));
189       return;
190     }
191   } else {
192     i.OnPairingFinished(PairingFailure("Unknown case of encryption change result"));
193     return;
194   }
195   log::info("Encryption change finished successfully");
196 
197   DistributedKeysOrFailure keyExchangeStatus = DistributeKeys(i, pairing_response, isSecureConnections);
198   if (std::holds_alternative<PairingFailure>(keyExchangeStatus)) {
199     i.OnPairingFinished(std::get<PairingFailure>(keyExchangeStatus));
200     log::error("Key exchange failed");
201     return;
202   }
203 
204   // If it's secure connections pairing, do cross-transport key derivation
205   DistributedKeys distributed_keys = std::get<DistributedKeys>(keyExchangeStatus);
206   if ((pairing_response.GetAuthReq() & AuthReqMaskSc) && distributed_keys.remote_ltk.has_value()) {
207     bool use_h7 = (pairing_response.GetAuthReq() & AuthReqMaskCt2);
208     Octet16 link_key = crypto_toolbox::ltk_to_link_key(*(distributed_keys.remote_ltk), use_h7);
209     distributed_keys.remote_link_key = link_key;
210   }
211 
212   // bool bonding = pairing_request.GetAuthReq() & pairing_response.GetAuthReq() & AuthReqMaskBondingFlag;
213 
214   i.OnPairingFinished(PairingResult{
215       .connection_address = i.remote_connection_address,
216       .distributed_keys = distributed_keys,
217       .key_size = key_size,
218   });
219 
220   log::info("Pairing finished successfully.");
221 }
222 
ExchangePairingFeature(const InitialInformations & i)223 Phase1ResultOrFailure PairingHandlerLe::ExchangePairingFeature(const InitialInformations& i) {
224   log::info("Phase 1 start");
225 
226   if (IAmCentral(i)) {
227     // Send Pairing Request
228     const auto& x = i.myPairingCapabilities;
229     auto pairing_request_builder =
230         PairingRequestBuilder::Create(x.io_capability, x.oob_data_flag, x.auth_req, x.maximum_encryption_key_size,
231                                       x.initiator_key_distribution, x.responder_key_distribution);
232     // basically pairing_request = myPairingCapabilities;
233 
234     // Convert builder to view
235     std::shared_ptr<std::vector<uint8_t>> packet_bytes = std::make_shared<std::vector<uint8_t>>();
236     BitInserter it(*packet_bytes);
237     pairing_request_builder->Serialize(it);
238     PacketView<kLittleEndian> packet_bytes_view(packet_bytes);
239     auto temp_cmd_view = CommandView::Create(packet_bytes_view);
240     auto pairing_request = PairingRequestView::Create(temp_cmd_view);
241     log::assert_that(pairing_request.IsValid(), "assert failed: pairing_request.IsValid()");
242 
243     log::info("Sending Pairing Request");
244     SendL2capPacket(i, std::move(pairing_request_builder));
245 
246     log::info("Waiting for Pairing Response");
247     auto response = WaitPairingResponse();
248 
249     /* There is a potential collision where the peripheral initiates the pairing at the same time we initiate it, by
250      * sending security request. */
251     if (std::holds_alternative<PairingFailure>(response) &&
252         std::get<PairingFailure>(response).received_code_ == Code::SECURITY_REQUEST) {
253       log::info("Received security request, waiting for Pairing Response again...");
254       response = WaitPairingResponse();
255     }
256 
257     if (std::holds_alternative<PairingFailure>(response)) {
258       // TODO: should the failure reason be different in some cases ? How about
259       // when we lost connection ? Don't send anything at all, or have L2CAP
260       // layer ignore it?
261       SendL2capPacket(i, PairingFailedBuilder::Create(PairingFailedReason::UNSPECIFIED_REASON));
262       return std::get<PairingFailure>(response);
263     }
264 
265     auto pairing_response = std::get<PairingResponseView>(response);
266 
267     log::info("Phase 1 finish");
268     return Phase1Result{pairing_request, pairing_response};
269   } else {
270     std::optional<PairingRequestView> pairing_request;
271 
272     if (i.remotely_initiated) {
273       if (!i.pairing_request.has_value()) {
274         return PairingFailure("You must pass PairingRequest as a initial information to peripheral!");
275       }
276 
277       pairing_request = i.pairing_request.value();
278 
279       if (!pairing_request->IsValid()) return PairingFailure("Malformed PairingRequest");
280     } else {
281       SendL2capPacket(i, SecurityRequestBuilder::Create(i.myPairingCapabilities.auth_req));
282 
283       log::info("Waiting for Pairing Request");
284       auto request = WaitPairingRequest();
285       if (std::holds_alternative<PairingFailure>(request)) {
286         log::info("{}", std::get<PairingFailure>(request).message);
287         SendL2capPacket(i, PairingFailedBuilder::Create(PairingFailedReason::UNSPECIFIED_REASON));
288         return std::get<PairingFailure>(request);
289       }
290 
291       pairing_request = std::get<PairingRequestView>(request);
292     }
293 
294     uint8_t key_size = pairing_request->GetMaximumEncryptionKeySize();
295     if (key_size < 7 || key_size > 16) {
296       log::warn("Resulting key size is bad {}", key_size);
297       SendL2capPacket(i, PairingFailedBuilder::Create(PairingFailedReason::ENCRYPTION_KEY_SIZE));
298       return PairingFailure("Resulting key size is bad", PairingFailedReason::ENCRYPTION_KEY_SIZE);
299     }
300 
301     // Send Pairing Request
302     const auto& x = i.myPairingCapabilities;
303     // basically pairing_response_builder = my_first_packet;
304     // We are not allowed to enable bits that the remote did not allow us to set in initiator_key_dist and
305     // responder_key_distribution
306     auto pairing_response_builder =
307         PairingResponseBuilder::Create(x.io_capability, x.oob_data_flag, x.auth_req, x.maximum_encryption_key_size,
308                                        x.initiator_key_distribution & pairing_request->GetInitiatorKeyDistribution(),
309                                        x.responder_key_distribution & pairing_request->GetResponderKeyDistribution());
310 
311     // Convert builder to view
312     std::shared_ptr<std::vector<uint8_t>> packet_bytes = std::make_shared<std::vector<uint8_t>>();
313     BitInserter it(*packet_bytes);
314     pairing_response_builder->Serialize(it);
315     PacketView<kLittleEndian> packet_bytes_view(packet_bytes);
316     auto temp_cmd_view = CommandView::Create(packet_bytes_view);
317     auto pairing_response = PairingResponseView::Create(temp_cmd_view);
318     log::assert_that(pairing_response.IsValid(), "assert failed: pairing_response.IsValid()");
319 
320     log::info("Sending Pairing Response");
321     SendL2capPacket(i, std::move(pairing_response_builder));
322 
323     log::info("Phase 1 finish");
324     return Phase1Result{pairing_request.value(), pairing_response};
325   }
326 }
327 
DistributeKeys(const InitialInformations & i,const PairingResponseView & pairing_response,bool isSecureConnections)328 DistributedKeysOrFailure PairingHandlerLe::DistributeKeys(const InitialInformations& i,
329                                                           const PairingResponseView& pairing_response,
330                                                           bool isSecureConnections) {
331   uint8_t keys_i_receive =
332       IAmCentral(i) ? pairing_response.GetResponderKeyDistribution() : pairing_response.GetInitiatorKeyDistribution();
333   uint8_t keys_i_send =
334       IAmCentral(i) ? pairing_response.GetInitiatorKeyDistribution() : pairing_response.GetResponderKeyDistribution();
335 
336   // In Secure Connections on the LE Transport, the EncKey field shall be ignored
337   if (isSecureConnections) {
338     keys_i_send = (~KeyMaskEnc) & keys_i_send;
339     keys_i_receive = (~KeyMaskEnc) & keys_i_receive;
340   }
341 
342   log::info(
343       "Key distribution start, keys_i_send=0x{:02x}, keys_i_receive=0x{:02x}",
344       keys_i_send,
345       keys_i_receive);
346 
347   // TODO: obtain actual values, and apply key_size to the LTK
348   Octet16 my_ltk = bluetooth::os::GenerateRandom<16>();
349   uint16_t my_ediv = bluetooth::os::GenerateRandom();
350   std::array<uint8_t, 8> my_rand = bluetooth::os::GenerateRandom<8>();
351 
352   Octet16 my_irk = i.my_identity_resolving_key;
353   Address my_identity_address = i.my_identity_address.GetAddress();
354   AddrType my_identity_address_type =
355       static_cast<bluetooth::security::AddrType>(i.my_identity_address.GetAddressType());
356   Octet16 my_signature_key{0};
357 
358   if (IAmCentral(i)) {
359     // EncKey is unused for LE Secure Connections
360     DistributedKeysOrFailure keys = ReceiveKeys(keys_i_receive);
361     if (std::holds_alternative<PairingFailure>(keys)) {
362       return keys;
363     }
364 
365     SendKeys(i, keys_i_send, my_ltk, my_ediv, my_rand, my_irk, my_identity_address, my_identity_address_type,
366              my_signature_key);
367 
368     std::get<DistributedKeys>(keys).local_ltk = my_ltk;
369     std::get<DistributedKeys>(keys).local_ediv = my_ediv;
370     std::get<DistributedKeys>(keys).local_rand = my_rand;
371     log::info("Key distribution finish");
372     return keys;
373   } else {
374     SendKeys(i, keys_i_send, my_ltk, my_ediv, my_rand, my_irk, my_identity_address, my_identity_address_type,
375              my_signature_key);
376 
377     DistributedKeysOrFailure keys = ReceiveKeys(keys_i_receive);
378     if (std::holds_alternative<PairingFailure>(keys)) {
379       return keys;
380     }
381 
382     std::get<DistributedKeys>(keys).local_ltk = my_ltk;
383     std::get<DistributedKeys>(keys).local_ediv = my_ediv;
384     std::get<DistributedKeys>(keys).local_rand = my_rand;
385     log::info("Key distribution finish");
386     return keys;
387   }
388 }
389 
ReceiveKeys(const uint8_t & keys_i_receive)390 DistributedKeysOrFailure PairingHandlerLe::ReceiveKeys(const uint8_t& keys_i_receive) {
391   std::optional<Octet16> ltk;                 /* Legacy only */
392   std::optional<uint16_t> ediv;               /* Legacy only */
393   std::optional<std::array<uint8_t, 8>> rand; /* Legacy only */
394   std::optional<hci::AddressWithType> identity_address;
395   std::optional<Octet16> irk;
396   std::optional<Octet16> signature_key;
397 
398   if (keys_i_receive & KeyMaskEnc) {
399     {
400       auto packet = WaitEncryptionInformation();
401       if (std::holds_alternative<PairingFailure>(packet)) {
402         log::error("Was expecting Encryption Information but did not receive!");
403         return std::get<PairingFailure>(packet);
404       }
405       ltk = std::get<EncryptionInformationView>(packet).GetLongTermKey();
406     }
407 
408     {
409       auto packet = WaitCentralIdentification();
410       if (std::holds_alternative<PairingFailure>(packet)) {
411         log::error("Was expecting Central Identification but did not receive!");
412         return std::get<PairingFailure>(packet);
413       }
414       ediv = std::get<CentralIdentificationView>(packet).GetEdiv();
415       rand = std::get<CentralIdentificationView>(packet).GetRand();
416     }
417   }
418 
419   if (keys_i_receive & KeyMaskId) {
420     auto packet = WaitIdentityInformation();
421     if (std::holds_alternative<PairingFailure>(packet)) {
422       log::error("Was expecting Identity Information but did not receive!");
423       return std::get<PairingFailure>(packet);
424     }
425 
426     log::info("Received Identity Information");
427     irk = std::get<IdentityInformationView>(packet).GetIdentityResolvingKey();
428 
429     auto iapacket = WaitIdentityAddressInformation();
430     if (std::holds_alternative<PairingFailure>(iapacket)) {
431       log::error("Was expecting Identity Address Information but did not receive!");
432       return std::get<PairingFailure>(iapacket);
433     }
434     log::info("Received Identity Address Information");
435     auto iapacketview = std::get<IdentityAddressInformationView>(iapacket);
436     identity_address = hci::AddressWithType(iapacketview.GetBdAddr(), iapacketview.GetAddrType() == AddrType::PUBLIC
437                                                                           ? hci::AddressType::PUBLIC_DEVICE_ADDRESS
438                                                                           : hci::AddressType::RANDOM_DEVICE_ADDRESS);
439   }
440 
441   if (keys_i_receive & KeyMaskSign) {
442     auto packet = WaitSigningInformation();
443     if (std::holds_alternative<PairingFailure>(packet)) {
444       log::error("Was expecting Signing Information but did not receive!");
445       return std::get<PairingFailure>(packet);
446     }
447 
448     log::info("Received Signing Information");
449     signature_key = std::get<SigningInformationView>(packet).GetSignatureKey();
450   }
451 
452   return DistributedKeys{.remote_ltk = ltk,
453                          .remote_ediv = ediv,
454                          .remote_rand = rand,
455                          .remote_identity_address = identity_address,
456                          .remote_irk = irk,
457                          .remote_signature_key = signature_key};
458 }
459 
SendKeys(const InitialInformations & i,const uint8_t & keys_i_send,Octet16 ltk,uint16_t ediv,std::array<uint8_t,8> rand,Octet16 irk,Address identity_address,AddrType identity_addres_type,Octet16 signature_key)460 void PairingHandlerLe::SendKeys(const InitialInformations& i, const uint8_t& keys_i_send, Octet16 ltk, uint16_t ediv,
461                                 std::array<uint8_t, 8> rand, Octet16 irk, Address identity_address,
462                                 AddrType identity_addres_type, Octet16 signature_key) {
463   if (keys_i_send & KeyMaskEnc) {
464     log::info("Sending Encryption Information");
465     SendL2capPacket(i, EncryptionInformationBuilder::Create(ltk));
466     log::info("Sending Central Identification");
467     SendL2capPacket(i, CentralIdentificationBuilder::Create(ediv, rand));
468   }
469 
470   if (keys_i_send & KeyMaskId) {
471     log::info("Sending Identity Information");
472     SendL2capPacket(i, IdentityInformationBuilder::Create(irk));
473     log::info("Sending Identity Address Information");
474     SendL2capPacket(i, IdentityAddressInformationBuilder::Create(identity_addres_type, identity_address));
475   }
476 
477   if (keys_i_send & KeyMaskSign) {
478     log::info("Sending Signing Information");
479     SendL2capPacket(i, SigningInformationBuilder::Create(signature_key));
480   }
481 }
482 
483 }  // namespace security
484 }  // namespace bluetooth
485