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