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