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