1 /******************************************************************************
2 *
3 * Copyright 1999-2012 Broadcom Corporation
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 ******************************************************************************/
18
19 /******************************************************************************
20 *
21 * This file contains functions for the Bluetooth Security Manager
22 *
23 ******************************************************************************/
24
25 #define LOG_TAG "bt_btm_sec"
26
27 #include "stack/btm/btm_sec.h"
28
29 #include <base/functional/bind.h>
30 #include <base/strings/stringprintf.h>
31 #include <bluetooth/log.h>
32 #include <com_android_bluetooth_flags.h>
33
34 #include <cstddef>
35 #include <cstdint>
36 #include <string>
37
38 #include "bt_dev_class.h"
39 #include "btif/include/btif_storage.h"
40 #include "common/init_flags.h"
41 #include "common/metrics.h"
42 #include "common/time_util.h"
43 #include "device/include/device_iot_config.h"
44 #include "device/include/interop.h"
45 #include "hci/controller_interface.h"
46 #include "internal_include/bt_target.h"
47 #include "l2c_api.h"
48 #include "main/shim/acl_api.h"
49 #include "main/shim/entry.h"
50 #include "main/shim/helpers.h"
51 #include "osi/include/allocator.h"
52 #include "osi/include/properties.h"
53 #include "stack/btm/btm_ble_int.h"
54 #include "stack/btm/btm_ble_sec.h"
55 #include "stack/btm/btm_dev.h"
56 #include "stack/btm/btm_int_types.h"
57 #include "stack/btm/btm_sec_cb.h"
58 #include "stack/btm/btm_sec_int_types.h"
59 #include "stack/btm/security_device_record.h"
60 #include "stack/include/acl_api.h"
61 #include "stack/include/bt_psm_types.h"
62 #include "stack/include/bt_types.h"
63 #include "stack/include/btm_api.h"
64 #include "stack/include/btm_ble_addr.h"
65 #include "stack/include/btm_ble_api.h"
66 #include "stack/include/btm_ble_privacy.h"
67 #include "stack/include/btm_client_interface.h"
68 #include "stack/include/btm_log_history.h"
69 #include "stack/include/btm_sec_api.h"
70 #include "stack/include/btm_status.h"
71 #include "stack/include/hci_error_code.h"
72 #include "stack/include/l2cap_security_interface.h"
73 #include "stack/include/l2cdefs.h"
74 #include "stack/include/main_thread.h"
75 #include "stack/include/smp_api.h"
76 #include "stack/include/stack_metrics_logging.h"
77 #include "types/bt_transport.h"
78 #include "types/raw_address.h"
79
80 namespace {
81
82 constexpr char kBtmLogTag[] = "SEC";
83
84 }
85
86 using namespace bluetooth;
87
88 extern tBTM_CB btm_cb;
89
90 #define BTM_SEC_MAX_COLLISION_DELAY (5000)
91 #define BTM_SEC_START_AUTH_DELAY (200)
92
93 #define BTM_SEC_IS_SM4(sm) ((bool)(BTM_SM4_TRUE == ((sm)&BTM_SM4_TRUE)))
94 #define BTM_SEC_IS_SM4_LEGACY(sm) ((bool)(BTM_SM4_KNOWN == ((sm)&BTM_SM4_TRUE)))
95 #define BTM_SEC_IS_SM4_UNKNOWN(sm) \
96 ((bool)(BTM_SM4_UNKNOWN == ((sm)&BTM_SM4_TRUE)))
97
98 #define BTM_SEC_LE_MASK \
99 (BTM_SEC_LE_AUTHENTICATED | BTM_SEC_LE_ENCRYPTED | \
100 BTM_SEC_LE_LINK_KEY_KNOWN | BTM_SEC_LE_LINK_KEY_AUTHED)
101
102 bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec,
103 const RawAddress& new_pseudo_addr);
104 void bta_dm_remove_device(const RawAddress& bd_addr);
105 void bta_dm_remote_key_missing(const RawAddress bd_addr);
106 void bta_dm_process_remove_device(const RawAddress& bd_addr);
107
108 static tBTM_STATUS btm_sec_execute_procedure(tBTM_SEC_DEV_REC* p_dev_rec);
109 static bool btm_sec_start_get_name(tBTM_SEC_DEV_REC* p_dev_rec);
110 static void btm_sec_wait_and_start_authentication(tBTM_SEC_DEV_REC* p_dev_rec);
111 static void btm_sec_auth_timer_timeout(void* data);
112 static void btm_sec_collision_timeout(void* data);
113 static void btm_restore_mode(void);
114 static void btm_sec_pairing_timeout(void* data);
115 static tBTM_STATUS btm_sec_dd_create_conn(tBTM_SEC_DEV_REC* p_dev_rec);
116
117 static void btm_sec_check_pending_reqs(void);
118 static bool btm_sec_queue_mx_request(const RawAddress& bd_addr, uint16_t psm,
119 bool is_orig, uint16_t security_required,
120 tBTM_SEC_CALLBACK* p_callback,
121 void* p_ref_data);
122 static void btm_sec_bond_cancel_complete(void);
123 static void btm_send_link_key_notif(tBTM_SEC_DEV_REC* p_dev_rec);
124 static bool btm_sec_check_prefetch_pin(tBTM_SEC_DEV_REC* p_dev_rec);
125
126 static tBTM_STATUS btm_sec_send_hci_disconnect(tBTM_SEC_DEV_REC* p_dev_rec,
127 tHCI_STATUS reason,
128 uint16_t conn_handle,
129 std::string comment);
130
131 static bool btm_dev_authenticated(const tBTM_SEC_DEV_REC* p_dev_rec);
132 static bool btm_dev_encrypted(const tBTM_SEC_DEV_REC* p_dev_rec);
133 static uint16_t btm_sec_set_serv_level4_flags(uint16_t cur_security,
134 bool is_originator);
135
136 static void btm_sec_queue_encrypt_request(const RawAddress& bd_addr,
137 tBT_TRANSPORT transport,
138 tBTM_SEC_CALLBACK* p_callback,
139 void* p_ref_data,
140 tBTM_BLE_SEC_ACT sec_act);
141 static void btm_sec_check_pending_enc_req(tBTM_SEC_DEV_REC* p_dev_rec,
142 tBT_TRANSPORT transport,
143 uint8_t encr_enable);
144
145 static bool btm_sec_use_smp_br_chnl(tBTM_SEC_DEV_REC* p_dev_rec);
146
147 /* true - authenticated link key is possible */
148 static const bool btm_sec_io_map[BTM_IO_CAP_MAX][BTM_IO_CAP_MAX] = {
149 /* OUT, IO, IN, NONE */
150 /* OUT */ {false, false, true, false},
151 /* IO */ {false, true, true, false},
152 /* IN */ {true, true, true, false},
153 /* NONE */ {false, false, false, false}};
154 /* BTM_IO_CAP_OUT 0 DisplayOnly */
155 /* BTM_IO_CAP_IO 1 DisplayYesNo */
156 /* BTM_IO_CAP_IN 2 KeyboardOnly */
157 /* BTM_IO_CAP_NONE 3 NoInputNoOutput */
158
NotifyBondingChange(tBTM_SEC_DEV_REC & p_dev_rec,tHCI_STATUS status)159 static void NotifyBondingChange(tBTM_SEC_DEV_REC& p_dev_rec,
160 tHCI_STATUS status) {
161 if (btm_sec_cb.api.p_auth_complete_callback != nullptr) {
162 (*btm_sec_cb.api.p_auth_complete_callback)(
163 p_dev_rec.bd_addr, p_dev_rec.dev_class, p_dev_rec.sec_bd_name, status);
164 }
165 }
166
concurrentPeerAuthIsEnabled()167 static bool concurrentPeerAuthIsEnabled() {
168 // Was previously named BTM_DISABLE_CONCURRENT_PEER_AUTH.
169 // Renamed to ENABLED for homogeneity with system properties
170 static const bool sCONCURRENT_PEER_AUTH_IS_ENABLED = osi_property_get_bool(
171 "bluetooth.btm.sec.concurrent_peer_auth.enabled", true);
172 return sCONCURRENT_PEER_AUTH_IS_ENABLED;
173 }
174
175 /**
176 * Whether we should handle encryption change events from a peer device, while
177 * we are in the IDLE state. This matters if we are waiting to retry encryption
178 * following an LMP timeout, and then we get an encryption change event from the
179 * peer.
180 */
handleUnexpectedEncryptionChange()181 static bool handleUnexpectedEncryptionChange() {
182 static const bool sHandleUnexpectedEncryptionChange = osi_property_get_bool(
183 "bluetooth.btm.sec.handle_unexpected_encryption_change.enabled", false);
184 return sHandleUnexpectedEncryptionChange;
185 }
186
NotifyBondingCanceled(tBTM_STATUS)187 void NotifyBondingCanceled(tBTM_STATUS /* btm_status */) {
188 if (btm_sec_cb.api.p_bond_cancel_cmpl_callback) {
189 btm_sec_cb.api.p_bond_cancel_cmpl_callback(BTM_SUCCESS);
190 }
191 }
192
193 /*******************************************************************************
194 *
195 * Function btm_dev_authenticated
196 *
197 * Description check device is authenticated on BR/EDR
198 *
199 * Returns bool true or false
200 *
201 ******************************************************************************/
btm_dev_authenticated(const tBTM_SEC_DEV_REC * p_dev_rec)202 static bool btm_dev_authenticated(const tBTM_SEC_DEV_REC* p_dev_rec) {
203 return p_dev_rec->sec_rec.sec_flags & BTM_SEC_AUTHENTICATED;
204 }
205
206 /*******************************************************************************
207 *
208 * Function btm_dev_encrypted
209 *
210 * Description check device is encrypted on BR/EDR
211 *
212 * Returns bool true or false
213 *
214 ******************************************************************************/
btm_dev_encrypted(const tBTM_SEC_DEV_REC * p_dev_rec)215 static bool btm_dev_encrypted(const tBTM_SEC_DEV_REC* p_dev_rec) {
216 return p_dev_rec->sec_rec.sec_flags & BTM_SEC_ENCRYPTED;
217 }
218
219 /*******************************************************************************
220 *
221 * Function btm_dev_16_digit_authenticated
222 *
223 * Description check device is authenticated by using 16 digit pin or MITM (BR/EDR)
224 *
225 * Returns bool true or false
226 *
227 ******************************************************************************/
btm_dev_16_digit_authenticated(const tBTM_SEC_DEV_REC * p_dev_rec)228 static bool btm_dev_16_digit_authenticated(const tBTM_SEC_DEV_REC* p_dev_rec) {
229 // BTM_SEC_16_DIGIT_PIN_AUTHED is set if MITM or 16 digit pin is used
230 return p_dev_rec->sec_rec.sec_flags & BTM_SEC_16_DIGIT_PIN_AUTHED;
231 }
232
is_sec_state_equal(void * data,void * context)233 static bool is_sec_state_equal(void* data, void* context) {
234 tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data);
235 uint8_t* state = static_cast<uint8_t*>(context);
236
237 if (p_dev_rec->sec_rec.sec_state == *state) return false;
238
239 return true;
240 }
241
242 /*******************************************************************************
243 *
244 * Function btm_sec_find_dev_by_sec_state
245 *
246 * Description Look for the record in the device database for the device
247 * which is being authenticated or encrypted
248 *
249 * Returns Pointer to the record or NULL
250 *
251 ******************************************************************************/
btm_sec_find_dev_by_sec_state(uint8_t state)252 static tBTM_SEC_DEV_REC* btm_sec_find_dev_by_sec_state(uint8_t state) {
253 list_node_t* n =
254 list_foreach(btm_sec_cb.sec_dev_rec, is_sec_state_equal, &state);
255 if (n) return static_cast<tBTM_SEC_DEV_REC*>(list_node(n));
256
257 return nullptr;
258 }
259
260 /*******************************************************************************
261 *
262 * Function btm_sec_is_device_sc_downgrade
263 *
264 * Description Check for a stored device record matching the candidate
265 * device, and return true if the stored device has reported
266 * that it supports Secure Connections mode and the candidate
267 * device reports that it does not. Otherwise, return false.
268 *
269 * Returns bool
270 *
271 ******************************************************************************/
btm_sec_is_device_sc_downgrade(uint16_t hci_handle,bool secure_connections_supported)272 static bool btm_sec_is_device_sc_downgrade(uint16_t hci_handle,
273 bool secure_connections_supported) {
274 if (secure_connections_supported) return false;
275
276 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(hci_handle);
277 if (p_dev_rec == nullptr) return false;
278
279 uint8_t property_val = 0;
280 bt_property_t property = {
281 .type = BT_PROPERTY_REMOTE_SECURE_CONNECTIONS_SUPPORTED,
282 .len = sizeof(uint8_t),
283 .val = &property_val};
284
285 bt_status_t cached =
286 btif_storage_get_remote_device_property(&p_dev_rec->bd_addr, &property);
287
288 if (cached == BT_STATUS_FAIL) return false;
289
290 return (bool)property_val;
291 }
292
293 /*******************************************************************************
294 *
295 * Function btm_sec_store_device_sc_support
296 *
297 * Description Save Secure Connections support for this device to file
298 *
299 ******************************************************************************/
300
btm_sec_store_device_sc_support(uint16_t hci_handle,bool secure_connections_supported)301 static void btm_sec_store_device_sc_support(uint16_t hci_handle,
302 bool secure_connections_supported) {
303 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(hci_handle);
304 if (p_dev_rec == nullptr) return;
305
306 uint8_t property_val = (uint8_t)secure_connections_supported;
307 bt_property_t property = {
308 .type = BT_PROPERTY_REMOTE_SECURE_CONNECTIONS_SUPPORTED,
309 .len = sizeof(uint8_t),
310 .val = &property_val};
311
312 btif_storage_set_remote_device_property(&p_dev_rec->bd_addr, &property);
313 }
314
315 /*******************************************************************************
316 *
317 * Function btm_sec_is_session_key_size_downgrade
318 *
319 * Description Check if there is a stored device record matching this
320 * handle, and return true if the stored record has a lower
321 * session key size than the candidate device.
322 *
323 * Returns bool
324 *
325 ******************************************************************************/
btm_sec_is_session_key_size_downgrade(uint16_t hci_handle,uint8_t key_size)326 static bool btm_sec_is_session_key_size_downgrade(uint16_t hci_handle,
327 uint8_t key_size) {
328 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(hci_handle);
329 if (p_dev_rec == nullptr) return false;
330
331 uint8_t property_val = 0;
332 bt_property_t property = {.type = BT_PROPERTY_REMOTE_MAX_SESSION_KEY_SIZE,
333 .len = sizeof(uint8_t),
334 .val = &property_val};
335
336 bt_status_t cached =
337 btif_storage_get_remote_device_property(&p_dev_rec->bd_addr, &property);
338
339 if (cached == BT_STATUS_FAIL) return false;
340
341 return property_val > key_size;
342 }
343
344 /*******************************************************************************
345 *
346 * Function btm_sec_update_session_key_size
347 *
348 * Description Store the max session key size to disk, if possible.
349 *
350 ******************************************************************************/
btm_sec_update_session_key_size(uint16_t hci_handle,uint8_t key_size)351 static void btm_sec_update_session_key_size(uint16_t hci_handle,
352 uint8_t key_size) {
353 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(hci_handle);
354 if (p_dev_rec == nullptr) return;
355
356 uint8_t property_val = key_size;
357 bt_property_t property = {.type = BT_PROPERTY_REMOTE_MAX_SESSION_KEY_SIZE,
358 .len = sizeof(uint8_t),
359 .val = &property_val};
360
361 btif_storage_set_remote_device_property(&p_dev_rec->bd_addr, &property);
362 }
363
364 /*******************************************************************************
365 *
366 * Function access_secure_service_from_temp_bond
367 *
368 * Description a utility function to test whether an access to
369 * secure service from temp bonding is happening
370 *
371 * Returns true if the aforementioned condition holds,
372 * false otherwise
373 *
374 ******************************************************************************/
access_secure_service_from_temp_bond(const tBTM_SEC_DEV_REC * p_dev_rec,bool locally_initiated,uint16_t security_req)375 static bool access_secure_service_from_temp_bond(const tBTM_SEC_DEV_REC* p_dev_rec,
376 bool locally_initiated,
377 uint16_t security_req) {
378 return !locally_initiated && (security_req & BTM_SEC_IN_AUTHENTICATE) &&
379 p_dev_rec->sec_rec.is_bond_type_temporary();
380 }
381
382 /*******************************************************************************
383 *
384 * Function BTM_SecRegister
385 *
386 * Description Application manager calls this function to register for
387 * security services. There can be one and only one
388 * application saving link keys. BTM allows only first
389 * registration.
390 *
391 * Returns true if registered OK, else false
392 *
393 ******************************************************************************/
BTM_SecRegister(const tBTM_APPL_INFO * p_cb_info)394 bool BTM_SecRegister(const tBTM_APPL_INFO* p_cb_info) {
395 log::info("p_cb_info->p_le_callback == 0x{}",
396 fmt::ptr(p_cb_info->p_le_callback));
397 if (p_cb_info->p_le_callback) {
398 log::verbose("SMP_Register( btm_proc_smp_cback )");
399 SMP_Register(btm_proc_smp_cback);
400 Octet16 zero{0};
401 /* if no IR is loaded, need to regenerate all the keys */
402 if (btm_sec_cb.devcb.id_keys.ir == zero) {
403 btm_ble_reset_id();
404 }
405 } else {
406 log::warn("p_cb_info->p_le_callback == NULL");
407 }
408
409 btm_sec_cb.api = *p_cb_info;
410 log::info("btm_sec_cb.api.p_le_callback = 0x{}",
411 fmt::ptr(btm_sec_cb.api.p_le_callback));
412 log::verbose("application registered");
413 return (true);
414 }
415
416 /*******************************************************************************
417 *
418 * Function BTM_SecAddRmtNameNotifyCallback
419 *
420 * Description Any profile can register to be notified when name of the
421 * remote device is resolved.
422 *
423 * Returns true if registered OK, else false
424 *
425 ******************************************************************************/
BTM_SecAddRmtNameNotifyCallback(tBTM_RMT_NAME_CALLBACK * p_callback)426 bool BTM_SecAddRmtNameNotifyCallback(tBTM_RMT_NAME_CALLBACK* p_callback) {
427 int i;
428
429 for (i = 0; i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) {
430 if (btm_cb.p_rmt_name_callback[i] == NULL) {
431 btm_cb.p_rmt_name_callback[i] = p_callback;
432 return (true);
433 }
434 }
435
436 return (false);
437 }
438
439 /*******************************************************************************
440 *
441 * Function BTM_SecDeleteRmtNameNotifyCallback
442 *
443 * Description Any profile can deregister notification when a new Link Key
444 * is generated per connection.
445 *
446 * Returns true if OK, else false
447 *
448 ******************************************************************************/
BTM_SecDeleteRmtNameNotifyCallback(tBTM_RMT_NAME_CALLBACK * p_callback)449 bool BTM_SecDeleteRmtNameNotifyCallback(tBTM_RMT_NAME_CALLBACK* p_callback) {
450 int i;
451
452 for (i = 0; i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) {
453 if (btm_cb.p_rmt_name_callback[i] == p_callback) {
454 btm_cb.p_rmt_name_callback[i] = NULL;
455 return (true);
456 }
457 }
458
459 return (false);
460 }
461
BTM_IsEncrypted(const RawAddress & bd_addr,tBT_TRANSPORT transport)462 bool BTM_IsEncrypted(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
463 return btm_sec_cb.IsDeviceEncrypted(bd_addr, transport);
464 }
465
BTM_IsLinkKeyAuthed(const RawAddress & bd_addr,tBT_TRANSPORT transport)466 bool BTM_IsLinkKeyAuthed(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
467 return btm_sec_cb.IsLinkKeyAuthenticated(bd_addr, transport);
468 }
469
BTM_IsLinkKeyKnown(const RawAddress & bd_addr,tBT_TRANSPORT transport)470 bool BTM_IsLinkKeyKnown(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
471 return btm_sec_cb.IsLinkKeyKnown(bd_addr, transport);
472 }
473
BTM_IsAuthenticated(const RawAddress & bd_addr,tBT_TRANSPORT transport)474 bool BTM_IsAuthenticated(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
475 return btm_sec_cb.IsDeviceAuthenticated(bd_addr, transport);
476 }
477
BTM_CanReadDiscoverableCharacteristics(const RawAddress & bd_addr)478 bool BTM_CanReadDiscoverableCharacteristics(const RawAddress& bd_addr) {
479 auto p_dev_rec = btm_find_dev(bd_addr);
480 if (p_dev_rec != nullptr) {
481 return p_dev_rec->can_read_discoverable;
482 } else {
483 log::error(
484 "BTM_CanReadDiscoverableCharacteristics invoked for an invalid "
485 "BD_ADDR");
486 return false;
487 }
488 }
489
490 /*******************************************************************************
491 *
492 * Function BTM_SetPinType
493 *
494 * Description Set PIN type for the device.
495 *
496 * Returns void
497 *
498 ******************************************************************************/
BTM_SetPinType(uint8_t pin_type,PIN_CODE pin_code,uint8_t pin_code_len)499 void BTM_SetPinType(uint8_t pin_type, PIN_CODE pin_code, uint8_t pin_code_len) {
500 log::verbose(
501 "BTM_SetPinType: pin type {} [variable-0, fixed-1], code {}, length {}",
502 pin_type, (char*)pin_code, pin_code_len);
503
504 /* If device is not up security mode will be set as a part of startup */
505 if ((btm_sec_cb.cfg.pin_type != pin_type) &&
506 bluetooth::shim::GetController() != nullptr) {
507 btsnd_hcic_write_pin_type(pin_type);
508 }
509
510 btm_sec_cb.cfg.pin_type = pin_type;
511 btm_sec_cb.cfg.pin_code_len = pin_code_len;
512 memcpy(btm_sec_cb.cfg.pin_code, pin_code, pin_code_len);
513 }
514
515 /*******************************************************************************
516 *
517 * Function BTM_SetSecurityLevel
518 *
519 * Description Register service security level with Security Manager
520 *
521 * Parameters: is_originator - true if originating the connection
522 * p_name - Name of the service relevant only if
523 * authorization will show this name to user.
524 * Ignored if BT_MAX_SERVICE_NAME_LEN is 0.
525 * service_id - service ID for the service passed to
526 * authorization callback
527 * sec_level - bit mask of the security features
528 * psm - L2CAP PSM
529 * mx_proto_id - protocol ID of multiplexing proto below
530 * mx_chan_id - channel ID of multiplexing proto below
531 *
532 * Returns true if registered OK, else false
533 *
534 ******************************************************************************/
BTM_SetSecurityLevel(bool is_originator,const char * p_name,uint8_t service_id,uint16_t sec_level,uint16_t psm,uint32_t mx_proto_id,uint32_t mx_chan_id)535 bool BTM_SetSecurityLevel(bool is_originator, const char* p_name,
536 uint8_t service_id, uint16_t sec_level, uint16_t psm,
537 uint32_t mx_proto_id, uint32_t mx_chan_id) {
538 return btm_sec_cb.AddService(is_originator, p_name, service_id, sec_level,
539 psm, mx_proto_id, mx_chan_id);
540 }
541
542 /*******************************************************************************
543 *
544 * Function BTM_SecClrService
545 *
546 * Description Removes specified service record(s) from the security
547 * database. All service records with the specified name are
548 * removed. Typically used only by devices with limited RAM so
549 * that it can reuse an old security service record.
550 *
551 * Note: Unpredictable results may occur if a service is
552 * cleared that is still in use by an application/profile.
553 *
554 * Parameters Service ID - Id of the service to remove. '0' removes all
555 * service records (except SDP).
556 *
557 * Returns Number of records that were freed.
558 *
559 ******************************************************************************/
BTM_SecClrService(uint8_t service_id)560 uint8_t BTM_SecClrService(uint8_t service_id) {
561 return btm_sec_cb.RemoveServiceById(service_id);
562 }
563
564 /*******************************************************************************
565 *
566 * Function BTM_SecClrServiceByPsm
567 *
568 * Description Removes specified service record from the security database.
569 * All service records with the specified psm are removed.
570 * Typically used by L2CAP to free up the service record used
571 * by dynamic PSM clients when the channel is closed.
572 * The given psm must be a virtual psm.
573 *
574 * Parameters Service ID - Id of the service to remove. '0' removes all
575 * service records (except SDP).
576 *
577 * Returns Number of records that were freed.
578 *
579 ******************************************************************************/
BTM_SecClrServiceByPsm(uint16_t psm)580 uint8_t BTM_SecClrServiceByPsm(uint16_t psm) {
581 return btm_sec_cb.RemoveServiceByPsm(psm);
582 }
583
584 /*******************************************************************************
585 *
586 * Function BTM_PINCodeReply
587 *
588 * Description This function is called after Security Manager submitted
589 * PIN code request to the UI.
590 *
591 * Parameters: bd_addr - Address of the device for which PIN was
592 * requested
593 * res - result of the operation BTM_SUCCESS
594 * if success
595 * pin_len - length in bytes of the PIN Code
596 * p_pin - pointer to array with the PIN Code
597 *
598 ******************************************************************************/
BTM_PINCodeReply(const RawAddress & bd_addr,tBTM_STATUS res,uint8_t pin_len,uint8_t * p_pin)599 void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res,
600 uint8_t pin_len, uint8_t* p_pin) {
601 tBTM_SEC_DEV_REC* p_dev_rec;
602
603 log::verbose(
604 "BTM_PINCodeReply(): PairState: {} PairFlags: 0x{:02x} PinLen:{} "
605 "Result:{}",
606 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
607 btm_sec_cb.pairing_flags, pin_len, res);
608
609 /* If timeout already expired or has been canceled, ignore the reply */
610 if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN) {
611 log::warn("BTM_PINCodeReply() - Wrong State: {}", btm_sec_cb.pairing_state);
612 return;
613 }
614
615 if (bd_addr != btm_sec_cb.pairing_bda) {
616 log::error("BTM_PINCodeReply() - Wrong BD Addr");
617 return;
618 }
619
620 p_dev_rec = btm_find_dev(bd_addr);
621 if (p_dev_rec == NULL) {
622 log::error("BTM_PINCodeReply() - no dev CB");
623 return;
624 }
625
626 if ((pin_len > PIN_CODE_LEN) || (pin_len == 0) || (p_pin == NULL))
627 res = BTM_ILLEGAL_VALUE;
628
629 if (res != BTM_SUCCESS) {
630 /* if peer started dd OR we started dd and pre-fetch pin was not used send
631 * negative reply */
632 if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_PEER_STARTED_DD) ||
633 ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
634 (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE))) {
635 /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed
636 * event */
637 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
638 acl_set_disconnect_reason(HCI_ERR_HOST_REJECT_SECURITY);
639
640 btsnd_hcic_pin_code_neg_reply(bd_addr);
641 } else {
642 p_dev_rec->sec_rec.security_required = BTM_SEC_NONE;
643 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
644 }
645 return;
646 }
647 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_LINK_KEY_AUTHED;
648 p_dev_rec->sec_rec.pin_code_length = pin_len;
649 if (pin_len >= 16) {
650 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED;
651 }
652
653 if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
654 (p_dev_rec->hci_handle == HCI_INVALID_HANDLE) &&
655 (!btm_sec_cb.security_mode_changed)) {
656 /* This is start of the dedicated bonding if local device is 2.0 */
657 btm_sec_cb.pin_code_len = pin_len;
658 memcpy(btm_sec_cb.pin_code, p_pin, pin_len);
659
660 btm_sec_cb.security_mode_changed = true;
661 btsnd_hcic_write_auth_enable(true);
662
663 acl_set_disconnect_reason(HCI_ERR_UNDEFINED);
664
665 /* if we rejected incoming connection request, we have to wait
666 * HCI_Connection_Complete event */
667 /* before originating */
668 if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) {
669 log::warn(
670 "BTM_PINCodeReply(): waiting HCI_Connection_Complete after rejected "
671 "incoming connection");
672 /* we change state little bit early so btm_sec_connected() will originate
673 * connection */
674 /* when existing ACL link is down completely */
675 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
676 }
677 /* if we already accepted incoming connection from pairing device */
678 else if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND) {
679 log::warn(
680 "BTM_PINCodeReply(): link is connecting so wait pin code request "
681 "from peer");
682 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
683 } else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) {
684 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
685 p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_LINK_KEY_AUTHED;
686
687 NotifyBondingChange(*p_dev_rec, HCI_ERR_AUTH_FAILURE);
688 }
689 return;
690 }
691
692 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
693 acl_set_disconnect_reason(HCI_SUCCESS);
694
695 btsnd_hcic_pin_code_req_reply(bd_addr, pin_len, p_pin);
696 }
697
698 /*******************************************************************************
699 *
700 * Function btm_sec_bond_by_transport
701 *
702 * Description this is the bond function that will start either SSP or SMP.
703 *
704 * Parameters: bd_addr - Address of the device to bond
705 * addr_type - type of the address
706 * transport - transport on which to create bond
707 *
708 * Note: After 2.1 parameters are not used and preserved here not to change API
709 ******************************************************************************/
btm_sec_bond_by_transport(const RawAddress & bd_addr,tBLE_ADDR_TYPE addr_type,tBT_TRANSPORT transport)710 tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr,
711 tBLE_ADDR_TYPE addr_type,
712 tBT_TRANSPORT transport) {
713 tBTM_SEC_DEV_REC* p_dev_rec;
714 tBTM_STATUS status;
715 log::info("Transport used {}, bd_addr={}", transport, bd_addr);
716
717 /* Other security process is in progress */
718 if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) {
719 log::error("BTM_SecBond: already busy in state: {}",
720 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
721 return (BTM_WRONG_MODE);
722 }
723
724 p_dev_rec = btm_find_or_alloc_dev(bd_addr);
725 if (p_dev_rec == NULL) {
726 log::error("No memory to allocate new p_dev_rec");
727 return (BTM_NO_RESOURCES);
728 }
729
730 if (bluetooth::shim::GetController() == nullptr) {
731 log::error("controller module is not ready");
732 return (BTM_NO_RESOURCES);
733 }
734
735 log::verbose("before update sec_flags=0x{:x}", p_dev_rec->sec_rec.sec_flags);
736
737 /* Finished if connection is active and already paired */
738 if (((p_dev_rec->hci_handle != HCI_INVALID_HANDLE) &&
739 transport == BT_TRANSPORT_BR_EDR &&
740 (p_dev_rec->sec_rec.sec_flags & BTM_SEC_AUTHENTICATED)) ||
741 ((p_dev_rec->ble_hci_handle != HCI_INVALID_HANDLE) &&
742 transport == BT_TRANSPORT_LE &&
743 (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_AUTHENTICATED))) {
744 log::warn("BTM_SecBond -> Already Paired");
745 return (BTM_SUCCESS);
746 }
747
748 /* Tell controller to get rid of the link key if it has one stored */
749 if ((BTM_DeleteStoredLinkKey(&bd_addr, NULL)) != BTM_SUCCESS) {
750 log::error("Failed to delete stored link keys");
751 return (BTM_NO_RESOURCES);
752 }
753
754 btm_sec_cb.pairing_bda = bd_addr;
755
756 btm_sec_cb.pairing_flags = BTM_PAIR_FLAGS_WE_STARTED_DD;
757
758 p_dev_rec->sec_rec.security_required = BTM_SEC_OUT_AUTHENTICATE;
759 p_dev_rec->is_originator = true;
760
761 BTM_LogHistory(kBtmLogTag, bd_addr, "Bonding initiated",
762 bt_transport_text(transport));
763
764 if (transport == BT_TRANSPORT_LE) {
765 btm_ble_init_pseudo_addr(p_dev_rec, bd_addr);
766 p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_LE_MASK;
767
768 if (SMP_Pair(bd_addr, addr_type) == SMP_STARTED) {
769 btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_LE_ACTIVE;
770 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_AUTHENTICATING;
771 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
772 return BTM_CMD_STARTED;
773 }
774
775 btm_sec_cb.pairing_flags = 0;
776 return (BTM_NO_RESOURCES);
777 }
778
779 p_dev_rec->sec_rec.sec_flags &=
780 ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED |
781 BTM_SEC_ROLE_SWITCHED | BTM_SEC_LINK_KEY_AUTHED);
782
783 log::verbose("after update sec_flags=0x{:x}", p_dev_rec->sec_rec.sec_flags);
784 if (!bluetooth::shim::GetController()->SupportsSimplePairing()) {
785 /* The special case when we authenticate keyboard. Set pin type to fixed */
786 /* It would be probably better to do it from the application, but it is */
787 /* complicated */
788 if (((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) ==
789 BTM_COD_MAJOR_PERIPHERAL) &&
790 (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD) &&
791 (btm_sec_cb.cfg.pin_type != HCI_PIN_TYPE_FIXED)) {
792 btm_sec_cb.pin_type_changed = true;
793 btsnd_hcic_write_pin_type(HCI_PIN_TYPE_FIXED);
794 }
795 }
796
797 log::verbose("BTM_SecBond: Remote sm4: 0x{:x} HCI Handle: 0x{:04x}",
798 p_dev_rec->sm4, p_dev_rec->hci_handle);
799
800 /* If connection already exists... */
801 if (BTM_IsAclConnectionUpAndHandleValid(bd_addr, transport)) {
802 log::debug("An ACL connection currently exists peer:{} transport:{}",
803 bd_addr, bt_transport_text(transport));
804 btm_sec_wait_and_start_authentication(p_dev_rec);
805
806 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
807
808 /* Mark lcb as bonding */
809 l2cu_update_lcb_4_bonding(bd_addr, true);
810 return (BTM_CMD_STARTED);
811 }
812 log::debug("An ACL connection does not currently exist peer:{} transport:{}",
813 bd_addr, bt_transport_text(transport));
814
815 log::verbose("sec mode: {} sm4:x{:x}", btm_sec_cb.security_mode,
816 p_dev_rec->sm4);
817 if (!bluetooth::shim::GetController()->SupportsSimplePairing() ||
818 (p_dev_rec->sm4 == BTM_SM4_KNOWN)) {
819 if (btm_sec_check_prefetch_pin(p_dev_rec)) {
820 log::debug("Class of device used to check for pin peer:{} transport:{}",
821 bd_addr, bt_transport_text(transport));
822 return (BTM_CMD_STARTED);
823 }
824 }
825 if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SP ||
826 btm_sec_cb.security_mode == BTM_SEC_MODE_SC) &&
827 BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) {
828 /* local is 2.1 and peer is unknown */
829 if ((p_dev_rec->sm4 & BTM_SM4_CONN_PEND) == 0) {
830 /* we are not accepting connection request from peer
831 * -> RNR (to learn if peer is 2.1)
832 * RNR when no ACL causes HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT */
833 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_GET_REM_NAME);
834 status = BTM_ReadRemoteDeviceName(bd_addr, NULL, BT_TRANSPORT_BR_EDR);
835 } else {
836 /* We are accepting connection request from peer */
837 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
838 status = BTM_CMD_STARTED;
839 }
840 log::verbose("State:{} sm4: 0x{:x} sec_state:{}",
841 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
842 p_dev_rec->sm4, p_dev_rec->sec_rec.sec_state);
843 } else {
844 /* both local and peer are 2.1 */
845 status = btm_sec_dd_create_conn(p_dev_rec);
846 }
847
848 if (status != BTM_CMD_STARTED) {
849 log::error(
850 "BTM_ReadRemoteDeviceName or btm_sec_dd_create_conn error: 0x{:x}",
851 (int)status);
852 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
853 }
854
855 return status;
856 }
857
858 /*******************************************************************************
859 *
860 * Function BTM_SecBond
861 *
862 * Description This function is called to perform bonding with peer device.
863 * If the connection is already up, but not secure, pairing
864 * is attempted. If already paired BTM_SUCCESS is returned.
865 *
866 * Parameters: bd_addr - Address of the device to bond
867 * transport - doing SSP over BR/EDR or SMP over LE
868 *
869 * Note: After 2.1 parameters are not used and preserved here not to change API
870 ******************************************************************************/
BTM_SecBond(const RawAddress & bd_addr,tBLE_ADDR_TYPE addr_type,tBT_TRANSPORT transport,tBT_DEVICE_TYPE)871 tBTM_STATUS BTM_SecBond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type,
872 tBT_TRANSPORT transport,
873 tBT_DEVICE_TYPE /* device_type */) {
874 if (transport == BT_TRANSPORT_AUTO) {
875 if (addr_type == BLE_ADDR_PUBLIC) {
876 transport =
877 BTM_UseLeLink(bd_addr) ? BT_TRANSPORT_LE : BT_TRANSPORT_BR_EDR;
878 } else {
879 log::info("Forcing transport LE (was auto) because of the address type");
880 transport = BT_TRANSPORT_LE;
881 }
882 }
883 tBT_DEVICE_TYPE dev_type;
884
885 BTM_ReadDevInfo(bd_addr, &dev_type, &addr_type);
886 /* LE device, do SMP pairing */
887 if ((transport == BT_TRANSPORT_LE && (dev_type & BT_DEVICE_TYPE_BLE) == 0) ||
888 (transport == BT_TRANSPORT_BR_EDR &&
889 (dev_type & BT_DEVICE_TYPE_BREDR) == 0)) {
890 log::warn("Requested transport and supported transport don't match");
891 if (!com::android::bluetooth::flags::pairing_on_unknown_transport()) {
892 return BTM_ILLEGAL_ACTION;
893 }
894 }
895 return btm_sec_bond_by_transport(bd_addr, addr_type, transport);
896 }
897
898 /*******************************************************************************
899 *
900 * Function BTM_SecBondCancel
901 *
902 * Description This function is called to cancel ongoing bonding process
903 * with peer device.
904 *
905 * Parameters: bd_addr - Address of the peer device
906 * transport - false for BR/EDR link; true for LE link
907 *
908 ******************************************************************************/
BTM_SecBondCancel(const RawAddress & bd_addr)909 tBTM_STATUS BTM_SecBondCancel(const RawAddress& bd_addr) {
910 tBTM_SEC_DEV_REC* p_dev_rec;
911
912 log::verbose("BTM_SecBondCancel() State: {} flags:0x{:x}",
913 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
914 btm_sec_cb.pairing_flags);
915 p_dev_rec = btm_find_dev(bd_addr);
916 if (!p_dev_rec || btm_sec_cb.pairing_bda != bd_addr) {
917 return BTM_UNKNOWN_ADDR;
918 }
919
920 if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_LE_ACTIVE) {
921 if (p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_AUTHENTICATING) {
922 log::verbose("Cancel LE pairing");
923 if (SMP_PairCancel(bd_addr)) {
924 return BTM_CMD_STARTED;
925 }
926 }
927 return BTM_WRONG_MODE;
928 }
929
930 log::verbose("hci_handle:0x{:x} sec_state:{}", p_dev_rec->hci_handle,
931 p_dev_rec->sec_rec.sec_state);
932 if (BTM_PAIR_STATE_WAIT_LOCAL_PIN == btm_sec_cb.pairing_state &&
933 BTM_PAIR_FLAGS_WE_STARTED_DD & btm_sec_cb.pairing_flags) {
934 /* pre-fetching pin for dedicated bonding */
935 btm_sec_bond_cancel_complete();
936 return BTM_SUCCESS;
937 }
938
939 /* If this BDA is in a bonding procedure */
940 if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
941 (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)) {
942 /* If the HCI link is up */
943 if (p_dev_rec->hci_handle != HCI_INVALID_HANDLE) {
944 /* If some other thread disconnecting, we do not send second command */
945 if ((p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_DISCONNECTING) ||
946 (p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_DISCONNECTING_BOTH))
947 return (BTM_CMD_STARTED);
948
949 /* If the HCI link was set up by Bonding process */
950 if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE)
951 return btm_sec_send_hci_disconnect(
952 p_dev_rec, HCI_ERR_PEER_USER, p_dev_rec->hci_handle,
953 "stack::btm::btm_sec::BTM_SecBondCancel");
954 else
955 l2cu_update_lcb_4_bonding(bd_addr, false);
956
957 return BTM_NOT_AUTHORIZED;
958 } else /*HCI link is not up */
959 {
960 /* If the HCI link creation was started by Bonding process */
961 if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE) {
962 btsnd_hcic_create_conn_cancel(bd_addr);
963 return BTM_CMD_STARTED;
964 }
965 if (btm_sec_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME) {
966 if (get_btm_client_interface().peer.BTM_CancelRemoteDeviceName() !=
967 BTM_SUCCESS) {
968 log::warn("Unable to cancel RNR");
969 }
970 btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_WE_CANCEL_DD;
971 return BTM_CMD_STARTED;
972 }
973 return BTM_NOT_AUTHORIZED;
974 }
975 }
976
977 return BTM_WRONG_MODE;
978 }
979
980 /*******************************************************************************
981 *
982 * Function BTM_SecGetDeviceLinkKeyType
983 *
984 * Description This function is called to obtain link key type for the
985 * device.
986 * it returns BTM_SUCCESS if link key is available, or
987 * BTM_UNKNOWN_ADDR if Security Manager does not know about
988 * the device or device record does not contain link key info
989 *
990 * Returns BTM_LKEY_TYPE_IGNORE if link key is unknown, link type
991 * otherwise.
992 *
993 ******************************************************************************/
BTM_SecGetDeviceLinkKeyType(const RawAddress & bd_addr)994 tBTM_LINK_KEY_TYPE BTM_SecGetDeviceLinkKeyType(const RawAddress& bd_addr) {
995 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
996
997 if ((p_dev_rec != NULL) &&
998 (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN)) {
999 return p_dev_rec->sec_rec.link_key_type;
1000 }
1001 return BTM_LKEY_TYPE_IGNORE;
1002 }
1003
1004 /*******************************************************************************
1005 *
1006 * Function BTM_SetEncryption
1007 *
1008 * Description This function is called to ensure that connection is
1009 * encrypted. Should be called only on an open connection.
1010 * Typically only needed for connections that first want to
1011 * bring up unencrypted links, then later encrypt them.
1012 *
1013 * Parameters: bd_addr - Address of the peer device
1014 * transport - Link transport
1015 * p_callback - Pointer to callback function called after
1016 * required procedures are completed. Can be
1017 * set to NULL if status is not desired.
1018 * p_ref_data - pointer to any data the caller wishes to
1019 * receive in the callback function upon
1020 * completion. can be set to NULL if not used.
1021 * sec_act - LE security action, unused for BR/EDR
1022 *
1023 * Returns BTM_SUCCESS - already encrypted
1024 * BTM_PENDING - command will be returned in the callback
1025 * BTM_WRONG_MODE- connection not up.
1026 * BTM_BUSY - security procedures are currently active
1027 * BTM_MODE_UNSUPPORTED - if security manager not linked in.
1028 *
1029 ******************************************************************************/
BTM_SetEncryption(const RawAddress & bd_addr,tBT_TRANSPORT transport,tBTM_SEC_CALLBACK * p_callback,void * p_ref_data,tBTM_BLE_SEC_ACT sec_act)1030 tBTM_STATUS BTM_SetEncryption(const RawAddress& bd_addr,
1031 tBT_TRANSPORT transport,
1032 tBTM_SEC_CALLBACK* p_callback, void* p_ref_data,
1033 tBTM_BLE_SEC_ACT sec_act) {
1034 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
1035 if (p_dev_rec == nullptr) {
1036 log::error("Unable to set encryption for unknown device");
1037 return BTM_WRONG_MODE;
1038 }
1039
1040 switch (transport) {
1041 case BT_TRANSPORT_BR_EDR:
1042 if (p_dev_rec->hci_handle == HCI_INVALID_HANDLE) {
1043 log::warn(
1044 "Security Manager: BTM_SetEncryption not connected peer:{} "
1045 "transport:{}",
1046 bd_addr, bt_transport_text(transport));
1047 if (p_callback) {
1048 do_in_main_thread(FROM_HERE,
1049 base::BindOnce(p_callback, bd_addr, transport,
1050 p_ref_data, BTM_WRONG_MODE));
1051 }
1052 return BTM_WRONG_MODE;
1053 }
1054 if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_ENCRYPTED) {
1055 log::debug(
1056 "Security Manager: BTM_SetEncryption already encrypted peer:{} "
1057 "transport:{}",
1058 bd_addr, bt_transport_text(transport));
1059 if (p_callback) {
1060 do_in_main_thread(FROM_HERE,
1061 base::BindOnce(p_callback, bd_addr, transport,
1062 p_ref_data, BTM_SUCCESS));
1063 }
1064 return BTM_SUCCESS;
1065 }
1066 break;
1067
1068 case BT_TRANSPORT_LE:
1069 if (p_dev_rec->ble_hci_handle == HCI_INVALID_HANDLE) {
1070 log::warn(
1071 "Security Manager: BTM_SetEncryption not connected peer:{} "
1072 "transport:{}",
1073 bd_addr, bt_transport_text(transport));
1074 if (p_callback) {
1075 do_in_main_thread(FROM_HERE,
1076 base::BindOnce(p_callback, bd_addr, transport,
1077 p_ref_data, BTM_WRONG_MODE));
1078 }
1079 return BTM_WRONG_MODE;
1080 }
1081 if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_ENCRYPTED) {
1082 log::debug(
1083 "Security Manager: BTM_SetEncryption already encrypted peer:{} "
1084 "transport:{}",
1085 bd_addr, bt_transport_text(transport));
1086 if (p_callback) {
1087 do_in_main_thread(FROM_HERE,
1088 base::BindOnce(p_callback, bd_addr, transport,
1089 p_ref_data, BTM_SUCCESS));
1090 }
1091 return BTM_SUCCESS;
1092 }
1093 break;
1094
1095 default:
1096 log::error("Unknown transport");
1097 break;
1098 }
1099
1100 /* Enqueue security request if security is active */
1101 if (bluetooth::common::init_flags::encryption_in_busy_state_is_enabled()) {
1102 bool enqueue = false;
1103 switch (p_dev_rec->sec_rec.sec_state) {
1104 case BTM_SEC_STATE_AUTHENTICATING:
1105 case BTM_SEC_STATE_DISCONNECTING_BOTH:
1106 /* Applicable for both transports */
1107 enqueue = true;
1108 break;
1109
1110 case BTM_SEC_STATE_ENCRYPTING:
1111 case BTM_SEC_STATE_DISCONNECTING:
1112 if (transport == BT_TRANSPORT_BR_EDR) {
1113 enqueue = true;
1114 }
1115 break;
1116
1117 case BTM_SEC_STATE_LE_ENCRYPTING:
1118 case BTM_SEC_STATE_DISCONNECTING_BLE:
1119 if (transport == BT_TRANSPORT_LE) {
1120 enqueue = true;
1121 }
1122 break;
1123
1124 default:
1125 if (p_dev_rec->sec_rec.p_callback != nullptr) {
1126 enqueue = true;
1127 }
1128 break;
1129 }
1130
1131 if (enqueue) {
1132 log::warn("Security Manager: Enqueue request in state:{}",
1133 security_state_text(p_dev_rec->sec_rec.sec_state));
1134 btm_sec_queue_encrypt_request(bd_addr, transport, p_callback, p_ref_data,
1135 sec_act);
1136 return BTM_CMD_STARTED;
1137 }
1138 } else {
1139 if (p_dev_rec->sec_rec.p_callback ||
1140 (p_dev_rec->sec_rec.sec_state != BTM_SEC_STATE_IDLE)) {
1141 log::warn("Security Manager: BTM_SetEncryption busy, enqueue request");
1142 btm_sec_queue_encrypt_request(bd_addr, transport, p_callback, p_ref_data,
1143 sec_act);
1144 log::info("Queued start encryption");
1145 return BTM_CMD_STARTED;
1146 }
1147 }
1148
1149 p_dev_rec->sec_rec.p_callback = p_callback;
1150 p_dev_rec->sec_rec.p_ref_data = p_ref_data;
1151 p_dev_rec->sec_rec.security_required |=
1152 (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT);
1153 p_dev_rec->is_originator = false;
1154
1155 log::debug(
1156 "Security Manager: BTM_SetEncryption classic_handle:0x{:04x} "
1157 "ble_handle:0x{:04x} state:{} flags:0x{:x} required:0x{:x} "
1158 "p_callback={:c}",
1159 p_dev_rec->hci_handle, p_dev_rec->ble_hci_handle,
1160 p_dev_rec->sec_rec.sec_state, p_dev_rec->sec_rec.sec_flags,
1161 p_dev_rec->sec_rec.security_required, (p_callback) ? 'T' : 'F');
1162
1163 tBTM_STATUS rc = BTM_SUCCESS;
1164 switch (transport) {
1165 case BT_TRANSPORT_LE:
1166 if (BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) {
1167 rc = btm_ble_set_encryption(bd_addr, sec_act,
1168 L2CA_GetBleConnRole(bd_addr));
1169 } else {
1170 rc = BTM_WRONG_MODE;
1171 log::warn("cannot call btm_ble_set_encryption, p is NULL");
1172 }
1173 break;
1174
1175 case BT_TRANSPORT_BR_EDR:
1176 rc = btm_sec_execute_procedure(p_dev_rec);
1177 break;
1178
1179 default:
1180 log::error("Unknown transport");
1181 break;
1182 }
1183
1184 switch (rc) {
1185 case BTM_CMD_STARTED:
1186 case BTM_BUSY:
1187 break;
1188
1189 default:
1190 if (p_callback) {
1191 log::debug("Executing encryption callback peer:{} transport:{}",
1192 bd_addr, bt_transport_text(transport));
1193 p_dev_rec->sec_rec.p_callback = nullptr;
1194 do_in_main_thread(FROM_HERE,
1195 base::BindOnce(p_callback, bd_addr, transport,
1196 p_dev_rec->sec_rec.p_ref_data, rc));
1197 }
1198 break;
1199 }
1200 return rc;
1201 }
1202
BTM_SecIsSecurityPending(const RawAddress & bd_addr)1203 bool BTM_SecIsSecurityPending(const RawAddress& bd_addr) {
1204 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
1205 return p_dev_rec &&
1206 (p_dev_rec->sec_rec.is_security_state_encrypting() ||
1207 p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_AUTHENTICATING);
1208 }
1209
1210 /*******************************************************************************
1211 * disconnect the ACL link, if it's not done yet.
1212 ******************************************************************************/
btm_sec_send_hci_disconnect(tBTM_SEC_DEV_REC * p_dev_rec,tHCI_STATUS reason,uint16_t conn_handle,std::string comment)1213 static tBTM_STATUS btm_sec_send_hci_disconnect(tBTM_SEC_DEV_REC* p_dev_rec,
1214 tHCI_STATUS reason,
1215 uint16_t conn_handle,
1216 std::string comment) {
1217 const tSECURITY_STATE old_state =
1218 static_cast<tSECURITY_STATE>(p_dev_rec->sec_rec.sec_state);
1219 const tBTM_STATUS status = BTM_CMD_STARTED;
1220
1221 /* send HCI_Disconnect on a transport only once */
1222 switch (old_state) {
1223 case BTM_SEC_STATE_DISCONNECTING:
1224 if (conn_handle == p_dev_rec->hci_handle) {
1225 // Already sent classic disconnect
1226 return status;
1227 }
1228 // Prepare to send disconnect on le transport
1229 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_DISCONNECTING_BOTH;
1230 break;
1231
1232 case BTM_SEC_STATE_DISCONNECTING_BLE:
1233 if (conn_handle == p_dev_rec->ble_hci_handle) {
1234 // Already sent ble disconnect
1235 return status;
1236 }
1237 // Prepare to send disconnect on classic transport
1238 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_DISCONNECTING_BOTH;
1239 break;
1240
1241 case BTM_SEC_STATE_DISCONNECTING_BOTH:
1242 // Already sent disconnect on both transports
1243 return status;
1244
1245 default:
1246 p_dev_rec->sec_rec.sec_state = (conn_handle == p_dev_rec->hci_handle)
1247 ? BTM_SEC_STATE_DISCONNECTING
1248 : BTM_SEC_STATE_DISCONNECTING_BLE;
1249
1250 break;
1251 }
1252
1253 log::debug("Send hci disconnect handle:0x{:04x} reason:{}", conn_handle,
1254 hci_reason_code_text(reason));
1255 acl_disconnect_after_role_switch(conn_handle, reason, comment);
1256
1257 return status;
1258 }
1259
1260 /*******************************************************************************
1261 *
1262 * Function BTM_ConfirmReqReply
1263 *
1264 * Description This function is called to confirm the numeric value for
1265 * Simple Pairing in response to BTM_SP_CFM_REQ_EVT
1266 *
1267 * Parameters: res - result of the operation BTM_SUCCESS if
1268 * success
1269 * bd_addr - Address of the peer device
1270 *
1271 ******************************************************************************/
BTM_ConfirmReqReply(tBTM_STATUS res,const RawAddress & bd_addr)1272 void BTM_ConfirmReqReply(tBTM_STATUS res, const RawAddress& bd_addr) {
1273 log::verbose("BTM_ConfirmReqReply() State: {} Res: {}",
1274 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
1275 res);
1276
1277 /* If timeout already expired or has been canceled, ignore the reply */
1278 if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM) ||
1279 (btm_sec_cb.pairing_bda != bd_addr)) {
1280 log::warn(
1281 "Unexpected pairing confirm for {}, pairing_state: {}, pairing_bda: {}",
1282 bd_addr, tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
1283 btm_sec_cb.pairing_bda);
1284 return;
1285 }
1286
1287 BTM_LogHistory(kBtmLogTag, bd_addr, "Confirm reply",
1288 base::StringPrintf("status:%s", btm_status_text(res).c_str()));
1289
1290 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
1291
1292 if ((res == BTM_SUCCESS) || (res == BTM_SUCCESS_NO_SECURITY)) {
1293 acl_set_disconnect_reason(HCI_SUCCESS);
1294
1295 btsnd_hcic_user_conf_reply(bd_addr, true);
1296 } else {
1297 /* Report authentication failed event from state
1298 * BTM_PAIR_STATE_WAIT_AUTH_COMPLETE */
1299 acl_set_disconnect_reason(HCI_ERR_HOST_REJECT_SECURITY);
1300 btsnd_hcic_user_conf_reply(bd_addr, false);
1301 }
1302 }
1303
1304 /*******************************************************************************
1305 *
1306 * Function BTM_PasskeyReqReply
1307 *
1308 * Description This function is called to provide the passkey for
1309 * Simple Pairing in response to BTM_SP_KEY_REQ_EVT
1310 *
1311 * Parameters: res - result of the operation BTM_SUCCESS if success
1312 * bd_addr - Address of the peer device
1313 * passkey - numeric value in the range of
1314 * BTM_MIN_PASSKEY_VAL(0) -
1315 * BTM_MAX_PASSKEY_VAL(999999(0xF423F)).
1316 *
1317 ******************************************************************************/
BTM_PasskeyReqReply(tBTM_STATUS res,const RawAddress & bd_addr,uint32_t passkey)1318 void BTM_PasskeyReqReply(tBTM_STATUS res, const RawAddress& bd_addr,
1319 uint32_t passkey) {
1320 log::verbose("BTM_PasskeyReqReply: State: {} res:{}",
1321 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
1322 res);
1323
1324 if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_IDLE) ||
1325 (btm_sec_cb.pairing_bda != bd_addr)) {
1326 return;
1327 }
1328
1329 /* If timeout already expired or has been canceled, ignore the reply */
1330 if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) &&
1331 (res != BTM_SUCCESS)) {
1332 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
1333 if (p_dev_rec != NULL) {
1334 acl_set_disconnect_reason(HCI_ERR_HOST_REJECT_SECURITY);
1335
1336 if (p_dev_rec->hci_handle != HCI_INVALID_HANDLE)
1337 btm_sec_send_hci_disconnect(
1338 p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle,
1339 "stack::btm::btm_sec::BTM_PasskeyReqReply Invalid handle");
1340 else
1341 BTM_SecBondCancel(bd_addr);
1342
1343 p_dev_rec->sec_rec.sec_flags &=
1344 ~(BTM_SEC_LINK_KEY_AUTHED | BTM_SEC_LINK_KEY_KNOWN);
1345
1346 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
1347 return;
1348 }
1349 } else if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_KEY_ENTRY)
1350 return;
1351
1352 if (passkey > BTM_MAX_PASSKEY_VAL) res = BTM_ILLEGAL_VALUE;
1353
1354 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
1355
1356 if (res != BTM_SUCCESS) {
1357 /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed
1358 * event */
1359 acl_set_disconnect_reason(HCI_ERR_HOST_REJECT_SECURITY);
1360 btsnd_hcic_user_passkey_neg_reply(bd_addr);
1361 } else {
1362 acl_set_disconnect_reason(HCI_SUCCESS);
1363 btsnd_hcic_user_passkey_reply(bd_addr, passkey);
1364 }
1365 }
1366
1367 /*******************************************************************************
1368 *
1369 * Function BTM_ReadLocalOobData
1370 *
1371 * Description This function is called to read the local OOB data from
1372 * LM
1373 *
1374 ******************************************************************************/
BTM_ReadLocalOobData(void)1375 void BTM_ReadLocalOobData(void) {
1376 if (com::android::bluetooth::flags::use_local_oob_extended_command() &&
1377 bluetooth::shim::GetController()->SupportsSecureConnections()) {
1378 btsnd_hcic_read_local_oob_extended_data();
1379 } else {
1380 btsnd_hcic_read_local_oob_data();
1381 }
1382 }
1383
1384 /*******************************************************************************
1385 *
1386 * Function BTM_RemoteOobDataReply
1387 *
1388 * Description This function is called to provide the remote OOB data for
1389 * Simple Pairing in response to BTM_SP_RMT_OOB_EVT
1390 *
1391 * Parameters: bd_addr - Address of the peer device
1392 * c - simple pairing Hash C.
1393 * r - simple pairing Randomizer C.
1394 *
1395 ******************************************************************************/
BTM_RemoteOobDataReply(tBTM_STATUS res,const RawAddress & bd_addr,const Octet16 & c,const Octet16 & r)1396 void BTM_RemoteOobDataReply(tBTM_STATUS res, const RawAddress& bd_addr,
1397 const Octet16& c, const Octet16& r) {
1398 log::verbose("State: {} res: {}",
1399 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
1400 res);
1401
1402 /* If timeout already expired or has been canceled, ignore the reply */
1403 if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP) return;
1404
1405 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
1406
1407 if (res != BTM_SUCCESS) {
1408 /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed
1409 * event */
1410 acl_set_disconnect_reason(HCI_ERR_HOST_REJECT_SECURITY);
1411 btsnd_hcic_rem_oob_neg_reply(bd_addr);
1412 } else {
1413 acl_set_disconnect_reason(HCI_SUCCESS);
1414 btsnd_hcic_rem_oob_reply(bd_addr, c, r);
1415 }
1416 }
1417
1418 /*******************************************************************************
1419 *
1420 * Function BTM_PeerSupportsSecureConnections
1421 *
1422 * Description This function is called to check if the peer supports
1423 * BR/EDR Secure Connections.
1424 *
1425 * Parameters: bd_addr - address of the peer
1426 *
1427 * Returns true if BR/EDR Secure Connections are supported by the peer,
1428 * else false.
1429 *
1430 ******************************************************************************/
BTM_PeerSupportsSecureConnections(const RawAddress & bd_addr)1431 bool BTM_PeerSupportsSecureConnections(const RawAddress& bd_addr) {
1432 tBTM_SEC_DEV_REC* p_dev_rec;
1433
1434 p_dev_rec = btm_find_dev(bd_addr);
1435 if (p_dev_rec == NULL) {
1436 log::warn("unknown BDA: {}", bd_addr);
1437 return false;
1438 }
1439
1440 return (p_dev_rec->SupportsSecureConnections());
1441 }
1442
1443 /*******************************************************************************
1444 *
1445 * Function BTM_GetPeerDeviceTypeFromFeatures
1446 *
1447 * Description This function is called to retrieve the peer device type
1448 * by referencing the remote features.
1449 *
1450 * Parameters: bd_addr - address of the peer
1451 *
1452 * Returns BT_DEVICE_TYPE_DUMO if both BR/EDR and BLE transports are
1453 * supported by the peer,
1454 * BT_DEVICE_TYPE_BREDR if only BR/EDR transport is supported,
1455 * BT_DEVICE_TYPE_BLE if only BLE transport is supported.
1456 *
1457 ******************************************************************************/
BTM_GetPeerDeviceTypeFromFeatures(const RawAddress & bd_addr)1458 tBT_DEVICE_TYPE BTM_GetPeerDeviceTypeFromFeatures(const RawAddress& bd_addr) {
1459 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
1460 if (p_dev_rec == nullptr) {
1461 log::warn("Unknown BDA:{}", bd_addr);
1462 } else {
1463 if (p_dev_rec->remote_supports_ble && p_dev_rec->remote_supports_bredr) {
1464 return BT_DEVICE_TYPE_DUMO;
1465 } else if (p_dev_rec->remote_supports_bredr) {
1466 return BT_DEVICE_TYPE_BREDR;
1467 } else if (p_dev_rec->remote_supports_ble) {
1468 return BT_DEVICE_TYPE_BLE;
1469 } else {
1470 log::warn("Device features does not support BR/EDR and BLE:{}", bd_addr);
1471 }
1472 }
1473 return BT_DEVICE_TYPE_BREDR;
1474 }
1475
1476 /*******************************************************************************
1477 *
1478 * Function BTM_GetInitialSecurityMode
1479 *
1480 * Description This function is called to retrieve the configured
1481 * security mode.
1482 *
1483 ******************************************************************************/
BTM_GetSecurityMode()1484 uint8_t BTM_GetSecurityMode() { return btm_sec_cb.security_mode; }
1485
1486 /************************************************************************
1487 * I N T E R N A L F U N C T I O N S
1488 ************************************************************************/
1489 /*******************************************************************************
1490 *
1491 * Function btm_sec_is_upgrade_possible
1492 *
1493 * Description This function returns true if the existing link key
1494 * can be upgraded or if the link key does not exist.
1495 *
1496 * Returns bool
1497 *
1498 ******************************************************************************/
btm_sec_is_upgrade_possible(tBTM_SEC_DEV_REC * p_dev_rec,bool is_originator)1499 static bool btm_sec_is_upgrade_possible(tBTM_SEC_DEV_REC* p_dev_rec,
1500 bool is_originator) {
1501 uint16_t mtm_check = is_originator ? BTM_SEC_OUT_MITM : BTM_SEC_IN_MITM;
1502 bool is_possible = true;
1503
1504 if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN) {
1505 is_possible = false;
1506 /* Already have a link key to the connected peer. Is the link key secure
1507 *enough?
1508 ** Is a link key upgrade even possible?
1509 */
1510 if ((p_dev_rec->sec_rec.security_required & mtm_check) /* needs MITM */
1511 &&
1512 ((p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB) ||
1513 (p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256))
1514 /* has unauthenticated
1515 link key */
1516 && (p_dev_rec->sec_rec.rmt_io_caps <
1517 BTM_IO_CAP_MAX) /* a valid peer IO cap */
1518 && (btm_sec_io_map[p_dev_rec->sec_rec.rmt_io_caps]
1519 [btm_sec_cb.devcb.loc_io_caps]))
1520 /* authenticated
1521 link key is possible */
1522 {
1523 /* upgrade is possible: check if the application wants the upgrade.
1524 * If the application is configured to use a global MITM flag,
1525 * it probably would not want to upgrade the link key based on the
1526 * security level database */
1527 is_possible = true;
1528 }
1529 }
1530 log::verbose("is_possible: {} sec_flags: 0x{:x}", is_possible,
1531 p_dev_rec->sec_rec.sec_flags);
1532 return is_possible;
1533 }
1534
1535 /*******************************************************************************
1536 *
1537 * Function btm_sec_check_upgrade
1538 *
1539 * Description This function is called to check if the existing link key
1540 * needs to be upgraded.
1541 *
1542 * Returns void
1543 *
1544 ******************************************************************************/
btm_sec_check_upgrade(tBTM_SEC_DEV_REC * p_dev_rec,bool is_originator)1545 static void btm_sec_check_upgrade(tBTM_SEC_DEV_REC* p_dev_rec,
1546 bool is_originator) {
1547 log::verbose("verify whether the link key should be upgraded");
1548
1549 /* Only check if link key already exists */
1550 if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN)) return;
1551
1552 if (btm_sec_is_upgrade_possible(p_dev_rec, is_originator)) {
1553 log::verbose("need upgrade!! sec_flags:0x{:x}",
1554 p_dev_rec->sec_rec.sec_flags);
1555 /* if the application confirms the upgrade, set the upgrade bit */
1556 p_dev_rec->sm4 |= BTM_SM4_UPGRADE;
1557
1558 /* Clear the link key known to go through authentication/pairing again */
1559 p_dev_rec->sec_rec.sec_flags &=
1560 ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED);
1561 p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_AUTHENTICATED;
1562 log::verbose("sec_flags:0x{:x}", p_dev_rec->sec_rec.sec_flags);
1563 }
1564 }
1565
btm_sec_l2cap_access_req_by_requirement(const RawAddress & bd_addr,uint16_t security_required,bool is_originator,tBTM_SEC_CALLBACK * p_callback,void * p_ref_data)1566 tBTM_STATUS btm_sec_l2cap_access_req_by_requirement(
1567 const RawAddress& bd_addr, uint16_t security_required, bool is_originator,
1568 tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) {
1569 log::debug(
1570 "Checking l2cap access requirements peer:{} security:0x{:x} "
1571 "is_initiator:{}",
1572 bd_addr, security_required, is_originator);
1573
1574 tBTM_STATUS rc = BTM_SUCCESS;
1575 bool chk_acp_auth_done = false;
1576 /* should check PSM range in LE connection oriented L2CAP connection */
1577 constexpr tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
1578
1579 /* Find or get oldest record */
1580 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(bd_addr);
1581
1582 p_dev_rec->hci_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_BR_EDR);
1583
1584 if ((!is_originator) && (security_required & BTM_SEC_MODE4_LEVEL4)) {
1585 bool local_supports_sc =
1586 bluetooth::shim::GetController()->SupportsSecureConnections();
1587 /* acceptor receives L2CAP Channel Connect Request for Secure Connections
1588 * Only service */
1589 if (!local_supports_sc || !p_dev_rec->SupportsSecureConnections()) {
1590 log::warn(
1591 "Policy requires mode 4 level 4, but local_support_for_sc={}, "
1592 "rmt_support_for_sc={}, failing connection",
1593 local_supports_sc, p_dev_rec->SupportsSecureConnections());
1594 if (p_callback) {
1595 (*p_callback)(bd_addr, transport, (void*)p_ref_data,
1596 BTM_MODE4_LEVEL4_NOT_SUPPORTED);
1597 }
1598
1599 return (BTM_MODE4_LEVEL4_NOT_SUPPORTED);
1600 }
1601 }
1602
1603 /* there are some devices (moto KRZR) which connects to several services at
1604 * the same time */
1605 /* we will process one after another */
1606 if ((p_dev_rec->sec_rec.p_callback) ||
1607 (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE)) {
1608 log::debug("security_flags:x{:x}, sec_flags:x{:x}", security_required,
1609 p_dev_rec->sec_rec.sec_flags);
1610 rc = BTM_CMD_STARTED;
1611 if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SERVICE) ||
1612 (BTM_SM4_KNOWN == p_dev_rec->sm4) ||
1613 (BTM_SEC_IS_SM4(p_dev_rec->sm4) &&
1614 (!btm_sec_is_upgrade_possible(p_dev_rec, is_originator)))) {
1615 /* legacy mode - local is legacy or local is lisbon/peer is legacy
1616 * or SM4 with no possibility of link key upgrade */
1617 if (is_originator) {
1618 if (((security_required & BTM_SEC_OUT_FLAGS) == 0) ||
1619 ((((security_required & BTM_SEC_OUT_FLAGS) ==
1620 BTM_SEC_OUT_AUTHENTICATE) &&
1621 btm_dev_authenticated(p_dev_rec))) ||
1622 ((((security_required & BTM_SEC_OUT_FLAGS) ==
1623 (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) &&
1624 btm_dev_encrypted(p_dev_rec)))) {
1625 rc = BTM_SUCCESS;
1626 }
1627 } else {
1628 if (((security_required & BTM_SEC_IN_FLAGS) == 0) ||
1629 (((security_required & BTM_SEC_IN_FLAGS) ==
1630 BTM_SEC_IN_AUTHENTICATE) &&
1631 btm_dev_authenticated(p_dev_rec)) ||
1632 (((security_required & BTM_SEC_IN_FLAGS) ==
1633 (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) &&
1634 btm_dev_encrypted(p_dev_rec))) {
1635 // Check for 16 digits (or MITM)
1636 if (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == 0) ||
1637 (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) ==
1638 BTM_SEC_IN_MIN_16_DIGIT_PIN) &&
1639 btm_dev_16_digit_authenticated(p_dev_rec))) {
1640 rc = BTM_SUCCESS;
1641 }
1642 }
1643 }
1644
1645 if ((rc == BTM_SUCCESS) && (security_required & BTM_SEC_MODE4_LEVEL4) &&
1646 (p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
1647 rc = BTM_CMD_STARTED;
1648 }
1649
1650 if (rc == BTM_SUCCESS) {
1651 if (access_secure_service_from_temp_bond(p_dev_rec, is_originator, security_required)) {
1652 log::error(
1653 "Trying to access a secure service from a temp bonding, "
1654 "rejecting");
1655 rc = BTM_FAILED_ON_SECURITY;
1656 }
1657
1658 if (p_callback)
1659 (*p_callback)(bd_addr, transport, (void*)p_ref_data, rc);
1660 return rc;
1661 }
1662 }
1663
1664 btm_sec_cb.sec_req_pending = true;
1665 return (BTM_CMD_STARTED);
1666 }
1667
1668 /* Save the security requirements in case a pairing is needed */
1669 p_dev_rec->sec_rec.required_security_flags_for_pairing = security_required;
1670
1671 /* Modify security_required in btm_sec_l2cap_access_req for Lisbon */
1672 if (btm_sec_cb.security_mode == BTM_SEC_MODE_SP ||
1673 btm_sec_cb.security_mode == BTM_SEC_MODE_SC) {
1674 if (BTM_SEC_IS_SM4(p_dev_rec->sm4)) {
1675 if (is_originator) {
1676 /* SM4 to SM4 -> always encrypt */
1677 security_required |= BTM_SEC_OUT_ENCRYPT;
1678 } else /* acceptor */
1679 {
1680 /* SM4 to SM4: the acceptor needs to make sure the authentication is
1681 * already done */
1682 chk_acp_auth_done = true;
1683 /* SM4 to SM4 -> always encrypt */
1684 security_required |= BTM_SEC_IN_ENCRYPT;
1685 }
1686 } else if (!(BTM_SM4_KNOWN & p_dev_rec->sm4)) {
1687 /* the remote features are not known yet */
1688 log::debug(
1689 "Remote features have not yet been received sec_flags:0x{:02x} {}",
1690 p_dev_rec->sec_rec.sec_flags,
1691 (is_originator) ? "initiator" : "acceptor");
1692
1693 p_dev_rec->sm4 |= BTM_SM4_REQ_PEND;
1694 return (BTM_CMD_STARTED);
1695 }
1696 }
1697
1698 log::verbose("sm4:0x{:x}, sec_flags:0x{:x}, security_required:0x{:x} chk:{}",
1699 p_dev_rec->sm4, p_dev_rec->sec_rec.sec_flags, security_required,
1700 chk_acp_auth_done);
1701
1702 p_dev_rec->sec_rec.security_required = security_required;
1703 p_dev_rec->sec_rec.p_ref_data = p_ref_data;
1704 p_dev_rec->is_originator = is_originator;
1705
1706 if (chk_acp_auth_done) {
1707 log::verbose(
1708 "(SM4 to SM4) btm_sec_l2cap_access_req rspd. authenticated: x{:x}, "
1709 "enc: x{:x}",
1710 p_dev_rec->sec_rec.sec_flags & BTM_SEC_AUTHENTICATED,
1711 p_dev_rec->sec_rec.sec_flags & BTM_SEC_ENCRYPTED);
1712 /* SM4, but we do not know for sure which level of security we need.
1713 * as long as we have a link key, it's OK */
1714 if ((0 == (p_dev_rec->sec_rec.sec_flags & BTM_SEC_AUTHENTICATED)) ||
1715 (0 == (p_dev_rec->sec_rec.sec_flags & BTM_SEC_ENCRYPTED))) {
1716 rc = BTM_DELAY_CHECK;
1717 /*
1718 2046 may report HCI_Encryption_Change and L2C Connection Request out of
1719 sequence
1720 because of data path issues. Delay this disconnect a little bit
1721 */
1722 log::info(
1723 "peer should have initiated security process by now (SM4 to SM4)");
1724 p_dev_rec->sec_rec.p_callback = p_callback;
1725 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_DELAY_FOR_ENC;
1726 (*p_callback)(bd_addr, transport, p_ref_data, rc);
1727
1728 return BTM_SUCCESS;
1729 }
1730 }
1731
1732 p_dev_rec->sec_rec.p_callback = p_callback;
1733
1734 if (BTM_SEC_IS_SM4(p_dev_rec->sm4)) {
1735 if ((p_dev_rec->sec_rec.security_required & BTM_SEC_MODE4_LEVEL4) &&
1736 (p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
1737 /* BTM_LKEY_TYPE_AUTH_COMB_P_256 is the only acceptable key in this case
1738 */
1739 if ((p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN) != 0) {
1740 p_dev_rec->sm4 |= BTM_SM4_UPGRADE;
1741 }
1742 p_dev_rec->sec_rec.sec_flags &=
1743 ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED |
1744 BTM_SEC_AUTHENTICATED);
1745 log::verbose("sec_flags:0x{:x}", p_dev_rec->sec_rec.sec_flags);
1746 } else {
1747 /* If we already have a link key to the connected peer, is it secure
1748 * enough? */
1749 btm_sec_check_upgrade(p_dev_rec, is_originator);
1750 }
1751 }
1752
1753 rc = btm_sec_execute_procedure(p_dev_rec);
1754 if (rc != BTM_CMD_STARTED) {
1755 log::verbose("p_dev_rec={}, clearing callback. old p_callback={}",
1756 fmt::ptr(p_dev_rec), fmt::ptr(p_dev_rec->sec_rec.p_callback));
1757 p_dev_rec->sec_rec.p_callback = NULL;
1758 (*p_callback)(bd_addr, transport, p_dev_rec->sec_rec.p_ref_data, rc);
1759 }
1760
1761 return (rc);
1762 }
1763
1764 /*******************************************************************************
1765 *
1766 * Function btm_sec_l2cap_access_req
1767 *
1768 * Description This function is called by the L2CAP to grant permission to
1769 * establish L2CAP connection to or from the peer device.
1770 *
1771 * Parameters: bd_addr - Address of the peer device
1772 * psm - L2CAP PSM
1773 * is_originator - true if protocol above L2CAP originates
1774 * connection
1775 * p_callback - Pointer to callback function called if
1776 * this function returns PENDING after required
1777 * procedures are complete. MUST NOT BE NULL.
1778 *
1779 * Returns tBTM_STATUS
1780 *
1781 ******************************************************************************/
btm_sec_l2cap_access_req(const RawAddress & bd_addr,uint16_t psm,bool is_originator,tBTM_SEC_CALLBACK * p_callback,void * p_ref_data)1782 tBTM_STATUS btm_sec_l2cap_access_req(const RawAddress& bd_addr, uint16_t psm,
1783 bool is_originator,
1784 tBTM_SEC_CALLBACK* p_callback,
1785 void* p_ref_data) {
1786 // should check PSM range in LE connection oriented L2CAP connection
1787 constexpr tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
1788
1789 log::debug("is_originator:{}, psm=0x{:04x}", is_originator, psm);
1790
1791 // Find the service record for the PSM
1792 tBTM_SEC_SERV_REC* p_serv_rec =
1793 btm_sec_cb.find_first_serv_rec(is_originator, psm);
1794
1795 // If there is no application registered with this PSM do not allow connection
1796 if (!p_serv_rec) {
1797 log::warn("PSM: 0x{:04x} no application registered", psm);
1798 (*p_callback)(bd_addr, transport, p_ref_data, BTM_MODE_UNSUPPORTED);
1799 return (BTM_MODE_UNSUPPORTED);
1800 }
1801
1802 /* Services level0 by default have no security */
1803 if (psm == BT_PSM_SDP) {
1804 log::debug("No security required for SDP");
1805 (*p_callback)(bd_addr, transport, p_ref_data, BTM_SUCCESS_NO_SECURITY);
1806 return (BTM_SUCCESS);
1807 }
1808
1809 uint16_t security_required;
1810 if (btm_sec_cb.security_mode == BTM_SEC_MODE_SC) {
1811 security_required = btm_sec_set_serv_level4_flags(
1812 p_serv_rec->security_flags, is_originator);
1813 } else {
1814 security_required = p_serv_rec->security_flags;
1815 }
1816
1817 return btm_sec_l2cap_access_req_by_requirement(
1818 bd_addr, security_required, is_originator, p_callback, p_ref_data);
1819 }
1820
1821 /*******************************************************************************
1822 *
1823 * Function btm_sec_mx_access_request
1824 *
1825 * Description This function is called by all Multiplexing Protocols during
1826 * establishing connection to or from peer device to grant
1827 * permission to establish application connection.
1828 *
1829 * Parameters: bd_addr - Address of the peer device
1830 * psm - L2CAP PSM
1831 * is_originator - true if protocol above L2CAP originates
1832 * connection
1833 * mx_proto_id - protocol ID of the multiplexer
1834 * mx_chan_id - multiplexer channel to reach application
1835 * p_callback - Pointer to callback function called if
1836 * this function returns PENDING after required
1837 * procedures are completed
1838 * p_ref_data - Pointer to any reference data needed by the
1839 * the callback function.
1840 *
1841 * Returns BTM_CMD_STARTED
1842 *
1843 ******************************************************************************/
btm_sec_mx_access_request(const RawAddress & bd_addr,bool is_originator,uint16_t security_required,tBTM_SEC_CALLBACK * p_callback,void * p_ref_data)1844 tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr,
1845 bool is_originator,
1846 uint16_t security_required,
1847 tBTM_SEC_CALLBACK* p_callback,
1848 void* p_ref_data) {
1849 tBTM_SEC_DEV_REC* p_dev_rec;
1850 tBTM_STATUS rc;
1851 bool transport = false; /* should check PSM range in LE connection oriented
1852 L2CAP connection */
1853 log::debug("Multiplex access request device:{}", bd_addr);
1854
1855 /* Find or get oldest record */
1856 p_dev_rec = btm_find_or_alloc_dev(bd_addr);
1857
1858 /* there are some devices (moto phone) which connects to several services at
1859 * the same time */
1860 /* we will process one after another */
1861 if ((p_dev_rec->sec_rec.p_callback) ||
1862 (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE)) {
1863 log::debug("Pairing in progress pairing_state:{}",
1864 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
1865
1866 rc = BTM_CMD_STARTED;
1867
1868 if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SERVICE) ||
1869 (BTM_SM4_KNOWN == p_dev_rec->sm4) ||
1870 (BTM_SEC_IS_SM4(p_dev_rec->sm4) &&
1871 (!btm_sec_is_upgrade_possible(p_dev_rec, is_originator)))) {
1872 /* legacy mode - local is legacy or local is lisbon/peer is legacy
1873 * or SM4 with no possibility of link key upgrade */
1874 if (is_originator) {
1875 if (((security_required & BTM_SEC_OUT_FLAGS) == 0) ||
1876 ((((security_required & BTM_SEC_OUT_FLAGS) ==
1877 BTM_SEC_OUT_AUTHENTICATE) &&
1878 btm_dev_authenticated(p_dev_rec))) ||
1879 ((((security_required & BTM_SEC_OUT_FLAGS) ==
1880 (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) &&
1881 btm_dev_encrypted(p_dev_rec)))) {
1882 rc = BTM_SUCCESS;
1883 }
1884 } else {
1885 if (((security_required & BTM_SEC_IN_FLAGS) == 0) ||
1886 ((((security_required & BTM_SEC_IN_FLAGS) ==
1887 BTM_SEC_IN_AUTHENTICATE) &&
1888 btm_dev_authenticated(p_dev_rec))) ||
1889 ((((security_required & BTM_SEC_IN_FLAGS) ==
1890 (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) &&
1891 btm_dev_encrypted(p_dev_rec)))) {
1892 // Check for 16 digits (or MITM)
1893 if (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == 0) ||
1894 (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) ==
1895 BTM_SEC_IN_MIN_16_DIGIT_PIN) &&
1896 btm_dev_16_digit_authenticated(p_dev_rec))) {
1897 rc = BTM_SUCCESS;
1898 }
1899 }
1900 }
1901 if ((rc == BTM_SUCCESS) && (security_required & BTM_SEC_MODE4_LEVEL4) &&
1902 (p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
1903 rc = BTM_CMD_STARTED;
1904 }
1905 }
1906
1907 /* the new security request */
1908 if (p_dev_rec->sec_rec.sec_state != BTM_SEC_STATE_IDLE) {
1909 log::debug("A pending security procedure in progress");
1910 rc = BTM_CMD_STARTED;
1911 }
1912 if (rc == BTM_CMD_STARTED) {
1913 btm_sec_queue_mx_request(bd_addr, BT_PSM_RFCOMM, is_originator,
1914 security_required, p_callback, p_ref_data);
1915 } else /* rc == BTM_SUCCESS */
1916 {
1917 if (access_secure_service_from_temp_bond(p_dev_rec,
1918 is_originator, security_required)) {
1919 log::error(
1920 "Trying to access a secure rfcomm service from a temp bonding, "
1921 "rejecting");
1922 rc = BTM_FAILED_ON_SECURITY;
1923 }
1924 if (p_callback) {
1925 log::debug("Notifying client that security access has been granted");
1926 (*p_callback)(bd_addr, transport, p_ref_data, rc);
1927 }
1928 }
1929 return rc;
1930 }
1931
1932 if ((!is_originator) && ((security_required & BTM_SEC_MODE4_LEVEL4) ||
1933 (btm_sec_cb.security_mode == BTM_SEC_MODE_SC))) {
1934 bool local_supports_sc =
1935 bluetooth::shim::GetController()->SupportsSecureConnections();
1936 /* acceptor receives service connection establishment Request for */
1937 /* Secure Connections Only service */
1938 if (!(local_supports_sc) || !(p_dev_rec->SupportsSecureConnections())) {
1939 log::debug(
1940 "Secure Connection only mode unsupported local_SC_support:{} "
1941 "remote_SC_support:{}",
1942 local_supports_sc, p_dev_rec->SupportsSecureConnections());
1943 if (p_callback)
1944 (*p_callback)(bd_addr, transport, (void*)p_ref_data,
1945 BTM_MODE4_LEVEL4_NOT_SUPPORTED);
1946
1947 return (BTM_MODE4_LEVEL4_NOT_SUPPORTED);
1948 }
1949 }
1950
1951 if (security_required & BTM_SEC_OUT_AUTHENTICATE) {
1952 security_required |= BTM_SEC_OUT_MITM;
1953 }
1954 if (security_required & BTM_SEC_IN_AUTHENTICATE) {
1955 security_required |= BTM_SEC_IN_MITM;
1956 }
1957
1958 p_dev_rec->sec_rec.required_security_flags_for_pairing = security_required;
1959 p_dev_rec->sec_rec.security_required = security_required;
1960
1961 if (btm_sec_cb.security_mode == BTM_SEC_MODE_SP ||
1962 btm_sec_cb.security_mode == BTM_SEC_MODE_SC) {
1963 if (BTM_SEC_IS_SM4(p_dev_rec->sm4)) {
1964 if ((p_dev_rec->sec_rec.security_required & BTM_SEC_MODE4_LEVEL4) &&
1965 (p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
1966 /* BTM_LKEY_TYPE_AUTH_COMB_P_256 is the only acceptable key in this case
1967 */
1968 if ((p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN) != 0) {
1969 p_dev_rec->sm4 |= BTM_SM4_UPGRADE;
1970 }
1971
1972 p_dev_rec->sec_rec.sec_flags &=
1973 ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED |
1974 BTM_SEC_AUTHENTICATED);
1975 log::verbose("sec_flags:0x{:x}", p_dev_rec->sec_rec.sec_flags);
1976 } else {
1977 log::debug("Already have link key; checking if link key is sufficient");
1978 btm_sec_check_upgrade(p_dev_rec, is_originator);
1979 }
1980 }
1981 }
1982
1983 p_dev_rec->is_originator = is_originator;
1984 p_dev_rec->sec_rec.p_callback = p_callback;
1985 p_dev_rec->sec_rec.p_ref_data = p_ref_data;
1986
1987 rc = btm_sec_execute_procedure(p_dev_rec);
1988 log::debug("Started security procedure peer:{} btm_status:{}",
1989 p_dev_rec->RemoteAddress(), btm_status_text(rc));
1990 if (rc != BTM_CMD_STARTED) {
1991 if (p_callback) {
1992 p_dev_rec->sec_rec.p_callback = NULL;
1993 (*p_callback)(bd_addr, transport, p_ref_data, rc);
1994 }
1995 }
1996
1997 return rc;
1998 }
1999
2000 /*******************************************************************************
2001 *
2002 * Function btm_sec_conn_req
2003 *
2004 * Description This function is when the peer device is requesting
2005 * connection
2006 *
2007 * Returns void
2008 *
2009 ******************************************************************************/
btm_sec_conn_req(const RawAddress & bda,const DEV_CLASS dc)2010 void btm_sec_conn_req(const RawAddress& bda, const DEV_CLASS dc) {
2011 tBTM_SEC_DEV_REC* p_dev_rec = nullptr;
2012
2013 if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
2014 (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
2015 (btm_sec_cb.pairing_bda == bda)) {
2016 log::verbose(
2017 "Security Manager: reject connect request from bonding device");
2018
2019 /* incoming connection from bonding device is rejected */
2020 btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_REJECTED_CONNECT;
2021 btsnd_hcic_reject_conn(bda, HCI_ERR_HOST_REJECT_DEVICE);
2022 return;
2023 }
2024
2025 /* Host is not interested or approved connection. Save BDA and DC and */
2026 /* pass request to L2CAP */
2027 btm_sec_cb.connecting_bda = bda;
2028 btm_sec_cb.connecting_dc = dc;
2029
2030 p_dev_rec = btm_find_or_alloc_dev(bda);
2031 p_dev_rec->sm4 |= BTM_SM4_CONN_PEND;
2032 }
2033
2034 /*******************************************************************************
2035 *
2036 * Function btm_sec_bond_cancel_complete
2037 *
2038 * Description This function is called to report bond cancel complete
2039 * event.
2040 *
2041 * Returns void
2042 *
2043 ******************************************************************************/
btm_sec_bond_cancel_complete(void)2044 static void btm_sec_bond_cancel_complete(void) {
2045 tBTM_SEC_DEV_REC* p_dev_rec;
2046
2047 if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE) ||
2048 (BTM_PAIR_STATE_WAIT_LOCAL_PIN == btm_sec_cb.pairing_state &&
2049 BTM_PAIR_FLAGS_WE_STARTED_DD & btm_sec_cb.pairing_flags) ||
2050 (btm_sec_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME &&
2051 BTM_PAIR_FLAGS_WE_CANCEL_DD & btm_sec_cb.pairing_flags)) {
2052 /* for dedicated bonding in legacy mode, authentication happens at "link
2053 * level"
2054 * btm_sec_connected is called with failed status.
2055 * In theory, the code that handles is_pairing_device/true should clean out
2056 * security related code.
2057 * However, this function may clean out the security related flags and
2058 * btm_sec_connected would not know
2059 * this function also needs to do proper clean up.
2060 */
2061 p_dev_rec = btm_find_dev(btm_sec_cb.pairing_bda);
2062 if (p_dev_rec != NULL) p_dev_rec->sec_rec.security_required = BTM_SEC_NONE;
2063 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
2064
2065 /* Notify application that the cancel succeeded */
2066 if (btm_sec_cb.api.p_bond_cancel_cmpl_callback)
2067 btm_sec_cb.api.p_bond_cancel_cmpl_callback(BTM_SUCCESS);
2068 }
2069 }
2070
2071 /*******************************************************************************
2072 *
2073 * Function btm_create_conn_cancel_complete
2074 *
2075 * Description This function is called when the command complete message
2076 * is received from the HCI for the create connection cancel
2077 * command.
2078 *
2079 * Returns void
2080 *
2081 ******************************************************************************/
btm_create_conn_cancel_complete(uint8_t status,const RawAddress bd_addr)2082 void btm_create_conn_cancel_complete(uint8_t status, const RawAddress bd_addr) {
2083 log::verbose("btm_create_conn_cancel_complete(): in State: {} status:{}",
2084 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
2085 status);
2086 log_link_layer_connection_event(
2087 &bd_addr, bluetooth::common::kUnknownConnectionHandle,
2088 android::bluetooth::DIRECTION_OUTGOING, android::bluetooth::LINK_TYPE_ACL,
2089 android::bluetooth::hci::CMD_CREATE_CONNECTION_CANCEL,
2090 android::bluetooth::hci::EVT_COMMAND_COMPLETE,
2091 android::bluetooth::hci::BLE_EVT_UNKNOWN, status,
2092 android::bluetooth::hci::STATUS_UNKNOWN);
2093
2094 /* if the create conn cancel cmd was issued by the bond cancel,
2095 ** the application needs to be notified that bond cancel succeeded
2096 */
2097 switch (status) {
2098 case HCI_SUCCESS:
2099 btm_sec_bond_cancel_complete();
2100 break;
2101 case HCI_ERR_CONNECTION_EXISTS:
2102 case HCI_ERR_NO_CONNECTION:
2103 default:
2104 /* Notify application of the error */
2105 if (btm_sec_cb.api.p_bond_cancel_cmpl_callback)
2106 btm_sec_cb.api.p_bond_cancel_cmpl_callback(BTM_ERR_PROCESSING);
2107 break;
2108 }
2109 }
2110
2111 /*******************************************************************************
2112 *
2113 * Function btm_sec_check_pending_reqs
2114 *
2115 * Description This function is called at the end of the security procedure
2116 * to let L2CAP and RFCOMM know to re-submit any pending
2117 * requests
2118 *
2119 * Returns void
2120 *
2121 ******************************************************************************/
btm_sec_check_pending_reqs(void)2122 void btm_sec_check_pending_reqs(void) {
2123 if (btm_sec_cb.pairing_state == BTM_PAIR_STATE_IDLE) {
2124 /* First, resubmit L2CAP requests */
2125 if (btm_sec_cb.sec_req_pending) {
2126 btm_sec_cb.sec_req_pending = false;
2127 l2cu_resubmit_pending_sec_req(nullptr);
2128 }
2129
2130 /* Now, re-submit anything in the mux queue */
2131 fixed_queue_t* bq = btm_sec_cb.sec_pending_q;
2132
2133 btm_sec_cb.sec_pending_q = fixed_queue_new(SIZE_MAX);
2134
2135 tBTM_SEC_QUEUE_ENTRY* p_e;
2136 while ((p_e = (tBTM_SEC_QUEUE_ENTRY*)fixed_queue_try_dequeue(bq)) != NULL) {
2137 /* Check that the ACL is still up before starting security procedures */
2138 if (BTM_IsAclConnectionUp(p_e->bd_addr, p_e->transport)) {
2139 if (p_e->psm != 0) {
2140 log::verbose("PSM:0x{:04x} Is_Orig:{}", p_e->psm, p_e->is_orig);
2141
2142 btm_sec_mx_access_request(p_e->bd_addr, p_e->is_orig,
2143 p_e->rfcomm_security_requirement,
2144 p_e->p_callback, p_e->p_ref_data);
2145 } else {
2146 BTM_SetEncryption(p_e->bd_addr, p_e->transport, p_e->p_callback,
2147 p_e->p_ref_data, p_e->sec_act);
2148 }
2149 }
2150
2151 osi_free(p_e);
2152 }
2153 fixed_queue_free(bq, NULL);
2154 }
2155 }
2156
2157 /*******************************************************************************
2158 *
2159 * Function btm_sec_dev_reset
2160 *
2161 * Description This function should be called after device reset
2162 *
2163 * Returns void
2164 *
2165 ******************************************************************************/
btm_sec_dev_reset(void)2166 void btm_sec_dev_reset(void) {
2167 log::assert_that(bluetooth::shim::GetController()->SupportsSimplePairing(),
2168 "only controllers with SSP is supported");
2169
2170 /* set the default IO capabilities */
2171 btm_sec_cb.devcb.loc_io_caps = BTM_IO_CAP_IO;
2172 /* add mx service to use no security */
2173 BTM_SetSecurityLevel(false, "RFC_MUX", BTM_SEC_SERVICE_RFC_MUX,
2174 BTM_SEC_NONE, BT_PSM_RFCOMM, BTM_SEC_PROTO_RFCOMM, 0);
2175 BTM_SetSecurityLevel(true, "RFC_MUX", BTM_SEC_SERVICE_RFC_MUX, BTM_SEC_NONE,
2176 BT_PSM_RFCOMM, BTM_SEC_PROTO_RFCOMM, 0);
2177 log::verbose("btm_sec_dev_reset sec mode: {}", btm_sec_cb.security_mode);
2178 }
2179
2180 /*******************************************************************************
2181 *
2182 * Function btm_sec_abort_access_req
2183 *
2184 * Description This function is called by the L2CAP or RFCOMM to abort
2185 * the pending operation.
2186 *
2187 * Parameters: bd_addr - Address of the peer device
2188 *
2189 * Returns void
2190 *
2191 ******************************************************************************/
btm_sec_abort_access_req(const RawAddress & bd_addr)2192 void btm_sec_abort_access_req(const RawAddress& bd_addr) {
2193 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
2194
2195 if (!p_dev_rec) return;
2196
2197 if ((p_dev_rec->sec_rec.sec_state != BTM_SEC_STATE_AUTHORIZING) &&
2198 (p_dev_rec->sec_rec.sec_state != BTM_SEC_STATE_AUTHENTICATING))
2199 return;
2200
2201 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_IDLE;
2202
2203 log::verbose("clearing callback. p_dev_rec={}, p_callback={}",
2204 fmt::ptr(p_dev_rec), fmt::ptr(p_dev_rec->sec_rec.p_callback));
2205 p_dev_rec->sec_rec.p_callback = NULL;
2206 }
2207
2208 /*******************************************************************************
2209 *
2210 * Function btm_sec_dd_create_conn
2211 *
2212 * Description This function is called to create an ACL connection for
2213 * the dedicated bonding process
2214 *
2215 * Returns BTM_SUCCESS if an ACL connection is already up
2216 * BTM_CMD_STARTED if the ACL connection has been requested
2217 * BTM_NO_RESOURCES if failed to start the ACL connection
2218 *
2219 ******************************************************************************/
btm_sec_dd_create_conn(tBTM_SEC_DEV_REC * p_dev_rec)2220 static tBTM_STATUS btm_sec_dd_create_conn(tBTM_SEC_DEV_REC* p_dev_rec) {
2221 tBTM_STATUS status = l2cu_ConnectAclForSecurity(p_dev_rec->bd_addr);
2222 if (status == BTM_CMD_STARTED) {
2223 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
2224 /* If already connected, start pending security procedure */
2225 if (BTM_IsAclConnectionUp(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR)) {
2226 return BTM_SUCCESS;
2227 }
2228 return BTM_CMD_STARTED;
2229 } else if (status == BTM_NO_RESOURCES) {
2230 return BTM_NO_RESOURCES;
2231 }
2232
2233 /* set up the control block to indicated dedicated bonding */
2234 btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_DISC_WHEN_DONE;
2235
2236 log::info("Security Manager: {}", p_dev_rec->bd_addr);
2237
2238 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
2239
2240 return (BTM_CMD_STARTED);
2241 }
2242
call_registered_rmt_name_callbacks(const RawAddress * p_bd_addr,const DEV_CLASS & dev_class,uint8_t * p_bd_name,tHCI_STATUS status)2243 static void call_registered_rmt_name_callbacks(const RawAddress* p_bd_addr,
2244 const DEV_CLASS& dev_class,
2245 uint8_t* p_bd_name,
2246 tHCI_STATUS status) {
2247 int i;
2248
2249 if (p_bd_addr == nullptr) {
2250 // TODO Still need to send status back to get SDP state machine
2251 // running
2252 log::error("Unable to issue callback with unknown address status:{}",
2253 hci_status_code_text(status));
2254 return;
2255 }
2256
2257 if (p_bd_name == nullptr) {
2258 p_bd_name = (uint8_t*)kBtmBdNameEmpty;
2259 }
2260
2261 /* Notify all clients waiting for name to be resolved even if not found so
2262 * clients can continue */
2263 for (i = 0; i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) {
2264 if (btm_cb.p_rmt_name_callback[i]) {
2265 (*btm_cb.p_rmt_name_callback[i])(*p_bd_addr, dev_class, p_bd_name);
2266 }
2267 }
2268 }
2269
2270 /*******************************************************************************
2271 *
2272 * Function btm_sec_rmt_name_request_complete
2273 *
2274 * Description This function is called when remote name was obtained from
2275 * the peer device
2276 *
2277 * Returns void
2278 *
2279 ******************************************************************************/
btm_sec_rmt_name_request_complete(const RawAddress * p_bd_addr,const uint8_t * p_bd_name,tHCI_STATUS status)2280 void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr,
2281 const uint8_t* p_bd_name,
2282 tHCI_STATUS status) {
2283 tBTM_SEC_DEV_REC* p_dev_rec = nullptr;
2284 uint8_t old_sec_state;
2285
2286 log::info("btm_sec_rmt_name_request_complete for {}",
2287 p_bd_addr ? ADDRESS_TO_LOGGABLE_CSTR(*p_bd_addr) : "null");
2288
2289 if ((!p_bd_addr && !BTM_IsAclConnectionUp(btm_sec_cb.connecting_bda,
2290 BT_TRANSPORT_BR_EDR)) ||
2291 (p_bd_addr && !BTM_IsAclConnectionUp(*p_bd_addr, BT_TRANSPORT_BR_EDR))) {
2292 log::warn(
2293 "Remote read request complete with no underlying link connection");
2294 }
2295
2296 /* If remote name request failed, p_bd_addr is null and we need to search */
2297 /* based on state assuming that we are doing 1 at a time */
2298 if (p_bd_addr)
2299 p_dev_rec = btm_find_dev(*p_bd_addr);
2300 else {
2301 log::info(
2302 "Remote read request complete with no address so searching device "
2303 "database");
2304 p_dev_rec = btm_sec_find_dev_by_sec_state(BTM_SEC_STATE_GETTING_NAME);
2305 if (p_dev_rec) {
2306 p_bd_addr = &p_dev_rec->bd_addr;
2307 }
2308 }
2309
2310 if (!p_bd_name) p_bd_name = (const uint8_t*)kBtmBdNameEmpty;
2311
2312 BTM_LogHistory(kBtmLogTag, (p_bd_addr) ? *p_bd_addr : RawAddress::kEmpty,
2313 "RNR complete",
2314 base::StringPrintf("status:%s name:%s",
2315 hci_error_code_text(status).c_str(),
2316 PRIVATE_NAME(p_bd_name)));
2317
2318 if (p_dev_rec == nullptr) {
2319 log::debug(
2320 "Remote read request complete for unknown device pairing_state:{} "
2321 "status:{} name:{}",
2322 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
2323 hci_status_code_text(status), reinterpret_cast<char const*>(p_bd_name));
2324
2325 call_registered_rmt_name_callbacks(p_bd_addr, kDevClassEmpty, nullptr,
2326 status);
2327 return;
2328 }
2329
2330 old_sec_state = p_dev_rec->sec_rec.sec_state;
2331 if (status == HCI_SUCCESS) {
2332 log::debug(
2333 "Remote read request complete for known device pairing_state:{} "
2334 "name:{} sec_state:{}",
2335 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
2336 reinterpret_cast<char const*>(p_bd_name),
2337 security_state_text(p_dev_rec->sec_rec.sec_state));
2338
2339 bd_name_copy(p_dev_rec->sec_bd_name, p_bd_name);
2340 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_NAME_KNOWN;
2341 log::verbose("setting BTM_SEC_NAME_KNOWN sec_flags:0x{:x}",
2342 p_dev_rec->sec_rec.sec_flags);
2343 } else {
2344 log::warn(
2345 "Remote read request failed for known device pairing_state:{} "
2346 "status:{} name:{} sec_state:{}",
2347 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
2348 hci_status_code_text(status), reinterpret_cast<char const*>(p_bd_name),
2349 security_state_text(p_dev_rec->sec_rec.sec_state));
2350
2351 /* Notify all clients waiting for name to be resolved even if it failed so
2352 * clients can continue */
2353 p_dev_rec->sec_bd_name[0] = 0;
2354 }
2355
2356 if (p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_GETTING_NAME)
2357 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_IDLE;
2358
2359 /* Notify all clients waiting for name to be resolved */
2360 call_registered_rmt_name_callbacks(p_bd_addr, p_dev_rec->dev_class,
2361 p_dev_rec->sec_bd_name, status);
2362
2363 /* If we were delaying asking UI for a PIN because name was not resolved,
2364 * ask now */
2365 if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_WAIT_LOCAL_PIN) &&
2366 p_bd_addr && (btm_sec_cb.pairing_bda == *p_bd_addr)) {
2367 log::verbose(
2368 "delayed pin now being requested flags:0x{:x}, (p_pin_callback=0x{})",
2369 btm_sec_cb.pairing_flags, fmt::ptr(btm_sec_cb.api.p_pin_callback));
2370
2371 if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0 &&
2372 btm_sec_cb.api.p_pin_callback) {
2373 log::verbose("calling pin_callback");
2374 btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
2375 (*btm_sec_cb.api.p_pin_callback)(
2376 p_dev_rec->bd_addr, p_dev_rec->dev_class, p_bd_name,
2377 (p_dev_rec->sec_rec.required_security_flags_for_pairing &
2378 BTM_SEC_IN_MIN_16_DIGIT_PIN));
2379 }
2380
2381 /* Set the same state again to force the timer to be restarted */
2382 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_PIN);
2383 return;
2384 }
2385
2386 /* Check if we were delaying bonding because name was not resolved */
2387 if (btm_sec_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME) {
2388 if (p_bd_addr && btm_sec_cb.pairing_bda == *p_bd_addr) {
2389 log::verbose("continue bonding sm4: 0x{:04x}, status:0x{:x}",
2390 p_dev_rec->sm4, status);
2391 if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_CANCEL_DD) {
2392 btm_sec_bond_cancel_complete();
2393 return;
2394 }
2395
2396 if (status != HCI_SUCCESS) {
2397 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
2398
2399 return NotifyBondingChange(*p_dev_rec, status);
2400 }
2401
2402 /* if peer is very old legacy devices, HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT is
2403 * not reported */
2404 if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) {
2405 /* set the KNOWN flag only if BTM_PAIR_FLAGS_REJECTED_CONNECT is not
2406 * set.*/
2407 /* If it is set, there may be a race condition */
2408 log::verbose("IS_SM4_UNKNOWN Flags:0x{:04x}", btm_sec_cb.pairing_flags);
2409 if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) == 0)
2410 p_dev_rec->sm4 |= BTM_SM4_KNOWN;
2411 }
2412
2413 log::verbose("SM4 Value: {:x}, Legacy:{},IS SM4:{}, Unknown:{}",
2414 p_dev_rec->sm4, BTM_SEC_IS_SM4_LEGACY(p_dev_rec->sm4),
2415 BTM_SEC_IS_SM4(p_dev_rec->sm4),
2416 BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4));
2417
2418 bool await_connection = true;
2419 /* BT 2.1 or carkit, bring up the connection to force the peer to request
2420 *PIN.
2421 ** Else prefetch (btm_sec_check_prefetch_pin will do the prefetching if
2422 *needed)
2423 */
2424 if ((p_dev_rec->sm4 != BTM_SM4_KNOWN) ||
2425 !btm_sec_check_prefetch_pin(p_dev_rec)) {
2426 /* if we rejected incoming connection request, we have to wait
2427 * HCI_Connection_Complete event */
2428 /* before originating */
2429 if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) {
2430 log::warn(
2431 "waiting HCI_Connection_Complete after rejecting connection");
2432 }
2433 /* Both we and the peer are 2.1 - continue to create connection */
2434 else {
2435 tBTM_STATUS req_status = btm_sec_dd_create_conn(p_dev_rec);
2436 if (req_status == BTM_SUCCESS) {
2437 await_connection = false;
2438 } else if (req_status != BTM_CMD_STARTED) {
2439 log::warn("failed to start connection");
2440
2441 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
2442
2443 NotifyBondingChange(*p_dev_rec, HCI_ERR_MEMORY_FULL);
2444 }
2445 }
2446 }
2447
2448 if (await_connection) {
2449 log::debug("Wait for connection to begin pairing");
2450 return;
2451 }
2452 } else {
2453 log::warn("wrong BDA, retry with pairing BDA");
2454 if (BTM_ReadRemoteDeviceName(btm_sec_cb.pairing_bda, NULL,
2455 BT_TRANSPORT_BR_EDR) != BTM_CMD_STARTED) {
2456 log::error("failed to start remote name request");
2457 NotifyBondingChange(*p_dev_rec, HCI_ERR_MEMORY_FULL);
2458 };
2459 return;
2460 }
2461 }
2462
2463 /* check if we were delaying link_key_callback because name was not resolved
2464 */
2465 if (p_dev_rec->sec_rec.link_key_not_sent) {
2466 /* If HCI connection complete has not arrived, wait for it */
2467 if (p_dev_rec->hci_handle == HCI_INVALID_HANDLE) return;
2468
2469 p_dev_rec->sec_rec.link_key_not_sent = false;
2470 btm_send_link_key_notif(p_dev_rec);
2471 }
2472
2473 /* If this is a bonding procedure can disconnect the link now */
2474 if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
2475 (p_dev_rec->sec_rec.sec_flags & BTM_SEC_AUTHENTICATED)) {
2476 log::warn("btm_sec_rmt_name_request_complete (none/ce)");
2477 p_dev_rec->sec_rec.security_required &= ~(BTM_SEC_OUT_AUTHENTICATE);
2478 l2cu_start_post_bond_timer(p_dev_rec->hci_handle);
2479 return;
2480 }
2481
2482 if (old_sec_state != BTM_SEC_STATE_GETTING_NAME) return;
2483
2484 /* If get name failed, notify the waiting layer */
2485 if (status != HCI_SUCCESS) {
2486 btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, false);
2487 return;
2488 }
2489
2490 if (p_dev_rec->sm4 & BTM_SM4_REQ_PEND) {
2491 log::verbose("waiting for remote features!!");
2492 return;
2493 }
2494
2495 /* Remote Name succeeded, execute the next security procedure, if any */
2496 tBTM_STATUS btm_status = btm_sec_execute_procedure(p_dev_rec);
2497
2498 /* If result is pending reply from the user or from the device is pending */
2499 if (btm_status == BTM_CMD_STARTED) return;
2500
2501 /* There is no next procedure or start of procedure failed, notify the waiting
2502 * layer */
2503 btm_sec_dev_rec_cback_event(p_dev_rec, btm_status, false);
2504 }
2505
2506 /*******************************************************************************
2507 *
2508 * Function btm_sec_rmt_host_support_feat_evt
2509 *
2510 * Description This function is called when the
2511 * HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT is received
2512 *
2513 * Returns void
2514 *
2515 ******************************************************************************/
btm_sec_rmt_host_support_feat_evt(const RawAddress bd_addr,uint8_t features_0)2516 void btm_sec_rmt_host_support_feat_evt(const RawAddress bd_addr,
2517 uint8_t features_0) {
2518 tBTM_SEC_DEV_REC* p_dev_rec;
2519
2520 p_dev_rec = btm_find_or_alloc_dev(bd_addr);
2521
2522 log::info("Got btm_sec_rmt_host_support_feat_evt from {}", bd_addr);
2523
2524 log::verbose("btm_sec_rmt_host_support_feat_evt sm4: 0x{:x} p[0]: 0x{:x}",
2525 p_dev_rec->sm4, features_0);
2526
2527 if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) {
2528 p_dev_rec->sm4 = BTM_SM4_KNOWN;
2529 if (HCI_SSP_HOST_SUPPORTED((std::array<uint8_t, 1>({features_0})))) {
2530 p_dev_rec->sm4 = BTM_SM4_TRUE;
2531 }
2532 log::verbose(
2533 "btm_sec_rmt_host_support_feat_evt sm4: 0x{:x} features[0]: 0x{:x}",
2534 p_dev_rec->sm4, features_0);
2535 }
2536 }
2537
2538 /*******************************************************************************
2539 *
2540 * Function btm_io_capabilities_req
2541 *
2542 * Description This function is called when LM request for the IO
2543 * capability of the local device and
2544 * if the OOB data is present for the device in the event
2545 *
2546 * Returns void
2547 *
2548 ******************************************************************************/
btm_io_capabilities_req(RawAddress p)2549 void btm_io_capabilities_req(RawAddress p) {
2550 if (btm_sec_is_a_bonded_dev(p)) {
2551 if (com::android::bluetooth::flags::key_missing_classic_device()) {
2552 log::warn(
2553 "Incoming bond request, but {} is already bonded (notifying user)",
2554 p);
2555 bta_dm_remote_key_missing(p);
2556
2557 auto p_dev_rec = btm_find_dev(p);
2558 if (p_dev_rec != NULL) {
2559 btm_sec_disconnect(p_dev_rec->hci_handle, HCI_ERR_AUTH_FAILURE,
2560 "btm_io_capabilities_req Security failure");
2561 }
2562 return;
2563 }
2564
2565 log::warn("Incoming bond request, but {} is already bonded (removing)", p);
2566 bta_dm_process_remove_device(p);
2567 }
2568
2569 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(p);
2570
2571 if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SC) &&
2572 (!p_dev_rec->remote_feature_received)) {
2573 log::verbose(
2574 "Device security mode is SC only.To continue need to know remote "
2575 "features.");
2576
2577 // ACL calls back to btm_sec_set_peer_sec_caps after it gets data
2578 p_dev_rec->remote_features_needed = true;
2579 return;
2580 }
2581
2582 tBTM_SP_IO_REQ evt_data;
2583 evt_data.bd_addr = p;
2584
2585 /* setup the default response according to compile options */
2586 /* assume that the local IO capability does not change
2587 * loc_io_caps is initialized with the default value */
2588 evt_data.io_cap = btm_sec_cb.devcb.loc_io_caps;
2589 // TODO(optedoblivion): Inject OOB_DATA_PRESENT Flag
2590 evt_data.oob_data = BTM_OOB_NONE;
2591 evt_data.auth_req = BTM_AUTH_SP_NO;
2592
2593 p_dev_rec->sm4 |= BTM_SM4_TRUE;
2594
2595 log::verbose("State: {}, Security Mode: {}, Device security Flags: 0x{:04x}",
2596 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
2597 btm_sec_cb.security_mode, btm_sec_cb.pairing_flags);
2598
2599 uint8_t err_code = 0;
2600 bool is_orig = true;
2601 switch (btm_sec_cb.pairing_state) {
2602 /* initiator connecting */
2603 case BTM_PAIR_STATE_IDLE:
2604 // TODO: Handle Idle pairing state
2605 // security_required = p_dev_rec->sec_rec.security_required;
2606 break;
2607
2608 /* received IO capability response already->acceptor */
2609 case BTM_PAIR_STATE_INCOMING_SSP:
2610 is_orig = false;
2611
2612 if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_PEER_STARTED_DD) {
2613 /* acceptor in dedicated bonding */
2614 evt_data.auth_req = BTM_AUTH_AP_YES;
2615 }
2616 break;
2617
2618 /* initiator, at this point it is expected to be dedicated bonding
2619 initiated by local device */
2620 case BTM_PAIR_STATE_WAIT_PIN_REQ:
2621 if (evt_data.bd_addr == btm_sec_cb.pairing_bda) {
2622 evt_data.auth_req = BTM_AUTH_AP_YES;
2623 } else {
2624 err_code = HCI_ERR_HOST_BUSY_PAIRING;
2625 }
2626 break;
2627
2628 /* any other state is unexpected */
2629 default:
2630 err_code = HCI_ERR_HOST_BUSY_PAIRING;
2631 log::error("Unexpected Pairing state received {}",
2632 btm_sec_cb.pairing_state);
2633 break;
2634 }
2635
2636 if (btm_sec_cb.pairing_disabled) {
2637 /* pairing is not allowed */
2638 log::verbose("Pairing is not allowed -> fail pairing.");
2639 err_code = HCI_ERR_PAIRING_NOT_ALLOWED;
2640 } else if (btm_sec_cb.security_mode == BTM_SEC_MODE_SC) {
2641 bool local_supports_sc =
2642 bluetooth::shim::GetController()->SupportsSecureConnections();
2643 /* device in Secure Connections Only mode */
2644 if (!(local_supports_sc) || !(p_dev_rec->SupportsSecureConnections())) {
2645 log::debug(
2646 "SC only service, local_support_for_sc:{}, remote_support_for_sc:{} "
2647 "-> fail pairing",
2648 local_supports_sc, p_dev_rec->SupportsSecureConnections());
2649 err_code = HCI_ERR_PAIRING_NOT_ALLOWED;
2650 }
2651 }
2652
2653 if (err_code != 0) {
2654 btsnd_hcic_io_cap_req_neg_reply(evt_data.bd_addr, err_code);
2655 return;
2656 }
2657
2658 evt_data.is_orig = is_orig;
2659
2660 if (is_orig) {
2661 /* local device initiated the pairing non-bonding -> use
2662 * required_security_flags_for_pairing */
2663 if (!(btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
2664 (p_dev_rec->sec_rec.required_security_flags_for_pairing &
2665 BTM_SEC_OUT_AUTHENTICATE)) {
2666 if (btm_sec_cb.security_mode == BTM_SEC_MODE_SC) {
2667 /* SC only mode device requires MITM protection */
2668 evt_data.auth_req = BTM_AUTH_SP_YES;
2669 } else {
2670 evt_data.auth_req =
2671 (p_dev_rec->sec_rec.required_security_flags_for_pairing &
2672 BTM_SEC_OUT_MITM)
2673 ? BTM_AUTH_SP_YES
2674 : BTM_AUTH_SP_NO;
2675 }
2676 }
2677 }
2678
2679 /* Notify L2CAP to increase timeout */
2680 l2c_pin_code_request(evt_data.bd_addr);
2681
2682 btm_sec_cb.pairing_bda = evt_data.bd_addr;
2683
2684 if (evt_data.bd_addr == btm_sec_cb.connecting_bda)
2685 p_dev_rec->dev_class = btm_sec_cb.connecting_dc;
2686
2687 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS);
2688
2689 if (p_dev_rec->sm4 & BTM_SM4_UPGRADE) {
2690 p_dev_rec->sm4 &= ~BTM_SM4_UPGRADE;
2691
2692 /* link key upgrade: always use SPGB_YES - assuming we want to save the link
2693 * key */
2694 evt_data.auth_req = BTM_AUTH_SPGB_YES;
2695 } else if (btm_sec_cb.api.p_sp_callback) {
2696 /* the callback function implementation may change the IO capability... */
2697 (*btm_sec_cb.api.p_sp_callback)(BTM_SP_IO_REQ_EVT,
2698 (tBTM_SP_EVT_DATA*)&evt_data);
2699 }
2700
2701 if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)) {
2702 evt_data.auth_req =
2703 (BTM_AUTH_DD_BOND | (evt_data.auth_req & BTM_AUTH_YN_BIT));
2704 }
2705
2706 if (btm_sec_cb.security_mode == BTM_SEC_MODE_SC) {
2707 /* At this moment we know that both sides are SC capable, device in */
2708 /* SC only mode requires MITM for any service so let's set MITM bit */
2709 evt_data.auth_req |= BTM_AUTH_YN_BIT;
2710 log::verbose("for device in \"SC only\" mode set auth_req to 0x{:02x}",
2711 evt_data.auth_req);
2712 }
2713
2714 /* if the user does not indicate "reply later" by setting the oob_data to
2715 * unknown */
2716 /* send the response right now. Save the current IO capability in the
2717 * control block */
2718 btm_sec_cb.devcb.loc_auth_req = evt_data.auth_req;
2719 btm_sec_cb.devcb.loc_io_caps = evt_data.io_cap;
2720
2721 log::verbose("State: {} IO_CAP:{} oob_data:{} auth_req:{}",
2722 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
2723 evt_data.io_cap, evt_data.oob_data, evt_data.auth_req);
2724
2725 btsnd_hcic_io_cap_req_reply(evt_data.bd_addr, evt_data.io_cap,
2726 evt_data.oob_data, evt_data.auth_req);
2727 }
2728
2729 /*******************************************************************************
2730 *
2731 * Function btm_io_capabilities_rsp
2732 *
2733 * Description This function is called when the IO capability of the
2734 * specified device is received
2735 *
2736 * Returns void
2737 *
2738 ******************************************************************************/
btm_io_capabilities_rsp(const tBTM_SP_IO_RSP evt_data)2739 void btm_io_capabilities_rsp(const tBTM_SP_IO_RSP evt_data) {
2740 tBTM_SEC_DEV_REC* p_dev_rec;
2741
2742 /* Allocate a new device record or reuse the oldest one */
2743 p_dev_rec = btm_find_or_alloc_dev(evt_data.bd_addr);
2744
2745 /* If no security is in progress, this indicates incoming security */
2746 if (btm_sec_cb.pairing_state == BTM_PAIR_STATE_IDLE) {
2747 btm_sec_cb.pairing_bda = evt_data.bd_addr;
2748
2749 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_INCOMING_SSP);
2750 }
2751
2752 /* Notify L2CAP to increase timeout */
2753 l2c_pin_code_request(evt_data.bd_addr);
2754
2755 /* We must have a device record here.
2756 * Use the connecting device's CoD for the connection */
2757 if (evt_data.bd_addr == btm_sec_cb.connecting_bda)
2758 p_dev_rec->dev_class = btm_sec_cb.connecting_dc;
2759
2760 /* peer sets dedicated bonding bit and we did not initiate dedicated bonding
2761 */
2762 if (btm_sec_cb.pairing_state ==
2763 BTM_PAIR_STATE_INCOMING_SSP /* peer initiated bonding */
2764 && (evt_data.auth_req &
2765 BTM_AUTH_DD_BOND)) /* and dedicated bonding bit is set */
2766 {
2767 btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_PEER_STARTED_DD;
2768 }
2769
2770 /* save the IO capability in the device record */
2771 p_dev_rec->sec_rec.rmt_io_caps = evt_data.io_cap;
2772 p_dev_rec->sec_rec.rmt_auth_req = evt_data.auth_req;
2773
2774 if (btm_sec_cb.api.p_sp_callback)
2775 (*btm_sec_cb.api.p_sp_callback)(BTM_SP_IO_RSP_EVT,
2776 (tBTM_SP_EVT_DATA*)&evt_data);
2777 }
2778
2779 /*******************************************************************************
2780 *
2781 * Function btm_proc_sp_req_evt
2782 *
2783 * Description This function is called to process/report
2784 * HCI_USER_CONFIRMATION_REQUEST_EVT
2785 * or HCI_USER_PASSKEY_REQUEST_EVT
2786 * or HCI_USER_PASSKEY_NOTIFY_EVT
2787 *
2788 * Returns void
2789 *
2790 ******************************************************************************/
btm_proc_sp_req_evt(tBTM_SP_EVT event,const RawAddress bda,const uint32_t value)2791 void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bda,
2792 const uint32_t value) {
2793 tBTM_STATUS status = BTM_ERR_PROCESSING;
2794 tBTM_SP_EVT_DATA evt_data;
2795 RawAddress& p_bda = evt_data.cfm_req.bd_addr;
2796 tBTM_SEC_DEV_REC* p_dev_rec;
2797
2798 p_bda = bda;
2799 log::debug("BDA:{}, event:{}, state:{}", p_bda, sp_evt_to_text(event),
2800 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
2801
2802 p_dev_rec = btm_find_dev(p_bda);
2803 if ((p_dev_rec != NULL) &&
2804 (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
2805 (btm_sec_cb.pairing_bda == p_bda)) {
2806 evt_data.cfm_req.bd_addr = p_dev_rec->bd_addr;
2807 evt_data.cfm_req.dev_class = p_dev_rec->dev_class;
2808 bd_name_copy(evt_data.cfm_req.bd_name, p_dev_rec->sec_bd_name);
2809
2810 switch (event) {
2811 case BTM_SP_CFM_REQ_EVT:
2812 /* Numeric confirmation. Need user to conf the passkey */
2813 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM);
2814
2815 /* The device record must be allocated in the "IO cap exchange" step */
2816 evt_data.cfm_req.num_val = value;
2817 log::verbose("num_val:{}", evt_data.cfm_req.num_val);
2818
2819 evt_data.cfm_req.just_works = true;
2820
2821 /* process user confirm req in association with the auth_req param */
2822 if (btm_sec_cb.devcb.loc_io_caps == BTM_IO_CAP_IO) {
2823 if (p_dev_rec->sec_rec.rmt_io_caps == BTM_IO_CAP_UNKNOWN) {
2824 log::error(
2825 "did not receive IO cap response prior to BTM_SP_CFM_REQ_EVT, "
2826 "failing pairing request");
2827 status = BTM_WRONG_MODE;
2828 BTM_ConfirmReqReply(status, p_bda);
2829 return;
2830 }
2831
2832 if ((p_dev_rec->sec_rec.rmt_io_caps == BTM_IO_CAP_IO ||
2833 p_dev_rec->sec_rec.rmt_io_caps == BTM_IO_CAP_OUT) &&
2834 (btm_sec_cb.devcb.loc_io_caps == BTM_IO_CAP_IO) &&
2835 ((p_dev_rec->sec_rec.rmt_auth_req & BTM_AUTH_SP_YES) ||
2836 (btm_sec_cb.devcb.loc_auth_req & BTM_AUTH_SP_YES))) {
2837 /* Use Numeric Comparison if
2838 * 1. Local IO capability is DisplayYesNo,
2839 * 2. Remote IO capability is DisplayOnly or DiaplayYesNo, and
2840 * 3. Either of the devices have requested authenticated link key */
2841 evt_data.cfm_req.just_works = false;
2842 }
2843 }
2844
2845 log::verbose("just_works:{}, io loc:{}, rmt:{}, auth loc:{}, rmt:{}",
2846 evt_data.cfm_req.just_works, btm_sec_cb.devcb.loc_io_caps,
2847 p_dev_rec->sec_rec.rmt_io_caps,
2848 btm_sec_cb.devcb.loc_auth_req,
2849 p_dev_rec->sec_rec.rmt_auth_req);
2850
2851 evt_data.cfm_req.loc_auth_req = btm_sec_cb.devcb.loc_auth_req;
2852 evt_data.cfm_req.rmt_auth_req = p_dev_rec->sec_rec.rmt_auth_req;
2853 evt_data.cfm_req.loc_io_caps = btm_sec_cb.devcb.loc_io_caps;
2854 evt_data.cfm_req.rmt_io_caps = p_dev_rec->sec_rec.rmt_io_caps;
2855 break;
2856
2857 case BTM_SP_KEY_NOTIF_EVT:
2858 /* Passkey notification (other side is a keyboard) */
2859 evt_data.key_notif.passkey = value;
2860 log::verbose("passkey:{}", evt_data.key_notif.passkey);
2861
2862 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
2863 break;
2864
2865 case BTM_SP_KEY_REQ_EVT:
2866 if (btm_sec_cb.devcb.loc_io_caps != BTM_IO_CAP_NONE) {
2867 /* HCI_USER_PASSKEY_REQUEST_EVT */
2868 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_KEY_ENTRY);
2869 }
2870 break;
2871 default:
2872 log::warn("unhandled event:{}", sp_evt_to_text(event));
2873 break;
2874 }
2875
2876 if (btm_sec_cb.api.p_sp_callback) {
2877 status = (*btm_sec_cb.api.p_sp_callback)(event, &evt_data);
2878 if (status != BTM_NOT_AUTHORIZED) {
2879 return;
2880 }
2881 /* else BTM_NOT_AUTHORIZED means when the app wants to reject the req
2882 * right now */
2883 } else if ((event == BTM_SP_CFM_REQ_EVT) && (evt_data.cfm_req.just_works)) {
2884 /* automatically reply with just works if no sp_cback */
2885 status = BTM_SUCCESS;
2886 }
2887
2888 if (event == BTM_SP_CFM_REQ_EVT) {
2889 log::verbose("calling BTM_ConfirmReqReply with status: {}", status);
2890 BTM_ConfirmReqReply(status, p_bda);
2891 } else if (btm_sec_cb.devcb.loc_io_caps != BTM_IO_CAP_NONE &&
2892 event == BTM_SP_KEY_REQ_EVT) {
2893 BTM_PasskeyReqReply(status, p_bda, 0);
2894 }
2895 return;
2896 }
2897
2898 /* Something bad. we can only fail this connection */
2899 acl_set_disconnect_reason(HCI_ERR_HOST_REJECT_SECURITY);
2900
2901 if (BTM_SP_CFM_REQ_EVT == event) {
2902 btsnd_hcic_user_conf_reply(p_bda, false);
2903 } else if (BTM_SP_KEY_NOTIF_EVT == event) {
2904 /* do nothing -> it very unlikely to happen.
2905 This event is most likely to be received by a HID host when it first
2906 connects to a HID device.
2907 Usually the Host initiated the connection in this case.
2908 On Mobile platforms, if there's a security process happening,
2909 the host probably can not initiate another connection.
2910 BTW (PC) is another story. */
2911 p_dev_rec = btm_find_dev(p_bda);
2912 if (p_dev_rec != NULL) {
2913 btm_sec_disconnect(
2914 p_dev_rec->hci_handle, HCI_ERR_AUTH_FAILURE,
2915 "stack::btm::btm_sec::btm_proc_sp_req_evt Security failure");
2916 }
2917 } else if (btm_sec_cb.devcb.loc_io_caps != BTM_IO_CAP_NONE) {
2918 btsnd_hcic_user_passkey_neg_reply(p_bda);
2919 }
2920 }
2921
2922 /*******************************************************************************
2923 *
2924 * Function btm_simple_pair_complete
2925 *
2926 * Description This function is called when simple pairing process is
2927 * complete
2928 *
2929 * Returns void
2930 *
2931 ******************************************************************************/
btm_simple_pair_complete(const RawAddress bd_addr,uint8_t status)2932 void btm_simple_pair_complete(const RawAddress bd_addr, uint8_t status) {
2933 tBTM_SEC_DEV_REC* p_dev_rec;
2934 bool disc = false;
2935
2936 p_dev_rec = btm_find_dev(bd_addr);
2937 if (p_dev_rec == NULL) {
2938 log::error("unknown BDA: {}", bd_addr);
2939 return;
2940 }
2941
2942 log::verbose(
2943 "btm_simple_pair_complete() Pair State: {} Status:{} sec_state: {}",
2944 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), status,
2945 p_dev_rec->sec_rec.sec_state);
2946
2947 if (status == HCI_SUCCESS) {
2948 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_AUTHENTICATED;
2949 } else if (status == HCI_ERR_PAIRING_NOT_ALLOWED) {
2950 /* The test spec wants the peer device to get this failure code. */
2951 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_DISCONNECT);
2952
2953 /* Change the timer to 1 second */
2954 alarm_set_on_mloop(btm_sec_cb.pairing_timer, BT_1SEC_TIMEOUT_MS,
2955 btm_sec_pairing_timeout, NULL);
2956 } else if (btm_sec_cb.pairing_bda == bd_addr) {
2957 /* stop the timer */
2958 alarm_cancel(btm_sec_cb.pairing_timer);
2959
2960 if (p_dev_rec->sec_rec.sec_state != BTM_SEC_STATE_AUTHENTICATING) {
2961 /* the initiating side: will receive auth complete event. disconnect ACL
2962 * at that time */
2963 disc = true;
2964 }
2965 } else {
2966 disc = true;
2967 }
2968
2969 if (disc) {
2970 /* simple pairing failed */
2971 /* Avoid sending disconnect on HCI_ERR_PEER_USER */
2972 if ((status != HCI_ERR_PEER_USER) &&
2973 (status != HCI_ERR_CONN_CAUSE_LOCAL_HOST)) {
2974 btm_sec_send_hci_disconnect(
2975 p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle,
2976 "stack::btm::btm_sec::btm_simple_pair_complete Auth fail");
2977 }
2978 }
2979 }
2980
2981 /*******************************************************************************
2982 *
2983 * Function btm_rem_oob_req
2984 *
2985 * Description This function is called to process/report
2986 * HCI_REMOTE_OOB_DATA_REQUEST_EVT
2987 *
2988 * Returns void
2989 *
2990 ******************************************************************************/
btm_rem_oob_req(const RawAddress bd_addr)2991 void btm_rem_oob_req(const RawAddress bd_addr) {
2992 tBTM_SP_RMT_OOB evt_data;
2993 tBTM_SEC_DEV_REC* p_dev_rec;
2994 Octet16 c;
2995 Octet16 r;
2996
2997 evt_data.bd_addr = bd_addr;
2998 RawAddress& p_bda = evt_data.bd_addr;
2999
3000 log::verbose("BDA: {}", p_bda);
3001 p_dev_rec = btm_find_dev(p_bda);
3002 if ((p_dev_rec != NULL) && btm_sec_cb.api.p_sp_callback) {
3003 evt_data.bd_addr = p_dev_rec->bd_addr;
3004 evt_data.dev_class = p_dev_rec->dev_class;
3005 bd_name_copy(evt_data.bd_name, p_dev_rec->sec_bd_name);
3006
3007 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP);
3008 if ((*btm_sec_cb.api.p_sp_callback)(BTM_SP_RMT_OOB_EVT,
3009 (tBTM_SP_EVT_DATA*)&evt_data) ==
3010 BTM_NOT_AUTHORIZED) {
3011 BTM_RemoteOobDataReply(static_cast<tBTM_STATUS>(true), p_bda, c, r);
3012 }
3013 return;
3014 }
3015
3016 /* something bad. we can only fail this connection */
3017 acl_set_disconnect_reason(HCI_ERR_HOST_REJECT_SECURITY);
3018 btsnd_hcic_rem_oob_neg_reply(p_bda);
3019 }
3020
3021 /*******************************************************************************
3022 *
3023 * Function btm_read_local_oob_complete
3024 *
3025 * Description This function is called when read local oob data is
3026 * completed by the LM
3027 *
3028 * Returns void
3029 *
3030 ******************************************************************************/
btm_read_local_oob_complete(const tBTM_SP_LOC_OOB evt_data)3031 void btm_read_local_oob_complete(const tBTM_SP_LOC_OOB evt_data) {
3032 log::verbose("btm_read_local_oob_complete:{}", evt_data.status);
3033
3034 if (btm_sec_cb.api.p_sp_callback) {
3035 tBTM_SP_EVT_DATA btm_sp_evt_data;
3036 btm_sp_evt_data.loc_oob = evt_data;
3037 (*btm_sec_cb.api.p_sp_callback)(BTM_SP_LOC_OOB_EVT, &btm_sp_evt_data);
3038 }
3039 }
3040
3041 /*******************************************************************************
3042 *
3043 * Function btm_sec_auth_collision
3044 *
3045 * Description This function is called when authentication or encryption
3046 * needs to be retried at a later time.
3047 *
3048 * Returns void
3049 *
3050 ******************************************************************************/
btm_sec_auth_collision(uint16_t handle)3051 static void btm_sec_auth_collision(uint16_t handle) {
3052 tBTM_SEC_DEV_REC* p_dev_rec;
3053
3054 if (!btm_sec_cb.collision_start_time)
3055 btm_sec_cb.collision_start_time =
3056 bluetooth::common::time_get_os_boottime_ms();
3057
3058 if ((bluetooth::common::time_get_os_boottime_ms() -
3059 btm_sec_cb.collision_start_time) < BTM_SEC_MAX_COLLISION_DELAY) {
3060 if (handle == HCI_INVALID_HANDLE) {
3061 p_dev_rec = btm_sec_find_dev_by_sec_state(BTM_SEC_STATE_AUTHENTICATING);
3062 if (p_dev_rec == NULL)
3063 p_dev_rec = btm_sec_find_dev_by_sec_state(BTM_SEC_STATE_ENCRYPTING);
3064 } else
3065 p_dev_rec = btm_find_dev_by_handle(handle);
3066
3067 if (p_dev_rec != NULL) {
3068 log::verbose("btm_sec_auth_collision: state {} (retrying in a moment...)",
3069 p_dev_rec->sec_rec.sec_state);
3070 /* We will restart authentication after timeout */
3071 if (p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_AUTHENTICATING ||
3072 p_dev_rec->sec_rec.is_security_state_bredr_encrypting())
3073 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_IDLE;
3074
3075 btm_sec_cb.p_collided_dev_rec = p_dev_rec;
3076 alarm_set_on_mloop(btm_sec_cb.sec_collision_timer, BT_1SEC_TIMEOUT_MS,
3077 btm_sec_collision_timeout, NULL);
3078 }
3079 }
3080 }
3081
3082 /******************************************************************************
3083 *
3084 * Function btm_sec_auth_retry
3085 *
3086 * Description This function is called when authentication or encryption
3087 * needs to be retried at a later time.
3088 *
3089 * Returns TRUE if a security retry required
3090 *
3091 *****************************************************************************/
btm_sec_auth_retry(uint16_t handle,uint8_t status)3092 static bool btm_sec_auth_retry(uint16_t handle, uint8_t status) {
3093 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
3094 if (!p_dev_rec) return false;
3095
3096 /* keep the old sm4 flag and clear the retry bit in control block */
3097 uint8_t old_sm4 = p_dev_rec->sm4;
3098 p_dev_rec->sm4 &= ~BTM_SM4_RETRY;
3099
3100 if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_IDLE) &&
3101 ((old_sm4 & BTM_SM4_RETRY) == 0) && (HCI_ERR_KEY_MISSING == status) &&
3102 BTM_SEC_IS_SM4(p_dev_rec->sm4)) {
3103 /* This retry for missing key is for Lisbon or later only.
3104 Legacy device do not need this. the controller will drive the retry
3105 automatically
3106 set the retry bit */
3107 btm_sec_cb.collision_start_time = 0;
3108 btm_restore_mode();
3109 p_dev_rec->sm4 |= BTM_SM4_RETRY;
3110 p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_LINK_KEY_KNOWN;
3111 log::verbose("Retry for missing key sm4:x{:x} sec_flags:0x{:x}",
3112 p_dev_rec->sm4, p_dev_rec->sec_rec.sec_flags);
3113
3114 /* With BRCM controller, we do not need to delete the stored link key in
3115 controller.
3116 If the stack may sit on top of other controller, we may need this
3117 BTM_DeleteStoredLinkKey (bd_addr, NULL); */
3118 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_IDLE;
3119 btm_sec_execute_procedure(p_dev_rec);
3120 return true;
3121 }
3122
3123 return false;
3124 }
3125
btm_sec_auth_complete(uint16_t handle,tHCI_STATUS status)3126 void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status) {
3127 tBTM_PAIRING_STATE old_state = btm_sec_cb.pairing_state;
3128 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
3129 bool are_bonding = false;
3130 bool was_authenticating = false;
3131
3132 if (p_dev_rec) {
3133 log::verbose(
3134 "Security Manager: in state: {}, handle: {}, status: {}, "
3135 "dev->sec_rec.sec_state:{}, bda: {}, RName: {}",
3136 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle,
3137 status, p_dev_rec->sec_rec.sec_state, p_dev_rec->bd_addr,
3138 reinterpret_cast<char const*>(p_dev_rec->sec_bd_name));
3139 } else {
3140 log::verbose("Security Manager: in state: {}, handle: {}, status: {}",
3141 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
3142 handle, status);
3143 }
3144
3145 /* For transaction collision we need to wait and repeat. There is no need */
3146 /* for random timeout because only peripheral should receive the result */
3147 if ((status == HCI_ERR_LMP_ERR_TRANS_COLLISION) ||
3148 (status == HCI_ERR_DIFF_TRANSACTION_COLLISION)) {
3149 btm_sec_auth_collision(handle);
3150 return;
3151 } else if (btm_sec_auth_retry(handle, status)) {
3152 return;
3153 }
3154
3155 btm_sec_cb.collision_start_time = 0;
3156
3157 btm_restore_mode();
3158
3159 /* Check if connection was made just to do bonding. If we authenticate
3160 the connection that is up, this is the last event received.
3161 */
3162 if (p_dev_rec && (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
3163 !(btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE)) {
3164 p_dev_rec->sec_rec.security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
3165
3166 l2cu_start_post_bond_timer(p_dev_rec->hci_handle);
3167 }
3168
3169 if (!p_dev_rec) return;
3170
3171 if (p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_AUTHENTICATING) {
3172 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_IDLE;
3173 was_authenticating = true;
3174 /* There can be a race condition, when we are starting authentication
3175 * and the peer device is doing encryption.
3176 * If first we receive encryption change up, then initiated
3177 * authentication can not be performed.
3178 * According to the spec we can not do authentication on the
3179 * encrypted link, so device is correct.
3180 */
3181 if ((status == HCI_ERR_COMMAND_DISALLOWED) &&
3182 ((p_dev_rec->sec_rec.sec_flags &
3183 (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED)) ==
3184 (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED))) {
3185 status = HCI_SUCCESS;
3186 }
3187 if (status == HCI_SUCCESS) {
3188 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_AUTHENTICATED;
3189 }
3190 }
3191
3192 if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
3193 (p_dev_rec->bd_addr == btm_sec_cb.pairing_bda)) {
3194 if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) {
3195 are_bonding = true;
3196 }
3197 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
3198 }
3199
3200 if (was_authenticating == false) {
3201 if (status != HCI_SUCCESS && old_state != BTM_PAIR_STATE_IDLE) {
3202 NotifyBondingChange(*p_dev_rec, status);
3203 }
3204 return;
3205 }
3206
3207 /* Currently we do not notify user if it is a keyboard which connects */
3208 /* User probably Disabled the keyboard while it was asleap. Let them try */
3209 if (btm_sec_cb.api.p_auth_complete_callback) {
3210 /* report the suthentication status */
3211 if ((old_state != BTM_PAIR_STATE_IDLE) || (status != HCI_SUCCESS))
3212 (*btm_sec_cb.api.p_auth_complete_callback)(
3213 p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
3214 status);
3215 }
3216
3217 /* If this is a bonding procedure can disconnect the link now */
3218 if (are_bonding) {
3219 p_dev_rec->sec_rec.security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
3220
3221 if (status != HCI_SUCCESS) {
3222 if (((status != HCI_ERR_PEER_USER) &&
3223 (status != HCI_ERR_CONN_CAUSE_LOCAL_HOST)))
3224 btm_sec_send_hci_disconnect(
3225 p_dev_rec, HCI_ERR_PEER_USER, p_dev_rec->hci_handle,
3226 "stack::btm::btm_sec::btm_sec_auth_retry Auth fail while bonding");
3227 } else {
3228 BTM_LogHistory(kBtmLogTag, p_dev_rec->bd_addr, "Bonding completed",
3229 hci_error_code_text(status));
3230
3231 tHCI_ROLE role = HCI_ROLE_UNKNOWN;
3232 BTM_GetRole(p_dev_rec->bd_addr, &role);
3233 if (role == HCI_ROLE_CENTRAL) {
3234 // Encryption is required to start SM over BR/EDR
3235 // indicate that this is encryption after authentication
3236 BTM_SetEncryption(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR, NULL, NULL,
3237 BTM_BLE_SEC_NONE);
3238 } else if (p_dev_rec->IsLocallyInitiated()) {
3239 // Encryption will be set in role_changed callback
3240 log::info(
3241 "auth completed in role=peripheral, try to switch role and "
3242 "encrypt");
3243 BTM_SwitchRoleToCentral(p_dev_rec->RemoteAddress());
3244 }
3245
3246 l2cu_start_post_bond_timer(p_dev_rec->hci_handle);
3247 }
3248
3249 return;
3250 }
3251
3252 /* If authentication failed, notify the waiting layer */
3253 if (status != HCI_SUCCESS) {
3254 btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, false);
3255
3256 if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE) {
3257 btm_sec_send_hci_disconnect(
3258 p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle,
3259 "stack::btm::btm_sec::btm_sec_auth_retry Auth failed");
3260 }
3261 return;
3262 }
3263
3264 if (p_dev_rec->sec_rec.pin_code_length >= 16 ||
3265 p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_AUTH_COMB ||
3266 p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) {
3267 // If we have MITM protection we have a higher level of security than
3268 // provided by 16 digits PIN
3269 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED;
3270 }
3271
3272 /* Authentication succeeded, execute the next security procedure, if any */
3273 tBTM_STATUS btm_status = btm_sec_execute_procedure(p_dev_rec);
3274
3275 /* If there is no next procedure, or procedure failed to start, notify the
3276 * caller */
3277 if (btm_status != BTM_CMD_STARTED)
3278 btm_sec_dev_rec_cback_event(p_dev_rec, btm_status, false);
3279 }
3280
3281 /*******************************************************************************
3282 *
3283 * Function btm_sec_encrypt_change
3284 *
3285 * Description This function is when encryption of the connection is
3286 * completed by the LM
3287 *
3288 * Returns void
3289 *
3290 ******************************************************************************/
btm_sec_encrypt_change(uint16_t handle,tHCI_STATUS status,uint8_t encr_enable)3291 void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status,
3292 uint8_t encr_enable) {
3293 /* For transaction collision we need to wait and repeat. There is no need */
3294 /* for random timeout because only peripheral should receive the result */
3295 if ((status == HCI_ERR_LMP_ERR_TRANS_COLLISION) ||
3296 (status == HCI_ERR_DIFF_TRANSACTION_COLLISION)) {
3297 log::error("Encryption collision failed status:{}",
3298 hci_error_code_text(status));
3299 btm_sec_auth_collision(handle);
3300 return;
3301 }
3302 btm_sec_cb.collision_start_time = 0;
3303
3304 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
3305 if (p_dev_rec == nullptr) {
3306 log::warn(
3307 "Received encryption change for unknown device handle:0x{:04x} "
3308 "status:{} enable:0x{:x}",
3309 handle, hci_status_code_text(status), encr_enable);
3310 return;
3311 }
3312
3313 const tBT_TRANSPORT transport =
3314 BTM_IsBleConnection(handle) ? BT_TRANSPORT_LE : BT_TRANSPORT_BR_EDR;
3315
3316 log::debug(
3317 "Security Manager encryption change request hci_status:{} request:{} "
3318 "state:{} sec_flags:0x{:x}",
3319 hci_status_code_text(status), (encr_enable) ? "encrypt" : "unencrypt",
3320 (p_dev_rec->sec_rec.sec_state) ? "encrypted" : "unencrypted",
3321 p_dev_rec->sec_rec.sec_flags);
3322
3323 if (status == HCI_SUCCESS) {
3324 if (encr_enable) {
3325 if (p_dev_rec->hci_handle == handle) { // classic
3326 p_dev_rec->sec_rec.sec_flags |=
3327 (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED);
3328 if (p_dev_rec->sec_rec.pin_code_length >= 16 ||
3329 p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_AUTH_COMB ||
3330 p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) {
3331 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED;
3332 }
3333 } else if (p_dev_rec->ble_hci_handle == handle) { // BLE
3334 p_dev_rec->sec_rec.set_le_device_encrypted();
3335 if (p_dev_rec->sec_rec.is_le_link_key_authenticated()) {
3336 p_dev_rec->sec_rec.set_le_device_authenticated();
3337 }
3338 } else {
3339 log::error(
3340 "Received encryption change for unknown device handle:0x{:04x} "
3341 "status:{} enable:0x{:x}",
3342 handle, hci_status_code_text(status), encr_enable);
3343 }
3344 } else {
3345 log::info(
3346 "Encryption was not enabled locally resetting encryption state");
3347 /* It is possible that we decrypted the link to perform role switch */
3348 /* mark link not to be encrypted, so that when we execute security next
3349 * time it will kick in again */
3350 if (p_dev_rec->hci_handle == handle) { // clasic
3351 p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_ENCRYPTED;
3352 } else if (p_dev_rec->ble_hci_handle == handle) { // BLE
3353 p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_LE_ENCRYPTED;
3354 } else {
3355 log::error(
3356 "Received encryption change for unknown device handle:0x{:04x} "
3357 "status:{} enable:0x{:x}",
3358 handle, hci_status_code_text(status), encr_enable);
3359 }
3360 }
3361 }
3362
3363 const bool is_encrypted = p_dev_rec->sec_rec.is_le_device_encrypted() ||
3364 p_dev_rec->sec_rec.is_device_encrypted();
3365 BTM_LogHistory(
3366 kBtmLogTag,
3367 (transport == BT_TRANSPORT_LE) ? p_dev_rec->ble.pseudo_addr
3368 : p_dev_rec->bd_addr,
3369 (status == HCI_SUCCESS) ? "Encryption success" : "Encryption failed",
3370 base::StringPrintf("status:%s transport:%s is_encrypted:%c",
3371 hci_status_code_text(status).c_str(),
3372 bt_transport_text(transport).c_str(),
3373 is_encrypted ? 'T' : 'F'));
3374
3375 log::debug("after update p_dev_rec->sec_rec.sec_flags=0x{:x}",
3376 p_dev_rec->sec_rec.sec_flags);
3377
3378 btm_sec_check_pending_enc_req(p_dev_rec, transport, encr_enable);
3379
3380 if (transport == BT_TRANSPORT_LE) {
3381 if (status == HCI_ERR_KEY_MISSING || status == HCI_ERR_AUTH_FAILURE ||
3382 status == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE) {
3383 if (com::android::bluetooth::flags::
3384 sec_dont_clear_keys_on_encryption_err()) {
3385 log::error("{} encrypt failure status 0x{:x}", p_dev_rec->bd_addr,
3386 status);
3387 } else {
3388 p_dev_rec->sec_rec.sec_flags &= ~(BTM_SEC_LE_LINK_KEY_KNOWN);
3389 p_dev_rec->sec_rec.ble_keys.key_type = BTM_LE_KEY_NONE;
3390 }
3391 }
3392 p_dev_rec->sec_rec.sec_status = status;
3393 btm_ble_link_encrypted(p_dev_rec->ble.pseudo_addr, encr_enable);
3394
3395 if (status == HCI_ERR_KEY_MISSING) {
3396 log::info("Remote key missing - will report");
3397 bta_dm_remote_key_missing(p_dev_rec->ble.pseudo_addr);
3398 return;
3399 }
3400
3401 return;
3402 } else {
3403 /* BR/EDR connection, update the encryption key size to be 16 as always */
3404 p_dev_rec->sec_rec.enc_key_size = 16;
3405 }
3406
3407 log::debug("in new_encr_key_256 is {}",
3408 p_dev_rec->sec_rec.new_encryption_key_is_p256);
3409
3410 if ((status == HCI_SUCCESS) && encr_enable &&
3411 (p_dev_rec->hci_handle == handle)) {
3412 /* if BR key is temporary no need for LE LTK derivation */
3413 bool derive_ltk = true;
3414 if (p_dev_rec->sec_rec.rmt_auth_req == BTM_AUTH_SP_NO &&
3415 btm_sec_cb.devcb.loc_auth_req == BTM_AUTH_SP_NO) {
3416 derive_ltk = false;
3417 log::verbose("BR key is temporary, skip derivation of LE LTK");
3418 }
3419 tHCI_ROLE role = HCI_ROLE_UNKNOWN;
3420 BTM_GetRole(p_dev_rec->bd_addr, &role);
3421 if (p_dev_rec->sec_rec.new_encryption_key_is_p256) {
3422 if (btm_sec_use_smp_br_chnl(p_dev_rec) && role == HCI_ROLE_CENTRAL &&
3423 /* if LE key is not known, do deriving */
3424 (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN) ||
3425 /* or BR key is higher security than existing LE keys */
3426 (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_LINK_KEY_AUTHED) &&
3427 (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_AUTHED))) &&
3428 derive_ltk) {
3429 /* BR/EDR is encrypted with LK that can be used to derive LE LTK */
3430 p_dev_rec->sec_rec.new_encryption_key_is_p256 = false;
3431
3432 log::verbose("start SM over BR/EDR");
3433 SMP_BR_PairWith(p_dev_rec->bd_addr);
3434 }
3435 }
3436 }
3437
3438 /* If this encryption was started by peer do not need to do anything */
3439 if (!p_dev_rec->sec_rec.is_security_state_bredr_encrypting()) {
3440 if (BTM_SEC_STATE_DELAY_FOR_ENC == p_dev_rec->sec_rec.sec_state) {
3441 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_IDLE;
3442 log::verbose("clearing callback. p_dev_rec={}, p_callback={}",
3443 fmt::ptr(p_dev_rec),
3444 fmt::ptr(p_dev_rec->sec_rec.p_callback));
3445 p_dev_rec->sec_rec.p_callback = NULL;
3446 l2cu_resubmit_pending_sec_req(&p_dev_rec->bd_addr);
3447 return;
3448 } else if (!concurrentPeerAuthIsEnabled() &&
3449 p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_AUTHENTICATING) {
3450 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_IDLE;
3451 return;
3452 }
3453 if (!handleUnexpectedEncryptionChange()) {
3454 return;
3455 }
3456 }
3457
3458 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_IDLE;
3459 /* If encryption setup failed, notify the waiting layer */
3460 if (status != HCI_SUCCESS) {
3461 btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, false);
3462 return;
3463 }
3464
3465 /* Encryption setup succeeded, execute the next security procedure, if any */
3466 tBTM_STATUS btm_status = btm_sec_execute_procedure(p_dev_rec);
3467 /* If there is no next procedure, or procedure failed to start, notify the
3468 * caller */
3469 if (static_cast<std::underlying_type_t<tHCI_STATUS>>(status) !=
3470 BTM_CMD_STARTED)
3471 btm_sec_dev_rec_cback_event(p_dev_rec, btm_status, false);
3472 }
3473
3474 constexpr uint8_t MIN_KEY_SIZE = 7;
3475
read_encryption_key_size_complete_after_encryption_change(uint8_t status,uint16_t handle,uint8_t key_size)3476 static void read_encryption_key_size_complete_after_encryption_change(
3477 uint8_t status, uint16_t handle, uint8_t key_size) {
3478 if (status == HCI_ERR_INSUFFCIENT_SECURITY) {
3479 /* If remote device stop the encryption before we call "Read Encryption Key
3480 * Size", we might receive Insufficient Security, which means that link is
3481 * no longer encrypted. */
3482 log::info("encryption stopped on link:0x{:x}", handle);
3483 return;
3484 }
3485
3486 if (status != HCI_SUCCESS) {
3487 log::error("disconnecting, status:0x{:x}", status);
3488 acl_disconnect_from_handle(handle, HCI_ERR_PEER_USER,
3489 "stack::btu::btu_hcif::read_encryption_key_size_"
3490 "complete_after_encryption_change Bad key size");
3491 return;
3492 }
3493
3494 if (key_size < MIN_KEY_SIZE) {
3495 log::error(
3496 "encryption key too short, disconnecting. handle:0x{:x},key_size:{}",
3497 handle, key_size);
3498
3499 acl_disconnect_from_handle(
3500 handle, HCI_ERR_HOST_REJECT_SECURITY,
3501 "stack::btu::btu_hcif::read_encryption_key_size_complete_after_"
3502 "encryption_change Key Too Short");
3503 return;
3504 }
3505
3506 if (com::android::bluetooth::flags::bluffs_mitigation()) {
3507 if (btm_sec_is_session_key_size_downgrade(handle, key_size)) {
3508 log::error(
3509 "encryption key size lower than cached value, disconnecting. "
3510 "handle: 0x{:x} attempted key size: {}",
3511 handle, key_size);
3512 acl_disconnect_from_handle(
3513 handle, HCI_ERR_HOST_REJECT_SECURITY,
3514 "stack::btu::btu_hcif::read_encryption_key_size_complete_after_"
3515 "encryption_change Key Size Downgrade");
3516 return;
3517 }
3518
3519 btm_sec_update_session_key_size(handle, key_size);
3520 }
3521
3522 // good key size - succeed
3523 btm_acl_encrypt_change(handle, static_cast<tHCI_STATUS>(status),
3524 1 /* enable */);
3525 btm_sec_encrypt_change(handle, static_cast<tHCI_STATUS>(status),
3526 1 /* enable */);
3527 }
3528
3529 // TODO: Remove
3530 void smp_cancel_start_encryption_attempt();
3531
3532 /*******************************************************************************
3533 *
3534 * Function btm_encryption_change_evt
3535 *
3536 * Description Process event HCI_ENCRYPTION_CHANGE_EVT
3537 *
3538 * Returns void
3539 *
3540 ******************************************************************************/
btm_sec_encryption_change_evt(uint16_t handle,tHCI_STATUS status,uint8_t encr_enable)3541 void btm_sec_encryption_change_evt(uint16_t handle, tHCI_STATUS status,
3542 uint8_t encr_enable) {
3543 if (com::android::bluetooth::flags::bluffs_mitigation()) {
3544 if (status != HCI_SUCCESS || encr_enable == 0 ||
3545 BTM_IsBleConnection(handle) ||
3546 !bluetooth::shim::GetController()->IsSupported(
3547 bluetooth::hci::OpCode::READ_ENCRYPTION_KEY_SIZE)) {
3548 if (status == HCI_ERR_CONNECTION_TOUT) {
3549 smp_cancel_start_encryption_attempt();
3550 return;
3551 }
3552
3553 btm_acl_encrypt_change(handle, static_cast<tHCI_STATUS>(status),
3554 encr_enable);
3555 btm_sec_encrypt_change(handle, static_cast<tHCI_STATUS>(status),
3556 encr_enable);
3557 } else {
3558 btsnd_hcic_read_encryption_key_size(
3559 handle,
3560 base::Bind(
3561 &read_encryption_key_size_complete_after_encryption_change));
3562 }
3563 } else {
3564 // This block added to ensure matching code flow with the bluffs_mitigation
3565 // flag off. The entire block should be removed when the flag is.
3566 if (status != HCI_SUCCESS || encr_enable == 0 ||
3567 BTM_IsBleConnection(handle) ||
3568 !bluetooth::shim::GetController()->IsSupported(
3569 bluetooth::hci::OpCode::READ_ENCRYPTION_KEY_SIZE) ||
3570 // Skip encryption key size check when using set_min_encryption_key_size
3571 (bluetooth::common::init_flags::set_min_encryption_is_enabled() &&
3572 bluetooth::shim::GetController()->IsSupported(
3573 bluetooth::hci::OpCode::SET_MIN_ENCRYPTION_KEY_SIZE))) {
3574 if (status == HCI_ERR_CONNECTION_TOUT) {
3575 smp_cancel_start_encryption_attempt();
3576 return;
3577 }
3578
3579 btm_acl_encrypt_change(handle, static_cast<tHCI_STATUS>(status),
3580 encr_enable);
3581 btm_sec_encrypt_change(handle, static_cast<tHCI_STATUS>(status),
3582 encr_enable);
3583 } else {
3584 btsnd_hcic_read_encryption_key_size(
3585 handle,
3586 base::Bind(
3587 &read_encryption_key_size_complete_after_encryption_change));
3588 }
3589 }
3590 }
3591 /*******************************************************************************
3592 *
3593 * Function btm_sec_connect_after_reject_timeout
3594 *
3595 * Description This function is used to re-initiate an outgoing ACL
3596 * connection in case the ACL connection for bonding failed,
3597 * e.g., because of the collision.
3598 *
3599 * Returns void
3600 *
3601 ******************************************************************************/
btm_sec_connect_after_reject_timeout(void *)3602 static void btm_sec_connect_after_reject_timeout(void* /* data */) {
3603 tBTM_SEC_DEV_REC* p_dev_rec = btm_sec_cb.p_collided_dev_rec;
3604
3605 log::verbose("restarting ACL connection");
3606 btm_sec_cb.p_collided_dev_rec = 0;
3607
3608 if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) {
3609 log::warn("Security Manager: failed to start connection");
3610
3611 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
3612
3613 NotifyBondingChange(*p_dev_rec, HCI_ERR_MEMORY_FULL);
3614 }
3615 }
3616
3617 /*******************************************************************************
3618 *
3619 * Function btm_sec_connected
3620 *
3621 * Description This function is called when a (BR/EDR) ACL connection to
3622 * the peer device is established
3623 *
3624 * Returns void
3625 *
3626 ******************************************************************************/
btm_sec_connected(const RawAddress & bda,uint16_t handle,tHCI_STATUS status,uint8_t enc_mode,tHCI_ROLE assigned_role)3627 void btm_sec_connected(const RawAddress& bda, uint16_t handle,
3628 tHCI_STATUS status, uint8_t enc_mode,
3629 tHCI_ROLE assigned_role) {
3630 tBTM_STATUS res;
3631 bool is_pairing_device = false;
3632 bool addr_matched;
3633 uint8_t bit_shift = 0;
3634
3635 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bda);
3636 if (!p_dev_rec) {
3637 log::debug(
3638 "Connected to new device state:{} handle:0x{:04x} status:{} "
3639 "enc_mode:{} bda:{}",
3640 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle,
3641 hci_status_code_text(status), enc_mode, bda);
3642
3643 if (status == HCI_SUCCESS) {
3644 p_dev_rec = btm_sec_alloc_dev(bda);
3645 log::debug("Allocated new device record for new connection peer:{}", bda);
3646 } else {
3647 /* If the device matches with stored paring address
3648 * reset the paring state to idle */
3649 if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
3650 btm_sec_cb.pairing_bda == bda) {
3651 log::warn("Connection failed during bonding attempt peer:{} reason:{}",
3652 bda, hci_error_code_text(status));
3653 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
3654 }
3655
3656 log::debug("Ignoring failed device connection peer:{} reason:{}", bda,
3657 hci_error_code_text(status));
3658 return;
3659 }
3660 } else {
3661 log::debug(
3662 "Connected to known device state:{} handle:0x{:04x} status:{} "
3663 "enc_mode:{} bda:{} RName:{}",
3664 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle,
3665 hci_status_code_text(status), enc_mode, bda,
3666 reinterpret_cast<char const*>(p_dev_rec->sec_bd_name));
3667
3668 bit_shift = (handle == p_dev_rec->ble_hci_handle) ? 8 : 0;
3669 /* Update the timestamp for this device */
3670 p_dev_rec->timestamp = btm_sec_cb.dev_rec_count++;
3671 if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND) {
3672 if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
3673 (btm_sec_cb.pairing_bda == p_dev_rec->bd_addr) &&
3674 (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)) {
3675 /* if incoming acl connection failed while pairing, then try to connect
3676 * and continue */
3677 /* Motorola S9 disconnects without asking pin code */
3678 if ((status != HCI_SUCCESS) &&
3679 (btm_sec_cb.pairing_state == BTM_PAIR_STATE_WAIT_PIN_REQ)) {
3680 log::warn(
3681 "Security Manager: btm_sec_connected: incoming connection failed "
3682 "without asking PIN");
3683
3684 p_dev_rec->sm4 &= ~BTM_SM4_CONN_PEND;
3685 if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) {
3686 /* remote device name is known, start a new acl connection */
3687
3688 /* Start timer with 0 to initiate connection with new LCB */
3689 /* because L2CAP will delete current LCB with this event */
3690 btm_sec_cb.p_collided_dev_rec = p_dev_rec;
3691 alarm_set_on_mloop(btm_sec_cb.sec_collision_timer, 0,
3692 btm_sec_connect_after_reject_timeout, NULL);
3693 } else {
3694 /* remote device name is unknowm, start getting remote name first */
3695
3696 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_GET_REM_NAME);
3697 if (BTM_ReadRemoteDeviceName(p_dev_rec->bd_addr, NULL,
3698 BT_TRANSPORT_BR_EDR) !=
3699 BTM_CMD_STARTED) {
3700 log::error("cannot read remote name");
3701 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
3702 }
3703 }
3704 return;
3705 } else {
3706 /* tell L2CAP it's a bonding connection. */
3707 l2cu_update_lcb_4_bonding(p_dev_rec->bd_addr, true);
3708 }
3709 }
3710 /* always clear the pending flag */
3711 p_dev_rec->sm4 &= ~BTM_SM4_CONN_PEND;
3712 }
3713 }
3714
3715 p_dev_rec->device_type |= BT_DEVICE_TYPE_BREDR;
3716
3717 addr_matched = (btm_sec_cb.pairing_bda == bda);
3718
3719 if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) && addr_matched) {
3720 /* if we rejected incoming connection from bonding device */
3721 if ((status == HCI_ERR_HOST_REJECT_DEVICE) &&
3722 (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT)) {
3723 log::warn(
3724 "Security Manager: btm_sec_connected: HCI_Conn_Comp Flags:0x{:04x}, "
3725 "sm4: 0x{:x}",
3726 btm_sec_cb.pairing_flags, p_dev_rec->sm4);
3727
3728 btm_sec_cb.pairing_flags &= ~BTM_PAIR_FLAGS_REJECTED_CONNECT;
3729 if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) {
3730 /* Try again: RNR when no ACL causes HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT */
3731 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_GET_REM_NAME);
3732 if (BTM_ReadRemoteDeviceName(bda, NULL, BT_TRANSPORT_BR_EDR) !=
3733 BTM_CMD_STARTED) {
3734 log::error("cannot read remote name");
3735 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
3736 }
3737 return;
3738 }
3739
3740 /* if we already have pin code */
3741 if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN) {
3742 /* Start timer with 0 to initiate connection with new LCB */
3743 /* because L2CAP will delete current LCB with this event */
3744 btm_sec_cb.p_collided_dev_rec = p_dev_rec;
3745 alarm_set_on_mloop(btm_sec_cb.sec_collision_timer, 0,
3746 btm_sec_connect_after_reject_timeout, NULL);
3747 }
3748
3749 return;
3750 }
3751 /* wait for incoming connection without resetting pairing state */
3752 else if (status == HCI_ERR_CONNECTION_EXISTS) {
3753 log::warn(
3754 "Security Manager: btm_sec_connected: Wait for incoming connection");
3755 return;
3756 }
3757
3758 is_pairing_device = true;
3759 }
3760
3761 /* If connection was made to do bonding restore link security if changed */
3762 btm_restore_mode();
3763
3764 /* if connection fails during pin request, notify application */
3765 if (status != HCI_SUCCESS) {
3766 /* If connection failed because of during pairing, need to tell user */
3767 if (is_pairing_device) {
3768 p_dev_rec->sec_rec.security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
3769 p_dev_rec->sec_rec.sec_flags &=
3770 ~((BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED) << bit_shift);
3771 log::verbose("security_required:{:x}",
3772 p_dev_rec->sec_rec.security_required);
3773
3774 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
3775
3776 /* We need to notify host that the key is not known any more */
3777 NotifyBondingChange(*p_dev_rec, status);
3778 }
3779 /*
3780 Do not send authentication failure, if following conditions hold good
3781 1. BTM Sec Pairing state is idle
3782 2. Link key for the remote device is present.
3783 3. Remote is SSP capable.
3784 */
3785 else if ((p_dev_rec->sec_rec.link_key_type <= BTM_LKEY_TYPE_REMOTE_UNIT) &&
3786 (((status == HCI_ERR_AUTH_FAILURE) ||
3787 (status == HCI_ERR_KEY_MISSING) ||
3788 (status == HCI_ERR_HOST_REJECT_SECURITY) ||
3789 (status == HCI_ERR_PAIRING_NOT_ALLOWED) ||
3790 (status == HCI_ERR_UNIT_KEY_USED) ||
3791 (status == HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED) ||
3792 (status == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE) ||
3793 (status == HCI_ERR_REPEATED_ATTEMPTS)))) {
3794 p_dev_rec->sec_rec.security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
3795 p_dev_rec->sec_rec.sec_flags &= ~(BTM_SEC_LE_LINK_KEY_KNOWN << bit_shift);
3796
3797 #ifdef BRCM_NOT_4_BTE
3798 /* If we rejected pairing, pass this special result code */
3799 if (acl_set_disconnect_reason(HCI_ERR_HOST_REJECT_SECURITY)) {
3800 status = HCI_ERR_HOST_REJECT_SECURITY;
3801 }
3802 #endif
3803
3804 /* We need to notify host that the key is not known any more */
3805 NotifyBondingChange(*p_dev_rec, status);
3806 }
3807
3808 /* p_auth_complete_callback might have freed the p_dev_rec, ensure it exists
3809 * before accessing */
3810 p_dev_rec = btm_find_dev(bda);
3811 if (!p_dev_rec) {
3812 /* Don't callback when device security record was removed */
3813 log::debug(
3814 "device security record associated with this bda has been removed! "
3815 "bda={}, do not callback",
3816 bda);
3817 return;
3818 }
3819
3820 if (status == HCI_ERR_CONNECTION_TOUT ||
3821 status == HCI_ERR_LMP_RESPONSE_TIMEOUT ||
3822 status == HCI_ERR_UNSPECIFIED || status == HCI_ERR_PAGE_TIMEOUT)
3823 btm_sec_dev_rec_cback_event(p_dev_rec, BTM_DEVICE_TIMEOUT, false);
3824 else
3825 btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, false);
3826
3827 return;
3828 }
3829
3830 /*
3831 * The device is still in the pairing state machine and we now have the
3832 * link key. If we have not sent the link key, send it now and remove
3833 * the authenticate requirement bit. Reset the pairing state machine
3834 * and inform l2cap if the directed bonding was initiated.
3835 */
3836 if (is_pairing_device &&
3837 (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN)) {
3838 if (p_dev_rec->sec_rec.link_key_not_sent) {
3839 p_dev_rec->sec_rec.link_key_not_sent = false;
3840 btm_send_link_key_notif(p_dev_rec);
3841 }
3842
3843 p_dev_rec->sec_rec.security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
3844
3845 /* remember flag before it is initialized */
3846 const bool is_pair_flags_we_started_dd =
3847 btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD;
3848 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
3849
3850 if (is_pair_flags_we_started_dd) {
3851 /* Let l2cap start bond timer */
3852 l2cu_update_lcb_4_bonding(p_dev_rec->bd_addr, true);
3853 }
3854 log::info("Connection complete during pairing process peer:{}", bda);
3855 BTM_LogHistory(kBtmLogTag, bda, "Dedicated bonding",
3856 base::StringPrintf("Initiated:%c pairing_flag:0x%02x",
3857 (is_pair_flags_we_started_dd) ? 'T' : 'F',
3858 p_dev_rec->sec_rec.sec_flags));
3859 }
3860
3861 p_dev_rec->hci_handle = handle;
3862 btm_acl_created(bda, handle, assigned_role, BT_TRANSPORT_BR_EDR);
3863
3864 /* role may not be correct here, it will be updated by l2cap, but we need to
3865 */
3866 /* notify btm_acl that link is up, so starting of rmt name request will not */
3867 /* set paging flag up */
3868 /* whatever is in btm_establish_continue() without reporting the
3869 * BTM_BL_CONN_EVT event */
3870 /* For now there are a some devices that do not like sending */
3871 /* commands events and data at the same time. */
3872 /* Set the packet types to the default allowed by the device */
3873 btm_set_packet_types_from_address(bda, acl_get_supported_packet_types());
3874
3875 /* Initialize security flags. We need to do that because some */
3876 /* authorization complete could have come after the connection is dropped */
3877 /* and that would set wrong flag that link has been authorized already */
3878 p_dev_rec->sec_rec.sec_flags &=
3879 ~((BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED | BTM_SEC_ROLE_SWITCHED)
3880 << bit_shift);
3881
3882 if (enc_mode != HCI_ENCRYPT_MODE_DISABLED)
3883 p_dev_rec->sec_rec.sec_flags |=
3884 ((BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED) << bit_shift);
3885
3886 if (p_dev_rec->sec_rec.pin_code_length >= 16 ||
3887 p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_AUTH_COMB ||
3888 p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) {
3889 p_dev_rec->sec_rec.sec_flags |= (BTM_SEC_16_DIGIT_PIN_AUTHED << bit_shift);
3890 }
3891
3892 /* After connection is established we perform security if we do not know */
3893 /* the name, or if we are originator because some procedure can have */
3894 /* been scheduled while connection was down */
3895 log::debug("Is connection locally initiated:{}", p_dev_rec->is_originator);
3896 if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) ||
3897 p_dev_rec->is_originator) {
3898 res = btm_sec_execute_procedure(p_dev_rec);
3899 if (res != BTM_CMD_STARTED)
3900 btm_sec_dev_rec_cback_event(p_dev_rec, res, false);
3901 }
3902 }
3903
btm_sec_disconnect(uint16_t handle,tHCI_STATUS reason,std::string comment)3904 tBTM_STATUS btm_sec_disconnect(uint16_t handle, tHCI_STATUS reason,
3905 std::string comment) {
3906 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
3907
3908 /* In some weird race condition we may not have a record */
3909 if (!p_dev_rec) {
3910 acl_disconnect_from_handle(
3911 handle, reason,
3912 "stack::btm::btm_sec::btm_sec_disconnect No security record");
3913 return (BTM_SUCCESS);
3914 }
3915
3916 /* If we are in the process of bonding we need to tell client that auth failed
3917 */
3918 if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
3919 (btm_sec_cb.pairing_bda == p_dev_rec->bd_addr) &&
3920 (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)) {
3921 /* we are currently doing bonding. Link will be disconnected when done */
3922 btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_DISC_WHEN_DONE;
3923 return (BTM_BUSY);
3924 }
3925
3926 return btm_sec_send_hci_disconnect(p_dev_rec, reason, handle, comment);
3927 }
3928
btm_sec_disconnected(uint16_t handle,tHCI_REASON reason,std::string comment)3929 void btm_sec_disconnected(uint16_t handle, tHCI_REASON reason,
3930 std::string comment) {
3931 if ((reason != HCI_ERR_CONN_CAUSE_LOCAL_HOST) &&
3932 (reason != HCI_ERR_PEER_USER) && (reason != HCI_ERR_REMOTE_POWER_OFF)) {
3933 log::warn("Got uncommon disconnection reason:{} handle:0x{:04x} comment:{}",
3934 hci_error_code_text(reason), handle, comment);
3935 }
3936
3937 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
3938 if (p_dev_rec == nullptr) {
3939 log::warn("Got disconnect for unknown device record handle:0x{:04x}",
3940 handle);
3941 return;
3942 }
3943
3944 const tBT_TRANSPORT transport =
3945 (handle == p_dev_rec->hci_handle) ? BT_TRANSPORT_BR_EDR : BT_TRANSPORT_LE;
3946
3947 bool pairing_transport_matches = true;
3948 if (com::android::bluetooth::flags::
3949 cancel_pairing_only_on_disconnected_transport()) {
3950 tBT_TRANSPORT pairing_transport =
3951 (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_LE_ACTIVE) == 0
3952 ? BT_TRANSPORT_BR_EDR
3953 : BT_TRANSPORT_LE;
3954 pairing_transport_matches = (transport == pairing_transport);
3955 }
3956
3957 /* clear unused flags */
3958 p_dev_rec->sm4 &= BTM_SM4_TRUE;
3959
3960 /* If we are in the process of bonding we need to tell client that auth failed
3961 */
3962 const uint8_t old_pairing_flags = btm_sec_cb.pairing_flags;
3963 if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE &&
3964 btm_sec_cb.pairing_bda == p_dev_rec->bd_addr &&
3965 pairing_transport_matches) {
3966 log::debug("Disconnected while pairing process active handle:0x{:04x}",
3967 handle);
3968 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
3969 p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_LINK_KEY_KNOWN;
3970
3971 /* If the disconnection reason is REPEATED_ATTEMPTS,
3972 send this error message to complete callback function
3973 to display the error message of Repeated attempts.
3974 All others, send HCI_ERR_AUTH_FAILURE. */
3975 tHCI_STATUS status = HCI_ERR_AUTH_FAILURE;
3976 if (reason == HCI_ERR_REPEATED_ATTEMPTS) {
3977 status = HCI_ERR_REPEATED_ATTEMPTS;
3978 } else if (old_pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) {
3979 status = HCI_ERR_HOST_REJECT_SECURITY;
3980 } else {
3981 DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(p_dev_rec->bd_addr,
3982 IOT_CONF_KEY_GAP_DISC_AUTHFAIL_COUNT);
3983 }
3984
3985 NotifyBondingChange(*p_dev_rec, status);
3986
3987 p_dev_rec = btm_find_dev_by_handle(handle);
3988 if (p_dev_rec == nullptr) {
3989 // |btm_sec_cb.api.p_auth_complete_callback| may cause |p_dev_rec| to be
3990 // deallocated.
3991 log::warn("Device record was deallocated after user callback");
3992 return;
3993 }
3994 }
3995
3996 log::debug(
3997 "Disconnection complete device:{} name:{} state:{} reason:{} "
3998 "sec_req:{:x}",
3999 p_dev_rec->bd_addr, reinterpret_cast<char const*>(p_dev_rec->sec_bd_name),
4000 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
4001 hci_reason_code_text(reason), p_dev_rec->sec_rec.security_required);
4002
4003 // TODO Should this be gated by the transport check below ?
4004 btm_ble_update_mode_operation(HCI_ROLE_UNKNOWN, &p_dev_rec->bd_addr,
4005 HCI_SUCCESS);
4006 /* see sec_flags processing in btm_acl_removed */
4007
4008 if (transport == BT_TRANSPORT_LE) {
4009 p_dev_rec->ble_hci_handle = HCI_INVALID_HANDLE;
4010 p_dev_rec->sec_rec.sec_flags &=
4011 ~(BTM_SEC_LE_AUTHENTICATED | BTM_SEC_LE_ENCRYPTED |
4012 BTM_SEC_ROLE_SWITCHED);
4013 p_dev_rec->sec_rec.enc_key_size = 0;
4014 p_dev_rec->suggested_tx_octets = 0;
4015
4016 if ((p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN) == 0) {
4017 p_dev_rec->sec_rec.sec_flags &=
4018 ~(BTM_SEC_LE_LINK_KEY_AUTHED | BTM_SEC_LE_AUTHENTICATED);
4019 }
4020 } else {
4021 p_dev_rec->hci_handle = HCI_INVALID_HANDLE;
4022 p_dev_rec->sec_rec.sec_flags &=
4023 ~(BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED | BTM_SEC_ROLE_SWITCHED |
4024 BTM_SEC_16_DIGIT_PIN_AUTHED);
4025
4026 // Remove temporary key.
4027 if (p_dev_rec->sec_rec.bond_type == BOND_TYPE_TEMPORARY)
4028 p_dev_rec->sec_rec.sec_flags &= ~(BTM_SEC_LINK_KEY_KNOWN);
4029 }
4030
4031 /* Some devices hardcode sample LTK value from spec, instead of generating
4032 * one. Treat such devices as insecure, and remove such bonds on
4033 * disconnection.
4034 */
4035 if (is_sample_ltk(p_dev_rec->sec_rec.ble_keys.pltk)) {
4036 log::info("removing bond to device that used sample LTK: {}",
4037 p_dev_rec->bd_addr);
4038
4039 bta_dm_remove_device(p_dev_rec->bd_addr);
4040 return;
4041 }
4042
4043 if (p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_DISCONNECTING_BOTH) {
4044 log::debug("Waiting for other transport to disconnect current:{}",
4045 bt_transport_text(transport));
4046 p_dev_rec->sec_rec.sec_state = (transport == BT_TRANSPORT_LE)
4047 ? BTM_SEC_STATE_DISCONNECTING
4048 : BTM_SEC_STATE_DISCONNECTING_BLE;
4049 return;
4050 }
4051
4052 if (com::android::bluetooth::flags::
4053 cancel_pairing_only_on_disconnected_transport()) {
4054 if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE &&
4055 btm_sec_cb.pairing_bda == p_dev_rec->bd_addr &&
4056 !pairing_transport_matches) {
4057 log::debug("Disconnection on the other transport while pairing");
4058 return;
4059 }
4060
4061 if (p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_LE_ENCRYPTING &&
4062 transport != BT_TRANSPORT_LE) {
4063 log::debug("Disconnection on the other transport while encrypting LE");
4064 return;
4065 }
4066
4067 if ((p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_AUTHENTICATING ||
4068 p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_ENCRYPTING) &&
4069 transport != BT_TRANSPORT_BR_EDR) {
4070 log::debug(
4071 "Disconnection on the other transport while encrypting BR/EDR");
4072 return;
4073 }
4074 }
4075
4076 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_IDLE;
4077 p_dev_rec->sec_rec.security_required = BTM_SEC_NONE;
4078
4079 if (p_dev_rec->sec_rec.p_callback != nullptr) {
4080 tBTM_SEC_CALLBACK* p_callback = p_dev_rec->sec_rec.p_callback;
4081 /* when the peer device time out the authentication before
4082 we do, this call back must be reset here */
4083 p_dev_rec->sec_rec.p_callback = nullptr;
4084 (*p_callback)(p_dev_rec->bd_addr, transport, p_dev_rec->sec_rec.p_ref_data,
4085 BTM_ERR_PROCESSING);
4086 log::debug("Cleaned up pending security state device:{} transport:{}",
4087 p_dev_rec->bd_addr, bt_transport_text(transport));
4088 }
4089 }
4090
btm_sec_role_changed(tHCI_STATUS hci_status,const RawAddress & bd_addr,tHCI_ROLE new_role)4091 void btm_sec_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr,
4092 tHCI_ROLE new_role) {
4093 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
4094
4095 if (p_dev_rec == nullptr || hci_status != HCI_SUCCESS) {
4096 return;
4097 }
4098 if (new_role == HCI_ROLE_CENTRAL && btm_dev_authenticated(p_dev_rec) &&
4099 !btm_dev_encrypted(p_dev_rec)) {
4100 BTM_SetEncryption(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR, NULL, NULL,
4101 BTM_BLE_SEC_NONE);
4102 }
4103 }
4104
read_encryption_key_size_complete_after_key_refresh(uint8_t status,uint16_t handle,uint8_t key_size)4105 static void read_encryption_key_size_complete_after_key_refresh(
4106 uint8_t status, uint16_t handle, uint8_t key_size) {
4107 if (status == HCI_ERR_INSUFFCIENT_SECURITY) {
4108 /* If remote device stop the encryption before we call "Read Encryption Key
4109 * Size", we might receive Insufficient Security, which means that link is
4110 * no longer encrypted. */
4111 log::info("encryption stopped on link: 0x{:x}", handle);
4112 return;
4113 }
4114
4115 if (status != HCI_SUCCESS) {
4116 log::info("disconnecting, status: 0x{:x}", status);
4117 acl_disconnect_from_handle(handle, HCI_ERR_PEER_USER,
4118 "stack::btu_hcif Key size fail");
4119 return;
4120 }
4121
4122 if (key_size < MIN_KEY_SIZE) {
4123 log::error(
4124 "encryption key too short, disconnecting. handle: 0x{:x} key_size {}",
4125 handle, key_size);
4126
4127 acl_disconnect_from_handle(handle, HCI_ERR_HOST_REJECT_SECURITY,
4128 "stack::btu::btu_hcif::read_encryption_key_size_"
4129 "complete_after_key_refresh Key size too small");
4130 return;
4131 }
4132
4133 btm_sec_encrypt_change(handle, static_cast<tHCI_STATUS>(status),
4134 1 /* enc_enable */);
4135 }
4136
btm_sec_encryption_key_refresh_complete(uint16_t handle,tHCI_STATUS status)4137 void btm_sec_encryption_key_refresh_complete(uint16_t handle,
4138 tHCI_STATUS status) {
4139 if (status != HCI_SUCCESS || BTM_IsBleConnection(handle) ||
4140 // Skip encryption key size check when using set_min_encryption_key_size
4141 bluetooth::shim::GetController()->IsSupported(
4142 bluetooth::hci::OpCode::SET_MIN_ENCRYPTION_KEY_SIZE)) {
4143 btm_sec_encrypt_change(handle, static_cast<tHCI_STATUS>(status),
4144 (status == HCI_SUCCESS) ? 1 : 0);
4145 } else {
4146 btsnd_hcic_read_encryption_key_size(
4147 handle,
4148 base::Bind(&read_encryption_key_size_complete_after_key_refresh));
4149 }
4150 }
4151
4152 /** This function is called when a new connection link key is generated */
btm_sec_link_key_notification(const RawAddress & p_bda,const Octet16 & link_key,uint8_t key_type)4153 void btm_sec_link_key_notification(const RawAddress& p_bda,
4154 const Octet16& link_key, uint8_t key_type) {
4155 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(p_bda);
4156 bool we_are_bonding = false;
4157 bool ltk_derived_lk = false;
4158
4159 log::debug("New link key generated device:{} key_type:{}", p_bda, key_type);
4160
4161 if ((key_type >= BTM_LTK_DERIVED_LKEY_OFFSET + BTM_LKEY_TYPE_COMBINATION) &&
4162 (key_type <=
4163 BTM_LTK_DERIVED_LKEY_OFFSET + BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
4164 ltk_derived_lk = true;
4165 key_type -= BTM_LTK_DERIVED_LKEY_OFFSET;
4166 }
4167 /* If connection was made to do bonding restore link security if changed */
4168 btm_restore_mode();
4169
4170 if (key_type != BTM_LKEY_TYPE_CHANGED_COMB)
4171 p_dev_rec->sec_rec.link_key_type = key_type;
4172
4173 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_LINK_KEY_KNOWN;
4174
4175 /*
4176 * Until this point in time, we do not know if MITM was enabled, hence we
4177 * add the extended security flag here.
4178 */
4179 if (p_dev_rec->sec_rec.pin_code_length >= 16 ||
4180 p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_AUTH_COMB ||
4181 p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) {
4182 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_LINK_KEY_AUTHED;
4183 p_dev_rec->sec_rec.sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED;
4184 }
4185
4186 /* BR/EDR connection, update the encryption key size to be 16 as always */
4187 p_dev_rec->sec_rec.enc_key_size = 16;
4188 p_dev_rec->sec_rec.link_key = link_key;
4189
4190 if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
4191 (btm_sec_cb.pairing_bda == p_bda)) {
4192 if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
4193 we_are_bonding = true;
4194 else
4195 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
4196 }
4197
4198 /* save LTK derived LK no matter what */
4199 if (ltk_derived_lk) {
4200 if (btm_sec_cb.api.p_link_key_callback) {
4201 log::verbose("Save LTK derived LK (key_type = {})",
4202 p_dev_rec->sec_rec.link_key_type);
4203 (*btm_sec_cb.api.p_link_key_callback)(
4204 p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, link_key,
4205 p_dev_rec->sec_rec.link_key_type, true /* is_ctkd */);
4206 }
4207 } else {
4208 if ((p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256) ||
4209 (p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
4210 p_dev_rec->sec_rec.new_encryption_key_is_p256 = true;
4211 log::verbose("set new_encr_key_256 to {}",
4212 p_dev_rec->sec_rec.new_encryption_key_is_p256);
4213 }
4214 }
4215
4216 if (com::android::bluetooth::flags::bluffs_mitigation() &&
4217 p_dev_rec->sec_rec.is_bond_type_persistent() &&
4218 (p_dev_rec->is_device_type_br_edr() ||
4219 p_dev_rec->is_device_type_dual_mode())) {
4220 btm_sec_store_device_sc_support(p_dev_rec->get_br_edr_hci_handle(),
4221 p_dev_rec->SupportsSecureConnections());
4222 }
4223
4224 /* If name is not known at this point delay calling callback until the name is
4225 */
4226 /* resolved. Unless it is a HID Device and we really need to send all link
4227 * keys. */
4228 if ((!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) &&
4229 ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) !=
4230 BTM_COD_MAJOR_PERIPHERAL)) &&
4231 !ltk_derived_lk) {
4232 log::verbose("Delayed BDA: {}, Type: {}", p_bda, key_type);
4233
4234 p_dev_rec->sec_rec.link_key_not_sent = true;
4235
4236 /* If it is for bonding nothing else will follow, so we need to start name
4237 * resolution */
4238 if (we_are_bonding) {
4239 bluetooth::shim::ACL_RemoteNameRequest(p_bda, HCI_PAGE_SCAN_REP_MODE_R1,
4240 HCI_MANDATARY_PAGE_SCAN_MODE, 0);
4241 }
4242
4243 log::verbose("rmt_io_caps:{}, sec_flags:x{:x}, dev_class[1]:x{:02x}",
4244 p_dev_rec->sec_rec.rmt_io_caps, p_dev_rec->sec_rec.sec_flags,
4245 p_dev_rec->dev_class[1]);
4246 return;
4247 }
4248
4249 /* We will save link key only if the user authorized it - BTE report link key in
4250 * all cases */
4251 #ifdef BRCM_NONE_BTE
4252 if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_AUTHED)
4253 #endif
4254 {
4255 if (btm_sec_cb.api.p_link_key_callback) {
4256 if (ltk_derived_lk) {
4257 log::verbose(
4258 "btm_sec_link_key_notification() LTK derived LK is saved already "
4259 "(key_type = {})",
4260 p_dev_rec->sec_rec.link_key_type);
4261 } else {
4262 (*btm_sec_cb.api.p_link_key_callback)(
4263 p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, link_key,
4264 p_dev_rec->sec_rec.link_key_type, false /* is_ctkd */);
4265 }
4266 }
4267 }
4268 }
4269
4270 /*******************************************************************************
4271 *
4272 * Function btm_sec_link_key_request
4273 *
4274 * Description This function is called when controller requests link key
4275 *
4276 * Returns Pointer to the record or NULL
4277 *
4278 ******************************************************************************/
btm_sec_link_key_request(const RawAddress bda)4279 void btm_sec_link_key_request(const RawAddress bda) {
4280 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(bda);
4281
4282 log::verbose("bda: {}", bda);
4283 if (!concurrentPeerAuthIsEnabled()) {
4284 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_AUTHENTICATING;
4285 }
4286
4287 if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_WAIT_PIN_REQ) &&
4288 (btm_sec_cb.collision_start_time != 0) &&
4289 (btm_sec_cb.p_collided_dev_rec->bd_addr == bda)) {
4290 log::verbose(
4291 "btm_sec_link_key_request() rejecting link key req State: {} "
4292 "START_TIMEOUT : {}",
4293 btm_sec_cb.pairing_state, btm_sec_cb.collision_start_time);
4294 btsnd_hcic_link_key_neg_reply(bda);
4295 return;
4296 }
4297 if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN) {
4298 btsnd_hcic_link_key_req_reply(bda, p_dev_rec->sec_rec.link_key);
4299 return;
4300 }
4301
4302 /* Notify L2CAP to increase timeout */
4303 l2c_pin_code_request(bda);
4304
4305 /* The link key is not in the database and it is not known to the manager */
4306 btsnd_hcic_link_key_neg_reply(bda);
4307 }
4308
4309 /*******************************************************************************
4310 *
4311 * Function btm_sec_pairing_timeout
4312 *
4313 * Description This function is called when host does not provide PIN
4314 * within requested time
4315 *
4316 * Returns Pointer to the TLE struct
4317 *
4318 ******************************************************************************/
btm_sec_pairing_timeout(void *)4319 static void btm_sec_pairing_timeout(void* /* data */) {
4320 tBTM_SEC_CB* p_cb = &btm_sec_cb;
4321 tBTM_SEC_DEV_REC* p_dev_rec;
4322 tBTM_AUTH_REQ auth_req = (btm_sec_cb.devcb.loc_io_caps == BTM_IO_CAP_NONE)
4323 ? BTM_AUTH_AP_NO
4324 : BTM_AUTH_AP_YES;
4325 BD_NAME name;
4326
4327 p_dev_rec = btm_find_dev(p_cb->pairing_bda);
4328
4329 log::verbose("State: {} Flags: {}",
4330 tBTM_SEC_CB::btm_pair_state_descr(p_cb->pairing_state),
4331 p_cb->pairing_flags);
4332
4333 switch (p_cb->pairing_state) {
4334 case BTM_PAIR_STATE_WAIT_PIN_REQ:
4335 btm_sec_bond_cancel_complete();
4336 break;
4337
4338 case BTM_PAIR_STATE_WAIT_LOCAL_PIN:
4339 if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_PRE_FETCH_PIN) == 0)
4340 btsnd_hcic_pin_code_neg_reply(p_cb->pairing_bda);
4341 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
4342 /* We need to notify the UI that no longer need the PIN */
4343 if (btm_sec_cb.api.p_auth_complete_callback) {
4344 if (p_dev_rec == NULL) {
4345 name[0] = 0;
4346 (*btm_sec_cb.api.p_auth_complete_callback)(
4347 p_cb->pairing_bda, kDevClassEmpty, name, HCI_ERR_CONNECTION_TOUT);
4348 } else
4349 NotifyBondingChange(*p_dev_rec, HCI_ERR_CONNECTION_TOUT);
4350 }
4351 break;
4352
4353 case BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM:
4354 btsnd_hcic_user_conf_reply(p_cb->pairing_bda, false);
4355 /* btm_sec_cb.change_pairing_state (BTM_PAIR_STATE_IDLE); */
4356 break;
4357
4358 case BTM_PAIR_STATE_KEY_ENTRY:
4359 if (btm_sec_cb.devcb.loc_io_caps != BTM_IO_CAP_NONE) {
4360 btsnd_hcic_user_passkey_neg_reply(p_cb->pairing_bda);
4361 } else {
4362 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
4363 }
4364 break;
4365
4366 case BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS:
4367 // TODO(optedoblivion): Inject OOB_DATA_PRESENT Flag
4368 btsnd_hcic_io_cap_req_reply(p_cb->pairing_bda,
4369 btm_sec_cb.devcb.loc_io_caps, BTM_OOB_NONE,
4370 auth_req);
4371 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
4372 break;
4373
4374 case BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP:
4375 btsnd_hcic_rem_oob_neg_reply(p_cb->pairing_bda);
4376 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
4377 break;
4378
4379 case BTM_PAIR_STATE_WAIT_DISCONNECT:
4380 /* simple pairing failed. Started a 1-sec timer at simple pairing
4381 * complete.
4382 * now it's time to tear down the ACL link*/
4383 if (p_dev_rec == NULL) {
4384 log::error("BTM_PAIR_STATE_WAIT_DISCONNECT unknown BDA: {}",
4385 p_cb->pairing_bda);
4386 break;
4387 }
4388 btm_sec_send_hci_disconnect(
4389 p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle,
4390 "stack::btm::btm_sec::btm_sec_pairing_timeout");
4391 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
4392 break;
4393
4394 case BTM_PAIR_STATE_WAIT_AUTH_COMPLETE:
4395 case BTM_PAIR_STATE_GET_REM_NAME:
4396 /* We need to notify the UI that timeout has happened while waiting for
4397 * authentication*/
4398 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
4399 if (btm_sec_cb.api.p_auth_complete_callback) {
4400 if (p_dev_rec == NULL) {
4401 name[0] = 0;
4402 (*btm_sec_cb.api.p_auth_complete_callback)(
4403 p_cb->pairing_bda, kDevClassEmpty, name, HCI_ERR_CONNECTION_TOUT);
4404 } else {
4405 NotifyBondingChange(*p_dev_rec, HCI_ERR_CONNECTION_TOUT);
4406 }
4407 }
4408 break;
4409
4410 default:
4411 log::warn("not processed state: {}",
4412 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
4413 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
4414 break;
4415 }
4416 }
4417
4418 /*******************************************************************************
4419 *
4420 * Function btm_sec_pin_code_request
4421 *
4422 * Description This function is called when controller requests PIN code
4423 *
4424 * Returns Pointer to the record or NULL
4425 *
4426 ******************************************************************************/
btm_sec_pin_code_request(const RawAddress p_bda)4427 void btm_sec_pin_code_request(const RawAddress p_bda) {
4428 tBTM_SEC_DEV_REC* p_dev_rec;
4429 tBTM_SEC_CB* p_cb = &btm_sec_cb;
4430
4431 /* Tell L2CAP that there was a PIN code request, */
4432 /* it may need to stretch timeouts */
4433 l2c_pin_code_request(p_bda);
4434
4435 log::debug("Controller requests PIN code device:{} state:{}", p_bda,
4436 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
4437
4438 RawAddress local_bd_addr = bluetooth::ToRawAddress(
4439 bluetooth::shim::GetController()->GetMacAddress());
4440 if (p_bda == local_bd_addr) {
4441 btsnd_hcic_pin_code_neg_reply(p_bda);
4442 return;
4443 }
4444
4445 if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) {
4446 if ((p_bda == btm_sec_cb.pairing_bda) &&
4447 (btm_sec_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE)) {
4448 btsnd_hcic_pin_code_neg_reply(p_bda);
4449 return;
4450 } else if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_WAIT_PIN_REQ) ||
4451 p_bda != btm_sec_cb.pairing_bda) {
4452 log::warn("btm_sec_pin_code_request() rejected - state: {}",
4453 tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
4454 btsnd_hcic_pin_code_neg_reply(p_bda);
4455 return;
4456 }
4457 }
4458
4459 p_dev_rec = btm_find_or_alloc_dev(p_bda);
4460 /* received PIN code request. must be non-sm4 */
4461 p_dev_rec->sm4 = BTM_SM4_KNOWN;
4462
4463 if (btm_sec_cb.pairing_state == BTM_PAIR_STATE_IDLE) {
4464 btm_sec_cb.pairing_bda = p_bda;
4465
4466 btm_sec_cb.pairing_flags = BTM_PAIR_FLAGS_PEER_STARTED_DD;
4467 }
4468
4469 if (!p_cb->pairing_disabled && (p_cb->cfg.pin_type == HCI_PIN_TYPE_FIXED)) {
4470 log::verbose("btm_sec_pin_code_request fixed pin replying");
4471 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
4472 btsnd_hcic_pin_code_req_reply(p_bda, p_cb->cfg.pin_code_len,
4473 p_cb->cfg.pin_code);
4474 return;
4475 }
4476
4477 /* Use the connecting device's CoD for the connection */
4478 if ((p_bda == p_cb->connecting_bda) &&
4479 (p_cb->connecting_dc != kDevClassEmpty))
4480 p_dev_rec->dev_class = p_cb->connecting_dc;
4481
4482 /* We could have started connection after asking user for the PIN code */
4483 if (btm_sec_cb.pin_code_len != 0) {
4484 log::verbose("btm_sec_pin_code_request bonding sending reply");
4485 btsnd_hcic_pin_code_req_reply(p_bda, btm_sec_cb.pin_code_len,
4486 p_cb->pin_code);
4487
4488 /* Mark that we forwarded received from the user PIN code */
4489 btm_sec_cb.pin_code_len = 0;
4490
4491 /* We can change mode back right away, that other connection being
4492 * established */
4493 /* is not forced to be secure - found a FW issue, so we can not do this
4494 btm_restore_mode(); */
4495
4496 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
4497 }
4498
4499 /* If pairing disabled OR (no PIN callback and not bonding) */
4500 /* OR we could not allocate entry in the database reject pairing request */
4501 else if (p_cb->pairing_disabled ||
4502 (p_cb->api.p_pin_callback == NULL)
4503
4504 /* OR Microsoft keyboard can for some reason try to establish
4505 * connection
4506 */
4507 /* the only thing we can do here is to shut it up. Normally we will
4508 be originator */
4509 /* for keyboard bonding */
4510 || (!p_dev_rec->IsLocallyInitiated() &&
4511 ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) ==
4512 BTM_COD_MAJOR_PERIPHERAL) &&
4513 (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD))) {
4514 log::warn(
4515 "btm_sec_pin_code_request(): Pairing disabled:{}; PIN callback:{}, Dev "
4516 "Rec:{}!",
4517 p_cb->pairing_disabled, fmt::ptr(p_cb->api.p_pin_callback),
4518 fmt::ptr(p_dev_rec));
4519
4520 btsnd_hcic_pin_code_neg_reply(p_bda);
4521 }
4522 /* Notify upper layer of PIN request and start expiration timer */
4523 else {
4524 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_PIN);
4525 /* Pin code request can not come at the same time as connection request */
4526 p_cb->connecting_bda = p_bda;
4527 p_cb->connecting_dc = p_dev_rec->dev_class;
4528
4529 /* Check if the name is known */
4530 /* Even if name is not known we might not be able to get one */
4531 /* this is the case when we are already getting something from the */
4532 /* device, so HCI level is flow controlled */
4533 /* Also cannot send remote name request while paging, i.e. connection is not
4534 * completed */
4535 if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) {
4536 log::verbose("btm_sec_pin_code_request going for callback");
4537
4538 btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
4539 if (p_cb->api.p_pin_callback) {
4540 (*p_cb->api.p_pin_callback)(
4541 p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
4542 (p_dev_rec->sec_rec.required_security_flags_for_pairing &
4543 BTM_SEC_IN_MIN_16_DIGIT_PIN));
4544 }
4545 } else {
4546 log::verbose("btm_sec_pin_code_request going for remote name");
4547
4548 /* We received PIN code request for the device with unknown name */
4549 /* it is not user friendly just to ask for the PIN without name */
4550 /* try to get name at first */
4551 bluetooth::shim::ACL_RemoteNameRequest(p_dev_rec->bd_addr,
4552 HCI_PAGE_SCAN_REP_MODE_R1,
4553 HCI_MANDATARY_PAGE_SCAN_MODE, 0);
4554 }
4555 }
4556
4557 return;
4558 }
4559
4560 /*******************************************************************************
4561 *
4562 * Function btm_sec_update_clock_offset
4563 *
4564 * Description This function is called to update clock offset
4565 *
4566 * Returns void
4567 *
4568 ******************************************************************************/
btm_sec_update_clock_offset(uint16_t handle,uint16_t clock_offset)4569 void btm_sec_update_clock_offset(uint16_t handle, uint16_t clock_offset) {
4570 tBTM_SEC_DEV_REC* p_dev_rec;
4571 tBTM_INQ_INFO* p_inq_info;
4572
4573 p_dev_rec = btm_find_dev_by_handle(handle);
4574 if (p_dev_rec == NULL) return;
4575
4576 p_dev_rec->clock_offset = clock_offset | BTM_CLOCK_OFFSET_VALID;
4577
4578 p_inq_info = BTM_InqDbRead(p_dev_rec->bd_addr);
4579 if (p_inq_info == NULL) return;
4580
4581 p_inq_info->results.clock_offset = clock_offset | BTM_CLOCK_OFFSET_VALID;
4582 }
4583
4584 /******************************************************************
4585 * S T A T I C F U N C T I O N S
4586 ******************************************************************/
4587
4588 /*******************************************************************************
4589 *
4590 * Function btm_sec_execute_procedure
4591 *
4592 * Description This function is called to start required security
4593 * procedure. There is a case when multiplexing protocol
4594 * calls this function on the originating side, connection to
4595 * the peer will not be established. This function in this
4596 * case performs only authorization.
4597 *
4598 * Returns BTM_SUCCESS - permission is granted
4599 * BTM_CMD_STARTED - in process
4600 * BTM_NO_RESOURCES - permission declined
4601 *
4602 ******************************************************************************/
btm_sec_execute_procedure(tBTM_SEC_DEV_REC * p_dev_rec)4603 tBTM_STATUS btm_sec_execute_procedure(tBTM_SEC_DEV_REC* p_dev_rec) {
4604 log::assert_that(p_dev_rec != nullptr, "assert failed: p_dev_rec != nullptr");
4605 log::debug(
4606 "security_required:0x{:x} security_flags:0x{:x} security_state:{}[{}]",
4607 p_dev_rec->sec_rec.security_required, p_dev_rec->sec_rec.sec_flags,
4608 security_state_text(
4609 static_cast<tSECURITY_STATE>(p_dev_rec->sec_rec.sec_state)),
4610 p_dev_rec->sec_rec.sec_state);
4611
4612 if (p_dev_rec->sec_rec.sec_state != BTM_SEC_STATE_IDLE &&
4613 p_dev_rec->sec_rec.sec_state != BTM_SEC_STATE_LE_ENCRYPTING) {
4614 log::info("No immediate action taken in busy state: {}",
4615 security_state_text(p_dev_rec->sec_rec.sec_state));
4616 return (BTM_CMD_STARTED);
4617 }
4618
4619 /* If any security is required, get the name first */
4620 if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) &&
4621 (p_dev_rec->hci_handle != HCI_INVALID_HANDLE)) {
4622 log::debug("Security Manager: Start get name");
4623 if (!btm_sec_start_get_name(p_dev_rec)) {
4624 log::warn("Unable to start remote name request");
4625 return (BTM_NO_RESOURCES);
4626 }
4627 return (BTM_CMD_STARTED);
4628 }
4629
4630 /* If connection is not authenticated and authentication is required */
4631 /* start authentication and return PENDING to the caller */
4632 if (p_dev_rec->hci_handle != HCI_INVALID_HANDLE) {
4633 bool start_auth = false;
4634
4635 // Check link status of BR/EDR
4636 if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_AUTHENTICATED)) {
4637 if (p_dev_rec->IsLocallyInitiated()) {
4638 if (p_dev_rec->sec_rec.security_required &
4639 (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) {
4640 log::debug("Outgoing authentication/encryption Required");
4641 start_auth = true;
4642 }
4643 } else {
4644 if (p_dev_rec->sec_rec.security_required &
4645 (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) {
4646 log::debug("Incoming authentication/encryption Required");
4647 start_auth = true;
4648 }
4649 }
4650 }
4651
4652 if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_16_DIGIT_PIN_AUTHED)) {
4653 /*
4654 * We rely on BTM_SEC_16_DIGIT_PIN_AUTHED being set if MITM is in use,
4655 * as 16 DIGIT is only needed if MITM is not used. Unfortunately, the
4656 * BTM_SEC_AUTHENTICATED is used for both MITM and non-MITM
4657 * authenticated connections, hence we cannot distinguish here.
4658 */
4659 if (!p_dev_rec->IsLocallyInitiated()) {
4660 if (p_dev_rec->sec_rec.security_required &
4661 BTM_SEC_IN_MIN_16_DIGIT_PIN) {
4662 log::debug("BTM_SEC_IN_MIN_16_DIGIT_PIN Required");
4663 start_auth = true;
4664 }
4665 }
4666 }
4667
4668 if (start_auth) {
4669 log::debug("Security Manager: Start authentication");
4670
4671 /*
4672 * If we do have a link-key, but we end up here because we need an
4673 * upgrade, then clear the link-key known and authenticated flag before
4674 * restarting authentication.
4675 * WARNING: If the controller has link-key, it is optional and
4676 * recommended for the controller to send a Link_Key_Request.
4677 * In case we need an upgrade, the only alternative would be to delete
4678 * the existing link-key. That could lead to very bad user experience
4679 * or even IOP issues, if a reconnect causes a new connection that
4680 * requires an upgrade.
4681 */
4682 if ((p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN) &&
4683 (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_16_DIGIT_PIN_AUTHED) &&
4684 (!p_dev_rec->IsLocallyInitiated() &&
4685 (p_dev_rec->sec_rec.security_required &
4686 BTM_SEC_IN_MIN_16_DIGIT_PIN)))) {
4687 p_dev_rec->sec_rec.sec_flags &=
4688 ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED |
4689 BTM_SEC_AUTHENTICATED);
4690 }
4691
4692 btm_sec_wait_and_start_authentication(p_dev_rec);
4693 return (BTM_CMD_STARTED);
4694 }
4695 }
4696
4697 /* If connection is not encrypted and encryption is required */
4698 /* start encryption and return PENDING to the caller */
4699 if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_ENCRYPTED) &&
4700 ((p_dev_rec->IsLocallyInitiated() &&
4701 (p_dev_rec->sec_rec.security_required & BTM_SEC_OUT_ENCRYPT)) ||
4702 (!p_dev_rec->IsLocallyInitiated() &&
4703 (p_dev_rec->sec_rec.security_required & BTM_SEC_IN_ENCRYPT))) &&
4704 (p_dev_rec->hci_handle != HCI_INVALID_HANDLE)) {
4705 log::verbose("Security Manager: Start encryption");
4706
4707 btsnd_hcic_set_conn_encrypt(p_dev_rec->hci_handle, true);
4708 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_ENCRYPTING;
4709 return (BTM_CMD_STARTED);
4710 } else {
4711 log::debug("Encryption not required");
4712 }
4713
4714 if ((p_dev_rec->sec_rec.security_required & BTM_SEC_MODE4_LEVEL4) &&
4715 (p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
4716 log::verbose(
4717 "Security Manager: SC only service, but link key type is 0x{:02x} "
4718 "-security failure",
4719 p_dev_rec->sec_rec.link_key_type);
4720 return (BTM_FAILED_ON_SECURITY);
4721 }
4722
4723 if (access_secure_service_from_temp_bond(
4724 p_dev_rec, p_dev_rec->IsLocallyInitiated(),
4725 p_dev_rec->sec_rec.security_required)) {
4726 log::error(
4727 "Trying to access a secure service from a temp bonding, rejecting");
4728 return (BTM_FAILED_ON_SECURITY);
4729 }
4730
4731 /* All required security procedures already established */
4732 p_dev_rec->sec_rec.security_required &=
4733 ~(BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_IN_AUTHENTICATE |
4734 BTM_SEC_OUT_ENCRYPT | BTM_SEC_IN_ENCRYPT);
4735
4736 log::verbose("Security Manager: access granted");
4737
4738 return (BTM_SUCCESS);
4739 }
4740
4741 /*******************************************************************************
4742 *
4743 * Function btm_sec_start_get_name
4744 *
4745 * Description This function is called to start get name procedure
4746 *
4747 * Returns true if started
4748 *
4749 ******************************************************************************/
btm_sec_start_get_name(tBTM_SEC_DEV_REC * p_dev_rec)4750 static bool btm_sec_start_get_name(tBTM_SEC_DEV_REC* p_dev_rec) {
4751 if (!BTM_IsDeviceUp()) return false;
4752
4753 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_GETTING_NAME;
4754
4755 /* 0 and NULL are as timeout and callback params because they are not used in
4756 * security get name case */
4757 bluetooth::shim::ACL_RemoteNameRequest(p_dev_rec->bd_addr,
4758 HCI_PAGE_SCAN_REP_MODE_R1,
4759 HCI_MANDATARY_PAGE_SCAN_MODE, 0);
4760 return true;
4761 }
4762
4763 /*******************************************************************************
4764 *
4765 * Function btm_sec_wait_and_start_authentication
4766 *
4767 * Description This function is called to add an alarm to wait and start
4768 * authentication
4769 *
4770 ******************************************************************************/
btm_sec_wait_and_start_authentication(tBTM_SEC_DEV_REC * p_dev_rec)4771 static void btm_sec_wait_and_start_authentication(tBTM_SEC_DEV_REC* p_dev_rec) {
4772 auto addr = new RawAddress(p_dev_rec->bd_addr);
4773 int32_t delay_auth =
4774 osi_property_get_int32("bluetooth.btm.sec.delay_auth_ms.value", 0);
4775
4776 /* Overwrite the system-wide authentication delay if device-specific
4777 * interoperability delay is needed. */
4778 if (interop_match_addr(INTEROP_DELAY_AUTH, addr)) {
4779 delay_auth = BTM_SEC_START_AUTH_DELAY;
4780 }
4781
4782 bt_status_t status = do_in_main_thread_delayed(
4783 FROM_HERE, base::Bind(&btm_sec_auth_timer_timeout, addr),
4784 std::chrono::milliseconds(delay_auth));
4785 if (status != BT_STATUS_SUCCESS) {
4786 log::error("do_in_main_thread_delayed failed. directly calling");
4787 btm_sec_auth_timer_timeout(addr);
4788 }
4789 }
4790
4791 /*******************************************************************************
4792 *
4793 * Function btm_sec_auth_timer_timeout
4794 *
4795 * Description called after wait timeout to request authentication
4796 *
4797 ******************************************************************************/
btm_sec_auth_timer_timeout(void * data)4798 static void btm_sec_auth_timer_timeout(void* data) {
4799 RawAddress* p_addr = (RawAddress*)data;
4800 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(*p_addr);
4801 delete p_addr;
4802 if (p_dev_rec == NULL) {
4803 log::info("invalid device or not found");
4804 } else if (btm_dev_authenticated(p_dev_rec)) {
4805 log::info("device is already authenticated");
4806 if (p_dev_rec->sec_rec.p_callback) {
4807 (*p_dev_rec->sec_rec.p_callback)(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR,
4808 p_dev_rec->sec_rec.p_ref_data,
4809 BTM_SUCCESS);
4810 }
4811 } else if (p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_AUTHENTICATING) {
4812 log::info("device is in the process of authenticating");
4813 } else {
4814 log::info("starting authentication");
4815 p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_AUTHENTICATING;
4816 btsnd_hcic_auth_request(p_dev_rec->hci_handle);
4817 }
4818 }
4819
4820 /*******************************************************************************
4821 *
4822 * Function btm_sec_collision_timeout
4823 *
4824 * Description Encryption could not start because of the collision
4825 * try to do it again
4826 *
4827 * Returns Pointer to the TLE struct
4828 *
4829 ******************************************************************************/
btm_sec_collision_timeout(void *)4830 static void btm_sec_collision_timeout(void* /* data */) {
4831 log::verbose("restaring security process after collision");
4832
4833 tBTM_STATUS status = btm_sec_execute_procedure(btm_sec_cb.p_collided_dev_rec);
4834
4835 /* If result is pending reply from the user or from the device is pending */
4836 if (status != BTM_CMD_STARTED) {
4837 /* There is no next procedure or start of procedure failed, notify the
4838 * waiting layer */
4839 btm_sec_dev_rec_cback_event(btm_sec_cb.p_collided_dev_rec, status, false);
4840 }
4841 }
4842
4843 /*******************************************************************************
4844 *
4845 * Function btm_send_link_key_notif
4846 *
4847 * Description Call the link key callback.
4848 *
4849 * Returns void
4850 *
4851 ******************************************************************************/
btm_send_link_key_notif(tBTM_SEC_DEV_REC * p_dev_rec)4852 static void btm_send_link_key_notif(tBTM_SEC_DEV_REC* p_dev_rec) {
4853 if (btm_sec_cb.api.p_link_key_callback)
4854 (*btm_sec_cb.api.p_link_key_callback)(
4855 p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
4856 p_dev_rec->sec_rec.link_key, p_dev_rec->sec_rec.link_key_type, false);
4857 }
4858
4859 /*******************************************************************************
4860 *
4861 * Function btm_restore_mode
4862 *
4863 * Description This function returns the security mode to previous setting
4864 * if it was changed during bonding.
4865 *
4866 *
4867 * Parameters: void
4868 *
4869 ******************************************************************************/
btm_restore_mode(void)4870 static void btm_restore_mode(void) {
4871 if (btm_sec_cb.security_mode_changed) {
4872 btm_sec_cb.security_mode_changed = false;
4873 btsnd_hcic_write_auth_enable(false);
4874 }
4875
4876 if (btm_sec_cb.pin_type_changed) {
4877 btm_sec_cb.pin_type_changed = false;
4878 btsnd_hcic_write_pin_type(btm_sec_cb.cfg.pin_type);
4879 }
4880 }
4881
4882 /*******************************************************************************
4883 *
4884 * Function change_pairing_state
4885 *
4886 * Description This function is called to change pairing state
4887 *
4888 ******************************************************************************/
change_pairing_state(tBTM_PAIRING_STATE new_state)4889 void tBTM_SEC_CB::change_pairing_state(tBTM_PAIRING_STATE new_state) {
4890 tBTM_PAIRING_STATE old_state = pairing_state;
4891
4892 log::debug("Pairing state changed {} => {} pairing_flags:0x{:x}",
4893 tBTM_SEC_CB::btm_pair_state_descr(pairing_state),
4894 tBTM_SEC_CB::btm_pair_state_descr(new_state), pairing_flags);
4895
4896 if (pairing_state != new_state) {
4897 BTM_LogHistory(
4898 kBtmLogTag, btm_sec_cb.pairing_bda, "Pairing state changed",
4899 base::StringPrintf("%s => %s",
4900 tBTM_SEC_CB::btm_pair_state_descr(pairing_state),
4901 tBTM_SEC_CB::btm_pair_state_descr(new_state)));
4902 }
4903 pairing_state = new_state;
4904
4905 if (new_state == BTM_PAIR_STATE_IDLE) {
4906 alarm_cancel(pairing_timer);
4907
4908 pairing_flags = 0;
4909 pin_code_len = 0;
4910
4911 /* Make sure the the lcb shows we are not bonding */
4912 l2cu_update_lcb_4_bonding(pairing_bda, false);
4913
4914 btm_restore_mode();
4915 btm_sec_check_pending_reqs();
4916
4917 pairing_bda = RawAddress::kAny;
4918 } else {
4919 /* If transitioning out of idle, mark the lcb as bonding */
4920 if (old_state == BTM_PAIR_STATE_IDLE)
4921 l2cu_update_lcb_4_bonding(pairing_bda, true);
4922
4923 alarm_set_on_mloop(btm_sec_cb.pairing_timer, BTM_SEC_TIMEOUT_VALUE * 1000,
4924 btm_sec_pairing_timeout, NULL);
4925 }
4926 }
4927
4928 /*******************************************************************************
4929 *
4930 * Function btm_pair_state_descr
4931 *
4932 * Description Return state description for tracing
4933 *
4934 ******************************************************************************/
btm_pair_state_descr(tBTM_PAIRING_STATE state)4935 const char* tBTM_SEC_CB::btm_pair_state_descr(tBTM_PAIRING_STATE state) {
4936 switch (state) {
4937 case BTM_PAIR_STATE_IDLE:
4938 return ("IDLE");
4939 case BTM_PAIR_STATE_GET_REM_NAME:
4940 return ("GET_REM_NAME");
4941 case BTM_PAIR_STATE_WAIT_PIN_REQ:
4942 return ("WAIT_PIN_REQ");
4943 case BTM_PAIR_STATE_WAIT_LOCAL_PIN:
4944 return ("WAIT_LOCAL_PIN");
4945 case BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM:
4946 return ("WAIT_NUM_CONFIRM");
4947 case BTM_PAIR_STATE_KEY_ENTRY:
4948 return ("KEY_ENTRY");
4949 case BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP:
4950 return ("WAIT_LOCAL_OOB_RSP");
4951 case BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS:
4952 return ("WAIT_LOCAL_IOCAPS");
4953 case BTM_PAIR_STATE_INCOMING_SSP:
4954 return ("INCOMING_SSP");
4955 case BTM_PAIR_STATE_WAIT_AUTH_COMPLETE:
4956 return ("WAIT_AUTH_COMPLETE");
4957 case BTM_PAIR_STATE_WAIT_DISCONNECT:
4958 return ("WAIT_DISCONNECT");
4959 }
4960
4961 return ("???");
4962 }
4963
4964 /*******************************************************************************
4965 *
4966 * Function btm_sec_dev_rec_cback_event
4967 *
4968 * Description This function calls the callback function with the given
4969 * result and clear the callback function.
4970 *
4971 * Parameters: void
4972 *
4973 ******************************************************************************/
btm_sec_dev_rec_cback_event(tBTM_SEC_DEV_REC * p_dev_rec,tBTM_STATUS btm_status,bool is_le_transport)4974 void btm_sec_dev_rec_cback_event(tBTM_SEC_DEV_REC* p_dev_rec,
4975 tBTM_STATUS btm_status, bool is_le_transport) {
4976 log::assert_that(p_dev_rec != nullptr, "assert failed: p_dev_rec != nullptr");
4977 log::debug("transport={}, btm_status={}", is_le_transport ? "le" : "classic",
4978 btm_status_text(btm_status));
4979
4980 tBTM_SEC_CALLBACK* p_callback = p_dev_rec->sec_rec.p_callback;
4981 p_dev_rec->sec_rec.p_callback = NULL;
4982 if (p_callback != nullptr) {
4983 if (is_le_transport) {
4984 (*p_callback)(p_dev_rec->ble.pseudo_addr, BT_TRANSPORT_LE,
4985 p_dev_rec->sec_rec.p_ref_data, btm_status);
4986 } else {
4987 (*p_callback)(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR,
4988 p_dev_rec->sec_rec.p_ref_data, btm_status);
4989 }
4990 }
4991
4992 btm_sec_check_pending_reqs();
4993 }
4994
btm_sec_cr_loc_oob_data_cback_event(const RawAddress & address,tSMP_LOC_OOB_DATA loc_oob_data)4995 void btm_sec_cr_loc_oob_data_cback_event(const RawAddress& address,
4996 tSMP_LOC_OOB_DATA loc_oob_data) {
4997 tBTM_LE_EVT_DATA evt_data = {
4998 .local_oob_data = loc_oob_data,
4999 };
5000 if (btm_sec_cb.api.p_le_callback) {
5001 (*btm_sec_cb.api.p_le_callback)(BTM_LE_SC_LOC_OOB_EVT, address, &evt_data);
5002 }
5003 }
5004
5005 /*******************************************************************************
5006 *
5007 * Function btm_sec_queue_mx_request
5008 *
5009 * Description Return state description for tracing
5010 *
5011 ******************************************************************************/
btm_sec_queue_mx_request(const RawAddress & bd_addr,uint16_t psm,bool is_orig,uint16_t security_required,tBTM_SEC_CALLBACK * p_callback,void * p_ref_data)5012 static bool btm_sec_queue_mx_request(const RawAddress& bd_addr, uint16_t psm,
5013 bool is_orig, uint16_t security_required,
5014 tBTM_SEC_CALLBACK* p_callback,
5015 void* p_ref_data) {
5016 tBTM_SEC_QUEUE_ENTRY* p_e =
5017 (tBTM_SEC_QUEUE_ENTRY*)osi_malloc(sizeof(tBTM_SEC_QUEUE_ENTRY));
5018
5019 p_e->psm = psm;
5020 p_e->is_orig = is_orig;
5021 p_e->p_callback = p_callback;
5022 p_e->p_ref_data = p_ref_data;
5023 p_e->transport = BT_TRANSPORT_BR_EDR;
5024 p_e->sec_act = BTM_BLE_SEC_NONE;
5025 p_e->bd_addr = bd_addr;
5026 p_e->rfcomm_security_requirement = security_required;
5027
5028 log::verbose("PSM: 0x{:04x} Is_Orig: {} security_required: 0x{:x}", psm,
5029 is_orig, security_required);
5030
5031 fixed_queue_enqueue(btm_sec_cb.sec_pending_q, p_e);
5032
5033 return true;
5034 }
5035
btm_sec_check_prefetch_pin(tBTM_SEC_DEV_REC * p_dev_rec)5036 static bool btm_sec_check_prefetch_pin(tBTM_SEC_DEV_REC* p_dev_rec) {
5037 uint8_t major = (uint8_t)(p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK);
5038 uint8_t minor = (uint8_t)(p_dev_rec->dev_class[2] & BTM_COD_MINOR_CLASS_MASK);
5039 bool rv = false;
5040
5041 if ((major == BTM_COD_MAJOR_AUDIO) &&
5042 ((minor == BTM_COD_MINOR_CONFM_HANDSFREE) ||
5043 (minor == BTM_COD_MINOR_CAR_AUDIO))) {
5044 log::verbose(
5045 "Skipping pre-fetch PIN for carkit COD Major: 0x{:02x} Minor: 0x{:02x}",
5046 major, minor);
5047
5048 if (!btm_sec_cb.security_mode_changed) {
5049 btm_sec_cb.security_mode_changed = true;
5050 btsnd_hcic_write_auth_enable(true);
5051 }
5052 } else {
5053 btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_PIN);
5054
5055 /* If we got a PIN, use that, else try to get one */
5056 if (btm_sec_cb.pin_code_len) {
5057 BTM_PINCodeReply(p_dev_rec->bd_addr, BTM_SUCCESS, btm_sec_cb.pin_code_len,
5058 btm_sec_cb.pin_code);
5059 } else {
5060 /* pin was not supplied - pre-fetch pin code now */
5061 if (btm_sec_cb.api.p_pin_callback &&
5062 ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0)) {
5063 log::verbose("PIN code callback called");
5064 if (BTM_IsAclConnectionUp(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR))
5065 btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
5066 (btm_sec_cb.api.p_pin_callback)(
5067 p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
5068 (p_dev_rec->sec_rec.required_security_flags_for_pairing &
5069 BTM_SEC_IN_MIN_16_DIGIT_PIN));
5070 }
5071 }
5072
5073 rv = true;
5074 }
5075
5076 return rv;
5077 }
5078
5079 /*******************************************************************************
5080 *
5081 * Function btm_sec_queue_encrypt_request
5082 *
5083 * Description encqueue encryption request when device has active security
5084 * process pending.
5085 *
5086 ******************************************************************************/
btm_sec_queue_encrypt_request(const RawAddress & bd_addr,tBT_TRANSPORT transport,tBTM_SEC_CALLBACK * p_callback,void * p_ref_data,tBTM_BLE_SEC_ACT sec_act)5087 static void btm_sec_queue_encrypt_request(const RawAddress& bd_addr,
5088 tBT_TRANSPORT transport,
5089 tBTM_SEC_CALLBACK* p_callback,
5090 void* p_ref_data,
5091 tBTM_BLE_SEC_ACT sec_act) {
5092 tBTM_SEC_QUEUE_ENTRY* p_e =
5093 (tBTM_SEC_QUEUE_ENTRY*)osi_malloc(sizeof(tBTM_SEC_QUEUE_ENTRY) + 1);
5094
5095 p_e->psm = 0; /* if PSM 0, encryption request */
5096 p_e->p_callback = p_callback;
5097 p_e->p_ref_data = p_ref_data;
5098 p_e->transport = transport;
5099 p_e->sec_act = sec_act;
5100 p_e->bd_addr = bd_addr;
5101 fixed_queue_enqueue(btm_sec_cb.sec_pending_q, p_e);
5102 }
5103
5104 /*******************************************************************************
5105 *
5106 * Function btm_sec_check_pending_enc_req
5107 *
5108 * Description This function is called to send pending encryption callback
5109 * if waiting
5110 *
5111 * Returns void
5112 *
5113 ******************************************************************************/
btm_sec_check_pending_enc_req(tBTM_SEC_DEV_REC * p_dev_rec,tBT_TRANSPORT transport,uint8_t encr_enable)5114 static void btm_sec_check_pending_enc_req(tBTM_SEC_DEV_REC* p_dev_rec,
5115 tBT_TRANSPORT transport,
5116 uint8_t encr_enable) {
5117 if (fixed_queue_is_empty(btm_sec_cb.sec_pending_q)) return;
5118
5119 const tBTM_STATUS res = encr_enable ? BTM_SUCCESS : BTM_ERR_PROCESSING;
5120 list_t* list = fixed_queue_get_list(btm_sec_cb.sec_pending_q);
5121 for (const list_node_t* node = list_begin(list); node != list_end(list);) {
5122 tBTM_SEC_QUEUE_ENTRY* p_e = (tBTM_SEC_QUEUE_ENTRY*)list_node(node);
5123 node = list_next(node);
5124
5125 if (p_e->bd_addr == p_dev_rec->bd_addr && p_e->psm == 0 &&
5126 p_e->transport == transport) {
5127 if (encr_enable == 0 || transport == BT_TRANSPORT_BR_EDR ||
5128 p_e->sec_act == BTM_BLE_SEC_ENCRYPT ||
5129 p_e->sec_act == BTM_BLE_SEC_ENCRYPT_NO_MITM ||
5130 (p_e->sec_act == BTM_BLE_SEC_ENCRYPT_MITM &&
5131 p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_AUTHENTICATED)) {
5132 if (p_e->p_callback)
5133 (*p_e->p_callback)(p_dev_rec->bd_addr, transport, p_e->p_ref_data,
5134 res);
5135 fixed_queue_try_remove_from_queue(btm_sec_cb.sec_pending_q, (void*)p_e);
5136 osi_free(p_e);
5137 }
5138 }
5139 }
5140 }
5141
5142 /*******************************************************************************
5143 *
5144 * Function btm_sec_set_serv_level4_flags
5145 *
5146 * Description This function is called to set security mode 4 level 4
5147 * flags.
5148 *
5149 * Returns service security requirements updated to include secure
5150 * connections only mode.
5151 *
5152 ******************************************************************************/
btm_sec_set_serv_level4_flags(uint16_t cur_security,bool is_originator)5153 static uint16_t btm_sec_set_serv_level4_flags(uint16_t cur_security,
5154 bool is_originator) {
5155 uint16_t sec_level4_flags =
5156 is_originator ? BTM_SEC_OUT_LEVEL4_FLAGS : BTM_SEC_IN_LEVEL4_FLAGS;
5157
5158 return cur_security | sec_level4_flags;
5159 }
5160
5161 /*******************************************************************************
5162 *
5163 * Function btm_sec_clear_ble_keys
5164 *
5165 * Description This function is called to clear out the BLE keys.
5166 * Typically when devices are removed in BTM_SecDeleteDevice,
5167 * or when a new BT Link key is generated.
5168 *
5169 * Returns void
5170 *
5171 ******************************************************************************/
btm_sec_clear_ble_keys(tBTM_SEC_DEV_REC * p_dev_rec)5172 void btm_sec_clear_ble_keys(tBTM_SEC_DEV_REC* p_dev_rec) {
5173 log::verbose("Clearing BLE Keys");
5174 memset(&p_dev_rec->sec_rec.ble_keys, 0, sizeof(tBTM_SEC_BLE_KEYS));
5175
5176 btm_ble_resolving_list_remove_dev(p_dev_rec);
5177 }
5178
5179 /*******************************************************************************
5180 *
5181 * Function btm_sec_is_a_bonded_dev
5182 *
5183 * Description Is the specified device is a bonded device
5184 * (either on BR/EDR or LE)
5185 *
5186 * Returns true - dev is bonded
5187 *
5188 ******************************************************************************/
btm_sec_is_a_bonded_dev(const RawAddress & bda)5189 bool btm_sec_is_a_bonded_dev(const RawAddress& bda) {
5190 return btm_sec_cb.IsDeviceBonded(bda);
5191 }
5192
5193 /*******************************************************************************
5194 *
5195 * Function btm_sec_use_smp_br_chnl
5196 *
5197 * Description The function checks if SMP BR connection can be used with
5198 * the peer.
5199 * Is called when authentication for dedicated bonding is
5200 * successfully completed.
5201 *
5202 * Returns true - if SMP BR connection can be used (the link key is
5203 * generated from P-256 and the peer supports Security
5204 * Manager over BR).
5205 *
5206 ******************************************************************************/
btm_sec_use_smp_br_chnl(tBTM_SEC_DEV_REC * p_dev_rec)5207 static bool btm_sec_use_smp_br_chnl(tBTM_SEC_DEV_REC* p_dev_rec) {
5208 uint32_t ext_feat;
5209 uint8_t chnl_mask[L2CAP_FIXED_CHNL_ARRAY_SIZE];
5210
5211 log::verbose("link_key_type = 0x{:x}", p_dev_rec->sec_rec.link_key_type);
5212
5213 if ((p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_UNAUTH_COMB_P_256) &&
5214 (p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256))
5215 return false;
5216
5217 if (!L2CA_GetPeerFeatures(p_dev_rec->bd_addr, &ext_feat, chnl_mask))
5218 return false;
5219
5220 if (!(chnl_mask[0] & L2CAP_FIXED_CHNL_SMP_BR_BIT)) return false;
5221
5222 return true;
5223 }
5224
5225 /*******************************************************************************
5226 *
5227 * Function btm_sec_set_peer_sec_caps
5228 *
5229 * Description This function is called to set sm4 and rmt_sec_caps fields
5230 * based on the available peer device features.
5231 *
5232 * Returns void
5233 *
5234 ******************************************************************************/
btm_sec_set_peer_sec_caps(uint16_t hci_handle,bool ssp_supported,bool sc_supported,bool hci_role_switch_supported,bool br_edr_supported,bool le_supported)5235 void btm_sec_set_peer_sec_caps(uint16_t hci_handle, bool ssp_supported,
5236 bool sc_supported,
5237 bool hci_role_switch_supported,
5238 bool br_edr_supported, bool le_supported) {
5239 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(hci_handle);
5240 if (p_dev_rec == nullptr) return;
5241
5242 if (com::android::bluetooth::flags::bluffs_mitigation()) {
5243 // Drop the connection here if the remote attempts to downgrade from Secure
5244 // Connections mode.
5245 if (btm_sec_is_device_sc_downgrade(hci_handle, sc_supported)) {
5246 acl_set_disconnect_reason(HCI_ERR_HOST_REJECT_SECURITY);
5247 btm_sec_send_hci_disconnect(
5248 p_dev_rec, HCI_ERR_AUTH_FAILURE, hci_handle,
5249 "attempted to downgrade from Secure Connections mode");
5250 return;
5251 }
5252 }
5253
5254 p_dev_rec->remote_feature_received = true;
5255 p_dev_rec->remote_supports_hci_role_switch = hci_role_switch_supported;
5256
5257 uint8_t req_pend = (p_dev_rec->sm4 & BTM_SM4_REQ_PEND);
5258
5259 if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) ||
5260 p_dev_rec->is_originator) {
5261 tBTM_STATUS btm_status = btm_sec_execute_procedure(p_dev_rec);
5262 if (btm_status != BTM_CMD_STARTED) {
5263 log::warn("Security procedure not started! status:{}",
5264 btm_status_text(btm_status));
5265 btm_sec_dev_rec_cback_event(p_dev_rec, btm_status, false);
5266 }
5267 }
5268
5269 /* Store the Peer Security Capabilites (in SM4 and rmt_sec_caps) */
5270 if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SP ||
5271 btm_sec_cb.security_mode == BTM_SEC_MODE_SC) &&
5272 ssp_supported) {
5273 p_dev_rec->sm4 = BTM_SM4_TRUE;
5274 p_dev_rec->remote_supports_secure_connections = sc_supported;
5275 } else {
5276 p_dev_rec->sm4 = BTM_SM4_KNOWN;
5277 p_dev_rec->remote_supports_secure_connections = false;
5278 }
5279
5280 if (p_dev_rec->remote_features_needed) {
5281 log::debug("Now device in SC Only mode, waiting for peer remote features!");
5282 btm_io_capabilities_req(p_dev_rec->bd_addr);
5283 p_dev_rec->remote_features_needed = false;
5284 }
5285
5286 if (req_pend) {
5287 /* Request for remaining Security Features (if any) */
5288 l2cu_resubmit_pending_sec_req(&p_dev_rec->bd_addr);
5289 }
5290
5291 p_dev_rec->remote_supports_bredr = br_edr_supported;
5292 p_dev_rec->remote_supports_ble = le_supported;
5293 }
5294
5295 // Return DEV_CLASS (uint8_t[3]) of bda. If record doesn't exist, create one.
btm_get_dev_class(const RawAddress & bda)5296 DEV_CLASS btm_get_dev_class(const RawAddress& bda) {
5297 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(bda);
5298 return p_dev_rec->dev_class;
5299 }
5300
BTM_update_version_info(const RawAddress & bd_addr,const remote_version_info & remote_version_info)5301 void BTM_update_version_info(const RawAddress& bd_addr,
5302 const remote_version_info& remote_version_info) {
5303 tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
5304 if (p_dev_rec == NULL) return;
5305
5306 p_dev_rec->remote_version_info = remote_version_info;
5307 }
5308