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