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