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