OSDN Git Service

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