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