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