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