1 /*
2 * Copyright 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 */
17
18 #define LOG_TAG "ble_sec"
19
20 #include "stack/btm/btm_ble_sec.h"
21
22 #include <android_bluetooth_sysprop.h>
23 #include <base/strings/stringprintf.h>
24 #include <bluetooth/log.h>
25
26 #include <cstddef>
27 #include <cstdint>
28 #include <optional>
29
30 #include "btif/include/btif_storage.h"
31 #include "crypto_toolbox/crypto_toolbox.h"
32 #include "device/include/interop.h"
33 #include "device/include/interop_config.h"
34 #include "hci/controller_interface.h"
35 #include "main/shim/entry.h"
36 #include "os/log.h"
37 #include "osi/include/allocator.h"
38 #include "osi/include/properties.h"
39 #include "platform_ssl_mem.h"
40 #include "stack/btm/btm_ble_int.h"
41 #include "stack/btm/btm_dev.h"
42 #include "stack/btm/btm_int_types.h"
43 #include "stack/btm/btm_sec.h"
44 #include "stack/btm/btm_sec_cb.h"
45 #include "stack/btm/btm_sec_int_types.h"
46 #include "stack/btm/security_device_record.h"
47 #include "stack/eatt/eatt.h"
48 #include "stack/include/acl_api.h"
49 #include "stack/include/bt_name.h"
50 #include "stack/include/bt_octets.h"
51 #include "stack/include/bt_types.h"
52 #include "stack/include/btm_api.h"
53 #include "stack/include/btm_ble_addr.h"
54 #include "stack/include/btm_ble_privacy.h"
55 #include "stack/include/btm_ble_sec_api.h"
56 #include "stack/include/btm_log_history.h"
57 #include "stack/include/btm_status.h"
58 #include "stack/include/gatt_api.h"
59 #include "stack/include/l2cap_security_interface.h"
60 #include "stack/include/smp_api.h"
61 #include "stack/include/smp_api_types.h"
62 #include "types/raw_address.h"
63
64 using namespace bluetooth;
65
66 extern tBTM_CB btm_cb;
67
68 bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec,
69 const RawAddress& new_pseudo_addr);
70
71 namespace {
72 constexpr char kBtmLogTag[] = "SEC";
73 }
74
75 static constexpr char kPropertyCtkdDisableCsrkDistribution[] =
76 "bluetooth.core.smp.le.ctkd.quirk_disable_csrk_distribution";
77
78 /******************************************************************************/
79 /* External Function to be called by other modules */
80 /******************************************************************************/
BTM_SecAddBleDevice(const RawAddress & bd_addr,tBT_DEVICE_TYPE dev_type,tBLE_ADDR_TYPE addr_type)81 void BTM_SecAddBleDevice(const RawAddress& bd_addr, tBT_DEVICE_TYPE dev_type,
82 tBLE_ADDR_TYPE addr_type) {
83 log::debug("dev_type=0x{:x}", dev_type);
84
85 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
86 if (!p_dev_rec) {
87 p_dev_rec = btm_sec_allocate_dev_rec();
88
89 p_dev_rec->bd_addr = bd_addr;
90 p_dev_rec->hci_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_BR_EDR);
91 p_dev_rec->ble_hci_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE);
92
93 /* update conn params, use default value for background connection params */
94 p_dev_rec->conn_params.min_conn_int = BTM_BLE_CONN_PARAM_UNDEF;
95 p_dev_rec->conn_params.max_conn_int = BTM_BLE_CONN_PARAM_UNDEF;
96 p_dev_rec->conn_params.supervision_tout = BTM_BLE_CONN_PARAM_UNDEF;
97 p_dev_rec->conn_params.peripheral_latency = BTM_BLE_CONN_PARAM_UNDEF;
98
99 log::debug("Device added, handle=0x{:x}, p_dev_rec={}, bd_addr={}",
100 p_dev_rec->ble_hci_handle, fmt::ptr(p_dev_rec), bd_addr);
101 }
102
103 memset(p_dev_rec->sec_bd_name, 0, sizeof(BD_NAME));
104
105 p_dev_rec->device_type |= dev_type;
106 if (is_ble_addr_type_known(addr_type)) {
107 p_dev_rec->ble.SetAddressType(addr_type);
108 } else {
109 log::warn(
110 "Please do not update device record from anonymous le advertisement");
111 }
112
113 /* sync up with the Inq Data base*/
114 tBTM_INQ_INFO* p_info = BTM_InqDbRead(bd_addr);
115 if (p_info) {
116 p_info->results.ble_addr_type = p_dev_rec->ble.AddressType();
117 p_dev_rec->device_type |= p_info->results.device_type;
118 log::debug("InqDb device_type =0x{:x} addr_type=0x{:x}",
119 p_dev_rec->device_type, p_info->results.ble_addr_type);
120 p_info->results.device_type = p_dev_rec->device_type;
121 }
122 }
123
124 /*******************************************************************************
125 *
126 * Function BTM_GetRemoteDeviceName
127 *
128 * Description This function is called to get the dev name of remote device
129 * from NV
130 *
131 * Returns TRUE if success; otherwise failed.
132 *
133 ******************************************************************************/
BTM_GetRemoteDeviceName(const RawAddress & bd_addr,BD_NAME bd_name)134 bool BTM_GetRemoteDeviceName(const RawAddress& bd_addr, BD_NAME bd_name) {
135 log::verbose("bd_addr:{}", bd_addr);
136
137 bool ret = FALSE;
138 bt_bdname_t bdname;
139 bt_property_t prop_name;
140 BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME,
141 sizeof(bt_bdname_t), &bdname);
142
143 if (btif_storage_get_remote_device_property(&bd_addr, &prop_name) ==
144 BT_STATUS_SUCCESS) {
145 log::verbose("NV name={}", reinterpret_cast<const char*>(bdname.name));
146 bd_name_copy(bd_name, bdname.name);
147 ret = TRUE;
148 }
149 return ret;
150 }
151
152 /*******************************************************************************
153 *
154 * Function BTM_SecAddBleKey
155 *
156 * Description Add/modify LE device information. This function will be
157 * normally called during host startup to restore all required
158 * information stored in the NVRAM.
159 *
160 * Parameters: bd_addr - BD address of the peer
161 * p_le_key - LE key values.
162 * key_type - LE SMP key type.
163 *
164 * Returns true if added OK, else false
165 *
166 ******************************************************************************/
BTM_SecAddBleKey(const RawAddress & bd_addr,tBTM_LE_KEY_VALUE * p_le_key,tBTM_LE_KEY_TYPE key_type)167 void BTM_SecAddBleKey(const RawAddress& bd_addr, tBTM_LE_KEY_VALUE* p_le_key,
168 tBTM_LE_KEY_TYPE key_type) {
169 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
170 if (!p_dev_rec || !p_le_key ||
171 (key_type != BTM_LE_KEY_PENC && key_type != BTM_LE_KEY_PID &&
172 key_type != BTM_LE_KEY_PCSRK && key_type != BTM_LE_KEY_LENC &&
173 key_type != BTM_LE_KEY_LCSRK && key_type != BTM_LE_KEY_LID)) {
174 log::warn("Wrong Type, or No Device record for bdaddr:{}, Type:0{}",
175 bd_addr, key_type);
176 return;
177 }
178
179 log::debug("Adding BLE key device:{} key_type:{}", bd_addr, key_type);
180
181 btm_sec_save_le_key(bd_addr, key_type, p_le_key, false);
182 // Only set peer irk. Local irk is always the same.
183 if (key_type == BTM_LE_KEY_PID) {
184 btm_ble_resolving_list_load_dev(*p_dev_rec);
185 }
186 }
187
188 /*******************************************************************************
189 *
190 * Function BTM_BleLoadLocalKeys
191 *
192 * Description Local local identity key, encryption root or sign counter.
193 *
194 * Parameters: key_type: type of key, can be BTM_BLE_KEY_TYPE_ID,
195 * BTM_BLE_KEY_TYPE_ER
196 * or BTM_BLE_KEY_TYPE_COUNTER.
197 * p_key: pointer to the key.
198 *
199 * Returns non2.
200 *
201 ******************************************************************************/
BTM_BleLoadLocalKeys(uint8_t key_type,tBTM_BLE_LOCAL_KEYS * p_key)202 void BTM_BleLoadLocalKeys(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key) {
203 tBTM_SEC_DEVCB* p_devcb = &btm_sec_cb.devcb;
204 log::verbose("type:{}", key_type);
205 if (p_key != NULL) {
206 switch (key_type) {
207 case BTM_BLE_KEY_TYPE_ID:
208 memcpy(&p_devcb->id_keys, &p_key->id_keys,
209 sizeof(tBTM_BLE_LOCAL_ID_KEYS));
210 break;
211
212 case BTM_BLE_KEY_TYPE_ER:
213 p_devcb->ble_encryption_key_value = p_key->er;
214 break;
215
216 default:
217 log::error("unknown key type:{}", key_type);
218 break;
219 }
220 }
221 }
222
223 /** Returns local device encryption root (ER) */
BTM_GetDeviceEncRoot()224 const Octet16& BTM_GetDeviceEncRoot() {
225 return btm_sec_cb.devcb.ble_encryption_key_value;
226 }
227
228 /** Returns local device identity root (IR). */
BTM_GetDeviceIDRoot()229 const Octet16& BTM_GetDeviceIDRoot() { return btm_sec_cb.devcb.id_keys.irk; }
230
231 /** Return local device DHK. */
BTM_GetDeviceDHK()232 const Octet16& BTM_GetDeviceDHK() { return btm_sec_cb.devcb.id_keys.dhk; }
233
234 /*******************************************************************************
235 *
236 * Function BTM_SecurityGrant
237 *
238 * Description This function is called to grant security process.
239 *
240 * Parameters bd_addr - peer device bd address.
241 * res - result of the operation BTM_SUCCESS if success.
242 * Otherwise, BTM_REPEATED_ATTEMPTS if too many
243 * attempts.
244 *
245 * Returns None
246 *
247 ******************************************************************************/
BTM_SecurityGrant(const RawAddress & bd_addr,uint8_t res)248 void BTM_SecurityGrant(const RawAddress& bd_addr, uint8_t res) {
249 const tSMP_STATUS res_smp =
250 (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_REPEATED_ATTEMPTS;
251 log::verbose("bd_addr:{}, res:{}", bd_addr, smp_status_text(res_smp));
252 BTM_LogHistory(kBtmLogTag, bd_addr, "Granted",
253 base::StringPrintf("passkey_status:%s",
254 smp_status_text(res_smp).c_str()));
255
256 SMP_SecurityGrant(bd_addr, res_smp);
257 }
258
259 /*******************************************************************************
260 *
261 * Function BTM_BlePasskeyReply
262 *
263 * Description This function is called after Security Manager submitted
264 * passkey request to the application.
265 *
266 * Parameters: bd_addr - Address of the device for which passkey was
267 * requested
268 * res - result of the operation BTM_SUCCESS if success
269 * key_len - length in bytes of the Passkey
270 * p_passkey - pointer to array with the passkey
271 *
272 ******************************************************************************/
BTM_BlePasskeyReply(const RawAddress & bd_addr,uint8_t res,uint32_t passkey)273 void BTM_BlePasskeyReply(const RawAddress& bd_addr, uint8_t res,
274 uint32_t passkey) {
275 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
276 log::verbose("bd_addr:{}, res:{}", bd_addr, res);
277 if (p_dev_rec == NULL) {
278 log::error("Unknown device:{}", bd_addr);
279 return;
280 }
281
282 const tSMP_STATUS res_smp =
283 (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_PASSKEY_ENTRY_FAIL;
284 BTM_LogHistory(kBtmLogTag, bd_addr, "Passkey reply",
285 base::StringPrintf("transport:%s authenticate_status:%s",
286 bt_transport_text(BT_TRANSPORT_LE).c_str(),
287 smp_status_text(res_smp).c_str()));
288
289 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_LE_AUTHENTICATED;
290 SMP_PasskeyReply(bd_addr, res_smp, passkey);
291 }
292
293 /*******************************************************************************
294 *
295 * Function BTM_BleConfirmReply
296 *
297 * Description This function is called after Security Manager submitted
298 * numeric comparison request to the application.
299 *
300 * Parameters: bd_addr - Address of the device with which numeric
301 * comparison was requested
302 * res - comparison result BTM_SUCCESS if success
303 *
304 ******************************************************************************/
BTM_BleConfirmReply(const RawAddress & bd_addr,uint8_t res)305 void BTM_BleConfirmReply(const RawAddress& bd_addr, uint8_t res) {
306 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
307 log::verbose("bd_addr:{}, res:{}", bd_addr, res);
308 if (p_dev_rec == NULL) {
309 log::error("Unknown device:{}", bd_addr);
310 return;
311 }
312 const tSMP_STATUS res_smp =
313 (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_PASSKEY_ENTRY_FAIL;
314
315 BTM_LogHistory(kBtmLogTag, bd_addr, "Confirm reply",
316 base::StringPrintf(
317 "transport:%s numeric_comparison_authenticate_status:%s",
318 bt_transport_text(BT_TRANSPORT_LE).c_str(),
319 smp_status_text(res_smp).c_str()));
320
321 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_LE_AUTHENTICATED;
322 SMP_ConfirmReply(bd_addr, res_smp);
323 }
324
325 /*******************************************************************************
326 *
327 * Function BTM_BleOobDataReply
328 *
329 * Description This function is called to provide the OOB data for
330 * SMP in response to BTM_LE_OOB_REQ_EVT
331 *
332 * Parameters: bd_addr - Address of the peer device
333 * res - result of the operation SMP_SUCCESS if success
334 * p_data - oob data, depending on transport and
335 * capabilities.
336 * Might be "Simple Pairing Randomizer", or
337 * "Security Manager TK Value".
338 *
339 ******************************************************************************/
BTM_BleOobDataReply(const RawAddress & bd_addr,uint8_t res,uint8_t len,uint8_t * p_data)340 void BTM_BleOobDataReply(const RawAddress& bd_addr, uint8_t res, uint8_t len,
341 uint8_t* p_data) {
342 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
343 if (p_dev_rec == NULL) {
344 log::error("Unknown device:{}", bd_addr);
345 return;
346 }
347
348 const tSMP_STATUS res_smp = (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_OOB_FAIL;
349 BTM_LogHistory(kBtmLogTag, bd_addr, "Oob data reply",
350 base::StringPrintf("transport:%s authenticate_status:%s",
351 bt_transport_text(BT_TRANSPORT_LE).c_str(),
352 smp_status_text(res_smp).c_str()));
353
354 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_LE_AUTHENTICATED;
355 SMP_OobDataReply(bd_addr, res_smp, len, p_data);
356 }
357
358 /*******************************************************************************
359 *
360 * Function BTM_BleSecureConnectionOobDataReply
361 *
362 * Description This function is called to provide the OOB data for
363 * SMP in response to BTM_LE_OOB_REQ_EVT when secure connection
364 * data is available
365 *
366 * Parameters: bd_addr - Address of the peer device
367 * p_c - pointer to Confirmation.
368 * p_r - pointer to Randomizer
369 *
370 ******************************************************************************/
BTM_BleSecureConnectionOobDataReply(const RawAddress & bd_addr,uint8_t * p_c,uint8_t * p_r)371 void BTM_BleSecureConnectionOobDataReply(const RawAddress& bd_addr,
372 uint8_t* p_c, uint8_t* p_r) {
373 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
374 if (p_dev_rec == NULL) {
375 log::error("Unknown device:{}", bd_addr);
376 return;
377 }
378
379 BTM_LogHistory(
380 kBtmLogTag, bd_addr, "Oob data reply",
381 base::StringPrintf("transport:%s",
382 bt_transport_text(BT_TRANSPORT_LE).c_str()));
383
384 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_LE_AUTHENTICATED;
385
386 tSMP_SC_OOB_DATA oob;
387 memset(&oob, 0, sizeof(tSMP_SC_OOB_DATA));
388
389 oob.peer_oob_data.present = true;
390 memcpy(&oob.peer_oob_data.randomizer, p_r, OCTET16_LEN);
391 memcpy(&oob.peer_oob_data.commitment, p_c, OCTET16_LEN);
392 oob.peer_oob_data.addr_rcvd_from.type = p_dev_rec->ble.AddressType();
393 oob.peer_oob_data.addr_rcvd_from.bda = bd_addr;
394
395 SMP_SecureConnectionOobDataReply((uint8_t*)&oob);
396 }
397
398 /********************************************************
399 *
400 * Function BTM_BleSetPrefConnParams
401 *
402 * Description Set a peripheral's preferred connection parameters
403 *
404 * Parameters: bd_addr - BD address of the peripheral
405 * scan_interval: scan interval
406 * scan_window: scan window
407 * min_conn_int - minimum preferred connection interval
408 * max_conn_int - maximum preferred connection interval
409 * peripheral_latency - preferred peripheral latency
410 * supervision_tout - preferred supervision timeout
411 *
412 * Returns void
413 *
414 ******************************************************************************/
BTM_BleSetPrefConnParams(const RawAddress & bd_addr,uint16_t min_conn_int,uint16_t max_conn_int,uint16_t peripheral_latency,uint16_t supervision_tout)415 void BTM_BleSetPrefConnParams(const RawAddress& bd_addr, uint16_t min_conn_int,
416 uint16_t max_conn_int,
417 uint16_t peripheral_latency,
418 uint16_t supervision_tout) {
419 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
420
421 log::verbose("min:{},max:{},latency:{},tout:{}", min_conn_int, max_conn_int,
422 peripheral_latency, supervision_tout);
423
424 if (BTM_BLE_ISVALID_PARAM(min_conn_int, BTM_BLE_CONN_INT_MIN,
425 BTM_BLE_CONN_INT_MAX) &&
426 BTM_BLE_ISVALID_PARAM(max_conn_int, BTM_BLE_CONN_INT_MIN,
427 BTM_BLE_CONN_INT_MAX) &&
428 BTM_BLE_ISVALID_PARAM(supervision_tout, BTM_BLE_CONN_SUP_TOUT_MIN,
429 BTM_BLE_CONN_SUP_TOUT_MAX) &&
430 (peripheral_latency <= BTM_BLE_CONN_LATENCY_MAX ||
431 peripheral_latency == BTM_BLE_CONN_PARAM_UNDEF)) {
432 if (p_dev_rec) {
433 /* expect conn int and stout and peripheral latency to be updated all
434 * together
435 */
436 if (min_conn_int != BTM_BLE_CONN_PARAM_UNDEF ||
437 max_conn_int != BTM_BLE_CONN_PARAM_UNDEF) {
438 if (min_conn_int != BTM_BLE_CONN_PARAM_UNDEF)
439 p_dev_rec->conn_params.min_conn_int = min_conn_int;
440 else
441 p_dev_rec->conn_params.min_conn_int = max_conn_int;
442
443 if (max_conn_int != BTM_BLE_CONN_PARAM_UNDEF)
444 p_dev_rec->conn_params.max_conn_int = max_conn_int;
445 else
446 p_dev_rec->conn_params.max_conn_int = min_conn_int;
447
448 if (peripheral_latency != BTM_BLE_CONN_PARAM_UNDEF)
449 p_dev_rec->conn_params.peripheral_latency = peripheral_latency;
450 else
451 p_dev_rec->conn_params.peripheral_latency =
452 BTM_BLE_CONN_PERIPHERAL_LATENCY_DEF;
453
454 if (supervision_tout != BTM_BLE_CONN_PARAM_UNDEF)
455 p_dev_rec->conn_params.supervision_tout = supervision_tout;
456 else
457 p_dev_rec->conn_params.supervision_tout = BTM_BLE_CONN_TIMEOUT_DEF;
458 }
459
460 } else {
461 log::error("Unknown Device, setting rejected");
462 }
463 } else {
464 log::error("Illegal Connection Parameters");
465 }
466 }
467
468 /*******************************************************************************
469 *
470 * Function BTM_ReadDevInfo
471 *
472 * Description This function is called to read the device/address type
473 * of BD address.
474 *
475 * Parameter remote_bda: remote device address
476 * p_dev_type: output parameter to read the device type.
477 * p_addr_type: output parameter to read the address type.
478 *
479 ******************************************************************************/
BTM_ReadDevInfo(const RawAddress & remote_bda,tBT_DEVICE_TYPE * p_dev_type,tBLE_ADDR_TYPE * p_addr_type)480 void BTM_ReadDevInfo(const RawAddress& remote_bda, tBT_DEVICE_TYPE* p_dev_type,
481 tBLE_ADDR_TYPE* p_addr_type) {
482 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(remote_bda);
483 tBTM_INQ_INFO* p_inq_info = BTM_InqDbRead(remote_bda);
484
485 *p_addr_type = BLE_ADDR_PUBLIC;
486
487 if (!p_dev_rec) {
488 *p_dev_type = BT_DEVICE_TYPE_BREDR;
489 /* Check with the BT manager if details about remote device are known */
490 if (p_inq_info != NULL) {
491 *p_dev_type = p_inq_info->results.device_type;
492 *p_addr_type = p_inq_info->results.ble_addr_type;
493 } else {
494 /* unknown device, assume BR/EDR */
495 log::verbose("unknown device, BR/EDR assumed");
496 }
497 } else /* there is a security device record existing */
498 {
499 /* new inquiry result, merge device type in security device record */
500 if (p_inq_info) {
501 p_dev_rec->device_type |= p_inq_info->results.device_type;
502 if (is_ble_addr_type_known(p_inq_info->results.ble_addr_type))
503 p_dev_rec->ble.SetAddressType(p_inq_info->results.ble_addr_type);
504 else
505 log::warn(
506 "Please do not update device record from anonymous le "
507 "advertisement");
508 }
509
510 if (p_dev_rec->bd_addr == remote_bda &&
511 p_dev_rec->ble.pseudo_addr == remote_bda) {
512 *p_dev_type = p_dev_rec->device_type;
513 *p_addr_type = p_dev_rec->ble.AddressType();
514 } else if (p_dev_rec->ble.pseudo_addr == remote_bda) {
515 *p_dev_type = BT_DEVICE_TYPE_BLE;
516 *p_addr_type = p_dev_rec->ble.AddressType();
517 } else /* matching static address only */ {
518 if (p_dev_rec->device_type != BT_DEVICE_TYPE_UNKNOWN) {
519 *p_dev_type = p_dev_rec->device_type;
520 } else {
521 log::warn("device_type not set; assuming BR/EDR");
522 *p_dev_type = BT_DEVICE_TYPE_BREDR;
523 }
524 *p_addr_type = BLE_ADDR_PUBLIC;
525 }
526 }
527 log::debug("Determined device_type:{} addr_type:{}",
528 DeviceTypeText(*p_dev_type), AddressTypeText(*p_addr_type));
529 }
530
531 /*******************************************************************************
532 *
533 * Function BTM_ReadConnectedTransportAddress
534 *
535 * Description This function is called to read the paired device/address
536 * type of other device paired corresponding to the BD_address
537 *
538 * Parameter remote_bda: remote device address, carry out the transport
539 * address
540 * transport: active transport
541 *
542 * Return true if an active link is identified; false otherwise
543 *
544 ******************************************************************************/
BTM_ReadConnectedTransportAddress(RawAddress * remote_bda,tBT_TRANSPORT transport)545 bool BTM_ReadConnectedTransportAddress(RawAddress* remote_bda,
546 tBT_TRANSPORT transport) {
547 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(*remote_bda);
548
549 /* if no device can be located, return */
550 if (p_dev_rec == NULL) return false;
551
552 if (transport == BT_TRANSPORT_BR_EDR) {
553 if (BTM_IsAclConnectionUp(p_dev_rec->bd_addr, transport)) {
554 *remote_bda = p_dev_rec->bd_addr;
555 return true;
556 } else if (p_dev_rec->device_type & BT_DEVICE_TYPE_BREDR) {
557 *remote_bda = p_dev_rec->bd_addr;
558 } else
559 *remote_bda = RawAddress::kEmpty;
560 return false;
561 }
562
563 if (transport == BT_TRANSPORT_LE) {
564 *remote_bda = p_dev_rec->ble.pseudo_addr;
565 if (BTM_IsAclConnectionUp(p_dev_rec->ble.pseudo_addr, transport))
566 return true;
567 else
568 return false;
569 }
570
571 return false;
572 }
573
BTM_SetBleDataLength(const RawAddress & bd_addr,uint16_t tx_pdu_length)574 tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr,
575 uint16_t tx_pdu_length) {
576 if (!bluetooth::shim::GetController()
577 ->SupportsBleDataPacketLengthExtension()) {
578 log::info("Local controller does not support le packet extension");
579 return BTM_ILLEGAL_VALUE;
580 }
581
582 log::info("bd_addr:{}, tx_pdu_length:{}", bd_addr, tx_pdu_length);
583
584 auto p_dev_rec = btm_find_dev(bd_addr);
585 if (p_dev_rec == NULL) {
586 log::error("Device {} not found", bd_addr);
587 return BTM_UNKNOWN_ADDR;
588 }
589
590 if (tx_pdu_length > BTM_BLE_DATA_SIZE_MAX)
591 tx_pdu_length = BTM_BLE_DATA_SIZE_MAX;
592 else if (tx_pdu_length < BTM_BLE_DATA_SIZE_MIN)
593 tx_pdu_length = BTM_BLE_DATA_SIZE_MIN;
594
595 if (p_dev_rec->get_suggested_tx_octets() >= tx_pdu_length) {
596 log::info("Suggested TX octect already set to controller {} >= {}",
597 p_dev_rec->get_suggested_tx_octets(), tx_pdu_length);
598 return BTM_SUCCESS;
599 }
600
601 uint16_t tx_time = BTM_BLE_DATA_TX_TIME_MAX_LEGACY;
602
603 if (bluetooth::shim::GetController()
604 ->GetLocalVersionInformation()
605 .hci_version_ >= bluetooth::hci::HciVersion::V_5_0)
606 tx_time = BTM_BLE_DATA_TX_TIME_MAX;
607
608 if (!BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) {
609 log::info(
610 "Unable to set data length because no le acl link connected to device");
611 return BTM_WRONG_MODE;
612 }
613
614 uint16_t hci_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE);
615
616 if (!acl_peer_supports_ble_packet_extension(hci_handle)) {
617 log::info("Remote device unable to support le packet extension");
618 return BTM_ILLEGAL_VALUE;
619 }
620
621 tx_pdu_length =
622 std::min<uint16_t>(tx_pdu_length, bluetooth::shim::GetController()
623 ->GetLeMaximumDataLength()
624 .supported_max_tx_octets_);
625 tx_time = std::min<uint16_t>(tx_time, bluetooth::shim::GetController()
626 ->GetLeMaximumDataLength()
627 .supported_max_tx_time_);
628
629 btsnd_hcic_ble_set_data_length(hci_handle, tx_pdu_length, tx_time);
630 p_dev_rec->set_suggested_tx_octect(tx_pdu_length);
631
632 return BTM_SUCCESS;
633 }
634
635 /*******************************************************************************
636 *
637 * Function btm_ble_determine_security_act
638 *
639 * Description This function checks the security of current LE link
640 * and returns the appropriate action that needs to be
641 * taken to achieve the required security.
642 *
643 * Parameter is_originator - True if outgoing connection
644 * bdaddr: remote device address
645 * security_required: Security required for the service.
646 *
647 * Returns The appropriate security action required.
648 *
649 ******************************************************************************/
btm_ble_determine_security_act(bool is_originator,const RawAddress & bdaddr,uint16_t security_required)650 static tBTM_SEC_ACTION btm_ble_determine_security_act(
651 bool is_originator, const RawAddress& bdaddr, uint16_t security_required) {
652 tBTM_LE_AUTH_REQ auth_req = 0x00;
653
654 if (is_originator) {
655 if ((security_required & BTM_SEC_OUT_FLAGS) == 0 &&
656 (security_required & BTM_SEC_OUT_MITM) == 0) {
657 log::info("No security required for outgoing connection");
658 return BTM_SEC_OK;
659 }
660
661 if (security_required & BTM_SEC_OUT_MITM) auth_req |= BTM_LE_AUTH_REQ_MITM;
662 } else {
663 if ((security_required & BTM_SEC_IN_FLAGS) == 0 &&
664 (security_required & BTM_SEC_IN_MITM) == 0) {
665 log::verbose("No security required for incoming connection");
666 return BTM_SEC_OK;
667 }
668
669 if (security_required & BTM_SEC_IN_MITM) auth_req |= BTM_LE_AUTH_REQ_MITM;
670 }
671
672 tBTM_BLE_SEC_REQ_ACT ble_sec_act = {BTM_BLE_SEC_REQ_ACT_NONE};
673 btm_ble_link_sec_check(bdaddr, auth_req, &ble_sec_act);
674
675 log::verbose("ble_sec_act {}", ble_sec_act);
676
677 if (ble_sec_act == BTM_BLE_SEC_REQ_ACT_DISCARD) return BTM_SEC_ENC_PENDING;
678
679 if (ble_sec_act == BTM_BLE_SEC_REQ_ACT_NONE) return BTM_SEC_OK;
680
681 bool is_link_encrypted = BTM_IsEncrypted(bdaddr, BT_TRANSPORT_LE);
682 bool is_key_mitm = BTM_IsLinkKeyAuthed(bdaddr, BT_TRANSPORT_LE);
683
684 if (auth_req & BTM_LE_AUTH_REQ_MITM) {
685 if (!is_key_mitm) {
686 return BTM_SEC_ENCRYPT_MITM;
687 } else {
688 if (is_link_encrypted)
689 return BTM_SEC_OK;
690 else
691 return BTM_SEC_ENCRYPT;
692 }
693 } else {
694 if (is_link_encrypted)
695 return BTM_SEC_OK;
696 else
697 return BTM_SEC_ENCRYPT_NO_MITM;
698 }
699
700 return BTM_SEC_OK;
701 }
702
703 /*******************************************************************************
704 *
705 * Function btm_ble_start_sec_check
706 *
707 * Description This function is to check and set the security required for
708 * LE link for LE COC.
709 *
710 * Parameter bdaddr: remote device address.
711 * psm : PSM of the LE COC service.
712 * is_originator: true if outgoing connection.
713 * p_callback : Pointer to the callback function.
714 * p_ref_data : Pointer to be returned along with the callback.
715 *
716 * Returns Returns - tBTM_STATUS
717 *
718 ******************************************************************************/
btm_ble_start_sec_check(const RawAddress & bd_addr,uint16_t psm,bool is_originator,tBTM_SEC_CALLBACK * p_callback,void * p_ref_data)719 tBTM_STATUS btm_ble_start_sec_check(const RawAddress& bd_addr, uint16_t psm,
720 bool is_originator,
721 tBTM_SEC_CALLBACK* p_callback,
722 void* p_ref_data) {
723 /* Find the service record for the PSM */
724 tBTM_SEC_SERV_REC* p_serv_rec =
725 btm_sec_cb.find_first_serv_rec(is_originator, psm);
726
727 /* If there is no application registered with this PSM do not allow connection
728 */
729 if (!p_serv_rec) {
730 log::warn("PSM: {} no application registered", psm);
731 (*p_callback)(bd_addr, BT_TRANSPORT_LE, p_ref_data, BTM_MODE_UNSUPPORTED);
732 return BTM_ILLEGAL_VALUE;
733 }
734
735 bool is_encrypted = BTM_IsEncrypted(bd_addr, BT_TRANSPORT_LE);
736 bool is_link_key_authed = BTM_IsLinkKeyAuthed(bd_addr, BT_TRANSPORT_LE);
737 bool is_authenticated = BTM_IsAuthenticated(bd_addr, BT_TRANSPORT_LE);
738
739 if (!is_originator) {
740 if ((p_serv_rec->security_flags & BTM_SEC_IN_ENCRYPT) && !is_encrypted) {
741 log::error("BTM_NOT_ENCRYPTED. service security_flags=0x{:x}",
742 p_serv_rec->security_flags);
743 return BTM_NOT_ENCRYPTED;
744 } else if ((p_serv_rec->security_flags & BTM_SEC_IN_AUTHENTICATE) &&
745 !(is_link_key_authed || is_authenticated)) {
746 log::error("BTM_NOT_AUTHENTICATED. service security_flags=0x{:x}",
747 p_serv_rec->security_flags);
748 return BTM_NOT_AUTHENTICATED;
749 }
750 /* TODO: When security is required, then must check that the key size of our
751 service is equal or smaller than the incoming connection key size. */
752 }
753
754 tBTM_SEC_ACTION sec_act = btm_ble_determine_security_act(
755 is_originator, bd_addr, p_serv_rec->security_flags);
756
757 tBTM_BLE_SEC_ACT ble_sec_act = BTM_BLE_SEC_NONE;
758
759 switch (sec_act) {
760 case BTM_SEC_OK:
761 log::debug("Security met");
762 p_callback(bd_addr, BT_TRANSPORT_LE, p_ref_data, BTM_SUCCESS);
763 break;
764
765 case BTM_SEC_ENCRYPT:
766 log::debug("Encryption needs to be done");
767 ble_sec_act = BTM_BLE_SEC_ENCRYPT;
768 break;
769
770 case BTM_SEC_ENCRYPT_MITM:
771 log::debug("Pairing with MITM needs to be done");
772 ble_sec_act = BTM_BLE_SEC_ENCRYPT_MITM;
773 break;
774
775 case BTM_SEC_ENCRYPT_NO_MITM:
776 log::debug("Pairing with No MITM needs to be done");
777 ble_sec_act = BTM_BLE_SEC_ENCRYPT_NO_MITM;
778 break;
779
780 case BTM_SEC_ENC_PENDING:
781 log::debug("Ecryption pending");
782 break;
783 }
784
785 if (ble_sec_act == BTM_BLE_SEC_NONE && sec_act != BTM_SEC_ENC_PENDING) {
786 return BTM_SUCCESS;
787 }
788
789 l2cble_update_sec_act(bd_addr, sec_act);
790
791 BTM_SetEncryption(bd_addr, BT_TRANSPORT_LE, p_callback, p_ref_data,
792 ble_sec_act);
793
794 return BTM_SUCCESS;
795 }
796
797 /*******************************************************************************
798 *
799 * Function increment_sign_counter
800 *
801 * Description This method is to increment the (local or peer) sign counter
802 * Returns None
803 *
804 ******************************************************************************/
increment_sign_counter(bool local)805 void tBTM_SEC_REC::increment_sign_counter(bool local) {
806 if (local) {
807 ble_keys.local_counter++;
808 } else {
809 ble_keys.counter++;
810 }
811
812 log::verbose("local={} local sign counter={} peer sign counter={}", local,
813 ble_keys.local_counter, ble_keys.counter);
814 }
815
816 /*******************************************************************************
817 *
818 * Function btm_ble_get_enc_key_type
819 *
820 * Description This function is to get the BLE key type that has been
821 * exchanged between the local device and the peer device.
822 *
823 * Returns p_key_type: output parameter to carry the key type value.
824 *
825 ******************************************************************************/
btm_ble_get_enc_key_type(const RawAddress & bd_addr,uint8_t * p_key_types)826 bool btm_ble_get_enc_key_type(const RawAddress& bd_addr, uint8_t* p_key_types) {
827 tBTM_SEC_DEV_REC* p_dev_rec;
828
829 log::verbose("bd_addr:{}", bd_addr);
830
831 p_dev_rec = btm_find_dev(bd_addr);
832 if (p_dev_rec != NULL) {
833 *p_key_types = p_dev_rec->sec_rec.ble_keys.key_type;
834 return true;
835 }
836 return false;
837 }
838
839 /*******************************************************************************
840 *
841 * Function btm_get_local_div
842 *
843 * Description This function is called to read the local DIV
844 *
845 * Returns TRUE - if a valid DIV is availavle
846 ******************************************************************************/
btm_get_local_div(const RawAddress & bd_addr,uint16_t * p_div)847 bool btm_get_local_div(const RawAddress& bd_addr, uint16_t* p_div) {
848 tBTM_SEC_DEV_REC* p_dev_rec;
849 bool status = false;
850
851 *p_div = 0;
852 p_dev_rec = btm_find_dev(bd_addr);
853
854 if (p_dev_rec && p_dev_rec->sec_rec.ble_keys.div) {
855 status = true;
856 *p_div = p_dev_rec->sec_rec.ble_keys.div;
857 }
858 log::verbose("status={} (1-OK) DIV=0x{:x}", status, *p_div);
859 return status;
860 }
861
862 /*******************************************************************************
863 *
864 * Function btm_sec_save_le_key
865 *
866 * Description This function is called by the SMP to update
867 * an BLE key. SMP is internal, whereas all the keys shall
868 * be sent to the application. The function is also called
869 * when application passes ble key stored in NVRAM to the
870 * btm_sec.
871 * pass_to_application parameter is false in this case.
872 *
873 * Returns void
874 *
875 ******************************************************************************/
btm_sec_save_le_key(const RawAddress & bd_addr,tBTM_LE_KEY_TYPE key_type,tBTM_LE_KEY_VALUE * p_keys,bool pass_to_application)876 void btm_sec_save_le_key(const RawAddress& bd_addr, tBTM_LE_KEY_TYPE key_type,
877 tBTM_LE_KEY_VALUE* p_keys, bool pass_to_application) {
878 tBTM_SEC_DEV_REC* p_rec;
879 tBTM_LE_EVT_DATA cb_data;
880
881 log::verbose("key_type=0x{:x} pass_to_application={}", key_type,
882 pass_to_application);
883 /* Store the updated key in the device database */
884
885 if ((p_rec = btm_find_dev(bd_addr)) != NULL &&
886 (p_keys || key_type == BTM_LE_KEY_LID)) {
887 btm_ble_init_pseudo_addr(p_rec, bd_addr);
888
889 switch (key_type) {
890 case BTM_LE_KEY_PENC:
891 p_rec->sec_rec.ble_keys.pltk = p_keys->penc_key.ltk;
892 memcpy(p_rec->sec_rec.ble_keys.rand, p_keys->penc_key.rand,
893 BT_OCTET8_LEN);
894 p_rec->sec_rec.ble_keys.sec_level = p_keys->penc_key.sec_level;
895 p_rec->sec_rec.ble_keys.ediv = p_keys->penc_key.ediv;
896 p_rec->sec_rec.ble_keys.key_size = p_keys->penc_key.key_size;
897 p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_PENC;
898 p_rec->sec_rec.sec_flags |= BTM_SEC_LE_LINK_KEY_KNOWN;
899 if (p_keys->penc_key.sec_level == SMP_SEC_AUTHENTICATED)
900 p_rec->sec_rec.sec_flags |= BTM_SEC_LE_LINK_KEY_AUTHED;
901 else
902 p_rec->sec_rec.sec_flags &= ~BTM_SEC_LE_LINK_KEY_AUTHED;
903 log::verbose(
904 "BTM_LE_KEY_PENC key_type=0x{:x} sec_flags=0x{:x} sec_leve=0x{:x}",
905 p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.sec_flags,
906 p_rec->sec_rec.ble_keys.sec_level);
907 break;
908
909 case BTM_LE_KEY_PID:
910 p_rec->sec_rec.ble_keys.irk = p_keys->pid_key.irk;
911 p_rec->ble.identity_address_with_type.bda =
912 p_keys->pid_key.identity_addr;
913 p_rec->ble.identity_address_with_type.type =
914 p_keys->pid_key.identity_addr_type;
915 p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_PID;
916 log::verbose(
917 "BTM_LE_KEY_PID key_type=0x{:x} save peer IRK, change bd_addr={} "
918 "to id_addr={} id_addr_type=0x{:x}",
919 p_rec->sec_rec.ble_keys.key_type, p_rec->bd_addr,
920 p_keys->pid_key.identity_addr, p_keys->pid_key.identity_addr_type);
921 /* update device record address as identity address */
922 p_rec->bd_addr = p_keys->pid_key.identity_addr;
923 /* combine DUMO device security record if needed */
924 btm_consolidate_dev(p_rec);
925 break;
926
927 case BTM_LE_KEY_PCSRK:
928 p_rec->sec_rec.ble_keys.pcsrk = p_keys->pcsrk_key.csrk;
929 p_rec->sec_rec.ble_keys.srk_sec_level = p_keys->pcsrk_key.sec_level;
930 p_rec->sec_rec.ble_keys.counter = p_keys->pcsrk_key.counter;
931 p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_PCSRK;
932 p_rec->sec_rec.sec_flags |= BTM_SEC_LE_LINK_KEY_KNOWN;
933 if (p_keys->pcsrk_key.sec_level == SMP_SEC_AUTHENTICATED)
934 p_rec->sec_rec.sec_flags |= BTM_SEC_LE_LINK_KEY_AUTHED;
935 else
936 p_rec->sec_rec.sec_flags &= ~BTM_SEC_LE_LINK_KEY_AUTHED;
937
938 log::verbose(
939 "BTM_LE_KEY_PCSRK key_type=0x{:x} sec_flags=0x{:x} "
940 "sec_level=0x{:x} peer_counter={}",
941 p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.sec_flags,
942 p_rec->sec_rec.ble_keys.srk_sec_level,
943 p_rec->sec_rec.ble_keys.counter);
944 break;
945
946 case BTM_LE_KEY_LENC:
947 p_rec->sec_rec.ble_keys.lltk = p_keys->lenc_key.ltk;
948 p_rec->sec_rec.ble_keys.div = p_keys->lenc_key.div; /* update DIV */
949 p_rec->sec_rec.ble_keys.sec_level = p_keys->lenc_key.sec_level;
950 p_rec->sec_rec.ble_keys.key_size = p_keys->lenc_key.key_size;
951 p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_LENC;
952
953 log::verbose(
954 "BTM_LE_KEY_LENC key_type=0x{:x} DIV=0x{:x} key_size=0x{:x} "
955 "sec_level=0x{:x}",
956 p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.ble_keys.div,
957 p_rec->sec_rec.ble_keys.key_size,
958 p_rec->sec_rec.ble_keys.sec_level);
959 break;
960
961 case BTM_LE_KEY_LCSRK: /* local CSRK has been delivered */
962 p_rec->sec_rec.ble_keys.lcsrk = p_keys->lcsrk_key.csrk;
963 p_rec->sec_rec.ble_keys.div = p_keys->lcsrk_key.div; /* update DIV */
964 p_rec->sec_rec.ble_keys.local_csrk_sec_level =
965 p_keys->lcsrk_key.sec_level;
966 p_rec->sec_rec.ble_keys.local_counter = p_keys->lcsrk_key.counter;
967 p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_LCSRK;
968 log::verbose(
969 "BTM_LE_KEY_LCSRK key_type=0x{:x} DIV=0x{:x} scrk_sec_level=0x{:x} "
970 "local_counter={}",
971 p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.ble_keys.div,
972 p_rec->sec_rec.ble_keys.local_csrk_sec_level,
973 p_rec->sec_rec.ble_keys.local_counter);
974 break;
975
976 case BTM_LE_KEY_LID:
977 p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_LID;
978 break;
979 default:
980 log::warn("btm_sec_save_le_key (Bad key_type 0x{:02x})", key_type);
981 return;
982 }
983
984 log::verbose("BLE key type 0x{:x}, updated for BDA:{}", key_type, bd_addr);
985
986 /* Notify the application that one of the BLE keys has been updated
987 If link key is in progress, it will get sent later.*/
988 if (pass_to_application && btm_sec_cb.api.p_le_callback) {
989 cb_data.key.p_key_value = p_keys;
990 cb_data.key.key_type = key_type;
991
992 (*btm_sec_cb.api.p_le_callback)(BTM_LE_KEY_EVT, bd_addr, &cb_data);
993 }
994 return;
995 }
996
997 log::warn("BLE key type 0x{:x}, called for Unknown BDA or type:{}", key_type,
998 bd_addr);
999
1000 if (p_rec) {
1001 log::verbose("sec_flags=0x{:x}", p_rec->sec_rec.sec_flags);
1002 }
1003 }
1004
1005 /*******************************************************************************
1006 *
1007 * Function btm_ble_update_sec_key_size
1008 *
1009 * Description update the current lin kencryption key size
1010 *
1011 * Returns void
1012 *
1013 ******************************************************************************/
btm_ble_update_sec_key_size(const RawAddress & bd_addr,uint8_t enc_key_size)1014 void btm_ble_update_sec_key_size(const RawAddress& bd_addr,
1015 uint8_t enc_key_size) {
1016 tBTM_SEC_DEV_REC* p_rec;
1017
1018 log::verbose("bd_addr:{}, enc_key_size={}", bd_addr, enc_key_size);
1019
1020 p_rec = btm_find_dev(bd_addr);
1021 if (p_rec != NULL) {
1022 p_rec->sec_rec.enc_key_size = enc_key_size;
1023 }
1024 }
1025
1026 /*******************************************************************************
1027 *
1028 * Function btm_ble_read_sec_key_size
1029 *
1030 * Description update the current lin kencryption key size
1031 *
1032 * Returns void
1033 *
1034 ******************************************************************************/
btm_ble_read_sec_key_size(const RawAddress & bd_addr)1035 uint8_t btm_ble_read_sec_key_size(const RawAddress& bd_addr) {
1036 tBTM_SEC_DEV_REC* p_rec;
1037
1038 p_rec = btm_find_dev(bd_addr);
1039 if (p_rec != NULL) {
1040 return p_rec->sec_rec.enc_key_size;
1041 } else
1042 return 0;
1043 }
1044
1045 /*******************************************************************************
1046 *
1047 * Function btm_ble_link_sec_check
1048 *
1049 * Description Check BLE link security level match.
1050 *
1051 * Returns true: check is OK and the *p_sec_req_act contain the action
1052 *
1053 ******************************************************************************/
btm_ble_link_sec_check(const RawAddress & bd_addr,tBTM_LE_AUTH_REQ auth_req,tBTM_BLE_SEC_REQ_ACT * p_sec_req_act)1054 void btm_ble_link_sec_check(const RawAddress& bd_addr,
1055 tBTM_LE_AUTH_REQ auth_req,
1056 tBTM_BLE_SEC_REQ_ACT* p_sec_req_act) {
1057 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
1058 uint8_t req_sec_level = SMP_SEC_NONE, cur_sec_level = SMP_SEC_NONE;
1059
1060 log::verbose("bd_addr:{}, auth_req=0x{:x}", bd_addr, auth_req);
1061
1062 if (p_dev_rec == NULL) {
1063 log::error("received for unknown device");
1064 return;
1065 }
1066
1067 if (p_dev_rec->sec_rec.is_security_state_encrypting() ||
1068 p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_AUTHENTICATING) {
1069 /* race condition: discard the security request while central is encrypting
1070 * the link */
1071 *p_sec_req_act = BTM_BLE_SEC_REQ_ACT_DISCARD;
1072 } else {
1073 req_sec_level = SMP_SEC_UNAUTHENTICATE;
1074 if (auth_req & BTM_LE_AUTH_REQ_MITM) {
1075 req_sec_level = SMP_SEC_AUTHENTICATED;
1076 }
1077
1078 log::verbose("dev_rec sec_flags=0x{:x}", p_dev_rec->sec_rec.sec_flags);
1079
1080 /* currently encrpted */
1081 if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_ENCRYPTED) {
1082 if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_AUTHENTICATED)
1083 cur_sec_level = SMP_SEC_AUTHENTICATED;
1084 else
1085 cur_sec_level = SMP_SEC_UNAUTHENTICATE;
1086 } else /* unencrypted link */
1087 {
1088 /* if bonded, get the key security level */
1089 if (p_dev_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_PENC)
1090 cur_sec_level = p_dev_rec->sec_rec.ble_keys.sec_level;
1091 else
1092 cur_sec_level = SMP_SEC_NONE;
1093 }
1094
1095 if (cur_sec_level >= req_sec_level) {
1096 /* To avoid re-encryption on an encrypted link for an equal condition
1097 * encryption */
1098 *p_sec_req_act = BTM_BLE_SEC_REQ_ACT_ENCRYPT;
1099 } else {
1100 /* start the pariring process to upgrade the keys*/
1101 *p_sec_req_act = BTM_BLE_SEC_REQ_ACT_PAIR;
1102 }
1103 }
1104
1105 log::verbose("cur_sec_level={} req_sec_level={} sec_req_act={}",
1106 cur_sec_level, req_sec_level, *p_sec_req_act);
1107 }
1108
1109 /*******************************************************************************
1110 *
1111 * Function btm_ble_set_encryption
1112 *
1113 * Description This function is called to ensure that LE connection is
1114 * encrypted. Should be called only on an open connection.
1115 * Typically only needed for connections that first want to
1116 * bring up unencrypted links, then later encrypt them.
1117 *
1118 * Returns void
1119 * the local device ER is copied into er
1120 *
1121 ******************************************************************************/
btm_ble_set_encryption(const RawAddress & bd_addr,tBTM_BLE_SEC_ACT sec_act,uint8_t link_role)1122 tBTM_STATUS btm_ble_set_encryption(const RawAddress& bd_addr,
1123 tBTM_BLE_SEC_ACT sec_act,
1124 uint8_t link_role) {
1125 tBTM_STATUS cmd = BTM_NO_RESOURCES;
1126 tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bd_addr);
1127 tBTM_BLE_SEC_REQ_ACT sec_req_act;
1128 tBTM_LE_AUTH_REQ auth_req;
1129
1130 if (p_rec == NULL) {
1131 log::warn("NULL device record!! sec_act=0x{:x}", sec_act);
1132 return (BTM_WRONG_MODE);
1133 }
1134
1135 log::verbose("sec_act=0x{:x} role_central={}", sec_act, p_rec->role_central);
1136
1137 if (sec_act == BTM_BLE_SEC_ENCRYPT_MITM) {
1138 p_rec->sec_rec.security_required |= BTM_SEC_IN_MITM;
1139 }
1140
1141 switch (sec_act) {
1142 case BTM_BLE_SEC_ENCRYPT:
1143 if (link_role == HCI_ROLE_CENTRAL) {
1144 /* start link layer encryption using the security info stored */
1145 cmd = btm_ble_start_encrypt(bd_addr, false, NULL);
1146 break;
1147 }
1148 /* if salve role then fall through to call SMP_Pair below which will send
1149 a sec_request to request the central to encrypt the link */
1150 FALLTHROUGH_INTENDED; /* FALLTHROUGH */
1151 case BTM_BLE_SEC_ENCRYPT_NO_MITM:
1152 case BTM_BLE_SEC_ENCRYPT_MITM:
1153 auth_req = (sec_act == BTM_BLE_SEC_ENCRYPT_NO_MITM)
1154 ? SMP_AUTH_BOND
1155 : (SMP_AUTH_BOND | SMP_AUTH_YN_BIT);
1156 btm_ble_link_sec_check(bd_addr, auth_req, &sec_req_act);
1157 if (sec_req_act == BTM_BLE_SEC_REQ_ACT_NONE ||
1158 sec_req_act == BTM_BLE_SEC_REQ_ACT_DISCARD) {
1159 log::verbose("no action needed. Ignore");
1160 cmd = BTM_SUCCESS;
1161 break;
1162 }
1163 if (link_role == HCI_ROLE_CENTRAL) {
1164 if (sec_req_act == BTM_BLE_SEC_REQ_ACT_ENCRYPT) {
1165 cmd = btm_ble_start_encrypt(bd_addr, false, NULL);
1166 break;
1167 }
1168 }
1169
1170 if (SMP_Pair(bd_addr) == SMP_STARTED) {
1171 cmd = BTM_CMD_STARTED;
1172 p_rec->sec_rec.sec_state = BTM_SEC_STATE_AUTHENTICATING;
1173 }
1174 break;
1175
1176 default:
1177 cmd = BTM_WRONG_MODE;
1178 break;
1179 }
1180 return cmd;
1181 }
1182
1183 /*******************************************************************************
1184 *
1185 * Function btm_ble_ltk_request
1186 *
1187 * Description This function is called when encryption request is received
1188 * on a peripheral device.
1189 *
1190 *
1191 * Returns void
1192 *
1193 ******************************************************************************/
btm_ble_ltk_request(uint16_t handle,BT_OCTET8 rand,uint16_t ediv)1194 void btm_ble_ltk_request(uint16_t handle, BT_OCTET8 rand, uint16_t ediv) {
1195 tBTM_SEC_CB* p_cb = &btm_sec_cb;
1196 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
1197
1198 log::verbose("handle:0x{:x}", handle);
1199
1200 p_cb->ediv = ediv;
1201
1202 memcpy(p_cb->enc_rand, rand, BT_OCTET8_LEN);
1203
1204 if (p_dev_rec != NULL) {
1205 if (!smp_proc_ltk_request(p_dev_rec->bd_addr)) {
1206 btm_ble_ltk_request_reply(p_dev_rec->bd_addr, false, Octet16{0});
1207 }
1208 }
1209 }
1210
1211 /** This function is called to start LE encryption.
1212 * Returns BTM_SUCCESS if encryption was started successfully
1213 */
btm_ble_start_encrypt(const RawAddress & bda,bool use_stk,Octet16 * p_stk)1214 tBTM_STATUS btm_ble_start_encrypt(const RawAddress& bda, bool use_stk,
1215 Octet16* p_stk) {
1216 tBTM_SEC_CB* p_cb = &btm_sec_cb;
1217 tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bda);
1218 BT_OCTET8 dummy_rand = {0};
1219
1220 log::verbose("bd_addr:{}, use_stk:{}", bda, use_stk);
1221
1222 if (!p_rec) {
1223 log::error("Link is not active, can not encrypt!");
1224 return BTM_WRONG_MODE;
1225 }
1226
1227 if (p_rec->sec_rec.is_security_state_le_encrypting()) {
1228 log::warn("LE link encryption is active, Busy!");
1229 return BTM_BUSY;
1230 }
1231
1232 // Some controllers may not like encrypting both transports at the same time
1233 bool allow_le_enc_with_bredr = GET_SYSPROP(Ble, allow_enc_with_bredr, false);
1234 if (!allow_le_enc_with_bredr &&
1235 p_rec->sec_rec.is_security_state_bredr_encrypting()) {
1236 log::warn("BR/EDR link encryption is active, Busy!");
1237 return BTM_BUSY;
1238 }
1239
1240 p_cb->enc_handle = p_rec->ble_hci_handle;
1241
1242 if (use_stk) {
1243 btsnd_hcic_ble_start_enc(p_rec->ble_hci_handle, dummy_rand, 0, *p_stk);
1244 } else if (p_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_PENC) {
1245 btsnd_hcic_ble_start_enc(
1246 p_rec->ble_hci_handle, p_rec->sec_rec.ble_keys.rand,
1247 p_rec->sec_rec.ble_keys.ediv, p_rec->sec_rec.ble_keys.pltk);
1248 } else {
1249 log::error("No key available to encrypt the link");
1250 return BTM_ERR_KEY_MISSING;
1251 }
1252
1253 if (p_rec->sec_rec.sec_state == BTM_SEC_STATE_IDLE)
1254 p_rec->sec_rec.sec_state = BTM_SEC_STATE_LE_ENCRYPTING;
1255
1256 return BTM_CMD_STARTED;
1257 }
1258
1259 /*******************************************************************************
1260 *
1261 * Function btm_ble_notify_enc_cmpl
1262 *
1263 * Description This function is called to connect EATT and notify GATT to
1264 * send data if any request is pending. This either happens on
1265 * encryption complete event, or if bond is pending, after SMP
1266 * notifies that bonding is complete.
1267 *
1268 * Returns void
1269 *
1270 ******************************************************************************/
btm_ble_notify_enc_cmpl(const RawAddress & bd_addr,bool encr_enable)1271 static void btm_ble_notify_enc_cmpl(const RawAddress& bd_addr,
1272 bool encr_enable) {
1273 if (encr_enable) {
1274 uint8_t remote_lmp_version = 0;
1275 if (!BTM_ReadRemoteVersion(bd_addr, &remote_lmp_version, nullptr,
1276 nullptr) ||
1277 remote_lmp_version == 0) {
1278 log::warn("BLE Unable to determine remote version");
1279 }
1280
1281 if (remote_lmp_version == 0 ||
1282 remote_lmp_version >= HCI_PROTO_VERSION_5_0) {
1283 /* Link is encrypted, start EATT if remote LMP version is unknown, or 5.2
1284 * or greater */
1285 bluetooth::eatt::EattExtension::GetInstance()->Connect(bd_addr);
1286 }
1287 }
1288
1289 /* to notify GATT to send data if any request is pending */
1290 gatt_notify_enc_cmpl(bd_addr);
1291 }
1292
1293 /*******************************************************************************
1294 *
1295 * Function btm_ble_link_encrypted
1296 *
1297 * Description This function is called when LE link encrption status is
1298 * changed.
1299 *
1300 * Returns void
1301 *
1302 ******************************************************************************/
btm_ble_link_encrypted(const RawAddress & bd_addr,uint8_t encr_enable)1303 void btm_ble_link_encrypted(const RawAddress& bd_addr, uint8_t encr_enable) {
1304 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
1305 bool enc_cback;
1306
1307 log::verbose("bd_addr:{}, encr_enable={}", bd_addr, encr_enable);
1308
1309 if (!p_dev_rec) {
1310 log::warn("No Device Found!");
1311 return;
1312 }
1313
1314 enc_cback = p_dev_rec->sec_rec.is_security_state_le_encrypting();
1315
1316 smp_link_encrypted(bd_addr, encr_enable);
1317
1318 log::verbose("p_dev_rec->sec_rec.sec_flags=0x{:x}",
1319 p_dev_rec->sec_rec.sec_flags);
1320
1321 if (encr_enable && p_dev_rec->sec_rec.enc_key_size == 0)
1322 p_dev_rec->sec_rec.enc_key_size = p_dev_rec->sec_rec.ble_keys.key_size;
1323
1324 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_IDLE;
1325 if (p_dev_rec->sec_rec.p_callback && enc_cback) {
1326 if (encr_enable) btm_sec_dev_rec_cback_event(p_dev_rec, BTM_SUCCESS, true);
1327 /* LTK missing on peripheral */
1328 else if (p_dev_rec->role_central &&
1329 (p_dev_rec->sec_rec.sec_status == HCI_ERR_KEY_MISSING)) {
1330 btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_KEY_MISSING, true);
1331 } else if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN)) {
1332 btm_sec_dev_rec_cback_event(p_dev_rec, BTM_FAILED_ON_SECURITY, true);
1333 } else if (p_dev_rec->role_central)
1334 btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, true);
1335 }
1336
1337 BD_NAME remote_name = {};
1338 /* to notify GATT to send data if any request is pending,
1339 or if IOP matched, delay notifying until SMP_CMPLT_EVT */
1340 if (BTM_GetRemoteDeviceName(p_dev_rec->ble.pseudo_addr, remote_name) &&
1341 interop_match_name(INTEROP_SUSPEND_ATT_TRAFFIC_DURING_PAIRING,
1342 (const char*)remote_name) &&
1343 (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_LE_ACTIVE) &&
1344 btm_sec_cb.pairing_bda == p_dev_rec->ble.pseudo_addr) {
1345 log::info(
1346 "INTEROP_DELAY_ATT_TRAFFIC_DURING_PAIRING: Waiting for bonding to "
1347 "complete to notify enc complete");
1348 } else {
1349 btm_ble_notify_enc_cmpl(p_dev_rec->ble.pseudo_addr, encr_enable);
1350 }
1351 }
1352
1353 /*******************************************************************************
1354 *
1355 * Function btm_ble_ltk_request_reply
1356 *
1357 * Description This function is called to send a LTK request reply on a
1358 * peripheral
1359 * device.
1360 *
1361 * Returns void
1362 *
1363 ******************************************************************************/
btm_ble_ltk_request_reply(const RawAddress & bda,bool use_stk,const Octet16 & stk)1364 void btm_ble_ltk_request_reply(const RawAddress& bda, bool use_stk,
1365 const Octet16& stk) {
1366 tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bda);
1367 tBTM_SEC_CB* p_cb = &btm_sec_cb;
1368
1369 log::debug("bd_addr:{},use_stk:{}", bda, use_stk);
1370
1371 if (p_rec == NULL) {
1372 log::error("unknown device");
1373 return;
1374 }
1375
1376 p_cb->enc_handle = p_rec->ble_hci_handle;
1377 p_cb->key_size = p_rec->sec_rec.ble_keys.key_size;
1378
1379 log::error("key size={}", p_rec->sec_rec.ble_keys.key_size);
1380 if (use_stk) {
1381 btsnd_hcic_ble_ltk_req_reply(btm_sec_cb.enc_handle, stk);
1382 return;
1383 }
1384 /* calculate LTK using peer device */
1385 if (p_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_LENC) {
1386 btsnd_hcic_ble_ltk_req_reply(btm_sec_cb.enc_handle,
1387 p_rec->sec_rec.ble_keys.lltk);
1388 return;
1389 }
1390
1391 p_rec = btm_find_dev_with_lenc(bda);
1392 if (!p_rec) {
1393 btsnd_hcic_ble_ltk_req_neg_reply(btm_sec_cb.enc_handle);
1394 return;
1395 }
1396
1397 log::info("Found second sec_dev_rec for device that have LTK");
1398 /* This can happen when remote established LE connection using RPA to this
1399 * device, but then pair with us using Classing transport while still keeping
1400 * LE connection. If remote attempts to encrypt the LE connection, we might
1401 * end up here. We will eventually consolidate both entries, this is to avoid
1402 * race conditions. */
1403
1404 log::assert_that(p_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_LENC,
1405 "local enccryption key not present");
1406 p_cb->key_size = p_rec->sec_rec.ble_keys.key_size;
1407 btsnd_hcic_ble_ltk_req_reply(btm_sec_cb.enc_handle,
1408 p_rec->sec_rec.ble_keys.lltk);
1409 }
1410
1411 /*******************************************************************************
1412 *
1413 * Function btm_ble_io_capabilities_req
1414 *
1415 * Description This function is called to handle SMP get IO capability
1416 * request.
1417 *
1418 * Returns void
1419 *
1420 ******************************************************************************/
btm_ble_io_capabilities_req(tBTM_SEC_DEV_REC * p_dev_rec,tBTM_LE_IO_REQ * p_data)1421 static uint8_t btm_ble_io_capabilities_req(tBTM_SEC_DEV_REC* p_dev_rec,
1422 tBTM_LE_IO_REQ* p_data) {
1423 uint8_t callback_rc = BTM_SUCCESS;
1424 log::verbose("p_dev_rec->bd_addr:{}", p_dev_rec->bd_addr);
1425 if (btm_sec_cb.api.p_le_callback) {
1426 /* the callback function implementation may change the IO capability... */
1427 callback_rc = (*btm_sec_cb.api.p_le_callback)(
1428 BTM_LE_IO_REQ_EVT, p_dev_rec->bd_addr, (tBTM_LE_EVT_DATA*)p_data);
1429 }
1430 if ((callback_rc == BTM_SUCCESS) || (BTM_OOB_UNKNOWN != p_data->oob_data)) {
1431 p_data->auth_req &= BTM_LE_AUTH_REQ_MASK;
1432
1433 log::verbose("1:p_dev_rec->sec_rec.security_required={}, auth_req:{}",
1434 p_dev_rec->sec_rec.security_required, p_data->auth_req);
1435 log::verbose("2:i_keys=0x{:x} r_keys=0x{:x} (bit 0-LTK 1-IRK 2-CSRK)",
1436 p_data->init_keys, p_data->resp_keys);
1437
1438 /* if authentication requires MITM protection, put on the mask */
1439 if (p_dev_rec->sec_rec.security_required & BTM_SEC_IN_MITM)
1440 p_data->auth_req |= BTM_LE_AUTH_REQ_MITM;
1441
1442 if (!(p_data->auth_req & SMP_AUTH_BOND)) {
1443 log::verbose("Non bonding: No keys should be exchanged");
1444 p_data->init_keys = 0;
1445 p_data->resp_keys = 0;
1446 }
1447
1448 log::verbose("3:auth_req:{}", p_data->auth_req);
1449 log::verbose("4:i_keys=0x{:x} r_keys=0x{:x}", p_data->init_keys,
1450 p_data->resp_keys);
1451
1452 log::verbose("5:p_data->io_cap={} auth_req:{}", p_data->io_cap,
1453 p_data->auth_req);
1454
1455 /* remove MITM protection requirement if IO cap does not allow it */
1456 if ((p_data->io_cap == BTM_IO_CAP_NONE) && p_data->oob_data == SMP_OOB_NONE)
1457 p_data->auth_req &= ~BTM_LE_AUTH_REQ_MITM;
1458
1459 if (!(p_data->auth_req & SMP_SC_SUPPORT_BIT)) {
1460 /* if Secure Connections are not supported then remove LK derivation,
1461 ** and keypress notifications.
1462 */
1463 log::verbose(
1464 "SC not supported -> No LK derivation, no keypress notifications");
1465 p_data->auth_req &= ~SMP_KP_SUPPORT_BIT;
1466 p_data->init_keys &= ~SMP_SEC_KEY_TYPE_LK;
1467 p_data->resp_keys &= ~SMP_SEC_KEY_TYPE_LK;
1468 }
1469
1470 log::verbose("6:IO_CAP:{} oob_data:{} auth_req:0x{:02x}", p_data->io_cap,
1471 p_data->oob_data, p_data->auth_req);
1472 }
1473 return callback_rc;
1474 }
1475
1476 /*******************************************************************************
1477 *
1478 * Function btm_ble_br_keys_req
1479 *
1480 * Description This function is called to handle SMP request for keys sent
1481 * over BR/EDR.
1482 *
1483 * Returns void
1484 *
1485 ******************************************************************************/
btm_ble_br_keys_req(tBTM_SEC_DEV_REC * p_dev_rec,tBTM_LE_IO_REQ * p_data)1486 static uint8_t btm_ble_br_keys_req(tBTM_SEC_DEV_REC* p_dev_rec,
1487 tBTM_LE_IO_REQ* p_data) {
1488 uint8_t callback_rc = BTM_SUCCESS;
1489 log::verbose("p_dev_rec->bd_addr:{}", p_dev_rec->bd_addr);
1490 *p_data = tBTM_LE_IO_REQ{
1491 .io_cap = BTM_IO_CAP_UNKNOWN,
1492 .oob_data = false,
1493 .auth_req = BTM_LE_AUTH_REQ_SC_MITM_BOND,
1494 .max_key_size = BTM_BLE_MAX_KEY_SIZE,
1495 .init_keys = SMP_BR_SEC_DEFAULT_KEY,
1496 .resp_keys = SMP_BR_SEC_DEFAULT_KEY,
1497 };
1498
1499 if (osi_property_get_bool(kPropertyCtkdDisableCsrkDistribution, false)) {
1500 p_data->init_keys &= (~SMP_SEC_KEY_TYPE_CSRK);
1501 p_data->resp_keys &= (~SMP_SEC_KEY_TYPE_CSRK);
1502 }
1503
1504 return callback_rc;
1505 }
1506
1507 /*******************************************************************************
1508 *
1509 * Function btm_ble_connected
1510 *
1511 * Description This function is when a LE connection to the peer device is
1512 * establsihed
1513 *
1514 * Returns void
1515 *
1516 ******************************************************************************/
btm_ble_connected(const RawAddress & bda,uint16_t handle,uint8_t,uint8_t role,tBLE_ADDR_TYPE addr_type,bool addr_matched,bool can_read_discoverable_characteristics)1517 void btm_ble_connected(const RawAddress& bda, uint16_t handle,
1518 uint8_t /* enc_mode */, uint8_t role,
1519 tBLE_ADDR_TYPE addr_type, bool addr_matched,
1520 bool can_read_discoverable_characteristics) {
1521 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(bda);
1522
1523 log::info("Update timestamp for ble connection:{}", bda);
1524 // TODO() Why is timestamp a counter ?
1525 p_dev_rec->timestamp = btm_sec_cb.dev_rec_count++;
1526
1527 if (is_ble_addr_type_known(addr_type))
1528 p_dev_rec->ble.SetAddressType(addr_type);
1529 else
1530 log::warn(
1531 "Please do not update device record from anonymous le advertisement");
1532
1533 p_dev_rec->ble.pseudo_addr = bda;
1534 p_dev_rec->ble_hci_handle = handle;
1535 p_dev_rec->device_type |= BT_DEVICE_TYPE_BLE;
1536 p_dev_rec->role_central = (role == HCI_ROLE_CENTRAL) ? true : false;
1537 p_dev_rec->can_read_discoverable = can_read_discoverable_characteristics;
1538
1539 if (!addr_matched) {
1540 p_dev_rec->ble.active_addr_type = BTM_BLE_ADDR_PSEUDO;
1541 if (p_dev_rec->ble.AddressType() == BLE_ADDR_RANDOM) {
1542 p_dev_rec->ble.cur_rand_addr = bda;
1543 }
1544 }
1545 btm_cb.ble_ctr_cb.inq_var.directed_conn = BTM_BLE_ADV_IND_EVT;
1546 }
1547
1548 /*****************************************************************************
1549 * Function btm_proc_smp_cback
1550 *
1551 * Description This function is the SMP callback handler.
1552 *
1553 *****************************************************************************/
btm_proc_smp_cback(tSMP_EVT event,const RawAddress & bd_addr,const tSMP_EVT_DATA * p_data)1554 tBTM_STATUS btm_proc_smp_cback(tSMP_EVT event, const RawAddress& bd_addr,
1555 const tSMP_EVT_DATA* p_data) {
1556 log::verbose("bd_addr:{}, event={}", bd_addr, smp_evt_to_text(event));
1557
1558 if (event == SMP_SC_LOC_OOB_DATA_UP_EVT) {
1559 btm_sec_cr_loc_oob_data_cback_event(RawAddress{}, p_data->loc_oob_data);
1560 return BTM_SUCCESS;
1561 }
1562
1563 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
1564 tBTM_STATUS res = BTM_SUCCESS;
1565
1566 if (p_dev_rec != NULL) {
1567 switch (event) {
1568 case SMP_IO_CAP_REQ_EVT:
1569 btm_ble_io_capabilities_req(p_dev_rec,
1570 (tBTM_LE_IO_REQ*)&p_data->io_req);
1571 break;
1572
1573 case SMP_BR_KEYS_REQ_EVT:
1574 btm_ble_br_keys_req(p_dev_rec, (tBTM_LE_IO_REQ*)&p_data->io_req);
1575 break;
1576
1577 case SMP_PASSKEY_REQ_EVT:
1578 case SMP_PASSKEY_NOTIF_EVT:
1579 case SMP_OOB_REQ_EVT:
1580 case SMP_NC_REQ_EVT:
1581 case SMP_SC_OOB_REQ_EVT:
1582 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_LE_AUTHENTICATED;
1583 FALLTHROUGH_INTENDED; /* FALLTHROUGH */
1584
1585 case SMP_CONSENT_REQ_EVT:
1586 case SMP_SEC_REQUEST_EVT:
1587 if (event == SMP_SEC_REQUEST_EVT &&
1588 btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) {
1589 log::verbose("Ignoring SMP Security request");
1590 break;
1591 }
1592 btm_sec_cb.pairing_bda = bd_addr;
1593 if (event != SMP_CONSENT_REQ_EVT) {
1594 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_AUTHENTICATING;
1595 }
1596 btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_LE_ACTIVE;
1597 FALLTHROUGH_INTENDED; /* FALLTHROUGH */
1598
1599 case SMP_COMPLT_EVT:
1600 if (btm_sec_cb.api.p_le_callback) {
1601 /* the callback function implementation may change the IO
1602 * capability... */
1603 log::verbose("btm_sec_cb.api.p_le_callback=0x{}",
1604 fmt::ptr(btm_sec_cb.api.p_le_callback));
1605 (*btm_sec_cb.api.p_le_callback)(static_cast<tBTM_LE_EVT>(event),
1606 bd_addr, (tBTM_LE_EVT_DATA*)p_data);
1607 }
1608
1609 if (event == SMP_COMPLT_EVT) {
1610 p_dev_rec = btm_find_dev(bd_addr);
1611 if (p_dev_rec == NULL) {
1612 log::error("p_dev_rec is NULL");
1613 return BTM_SUCCESS;
1614 }
1615 log::verbose("before update sec_level=0x{:x} sec_flags=0x{:x}",
1616 p_data->cmplt.sec_level, p_dev_rec->sec_rec.sec_flags);
1617
1618 res = (p_data->cmplt.reason == SMP_SUCCESS) ? BTM_SUCCESS
1619 : BTM_ERR_PROCESSING;
1620
1621 log::verbose(
1622 "after update result={} sec_level=0x{:x} sec_flags=0x{:x}", res,
1623 p_data->cmplt.sec_level, p_dev_rec->sec_rec.sec_flags);
1624
1625 if (p_data->cmplt.is_pair_cancel &&
1626 btm_sec_cb.api.p_bond_cancel_cmpl_callback) {
1627 log::verbose("Pairing Cancel completed");
1628 (*btm_sec_cb.api.p_bond_cancel_cmpl_callback)(BTM_SUCCESS);
1629 }
1630
1631 if (res != BTM_SUCCESS && p_data->cmplt.reason != SMP_CONN_TOUT) {
1632 log::verbose("Pairing failed - prepare to remove ACL");
1633 l2cu_start_post_bond_timer(p_dev_rec->ble_hci_handle);
1634 }
1635
1636 log::verbose(
1637 "btm_sec_cb.pairing_state={:x} pairing_flags={:x} "
1638 "pin_code_len={:x}",
1639 btm_sec_cb.pairing_state, btm_sec_cb.pairing_flags,
1640 btm_sec_cb.pin_code_len);
1641
1642 /* Reset btm state only if the callback address matches pairing
1643 * address*/
1644 if (bd_addr == btm_sec_cb.pairing_bda) {
1645 btm_sec_cb.pairing_bda = RawAddress::kAny;
1646 btm_sec_cb.pairing_state = BTM_PAIR_STATE_IDLE;
1647 btm_sec_cb.pairing_flags = 0;
1648 }
1649
1650 if (res == BTM_SUCCESS) {
1651 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_IDLE;
1652
1653 if (p_dev_rec->sec_rec.bond_type != BOND_TYPE_TEMPORARY) {
1654 // Add all bonded device into resolving list if IRK is available.
1655 btm_ble_resolving_list_load_dev(*p_dev_rec);
1656 } else if (p_dev_rec->ble_hci_handle == HCI_INVALID_HANDLE) {
1657 // At this point LTK should have been dropped by btif.
1658 // Reset the flags here if LE is not connected (over BR),
1659 // otherwise they would be reset on disconnected.
1660 log::debug(
1661 "SMP over BR triggered by temporary bond has completed, "
1662 "resetting the LK flags");
1663 p_dev_rec->sec_rec.sec_flags &= ~(BTM_SEC_LE_LINK_KEY_KNOWN);
1664 p_dev_rec->sec_rec.ble_keys.key_type = BTM_LE_KEY_NONE;
1665 }
1666 }
1667 BD_NAME remote_name = {};
1668 if (BTM_GetRemoteDeviceName(p_dev_rec->ble.pseudo_addr,
1669 remote_name) &&
1670 interop_match_name(INTEROP_SUSPEND_ATT_TRAFFIC_DURING_PAIRING,
1671 (const char*)remote_name)) {
1672 log::debug("Notifying encryption cmpl delayed due to IOP match");
1673 btm_ble_notify_enc_cmpl(p_dev_rec->ble.pseudo_addr, true);
1674 }
1675
1676 btm_sec_dev_rec_cback_event(p_dev_rec, res, true);
1677 }
1678 break;
1679
1680 case SMP_LE_ADDR_ASSOC_EVT:
1681 if (btm_sec_cb.api.p_le_callback) {
1682 log::verbose("btm_sec_cb.api.p_le_callback=0x{}",
1683 fmt::ptr(btm_sec_cb.api.p_le_callback));
1684 (*btm_sec_cb.api.p_le_callback)(static_cast<tBTM_LE_EVT>(event),
1685 bd_addr, (tBTM_LE_EVT_DATA*)p_data);
1686 }
1687 break;
1688
1689 case SMP_SIRK_VERIFICATION_REQ_EVT:
1690 res = (*btm_sec_cb.api.p_sirk_verification_callback)(bd_addr);
1691 log::debug("SMP SIRK verification result:{}", btm_status_text(res));
1692 if (res != BTM_CMD_STARTED) {
1693 return res;
1694 }
1695
1696 break;
1697
1698 default:
1699 log::verbose("unknown event={}", smp_evt_to_text(event));
1700 break;
1701 }
1702 } else {
1703 log::warn("Unexpected event '{}' for unknown device.",
1704 smp_evt_to_text(event));
1705 }
1706
1707 return BTM_SUCCESS;
1708 }
1709
1710 /*******************************************************************************
1711 *
1712 * Function BTM_BleDataSignature
1713 *
1714 * Description This function is called to sign the data using AES128 CMAC
1715 * algorithm.
1716 *
1717 * Parameter bd_addr: target device the data to be signed for.
1718 * p_text: singing data
1719 * len: length of the data to be signed.
1720 * signature: output parameter where data signature is going to
1721 * be stored.
1722 *
1723 * Returns true if signing sucessul, otherwise false.
1724 *
1725 ******************************************************************************/
BTM_BleDataSignature(const RawAddress & bd_addr,uint8_t * p_text,uint16_t len,BLE_SIGNATURE signature)1726 bool BTM_BleDataSignature(const RawAddress& bd_addr, uint8_t* p_text,
1727 uint16_t len, BLE_SIGNATURE signature) {
1728 tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bd_addr);
1729
1730 if (p_rec == NULL) {
1731 log::error("data signing can not be done from unknown device");
1732 return false;
1733 }
1734
1735 uint8_t* p_mac = (uint8_t*)signature;
1736 uint8_t* pp;
1737 uint8_t* p_buf = (uint8_t*)osi_malloc(len + 4);
1738
1739 pp = p_buf;
1740 /* prepare plain text */
1741 if (p_text) {
1742 memcpy(p_buf, p_text, len);
1743 pp = (p_buf + len);
1744 }
1745
1746 UINT32_TO_STREAM(pp, p_rec->sec_rec.ble_keys.local_counter);
1747 UINT32_TO_STREAM(p_mac, p_rec->sec_rec.ble_keys.local_counter);
1748
1749 crypto_toolbox::aes_cmac(p_rec->sec_rec.ble_keys.lcsrk, p_buf,
1750 (uint16_t)(len + 4), BTM_CMAC_TLEN_SIZE, p_mac);
1751 p_rec->sec_rec.increment_sign_counter(true);
1752
1753 log::verbose("p_mac = {}", fmt::ptr(p_mac));
1754 log::verbose(
1755 "p_mac[0]=0x{:02x} p_mac[1]=0x{:02x} p_mac[2]=0x{:02x} p_mac[3]=0x{:02x}",
1756 *p_mac, *(p_mac + 1), *(p_mac + 2), *(p_mac + 3));
1757 log::verbose(
1758 "p_mac[4]=0x{:02x} p_mac[5]=0x{:02x} p_mac[6]=0x{:02x} p_mac[7]=0x{:02x}",
1759 *(p_mac + 4), *(p_mac + 5), *(p_mac + 6), *(p_mac + 7));
1760 osi_free(p_buf);
1761 return true;
1762 }
1763
1764 /*******************************************************************************
1765 *
1766 * Function BTM_BleVerifySignature
1767 *
1768 * Description This function is called to verify the data signature
1769 *
1770 * Parameter bd_addr: target device the data to be signed for.
1771 * p_orig: original data before signature.
1772 * len: length of the signing data
1773 * counter: counter used when doing data signing
1774 * p_comp: signature to be compared against.
1775
1776 * Returns true if signature verified correctly; otherwise false.
1777 *
1778 ******************************************************************************/
BTM_BleVerifySignature(const RawAddress & bd_addr,uint8_t * p_orig,uint16_t len,uint32_t counter,uint8_t * p_comp)1779 bool BTM_BleVerifySignature(const RawAddress& bd_addr, uint8_t* p_orig,
1780 uint16_t len, uint32_t counter, uint8_t* p_comp) {
1781 bool verified = false;
1782 tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bd_addr);
1783 uint8_t p_mac[BTM_CMAC_TLEN_SIZE];
1784
1785 if (p_rec == NULL ||
1786 (p_rec && !(p_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_PCSRK))) {
1787 log::error("can not verify signature for unknown device");
1788 } else if (counter < p_rec->sec_rec.ble_keys.counter) {
1789 log::error("signature received with out dated sign counter");
1790 } else if (p_orig == NULL) {
1791 log::error("No signature to verify");
1792 } else {
1793 log::verbose("rcv_cnt={} >= expected_cnt={}", counter,
1794 p_rec->sec_rec.ble_keys.counter);
1795
1796 crypto_toolbox::aes_cmac(p_rec->sec_rec.ble_keys.pcsrk, p_orig, len,
1797 BTM_CMAC_TLEN_SIZE, p_mac);
1798 if (CRYPTO_memcmp(p_mac, p_comp, BTM_CMAC_TLEN_SIZE) == 0) {
1799 p_rec->sec_rec.increment_sign_counter(false);
1800 verified = true;
1801 }
1802 }
1803 return verified;
1804 }
1805
1806 /*******************************************************************************
1807 *
1808 * Function BTM_BleSirkConfirmDeviceReply
1809 *
1810 * Description This procedure confirms requested to validate set device.
1811 *
1812 * Parameter bd_addr - BD address of the peer
1813 * res - confirmation result BTM_SUCCESS if success
1814 *
1815 * Returns void
1816 *
1817 ******************************************************************************/
BTM_BleSirkConfirmDeviceReply(const RawAddress & bd_addr,uint8_t res)1818 void BTM_BleSirkConfirmDeviceReply(const RawAddress& bd_addr, uint8_t res) {
1819 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
1820 tSMP_STATUS res_smp = (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_FAIL;
1821
1822 log::info("bd_addr:{}, result:{}", bd_addr, smp_status_text(res_smp));
1823
1824 if (p_dev_rec == NULL) {
1825 log::error("Confirmation of Unknown device");
1826 return;
1827 }
1828
1829 BTM_LogHistory(
1830 kBtmLogTag, bd_addr, "SIRK confirmation",
1831 base::StringPrintf("status:%s", smp_status_text(res_smp).c_str()));
1832 SMP_SirkConfirmDeviceReply(bd_addr, res_smp);
1833 }
1834
1835 /*******************************************************************************
1836 * Utility functions for LE device IR/ER generation
1837 ******************************************************************************/
1838 /** This function is to notify application new keys have been generated. */
btm_notify_new_key(uint8_t key_type)1839 static void btm_notify_new_key(uint8_t key_type) {
1840 tBTM_BLE_LOCAL_KEYS* p_local_keys = NULL;
1841
1842 log::verbose("key_type={}", key_type);
1843
1844 if (btm_sec_cb.api.p_le_key_callback) {
1845 switch (key_type) {
1846 case BTM_BLE_KEY_TYPE_ID:
1847 log::verbose("BTM_BLE_KEY_TYPE_ID");
1848 p_local_keys = (tBTM_BLE_LOCAL_KEYS*)&btm_sec_cb.devcb.id_keys;
1849 break;
1850
1851 case BTM_BLE_KEY_TYPE_ER:
1852 log::verbose("BTM_BLE_KEY_TYPE_ER");
1853 p_local_keys =
1854 (tBTM_BLE_LOCAL_KEYS*)&btm_sec_cb.devcb.ble_encryption_key_value;
1855 break;
1856
1857 default:
1858 log::error("unknown key type: {}", key_type);
1859 break;
1860 }
1861 if (p_local_keys != NULL)
1862 (*btm_sec_cb.api.p_le_key_callback)(key_type, p_local_keys);
1863 }
1864 }
1865
1866 /** implementation of btm_ble_reset_id */
btm_ble_reset_id_impl(const Octet16 & rand1,const Octet16 & rand2)1867 static void btm_ble_reset_id_impl(const Octet16& rand1, const Octet16& rand2) {
1868 /* Regenerate Identity Root */
1869 btm_sec_cb.devcb.id_keys.ir = rand1;
1870 Octet16 btm_ble_dhk_pt{};
1871 btm_ble_dhk_pt[0] = 0x03;
1872
1873 /* generate DHK= Eir({0x03, 0x00, 0x00 ...}) */
1874 btm_sec_cb.devcb.id_keys.dhk =
1875 crypto_toolbox::aes_128(btm_sec_cb.devcb.id_keys.ir, btm_ble_dhk_pt);
1876
1877 Octet16 btm_ble_irk_pt{};
1878 btm_ble_irk_pt[0] = 0x01;
1879 /* IRK = D1(IR, 1) */
1880 btm_sec_cb.devcb.id_keys.irk =
1881 crypto_toolbox::aes_128(btm_sec_cb.devcb.id_keys.ir, btm_ble_irk_pt);
1882
1883 btm_notify_new_key(BTM_BLE_KEY_TYPE_ID);
1884
1885 /* proceed generate ER */
1886 btm_sec_cb.devcb.ble_encryption_key_value = rand2;
1887 btm_notify_new_key(BTM_BLE_KEY_TYPE_ER);
1888
1889 /* if privacy is enabled, update the irk and RPA in the LE address manager */
1890 if (btm_cb.ble_ctr_cb.privacy_mode != BTM_PRIVACY_NONE) {
1891 BTM_BleConfigPrivacy(true);
1892 }
1893 }
1894
1895 struct reset_id_data {
1896 Octet16 rand1;
1897 Octet16 rand2;
1898 };
1899
1900 /** This function is called to reset LE device identity. */
btm_ble_reset_id(void)1901 void btm_ble_reset_id(void) {
1902 log::verbose("btm_ble_reset_id");
1903
1904 /* In order to reset identity, we need four random numbers. Make four nested
1905 * calls to generate them first, then proceed to perform the actual reset in
1906 * btm_ble_reset_id_impl. */
1907 btsnd_hcic_ble_rand(base::Bind([](BT_OCTET8 rand) {
1908 reset_id_data tmp;
1909 memcpy(tmp.rand1.data(), rand, BT_OCTET8_LEN);
1910 btsnd_hcic_ble_rand(base::Bind(
1911 [](reset_id_data tmp, BT_OCTET8 rand) {
1912 memcpy(tmp.rand1.data() + 8, rand, BT_OCTET8_LEN);
1913 btsnd_hcic_ble_rand(base::Bind(
1914 [](reset_id_data tmp, BT_OCTET8 rand) {
1915 memcpy(tmp.rand2.data(), rand, BT_OCTET8_LEN);
1916 btsnd_hcic_ble_rand(base::Bind(
1917 [](reset_id_data tmp, BT_OCTET8 rand) {
1918 memcpy(tmp.rand2.data() + 8, rand, BT_OCTET8_LEN);
1919 // when all random numbers are ready, do the actual reset.
1920 btm_ble_reset_id_impl(tmp.rand1, tmp.rand2);
1921 },
1922 tmp));
1923 },
1924 tmp));
1925 },
1926 tmp));
1927 }));
1928 }
1929
1930 /*******************************************************************************
1931 *
1932 * Function btm_ble_get_acl_remote_addr
1933 *
1934 * Description This function reads the active remote address used for the
1935 * connection.
1936 *
1937 * Returns success return true, otherwise false.
1938 *
1939 ******************************************************************************/
btm_ble_get_acl_remote_addr(uint16_t hci_handle,RawAddress & conn_addr,tBLE_ADDR_TYPE * p_addr_type)1940 bool btm_ble_get_acl_remote_addr(uint16_t hci_handle, RawAddress& conn_addr,
1941 tBLE_ADDR_TYPE* p_addr_type) {
1942 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(hci_handle);
1943 if (p_dev_rec == nullptr) {
1944 log::warn("Unable to find security device record hci_handle:{}",
1945 hci_handle);
1946 // TODO Release acl resource
1947 return false;
1948 }
1949
1950 bool st = true;
1951
1952 switch (p_dev_rec->ble.active_addr_type) {
1953 case BTM_BLE_ADDR_PSEUDO:
1954 conn_addr = p_dev_rec->bd_addr;
1955 *p_addr_type = p_dev_rec->ble.AddressType();
1956 break;
1957
1958 case BTM_BLE_ADDR_RRA:
1959 conn_addr = p_dev_rec->ble.cur_rand_addr;
1960 *p_addr_type = BLE_ADDR_RANDOM;
1961 break;
1962
1963 case BTM_BLE_ADDR_STATIC:
1964 conn_addr = p_dev_rec->ble.identity_address_with_type.bda;
1965 *p_addr_type = p_dev_rec->ble.identity_address_with_type.type;
1966 break;
1967
1968 default:
1969 log::warn("Unable to find record with active address type:{}",
1970 p_dev_rec->ble.active_addr_type);
1971 st = false;
1972 break;
1973 }
1974 return st;
1975 }
1976
BTM_BleGetPeerLTK(const RawAddress address)1977 std::optional<Octet16> BTM_BleGetPeerLTK(const RawAddress address) {
1978 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(address);
1979 if (p_dev_rec == nullptr) {
1980 return std::nullopt;
1981 }
1982
1983 return p_dev_rec->sec_rec.ble_keys.pltk;
1984 }
1985
BTM_BleGetPeerIRK(const RawAddress address)1986 std::optional<Octet16> BTM_BleGetPeerIRK(const RawAddress address) {
1987 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(address);
1988 if (p_dev_rec == nullptr) {
1989 return std::nullopt;
1990 }
1991
1992 return p_dev_rec->sec_rec.ble_keys.irk;
1993 }
1994
BTM_BleIsLinkKeyKnown(const RawAddress address)1995 bool BTM_BleIsLinkKeyKnown(const RawAddress address) {
1996 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(address);
1997 return p_dev_rec != nullptr && p_dev_rec->sec_rec.is_le_link_key_known();
1998 }
1999
BTM_BleGetIdentityAddress(const RawAddress address)2000 std::optional<tBLE_BD_ADDR> BTM_BleGetIdentityAddress(
2001 const RawAddress address) {
2002 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(address);
2003 if (p_dev_rec == nullptr) {
2004 return std::nullopt;
2005 }
2006
2007 return p_dev_rec->ble.identity_address_with_type;
2008 }
2009