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