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