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