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