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