1 /**
2  * @file smp.c
3  * Security Manager Protocol implementation
4  */
5 
6 /*
7  * Copyright (c) 2017 Nordic Semiconductor ASA
8  * Copyright (c) 2015-2016 Intel Corporation
9  *
10  * SPDX-License-Identifier: Apache-2.0
11  */
12 
13 #include <errno.h>
14 #include <stddef.h>
15 #include <string.h>
16 
17 #include <zephyr/bluetooth/bluetooth.h>
18 #include <zephyr/bluetooth/buf.h>
19 #include <zephyr/bluetooth/conn.h>
20 #include <zephyr/bluetooth/hci.h>
21 #include <zephyr/debug/stack.h>
22 #include <zephyr/kernel.h>
23 #include <zephyr/net/buf.h>
24 #include <zephyr/sys/__assert.h>
25 #include <zephyr/sys/atomic.h>
26 #include <zephyr/sys/byteorder.h>
27 #include <zephyr/sys/check.h>
28 #include <zephyr/sys/util.h>
29 
30 
31 #include "common/bt_str.h"
32 
33 #include "crypto/bt_crypto.h"
34 
35 #include "hci_core.h"
36 #include "ecc.h"
37 #include "keys.h"
38 #include "conn_internal.h"
39 #include "l2cap_internal.h"
40 #include "smp.h"
41 
42 #define LOG_LEVEL CONFIG_BT_SMP_LOG_LEVEL
43 #include <zephyr/logging/log.h>
44 LOG_MODULE_REGISTER(bt_smp);
45 
46 #define SMP_TIMEOUT K_SECONDS(30)
47 
48 #if defined(CONFIG_BT_SIGNING)
49 #define SIGN_DIST BT_SMP_DIST_SIGN
50 #else
51 #define SIGN_DIST 0
52 #endif
53 
54 #if defined(CONFIG_BT_PRIVACY)
55 #define ID_DIST BT_SMP_DIST_ID_KEY
56 #else
57 #define ID_DIST 0
58 #endif
59 
60 #if defined(CONFIG_BT_BREDR)
61 #define LINK_DIST BT_SMP_DIST_LINK_KEY
62 #else
63 #define LINK_DIST 0
64 #endif
65 
66 #define RECV_KEYS (BT_SMP_DIST_ENC_KEY | BT_SMP_DIST_ID_KEY | SIGN_DIST |\
67 		   LINK_DIST)
68 #define SEND_KEYS (BT_SMP_DIST_ENC_KEY | ID_DIST | SIGN_DIST | LINK_DIST)
69 
70 #define RECV_KEYS_SC (RECV_KEYS & ~(BT_SMP_DIST_ENC_KEY))
71 #define SEND_KEYS_SC (SEND_KEYS & ~(BT_SMP_DIST_ENC_KEY))
72 
73 #define BR_RECV_KEYS_SC (RECV_KEYS & ~(LINK_DIST))
74 #define BR_SEND_KEYS_SC (SEND_KEYS & ~(LINK_DIST))
75 
76 #define BT_SMP_AUTH_MASK	0x07
77 
78 #if defined(CONFIG_BT_BONDABLE)
79 #define BT_SMP_AUTH_BONDING_FLAGS BT_SMP_AUTH_BONDING
80 #else
81 #define BT_SMP_AUTH_BONDING_FLAGS 0
82 #endif /* CONFIG_BT_BONDABLE */
83 
84 #if defined(CONFIG_BT_BREDR)
85 
86 #define BT_SMP_AUTH_MASK_SC	0x2f
87 #if defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)
88 #define BT_SMP_AUTH_DEFAULT (BT_SMP_AUTH_BONDING_FLAGS | BT_SMP_AUTH_CT2)
89 #else
90 #define BT_SMP_AUTH_DEFAULT (BT_SMP_AUTH_BONDING_FLAGS | BT_SMP_AUTH_CT2 |\
91 			     BT_SMP_AUTH_SC)
92 #endif /* CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY */
93 
94 #else
95 
96 #define BT_SMP_AUTH_MASK_SC	0x0f
97 #if defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)
98 #define BT_SMP_AUTH_DEFAULT (BT_SMP_AUTH_BONDING_FLAGS)
99 #else
100 #define BT_SMP_AUTH_DEFAULT (BT_SMP_AUTH_BONDING_FLAGS | BT_SMP_AUTH_SC)
101 #endif /* CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY */
102 
103 #endif /* CONFIG_BT_BREDR */
104 
105 enum pairing_method {
106 	JUST_WORKS,		/* JustWorks pairing */
107 	PASSKEY_INPUT,		/* Passkey Entry input */
108 	PASSKEY_DISPLAY,	/* Passkey Entry display */
109 	PASSKEY_CONFIRM,	/* Passkey confirm */
110 	PASSKEY_ROLE,		/* Passkey Entry depends on role */
111 	LE_SC_OOB,		/* LESC Out of Band */
112 	LEGACY_OOB,		/* Legacy Out of Band */
113 };
114 
115 enum {
116 	SMP_FLAG_CFM_DELAYED,	/* if confirm should be send when TK is valid */
117 	SMP_FLAG_ENC_PENDING,	/* if waiting for an encryption change event */
118 	SMP_FLAG_KEYS_DISTR,	/* if keys distribution phase is in progress */
119 	SMP_FLAG_PAIRING,	/* if pairing is in progress */
120 	SMP_FLAG_TIMEOUT,	/* if SMP timeout occurred */
121 	SMP_FLAG_SC,		/* if LE Secure Connections is used */
122 	SMP_FLAG_PKEY_SEND,	/* if should send Public Key when available */
123 	SMP_FLAG_DHKEY_PENDING,	/* if waiting for local DHKey */
124 	SMP_FLAG_DHKEY_GEN,     /* if generating DHKey */
125 	SMP_FLAG_DHKEY_SEND,	/* if should generate and send DHKey Check */
126 	SMP_FLAG_USER,		/* if waiting for user input */
127 	SMP_FLAG_DISPLAY,       /* if display_passkey() callback was called */
128 	SMP_FLAG_OOB_PENDING,	/* if waiting for OOB data */
129 	SMP_FLAG_BOND,		/* if bonding */
130 	SMP_FLAG_SC_DEBUG_KEY,	/* if Secure Connection are using debug key */
131 	SMP_FLAG_SEC_REQ,	/* if Security Request was sent/received */
132 	SMP_FLAG_DHCHECK_WAIT,	/* if waiting for remote DHCheck (as periph) */
133 	SMP_FLAG_DERIVE_LK,	/* if Link Key should be derived */
134 	SMP_FLAG_BR_CONNECTED,	/* if BR/EDR channel is connected */
135 	SMP_FLAG_BR_PAIR,	/* if should start BR/EDR pairing */
136 	SMP_FLAG_CT2,		/* if should use H7 for keys derivation */
137 
138 	/* Total number of flags - must be at the end */
139 	SMP_NUM_FLAGS,
140 };
141 
142 /* SMP channel specific context */
143 struct bt_smp {
144 	/* Commands that remote is allowed to send */
145 	ATOMIC_DEFINE(allowed_cmds, BT_SMP_NUM_CMDS);
146 
147 	/* Flags for SMP state machine */
148 	ATOMIC_DEFINE(flags, SMP_NUM_FLAGS);
149 
150 	/* Type of method used for pairing */
151 	uint8_t				method;
152 
153 	/* Pairing Request PDU */
154 	uint8_t				preq[7];
155 
156 	/* Pairing Response PDU */
157 	uint8_t				prsp[7];
158 
159 	/* Pairing Confirm PDU */
160 	uint8_t				pcnf[16];
161 
162 	/* Local random number */
163 	uint8_t				prnd[16];
164 
165 	/* Remote random number */
166 	uint8_t				rrnd[16];
167 
168 	/* Temporary key */
169 	uint8_t				tk[16];
170 
171 	/* Remote Public Key for LE SC */
172 	uint8_t				pkey[BT_PUB_KEY_LEN];
173 
174 	/* DHKey */
175 	uint8_t				dhkey[BT_DH_KEY_LEN];
176 
177 	/* Remote DHKey check */
178 	uint8_t				e[16];
179 
180 	/* MacKey */
181 	uint8_t				mackey[16];
182 
183 	/* LE SC passkey */
184 	uint32_t				passkey;
185 
186 	/* LE SC passkey round */
187 	uint8_t				passkey_round;
188 
189 	/* LE SC local OOB data */
190 	const struct bt_le_oob_sc_data	*oobd_local;
191 
192 	/* LE SC remote OOB data */
193 	const struct bt_le_oob_sc_data	*oobd_remote;
194 
195 	/* Local key distribution */
196 	uint8_t				local_dist;
197 
198 	/* Remote key distribution */
199 	uint8_t				remote_dist;
200 
201 	/* The channel this context is associated with.
202 	 * This marks the beginning of the part of the structure that will not
203 	 * be memset to zero in init.
204 	 */
205 	struct bt_l2cap_le_chan		chan;
206 
207 	/* Delayed work for timeout handling */
208 	struct k_work_delayable		work;
209 
210 	/* Used Bluetooth authentication callbacks. */
211 	atomic_ptr_t			auth_cb;
212 
213 	/* Bondable flag */
214 	atomic_t			bondable;
215 };
216 
217 static unsigned int fixed_passkey = BT_PASSKEY_INVALID;
218 
219 #define DISPLAY_FIXED(smp) (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && \
220 			    fixed_passkey != BT_PASSKEY_INVALID && \
221 			    (smp)->method == PASSKEY_DISPLAY)
222 
223 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
224 /* based on table 2.8 Core Spec 2.3.5.1 Vol. 3 Part H */
225 static const uint8_t gen_method_legacy[5 /* remote */][5 /* local */] = {
226 	{ JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS, PASSKEY_INPUT },
227 	{ JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS, PASSKEY_INPUT },
228 	{ PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS,
229 	  PASSKEY_DISPLAY },
230 	{ JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS },
231 	{ PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS,
232 	  PASSKEY_ROLE },
233 };
234 #endif /* CONFIG_BT_SMP_SC_PAIR_ONLY */
235 
236 #if !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)
237 /* based on table 2.8 Core Spec 2.3.5.1 Vol. 3 Part H */
238 static const uint8_t gen_method_sc[5 /* remote */][5 /* local */] = {
239 	{ JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS, PASSKEY_INPUT },
240 	{ JUST_WORKS, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS,
241 	  PASSKEY_CONFIRM },
242 	{ PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS,
243 	  PASSKEY_DISPLAY },
244 	{ JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS },
245 	{ PASSKEY_DISPLAY, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS,
246 	  PASSKEY_CONFIRM },
247 };
248 #endif /* !CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY */
249 
250 #if defined(CONFIG_BT_BREDR)
251 /* SMP over BR/EDR channel specific context */
252 struct bt_smp_br {
253 	/* Commands that remote is allowed to send */
254 	ATOMIC_DEFINE(allowed_cmds, BT_SMP_NUM_CMDS);
255 
256 	/* Flags for SMP state machine */
257 	ATOMIC_DEFINE(flags, SMP_NUM_FLAGS);
258 
259 	/* Local key distribution */
260 	uint8_t			local_dist;
261 
262 	/* Remote key distribution */
263 	uint8_t			remote_dist;
264 
265 	/* Encryption Key Size used for connection */
266 	uint8_t 			enc_key_size;
267 
268 	/* The channel this context is associated with.
269 	 * This marks the beginning of the part of the structure that will not
270 	 * be memset to zero in init.
271 	 */
272 	struct bt_l2cap_br_chan	chan;
273 
274 	/* Delayed work for timeout handling */
275 	struct k_work_delayable	work;
276 };
277 
278 static struct bt_smp_br bt_smp_br_pool[CONFIG_BT_MAX_CONN];
279 #endif /* CONFIG_BT_BREDR */
280 
281 static struct bt_smp bt_smp_pool[CONFIG_BT_MAX_CONN];
282 static bool bondable = IS_ENABLED(CONFIG_BT_BONDABLE);
283 static bool sc_oobd_present;
284 static bool legacy_oobd_present;
285 static bool sc_supported;
286 static const uint8_t *sc_public_key;
287 static K_SEM_DEFINE(sc_local_pkey_ready, 0, 1);
288 
289 /* Pointer to internal data is used to mark that callbacks of given SMP channel are not initialized.
290  * Value of NULL represents no authenticaiton capabilities and cannot be used for that purpose.
291  */
292 #define BT_SMP_AUTH_CB_UNINITIALIZED	((atomic_ptr_val_t)bt_smp_pool)
293 
294 /* Value used to mark that per-connection bondable flag is not initialized.
295  * Value false/true represent if flag is cleared or set and cannot be used for that purpose.
296  */
297 #define BT_SMP_BONDABLE_UNINITIALIZED	((atomic_val_t)-1)
298 
le_sc_supported(void)299 static bool le_sc_supported(void)
300 {
301 	/*
302 	 * If controller based ECC is to be used it must support
303 	 * "LE Read Local P-256 Public Key" and "LE Generate DH Key" commands.
304 	 * Otherwise LE SC are not supported.
305 	 */
306 	if (IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)) {
307 		return false;
308 	}
309 
310 	return BT_CMD_TEST(bt_dev.supported_commands, 34, 1) &&
311 	       BT_CMD_TEST(bt_dev.supported_commands, 34, 2);
312 }
313 
latch_auth_cb(struct bt_smp * smp)314 static const struct bt_conn_auth_cb *latch_auth_cb(struct bt_smp *smp)
315 {
316 	(void)atomic_ptr_cas(&smp->auth_cb, BT_SMP_AUTH_CB_UNINITIALIZED,
317 			     (atomic_ptr_val_t)bt_auth);
318 
319 	return atomic_ptr_get(&smp->auth_cb);
320 }
321 
latch_bondable(struct bt_smp * smp)322 static bool latch_bondable(struct bt_smp *smp)
323 {
324 	(void)atomic_cas(&smp->bondable, BT_SMP_BONDABLE_UNINITIALIZED, (atomic_val_t)bondable);
325 
326 	return atomic_get(&smp->bondable);
327 }
328 
get_io_capa(struct bt_smp * smp)329 static uint8_t get_io_capa(struct bt_smp *smp)
330 {
331 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
332 
333 	if (!smp_auth_cb) {
334 		goto no_callbacks;
335 	}
336 
337 	/* Passkey Confirmation is valid only for LE SC */
338 	if (smp_auth_cb->passkey_display && smp_auth_cb->passkey_entry &&
339 	    (smp_auth_cb->passkey_confirm || !sc_supported)) {
340 		return BT_SMP_IO_KEYBOARD_DISPLAY;
341 	}
342 
343 	/* DisplayYesNo is useful only for LE SC */
344 	if (sc_supported && smp_auth_cb->passkey_display &&
345 	    smp_auth_cb->passkey_confirm) {
346 		return BT_SMP_IO_DISPLAY_YESNO;
347 	}
348 
349 	if (smp_auth_cb->passkey_entry) {
350 		if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) &&
351 		    fixed_passkey != BT_PASSKEY_INVALID) {
352 			return BT_SMP_IO_KEYBOARD_DISPLAY;
353 		} else {
354 			return BT_SMP_IO_KEYBOARD_ONLY;
355 		}
356 	}
357 
358 	if (smp_auth_cb->passkey_display) {
359 		return BT_SMP_IO_DISPLAY_ONLY;
360 	}
361 
362 no_callbacks:
363 	if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) &&
364 	    fixed_passkey != BT_PASSKEY_INVALID) {
365 		return BT_SMP_IO_DISPLAY_ONLY;
366 	} else {
367 		return BT_SMP_IO_NO_INPUT_OUTPUT;
368 	}
369 }
370 
371 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
372 static uint8_t legacy_get_pair_method(struct bt_smp *smp, uint8_t remote_io);
373 #endif
374 
smp_keys_check(struct bt_conn * conn)375 static bool smp_keys_check(struct bt_conn *conn)
376 {
377 	if (atomic_test_bit(conn->flags, BT_CONN_FORCE_PAIR)) {
378 		return false;
379 	}
380 
381 	if (!conn->le.keys) {
382 		conn->le.keys = bt_keys_find(BT_KEYS_LTK_P256,
383 						     conn->id, &conn->le.dst);
384 		if (!conn->le.keys) {
385 			conn->le.keys = bt_keys_find(BT_KEYS_LTK,
386 						     conn->id,
387 						     &conn->le.dst);
388 		}
389 	}
390 
391 	if (!conn->le.keys ||
392 	    !(conn->le.keys->keys & (BT_KEYS_LTK | BT_KEYS_LTK_P256))) {
393 		return false;
394 	}
395 
396 	if (conn->required_sec_level >= BT_SECURITY_L3 &&
397 	    !(conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) {
398 		return false;
399 	}
400 
401 	if (conn->required_sec_level >= BT_SECURITY_L4 &&
402 	    !((conn->le.keys->flags & BT_KEYS_AUTHENTICATED) &&
403 	      (conn->le.keys->keys & BT_KEYS_LTK_P256) &&
404 	      (conn->le.keys->enc_size == BT_SMP_MAX_ENC_KEY_SIZE))) {
405 		return false;
406 	}
407 
408 	return true;
409 }
410 
get_pair_method(struct bt_smp * smp,uint8_t remote_io)411 static uint8_t get_pair_method(struct bt_smp *smp, uint8_t remote_io)
412 {
413 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
414 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
415 		return legacy_get_pair_method(smp, remote_io);
416 	}
417 #endif
418 
419 #if !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)
420 	struct bt_smp_pairing *req, *rsp;
421 
422 	req = (struct bt_smp_pairing *)&smp->preq[1];
423 	rsp = (struct bt_smp_pairing *)&smp->prsp[1];
424 
425 	if ((req->auth_req & rsp->auth_req) & BT_SMP_AUTH_SC) {
426 		/* if one side has OOB data use OOB */
427 		if ((req->oob_flag | rsp->oob_flag) & BT_SMP_OOB_DATA_MASK) {
428 			return LE_SC_OOB;
429 		}
430 	}
431 
432 	if (remote_io > BT_SMP_IO_KEYBOARD_DISPLAY) {
433 		return JUST_WORKS;
434 	}
435 
436 	/* if none side requires MITM use JustWorks */
437 	if (!((req->auth_req | rsp->auth_req) & BT_SMP_AUTH_MITM)) {
438 		return JUST_WORKS;
439 	}
440 
441 	return gen_method_sc[remote_io][get_io_capa(smp)];
442 #else
443 	return JUST_WORKS;
444 #endif
445 }
446 
security_err_get(uint8_t smp_err)447 static enum bt_security_err security_err_get(uint8_t smp_err)
448 {
449 	switch (smp_err) {
450 	case BT_SMP_ERR_PASSKEY_ENTRY_FAILED:
451 	case BT_SMP_ERR_DHKEY_CHECK_FAILED:
452 	case BT_SMP_ERR_NUMERIC_COMP_FAILED:
453 	case BT_SMP_ERR_CONFIRM_FAILED:
454 		return BT_SECURITY_ERR_AUTH_FAIL;
455 	case BT_SMP_ERR_OOB_NOT_AVAIL:
456 		return BT_SECURITY_ERR_OOB_NOT_AVAILABLE;
457 	case BT_SMP_ERR_AUTH_REQUIREMENTS:
458 	case BT_SMP_ERR_ENC_KEY_SIZE:
459 		return BT_SECURITY_ERR_AUTH_REQUIREMENT;
460 	case BT_SMP_ERR_PAIRING_NOTSUPP:
461 	case BT_SMP_ERR_CMD_NOTSUPP:
462 		return BT_SECURITY_ERR_PAIR_NOT_SUPPORTED;
463 	case BT_SMP_ERR_REPEATED_ATTEMPTS:
464 	case BT_SMP_ERR_BREDR_PAIRING_IN_PROGRESS:
465 	case BT_SMP_ERR_CROSS_TRANSP_NOT_ALLOWED:
466 		return BT_SECURITY_ERR_PAIR_NOT_ALLOWED;
467 	case BT_SMP_ERR_INVALID_PARAMS:
468 		return BT_SECURITY_ERR_INVALID_PARAM;
469 	case BT_SMP_ERR_KEY_REJECTED:
470 		return BT_SECURITY_ERR_KEY_REJECTED;
471 	case BT_SMP_ERR_UNSPECIFIED:
472 	default:
473 		return BT_SECURITY_ERR_UNSPECIFIED;
474 	}
475 }
476 
smp_err_get(enum bt_security_err auth_err)477 static uint8_t smp_err_get(enum bt_security_err auth_err)
478 {
479 	switch (auth_err) {
480 	case BT_SECURITY_ERR_OOB_NOT_AVAILABLE:
481 		return BT_SMP_ERR_OOB_NOT_AVAIL;
482 
483 	case BT_SECURITY_ERR_AUTH_FAIL:
484 	case BT_SECURITY_ERR_AUTH_REQUIREMENT:
485 		return BT_SMP_ERR_AUTH_REQUIREMENTS;
486 
487 	case BT_SECURITY_ERR_PAIR_NOT_SUPPORTED:
488 		return BT_SMP_ERR_PAIRING_NOTSUPP;
489 
490 	case BT_SECURITY_ERR_INVALID_PARAM:
491 		return BT_SMP_ERR_INVALID_PARAMS;
492 
493 	case BT_SECURITY_ERR_PIN_OR_KEY_MISSING:
494 	case BT_SECURITY_ERR_PAIR_NOT_ALLOWED:
495 	case BT_SECURITY_ERR_UNSPECIFIED:
496 		return BT_SMP_ERR_UNSPECIFIED;
497 	default:
498 		return 0;
499 	}
500 }
501 
smp_create_pdu(struct bt_smp * smp,uint8_t op,size_t len)502 static struct net_buf *smp_create_pdu(struct bt_smp *smp, uint8_t op, size_t len)
503 {
504 	struct bt_smp_hdr *hdr;
505 	struct net_buf *buf;
506 	k_timeout_t timeout;
507 
508 	/* Don't if session had already timed out */
509 	if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) {
510 		timeout = K_NO_WAIT;
511 	} else {
512 		timeout = SMP_TIMEOUT;
513 	}
514 
515 	/* Use smaller timeout if returning an error since that could be
516 	 * caused by lack of buffers.
517 	 */
518 	buf = bt_l2cap_create_pdu_timeout(NULL, 0, timeout);
519 	if (!buf) {
520 		/* If it was not possible to allocate a buffer within the
521 		 * timeout marked it as timed out.
522 		 */
523 		atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT);
524 		return NULL;
525 	}
526 
527 	hdr = net_buf_add(buf, sizeof(*hdr));
528 	hdr->code = op;
529 
530 	return buf;
531 }
532 
get_encryption_key_size(struct bt_smp * smp)533 static uint8_t get_encryption_key_size(struct bt_smp *smp)
534 {
535 	struct bt_smp_pairing *req, *rsp;
536 
537 	req = (struct bt_smp_pairing *)&smp->preq[1];
538 	rsp = (struct bt_smp_pairing *)&smp->prsp[1];
539 
540 	/*
541 	 * The smaller value of the initiating and responding devices maximum
542 	 * encryption key length parameters shall be used as the encryption key
543 	 * size.
544 	 */
545 	return MIN(req->max_key_size, rsp->max_key_size);
546 }
547 
548 /* Check that if a new pairing procedure with an existing bond will not lower
549  * the established security level of the bond.
550  */
update_keys_check(struct bt_smp * smp,struct bt_keys * keys)551 static bool update_keys_check(struct bt_smp *smp, struct bt_keys *keys)
552 {
553 	if (IS_ENABLED(CONFIG_BT_SMP_DISABLE_LEGACY_JW_PASSKEY) &&
554 	    !atomic_test_bit(smp->flags, SMP_FLAG_SC) &&
555 	    smp->method != LEGACY_OOB) {
556 		return false;
557 	}
558 
559 	if (IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) &&
560 	    smp->method != LEGACY_OOB) {
561 		return false;
562 	}
563 
564 	if (!keys ||
565 	    !(keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_LTK))) {
566 		return true;
567 	}
568 
569 	if (keys->enc_size > get_encryption_key_size(smp)) {
570 		return false;
571 	}
572 
573 	if ((keys->keys & BT_KEYS_LTK_P256) &&
574 	    !atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
575 		return false;
576 	}
577 
578 	if ((keys->flags & BT_KEYS_AUTHENTICATED) &&
579 	     smp->method == JUST_WORKS) {
580 		return false;
581 	}
582 
583 	if (!IS_ENABLED(CONFIG_BT_SMP_ALLOW_UNAUTH_OVERWRITE) &&
584 	    (!(keys->flags & BT_KEYS_AUTHENTICATED)
585 	     && smp->method == JUST_WORKS)) {
586 		if (!IS_ENABLED(CONFIG_BT_ID_ALLOW_UNAUTH_OVERWRITE) ||
587 		    (keys->id == smp->chan.chan.conn->id)) {
588 			return false;
589 		}
590 	}
591 
592 	return true;
593 }
594 
update_debug_keys_check(struct bt_smp * smp)595 static bool update_debug_keys_check(struct bt_smp *smp)
596 {
597 	struct bt_conn *conn = smp->chan.chan.conn;
598 
599 	if (!conn->le.keys) {
600 		conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst);
601 	}
602 
603 	if (!conn->le.keys ||
604 	    !(conn->le.keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_LTK))) {
605 		return true;
606 	}
607 
608 	if (conn->le.keys->flags & BT_KEYS_DEBUG) {
609 		return true;
610 	}
611 
612 	return false;
613 }
614 
615 #if defined(CONFIG_BT_PRIVACY) || defined(CONFIG_BT_SIGNING) || \
616 	!defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
617 /* For TX callbacks */
618 static void smp_pairing_complete(struct bt_smp *smp, uint8_t status);
619 #if defined(CONFIG_BT_BREDR)
620 static void smp_pairing_br_complete(struct bt_smp_br *smp, uint8_t status);
621 #endif
622 
smp_check_complete(struct bt_conn * conn,uint8_t dist_complete)623 static void smp_check_complete(struct bt_conn *conn, uint8_t dist_complete)
624 {
625 	struct bt_l2cap_chan *chan;
626 
627 	if (conn->type == BT_CONN_TYPE_LE) {
628 		struct bt_smp *smp;
629 
630 		chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_SMP);
631 		__ASSERT(chan, "No SMP channel found");
632 
633 		smp = CONTAINER_OF(chan, struct bt_smp, chan.chan);
634 		smp->local_dist &= ~dist_complete;
635 
636 		/* if all keys were distributed, pairing is done */
637 		if (!smp->local_dist && !smp->remote_dist) {
638 			smp_pairing_complete(smp, 0);
639 		}
640 
641 		return;
642 	}
643 
644 #if defined(CONFIG_BT_BREDR)
645 	if (conn->type == BT_CONN_TYPE_BR) {
646 		struct bt_smp_br *smp;
647 
648 		chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_BR_SMP);
649 		__ASSERT(chan, "No SMP channel found");
650 
651 		smp = CONTAINER_OF(chan, struct bt_smp_br, chan.chan);
652 		smp->local_dist &= ~dist_complete;
653 
654 		/* if all keys were distributed, pairing is done */
655 		if (!smp->local_dist && !smp->remote_dist) {
656 			smp_pairing_br_complete(smp, 0);
657 		}
658 	}
659 #endif
660 }
661 #endif
662 
663 #if defined(CONFIG_BT_PRIVACY)
smp_id_sent(struct bt_conn * conn,void * user_data,int err)664 static void smp_id_sent(struct bt_conn *conn, void *user_data, int err)
665 {
666 	if (!err) {
667 		smp_check_complete(conn, BT_SMP_DIST_ID_KEY);
668 	}
669 }
670 #endif /* CONFIG_BT_PRIVACY */
671 
672 #if defined(CONFIG_BT_SIGNING)
smp_sign_info_sent(struct bt_conn * conn,void * user_data,int err)673 static void smp_sign_info_sent(struct bt_conn *conn, void *user_data, int err)
674 {
675 	if (!err) {
676 		smp_check_complete(conn, BT_SMP_DIST_SIGN);
677 	}
678 }
679 #endif /* CONFIG_BT_SIGNING */
680 
681 #if defined(CONFIG_BT_BREDR)
sc_derive_link_key(struct bt_smp * smp)682 static void sc_derive_link_key(struct bt_smp *smp)
683 {
684 	/* constants as specified in Core Spec Vol.3 Part H 2.4.2.4 */
685 	static const uint8_t lebr[4] = { 0x72, 0x62, 0x65, 0x6c };
686 	struct bt_conn *conn = smp->chan.chan.conn;
687 	struct bt_keys_link_key *link_key;
688 	uint8_t ilk[16];
689 
690 	LOG_DBG("");
691 
692 	/* TODO handle errors? */
693 
694 	/*
695 	 * At this point remote device identity is known so we can use
696 	 * destination address here
697 	 */
698 	link_key = bt_keys_get_link_key(&conn->le.dst.a);
699 	if (!link_key) {
700 		return;
701 	}
702 
703 	if (atomic_test_bit(smp->flags, SMP_FLAG_CT2)) {
704 		/* constants as specified in Core Spec Vol.3 Part H 2.4.2.4 */
705 		static const uint8_t salt[16] = { 0x31, 0x70, 0x6d, 0x74,
706 					       0x00, 0x00, 0x00, 0x00,
707 					       0x00, 0x00, 0x00, 0x00,
708 					       0x00, 0x00, 0x00, 0x00 };
709 
710 		if (bt_crypto_h7(salt, conn->le.keys->ltk.val, ilk)) {
711 			bt_keys_link_key_clear(link_key);
712 			return;
713 		}
714 	} else {
715 		/* constants as specified in Core Spec Vol.3 Part H 2.4.2.4 */
716 		static const uint8_t tmp1[4] = { 0x31, 0x70, 0x6d, 0x74 };
717 
718 		if (bt_crypto_h6(conn->le.keys->ltk.val, tmp1, ilk)) {
719 			bt_keys_link_key_clear(link_key);
720 			return;
721 		}
722 	}
723 
724 	if (bt_crypto_h6(ilk, lebr, link_key->val)) {
725 		bt_keys_link_key_clear(link_key);
726 	}
727 
728 	link_key->flags |= BT_LINK_KEY_SC;
729 
730 	if (conn->le.keys->flags & BT_KEYS_AUTHENTICATED) {
731 		link_key->flags |= BT_LINK_KEY_AUTHENTICATED;
732 	} else {
733 		link_key->flags &= ~BT_LINK_KEY_AUTHENTICATED;
734 	}
735 }
736 
smp_br_reset(struct bt_smp_br * smp)737 static void smp_br_reset(struct bt_smp_br *smp)
738 {
739 	/* Clear flags first in case canceling of timeout fails. The SMP context
740 	 * shall be marked as timed out in that case.
741 	 */
742 	atomic_set(smp->flags, 0);
743 
744 	/* If canceling fails the timeout handler will set the timeout flag and
745 	 * mark the it as timed out. No new pairing procedures shall be started
746 	 * on this connection if that happens.
747 	 */
748 	(void)k_work_cancel_delayable(&smp->work);
749 
750 	atomic_set(smp->allowed_cmds, 0);
751 
752 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_REQ);
753 }
754 
smp_pairing_br_complete(struct bt_smp_br * smp,uint8_t status)755 static void smp_pairing_br_complete(struct bt_smp_br *smp, uint8_t status)
756 {
757 	struct bt_conn *conn = smp->chan.chan.conn;
758 	struct bt_keys *keys;
759 	bt_addr_le_t addr;
760 
761 	LOG_DBG("status 0x%x", status);
762 
763 	/* For dualmode devices LE address is same as BR/EDR address
764 	 * and is of public type.
765 	 */
766 	bt_addr_copy(&addr.a, &conn->br.dst);
767 	addr.type = BT_ADDR_LE_PUBLIC;
768 	keys = bt_keys_find_addr(conn->id, &addr);
769 
770 	if (status) {
771 		struct bt_conn_auth_info_cb *listener, *next;
772 
773 		if (keys) {
774 			bt_keys_clear(keys);
775 		}
776 
777 		SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&bt_auth_info_cbs, listener,
778 						  next, node) {
779 			if (listener->pairing_failed) {
780 				listener->pairing_failed(smp->chan.chan.conn,
781 							 security_err_get(status));
782 			}
783 		}
784 	} else {
785 		bool bond_flag = atomic_test_bit(smp->flags, SMP_FLAG_BOND);
786 		struct bt_conn_auth_info_cb *listener, *next;
787 
788 		if (bond_flag && keys) {
789 			bt_keys_store(keys);
790 		}
791 
792 		SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&bt_auth_info_cbs, listener,
793 						  next, node) {
794 			if (listener->pairing_complete) {
795 				listener->pairing_complete(smp->chan.chan.conn,
796 							   bond_flag);
797 			}
798 		}
799 	}
800 
801 	smp_br_reset(smp);
802 }
803 
smp_br_timeout(struct k_work * work)804 static void smp_br_timeout(struct k_work *work)
805 {
806 	struct k_work_delayable *dwork = k_work_delayable_from_work(work);
807 	struct bt_smp_br *smp = CONTAINER_OF(dwork, struct bt_smp_br, work);
808 
809 	LOG_ERR("SMP Timeout");
810 
811 	smp_pairing_br_complete(smp, BT_SMP_ERR_UNSPECIFIED);
812 	atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT);
813 }
814 
smp_br_send(struct bt_smp_br * smp,struct net_buf * buf,bt_conn_tx_cb_t cb)815 static void smp_br_send(struct bt_smp_br *smp, struct net_buf *buf,
816 			bt_conn_tx_cb_t cb)
817 {
818 	int err = bt_l2cap_send_cb(smp->chan.chan.conn, BT_L2CAP_CID_BR_SMP, buf, cb, NULL);
819 
820 	if (err) {
821 		if (err == -ENOBUFS) {
822 			LOG_ERR("Ran out of TX buffers or contexts.");
823 		}
824 
825 		net_buf_unref(buf);
826 		return;
827 	}
828 
829 	k_work_reschedule(&smp->work, SMP_TIMEOUT);
830 }
831 
bt_smp_br_connected(struct bt_l2cap_chan * chan)832 static void bt_smp_br_connected(struct bt_l2cap_chan *chan)
833 {
834 	struct bt_smp_br *smp = CONTAINER_OF(chan, struct bt_smp_br, chan.chan);
835 
836 	LOG_DBG("chan %p cid 0x%04x", chan,
837 		CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan)->tx.cid);
838 
839 	atomic_set_bit(smp->flags, SMP_FLAG_BR_CONNECTED);
840 
841 	/*
842 	 * if this flag is set it means pairing was requested before channel
843 	 * was connected
844 	 */
845 	if (atomic_test_bit(smp->flags, SMP_FLAG_BR_PAIR)) {
846 		bt_smp_br_send_pairing_req(chan->conn);
847 	}
848 }
849 
bt_smp_br_disconnected(struct bt_l2cap_chan * chan)850 static void bt_smp_br_disconnected(struct bt_l2cap_chan *chan)
851 {
852 	struct bt_smp_br *smp = CONTAINER_OF(chan, struct bt_smp_br, chan.chan);
853 
854 	LOG_DBG("chan %p cid 0x%04x", chan,
855 		CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan)->tx.cid);
856 
857 	/* Channel disconnected callback is always called from a work handler
858 	 * so canceling of the timeout work should always succeed.
859 	 */
860 	(void)k_work_cancel_delayable(&smp->work);
861 
862 	(void)memset(smp, 0, sizeof(*smp));
863 }
864 
smp_br_init(struct bt_smp_br * smp)865 static void smp_br_init(struct bt_smp_br *smp)
866 {
867 	/* Initialize SMP context exluding L2CAP channel context and anything
868 	 * else declared after.
869 	 */
870 	(void)memset(smp, 0, offsetof(struct bt_smp_br, chan));
871 
872 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_FAIL);
873 }
874 
smp_br_derive_ltk(struct bt_smp_br * smp)875 static void smp_br_derive_ltk(struct bt_smp_br *smp)
876 {
877 	/* constants as specified in Core Spec Vol.3 Part H 2.4.2.5 */
878 	static const uint8_t brle[4] = { 0x65, 0x6c, 0x72, 0x62 };
879 	struct bt_conn *conn = smp->chan.chan.conn;
880 	struct bt_keys_link_key *link_key = conn->br.link_key;
881 	struct bt_keys *keys;
882 	bt_addr_le_t addr;
883 	uint8_t ilk[16];
884 
885 	LOG_DBG("");
886 
887 	if (!link_key) {
888 		return;
889 	}
890 
891 	if (IS_ENABLED(CONFIG_BT_SMP_FORCE_BREDR) && conn->encrypt != 0x02) {
892 		LOG_WRN("Using P192 Link Key for P256 LTK derivation");
893 	}
894 
895 	/*
896 	 * For dualmode devices LE address is same as BR/EDR address and is of
897 	 * public type.
898 	 */
899 	bt_addr_copy(&addr.a, &conn->br.dst);
900 	addr.type = BT_ADDR_LE_PUBLIC;
901 
902 	keys = bt_keys_get_type(BT_KEYS_LTK_P256, conn->id, &addr);
903 	if (!keys) {
904 		LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&addr));
905 		return;
906 	}
907 
908 	if (atomic_test_bit(smp->flags, SMP_FLAG_CT2)) {
909 		/* constants as specified in Core Spec Vol.3 Part H 2.4.2.5 */
910 		static const uint8_t salt[16] = { 0x32, 0x70, 0x6d, 0x74,
911 					       0x00, 0x00, 0x00, 0x00,
912 					       0x00, 0x00, 0x00, 0x00,
913 					       0x00, 0x00, 0x00, 0x00 };
914 
915 		if (bt_crypto_h7(salt, link_key->val, ilk)) {
916 			bt_keys_link_key_clear(link_key);
917 			return;
918 		}
919 	} else {
920 		/* constants as specified in Core Spec Vol.3 Part H 2.4.2.5 */
921 		static const uint8_t tmp2[4] = { 0x32, 0x70, 0x6d, 0x74 };
922 
923 		if (bt_crypto_h6(link_key->val, tmp2, ilk)) {
924 			bt_keys_clear(keys);
925 			return;
926 		}
927 	}
928 
929 	if (bt_crypto_h6(ilk, brle, keys->ltk.val)) {
930 		bt_keys_clear(keys);
931 		return;
932 	}
933 
934 	(void)memset(keys->ltk.ediv, 0, sizeof(keys->ltk.ediv));
935 	(void)memset(keys->ltk.rand, 0, sizeof(keys->ltk.rand));
936 	keys->enc_size = smp->enc_key_size;
937 
938 	if (link_key->flags & BT_LINK_KEY_AUTHENTICATED) {
939 		keys->flags |= BT_KEYS_AUTHENTICATED;
940 	} else {
941 		keys->flags &= ~BT_KEYS_AUTHENTICATED;
942 	}
943 
944 	LOG_DBG("LTK derived from LinkKey");
945 }
946 
smp_br_create_pdu(struct bt_smp_br * smp,uint8_t op,size_t len)947 static struct net_buf *smp_br_create_pdu(struct bt_smp_br *smp, uint8_t op,
948 					 size_t len)
949 {
950 	struct bt_smp_hdr *hdr;
951 	struct net_buf *buf;
952 	k_timeout_t timeout;
953 
954 	/* Don't if session had already timed out */
955 	if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) {
956 		timeout = K_NO_WAIT;
957 	} else {
958 		timeout = SMP_TIMEOUT;
959 	}
960 
961 	/* Use smaller timeout if returning an error since that could be
962 	 * caused by lack of buffers.
963 	 */
964 	buf = bt_l2cap_create_pdu_timeout(NULL, 0, timeout);
965 	if (!buf) {
966 		/* If it was not possible to allocate a buffer within the
967 		 * timeout marked it as timed out.
968 		 */
969 		atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT);
970 		return NULL;
971 	}
972 
973 	hdr = net_buf_add(buf, sizeof(*hdr));
974 	hdr->code = op;
975 
976 	return buf;
977 }
978 
smp_br_distribute_keys(struct bt_smp_br * smp)979 static void smp_br_distribute_keys(struct bt_smp_br *smp)
980 {
981 	struct bt_conn *conn = smp->chan.chan.conn;
982 	struct bt_keys *keys;
983 	bt_addr_le_t addr;
984 
985 	/*
986 	 * For dualmode devices LE address is same as BR/EDR address and is of
987 	 * public type.
988 	 */
989 	bt_addr_copy(&addr.a, &conn->br.dst);
990 	addr.type = BT_ADDR_LE_PUBLIC;
991 
992 	keys = bt_keys_get_addr(conn->id, &addr);
993 	if (!keys) {
994 		LOG_ERR("No keys space for %s", bt_addr_le_str(&addr));
995 		return;
996 	}
997 
998 #if defined(CONFIG_BT_PRIVACY)
999 	if (smp->local_dist & BT_SMP_DIST_ID_KEY) {
1000 		struct bt_smp_ident_info *id_info;
1001 		struct bt_smp_ident_addr_info *id_addr_info;
1002 		struct net_buf *buf;
1003 
1004 		smp->local_dist &= ~BT_SMP_DIST_ID_KEY;
1005 
1006 		buf = smp_br_create_pdu(smp, BT_SMP_CMD_IDENT_INFO,
1007 					sizeof(*id_info));
1008 		if (!buf) {
1009 			LOG_ERR("Unable to allocate Ident Info buffer");
1010 			return;
1011 		}
1012 
1013 		id_info = net_buf_add(buf, sizeof(*id_info));
1014 		memcpy(id_info->irk, bt_dev.irk[conn->id], 16);
1015 
1016 		smp_br_send(smp, buf, NULL);
1017 
1018 		buf = smp_br_create_pdu(smp, BT_SMP_CMD_IDENT_ADDR_INFO,
1019 				     sizeof(*id_addr_info));
1020 		if (!buf) {
1021 			LOG_ERR("Unable to allocate Ident Addr Info buffer");
1022 			return;
1023 		}
1024 
1025 		id_addr_info = net_buf_add(buf, sizeof(*id_addr_info));
1026 		bt_addr_le_copy(&id_addr_info->addr, &bt_dev.id_addr[conn->id]);
1027 
1028 		smp_br_send(smp, buf, smp_id_sent);
1029 	}
1030 #endif /* CONFIG_BT_PRIVACY */
1031 
1032 #if defined(CONFIG_BT_SIGNING)
1033 	if (smp->local_dist & BT_SMP_DIST_SIGN) {
1034 		struct bt_smp_signing_info *info;
1035 		struct net_buf *buf;
1036 
1037 		smp->local_dist &= ~BT_SMP_DIST_SIGN;
1038 
1039 		buf = smp_br_create_pdu(smp, BT_SMP_CMD_SIGNING_INFO,
1040 					sizeof(*info));
1041 		if (!buf) {
1042 			LOG_ERR("Unable to allocate Signing Info buffer");
1043 			return;
1044 		}
1045 
1046 		info = net_buf_add(buf, sizeof(*info));
1047 
1048 		if (bt_rand(info->csrk, sizeof(info->csrk))) {
1049 			LOG_ERR("Unable to get random bytes");
1050 			return;
1051 		}
1052 
1053 		if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
1054 			bt_keys_add_type(keys, BT_KEYS_LOCAL_CSRK);
1055 			memcpy(keys->local_csrk.val, info->csrk, 16);
1056 			keys->local_csrk.cnt = 0U;
1057 		}
1058 
1059 		smp_br_send(smp, buf, smp_sign_info_sent);
1060 	}
1061 #endif /* CONFIG_BT_SIGNING */
1062 }
1063 
smp_br_pairing_allowed(struct bt_smp_br * smp)1064 static bool smp_br_pairing_allowed(struct bt_smp_br *smp)
1065 {
1066 	if (smp->chan.chan.conn->encrypt == 0x02) {
1067 		return true;
1068 	}
1069 
1070 	if (IS_ENABLED(CONFIG_BT_SMP_FORCE_BREDR) &&
1071 	    smp->chan.chan.conn->encrypt == 0x01) {
1072 		LOG_WRN("Allowing BR/EDR SMP with P-192 key");
1073 		return true;
1074 	}
1075 
1076 	return false;
1077 }
1078 
smp_br_pairing_req(struct bt_smp_br * smp,struct net_buf * buf)1079 static uint8_t smp_br_pairing_req(struct bt_smp_br *smp, struct net_buf *buf)
1080 {
1081 	struct bt_smp_pairing *req = (void *)buf->data;
1082 	struct bt_conn *conn = smp->chan.chan.conn;
1083 	struct bt_smp_pairing *rsp;
1084 	struct net_buf *rsp_buf;
1085 	uint8_t max_key_size;
1086 
1087 	LOG_DBG("req: io_capability 0x%02X, oob_flag 0x%02X, auth_req 0x%02X, "
1088 		"max_key_size 0x%02X, init_key_dist 0x%02X, resp_key_dist 0x%02X",
1089 		req->io_capability, req->oob_flag, req->auth_req,
1090 		req->max_key_size, req->init_key_dist, req->resp_key_dist);
1091 
1092 	/*
1093 	 * If a Pairing Request is received over the BR/EDR transport when
1094 	 * either cross-transport key derivation/generation is not supported or
1095 	 * the BR/EDR transport is not encrypted using a Link Key generated
1096 	 * using P256, a Pairing Failed shall be sent with the error code
1097 	 * "Cross-transport Key Derivation/Generation not allowed" (0x0E)."
1098 	 */
1099 	if (!smp_br_pairing_allowed(smp)) {
1100 		return BT_SMP_ERR_CROSS_TRANSP_NOT_ALLOWED;
1101 	}
1102 
1103 	max_key_size = bt_conn_enc_key_size(conn);
1104 	if (!max_key_size) {
1105 		LOG_DBG("Invalid encryption key size");
1106 		return BT_SMP_ERR_UNSPECIFIED;
1107 	}
1108 
1109 	if (req->max_key_size != max_key_size) {
1110 		return BT_SMP_ERR_ENC_KEY_SIZE;
1111 	}
1112 
1113 	rsp_buf = smp_br_create_pdu(smp, BT_SMP_CMD_PAIRING_RSP, sizeof(*rsp));
1114 	if (!rsp_buf) {
1115 		return BT_SMP_ERR_UNSPECIFIED;
1116 	}
1117 
1118 	smp_br_init(smp);
1119 	smp->enc_key_size = max_key_size;
1120 
1121 	/*
1122 	 * If Secure Connections pairing has been initiated over BR/EDR, the IO
1123 	 * Capability, OOB data flag and Auth Req fields of the SM Pairing
1124 	 * Request/Response PDU shall be set to zero on transmission, and
1125 	 * ignored on reception.
1126 	 */
1127 	rsp = net_buf_add(rsp_buf, sizeof(*rsp));
1128 
1129 	rsp->auth_req = 0x00;
1130 	rsp->io_capability = 0x00;
1131 	rsp->oob_flag = 0x00;
1132 	rsp->max_key_size = max_key_size;
1133 	rsp->init_key_dist = (req->init_key_dist & BR_RECV_KEYS_SC);
1134 	rsp->resp_key_dist = (req->resp_key_dist & BR_RECV_KEYS_SC);
1135 
1136 	smp->local_dist = rsp->resp_key_dist;
1137 	smp->remote_dist = rsp->init_key_dist;
1138 
1139 	LOG_DBG("rsp: io_capability 0x%02X, oob_flag 0x%02X, auth_req 0x%02X, "
1140 		"max_key_size 0x%02X, init_key_dist 0x%02X, resp_key_dist 0x%02X",
1141 		rsp->io_capability, rsp->oob_flag, rsp->auth_req,
1142 		rsp->max_key_size, rsp->init_key_dist, rsp->resp_key_dist);
1143 
1144 	smp_br_send(smp, rsp_buf, NULL);
1145 
1146 	atomic_set_bit(smp->flags, SMP_FLAG_PAIRING);
1147 
1148 	/* derive LTK if requested and clear distribution bits */
1149 	if ((smp->local_dist & BT_SMP_DIST_ENC_KEY) &&
1150 	    (smp->remote_dist & BT_SMP_DIST_ENC_KEY)) {
1151 		smp_br_derive_ltk(smp);
1152 	}
1153 	smp->local_dist &= ~BT_SMP_DIST_ENC_KEY;
1154 	smp->remote_dist &= ~BT_SMP_DIST_ENC_KEY;
1155 
1156 	/* BR/EDR acceptor is like LE Peripheral and distributes keys first */
1157 	smp_br_distribute_keys(smp);
1158 
1159 	if (smp->remote_dist & BT_SMP_DIST_ID_KEY) {
1160 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO);
1161 	} else if (smp->remote_dist & BT_SMP_DIST_SIGN) {
1162 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO);
1163 	}
1164 
1165 	/* if all keys were distributed, pairing is done */
1166 	if (!smp->local_dist && !smp->remote_dist) {
1167 		smp_pairing_br_complete(smp, 0);
1168 	}
1169 
1170 	return 0;
1171 }
1172 
smp_br_pairing_rsp(struct bt_smp_br * smp,struct net_buf * buf)1173 static uint8_t smp_br_pairing_rsp(struct bt_smp_br *smp, struct net_buf *buf)
1174 {
1175 	struct bt_smp_pairing *rsp = (void *)buf->data;
1176 	struct bt_conn *conn = smp->chan.chan.conn;
1177 	uint8_t max_key_size;
1178 
1179 	LOG_DBG("rsp: io_capability 0x%02X, oob_flag 0x%02X, auth_req 0x%02X, "
1180 		"max_key_size 0x%02X, init_key_dist 0x%02X, resp_key_dist 0x%02X",
1181 		rsp->io_capability, rsp->oob_flag, rsp->auth_req,
1182 		rsp->max_key_size, rsp->init_key_dist, rsp->resp_key_dist);
1183 
1184 	max_key_size = bt_conn_enc_key_size(conn);
1185 	if (!max_key_size) {
1186 		LOG_DBG("Invalid encryption key size");
1187 		return BT_SMP_ERR_UNSPECIFIED;
1188 	}
1189 
1190 	if (rsp->max_key_size != max_key_size) {
1191 		return BT_SMP_ERR_ENC_KEY_SIZE;
1192 	}
1193 
1194 	smp->local_dist &= rsp->init_key_dist;
1195 	smp->remote_dist &= rsp->resp_key_dist;
1196 
1197 	smp->local_dist &= SEND_KEYS_SC;
1198 	smp->remote_dist &= RECV_KEYS_SC;
1199 
1200 	/* Peripheral distributes its keys first */
1201 
1202 	if (smp->remote_dist & BT_SMP_DIST_ID_KEY) {
1203 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO);
1204 	} else if (smp->remote_dist & BT_SMP_DIST_SIGN) {
1205 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO);
1206 	}
1207 
1208 	/* derive LTK if requested and clear distribution bits */
1209 	if ((smp->local_dist & BT_SMP_DIST_ENC_KEY) &&
1210 	    (smp->remote_dist & BT_SMP_DIST_ENC_KEY)) {
1211 		smp_br_derive_ltk(smp);
1212 	}
1213 	smp->local_dist &= ~BT_SMP_DIST_ENC_KEY;
1214 	smp->remote_dist &= ~BT_SMP_DIST_ENC_KEY;
1215 
1216 	/* Pairing acceptor distributes it's keys first */
1217 	if (smp->remote_dist) {
1218 		return 0;
1219 	}
1220 
1221 	smp_br_distribute_keys(smp);
1222 
1223 	/* if all keys were distributed, pairing is done */
1224 	if (!smp->local_dist && !smp->remote_dist) {
1225 		smp_pairing_br_complete(smp, 0);
1226 	}
1227 
1228 	return 0;
1229 }
1230 
smp_br_pairing_failed(struct bt_smp_br * smp,struct net_buf * buf)1231 static uint8_t smp_br_pairing_failed(struct bt_smp_br *smp, struct net_buf *buf)
1232 {
1233 	struct bt_smp_pairing_fail *req = (void *)buf->data;
1234 
1235 	LOG_ERR("pairing failed (peer reason 0x%x)", req->reason);
1236 
1237 	smp_pairing_br_complete(smp, req->reason);
1238 	smp_br_reset(smp);
1239 
1240 	/* return no error to avoid sending Pairing Failed in response */
1241 	return 0;
1242 }
1243 
smp_br_ident_info(struct bt_smp_br * smp,struct net_buf * buf)1244 static uint8_t smp_br_ident_info(struct bt_smp_br *smp, struct net_buf *buf)
1245 {
1246 	struct bt_smp_ident_info *req = (void *)buf->data;
1247 	struct bt_conn *conn = smp->chan.chan.conn;
1248 	struct bt_keys *keys;
1249 	bt_addr_le_t addr;
1250 
1251 	LOG_DBG("");
1252 
1253 	/* TODO should we resolve LE address if matching RPA is connected? */
1254 
1255 	/*
1256 	 * For dualmode devices LE address is same as BR/EDR address and is of
1257 	 * public type.
1258 	 */
1259 	bt_addr_copy(&addr.a, &conn->br.dst);
1260 	addr.type = BT_ADDR_LE_PUBLIC;
1261 
1262 	keys = bt_keys_get_type(BT_KEYS_IRK, conn->id, &addr);
1263 	if (!keys) {
1264 		LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&addr));
1265 		return BT_SMP_ERR_UNSPECIFIED;
1266 	}
1267 
1268 	memcpy(keys->irk.val, req->irk, sizeof(keys->irk.val));
1269 
1270 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_IDENT_ADDR_INFO);
1271 
1272 	return 0;
1273 }
1274 
smp_br_ident_addr_info(struct bt_smp_br * smp,struct net_buf * buf)1275 static uint8_t smp_br_ident_addr_info(struct bt_smp_br *smp,
1276 				      struct net_buf *buf)
1277 {
1278 	struct bt_conn *conn = smp->chan.chan.conn;
1279 	struct bt_smp_ident_addr_info *req = (void *)buf->data;
1280 	bt_addr_le_t addr;
1281 
1282 	LOG_DBG("identity %s", bt_addr_le_str(&req->addr));
1283 
1284 	/*
1285 	 * For dual mode device identity address must be same as BR/EDR address
1286 	 * and be of public type. So if received one doesn't match BR/EDR
1287 	 * address we fail.
1288 	 */
1289 
1290 	bt_addr_copy(&addr.a, &conn->br.dst);
1291 	addr.type = BT_ADDR_LE_PUBLIC;
1292 
1293 	if (!bt_addr_le_eq(&addr, &req->addr)) {
1294 		return BT_SMP_ERR_UNSPECIFIED;
1295 	}
1296 
1297 	smp->remote_dist &= ~BT_SMP_DIST_ID_KEY;
1298 
1299 	if (smp->remote_dist & BT_SMP_DIST_SIGN) {
1300 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO);
1301 	}
1302 
1303 	if (conn->role == BT_CONN_ROLE_CENTRAL && !smp->remote_dist) {
1304 		smp_br_distribute_keys(smp);
1305 	}
1306 
1307 	/* if all keys were distributed, pairing is done */
1308 	if (!smp->local_dist && !smp->remote_dist) {
1309 		smp_pairing_br_complete(smp, 0);
1310 	}
1311 
1312 	return 0;
1313 }
1314 
1315 #if defined(CONFIG_BT_SIGNING)
smp_br_signing_info(struct bt_smp_br * smp,struct net_buf * buf)1316 static uint8_t smp_br_signing_info(struct bt_smp_br *smp, struct net_buf *buf)
1317 {
1318 	struct bt_smp_signing_info *req = (void *)buf->data;
1319 	struct bt_conn *conn = smp->chan.chan.conn;
1320 	struct bt_keys *keys;
1321 	bt_addr_le_t addr;
1322 
1323 	LOG_DBG("");
1324 
1325 	/*
1326 	 * For dualmode devices LE address is same as BR/EDR address and is of
1327 	 * public type.
1328 	 */
1329 	bt_addr_copy(&addr.a, &conn->br.dst);
1330 	addr.type = BT_ADDR_LE_PUBLIC;
1331 
1332 	keys = bt_keys_get_type(BT_KEYS_REMOTE_CSRK, conn->id, &addr);
1333 	if (!keys) {
1334 		LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&addr));
1335 		return BT_SMP_ERR_UNSPECIFIED;
1336 	}
1337 
1338 	memcpy(keys->remote_csrk.val, req->csrk, sizeof(keys->remote_csrk.val));
1339 
1340 	smp->remote_dist &= ~BT_SMP_DIST_SIGN;
1341 
1342 	if (conn->role == BT_CONN_ROLE_CENTRAL && !smp->remote_dist) {
1343 		smp_br_distribute_keys(smp);
1344 	}
1345 
1346 	/* if all keys were distributed, pairing is done */
1347 	if (!smp->local_dist && !smp->remote_dist) {
1348 		smp_pairing_br_complete(smp, 0);
1349 	}
1350 
1351 	return 0;
1352 }
1353 #else
smp_br_signing_info(struct bt_smp_br * smp,struct net_buf * buf)1354 static uint8_t smp_br_signing_info(struct bt_smp_br *smp, struct net_buf *buf)
1355 {
1356 	return BT_SMP_ERR_CMD_NOTSUPP;
1357 }
1358 #endif /* CONFIG_BT_SIGNING */
1359 
1360 static const struct {
1361 	uint8_t  (*func)(struct bt_smp_br *smp, struct net_buf *buf);
1362 	uint8_t  expect_len;
1363 } br_handlers[] = {
1364 	{ }, /* No op-code defined for 0x00 */
1365 	{ smp_br_pairing_req,      sizeof(struct bt_smp_pairing) },
1366 	{ smp_br_pairing_rsp,      sizeof(struct bt_smp_pairing) },
1367 	{ }, /* pairing confirm not used over BR/EDR */
1368 	{ }, /* pairing random not used over BR/EDR */
1369 	{ smp_br_pairing_failed,   sizeof(struct bt_smp_pairing_fail) },
1370 	{ }, /* encrypt info not used over BR/EDR */
1371 	{ }, /* central ident not used over BR/EDR */
1372 	{ smp_br_ident_info,       sizeof(struct bt_smp_ident_info) },
1373 	{ smp_br_ident_addr_info,  sizeof(struct bt_smp_ident_addr_info) },
1374 	{ smp_br_signing_info,     sizeof(struct bt_smp_signing_info) },
1375 	/* security request not used over BR/EDR */
1376 	/* public key not used over BR/EDR */
1377 	/* DHKey check not used over BR/EDR */
1378 };
1379 
smp_br_error(struct bt_smp_br * smp,uint8_t reason)1380 static int smp_br_error(struct bt_smp_br *smp, uint8_t reason)
1381 {
1382 	struct bt_smp_pairing_fail *rsp;
1383 	struct net_buf *buf;
1384 
1385 	/* reset context and report */
1386 	smp_br_reset(smp);
1387 
1388 	buf = smp_br_create_pdu(smp, BT_SMP_CMD_PAIRING_FAIL, sizeof(*rsp));
1389 	if (!buf) {
1390 		return -ENOBUFS;
1391 	}
1392 
1393 	rsp = net_buf_add(buf, sizeof(*rsp));
1394 	rsp->reason = reason;
1395 
1396 	/*
1397 	 * SMP timer is not restarted for PairingFailed so don't use
1398 	 * smp_br_send
1399 	 */
1400 	if (bt_l2cap_send(smp->chan.chan.conn, BT_L2CAP_CID_SMP, buf)) {
1401 		net_buf_unref(buf);
1402 	}
1403 
1404 	return 0;
1405 }
1406 
bt_smp_br_recv(struct bt_l2cap_chan * chan,struct net_buf * buf)1407 static int bt_smp_br_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
1408 {
1409 	struct bt_smp_br *smp = CONTAINER_OF(chan, struct bt_smp_br, chan.chan);
1410 	struct bt_smp_hdr *hdr;
1411 	uint8_t err;
1412 
1413 	if (buf->len < sizeof(*hdr)) {
1414 		LOG_ERR("Too small SMP PDU received");
1415 		return 0;
1416 	}
1417 
1418 	hdr = net_buf_pull_mem(buf, sizeof(*hdr));
1419 	LOG_DBG("Received SMP code 0x%02x len %u", hdr->code, buf->len);
1420 
1421 	/*
1422 	 * If SMP timeout occurred "no further SMP commands shall be sent over
1423 	 * the L2CAP Security Manager Channel. A new SM procedure shall only be
1424 	 * performed when a new physical link has been established."
1425 	 */
1426 	if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) {
1427 		LOG_WRN("SMP command (code 0x%02x) received after timeout", hdr->code);
1428 		return 0;
1429 	}
1430 
1431 	if (hdr->code >= ARRAY_SIZE(br_handlers) ||
1432 	    !br_handlers[hdr->code].func) {
1433 		LOG_WRN("Unhandled SMP code 0x%02x", hdr->code);
1434 		smp_br_error(smp, BT_SMP_ERR_CMD_NOTSUPP);
1435 		return 0;
1436 	}
1437 
1438 	if (!atomic_test_and_clear_bit(smp->allowed_cmds, hdr->code)) {
1439 		LOG_WRN("Unexpected SMP code 0x%02x", hdr->code);
1440 		smp_br_error(smp, BT_SMP_ERR_UNSPECIFIED);
1441 		return 0;
1442 	}
1443 
1444 	if (buf->len != br_handlers[hdr->code].expect_len) {
1445 		LOG_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code);
1446 		smp_br_error(smp, BT_SMP_ERR_INVALID_PARAMS);
1447 		return 0;
1448 	}
1449 
1450 	err = br_handlers[hdr->code].func(smp, buf);
1451 	if (err) {
1452 		smp_br_error(smp, err);
1453 	}
1454 
1455 	return 0;
1456 }
1457 
br_sc_supported(void)1458 static bool br_sc_supported(void)
1459 {
1460 	if (IS_ENABLED(CONFIG_BT_SMP_FORCE_BREDR)) {
1461 		LOG_WRN("Enabling BR/EDR SMP without BR/EDR SC support");
1462 		return true;
1463 	}
1464 
1465 	return BT_FEAT_SC(bt_dev.features);
1466 }
1467 
bt_smp_br_accept(struct bt_conn * conn,struct bt_l2cap_chan ** chan)1468 static int bt_smp_br_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan)
1469 {
1470 	static const struct bt_l2cap_chan_ops ops = {
1471 		.connected = bt_smp_br_connected,
1472 		.disconnected = bt_smp_br_disconnected,
1473 		.recv = bt_smp_br_recv,
1474 	};
1475 	int i;
1476 
1477 	/* Check BR/EDR SC is supported */
1478 	if (!br_sc_supported()) {
1479 		return -ENOTSUP;
1480 	}
1481 
1482 	LOG_DBG("conn %p handle %u", conn, conn->handle);
1483 
1484 	for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) {
1485 		struct bt_smp_br *smp = &bt_smp_br_pool[i];
1486 
1487 		if (smp->chan.chan.conn) {
1488 			continue;
1489 		}
1490 
1491 		smp->chan.chan.ops = &ops;
1492 
1493 		*chan = &smp->chan.chan;
1494 
1495 		k_work_init_delayable(&smp->work, smp_br_timeout);
1496 		smp_br_reset(smp);
1497 
1498 		return 0;
1499 	}
1500 
1501 	LOG_ERR("No available SMP context for conn %p", conn);
1502 
1503 	return -ENOMEM;
1504 }
1505 
smp_br_chan_get(struct bt_conn * conn)1506 static struct bt_smp_br *smp_br_chan_get(struct bt_conn *conn)
1507 {
1508 	struct bt_l2cap_chan *chan;
1509 
1510 	chan = bt_l2cap_br_lookup_rx_cid(conn, BT_L2CAP_CID_BR_SMP);
1511 	if (!chan) {
1512 		LOG_ERR("Unable to find SMP channel");
1513 		return NULL;
1514 	}
1515 
1516 	return CONTAINER_OF(chan, struct bt_smp_br, chan.chan);
1517 }
1518 
bt_smp_br_send_pairing_req(struct bt_conn * conn)1519 int bt_smp_br_send_pairing_req(struct bt_conn *conn)
1520 {
1521 	struct bt_smp_pairing *req;
1522 	struct net_buf *req_buf;
1523 	uint8_t max_key_size;
1524 	struct bt_smp_br *smp;
1525 
1526 	smp = smp_br_chan_get(conn);
1527 	if (!smp) {
1528 		return -ENOTCONN;
1529 	}
1530 
1531 	/* SMP Timeout */
1532 	if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) {
1533 		return -EIO;
1534 	}
1535 
1536 	/* pairing is in progress */
1537 	if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
1538 		return -EBUSY;
1539 	}
1540 
1541 	/* check if we are allowed to start SMP over BR/EDR */
1542 	if (!smp_br_pairing_allowed(smp)) {
1543 		return 0;
1544 	}
1545 
1546 	/* Channel not yet connected, will start pairing once connected */
1547 	if (!atomic_test_bit(smp->flags, SMP_FLAG_BR_CONNECTED)) {
1548 		atomic_set_bit(smp->flags, SMP_FLAG_BR_PAIR);
1549 		return 0;
1550 	}
1551 
1552 	max_key_size = bt_conn_enc_key_size(conn);
1553 	if (!max_key_size) {
1554 		LOG_DBG("Invalid encryption key size");
1555 		return -EIO;
1556 	}
1557 
1558 	smp_br_init(smp);
1559 	smp->enc_key_size = max_key_size;
1560 
1561 	req_buf = smp_br_create_pdu(smp, BT_SMP_CMD_PAIRING_REQ, sizeof(*req));
1562 	if (!req_buf) {
1563 		return -ENOBUFS;
1564 	}
1565 
1566 	req = net_buf_add(req_buf, sizeof(*req));
1567 
1568 	/*
1569 	 * If Secure Connections pairing has been initiated over BR/EDR, the IO
1570 	 * Capability, OOB data flag and Auth Req fields of the SM Pairing
1571 	 * Request/Response PDU shall be set to zero on transmission, and
1572 	 * ignored on reception.
1573 	 */
1574 
1575 	req->auth_req = 0x00;
1576 	req->io_capability = 0x00;
1577 	req->oob_flag = 0x00;
1578 	req->max_key_size = max_key_size;
1579 	req->init_key_dist = BR_SEND_KEYS_SC;
1580 	req->resp_key_dist = BR_RECV_KEYS_SC;
1581 
1582 	smp_br_send(smp, req_buf, NULL);
1583 
1584 	smp->local_dist = BR_SEND_KEYS_SC;
1585 	smp->remote_dist = BR_RECV_KEYS_SC;
1586 
1587 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RSP);
1588 
1589 	atomic_set_bit(smp->flags, SMP_FLAG_PAIRING);
1590 
1591 	return 0;
1592 }
1593 #endif /* CONFIG_BT_BREDR */
1594 
smp_reset(struct bt_smp * smp)1595 static void smp_reset(struct bt_smp *smp)
1596 {
1597 	struct bt_conn *conn = smp->chan.chan.conn;
1598 
1599 	/* Clear flags first in case canceling of timeout fails. The SMP context
1600 	 * shall be marked as timed out in that case.
1601 	 */
1602 	atomic_set(smp->flags, 0);
1603 
1604 	/* If canceling fails the timeout handler will set the timeout flag and
1605 	 * mark the it as timed out. No new pairing procedures shall be started
1606 	 * on this connection if that happens.
1607 	 */
1608 	(void)k_work_cancel_delayable(&smp->work);
1609 
1610 	smp->method = JUST_WORKS;
1611 	atomic_set(smp->allowed_cmds, 0);
1612 
1613 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
1614 	    conn->role == BT_HCI_ROLE_CENTRAL) {
1615 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST);
1616 		return;
1617 	}
1618 
1619 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
1620 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_REQ);
1621 	}
1622 }
1623 
hci_err_get(enum bt_security_err err)1624 static uint8_t hci_err_get(enum bt_security_err err)
1625 {
1626 	switch (err) {
1627 	case BT_SECURITY_ERR_SUCCESS:
1628 		return BT_HCI_ERR_SUCCESS;
1629 	case BT_SECURITY_ERR_AUTH_FAIL:
1630 		return BT_HCI_ERR_AUTH_FAIL;
1631 	case BT_SECURITY_ERR_PIN_OR_KEY_MISSING:
1632 		return BT_HCI_ERR_PIN_OR_KEY_MISSING;
1633 	case BT_SECURITY_ERR_PAIR_NOT_SUPPORTED:
1634 		return BT_HCI_ERR_PAIRING_NOT_SUPPORTED;
1635 	case BT_SECURITY_ERR_PAIR_NOT_ALLOWED:
1636 		return BT_HCI_ERR_PAIRING_NOT_ALLOWED;
1637 	case BT_SECURITY_ERR_INVALID_PARAM:
1638 		return BT_HCI_ERR_INVALID_PARAM;
1639 	default:
1640 		return BT_HCI_ERR_UNSPECIFIED;
1641 	}
1642 }
1643 
1644 /* Note: This function not only does set the status but also calls smp_reset
1645  * at the end which clears any flags previously set.
1646  */
smp_pairing_complete(struct bt_smp * smp,uint8_t status)1647 static void smp_pairing_complete(struct bt_smp *smp, uint8_t status)
1648 {
1649 	struct bt_conn *conn = smp->chan.chan.conn;
1650 
1651 	LOG_DBG("got status 0x%x", status);
1652 
1653 	if (conn->le.keys == NULL) {
1654 		/* We can get here if the application calls `bt_unpair` in the
1655 		 * `security_changed` callback.
1656 		 */
1657 		LOG_WRN("The in-progress pairing has been deleted!");
1658 		status = BT_SMP_ERR_UNSPECIFIED;
1659 	}
1660 
1661 	if (!status) {
1662 #if defined(CONFIG_BT_BREDR)
1663 		/*
1664 		 * Don't derive if Debug Keys are used.
1665 		 * TODO should we allow this if BR/EDR is already connected?
1666 		 */
1667 		if (atomic_test_bit(smp->flags, SMP_FLAG_DERIVE_LK) &&
1668 		    (!atomic_test_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY) ||
1669 		     IS_ENABLED(CONFIG_BT_STORE_DEBUG_KEYS))) {
1670 			sc_derive_link_key(smp);
1671 		}
1672 #endif /* CONFIG_BT_BREDR */
1673 		bool bond_flag = atomic_test_bit(smp->flags, SMP_FLAG_BOND);
1674 		struct bt_conn_auth_info_cb *listener, *next;
1675 
1676 		if (IS_ENABLED(CONFIG_BT_LOG_SNIFFER_INFO)) {
1677 			bt_keys_show_sniffer_info(conn->le.keys, NULL);
1678 		}
1679 
1680 		if (bond_flag && conn->le.keys) {
1681 			bt_keys_store(conn->le.keys);
1682 		}
1683 
1684 		SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&bt_auth_info_cbs, listener,
1685 						  next, node) {
1686 			if (listener->pairing_complete) {
1687 				listener->pairing_complete(conn, bond_flag);
1688 			}
1689 		}
1690 	} else {
1691 		enum bt_security_err security_err = security_err_get(status);
1692 
1693 		/* Clear the key pool entry in case of pairing failure if the
1694 		 * keys already existed before the pairing procedure or the
1695 		 * pairing failed during key distribution.
1696 		 */
1697 		if (conn->le.keys &&
1698 		    (!conn->le.keys->enc_size ||
1699 		     atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR))) {
1700 			bt_keys_clear(conn->le.keys);
1701 			conn->le.keys = NULL;
1702 		}
1703 
1704 		if (!atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR)) {
1705 			bt_conn_security_changed(conn,
1706 						 hci_err_get(security_err),
1707 						 security_err);
1708 		}
1709 
1710 		/* Check SMP_FLAG_PAIRING as bt_conn_security_changed may
1711 		 * have called the pairing_failed callback already.
1712 		 */
1713 		if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
1714 			struct bt_conn_auth_info_cb *listener, *next;
1715 
1716 			SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&bt_auth_info_cbs,
1717 							  listener, next,
1718 							  node) {
1719 				if (listener->pairing_failed) {
1720 					listener->pairing_failed(conn, security_err);
1721 				}
1722 			}
1723 		}
1724 	}
1725 
1726 	smp_reset(smp);
1727 
1728 	if (conn->state == BT_CONN_CONNECTED && conn->sec_level != conn->required_sec_level) {
1729 		bt_smp_start_security(conn);
1730 	}
1731 }
1732 
smp_timeout(struct k_work * work)1733 static void smp_timeout(struct k_work *work)
1734 {
1735 	struct k_work_delayable *dwork = k_work_delayable_from_work(work);
1736 	struct bt_smp *smp = CONTAINER_OF(dwork, struct bt_smp, work);
1737 
1738 	LOG_ERR("SMP Timeout");
1739 
1740 	smp_pairing_complete(smp, BT_SMP_ERR_UNSPECIFIED);
1741 
1742 	/* smp_pairing_complete clears flags so setting timeout flag must come
1743 	 * after it.
1744 	 */
1745 	atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT);
1746 }
1747 
smp_send(struct bt_smp * smp,struct net_buf * buf,bt_conn_tx_cb_t cb,void * user_data)1748 static void smp_send(struct bt_smp *smp, struct net_buf *buf,
1749 		     bt_conn_tx_cb_t cb, void *user_data)
1750 {
1751 	int err = bt_l2cap_send_cb(smp->chan.chan.conn, BT_L2CAP_CID_SMP, buf, cb, NULL);
1752 
1753 	if (err) {
1754 		if (err == -ENOBUFS) {
1755 			LOG_ERR("Ran out of TX buffers or contexts.");
1756 		}
1757 
1758 		net_buf_unref(buf);
1759 		return;
1760 	}
1761 
1762 	k_work_reschedule(&smp->work, SMP_TIMEOUT);
1763 }
1764 
smp_error(struct bt_smp * smp,uint8_t reason)1765 static int smp_error(struct bt_smp *smp, uint8_t reason)
1766 {
1767 	struct bt_smp_pairing_fail *rsp;
1768 	struct net_buf *buf;
1769 	bool remote_already_completed;
1770 
1771 	/* By spec, SMP "pairing process" completes successfully when the last
1772 	 * key to distribute is acknowledged at link-layer.
1773 	 */
1774 	remote_already_completed = (atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR) &&
1775 				    !smp->local_dist && !smp->remote_dist);
1776 
1777 	if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING) ||
1778 	    atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING) ||
1779 	    atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ)) {
1780 		/* reset context and report */
1781 		smp_pairing_complete(smp, reason);
1782 	}
1783 
1784 	if (remote_already_completed) {
1785 		LOG_WRN("SMP does not allow a pairing failure at this point. Known issue. "
1786 			"Disconnecting instead.");
1787 		/* We are probably here because we are, as a peripheral, rejecting a pairing based
1788 		 * on the central's identity address information, but that was the last key to
1789 		 * be transmitted. In that case, the pairing process is already completed.
1790 		 * The SMP protocol states that the pairing process is completed the moment the
1791 		 * peripheral link-layer confirmed the reception of the PDU with the last key.
1792 		 */
1793 		bt_conn_disconnect(smp->chan.chan.conn, BT_HCI_ERR_AUTH_FAIL);
1794 		return 0;
1795 	}
1796 
1797 	buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_FAIL, sizeof(*rsp));
1798 	if (!buf) {
1799 		return -ENOBUFS;
1800 	}
1801 
1802 	rsp = net_buf_add(buf, sizeof(*rsp));
1803 	rsp->reason = reason;
1804 
1805 	/* SMP timer is not restarted for PairingFailed so don't use smp_send */
1806 	if (bt_l2cap_send(smp->chan.chan.conn, BT_L2CAP_CID_SMP, buf)) {
1807 		net_buf_unref(buf);
1808 	}
1809 
1810 	return 0;
1811 }
1812 
smp_send_pairing_random(struct bt_smp * smp)1813 static uint8_t smp_send_pairing_random(struct bt_smp *smp)
1814 {
1815 	struct bt_smp_pairing_random *req;
1816 	struct net_buf *rsp_buf;
1817 
1818 	rsp_buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_RANDOM, sizeof(*req));
1819 	if (!rsp_buf) {
1820 		return BT_SMP_ERR_UNSPECIFIED;
1821 	}
1822 
1823 	req = net_buf_add(rsp_buf, sizeof(*req));
1824 	memcpy(req->val, smp->prnd, sizeof(req->val));
1825 
1826 	smp_send(smp, rsp_buf, NULL, NULL);
1827 
1828 	return 0;
1829 }
1830 
1831 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
smp_c1(const uint8_t k[16],const uint8_t r[16],const uint8_t preq[7],const uint8_t pres[7],const bt_addr_le_t * ia,const bt_addr_le_t * ra,uint8_t enc_data[16])1832 static int smp_c1(const uint8_t k[16], const uint8_t r[16],
1833 		  const uint8_t preq[7], const uint8_t pres[7],
1834 		  const bt_addr_le_t *ia, const bt_addr_le_t *ra,
1835 		  uint8_t enc_data[16])
1836 {
1837 	uint8_t p1[16], p2[16];
1838 	int err;
1839 
1840 	LOG_DBG("k %s", bt_hex(k, 16));
1841 	LOG_DBG("r %s", bt_hex(r, 16));
1842 	LOG_DBG("ia %s", bt_addr_le_str(ia));
1843 	LOG_DBG("ra %s", bt_addr_le_str(ra));
1844 	LOG_DBG("preq %s", bt_hex(preq, 7));
1845 	LOG_DBG("pres %s", bt_hex(pres, 7));
1846 
1847 	/* pres, preq, rat and iat are concatenated to generate p1 */
1848 	p1[0] = ia->type;
1849 	p1[1] = ra->type;
1850 	memcpy(p1 + 2, preq, 7);
1851 	memcpy(p1 + 9, pres, 7);
1852 
1853 	LOG_DBG("p1 %s", bt_hex(p1, 16));
1854 
1855 	/* c1 = e(k, e(k, r XOR p1) XOR p2) */
1856 
1857 	/* Using enc_data as temporary output buffer */
1858 	mem_xor_128(enc_data, r, p1);
1859 
1860 	err = bt_encrypt_le(k, enc_data, enc_data);
1861 	if (err) {
1862 		return err;
1863 	}
1864 
1865 	/* ra is concatenated with ia and padding to generate p2 */
1866 	memcpy(p2, ra->a.val, 6);
1867 	memcpy(p2 + 6, ia->a.val, 6);
1868 	(void)memset(p2 + 12, 0, 4);
1869 
1870 	LOG_DBG("p2 %s", bt_hex(p2, 16));
1871 
1872 	mem_xor_128(enc_data, p2, enc_data);
1873 
1874 	return bt_encrypt_le(k, enc_data, enc_data);
1875 }
1876 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
1877 
smp_send_pairing_confirm(struct bt_smp * smp)1878 static uint8_t smp_send_pairing_confirm(struct bt_smp *smp)
1879 {
1880 	struct bt_smp_pairing_confirm *req;
1881 	struct net_buf *buf;
1882 	uint8_t r;
1883 
1884 	switch (smp->method) {
1885 	case PASSKEY_CONFIRM:
1886 	case JUST_WORKS:
1887 		r = 0U;
1888 		break;
1889 	case PASSKEY_DISPLAY:
1890 	case PASSKEY_INPUT:
1891 		/*
1892 		 * In the Passkey Entry protocol, the most significant
1893 		 * bit of Z is set equal to one and the least
1894 		 * significant bit is made up from one bit of the
1895 		 * passkey e.g. if the passkey bit is 1, then Z = 0x81
1896 		 * and if the passkey bit is 0, then Z = 0x80.
1897 		 */
1898 		r = (smp->passkey >> smp->passkey_round) & 0x01;
1899 		r |= 0x80;
1900 		break;
1901 	default:
1902 		LOG_ERR("Unknown pairing method (%u)", smp->method);
1903 		return BT_SMP_ERR_UNSPECIFIED;
1904 	}
1905 
1906 	buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_CONFIRM, sizeof(*req));
1907 	if (!buf) {
1908 		return BT_SMP_ERR_UNSPECIFIED;
1909 	}
1910 
1911 	req = net_buf_add(buf, sizeof(*req));
1912 
1913 	if (bt_crypto_f4(sc_public_key, smp->pkey, smp->prnd, r, req->val)) {
1914 		net_buf_unref(buf);
1915 		return BT_SMP_ERR_UNSPECIFIED;
1916 	}
1917 
1918 	smp_send(smp, buf, NULL, NULL);
1919 
1920 	atomic_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED);
1921 
1922 	return 0;
1923 }
1924 
1925 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
smp_ident_sent(struct bt_conn * conn,void * user_data,int err)1926 static void smp_ident_sent(struct bt_conn *conn, void *user_data, int err)
1927 {
1928 	if (!err) {
1929 		smp_check_complete(conn, BT_SMP_DIST_ENC_KEY);
1930 	}
1931 }
1932 
legacy_distribute_keys(struct bt_smp * smp)1933 static void legacy_distribute_keys(struct bt_smp *smp)
1934 {
1935 	struct bt_conn *conn = smp->chan.chan.conn;
1936 	struct bt_keys *keys = conn->le.keys;
1937 
1938 	if (smp->local_dist & BT_SMP_DIST_ENC_KEY) {
1939 		struct bt_smp_encrypt_info *info;
1940 		struct bt_smp_central_ident *ident;
1941 		struct net_buf *buf;
1942 		/* Use struct to get randomness in single call to bt_rand */
1943 		struct {
1944 			uint8_t key[16];
1945 			uint8_t rand[8];
1946 			uint8_t ediv[2];
1947 		} rand;
1948 
1949 		if (bt_rand((void *)&rand, sizeof(rand))) {
1950 			LOG_ERR("Unable to get random bytes");
1951 			return;
1952 		}
1953 
1954 		buf = smp_create_pdu(smp, BT_SMP_CMD_ENCRYPT_INFO,
1955 				     sizeof(*info));
1956 		if (!buf) {
1957 			LOG_ERR("Unable to allocate Encrypt Info buffer");
1958 			return;
1959 		}
1960 
1961 		info = net_buf_add(buf, sizeof(*info));
1962 
1963 		/* distributed only enc_size bytes of key */
1964 		memcpy(info->ltk, rand.key, keys->enc_size);
1965 		if (keys->enc_size < sizeof(info->ltk)) {
1966 			(void)memset(info->ltk + keys->enc_size, 0,
1967 				     sizeof(info->ltk) - keys->enc_size);
1968 		}
1969 
1970 		smp_send(smp, buf, NULL, NULL);
1971 
1972 		buf = smp_create_pdu(smp, BT_SMP_CMD_CENTRAL_IDENT,
1973 				     sizeof(*ident));
1974 		if (!buf) {
1975 			LOG_ERR("Unable to allocate Central Ident buffer");
1976 			return;
1977 		}
1978 
1979 		ident = net_buf_add(buf, sizeof(*ident));
1980 		memcpy(ident->rand, rand.rand, sizeof(ident->rand));
1981 		memcpy(ident->ediv, rand.ediv, sizeof(ident->ediv));
1982 
1983 		smp_send(smp, buf, smp_ident_sent, NULL);
1984 
1985 		if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
1986 			bt_keys_add_type(keys, BT_KEYS_PERIPH_LTK);
1987 
1988 			memcpy(keys->periph_ltk.val, rand.key,
1989 			       sizeof(keys->periph_ltk.val));
1990 			memcpy(keys->periph_ltk.rand, rand.rand,
1991 			       sizeof(keys->periph_ltk.rand));
1992 			memcpy(keys->periph_ltk.ediv, rand.ediv,
1993 			       sizeof(keys->periph_ltk.ediv));
1994 		}
1995 	}
1996 }
1997 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
1998 
bt_smp_distribute_keys(struct bt_smp * smp)1999 static uint8_t bt_smp_distribute_keys(struct bt_smp *smp)
2000 {
2001 	struct bt_conn *conn = smp->chan.chan.conn;
2002 	struct bt_keys *keys = conn->le.keys;
2003 
2004 	if (!keys) {
2005 		LOG_ERR("No keys space for %s", bt_addr_le_str(&conn->le.dst));
2006 		return BT_SMP_ERR_UNSPECIFIED;
2007 	}
2008 
2009 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
2010 	/* Distribute legacy pairing specific keys */
2011 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
2012 		legacy_distribute_keys(smp);
2013 	}
2014 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
2015 
2016 #if defined(CONFIG_BT_PRIVACY)
2017 	if (smp->local_dist & BT_SMP_DIST_ID_KEY) {
2018 		struct bt_smp_ident_info *id_info;
2019 		struct bt_smp_ident_addr_info *id_addr_info;
2020 		struct net_buf *buf;
2021 
2022 		buf = smp_create_pdu(smp, BT_SMP_CMD_IDENT_INFO,
2023 				     sizeof(*id_info));
2024 		if (!buf) {
2025 			LOG_ERR("Unable to allocate Ident Info buffer");
2026 			return BT_SMP_ERR_UNSPECIFIED;
2027 		}
2028 
2029 		id_info = net_buf_add(buf, sizeof(*id_info));
2030 		memcpy(id_info->irk, bt_dev.irk[conn->id], 16);
2031 
2032 		smp_send(smp, buf, NULL, NULL);
2033 
2034 		buf = smp_create_pdu(smp, BT_SMP_CMD_IDENT_ADDR_INFO,
2035 				     sizeof(*id_addr_info));
2036 		if (!buf) {
2037 			LOG_ERR("Unable to allocate Ident Addr Info buffer");
2038 			return BT_SMP_ERR_UNSPECIFIED;
2039 		}
2040 
2041 		id_addr_info = net_buf_add(buf, sizeof(*id_addr_info));
2042 		bt_addr_le_copy(&id_addr_info->addr, &bt_dev.id_addr[conn->id]);
2043 
2044 		smp_send(smp, buf, smp_id_sent, NULL);
2045 	}
2046 #endif /* CONFIG_BT_PRIVACY */
2047 
2048 #if defined(CONFIG_BT_SIGNING)
2049 	if (smp->local_dist & BT_SMP_DIST_SIGN) {
2050 		struct bt_smp_signing_info *info;
2051 		struct net_buf *buf;
2052 
2053 		buf = smp_create_pdu(smp, BT_SMP_CMD_SIGNING_INFO,
2054 				     sizeof(*info));
2055 		if (!buf) {
2056 			LOG_ERR("Unable to allocate Signing Info buffer");
2057 			return BT_SMP_ERR_UNSPECIFIED;
2058 		}
2059 
2060 		info = net_buf_add(buf, sizeof(*info));
2061 
2062 		if (bt_rand(info->csrk, sizeof(info->csrk))) {
2063 			return BT_SMP_ERR_UNSPECIFIED;
2064 		}
2065 
2066 		if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
2067 			bt_keys_add_type(keys, BT_KEYS_LOCAL_CSRK);
2068 			memcpy(keys->local_csrk.val, info->csrk, 16);
2069 			keys->local_csrk.cnt = 0U;
2070 		}
2071 
2072 		smp_send(smp, buf, smp_sign_info_sent, NULL);
2073 	}
2074 #endif /* CONFIG_BT_SIGNING */
2075 
2076 	return 0;
2077 }
2078 
2079 #if defined(CONFIG_BT_PERIPHERAL)
send_pairing_rsp(struct bt_smp * smp)2080 static uint8_t send_pairing_rsp(struct bt_smp *smp)
2081 {
2082 	struct bt_smp_pairing *rsp;
2083 	struct net_buf *rsp_buf;
2084 
2085 	rsp_buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_RSP, sizeof(*rsp));
2086 	if (!rsp_buf) {
2087 		return BT_SMP_ERR_UNSPECIFIED;
2088 	}
2089 
2090 	rsp = net_buf_add(rsp_buf, sizeof(*rsp));
2091 	memcpy(rsp, smp->prsp + 1, sizeof(*rsp));
2092 
2093 	smp_send(smp, rsp_buf, NULL, NULL);
2094 
2095 	return 0;
2096 }
2097 #endif /* CONFIG_BT_PERIPHERAL */
2098 
smp_pairing_accept_query(struct bt_smp * smp,struct bt_smp_pairing * pairing)2099 static uint8_t smp_pairing_accept_query(struct bt_smp *smp, struct bt_smp_pairing *pairing)
2100 {
2101 #if defined(CONFIG_BT_SMP_APP_PAIRING_ACCEPT)
2102 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
2103 	struct bt_conn *conn = smp->chan.chan.conn;
2104 
2105 	if (smp_auth_cb && smp_auth_cb->pairing_accept) {
2106 		const struct bt_conn_pairing_feat feat = {
2107 			.io_capability = pairing->io_capability,
2108 			.oob_data_flag = pairing->oob_flag,
2109 			.auth_req = pairing->auth_req,
2110 			.max_enc_key_size = pairing->max_key_size,
2111 			.init_key_dist = pairing->init_key_dist,
2112 			.resp_key_dist = pairing->resp_key_dist
2113 		};
2114 
2115 		return smp_err_get(smp_auth_cb->pairing_accept(conn, &feat));
2116 	}
2117 #endif /* CONFIG_BT_SMP_APP_PAIRING_ACCEPT */
2118 	return 0;
2119 }
2120 
2121 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
smp_s1(const uint8_t k[16],const uint8_t r1[16],const uint8_t r2[16],uint8_t out[16])2122 static int smp_s1(const uint8_t k[16], const uint8_t r1[16],
2123 		  const uint8_t r2[16], uint8_t out[16])
2124 {
2125 	/* The most significant 64-bits of r1 are discarded to generate
2126 	 * r1' and the most significant 64-bits of r2 are discarded to
2127 	 * generate r2'.
2128 	 * r1' is concatenated with r2' to generate r' which is used as
2129 	 * the 128-bit input parameter plaintextData to security function e:
2130 	 *
2131 	 *    r' = r1' || r2'
2132 	 */
2133 	memcpy(out, r2, 8);
2134 	memcpy(out + 8, r1, 8);
2135 
2136 	/* s1(k, r1 , r2) = e(k, r') */
2137 	return bt_encrypt_le(k, out, out);
2138 }
2139 
legacy_get_pair_method(struct bt_smp * smp,uint8_t remote_io)2140 static uint8_t legacy_get_pair_method(struct bt_smp *smp, uint8_t remote_io)
2141 {
2142 	struct bt_smp_pairing *req, *rsp;
2143 	uint8_t method;
2144 
2145 	if (remote_io > BT_SMP_IO_KEYBOARD_DISPLAY) {
2146 		return JUST_WORKS;
2147 	}
2148 
2149 	req = (struct bt_smp_pairing *)&smp->preq[1];
2150 	rsp = (struct bt_smp_pairing *)&smp->prsp[1];
2151 
2152 	/* if both sides have OOB data use OOB */
2153 	if ((req->oob_flag & rsp->oob_flag) & BT_SMP_OOB_DATA_MASK) {
2154 		return LEGACY_OOB;
2155 	}
2156 
2157 	/* if none side requires MITM use JustWorks */
2158 	if (!((req->auth_req | rsp->auth_req) & BT_SMP_AUTH_MITM)) {
2159 		return JUST_WORKS;
2160 	}
2161 
2162 	method = gen_method_legacy[remote_io][get_io_capa(smp)];
2163 
2164 	/* if both sides have KeyboardDisplay capabilities, initiator displays
2165 	 * and responder inputs
2166 	 */
2167 	if (method == PASSKEY_ROLE) {
2168 		if (smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
2169 			method = PASSKEY_DISPLAY;
2170 		} else {
2171 			method = PASSKEY_INPUT;
2172 		}
2173 	}
2174 
2175 	return method;
2176 }
2177 
legacy_request_tk(struct bt_smp * smp)2178 static uint8_t legacy_request_tk(struct bt_smp *smp)
2179 {
2180 	struct bt_conn *conn = smp->chan.chan.conn;
2181 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
2182 	struct bt_keys *keys;
2183 	uint32_t passkey;
2184 
2185 	/*
2186 	 * Fail if we have keys that are stronger than keys that will be
2187 	 * distributed in new pairing. This is to avoid replacing authenticated
2188 	 * keys with unauthenticated ones.
2189 	  */
2190 	keys = bt_keys_find_addr(conn->id, &conn->le.dst);
2191 	if (keys && (keys->flags & BT_KEYS_AUTHENTICATED) &&
2192 	    smp->method == JUST_WORKS) {
2193 		LOG_ERR("JustWorks failed, authenticated keys present");
2194 		return BT_SMP_ERR_UNSPECIFIED;
2195 	}
2196 
2197 	switch (smp->method) {
2198 	case LEGACY_OOB:
2199 		if (smp_auth_cb && smp_auth_cb->oob_data_request) {
2200 			struct bt_conn_oob_info info = {
2201 				.type = BT_CONN_OOB_LE_LEGACY,
2202 			};
2203 
2204 			atomic_set_bit(smp->flags, SMP_FLAG_USER);
2205 			smp_auth_cb->oob_data_request(smp->chan.chan.conn, &info);
2206 		} else {
2207 			return BT_SMP_ERR_OOB_NOT_AVAIL;
2208 		}
2209 
2210 		break;
2211 	case PASSKEY_DISPLAY:
2212 		if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) &&
2213 		    fixed_passkey != BT_PASSKEY_INVALID) {
2214 			passkey = fixed_passkey;
2215 		} else  {
2216 			if (bt_rand(&passkey, sizeof(passkey))) {
2217 				return BT_SMP_ERR_UNSPECIFIED;
2218 			}
2219 
2220 			passkey %= 1000000;
2221 		}
2222 
2223 		if (IS_ENABLED(CONFIG_BT_LOG_SNIFFER_INFO)) {
2224 			LOG_INF("Legacy passkey %u", passkey);
2225 		}
2226 
2227 		if (smp_auth_cb && smp_auth_cb->passkey_display) {
2228 			atomic_set_bit(smp->flags, SMP_FLAG_DISPLAY);
2229 			smp_auth_cb->passkey_display(conn, passkey);
2230 		}
2231 
2232 		sys_put_le32(passkey, smp->tk);
2233 
2234 		break;
2235 	case PASSKEY_INPUT:
2236 		atomic_set_bit(smp->flags, SMP_FLAG_USER);
2237 		smp_auth_cb->passkey_entry(conn);
2238 		break;
2239 	case JUST_WORKS:
2240 		break;
2241 	default:
2242 		LOG_ERR("Unknown pairing method (%u)", smp->method);
2243 		return BT_SMP_ERR_UNSPECIFIED;
2244 	}
2245 
2246 	return 0;
2247 }
2248 
legacy_send_pairing_confirm(struct bt_smp * smp)2249 static uint8_t legacy_send_pairing_confirm(struct bt_smp *smp)
2250 {
2251 	struct bt_conn *conn = smp->chan.chan.conn;
2252 	struct bt_smp_pairing_confirm *req;
2253 	struct net_buf *buf;
2254 
2255 	buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_CONFIRM, sizeof(*req));
2256 	if (!buf) {
2257 		return BT_SMP_ERR_UNSPECIFIED;
2258 	}
2259 
2260 	req = net_buf_add(buf, sizeof(*req));
2261 
2262 	if (smp_c1(smp->tk, smp->prnd, smp->preq, smp->prsp,
2263 		   &conn->le.init_addr, &conn->le.resp_addr, req->val)) {
2264 		net_buf_unref(buf);
2265 		return BT_SMP_ERR_UNSPECIFIED;
2266 	}
2267 
2268 	smp_send(smp, buf, NULL, NULL);
2269 
2270 	atomic_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED);
2271 
2272 	return 0;
2273 }
2274 
2275 #if defined(CONFIG_BT_PERIPHERAL)
legacy_pairing_req(struct bt_smp * smp)2276 static uint8_t legacy_pairing_req(struct bt_smp *smp)
2277 {
2278 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
2279 	uint8_t ret;
2280 
2281 	LOG_DBG("");
2282 
2283 	ret = legacy_request_tk(smp);
2284 	if (ret) {
2285 		return ret;
2286 	}
2287 
2288 	/* ask for consent if pairing is not due to sending SecReq*/
2289 	if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) &&
2290 	    !atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) &&
2291 	    smp_auth_cb && smp_auth_cb->pairing_confirm) {
2292 		atomic_set_bit(smp->flags, SMP_FLAG_USER);
2293 		smp_auth_cb->pairing_confirm(smp->chan.chan.conn);
2294 		return 0;
2295 	}
2296 
2297 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM);
2298 	atomic_set_bit(smp->allowed_cmds, BT_SMP_KEYPRESS_NOTIFICATION);
2299 	return send_pairing_rsp(smp);
2300 }
2301 #endif /* CONFIG_BT_PERIPHERAL */
2302 
legacy_pairing_random(struct bt_smp * smp)2303 static uint8_t legacy_pairing_random(struct bt_smp *smp)
2304 {
2305 	struct bt_conn *conn = smp->chan.chan.conn;
2306 	uint8_t tmp[16];
2307 	int err;
2308 
2309 	LOG_DBG("");
2310 
2311 	/* calculate confirmation */
2312 	err = smp_c1(smp->tk, smp->rrnd, smp->preq, smp->prsp,
2313 		     &conn->le.init_addr, &conn->le.resp_addr, tmp);
2314 	if (err) {
2315 		return BT_SMP_ERR_UNSPECIFIED;
2316 	}
2317 
2318 	LOG_DBG("pcnf %s", bt_hex(smp->pcnf, 16));
2319 	LOG_DBG("cfm %s", bt_hex(tmp, 16));
2320 
2321 	if (memcmp(smp->pcnf, tmp, sizeof(smp->pcnf))) {
2322 		return BT_SMP_ERR_CONFIRM_FAILED;
2323 	}
2324 
2325 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
2326 	    conn->role == BT_HCI_ROLE_CENTRAL) {
2327 		uint8_t ediv[2], rand[8];
2328 
2329 		/* No need to store central STK */
2330 		err = smp_s1(smp->tk, smp->rrnd, smp->prnd, tmp);
2331 		if (err) {
2332 			return BT_SMP_ERR_UNSPECIFIED;
2333 		}
2334 
2335 		/* Rand and EDiv are 0 for the STK */
2336 		(void)memset(ediv, 0, sizeof(ediv));
2337 		(void)memset(rand, 0, sizeof(rand));
2338 		if (bt_conn_le_start_encryption(conn, rand, ediv, tmp,
2339 						get_encryption_key_size(smp))) {
2340 			LOG_ERR("Failed to start encryption");
2341 			return BT_SMP_ERR_UNSPECIFIED;
2342 		}
2343 
2344 		atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
2345 
2346 		if (IS_ENABLED(CONFIG_BT_SMP_USB_HCI_CTLR_WORKAROUND)) {
2347 			if (smp->remote_dist & BT_SMP_DIST_ENC_KEY) {
2348 				atomic_set_bit(smp->allowed_cmds,
2349 					       BT_SMP_CMD_ENCRYPT_INFO);
2350 			} else if (smp->remote_dist & BT_SMP_DIST_ID_KEY) {
2351 				atomic_set_bit(smp->allowed_cmds,
2352 					       BT_SMP_CMD_IDENT_INFO);
2353 			} else if (smp->remote_dist & BT_SMP_DIST_SIGN) {
2354 				atomic_set_bit(smp->allowed_cmds,
2355 					       BT_SMP_CMD_SIGNING_INFO);
2356 			}
2357 		}
2358 
2359 		return 0;
2360 	}
2361 
2362 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
2363 		err = smp_s1(smp->tk, smp->prnd, smp->rrnd, tmp);
2364 		if (err) {
2365 			LOG_ERR("Calculate STK failed");
2366 			return BT_SMP_ERR_UNSPECIFIED;
2367 		}
2368 
2369 		memcpy(smp->tk, tmp, sizeof(smp->tk));
2370 		LOG_DBG("generated STK %s", bt_hex(smp->tk, 16));
2371 
2372 		atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
2373 
2374 		return smp_send_pairing_random(smp);
2375 	}
2376 
2377 	return 0;
2378 }
2379 
legacy_pairing_confirm(struct bt_smp * smp)2380 static uint8_t legacy_pairing_confirm(struct bt_smp *smp)
2381 {
2382 	LOG_DBG("");
2383 
2384 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
2385 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
2386 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM);
2387 		return legacy_send_pairing_confirm(smp);
2388 	}
2389 
2390 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
2391 		if (!atomic_test_bit(smp->flags, SMP_FLAG_USER)) {
2392 			atomic_set_bit(smp->allowed_cmds,
2393 				       BT_SMP_CMD_PAIRING_RANDOM);
2394 			return legacy_send_pairing_confirm(smp);
2395 		}
2396 
2397 		atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED);
2398 	}
2399 
2400 	return 0;
2401 }
2402 
legacy_user_tk_entry(struct bt_smp * smp)2403 static void legacy_user_tk_entry(struct bt_smp *smp)
2404 {
2405 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED)) {
2406 		return;
2407 	}
2408 
2409 	/* if confirm failed ie. due to invalid passkey, cancel pairing */
2410 	if (legacy_pairing_confirm(smp)) {
2411 		smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED);
2412 		return;
2413 	}
2414 
2415 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
2416 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
2417 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM);
2418 		return;
2419 	}
2420 
2421 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
2422 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
2423 	}
2424 }
2425 
legacy_passkey_entry(struct bt_smp * smp,unsigned int passkey)2426 static void legacy_passkey_entry(struct bt_smp *smp, unsigned int passkey)
2427 {
2428 	passkey = sys_cpu_to_le32(passkey);
2429 	memcpy(smp->tk, &passkey, sizeof(passkey));
2430 
2431 	legacy_user_tk_entry(smp);
2432 }
2433 
smp_encrypt_info(struct bt_smp * smp,struct net_buf * buf)2434 static uint8_t smp_encrypt_info(struct bt_smp *smp, struct net_buf *buf)
2435 {
2436 	LOG_DBG("");
2437 
2438 	if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
2439 		struct bt_smp_encrypt_info *req = (void *)buf->data;
2440 		struct bt_conn *conn = smp->chan.chan.conn;
2441 		struct bt_keys *keys;
2442 
2443 		keys = bt_keys_get_type(BT_KEYS_LTK, conn->id, &conn->le.dst);
2444 		if (!keys) {
2445 			LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst));
2446 			return BT_SMP_ERR_UNSPECIFIED;
2447 		}
2448 
2449 		memcpy(keys->ltk.val, req->ltk, 16);
2450 	}
2451 
2452 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_CENTRAL_IDENT);
2453 
2454 	return 0;
2455 }
2456 
smp_central_ident(struct bt_smp * smp,struct net_buf * buf)2457 static uint8_t smp_central_ident(struct bt_smp *smp, struct net_buf *buf)
2458 {
2459 	struct bt_conn *conn = smp->chan.chan.conn;
2460 	uint8_t err;
2461 
2462 	LOG_DBG("");
2463 
2464 	if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
2465 		struct bt_smp_central_ident *req = (void *)buf->data;
2466 		struct bt_keys *keys;
2467 
2468 		keys = bt_keys_get_type(BT_KEYS_LTK, conn->id, &conn->le.dst);
2469 		if (!keys) {
2470 			LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst));
2471 			return BT_SMP_ERR_UNSPECIFIED;
2472 		}
2473 
2474 		memcpy(keys->ltk.ediv, req->ediv, sizeof(keys->ltk.ediv));
2475 		memcpy(keys->ltk.rand, req->rand, sizeof(req->rand));
2476 	}
2477 
2478 	smp->remote_dist &= ~BT_SMP_DIST_ENC_KEY;
2479 
2480 	if (smp->remote_dist & BT_SMP_DIST_ID_KEY) {
2481 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO);
2482 	} else if (smp->remote_dist & BT_SMP_DIST_SIGN) {
2483 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO);
2484 	}
2485 
2486 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
2487 	    conn->role == BT_HCI_ROLE_CENTRAL && !smp->remote_dist) {
2488 		err = bt_smp_distribute_keys(smp);
2489 		if (err) {
2490 			return err;
2491 		}
2492 	}
2493 
2494 	/* if all keys were distributed, pairing is done */
2495 	if (!smp->local_dist && !smp->remote_dist) {
2496 		smp_pairing_complete(smp, 0);
2497 	}
2498 
2499 	return 0;
2500 }
2501 
2502 #if defined(CONFIG_BT_CENTRAL)
legacy_pairing_rsp(struct bt_smp * smp)2503 static uint8_t legacy_pairing_rsp(struct bt_smp *smp)
2504 {
2505 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
2506 	uint8_t ret;
2507 
2508 	LOG_DBG("");
2509 
2510 	ret = legacy_request_tk(smp);
2511 	if (ret) {
2512 		return ret;
2513 	}
2514 
2515 	/* ask for consent if this is due to received SecReq */
2516 	if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) &&
2517 	    atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) &&
2518 	    smp_auth_cb && smp_auth_cb->pairing_confirm) {
2519 		atomic_set_bit(smp->flags, SMP_FLAG_USER);
2520 		smp_auth_cb->pairing_confirm(smp->chan.chan.conn);
2521 		return 0;
2522 	}
2523 
2524 	if (!atomic_test_bit(smp->flags, SMP_FLAG_USER)) {
2525 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM);
2526 		atomic_set_bit(smp->allowed_cmds, BT_SMP_KEYPRESS_NOTIFICATION);
2527 		return legacy_send_pairing_confirm(smp);
2528 	}
2529 
2530 	atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED);
2531 
2532 	return 0;
2533 }
2534 #endif /* CONFIG_BT_CENTRAL */
2535 #else
smp_encrypt_info(struct bt_smp * smp,struct net_buf * buf)2536 static uint8_t smp_encrypt_info(struct bt_smp *smp, struct net_buf *buf)
2537 {
2538 	return BT_SMP_ERR_CMD_NOTSUPP;
2539 }
2540 
smp_central_ident(struct bt_smp * smp,struct net_buf * buf)2541 static uint8_t smp_central_ident(struct bt_smp *smp, struct net_buf *buf)
2542 {
2543 	return BT_SMP_ERR_CMD_NOTSUPP;
2544 }
2545 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
2546 
smp_init(struct bt_smp * smp)2547 static int smp_init(struct bt_smp *smp)
2548 {
2549 	/* Initialize SMP context exluding L2CAP channel context and anything
2550 	 * else declared after.
2551 	 */
2552 	(void)memset(smp, 0, offsetof(struct bt_smp, chan));
2553 
2554 	/* Generate local random number */
2555 	if (bt_rand(smp->prnd, 16)) {
2556 		return BT_SMP_ERR_UNSPECIFIED;
2557 	}
2558 
2559 	LOG_DBG("prnd %s", bt_hex(smp->prnd, 16));
2560 
2561 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_FAIL);
2562 
2563 #if !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)
2564 	sc_public_key = bt_pub_key_get();
2565 #endif
2566 
2567 	return 0;
2568 }
2569 
bt_set_bondable(bool enable)2570 void bt_set_bondable(bool enable)
2571 {
2572 	bondable = enable;
2573 }
2574 
bt_le_oob_set_sc_flag(bool enable)2575 void bt_le_oob_set_sc_flag(bool enable)
2576 {
2577 	sc_oobd_present = enable;
2578 }
2579 
bt_le_oob_set_legacy_flag(bool enable)2580 void bt_le_oob_set_legacy_flag(bool enable)
2581 {
2582 	legacy_oobd_present = enable;
2583 }
2584 
get_auth(struct bt_smp * smp,uint8_t auth)2585 static uint8_t get_auth(struct bt_smp *smp, uint8_t auth)
2586 {
2587 	struct bt_conn *conn = smp->chan.chan.conn;
2588 
2589 	if (sc_supported) {
2590 		auth &= BT_SMP_AUTH_MASK_SC;
2591 	} else {
2592 		auth &= BT_SMP_AUTH_MASK;
2593 	}
2594 
2595 	if ((get_io_capa(smp) == BT_SMP_IO_NO_INPUT_OUTPUT) ||
2596 	    (!IS_ENABLED(CONFIG_BT_SMP_ENFORCE_MITM) &&
2597 	    (conn->required_sec_level < BT_SECURITY_L3))) {
2598 		auth &= ~(BT_SMP_AUTH_MITM);
2599 	} else {
2600 		auth |= BT_SMP_AUTH_MITM;
2601 	}
2602 
2603 	if (latch_bondable(smp)) {
2604 		auth |= BT_SMP_AUTH_BONDING;
2605 	} else {
2606 		auth &= ~BT_SMP_AUTH_BONDING;
2607 	}
2608 
2609 	if (IS_ENABLED(CONFIG_BT_PASSKEY_KEYPRESS)) {
2610 		auth |= BT_SMP_AUTH_KEYPRESS;
2611 	} else {
2612 		auth &= ~BT_SMP_AUTH_KEYPRESS;
2613 	}
2614 
2615 	return auth;
2616 }
2617 
remote_sec_level_reachable(struct bt_smp * smp)2618 static uint8_t remote_sec_level_reachable(struct bt_smp *smp)
2619 {
2620 	bt_security_t sec = smp->chan.chan.conn->required_sec_level;
2621 
2622 	if (IS_ENABLED(CONFIG_BT_SMP_SC_ONLY)) {
2623 		sec = BT_SECURITY_L4;
2624 	}
2625 	if (IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)) {
2626 		sec = BT_SECURITY_L3;
2627 	}
2628 
2629 	switch (sec) {
2630 	case BT_SECURITY_L1:
2631 	case BT_SECURITY_L2:
2632 		return 0;
2633 
2634 	case BT_SECURITY_L4:
2635 		if (get_encryption_key_size(smp) != BT_SMP_MAX_ENC_KEY_SIZE) {
2636 			return BT_SMP_ERR_ENC_KEY_SIZE;
2637 		}
2638 
2639 		if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
2640 			return BT_SMP_ERR_AUTH_REQUIREMENTS;
2641 		}
2642 		__fallthrough;
2643 	case BT_SECURITY_L3:
2644 		if (smp->method == JUST_WORKS) {
2645 			return BT_SMP_ERR_AUTH_REQUIREMENTS;
2646 		}
2647 
2648 		return 0;
2649 	default:
2650 		return BT_SMP_ERR_UNSPECIFIED;
2651 	}
2652 }
2653 
sec_level_reachable(struct bt_smp * smp)2654 static bool sec_level_reachable(struct bt_smp *smp)
2655 {
2656 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
2657 
2658 	switch (smp->chan.chan.conn->required_sec_level) {
2659 	case BT_SECURITY_L1:
2660 	case BT_SECURITY_L2:
2661 		return true;
2662 	case BT_SECURITY_L3:
2663 		return get_io_capa(smp) != BT_SMP_IO_NO_INPUT_OUTPUT ||
2664 		       (smp_auth_cb && smp_auth_cb->oob_data_request);
2665 	case BT_SECURITY_L4:
2666 		return (get_io_capa(smp) != BT_SMP_IO_NO_INPUT_OUTPUT ||
2667 		       (smp_auth_cb && smp_auth_cb->oob_data_request)) && sc_supported;
2668 	default:
2669 		return false;
2670 	}
2671 }
2672 
smp_chan_get(struct bt_conn * conn)2673 static struct bt_smp *smp_chan_get(struct bt_conn *conn)
2674 {
2675 	struct bt_l2cap_chan *chan;
2676 
2677 	chan = bt_l2cap_le_lookup_rx_cid(conn, BT_L2CAP_CID_SMP);
2678 	if (!chan) {
2679 		LOG_ERR("Unable to find SMP channel");
2680 		return NULL;
2681 	}
2682 
2683 	return CONTAINER_OF(chan, struct bt_smp, chan.chan);
2684 }
2685 
bt_smp_request_ltk(struct bt_conn * conn,uint64_t rand,uint16_t ediv,uint8_t * ltk)2686 bool bt_smp_request_ltk(struct bt_conn *conn, uint64_t rand, uint16_t ediv, uint8_t *ltk)
2687 {
2688 	struct bt_smp *smp;
2689 	uint8_t enc_size;
2690 
2691 	smp = smp_chan_get(conn);
2692 	if (!smp) {
2693 		return false;
2694 	}
2695 
2696 	/*
2697 	 * Both legacy STK and LE SC LTK have rand and ediv equal to zero.
2698 	 * If pairing is in progress use the TK for encryption.
2699 	 */
2700 	if (ediv == 0U && rand == 0U &&
2701 	    atomic_test_bit(smp->flags, SMP_FLAG_PAIRING) &&
2702 	    atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) {
2703 		enc_size = get_encryption_key_size(smp);
2704 
2705 		/*
2706 		 * We keep both legacy STK and LE SC LTK in TK.
2707 		 * Also use only enc_size bytes of key for encryption.
2708 		 */
2709 		memcpy(ltk, smp->tk, enc_size);
2710 		if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) {
2711 			(void)memset(ltk + enc_size, 0,
2712 				     BT_SMP_MAX_ENC_KEY_SIZE - enc_size);
2713 		}
2714 
2715 		atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
2716 		return true;
2717 	}
2718 
2719 	if (!conn->le.keys) {
2720 		conn->le.keys = bt_keys_find(BT_KEYS_LTK_P256, conn->id,
2721 					     &conn->le.dst);
2722 		if (!conn->le.keys) {
2723 			conn->le.keys = bt_keys_find(BT_KEYS_PERIPH_LTK,
2724 						     conn->id, &conn->le.dst);
2725 		}
2726 	}
2727 
2728 	if (ediv == 0U && rand == 0U &&
2729 	    conn->le.keys && (conn->le.keys->keys & BT_KEYS_LTK_P256)) {
2730 		enc_size = conn->le.keys->enc_size;
2731 
2732 		memcpy(ltk, conn->le.keys->ltk.val, enc_size);
2733 		if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) {
2734 			(void)memset(ltk + enc_size, 0,
2735 				     BT_SMP_MAX_ENC_KEY_SIZE - enc_size);
2736 		}
2737 
2738 		atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
2739 		return true;
2740 	}
2741 
2742 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
2743 	if (conn->le.keys && (conn->le.keys->keys & BT_KEYS_PERIPH_LTK) &&
2744 	    !memcmp(conn->le.keys->periph_ltk.rand, &rand, 8) &&
2745 	    !memcmp(conn->le.keys->periph_ltk.ediv, &ediv, 2)) {
2746 		enc_size = conn->le.keys->enc_size;
2747 
2748 		memcpy(ltk, conn->le.keys->periph_ltk.val, enc_size);
2749 		if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) {
2750 			(void)memset(ltk + enc_size, 0,
2751 				     BT_SMP_MAX_ENC_KEY_SIZE - enc_size);
2752 		}
2753 
2754 		atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
2755 		return true;
2756 	}
2757 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
2758 
2759 	if (atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ)) {
2760 		/* Notify higher level that security failed if security was
2761 		 * initiated by peripheral.
2762 		 */
2763 		bt_conn_security_changed(conn, BT_HCI_ERR_PIN_OR_KEY_MISSING,
2764 					 BT_SECURITY_ERR_PIN_OR_KEY_MISSING);
2765 	}
2766 
2767 	smp_reset(smp);
2768 	return false;
2769 }
2770 
2771 #if defined(CONFIG_BT_PERIPHERAL)
smp_send_security_req(struct bt_conn * conn)2772 static int smp_send_security_req(struct bt_conn *conn)
2773 {
2774 	struct bt_smp *smp;
2775 	struct bt_smp_security_request *req;
2776 	struct net_buf *req_buf;
2777 	int err;
2778 
2779 	LOG_DBG("");
2780 	smp = smp_chan_get(conn);
2781 	if (!smp) {
2782 		return -ENOTCONN;
2783 	}
2784 
2785 	/* SMP Timeout */
2786 	if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) {
2787 		return -EIO;
2788 	}
2789 
2790 	/* pairing is in progress */
2791 	if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
2792 		return -EBUSY;
2793 	}
2794 
2795 	if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) {
2796 		return -EBUSY;
2797 	}
2798 
2799 	/* early verify if required sec level if reachable */
2800 	if (!(sec_level_reachable(smp) || smp_keys_check(conn))) {
2801 		return -EINVAL;
2802 	}
2803 
2804 	if (!conn->le.keys) {
2805 		conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst);
2806 		if (!conn->le.keys) {
2807 			return -ENOMEM;
2808 		}
2809 	}
2810 
2811 	if (smp_init(smp) != 0) {
2812 		return -ENOBUFS;
2813 	}
2814 
2815 	req_buf = smp_create_pdu(smp, BT_SMP_CMD_SECURITY_REQUEST,
2816 				 sizeof(*req));
2817 	if (!req_buf) {
2818 		return -ENOBUFS;
2819 	}
2820 
2821 	req = net_buf_add(req_buf, sizeof(*req));
2822 	req->auth_req = get_auth(smp, BT_SMP_AUTH_DEFAULT);
2823 
2824 	/* SMP timer is not restarted for SecRequest so don't use smp_send */
2825 	err = bt_l2cap_send(conn, BT_L2CAP_CID_SMP, req_buf);
2826 	if (err) {
2827 		net_buf_unref(req_buf);
2828 		return err;
2829 	}
2830 
2831 	atomic_set_bit(smp->flags, SMP_FLAG_SEC_REQ);
2832 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_REQ);
2833 
2834 	return 0;
2835 }
2836 
smp_pairing_req(struct bt_smp * smp,struct net_buf * buf)2837 static uint8_t smp_pairing_req(struct bt_smp *smp, struct net_buf *buf)
2838 {
2839 	struct bt_conn *conn = smp->chan.chan.conn;
2840 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
2841 
2842 	struct bt_smp_pairing *req = (void *)buf->data;
2843 	struct bt_smp_pairing *rsp;
2844 	uint8_t err;
2845 
2846 	LOG_DBG("req: io_capability 0x%02X, oob_flag 0x%02X, auth_req 0x%02X, "
2847 		"max_key_size 0x%02X, init_key_dist 0x%02X, resp_key_dist 0x%02X",
2848 		req->io_capability, req->oob_flag, req->auth_req,
2849 		req->max_key_size, req->init_key_dist, req->resp_key_dist);
2850 
2851 	if ((req->max_key_size > BT_SMP_MAX_ENC_KEY_SIZE) ||
2852 	    (req->max_key_size < BT_SMP_MIN_ENC_KEY_SIZE)) {
2853 		return BT_SMP_ERR_ENC_KEY_SIZE;
2854 	}
2855 
2856 	if (!conn->le.keys) {
2857 		conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst);
2858 		if (!conn->le.keys) {
2859 			LOG_DBG("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst));
2860 			return BT_SMP_ERR_UNSPECIFIED;
2861 		}
2862 	}
2863 
2864 	/* If we already sent a security request then the SMP context
2865 	 * is already initialized.
2866 	 */
2867 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ)) {
2868 		int ret = smp_init(smp);
2869 
2870 		if (ret) {
2871 			return ret;
2872 		}
2873 	}
2874 
2875 	/* Store req for later use */
2876 	smp->preq[0] = BT_SMP_CMD_PAIRING_REQ;
2877 	memcpy(smp->preq + 1, req, sizeof(*req));
2878 
2879 	/* create rsp, it will be used later on */
2880 	smp->prsp[0] = BT_SMP_CMD_PAIRING_RSP;
2881 	rsp = (struct bt_smp_pairing *)&smp->prsp[1];
2882 
2883 	rsp->auth_req = get_auth(smp, req->auth_req);
2884 	rsp->io_capability = get_io_capa(smp);
2885 	rsp->max_key_size = BT_SMP_MAX_ENC_KEY_SIZE;
2886 	rsp->init_key_dist = (req->init_key_dist & RECV_KEYS);
2887 	rsp->resp_key_dist = (req->resp_key_dist & SEND_KEYS);
2888 
2889 	if ((rsp->auth_req & BT_SMP_AUTH_SC) &&
2890 	    (req->auth_req & BT_SMP_AUTH_SC)) {
2891 		atomic_set_bit(smp->flags, SMP_FLAG_SC);
2892 
2893 		rsp->init_key_dist &= RECV_KEYS_SC;
2894 		rsp->resp_key_dist &= SEND_KEYS_SC;
2895 	}
2896 
2897 	if (atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
2898 		rsp->oob_flag = sc_oobd_present ? BT_SMP_OOB_PRESENT :
2899 				BT_SMP_OOB_NOT_PRESENT;
2900 	} else {
2901 		rsp->oob_flag = legacy_oobd_present ? BT_SMP_OOB_PRESENT :
2902 				BT_SMP_OOB_NOT_PRESENT;
2903 	}
2904 
2905 	if ((rsp->auth_req & BT_SMP_AUTH_CT2) &&
2906 	    (req->auth_req & BT_SMP_AUTH_CT2)) {
2907 		atomic_set_bit(smp->flags, SMP_FLAG_CT2);
2908 	}
2909 
2910 	if ((rsp->auth_req & BT_SMP_AUTH_BONDING) &&
2911 	    (req->auth_req & BT_SMP_AUTH_BONDING)) {
2912 		atomic_set_bit(smp->flags, SMP_FLAG_BOND);
2913 	} else if (IS_ENABLED(CONFIG_BT_BONDING_REQUIRED)) {
2914 		/* Reject pairing req if not both intend to bond */
2915 		LOG_DBG("Bonding required");
2916 		return BT_SMP_ERR_UNSPECIFIED;
2917 	} else {
2918 		rsp->init_key_dist = 0;
2919 		rsp->resp_key_dist = 0;
2920 	}
2921 
2922 	smp->local_dist = rsp->resp_key_dist;
2923 	smp->remote_dist = rsp->init_key_dist;
2924 
2925 	atomic_set_bit(smp->flags, SMP_FLAG_PAIRING);
2926 
2927 	smp->method = get_pair_method(smp, req->io_capability);
2928 
2929 	if (!update_keys_check(smp, conn->le.keys)) {
2930 		return BT_SMP_ERR_AUTH_REQUIREMENTS;
2931 	}
2932 
2933 	err = remote_sec_level_reachable(smp);
2934 	if (err) {
2935 		return err;
2936 	}
2937 
2938 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
2939 #if defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
2940 		return BT_SMP_ERR_AUTH_REQUIREMENTS;
2941 #else
2942 		if (IS_ENABLED(CONFIG_BT_SMP_APP_PAIRING_ACCEPT)) {
2943 			err = smp_pairing_accept_query(smp, req);
2944 			if (err) {
2945 				return err;
2946 			}
2947 		}
2948 
2949 		return legacy_pairing_req(smp);
2950 #endif /* CONFIG_BT_SMP_SC_PAIR_ONLY */
2951 	}
2952 
2953 	if (IS_ENABLED(CONFIG_BT_SMP_APP_PAIRING_ACCEPT)) {
2954 		err = smp_pairing_accept_query(smp, req);
2955 		if (err) {
2956 			return err;
2957 		}
2958 	}
2959 
2960 	if (!IS_ENABLED(CONFIG_BT_SMP_SC_PAIR_ONLY) &&
2961 	    (DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) &&
2962 	    !atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) &&
2963 	    smp_auth_cb && smp_auth_cb->pairing_confirm) {
2964 		atomic_set_bit(smp->flags, SMP_FLAG_USER);
2965 		smp_auth_cb->pairing_confirm(conn);
2966 		return 0;
2967 	}
2968 
2969 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY);
2970 
2971 	LOG_DBG("rsp: io_capability 0x%02X, oob_flag 0x%02X, auth_req 0x%02X, "
2972 		"max_key_size 0x%02X, init_key_dist 0x%02X, resp_key_dist 0x%02X",
2973 		rsp->io_capability, rsp->oob_flag, rsp->auth_req,
2974 		rsp->max_key_size, rsp->init_key_dist, rsp->resp_key_dist);
2975 
2976 	return send_pairing_rsp(smp);
2977 }
2978 #else
smp_pairing_req(struct bt_smp * smp,struct net_buf * buf)2979 static uint8_t smp_pairing_req(struct bt_smp *smp, struct net_buf *buf)
2980 {
2981 	return BT_SMP_ERR_CMD_NOTSUPP;
2982 }
2983 #endif /* CONFIG_BT_PERIPHERAL */
2984 
sc_send_public_key(struct bt_smp * smp)2985 static uint8_t sc_send_public_key(struct bt_smp *smp)
2986 {
2987 	struct bt_smp_public_key *req;
2988 	struct net_buf *req_buf;
2989 
2990 	req_buf = smp_create_pdu(smp, BT_SMP_CMD_PUBLIC_KEY, sizeof(*req));
2991 	if (!req_buf) {
2992 		return BT_SMP_ERR_UNSPECIFIED;
2993 	}
2994 
2995 	req = net_buf_add(req_buf, sizeof(*req));
2996 
2997 	memcpy(req->x, sc_public_key, sizeof(req->x));
2998 	memcpy(req->y, &sc_public_key[32], sizeof(req->y));
2999 
3000 	smp_send(smp, req_buf, NULL, NULL);
3001 
3002 	if (IS_ENABLED(CONFIG_BT_USE_DEBUG_KEYS)) {
3003 		atomic_set_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY);
3004 	}
3005 
3006 	return 0;
3007 }
3008 
3009 #if defined(CONFIG_BT_CENTRAL)
smp_send_pairing_req(struct bt_conn * conn)3010 static int smp_send_pairing_req(struct bt_conn *conn)
3011 {
3012 	struct bt_smp *smp;
3013 	struct bt_smp_pairing *req;
3014 	struct net_buf *req_buf;
3015 
3016 	LOG_DBG("");
3017 
3018 	smp = smp_chan_get(conn);
3019 	if (!smp) {
3020 		return -ENOTCONN;
3021 	}
3022 
3023 	/* SMP Timeout */
3024 	if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) {
3025 		return -EIO;
3026 	}
3027 
3028 	/* A higher security level is requested during the key distribution
3029 	 * phase, once pairing is complete a new pairing procedure will start.
3030 	 */
3031 	if (atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR)) {
3032 		return 0;
3033 	}
3034 
3035 	/* pairing is in progress */
3036 	if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
3037 		return -EBUSY;
3038 	}
3039 
3040 	/* Encryption is in progress */
3041 	if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) {
3042 		return -EBUSY;
3043 	}
3044 
3045 	/* early verify if required sec level if reachable */
3046 	if (!sec_level_reachable(smp)) {
3047 		return -EINVAL;
3048 	}
3049 
3050 	if (!conn->le.keys) {
3051 		conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst);
3052 		if (!conn->le.keys) {
3053 			return -ENOMEM;
3054 		}
3055 	}
3056 
3057 	if (smp_init(smp)) {
3058 		return -ENOBUFS;
3059 	}
3060 
3061 	req_buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_REQ, sizeof(*req));
3062 	if (!req_buf) {
3063 		return -ENOBUFS;
3064 	}
3065 
3066 	req = net_buf_add(req_buf, sizeof(*req));
3067 
3068 	req->auth_req = get_auth(smp, BT_SMP_AUTH_DEFAULT);
3069 	req->io_capability = get_io_capa(smp);
3070 
3071 	/* At this point is it unknown if pairing will be legacy or LE SC so
3072 	 * set OOB flag if any OOB data is present and assume to peer device
3073 	 * provides OOB data that will match it's pairing type.
3074 	 */
3075 	req->oob_flag = (legacy_oobd_present || sc_oobd_present) ?
3076 				BT_SMP_OOB_PRESENT : BT_SMP_OOB_NOT_PRESENT;
3077 
3078 	req->max_key_size = BT_SMP_MAX_ENC_KEY_SIZE;
3079 
3080 	if (req->auth_req & BT_SMP_AUTH_BONDING) {
3081 		req->init_key_dist = SEND_KEYS;
3082 		req->resp_key_dist = RECV_KEYS;
3083 	} else {
3084 		req->init_key_dist = 0;
3085 		req->resp_key_dist = 0;
3086 	}
3087 
3088 	smp->local_dist = req->init_key_dist;
3089 	smp->remote_dist = req->resp_key_dist;
3090 
3091 	/* Store req for later use */
3092 	smp->preq[0] = BT_SMP_CMD_PAIRING_REQ;
3093 	memcpy(smp->preq + 1, req, sizeof(*req));
3094 
3095 	LOG_DBG("req: io_capability 0x%02X, oob_flag 0x%02X, auth_req 0x%02X, "
3096 		"max_key_size 0x%02X, init_key_dist 0x%02X, resp_key_dist 0x%02X",
3097 		req->io_capability, req->oob_flag, req->auth_req,
3098 		req->max_key_size, req->init_key_dist, req->resp_key_dist);
3099 
3100 	smp_send(smp, req_buf, NULL, NULL);
3101 
3102 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RSP);
3103 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST);
3104 	atomic_set_bit(smp->flags, SMP_FLAG_PAIRING);
3105 
3106 	return 0;
3107 }
3108 
smp_pairing_rsp(struct bt_smp * smp,struct net_buf * buf)3109 static uint8_t smp_pairing_rsp(struct bt_smp *smp, struct net_buf *buf)
3110 {
3111 	struct bt_conn *conn = smp->chan.chan.conn;
3112 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
3113 	struct bt_smp_pairing *rsp = (void *)buf->data;
3114 	struct bt_smp_pairing *req = (struct bt_smp_pairing *)&smp->preq[1];
3115 	uint8_t err;
3116 
3117 	LOG_DBG("rsp: io_capability 0x%02X, oob_flag 0x%02X, auth_req 0x%02X, "
3118 		"max_key_size 0x%02X, init_key_dist 0x%02X, resp_key_dist 0x%02X",
3119 		rsp->io_capability, rsp->oob_flag, rsp->auth_req,
3120 		rsp->max_key_size, rsp->init_key_dist, rsp->resp_key_dist);
3121 
3122 	if ((rsp->max_key_size > BT_SMP_MAX_ENC_KEY_SIZE) ||
3123 	    (rsp->max_key_size < BT_SMP_MIN_ENC_KEY_SIZE)) {
3124 		return BT_SMP_ERR_ENC_KEY_SIZE;
3125 	}
3126 
3127 	smp->local_dist &= rsp->init_key_dist;
3128 	smp->remote_dist &= rsp->resp_key_dist;
3129 
3130 	/* Store rsp for later use */
3131 	smp->prsp[0] = BT_SMP_CMD_PAIRING_RSP;
3132 	memcpy(smp->prsp + 1, rsp, sizeof(*rsp));
3133 
3134 	if ((rsp->auth_req & BT_SMP_AUTH_SC) &&
3135 	    (req->auth_req & BT_SMP_AUTH_SC)) {
3136 		atomic_set_bit(smp->flags, SMP_FLAG_SC);
3137 	}
3138 
3139 	if ((rsp->auth_req & BT_SMP_AUTH_CT2) &&
3140 	    (req->auth_req & BT_SMP_AUTH_CT2)) {
3141 		atomic_set_bit(smp->flags, SMP_FLAG_CT2);
3142 	}
3143 
3144 	if ((rsp->auth_req & BT_SMP_AUTH_BONDING) &&
3145 	    (req->auth_req & BT_SMP_AUTH_BONDING)) {
3146 		atomic_set_bit(smp->flags, SMP_FLAG_BOND);
3147 	} else if (IS_ENABLED(CONFIG_BT_BONDING_REQUIRED)) {
3148 		/* Reject pairing req if not both intend to bond */
3149 		LOG_DBG("Bonding required");
3150 		return BT_SMP_ERR_UNSPECIFIED;
3151 	} else {
3152 		smp->local_dist = 0;
3153 		smp->remote_dist = 0;
3154 	}
3155 
3156 	smp->method = get_pair_method(smp, rsp->io_capability);
3157 
3158 	if (!update_keys_check(smp, conn->le.keys)) {
3159 		return BT_SMP_ERR_AUTH_REQUIREMENTS;
3160 	}
3161 
3162 	err = remote_sec_level_reachable(smp);
3163 	if (err) {
3164 		return err;
3165 	}
3166 
3167 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
3168 #if defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
3169 		return BT_SMP_ERR_AUTH_REQUIREMENTS;
3170 #else
3171 		if (IS_ENABLED(CONFIG_BT_SMP_APP_PAIRING_ACCEPT)) {
3172 			err = smp_pairing_accept_query(smp, rsp);
3173 			if (err) {
3174 				return err;
3175 			}
3176 		}
3177 
3178 		return legacy_pairing_rsp(smp);
3179 #endif /* CONFIG_BT_SMP_SC_PAIR_ONLY */
3180 	}
3181 
3182 	smp->local_dist &= SEND_KEYS_SC;
3183 	smp->remote_dist &= RECV_KEYS_SC;
3184 
3185 	if (IS_ENABLED(CONFIG_BT_SMP_APP_PAIRING_ACCEPT)) {
3186 		err = smp_pairing_accept_query(smp, rsp);
3187 		if (err) {
3188 			return err;
3189 		}
3190 	}
3191 
3192 	if (!IS_ENABLED(CONFIG_BT_SMP_SC_PAIR_ONLY) &&
3193 	    (DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) &&
3194 	    atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) &&
3195 	    smp_auth_cb && smp_auth_cb->pairing_confirm) {
3196 		atomic_set_bit(smp->flags, SMP_FLAG_USER);
3197 		smp_auth_cb->pairing_confirm(conn);
3198 		return 0;
3199 	}
3200 
3201 	if (!sc_public_key) {
3202 		atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND);
3203 		return 0;
3204 	}
3205 
3206 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY);
3207 	atomic_clear_bit(smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST);
3208 
3209 	return sc_send_public_key(smp);
3210 }
3211 #else
smp_pairing_rsp(struct bt_smp * smp,struct net_buf * buf)3212 static uint8_t smp_pairing_rsp(struct bt_smp *smp, struct net_buf *buf)
3213 {
3214 	return BT_SMP_ERR_CMD_NOTSUPP;
3215 }
3216 #endif /* CONFIG_BT_CENTRAL */
3217 
smp_pairing_confirm(struct bt_smp * smp,struct net_buf * buf)3218 static uint8_t smp_pairing_confirm(struct bt_smp *smp, struct net_buf *buf)
3219 {
3220 	struct bt_smp_pairing_confirm *req = (void *)buf->data;
3221 
3222 	LOG_DBG("");
3223 
3224 	atomic_clear_bit(smp->flags, SMP_FLAG_DISPLAY);
3225 
3226 	memcpy(smp->pcnf, req->val, sizeof(smp->pcnf));
3227 
3228 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
3229 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
3230 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
3231 		return smp_send_pairing_random(smp);
3232 	}
3233 
3234 	if (!IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
3235 		return 0;
3236 	}
3237 
3238 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
3239 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
3240 		return legacy_pairing_confirm(smp);
3241 	}
3242 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
3243 
3244 	switch (smp->method) {
3245 	case PASSKEY_DISPLAY:
3246 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
3247 		return smp_send_pairing_confirm(smp);
3248 	case PASSKEY_INPUT:
3249 		if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) {
3250 			atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED);
3251 			return 0;
3252 		}
3253 
3254 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
3255 		return smp_send_pairing_confirm(smp);
3256 	case JUST_WORKS:
3257 	case PASSKEY_CONFIRM:
3258 	default:
3259 		LOG_ERR("Unknown pairing method (%u)", smp->method);
3260 		return BT_SMP_ERR_UNSPECIFIED;
3261 	}
3262 }
3263 
sc_smp_send_dhkey_check(struct bt_smp * smp,const uint8_t * e)3264 static uint8_t sc_smp_send_dhkey_check(struct bt_smp *smp, const uint8_t *e)
3265 {
3266 	struct bt_smp_dhkey_check *req;
3267 	struct net_buf *buf;
3268 
3269 	LOG_DBG("");
3270 
3271 	buf = smp_create_pdu(smp, BT_SMP_DHKEY_CHECK, sizeof(*req));
3272 	if (!buf) {
3273 		return BT_SMP_ERR_UNSPECIFIED;
3274 	}
3275 
3276 	req = net_buf_add(buf, sizeof(*req));
3277 	memcpy(req->e, e, sizeof(req->e));
3278 
3279 	smp_send(smp, buf, NULL, NULL);
3280 
3281 	return 0;
3282 }
3283 
3284 #if defined(CONFIG_BT_CENTRAL)
compute_and_send_central_dhcheck(struct bt_smp * smp)3285 static uint8_t compute_and_send_central_dhcheck(struct bt_smp *smp)
3286 {
3287 	uint8_t e[16], r[16];
3288 
3289 	(void)memset(r, 0, sizeof(r));
3290 
3291 	switch (smp->method) {
3292 	case JUST_WORKS:
3293 	case PASSKEY_CONFIRM:
3294 		break;
3295 	case PASSKEY_DISPLAY:
3296 	case PASSKEY_INPUT:
3297 		memcpy(r, &smp->passkey, sizeof(smp->passkey));
3298 		break;
3299 	case LE_SC_OOB:
3300 		if (smp->oobd_remote) {
3301 			memcpy(r, smp->oobd_remote->r, sizeof(r));
3302 		}
3303 		break;
3304 	default:
3305 		LOG_ERR("Unknown pairing method (%u)", smp->method);
3306 		return BT_SMP_ERR_UNSPECIFIED;
3307 	}
3308 
3309 	/* calculate LTK and mackey */
3310 	if (bt_crypto_f5(smp->dhkey, smp->prnd, smp->rrnd, &smp->chan.chan.conn->le.init_addr,
3311 			 &smp->chan.chan.conn->le.resp_addr, smp->mackey, smp->tk)) {
3312 		LOG_ERR("Calculate LTK failed");
3313 		return BT_SMP_ERR_UNSPECIFIED;
3314 	}
3315 	/* calculate local DHKey check */
3316 	if (bt_crypto_f6(smp->mackey, smp->prnd, smp->rrnd, r, &smp->preq[1],
3317 			 &smp->chan.chan.conn->le.init_addr, &smp->chan.chan.conn->le.resp_addr,
3318 			 e)) {
3319 		LOG_ERR("Calculate local DHKey check failed");
3320 		return BT_SMP_ERR_UNSPECIFIED;
3321 	}
3322 
3323 	atomic_set_bit(smp->allowed_cmds, BT_SMP_DHKEY_CHECK);
3324 	return sc_smp_send_dhkey_check(smp, e);
3325 }
3326 #endif /* CONFIG_BT_CENTRAL */
3327 
3328 #if defined(CONFIG_BT_PERIPHERAL)
compute_and_check_and_send_periph_dhcheck(struct bt_smp * smp)3329 static uint8_t compute_and_check_and_send_periph_dhcheck(struct bt_smp *smp)
3330 {
3331 	uint8_t re[16], e[16], r[16];
3332 	uint8_t err;
3333 
3334 	(void)memset(r, 0, sizeof(r));
3335 
3336 	switch (smp->method) {
3337 	case JUST_WORKS:
3338 	case PASSKEY_CONFIRM:
3339 		break;
3340 	case PASSKEY_DISPLAY:
3341 	case PASSKEY_INPUT:
3342 		memcpy(r, &smp->passkey, sizeof(smp->passkey));
3343 		break;
3344 	case LE_SC_OOB:
3345 		if (smp->oobd_remote) {
3346 			memcpy(r, smp->oobd_remote->r, sizeof(r));
3347 		}
3348 		break;
3349 	default:
3350 		LOG_ERR("Unknown pairing method (%u)", smp->method);
3351 		return BT_SMP_ERR_UNSPECIFIED;
3352 	}
3353 
3354 	/* calculate LTK and mackey */
3355 	if (bt_crypto_f5(smp->dhkey, smp->rrnd, smp->prnd, &smp->chan.chan.conn->le.init_addr,
3356 			 &smp->chan.chan.conn->le.resp_addr, smp->mackey, smp->tk)) {
3357 		LOG_ERR("Calculate LTK failed");
3358 		return BT_SMP_ERR_UNSPECIFIED;
3359 	}
3360 
3361 	/* calculate local DHKey check */
3362 	if (bt_crypto_f6(smp->mackey, smp->prnd, smp->rrnd, r, &smp->prsp[1],
3363 			 &smp->chan.chan.conn->le.resp_addr, &smp->chan.chan.conn->le.init_addr,
3364 			 e)) {
3365 		LOG_ERR("Calculate local DHKey check failed");
3366 		return BT_SMP_ERR_UNSPECIFIED;
3367 	}
3368 
3369 	if (smp->method == LE_SC_OOB) {
3370 		if (smp->oobd_local) {
3371 			memcpy(r, smp->oobd_local->r, sizeof(r));
3372 		} else {
3373 			memset(r, 0, sizeof(r));
3374 		}
3375 	}
3376 
3377 	/* calculate remote DHKey check */
3378 	if (bt_crypto_f6(smp->mackey, smp->rrnd, smp->prnd, r, &smp->preq[1],
3379 			 &smp->chan.chan.conn->le.init_addr, &smp->chan.chan.conn->le.resp_addr,
3380 			 re)) {
3381 		LOG_ERR("Calculate remote DHKey check failed");
3382 		return BT_SMP_ERR_UNSPECIFIED;
3383 	}
3384 
3385 	/* compare received E with calculated remote */
3386 	if (memcmp(smp->e, re, 16)) {
3387 		return BT_SMP_ERR_DHKEY_CHECK_FAILED;
3388 	}
3389 
3390 	/* send local e */
3391 	err = sc_smp_send_dhkey_check(smp, e);
3392 	if (err) {
3393 		return err;
3394 	}
3395 
3396 	atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
3397 	return 0;
3398 }
3399 #endif /* CONFIG_BT_PERIPHERAL */
3400 
3401 static void bt_smp_dhkey_ready(const uint8_t *dhkey);
smp_dhkey_generate(struct bt_smp * smp)3402 static uint8_t smp_dhkey_generate(struct bt_smp *smp)
3403 {
3404 	int err;
3405 
3406 	atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_GEN);
3407 	err = bt_dh_key_gen(smp->pkey, bt_smp_dhkey_ready);
3408 	if (err) {
3409 		atomic_clear_bit(smp->flags, SMP_FLAG_DHKEY_GEN);
3410 
3411 		LOG_ERR("Failed to generate DHKey");
3412 		return BT_SMP_ERR_UNSPECIFIED;
3413 	}
3414 
3415 	return 0;
3416 }
3417 
smp_dhkey_ready(struct bt_smp * smp,const uint8_t * dhkey)3418 static uint8_t smp_dhkey_ready(struct bt_smp *smp, const uint8_t *dhkey)
3419 {
3420 	if (!dhkey) {
3421 		return BT_SMP_ERR_DHKEY_CHECK_FAILED;
3422 	}
3423 
3424 	atomic_clear_bit(smp->flags, SMP_FLAG_DHKEY_PENDING);
3425 	memcpy(smp->dhkey, dhkey, BT_DH_KEY_LEN);
3426 
3427 	/* wait for user passkey confirmation */
3428 	if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) {
3429 		atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
3430 		return 0;
3431 	}
3432 
3433 	/* wait for remote DHKey Check */
3434 	if (atomic_test_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT)) {
3435 		atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
3436 		return 0;
3437 	}
3438 
3439 	if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_SEND)) {
3440 #if defined(CONFIG_BT_CENTRAL)
3441 		if (smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
3442 			return compute_and_send_central_dhcheck(smp);
3443 		}
3444 
3445 #endif /* CONFIG_BT_CENTRAL */
3446 
3447 #if defined(CONFIG_BT_PERIPHERAL)
3448 		return  compute_and_check_and_send_periph_dhcheck(smp);
3449 #endif /* CONFIG_BT_PERIPHERAL */
3450 	}
3451 
3452 	return 0;
3453 }
3454 
smp_find(int flag)3455 static struct bt_smp *smp_find(int flag)
3456 {
3457 	for (int i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) {
3458 		if (atomic_test_bit(bt_smp_pool[i].flags, flag)) {
3459 			return &bt_smp_pool[i];
3460 		}
3461 	}
3462 
3463 	return NULL;
3464 }
3465 
bt_smp_dhkey_ready(const uint8_t * dhkey)3466 static void bt_smp_dhkey_ready(const uint8_t *dhkey)
3467 {
3468 	LOG_DBG("%p", (void *)dhkey);
3469 	int err;
3470 
3471 	struct bt_smp *smp = smp_find(SMP_FLAG_DHKEY_GEN);
3472 	if (smp) {
3473 		atomic_clear_bit(smp->flags, SMP_FLAG_DHKEY_GEN);
3474 		err = smp_dhkey_ready(smp, dhkey);
3475 		if (err) {
3476 			smp_error(smp, err);
3477 		}
3478 	}
3479 
3480 	err = 0;
3481 	do {
3482 		smp = smp_find(SMP_FLAG_DHKEY_PENDING);
3483 		if (smp) {
3484 			err = smp_dhkey_generate(smp);
3485 			if (err) {
3486 				smp_error(smp, err);
3487 			}
3488 		}
3489 	} while (smp && err);
3490 }
3491 
sc_smp_check_confirm(struct bt_smp * smp)3492 static uint8_t sc_smp_check_confirm(struct bt_smp *smp)
3493 {
3494 	uint8_t cfm[16];
3495 	uint8_t r;
3496 
3497 	switch (smp->method) {
3498 	case LE_SC_OOB:
3499 		return 0;
3500 	case PASSKEY_CONFIRM:
3501 	case JUST_WORKS:
3502 		r = 0U;
3503 		break;
3504 	case PASSKEY_DISPLAY:
3505 	case PASSKEY_INPUT:
3506 		/*
3507 		 * In the Passkey Entry protocol, the most significant
3508 		 * bit of Z is set equal to one and the least
3509 		 * significant bit is made up from one bit of the
3510 		 * passkey e.g. if the passkey bit is 1, then Z = 0x81
3511 		 * and if the passkey bit is 0, then Z = 0x80.
3512 		 */
3513 		r = (smp->passkey >> smp->passkey_round) & 0x01;
3514 		r |= 0x80;
3515 		break;
3516 	default:
3517 		LOG_ERR("Unknown pairing method (%u)", smp->method);
3518 		return BT_SMP_ERR_UNSPECIFIED;
3519 	}
3520 
3521 	if (bt_crypto_f4(smp->pkey, sc_public_key, smp->rrnd, r, cfm)) {
3522 		LOG_ERR("Calculate confirm failed");
3523 		return BT_SMP_ERR_UNSPECIFIED;
3524 	}
3525 
3526 	LOG_DBG("pcnf %s", bt_hex(smp->pcnf, 16));
3527 	LOG_DBG("cfm %s", bt_hex(cfm, 16));
3528 
3529 	if (memcmp(smp->pcnf, cfm, 16)) {
3530 		return BT_SMP_ERR_CONFIRM_FAILED;
3531 	}
3532 
3533 	return 0;
3534 }
3535 
le_sc_oob_data_req_check(struct bt_smp * smp)3536 static bool le_sc_oob_data_req_check(struct bt_smp *smp)
3537 {
3538 	struct bt_smp_pairing *req = (struct bt_smp_pairing *)&smp->preq[1];
3539 
3540 	return ((req->oob_flag & BT_SMP_OOB_DATA_MASK) == BT_SMP_OOB_PRESENT);
3541 }
3542 
le_sc_oob_data_rsp_check(struct bt_smp * smp)3543 static bool le_sc_oob_data_rsp_check(struct bt_smp *smp)
3544 {
3545 	struct bt_smp_pairing *rsp = (struct bt_smp_pairing *)&smp->prsp[1];
3546 
3547 	return ((rsp->oob_flag & BT_SMP_OOB_DATA_MASK) == BT_SMP_OOB_PRESENT);
3548 }
3549 
le_sc_oob_config_set(struct bt_smp * smp,struct bt_conn_oob_info * info)3550 static void le_sc_oob_config_set(struct bt_smp *smp,
3551 				 struct bt_conn_oob_info *info)
3552 {
3553 	bool req_oob_present = le_sc_oob_data_req_check(smp);
3554 	bool rsp_oob_present = le_sc_oob_data_rsp_check(smp);
3555 	int oob_config = BT_CONN_OOB_NO_DATA;
3556 
3557 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
3558 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
3559 		oob_config = req_oob_present ? BT_CONN_OOB_REMOTE_ONLY :
3560 					       BT_CONN_OOB_NO_DATA;
3561 
3562 		if (rsp_oob_present) {
3563 			oob_config = (oob_config == BT_CONN_OOB_REMOTE_ONLY) ?
3564 				     BT_CONN_OOB_BOTH_PEERS :
3565 				     BT_CONN_OOB_LOCAL_ONLY;
3566 		}
3567 	} else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
3568 		oob_config = req_oob_present ? BT_CONN_OOB_LOCAL_ONLY :
3569 					       BT_CONN_OOB_NO_DATA;
3570 
3571 		if (rsp_oob_present) {
3572 			oob_config = (oob_config == BT_CONN_OOB_LOCAL_ONLY) ?
3573 				     BT_CONN_OOB_BOTH_PEERS :
3574 				     BT_CONN_OOB_REMOTE_ONLY;
3575 		}
3576 	}
3577 
3578 	info->lesc.oob_config = oob_config;
3579 }
3580 
smp_pairing_random(struct bt_smp * smp,struct net_buf * buf)3581 static uint8_t smp_pairing_random(struct bt_smp *smp, struct net_buf *buf)
3582 {
3583 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
3584 	struct bt_smp_pairing_random *req = (void *)buf->data;
3585 	uint32_t passkey;
3586 	uint8_t err;
3587 
3588 	LOG_DBG("");
3589 
3590 	memcpy(smp->rrnd, req->val, sizeof(smp->rrnd));
3591 
3592 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
3593 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
3594 		return legacy_pairing_random(smp);
3595 	}
3596 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
3597 
3598 #if defined(CONFIG_BT_CENTRAL)
3599 	if (smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
3600 		err = sc_smp_check_confirm(smp);
3601 		if (err) {
3602 			return err;
3603 		}
3604 
3605 		switch (smp->method) {
3606 		case PASSKEY_CONFIRM:
3607 			/* compare passkey before calculating LTK */
3608 			if (bt_crypto_g2(sc_public_key, smp->pkey, smp->prnd, smp->rrnd,
3609 					 &passkey)) {
3610 				return BT_SMP_ERR_UNSPECIFIED;
3611 			}
3612 
3613 			atomic_set_bit(smp->flags, SMP_FLAG_USER);
3614 			atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
3615 			smp_auth_cb->passkey_confirm(smp->chan.chan.conn, passkey);
3616 			return 0;
3617 		case JUST_WORKS:
3618 			break;
3619 		case LE_SC_OOB:
3620 			break;
3621 		case PASSKEY_DISPLAY:
3622 		case PASSKEY_INPUT:
3623 			smp->passkey_round++;
3624 			if (smp->passkey_round == 20U) {
3625 				break;
3626 			}
3627 
3628 			if (bt_rand(smp->prnd, 16)) {
3629 				return BT_SMP_ERR_UNSPECIFIED;
3630 			}
3631 
3632 			atomic_set_bit(smp->allowed_cmds,
3633 				       BT_SMP_CMD_PAIRING_CONFIRM);
3634 			return smp_send_pairing_confirm(smp);
3635 		default:
3636 			LOG_ERR("Unknown pairing method (%u)", smp->method);
3637 			return BT_SMP_ERR_UNSPECIFIED;
3638 		}
3639 
3640 		/* wait for DHKey being generated */
3641 		if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) {
3642 			atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
3643 			return 0;
3644 		}
3645 
3646 		return compute_and_send_central_dhcheck(smp);
3647 	}
3648 #endif /* CONFIG_BT_CENTRAL */
3649 
3650 #if defined(CONFIG_BT_PERIPHERAL)
3651 	switch (smp->method) {
3652 	case PASSKEY_CONFIRM:
3653 		if (bt_crypto_g2(smp->pkey, sc_public_key, smp->rrnd, smp->prnd, &passkey)) {
3654 			return BT_SMP_ERR_UNSPECIFIED;
3655 		}
3656 
3657 		atomic_set_bit(smp->flags, SMP_FLAG_USER);
3658 		smp_auth_cb->passkey_confirm(smp->chan.chan.conn, passkey);
3659 		break;
3660 	case JUST_WORKS:
3661 		break;
3662 	case PASSKEY_DISPLAY:
3663 	case PASSKEY_INPUT:
3664 		err = sc_smp_check_confirm(smp);
3665 		if (err) {
3666 			return err;
3667 		}
3668 
3669 		atomic_set_bit(smp->allowed_cmds,
3670 			       BT_SMP_CMD_PAIRING_CONFIRM);
3671 		err = smp_send_pairing_random(smp);
3672 		if (err) {
3673 			return err;
3674 		}
3675 
3676 		smp->passkey_round++;
3677 		if (smp->passkey_round == 20U) {
3678 			atomic_set_bit(smp->allowed_cmds, BT_SMP_DHKEY_CHECK);
3679 			atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT);
3680 			return 0;
3681 		}
3682 
3683 		if (bt_rand(smp->prnd, 16)) {
3684 			return BT_SMP_ERR_UNSPECIFIED;
3685 		}
3686 
3687 		return 0;
3688 	case LE_SC_OOB:
3689 		/* Step 6: Select random N */
3690 		if (bt_rand(smp->prnd, 16)) {
3691 			return BT_SMP_ERR_UNSPECIFIED;
3692 		}
3693 
3694 		if (smp_auth_cb && smp_auth_cb->oob_data_request) {
3695 			struct bt_conn_oob_info info = {
3696 				.type = BT_CONN_OOB_LE_SC,
3697 				.lesc.oob_config = BT_CONN_OOB_NO_DATA,
3698 			};
3699 
3700 			le_sc_oob_config_set(smp, &info);
3701 
3702 			smp->oobd_local = NULL;
3703 			smp->oobd_remote = NULL;
3704 
3705 			atomic_set_bit(smp->flags, SMP_FLAG_OOB_PENDING);
3706 			smp_auth_cb->oob_data_request(smp->chan.chan.conn, &info);
3707 
3708 			return 0;
3709 		} else {
3710 			return BT_SMP_ERR_OOB_NOT_AVAIL;
3711 		}
3712 	default:
3713 		LOG_ERR("Unknown pairing method (%u)", smp->method);
3714 		return BT_SMP_ERR_UNSPECIFIED;
3715 	}
3716 
3717 	atomic_set_bit(smp->allowed_cmds, BT_SMP_DHKEY_CHECK);
3718 	atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT);
3719 	return smp_send_pairing_random(smp);
3720 #else
3721 	return BT_SMP_ERR_PAIRING_NOTSUPP;
3722 #endif /* CONFIG_BT_PERIPHERAL */
3723 }
3724 
smp_pairing_failed(struct bt_smp * smp,struct net_buf * buf)3725 static uint8_t smp_pairing_failed(struct bt_smp *smp, struct net_buf *buf)
3726 {
3727 	struct bt_conn *conn = smp->chan.chan.conn;
3728 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
3729 	struct bt_smp_pairing_fail *req = (void *)buf->data;
3730 
3731 	LOG_ERR("pairing failed (peer reason 0x%x)", req->reason);
3732 
3733 	if (atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER) ||
3734 	    atomic_test_and_clear_bit(smp->flags, SMP_FLAG_DISPLAY)) {
3735 		if (smp_auth_cb && smp_auth_cb->cancel) {
3736 			smp_auth_cb->cancel(conn);
3737 		}
3738 	}
3739 
3740 	smp_pairing_complete(smp, req->reason);
3741 
3742 	/* return no error to avoid sending Pairing Failed in response */
3743 	return 0;
3744 }
3745 
smp_ident_info(struct bt_smp * smp,struct net_buf * buf)3746 static uint8_t smp_ident_info(struct bt_smp *smp, struct net_buf *buf)
3747 {
3748 	LOG_DBG("");
3749 
3750 	if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
3751 		struct bt_smp_ident_info *req = (void *)buf->data;
3752 		struct bt_conn *conn = smp->chan.chan.conn;
3753 		struct bt_keys *keys;
3754 
3755 		keys = bt_keys_get_type(BT_KEYS_IRK, conn->id, &conn->le.dst);
3756 		if (!keys) {
3757 			LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst));
3758 			return BT_SMP_ERR_UNSPECIFIED;
3759 		}
3760 
3761 		memcpy(keys->irk.val, req->irk, 16);
3762 	}
3763 
3764 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_IDENT_ADDR_INFO);
3765 
3766 	return 0;
3767 }
3768 
smp_id_add_replace(struct bt_smp * smp,struct bt_keys * new_bond)3769 static uint8_t smp_id_add_replace(struct bt_smp *smp, struct bt_keys *new_bond)
3770 {
3771 	struct bt_keys *conflict;
3772 
3773 	/* Sanity check: It does not make sense to finalize a bond before we
3774 	 * have the remote identity.
3775 	 */
3776 	__ASSERT_NO_MSG(!(smp->remote_dist & BT_SMP_DIST_ID_KEY));
3777 
3778 	conflict = bt_id_find_conflict(new_bond);
3779 	if (conflict) {
3780 		LOG_DBG("New bond conflicts with a bond on id %d.", conflict->id);
3781 	}
3782 
3783 	if (conflict && !IS_ENABLED(CONFIG_BT_ID_UNPAIR_MATCHING_BONDS)) {
3784 		LOG_WRN("Refusing new pairing. The old bond must be unpaired first.");
3785 		return BT_SMP_ERR_AUTH_REQUIREMENTS;
3786 	}
3787 
3788 	if (conflict && IS_ENABLED(CONFIG_BT_ID_UNPAIR_MATCHING_BONDS)) {
3789 		bool trust_ok;
3790 		int unpair_err;
3791 
3792 		trust_ok = update_keys_check(smp, conflict);
3793 		if (!trust_ok) {
3794 			LOG_WRN("Refusing new pairing. The old bond has more trust.");
3795 			return BT_SMP_ERR_AUTH_REQUIREMENTS;
3796 		}
3797 
3798 		LOG_DBG("Un-pairing old conflicting bond and finalizing new.");
3799 
3800 		unpair_err = bt_unpair(conflict->id, &conflict->addr);
3801 		__ASSERT_NO_MSG(!unpair_err);
3802 	}
3803 
3804 	__ASSERT_NO_MSG(!bt_id_find_conflict(new_bond));
3805 	bt_id_add(new_bond);
3806 	return 0;
3807 }
3808 
3809 struct addr_match {
3810 	const bt_addr_le_t *rpa;
3811 	const bt_addr_le_t *id_addr;
3812 };
3813 
convert_to_id_on_match(struct bt_conn * conn,void * data)3814 static void convert_to_id_on_match(struct bt_conn *conn, void *data)
3815 {
3816 	struct addr_match *addr_match = data;
3817 
3818 	if (bt_addr_le_eq(&conn->le.dst, addr_match->rpa)) {
3819 		bt_addr_le_copy(&conn->le.dst, addr_match->id_addr);
3820 	}
3821 }
3822 
smp_ident_addr_info(struct bt_smp * smp,struct net_buf * buf)3823 static uint8_t smp_ident_addr_info(struct bt_smp *smp, struct net_buf *buf)
3824 {
3825 	struct bt_conn *conn = smp->chan.chan.conn;
3826 	struct bt_smp_ident_addr_info *req = (void *)buf->data;
3827 	uint8_t err;
3828 
3829 	LOG_DBG("identity %s", bt_addr_le_str(&req->addr));
3830 
3831 	smp->remote_dist &= ~BT_SMP_DIST_ID_KEY;
3832 
3833 	if (!bt_addr_le_is_identity(&req->addr)) {
3834 		LOG_ERR("Invalid identity %s", bt_addr_le_str(&req->addr));
3835 		LOG_ERR(" for %s", bt_addr_le_str(&conn->le.dst));
3836 		return BT_SMP_ERR_INVALID_PARAMS;
3837 	}
3838 
3839 	if (!bt_addr_le_eq(&conn->le.dst, &req->addr)) {
3840 		struct bt_keys *keys = bt_keys_find_addr(conn->id, &req->addr);
3841 
3842 		if (keys) {
3843 			if (!update_keys_check(smp, keys)) {
3844 				return BT_SMP_ERR_UNSPECIFIED;
3845 			}
3846 
3847 			bt_keys_clear(keys);
3848 		}
3849 	}
3850 
3851 	if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
3852 		const bt_addr_le_t *dst;
3853 		struct bt_keys *keys;
3854 
3855 		keys = bt_keys_get_type(BT_KEYS_IRK, conn->id, &conn->le.dst);
3856 		if (!keys) {
3857 			LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst));
3858 			return BT_SMP_ERR_UNSPECIFIED;
3859 		}
3860 
3861 		/*
3862 		 * We can't use conn->dst here as this might already contain
3863 		 * identity address known from previous pairing. Since all keys
3864 		 * are cleared on re-pairing we wouldn't store IRK distributed
3865 		 * in new pairing.
3866 		 */
3867 		if (conn->role == BT_HCI_ROLE_CENTRAL) {
3868 			dst = &conn->le.resp_addr;
3869 		} else {
3870 			dst = &conn->le.init_addr;
3871 		}
3872 
3873 		if (bt_addr_le_is_rpa(dst)) {
3874 			/* always update last use RPA */
3875 			bt_addr_copy(&keys->irk.rpa, &dst->a);
3876 
3877 			/*
3878 			 * Update connection address and notify about identity
3879 			 * resolved only if connection wasn't already reported
3880 			 * with identity address. This may happen if IRK was
3881 			 * present before ie. due to re-pairing.
3882 			 */
3883 			if (!bt_addr_le_is_identity(&conn->le.dst)) {
3884 				struct addr_match addr_match = {
3885 					.rpa = &conn->le.dst,
3886 					.id_addr = &req->addr,
3887 				};
3888 
3889 				bt_conn_foreach(BT_CONN_TYPE_LE,
3890 						convert_to_id_on_match,
3891 						&addr_match);
3892 				bt_addr_le_copy(&keys->addr, &req->addr);
3893 
3894 				bt_conn_identity_resolved(conn);
3895 			}
3896 		}
3897 
3898 		err = smp_id_add_replace(smp, keys);
3899 		if (err) {
3900 			return err;
3901 		}
3902 	}
3903 
3904 	if (smp->remote_dist & BT_SMP_DIST_SIGN) {
3905 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO);
3906 	}
3907 
3908 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
3909 	    conn->role == BT_HCI_ROLE_CENTRAL && !smp->remote_dist) {
3910 		err = bt_smp_distribute_keys(smp);
3911 		if (err) {
3912 			return err;
3913 		}
3914 	}
3915 
3916 	/* if all keys were distributed, pairing is done */
3917 	if (!smp->local_dist && !smp->remote_dist) {
3918 		smp_pairing_complete(smp, 0);
3919 	}
3920 
3921 	return 0;
3922 }
3923 
3924 #if defined(CONFIG_BT_SIGNING)
smp_signing_info(struct bt_smp * smp,struct net_buf * buf)3925 static uint8_t smp_signing_info(struct bt_smp *smp, struct net_buf *buf)
3926 {
3927 	struct bt_conn *conn = smp->chan.chan.conn;
3928 	uint8_t err;
3929 
3930 	LOG_DBG("");
3931 
3932 	if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
3933 		struct bt_smp_signing_info *req = (void *)buf->data;
3934 		struct bt_keys *keys;
3935 
3936 		keys = bt_keys_get_type(BT_KEYS_REMOTE_CSRK, conn->id,
3937 					&conn->le.dst);
3938 		if (!keys) {
3939 			LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst));
3940 			return BT_SMP_ERR_UNSPECIFIED;
3941 		}
3942 
3943 		memcpy(keys->remote_csrk.val, req->csrk,
3944 		       sizeof(keys->remote_csrk.val));
3945 	}
3946 
3947 	smp->remote_dist &= ~BT_SMP_DIST_SIGN;
3948 
3949 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
3950 	    conn->role == BT_HCI_ROLE_CENTRAL && !smp->remote_dist) {
3951 		err = bt_smp_distribute_keys(smp);
3952 		if (err) {
3953 			return err;
3954 		}
3955 	}
3956 
3957 	/* if all keys were distributed, pairing is done */
3958 	if (!smp->local_dist && !smp->remote_dist) {
3959 		smp_pairing_complete(smp, 0);
3960 	}
3961 
3962 	return 0;
3963 }
3964 #else
smp_signing_info(struct bt_smp * smp,struct net_buf * buf)3965 static uint8_t smp_signing_info(struct bt_smp *smp, struct net_buf *buf)
3966 {
3967 	return BT_SMP_ERR_CMD_NOTSUPP;
3968 }
3969 #endif /* CONFIG_BT_SIGNING */
3970 
3971 #if defined(CONFIG_BT_CENTRAL)
smp_security_request(struct bt_smp * smp,struct net_buf * buf)3972 static uint8_t smp_security_request(struct bt_smp *smp, struct net_buf *buf)
3973 {
3974 	struct bt_conn *conn = smp->chan.chan.conn;
3975 	struct bt_smp_security_request *req = (void *)buf->data;
3976 	uint8_t auth;
3977 
3978 	LOG_DBG("");
3979 
3980 	/* A higher security level is requested during the key distribution
3981 	 * phase, once pairing is complete a new pairing procedure will start.
3982 	 */
3983 	if (atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR)) {
3984 		return 0;
3985 	}
3986 
3987 	if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
3988 		/* We have already started pairing process */
3989 		return 0;
3990 	}
3991 
3992 	if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) {
3993 		/* We have already started encryption procedure */
3994 		return 0;
3995 	}
3996 
3997 	if (sc_supported) {
3998 		auth = req->auth_req & BT_SMP_AUTH_MASK_SC;
3999 	} else {
4000 		auth = req->auth_req & BT_SMP_AUTH_MASK;
4001 	}
4002 
4003 	if (IS_ENABLED(CONFIG_BT_SMP_SC_PAIR_ONLY) &&
4004 	    !(auth & BT_SMP_AUTH_SC)) {
4005 		return BT_SMP_ERR_AUTH_REQUIREMENTS;
4006 	}
4007 
4008 	if (IS_ENABLED(CONFIG_BT_BONDING_REQUIRED) &&
4009 	    !(latch_bondable(smp) && (auth & BT_SMP_AUTH_BONDING))) {
4010 		/* Reject security req if not both intend to bond */
4011 		LOG_DBG("Bonding required");
4012 		return BT_SMP_ERR_UNSPECIFIED;
4013 	}
4014 
4015 	if (conn->le.keys) {
4016 		/* Make sure we have an LTK to encrypt with */
4017 		if (!(conn->le.keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_LTK))) {
4018 			goto pair;
4019 		}
4020 	} else {
4021 		conn->le.keys = bt_keys_find(BT_KEYS_LTK_P256, conn->id,
4022 					     &conn->le.dst);
4023 		if (!conn->le.keys) {
4024 			conn->le.keys = bt_keys_find(BT_KEYS_LTK, conn->id,
4025 						     &conn->le.dst);
4026 		}
4027 	}
4028 
4029 	if (!conn->le.keys) {
4030 		goto pair;
4031 	}
4032 
4033 	/* if MITM required key must be authenticated */
4034 	if ((auth & BT_SMP_AUTH_MITM) &&
4035 	    !(conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) {
4036 		if (get_io_capa(smp) != BT_SMP_IO_NO_INPUT_OUTPUT) {
4037 			LOG_INF("New auth requirements: 0x%x, repairing", auth);
4038 			goto pair;
4039 		}
4040 
4041 		LOG_WRN("Unsupported auth requirements: 0x%x, repairing", auth);
4042 		goto pair;
4043 	}
4044 
4045 	/* if LE SC required and no p256 key present repair */
4046 	if ((auth & BT_SMP_AUTH_SC) &&
4047 	    !(conn->le.keys->keys & BT_KEYS_LTK_P256)) {
4048 		LOG_INF("New auth requirements: 0x%x, repairing", auth);
4049 		goto pair;
4050 	}
4051 
4052 	if (bt_conn_le_start_encryption(conn, conn->le.keys->ltk.rand,
4053 					conn->le.keys->ltk.ediv,
4054 					conn->le.keys->ltk.val,
4055 					conn->le.keys->enc_size) < 0) {
4056 		LOG_ERR("Failed to start encryption");
4057 		return BT_SMP_ERR_UNSPECIFIED;
4058 	}
4059 
4060 	atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
4061 
4062 	return 0;
4063 pair:
4064 	if (smp_send_pairing_req(conn) < 0) {
4065 		return BT_SMP_ERR_UNSPECIFIED;
4066 	}
4067 
4068 	atomic_set_bit(smp->flags, SMP_FLAG_SEC_REQ);
4069 
4070 	return 0;
4071 }
4072 #else
smp_security_request(struct bt_smp * smp,struct net_buf * buf)4073 static uint8_t smp_security_request(struct bt_smp *smp, struct net_buf *buf)
4074 {
4075 	return BT_SMP_ERR_CMD_NOTSUPP;
4076 }
4077 #endif /* CONFIG_BT_CENTRAL */
4078 
generate_dhkey(struct bt_smp * smp)4079 static uint8_t generate_dhkey(struct bt_smp *smp)
4080 {
4081 	if (IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)) {
4082 		return BT_SMP_ERR_UNSPECIFIED;
4083 	}
4084 
4085 	atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_PENDING);
4086 	if (!smp_find(SMP_FLAG_DHKEY_GEN)) {
4087 		return smp_dhkey_generate(smp);
4088 	}
4089 
4090 	return 0;
4091 }
4092 
display_passkey(struct bt_smp * smp)4093 static uint8_t display_passkey(struct bt_smp *smp)
4094 {
4095 	struct bt_conn *conn = smp->chan.chan.conn;
4096 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
4097 
4098 	if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) &&
4099 	    fixed_passkey != BT_PASSKEY_INVALID) {
4100 		smp->passkey = fixed_passkey;
4101 	} else {
4102 		if (bt_rand(&smp->passkey, sizeof(smp->passkey))) {
4103 			return BT_SMP_ERR_UNSPECIFIED;
4104 		}
4105 
4106 		smp->passkey %= 1000000;
4107 	}
4108 
4109 	smp->passkey_round = 0U;
4110 
4111 	if (smp_auth_cb && smp_auth_cb->passkey_display) {
4112 		atomic_set_bit(smp->flags, SMP_FLAG_DISPLAY);
4113 		smp_auth_cb->passkey_display(conn, smp->passkey);
4114 	}
4115 
4116 	smp->passkey = sys_cpu_to_le32(smp->passkey);
4117 
4118 	return 0;
4119 }
4120 
4121 #if defined(CONFIG_BT_PERIPHERAL)
smp_public_key_periph(struct bt_smp * smp)4122 static uint8_t smp_public_key_periph(struct bt_smp *smp)
4123 {
4124 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
4125 	uint8_t err;
4126 
4127 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY) &&
4128 	    memcmp(smp->pkey, sc_public_key, BT_PUB_KEY_COORD_LEN) == 0) {
4129 		/* Deny public key with identitcal X coordinate unless it is the
4130 		 * debug public key.
4131 		 */
4132 		LOG_WRN("Remote public key rejected");
4133 		return BT_SMP_ERR_UNSPECIFIED;
4134 	}
4135 
4136 	err = sc_send_public_key(smp);
4137 	if (err) {
4138 		return err;
4139 	}
4140 
4141 	switch (smp->method) {
4142 	case PASSKEY_CONFIRM:
4143 	case JUST_WORKS:
4144 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
4145 
4146 		err = smp_send_pairing_confirm(smp);
4147 		if (err) {
4148 			return err;
4149 		}
4150 		break;
4151 	case PASSKEY_DISPLAY:
4152 		err = display_passkey(smp);
4153 		if (err) {
4154 			return err;
4155 		}
4156 
4157 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM);
4158 		atomic_set_bit(smp->allowed_cmds, BT_SMP_KEYPRESS_NOTIFICATION);
4159 		break;
4160 	case PASSKEY_INPUT:
4161 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM);
4162 		atomic_set_bit(smp->allowed_cmds, BT_SMP_KEYPRESS_NOTIFICATION);
4163 		atomic_set_bit(smp->flags, SMP_FLAG_USER);
4164 		smp_auth_cb->passkey_entry(smp->chan.chan.conn);
4165 		break;
4166 	case LE_SC_OOB:
4167 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
4168 		break;
4169 	default:
4170 		LOG_ERR("Unknown pairing method (%u)", smp->method);
4171 		return BT_SMP_ERR_UNSPECIFIED;
4172 	}
4173 
4174 	return generate_dhkey(smp);
4175 }
4176 #endif /* CONFIG_BT_PERIPHERAL */
4177 
smp_public_key(struct bt_smp * smp,struct net_buf * buf)4178 static uint8_t smp_public_key(struct bt_smp *smp, struct net_buf *buf)
4179 {
4180 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
4181 	struct bt_smp_public_key *req = (void *)buf->data;
4182 	uint8_t err;
4183 
4184 	LOG_DBG("");
4185 
4186 	memcpy(smp->pkey, req->x, BT_PUB_KEY_COORD_LEN);
4187 	memcpy(&smp->pkey[BT_PUB_KEY_COORD_LEN], req->y, BT_PUB_KEY_COORD_LEN);
4188 
4189 	/* mark key as debug if remote is using it */
4190 	if (bt_pub_key_is_debug(smp->pkey)) {
4191 		LOG_INF("Remote is using Debug Public key");
4192 		atomic_set_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY);
4193 
4194 		/* Don't allow a bond established without debug key to be
4195 		 * updated using LTK generated from debug key.
4196 		 */
4197 		if (!update_debug_keys_check(smp)) {
4198 			return BT_SMP_ERR_AUTH_REQUIREMENTS;
4199 		}
4200 	}
4201 
4202 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
4203 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
4204 		if (!atomic_test_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY) &&
4205 		    memcmp(smp->pkey, sc_public_key, BT_PUB_KEY_COORD_LEN) == 0) {
4206 			/* Deny public key with identitcal X coordinate unless
4207 			 * it is the debug public key.
4208 			 */
4209 			LOG_WRN("Remote public key rejected");
4210 			return BT_SMP_ERR_UNSPECIFIED;
4211 		}
4212 
4213 		switch (smp->method) {
4214 		case PASSKEY_CONFIRM:
4215 		case JUST_WORKS:
4216 			atomic_set_bit(smp->allowed_cmds,
4217 				       BT_SMP_CMD_PAIRING_CONFIRM);
4218 			break;
4219 		case PASSKEY_DISPLAY:
4220 			err = display_passkey(smp);
4221 			if (err) {
4222 				return err;
4223 			}
4224 
4225 			atomic_set_bit(smp->allowed_cmds,
4226 				       BT_SMP_CMD_PAIRING_CONFIRM);
4227 
4228 			atomic_set_bit(smp->allowed_cmds,
4229 				       BT_SMP_KEYPRESS_NOTIFICATION);
4230 
4231 			err = smp_send_pairing_confirm(smp);
4232 			if (err) {
4233 				return err;
4234 			}
4235 			break;
4236 		case PASSKEY_INPUT:
4237 			atomic_set_bit(smp->flags, SMP_FLAG_USER);
4238 			smp_auth_cb->passkey_entry(smp->chan.chan.conn);
4239 
4240 			atomic_set_bit(smp->allowed_cmds,
4241 				       BT_SMP_KEYPRESS_NOTIFICATION);
4242 
4243 			break;
4244 		case LE_SC_OOB:
4245 			/* Step 6: Select random N */
4246 			if (bt_rand(smp->prnd, 16)) {
4247 				return BT_SMP_ERR_UNSPECIFIED;
4248 			}
4249 
4250 			if (smp_auth_cb && smp_auth_cb->oob_data_request) {
4251 				struct bt_conn_oob_info info = {
4252 					.type = BT_CONN_OOB_LE_SC,
4253 					.lesc.oob_config = BT_CONN_OOB_NO_DATA,
4254 				};
4255 
4256 				le_sc_oob_config_set(smp, &info);
4257 
4258 				smp->oobd_local = NULL;
4259 				smp->oobd_remote = NULL;
4260 
4261 				atomic_set_bit(smp->flags,
4262 					       SMP_FLAG_OOB_PENDING);
4263 				smp_auth_cb->oob_data_request(smp->chan.chan.conn, &info);
4264 			} else {
4265 				return BT_SMP_ERR_OOB_NOT_AVAIL;
4266 			}
4267 			break;
4268 		default:
4269 			LOG_ERR("Unknown pairing method (%u)", smp->method);
4270 			return BT_SMP_ERR_UNSPECIFIED;
4271 		}
4272 
4273 		return generate_dhkey(smp);
4274 	}
4275 
4276 #if defined(CONFIG_BT_PERIPHERAL)
4277 	if (!sc_public_key) {
4278 		atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND);
4279 		return 0;
4280 	}
4281 
4282 	err = smp_public_key_periph(smp);
4283 	if (err) {
4284 		return err;
4285 	}
4286 #endif /* CONFIG_BT_PERIPHERAL */
4287 
4288 	return 0;
4289 }
4290 
smp_dhkey_check(struct bt_smp * smp,struct net_buf * buf)4291 static uint8_t smp_dhkey_check(struct bt_smp *smp, struct net_buf *buf)
4292 {
4293 	struct bt_smp_dhkey_check *req = (void *)buf->data;
4294 
4295 	LOG_DBG("");
4296 
4297 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
4298 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
4299 		uint8_t e[16], r[16], enc_size;
4300 		uint8_t ediv[2], rand[8];
4301 
4302 		(void)memset(r, 0, sizeof(r));
4303 
4304 		switch (smp->method) {
4305 		case JUST_WORKS:
4306 		case PASSKEY_CONFIRM:
4307 			break;
4308 		case PASSKEY_DISPLAY:
4309 		case PASSKEY_INPUT:
4310 			memcpy(r, &smp->passkey, sizeof(smp->passkey));
4311 			break;
4312 		case LE_SC_OOB:
4313 			if (smp->oobd_local) {
4314 				memcpy(r, smp->oobd_local->r, sizeof(r));
4315 			}
4316 			break;
4317 		default:
4318 			LOG_ERR("Unknown pairing method (%u)", smp->method);
4319 			return BT_SMP_ERR_UNSPECIFIED;
4320 		}
4321 
4322 		/* calculate remote DHKey check for comparison */
4323 		if (bt_crypto_f6(smp->mackey, smp->rrnd, smp->prnd, r, &smp->prsp[1],
4324 				 &smp->chan.chan.conn->le.resp_addr,
4325 				 &smp->chan.chan.conn->le.init_addr, e)) {
4326 			return BT_SMP_ERR_UNSPECIFIED;
4327 		}
4328 
4329 		if (memcmp(e, req->e, 16)) {
4330 			return BT_SMP_ERR_DHKEY_CHECK_FAILED;
4331 		}
4332 
4333 		enc_size = get_encryption_key_size(smp);
4334 
4335 		/* Rand and EDiv are 0 */
4336 		(void)memset(ediv, 0, sizeof(ediv));
4337 		(void)memset(rand, 0, sizeof(rand));
4338 		if (bt_conn_le_start_encryption(smp->chan.chan.conn, rand, ediv,
4339 						smp->tk, enc_size) < 0) {
4340 			LOG_ERR("Failed to start encryption");
4341 			return BT_SMP_ERR_UNSPECIFIED;
4342 		}
4343 
4344 		atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
4345 
4346 		if (IS_ENABLED(CONFIG_BT_SMP_USB_HCI_CTLR_WORKAROUND)) {
4347 			if (smp->remote_dist & BT_SMP_DIST_ID_KEY) {
4348 				atomic_set_bit(smp->allowed_cmds,
4349 					       BT_SMP_CMD_IDENT_INFO);
4350 			} else if (smp->remote_dist & BT_SMP_DIST_SIGN) {
4351 				atomic_set_bit(smp->allowed_cmds,
4352 					       BT_SMP_CMD_SIGNING_INFO);
4353 			}
4354 		}
4355 
4356 		return 0;
4357 	}
4358 
4359 #if defined(CONFIG_BT_PERIPHERAL)
4360 	if (smp->chan.chan.conn->role == BT_HCI_ROLE_PERIPHERAL) {
4361 		atomic_clear_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT);
4362 		memcpy(smp->e, req->e, sizeof(smp->e));
4363 
4364 		/* wait for DHKey being generated */
4365 		if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) {
4366 			atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
4367 			return 0;
4368 		}
4369 
4370 		/* waiting for user to confirm passkey */
4371 		if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) {
4372 			atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
4373 			return 0;
4374 		}
4375 
4376 		return compute_and_check_and_send_periph_dhcheck(smp);
4377 	}
4378 #endif /* CONFIG_BT_PERIPHERAL */
4379 
4380 	return 0;
4381 }
4382 
4383 #if defined(CONFIG_BT_PASSKEY_KEYPRESS)
smp_keypress_notif(struct bt_smp * smp,struct net_buf * buf)4384 static uint8_t smp_keypress_notif(struct bt_smp *smp, struct net_buf *buf)
4385 {
4386 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
4387 	struct bt_conn *conn = smp->chan.chan.conn;
4388 	struct bt_smp_keypress_notif *notif = (void *)buf->data;
4389 	enum bt_conn_auth_keypress type = notif->type;
4390 
4391 	LOG_DBG("Keypress from conn %u, type %u", bt_conn_index(conn), type);
4392 
4393 	/* For now, keypress notifications are always accepted. In the future we
4394 	 * should be smarter about this. We might also want to enforce something
4395 	 * about the 'start' and 'end' messages.
4396 	 */
4397 	atomic_set_bit(smp->allowed_cmds, BT_SMP_KEYPRESS_NOTIFICATION);
4398 
4399 	if (!IN_RANGE(type,
4400 		      BT_CONN_AUTH_KEYPRESS_ENTRY_STARTED,
4401 		      BT_CONN_AUTH_KEYPRESS_ENTRY_COMPLETED)) {
4402 		LOG_WRN("Received unknown keypress event type %u. Discarding.", type);
4403 		return BT_SMP_ERR_INVALID_PARAMS;
4404 	}
4405 
4406 	/* Reset SMP timeout, like the spec says. */
4407 	k_work_reschedule(&smp->work, SMP_TIMEOUT);
4408 
4409 	if (smp_auth_cb->passkey_display_keypress) {
4410 		smp_auth_cb->passkey_display_keypress(conn, type);
4411 	}
4412 
4413 	return 0;
4414 }
4415 #else
smp_keypress_notif(struct bt_smp * smp,struct net_buf * buf)4416 static uint8_t smp_keypress_notif(struct bt_smp *smp, struct net_buf *buf)
4417 {
4418 	ARG_UNUSED(smp);
4419 	ARG_UNUSED(buf);
4420 
4421 	LOG_DBG("");
4422 
4423 	/* Ignore packets until keypress notifications are fully supported. */
4424 	atomic_set_bit(smp->allowed_cmds, BT_SMP_KEYPRESS_NOTIFICATION);
4425 	return 0;
4426 }
4427 #endif
4428 
4429 static const struct {
4430 	uint8_t  (*func)(struct bt_smp *smp, struct net_buf *buf);
4431 	uint8_t  expect_len;
4432 } handlers[] = {
4433 	{ }, /* No op-code defined for 0x00 */
4434 	{ smp_pairing_req,         sizeof(struct bt_smp_pairing) },
4435 	{ smp_pairing_rsp,         sizeof(struct bt_smp_pairing) },
4436 	{ smp_pairing_confirm,     sizeof(struct bt_smp_pairing_confirm) },
4437 	{ smp_pairing_random,      sizeof(struct bt_smp_pairing_random) },
4438 	{ smp_pairing_failed,      sizeof(struct bt_smp_pairing_fail) },
4439 	{ smp_encrypt_info,        sizeof(struct bt_smp_encrypt_info) },
4440 	{ smp_central_ident,       sizeof(struct bt_smp_central_ident) },
4441 	{ smp_ident_info,          sizeof(struct bt_smp_ident_info) },
4442 	{ smp_ident_addr_info,     sizeof(struct bt_smp_ident_addr_info) },
4443 	{ smp_signing_info,        sizeof(struct bt_smp_signing_info) },
4444 	{ smp_security_request,    sizeof(struct bt_smp_security_request) },
4445 	{ smp_public_key,          sizeof(struct bt_smp_public_key) },
4446 	{ smp_dhkey_check,         sizeof(struct bt_smp_dhkey_check) },
4447 	{ smp_keypress_notif,      sizeof(struct bt_smp_keypress_notif) },
4448 };
4449 
is_in_pairing_procedure(struct bt_smp * smp)4450 static bool is_in_pairing_procedure(struct bt_smp *smp)
4451 {
4452 	return atomic_test_bit(smp->flags, SMP_FLAG_PAIRING);
4453 }
4454 
bt_smp_recv(struct bt_l2cap_chan * chan,struct net_buf * buf)4455 static int bt_smp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
4456 {
4457 	struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan.chan);
4458 	struct bt_smp_hdr *hdr;
4459 	uint8_t err;
4460 
4461 	if (buf->len < sizeof(*hdr)) {
4462 		LOG_ERR("Too small SMP PDU received");
4463 		return 0;
4464 	}
4465 
4466 	hdr = net_buf_pull_mem(buf, sizeof(*hdr));
4467 	LOG_DBG("Received SMP code 0x%02x len %u", hdr->code, buf->len);
4468 
4469 	/*
4470 	 * If SMP timeout occurred "no further SMP commands shall be sent over
4471 	 * the L2CAP Security Manager Channel. A new SM procedure shall only be
4472 	 * performed when a new physical link has been established."
4473 	 */
4474 	if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) {
4475 		LOG_WRN("SMP command (code 0x%02x) received after timeout", hdr->code);
4476 		return 0;
4477 	}
4478 
4479 	/*
4480 	 * Bluetooth Core Specification Version 5.2, Vol 3, Part H, page 1667:
4481 	 * If a packet is received with a Code that is reserved for future use
4482 	 * it shall be ignored.
4483 	 */
4484 	if (hdr->code >= ARRAY_SIZE(handlers)) {
4485 		LOG_WRN("Received reserved SMP code 0x%02x", hdr->code);
4486 		return 0;
4487 	}
4488 
4489 	if (!handlers[hdr->code].func) {
4490 		LOG_WRN("Unhandled SMP code 0x%02x", hdr->code);
4491 		smp_error(smp, BT_SMP_ERR_CMD_NOTSUPP);
4492 		return 0;
4493 	}
4494 
4495 	if (!atomic_test_and_clear_bit(smp->allowed_cmds, hdr->code)) {
4496 		LOG_WRN("Unexpected SMP code 0x%02x", hdr->code);
4497 		/* Do not send errors outside of pairing procedure. */
4498 		if (is_in_pairing_procedure(smp)) {
4499 			smp_error(smp, BT_SMP_ERR_UNSPECIFIED);
4500 		}
4501 		return 0;
4502 	}
4503 
4504 	if (buf->len != handlers[hdr->code].expect_len) {
4505 		LOG_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code);
4506 		smp_error(smp, BT_SMP_ERR_INVALID_PARAMS);
4507 		return 0;
4508 	}
4509 
4510 	err = handlers[hdr->code].func(smp, buf);
4511 	if (err) {
4512 		smp_error(smp, err);
4513 	}
4514 
4515 	return 0;
4516 }
4517 
bt_smp_pkey_ready(const uint8_t * pkey)4518 static void bt_smp_pkey_ready(const uint8_t *pkey)
4519 {
4520 	int i;
4521 
4522 	LOG_DBG("");
4523 
4524 	sc_public_key = pkey;
4525 
4526 	if (!pkey) {
4527 		LOG_WRN("Public key not available");
4528 		return;
4529 	}
4530 
4531 	k_sem_give(&sc_local_pkey_ready);
4532 
4533 	for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) {
4534 		struct bt_smp *smp = &bt_smp_pool[i];
4535 		uint8_t err;
4536 
4537 		if (!atomic_test_bit(smp->flags, SMP_FLAG_PKEY_SEND)) {
4538 			continue;
4539 		}
4540 
4541 		if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
4542 		    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
4543 			err = sc_send_public_key(smp);
4544 			if (err) {
4545 				smp_error(smp, err);
4546 			}
4547 
4548 			atomic_set_bit(smp->allowed_cmds,
4549 				       BT_SMP_CMD_PUBLIC_KEY);
4550 			continue;
4551 		}
4552 
4553 #if defined(CONFIG_BT_PERIPHERAL)
4554 		err = smp_public_key_periph(smp);
4555 		if (err) {
4556 			smp_error(smp, err);
4557 		}
4558 #endif /* CONFIG_BT_PERIPHERAL */
4559 	}
4560 }
4561 
bt_smp_connected(struct bt_l2cap_chan * chan)4562 static void bt_smp_connected(struct bt_l2cap_chan *chan)
4563 {
4564 	struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan.chan);
4565 
4566 	LOG_DBG("chan %p cid 0x%04x", chan,
4567 		CONTAINER_OF(chan, struct bt_l2cap_le_chan, chan)->tx.cid);
4568 
4569 	k_work_init_delayable(&smp->work, smp_timeout);
4570 	smp_reset(smp);
4571 
4572 	atomic_ptr_set(&smp->auth_cb, BT_SMP_AUTH_CB_UNINITIALIZED);
4573 	atomic_set(&smp->bondable, BT_SMP_BONDABLE_UNINITIALIZED);
4574 }
4575 
bt_smp_disconnected(struct bt_l2cap_chan * chan)4576 static void bt_smp_disconnected(struct bt_l2cap_chan *chan)
4577 {
4578 	struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan.chan);
4579 	struct bt_keys *keys = chan->conn->le.keys;
4580 
4581 	LOG_DBG("chan %p cid 0x%04x", chan,
4582 		CONTAINER_OF(chan, struct bt_l2cap_le_chan, chan)->tx.cid);
4583 
4584 	/* Channel disconnected callback is always called from a work handler
4585 	 * so canceling of the timeout work should always succeed.
4586 	 */
4587 	(void)k_work_cancel_delayable(&smp->work);
4588 
4589 	if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING) ||
4590 	    atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING) ||
4591 	    atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ)) {
4592 		/* reset context and report */
4593 		smp_pairing_complete(smp, BT_SMP_ERR_UNSPECIFIED);
4594 	}
4595 
4596 	if (keys) {
4597 		/*
4598 		 * If debug keys were used for pairing remove them.
4599 		 * No keys indicate no bonding so free keys storage.
4600 		 */
4601 		if (!keys->keys || (!IS_ENABLED(CONFIG_BT_STORE_DEBUG_KEYS) &&
4602 		    (keys->flags & BT_KEYS_DEBUG))) {
4603 			bt_keys_clear(keys);
4604 		}
4605 	}
4606 
4607 	(void)memset(smp, 0, sizeof(*smp));
4608 }
4609 
bt_smp_encrypt_change(struct bt_l2cap_chan * chan,uint8_t hci_status)4610 static void bt_smp_encrypt_change(struct bt_l2cap_chan *chan,
4611 				  uint8_t hci_status)
4612 {
4613 	struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan.chan);
4614 	struct bt_conn *conn = chan->conn;
4615 
4616 	LOG_DBG("chan %p conn %p handle %u encrypt 0x%02x hci status 0x%02x", chan, conn,
4617 		conn->handle, conn->encrypt, hci_status);
4618 
4619 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_ENC_PENDING)) {
4620 		/* We where not waiting for encryption procedure.
4621 		 * This happens when encrypt change is called to notify that
4622 		 * security has failed before starting encryption.
4623 		 */
4624 		return;
4625 	}
4626 
4627 	if (hci_status) {
4628 		if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
4629 			uint8_t smp_err = smp_err_get(
4630 				bt_security_err_get(hci_status));
4631 
4632 			/* Fail as if it happened during key distribution */
4633 			atomic_set_bit(smp->flags, SMP_FLAG_KEYS_DISTR);
4634 			smp_pairing_complete(smp, smp_err);
4635 		}
4636 
4637 		return;
4638 	}
4639 
4640 	if (!conn->encrypt) {
4641 		return;
4642 	}
4643 
4644 	/* We were waiting for encryption but with no pairing in progress.
4645 	 * This can happen if paired peripheral sent Security Request and we
4646 	 * enabled encryption.
4647 	 */
4648 	if (!atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
4649 		smp_reset(smp);
4650 		return;
4651 	}
4652 
4653 	/* derive BR/EDR LinkKey if supported by both sides */
4654 	if (atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
4655 		if ((smp->local_dist & BT_SMP_DIST_LINK_KEY) &&
4656 		    (smp->remote_dist & BT_SMP_DIST_LINK_KEY)) {
4657 			/*
4658 			 * Link Key will be derived after key distribution to
4659 			 * make sure remote device identity is known
4660 			 */
4661 			atomic_set_bit(smp->flags, SMP_FLAG_DERIVE_LK);
4662 		}
4663 		/*
4664 		 * Those are used as pairing finished indicator so generated
4665 		 * but not distributed keys must be cleared here.
4666 		 */
4667 		smp->local_dist &= ~BT_SMP_DIST_LINK_KEY;
4668 		smp->remote_dist &= ~BT_SMP_DIST_LINK_KEY;
4669 	}
4670 
4671 	if (smp->remote_dist & BT_SMP_DIST_ENC_KEY) {
4672 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_ENCRYPT_INFO);
4673 	} else if (smp->remote_dist & BT_SMP_DIST_ID_KEY) {
4674 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO);
4675 	} else if (smp->remote_dist & BT_SMP_DIST_SIGN) {
4676 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO);
4677 	}
4678 
4679 	/* This is the last point that is common for all code paths in the
4680 	 * pairing process (during which we still have the option to send
4681 	 * Pairing Failed). That makes it convenient to update the RL here. We
4682 	 * want to update the RL during the pairing process so that we can fail
4683 	 * it in case there is a conflict with an existing bond.
4684 	 *
4685 	 * We can do the update here only if the peer does not intend to send us
4686 	 * any identity information. In this case we already have everything
4687 	 * that goes into the RL.
4688 	 *
4689 	 * We need an entry in the RL despite the remote not using privacy. This
4690 	 * is because we are using privacy locally and need to associate correct
4691 	 * local IRK with the peer.
4692 	 *
4693 	 * If the peer does intend to send us identity information, we must wait
4694 	 * for that information to enter it in the RL. In that case, we call
4695 	 * `smp_id_add_replace` not here, but later. If neither we nor the peer
4696 	 * are using privacy, there is no need for an entry in the RL.
4697 	 */
4698 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
4699 	    IS_ENABLED(CONFIG_BT_PRIVACY) &&
4700 	    conn->role == BT_HCI_ROLE_CENTRAL &&
4701 	    !(smp->remote_dist & BT_SMP_DIST_ID_KEY)) {
4702 		uint8_t smp_err;
4703 
4704 		smp_err = smp_id_add_replace(smp, conn->le.keys);
4705 		if (smp_err) {
4706 			smp_pairing_complete(smp, smp_err);
4707 		}
4708 	}
4709 
4710 	atomic_set_bit(smp->flags, SMP_FLAG_KEYS_DISTR);
4711 
4712 	/* Peripheral distributes it's keys first */
4713 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
4714 	    conn->role == BT_HCI_ROLE_CENTRAL && smp->remote_dist) {
4715 		return;
4716 	}
4717 
4718 	if (IS_ENABLED(CONFIG_BT_TESTING)) {
4719 		/* Avoid the HCI-USB race condition where HCI data and
4720 		 * HCI events can be re-ordered, and pairing information appears
4721 		 * to be sent unencrypted.
4722 		 */
4723 		k_sleep(K_MSEC(100));
4724 	}
4725 
4726 	if (bt_smp_distribute_keys(smp)) {
4727 		return;
4728 	}
4729 
4730 	/* if all keys were distributed, pairing is done */
4731 	if (!smp->local_dist && !smp->remote_dist) {
4732 		smp_pairing_complete(smp, 0);
4733 	}
4734 }
4735 
4736 #if defined(CONFIG_BT_SIGNING) || defined(CONFIG_BT_SMP_SELFTEST)
4737 /* Sign message using msg as a buffer, len is a size of the message,
4738  * msg buffer contains message itself, 32 bit count and signature,
4739  * so total buffer size is len + 4 + 8 octets.
4740  * API is Little Endian to make it suitable for Bluetooth.
4741  */
smp_sign_buf(const uint8_t * key,uint8_t * msg,uint16_t len)4742 static int smp_sign_buf(const uint8_t *key, uint8_t *msg, uint16_t len)
4743 {
4744 	uint8_t *m = msg;
4745 	uint32_t cnt = UNALIGNED_GET((uint32_t *)&msg[len]);
4746 	uint8_t *sig = msg + len;
4747 	uint8_t key_s[16], tmp[16];
4748 	int err;
4749 
4750 	LOG_DBG("Signing msg %s len %u key %s", bt_hex(msg, len), len, bt_hex(key, 16));
4751 
4752 	sys_mem_swap(m, len + sizeof(cnt));
4753 	sys_memcpy_swap(key_s, key, 16);
4754 
4755 	err = bt_crypto_aes_cmac(key_s, m, len + sizeof(cnt), tmp);
4756 	if (err) {
4757 		LOG_ERR("Data signing failed");
4758 		return err;
4759 	}
4760 
4761 	sys_mem_swap(tmp, sizeof(tmp));
4762 	memcpy(tmp + 4, &cnt, sizeof(cnt));
4763 
4764 	/* Swap original message back */
4765 	sys_mem_swap(m, len + sizeof(cnt));
4766 
4767 	memcpy(sig, tmp + 4, 12);
4768 
4769 	LOG_DBG("sig %s", bt_hex(sig, 12));
4770 
4771 	return 0;
4772 }
4773 #endif
4774 
4775 #if defined(CONFIG_BT_SIGNING)
bt_smp_sign_verify(struct bt_conn * conn,struct net_buf * buf)4776 int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf)
4777 {
4778 	struct bt_keys *keys;
4779 	uint8_t sig[12];
4780 	uint32_t cnt;
4781 	int err;
4782 
4783 	/* Store signature incl. count */
4784 	memcpy(sig, net_buf_tail(buf) - sizeof(sig), sizeof(sig));
4785 
4786 	keys = bt_keys_find(BT_KEYS_REMOTE_CSRK, conn->id, &conn->le.dst);
4787 	if (!keys) {
4788 		LOG_ERR("Unable to find Remote CSRK for %s", bt_addr_le_str(&conn->le.dst));
4789 		return -ENOENT;
4790 	}
4791 
4792 	/* Copy signing count */
4793 	cnt = sys_cpu_to_le32(keys->remote_csrk.cnt);
4794 	memcpy(net_buf_tail(buf) - sizeof(sig), &cnt, sizeof(cnt));
4795 
4796 	LOG_DBG("Sign data len %zu key %s count %u", buf->len - sizeof(sig),
4797 		bt_hex(keys->remote_csrk.val, 16), keys->remote_csrk.cnt);
4798 
4799 	err = smp_sign_buf(keys->remote_csrk.val, buf->data,
4800 			   buf->len - sizeof(sig));
4801 	if (err) {
4802 		LOG_ERR("Unable to create signature for %s", bt_addr_le_str(&conn->le.dst));
4803 		return -EIO;
4804 	}
4805 
4806 	if (memcmp(sig, net_buf_tail(buf) - sizeof(sig), sizeof(sig))) {
4807 		LOG_ERR("Unable to verify signature for %s", bt_addr_le_str(&conn->le.dst));
4808 		return -EBADMSG;
4809 	}
4810 
4811 	keys->remote_csrk.cnt++;
4812 
4813 	return 0;
4814 }
4815 
bt_smp_sign(struct bt_conn * conn,struct net_buf * buf)4816 int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf)
4817 {
4818 	struct bt_keys *keys;
4819 	uint32_t cnt;
4820 	int err;
4821 
4822 	keys = bt_keys_find(BT_KEYS_LOCAL_CSRK, conn->id, &conn->le.dst);
4823 	if (!keys) {
4824 		LOG_ERR("Unable to find local CSRK for %s", bt_addr_le_str(&conn->le.dst));
4825 		return -ENOENT;
4826 	}
4827 
4828 	/* Reserve space for data signature */
4829 	net_buf_add(buf, 12);
4830 
4831 	/* Copy signing count */
4832 	cnt = sys_cpu_to_le32(keys->local_csrk.cnt);
4833 	memcpy(net_buf_tail(buf) - 12, &cnt, sizeof(cnt));
4834 
4835 	LOG_DBG("Sign data len %u key %s count %u", buf->len, bt_hex(keys->local_csrk.val, 16),
4836 		keys->local_csrk.cnt);
4837 
4838 	err = smp_sign_buf(keys->local_csrk.val, buf->data, buf->len - 12);
4839 	if (err) {
4840 		LOG_ERR("Unable to create signature for %s", bt_addr_le_str(&conn->le.dst));
4841 		return -EIO;
4842 	}
4843 
4844 	keys->local_csrk.cnt++;
4845 
4846 	return 0;
4847 }
4848 #else
bt_smp_sign_verify(struct bt_conn * conn,struct net_buf * buf)4849 int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf)
4850 {
4851 	return -ENOTSUP;
4852 }
4853 
bt_smp_sign(struct bt_conn * conn,struct net_buf * buf)4854 int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf)
4855 {
4856 	return -ENOTSUP;
4857 }
4858 #endif /* CONFIG_BT_SIGNING */
4859 
smp_d1(const uint8_t * key,uint16_t d,uint16_t r,uint8_t res[16])4860 static int smp_d1(const uint8_t *key, uint16_t d, uint16_t r, uint8_t res[16])
4861 {
4862 	int err;
4863 
4864 	LOG_DBG("key %s d %u r %u", bt_hex(key, 16), d, r);
4865 
4866 	sys_put_le16(d, &res[0]);
4867 	sys_put_le16(r, &res[2]);
4868 	memset(&res[4], 0, 16 - 4);
4869 
4870 	err = bt_encrypt_le(key, res, res);
4871 	if (err) {
4872 		return err;
4873 	}
4874 
4875 	LOG_DBG("res %s", bt_hex(res, 16));
4876 	return 0;
4877 }
4878 
bt_smp_irk_get(uint8_t * ir,uint8_t * irk)4879 int bt_smp_irk_get(uint8_t *ir, uint8_t *irk)
4880 {
4881 	uint8_t invalid_ir[16] = { 0 };
4882 
4883 	if (!memcmp(ir, invalid_ir, 16)) {
4884 		return -EINVAL;
4885 	}
4886 
4887 	return smp_d1(ir, 1, 0, irk);
4888 }
4889 
4890 #if defined(CONFIG_BT_SMP_SELFTEST)
4891 /* Test vectors are taken from RFC 4493
4892  * https://tools.ietf.org/html/rfc4493
4893  * Same mentioned in the Bluetooth Spec.
4894  */
4895 static const uint8_t key[] = {
4896 	0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
4897 	0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c
4898 };
4899 
4900 static const uint8_t M[] = {
4901 	0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96,
4902 	0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
4903 	0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c,
4904 	0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
4905 	0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11,
4906 	0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
4907 	0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17,
4908 	0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10
4909 };
4910 
aes_test(const char * prefix,const uint8_t * in_key,const uint8_t * m,uint16_t len,const uint8_t * mac)4911 static int aes_test(const char *prefix, const uint8_t *in_key, const uint8_t *m,
4912 		    uint16_t len, const uint8_t *mac)
4913 {
4914 	uint8_t out[16];
4915 
4916 	LOG_DBG("%s: AES CMAC of message with len %u", prefix, len);
4917 
4918 	bt_crypto_aes_cmac(in_key, m, len, out);
4919 	if (!memcmp(out, mac, 16)) {
4920 		LOG_DBG("%s: Success", prefix);
4921 	} else {
4922 		LOG_ERR("%s: Failed", prefix);
4923 		return -1;
4924 	}
4925 
4926 	return 0;
4927 }
4928 
smp_aes_cmac_test(void)4929 static int smp_aes_cmac_test(void)
4930 {
4931 	uint8_t mac1[] = {
4932 		0xbb, 0x1d, 0x69, 0x29, 0xe9, 0x59, 0x37, 0x28,
4933 		0x7f, 0xa3, 0x7d, 0x12, 0x9b, 0x75, 0x67, 0x46
4934 	};
4935 	uint8_t mac2[] = {
4936 		0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44,
4937 		0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a, 0x28, 0x7c
4938 	};
4939 	uint8_t mac3[] = {
4940 		0xdf, 0xa6, 0x67, 0x47, 0xde, 0x9a, 0xe6, 0x30,
4941 		0x30, 0xca, 0x32, 0x61, 0x14, 0x97, 0xc8, 0x27
4942 	};
4943 	uint8_t mac4[] = {
4944 		0x51, 0xf0, 0xbe, 0xbf, 0x7e, 0x3b, 0x9d, 0x92,
4945 		0xfc, 0x49, 0x74, 0x17, 0x79, 0x36, 0x3c, 0xfe
4946 	};
4947 	int err;
4948 
4949 	err = aes_test("Test aes-cmac0", key, M, 0, mac1);
4950 	if (err) {
4951 		return err;
4952 	}
4953 
4954 	err = aes_test("Test aes-cmac16", key, M, 16, mac2);
4955 	if (err) {
4956 		return err;
4957 	}
4958 
4959 	err = aes_test("Test aes-cmac40", key, M, 40, mac3);
4960 	if (err) {
4961 		return err;
4962 	}
4963 
4964 	err = aes_test("Test aes-cmac64", key, M, 64, mac4);
4965 	if (err) {
4966 		return err;
4967 	}
4968 
4969 	return 0;
4970 }
4971 
sign_test(const char * prefix,const uint8_t * sign_key,const uint8_t * m,uint16_t len,const uint8_t * sig)4972 static int sign_test(const char *prefix, const uint8_t *sign_key, const uint8_t *m,
4973 		     uint16_t len, const uint8_t *sig)
4974 {
4975 	uint8_t msg[len + sizeof(uint32_t) + 8];
4976 	uint8_t orig[len + sizeof(uint32_t) + 8];
4977 	uint8_t *out = msg + len;
4978 	int err;
4979 
4980 	LOG_DBG("%s: Sign message with len %u", prefix, len);
4981 
4982 	(void)memset(msg, 0, sizeof(msg));
4983 	memcpy(msg, m, len);
4984 	(void)memset(msg + len, 0, sizeof(uint32_t));
4985 
4986 	memcpy(orig, msg, sizeof(msg));
4987 
4988 	err = smp_sign_buf(sign_key, msg, len);
4989 	if (err) {
4990 		return err;
4991 	}
4992 
4993 	/* Check original message */
4994 	if (!memcmp(msg, orig, len + sizeof(uint32_t))) {
4995 		LOG_DBG("%s: Original message intact", prefix);
4996 	} else {
4997 		LOG_ERR("%s: Original message modified", prefix);
4998 		LOG_DBG("%s: orig %s", prefix, bt_hex(orig, sizeof(orig)));
4999 		LOG_DBG("%s: msg %s", prefix, bt_hex(msg, sizeof(msg)));
5000 		return -1;
5001 	}
5002 
5003 	if (!memcmp(out, sig, 12)) {
5004 		LOG_DBG("%s: Success", prefix);
5005 	} else {
5006 		LOG_ERR("%s: Failed", prefix);
5007 		return -1;
5008 	}
5009 
5010 	return 0;
5011 }
5012 
smp_sign_test(void)5013 static int smp_sign_test(void)
5014 {
5015 	const uint8_t sig1[] = {
5016 		0x00, 0x00, 0x00, 0x00, 0xb3, 0xa8, 0x59, 0x41,
5017 		0x27, 0xeb, 0xc2, 0xc0
5018 	};
5019 	const uint8_t sig2[] = {
5020 		0x00, 0x00, 0x00, 0x00, 0x27, 0x39, 0x74, 0xf4,
5021 		0x39, 0x2a, 0x23, 0x2a
5022 	};
5023 	const uint8_t sig3[] = {
5024 		0x00, 0x00, 0x00, 0x00, 0xb7, 0xca, 0x94, 0xab,
5025 		0x87, 0xc7, 0x82, 0x18
5026 	};
5027 	const uint8_t sig4[] = {
5028 		0x00, 0x00, 0x00, 0x00, 0x44, 0xe1, 0xe6, 0xce,
5029 		0x1d, 0xf5, 0x13, 0x68
5030 	};
5031 	uint8_t key_s[16];
5032 	int err;
5033 
5034 	/* Use the same key as aes-cmac but swap bytes */
5035 	sys_memcpy_swap(key_s, key, 16);
5036 
5037 	err = sign_test("Test sign0", key_s, M, 0, sig1);
5038 	if (err) {
5039 		return err;
5040 	}
5041 
5042 	err = sign_test("Test sign16", key_s, M, 16, sig2);
5043 	if (err) {
5044 		return err;
5045 	}
5046 
5047 	err = sign_test("Test sign40", key_s, M, 40, sig3);
5048 	if (err) {
5049 		return err;
5050 	}
5051 
5052 	err = sign_test("Test sign64", key_s, M, 64, sig4);
5053 	if (err) {
5054 		return err;
5055 	}
5056 
5057 	return 0;
5058 }
5059 
smp_f4_test(void)5060 static int smp_f4_test(void)
5061 {
5062 	uint8_t u[32] = { 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc,
5063 			  0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef,
5064 			  0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
5065 			  0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 };
5066 	uint8_t v[32] = { 0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b,
5067 			  0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59,
5068 			  0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90,
5069 			  0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 };
5070 	uint8_t x[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
5071 			  0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
5072 	uint8_t z = 0x00;
5073 	uint8_t exp[16] = { 0x2d, 0x87, 0x74, 0xa9, 0xbe, 0xa1, 0xed, 0xf1,
5074 			    0x1c, 0xbd, 0xa9, 0x07, 0xf1, 0x16, 0xc9, 0xf2 };
5075 	uint8_t res[16];
5076 	int err;
5077 
5078 	err = bt_crypto_f4(u, v, x, z, res);
5079 	if (err) {
5080 		return err;
5081 	}
5082 
5083 	if (memcmp(res, exp, 16)) {
5084 		return -EINVAL;
5085 	}
5086 
5087 	return 0;
5088 }
5089 
smp_f5_test(void)5090 static int smp_f5_test(void)
5091 {
5092 	uint8_t w[32] = { 0x98, 0xa6, 0xbf, 0x73, 0xf3, 0x34, 0x8d, 0x86,
5093 			  0xf1, 0x66, 0xf8, 0xb4, 0x13, 0x6b, 0x79, 0x99,
5094 			  0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
5095 			  0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
5096 	uint8_t n1[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
5097 			   0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
5098 	uint8_t n2[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
5099 			   0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
5100 	bt_addr_le_t a1 = { .type = 0x00,
5101 			    .a.val = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56 } };
5102 	bt_addr_le_t a2 = { .type = 0x00,
5103 			    .a.val = {0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7 } };
5104 	uint8_t exp_ltk[16] = { 0x38, 0x0a, 0x75, 0x94, 0xb5, 0x22, 0x05,
5105 				0x98, 0x23, 0xcd, 0xd7, 0x69, 0x11, 0x79,
5106 				0x86, 0x69 };
5107 	uint8_t exp_mackey[16] = { 0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f,
5108 				   0xfd, 0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1,
5109 				   0x65, 0x29 };
5110 	uint8_t mackey[16], ltk[16];
5111 	int err;
5112 
5113 	err = bt_crypto_f5(w, n1, n2, &a1, &a2, mackey, ltk);
5114 	if (err) {
5115 		return err;
5116 	}
5117 
5118 	if (memcmp(mackey, exp_mackey, 16) || memcmp(ltk, exp_ltk, 16)) {
5119 		return -EINVAL;
5120 	}
5121 
5122 	return 0;
5123 }
5124 
smp_f6_test(void)5125 static int smp_f6_test(void)
5126 {
5127 	uint8_t w[16] = { 0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f, 0xfd,
5128 			  0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1, 0x65, 0x29 };
5129 	uint8_t n1[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
5130 			   0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
5131 	uint8_t n2[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
5132 			   0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
5133 	uint8_t r[16] = { 0xc8, 0x0f, 0x2d, 0x0c, 0xd2, 0x42, 0xda, 0x08,
5134 			  0x54, 0xbb, 0x53, 0xb4, 0x3b, 0x34, 0xa3, 0x12 };
5135 	uint8_t io_cap[3] = { 0x02, 0x01, 0x01 };
5136 	bt_addr_le_t a1 = { .type = 0x00,
5137 			    .a.val = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56 } };
5138 	bt_addr_le_t a2 = { .type = 0x00,
5139 			    .a.val = {0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7 } };
5140 	uint8_t exp[16] = { 0x61, 0x8f, 0x95, 0xda, 0x09, 0x0b, 0x6c, 0xd2,
5141 			    0xc5, 0xe8, 0xd0, 0x9c, 0x98, 0x73, 0xc4, 0xe3 };
5142 	uint8_t res[16];
5143 	int err;
5144 
5145 	err = bt_crypto_f6(w, n1, n2, r, io_cap, &a1, &a2, res);
5146 	if (err)
5147 		return err;
5148 
5149 	if (memcmp(res, exp, 16))
5150 		return -EINVAL;
5151 
5152 	return 0;
5153 }
5154 
smp_g2_test(void)5155 static int smp_g2_test(void)
5156 {
5157 	uint8_t u[32] = { 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc,
5158 			  0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef,
5159 			  0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
5160 			  0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 };
5161 	uint8_t v[32] = { 0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b,
5162 			  0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59,
5163 			  0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90,
5164 			  0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 };
5165 	uint8_t x[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
5166 			  0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
5167 	uint8_t y[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
5168 			  0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
5169 	uint32_t exp_val = 0x2f9ed5ba % 1000000;
5170 	uint32_t val;
5171 	int err;
5172 
5173 	err = bt_crypto_g2(u, v, x, y, &val);
5174 	if (err) {
5175 		return err;
5176 	}
5177 
5178 	if (val != exp_val) {
5179 		return -EINVAL;
5180 	}
5181 
5182 	return 0;
5183 }
5184 
5185 #if defined(CONFIG_BT_BREDR)
smp_h6_test(void)5186 static int smp_h6_test(void)
5187 {
5188 	uint8_t w[16] = { 0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
5189 			  0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
5190 	uint8_t key_id[4] = { 0x72, 0x62, 0x65, 0x6c };
5191 	uint8_t exp_res[16] = { 0x99, 0x63, 0xb1, 0x80, 0xe2, 0xa9, 0xd3, 0xe8,
5192 				0x1c, 0xc9, 0x6d, 0xe7, 0x02, 0xe1, 0x9a, 0x2d};
5193 	uint8_t res[16];
5194 	int err;
5195 
5196 	err = bt_crypto_h6(w, key_id, res);
5197 	if (err) {
5198 		return err;
5199 	}
5200 
5201 	if (memcmp(res, exp_res, 16)) {
5202 		return -EINVAL;
5203 	}
5204 
5205 	return 0;
5206 }
5207 
smp_h7_test(void)5208 static int smp_h7_test(void)
5209 {
5210 	uint8_t salt[16] = { 0x31, 0x70, 0x6d, 0x74, 0x00, 0x00, 0x00, 0x00,
5211 			     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
5212 	uint8_t w[16] = { 0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
5213 			  0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
5214 	uint8_t exp_res[16] = { 0x11, 0x70, 0xa5, 0x75, 0x2a, 0x8c, 0x99, 0xd2,
5215 				0xec, 0xc0, 0xa3, 0xc6, 0x97, 0x35, 0x17, 0xfb};
5216 	uint8_t res[16];
5217 	int err;
5218 
5219 	err = bt_crypto_h7(salt, w, res);
5220 	if (err) {
5221 		return err;
5222 	}
5223 
5224 	if (memcmp(res, exp_res, 16)) {
5225 		return -EINVAL;
5226 	}
5227 
5228 	return 0;
5229 }
5230 #endif /* CONFIG_BT_BREDR */
5231 
smp_h8_test(void)5232 static int smp_h8_test(void)
5233 {
5234 	uint8_t k[16] = {0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05,
5235 			 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b};
5236 	uint8_t s[16] = {0x15, 0x36, 0xd1, 0x8d, 0xe3, 0xd2, 0x0d, 0xf9,
5237 			 0x9b, 0x70, 0x44, 0xc1, 0x2f, 0x9e, 0xd5, 0xba};
5238 	uint8_t key_id[4] = {0xcc, 0x03, 0x01, 0x48};
5239 
5240 	uint8_t exp_res[16] = {0xe5, 0xe5, 0xbe, 0xba, 0xae, 0x72, 0x28, 0xe7,
5241 			       0x22, 0xa3, 0x89, 0x04, 0xed, 0x35, 0x0f, 0x6d};
5242 	uint8_t res[16];
5243 	int err;
5244 
5245 	err = bt_crypto_h8(k, s, key_id, res);
5246 	if (err) {
5247 		return err;
5248 	}
5249 
5250 	if (memcmp(res, exp_res, 16)) {
5251 		return -EINVAL;
5252 	}
5253 
5254 	return 0;
5255 }
5256 
smp_self_test(void)5257 static int smp_self_test(void)
5258 {
5259 	int err;
5260 
5261 	err = smp_aes_cmac_test();
5262 	if (err) {
5263 		LOG_ERR("SMP AES-CMAC self tests failed");
5264 		return err;
5265 	}
5266 
5267 	err = smp_sign_test();
5268 	if (err) {
5269 		LOG_ERR("SMP signing self tests failed");
5270 		return err;
5271 	}
5272 
5273 	err = smp_f4_test();
5274 	if (err) {
5275 		LOG_ERR("SMP f4 self test failed");
5276 		return err;
5277 	}
5278 
5279 	err = smp_f5_test();
5280 	if (err) {
5281 		LOG_ERR("SMP f5 self test failed");
5282 		return err;
5283 	}
5284 
5285 	err = smp_f6_test();
5286 	if (err) {
5287 		LOG_ERR("SMP f6 self test failed");
5288 		return err;
5289 	}
5290 
5291 	err = smp_g2_test();
5292 	if (err) {
5293 		LOG_ERR("SMP g2 self test failed");
5294 		return err;
5295 	}
5296 
5297 #if defined(CONFIG_BT_BREDR)
5298 	err = smp_h6_test();
5299 	if (err) {
5300 		LOG_ERR("SMP h6 self test failed");
5301 		return err;
5302 	}
5303 
5304 	err = smp_h7_test();
5305 	if (err) {
5306 		LOG_ERR("SMP h7 self test failed");
5307 		return err;
5308 	}
5309 #endif /* CONFIG_BT_BREDR */
5310 	err = smp_h8_test();
5311 	if (err) {
5312 		LOG_ERR("SMP h8 self test failed");
5313 		return err;
5314 	}
5315 
5316 	return 0;
5317 }
5318 #else
smp_self_test(void)5319 static inline int smp_self_test(void)
5320 {
5321 	return 0;
5322 }
5323 #endif
5324 
5325 #if defined(CONFIG_BT_BONDABLE_PER_CONNECTION)
bt_conn_set_bondable(struct bt_conn * conn,bool enable)5326 int bt_conn_set_bondable(struct bt_conn *conn, bool enable)
5327 {
5328 	struct bt_smp *smp;
5329 
5330 	smp = smp_chan_get(conn);
5331 	if (!smp) {
5332 		return -EINVAL;
5333 	}
5334 
5335 	if (atomic_cas(&smp->bondable, BT_SMP_BONDABLE_UNINITIALIZED, (atomic_val_t)enable)) {
5336 		return 0;
5337 	} else {
5338 		return -EALREADY;
5339 	}
5340 }
5341 #endif
5342 
bt_smp_auth_cb_overlay(struct bt_conn * conn,const struct bt_conn_auth_cb * cb)5343 int bt_smp_auth_cb_overlay(struct bt_conn *conn, const struct bt_conn_auth_cb *cb)
5344 {
5345 	struct bt_smp *smp;
5346 
5347 	smp = smp_chan_get(conn);
5348 	if (!smp) {
5349 		return -EINVAL;
5350 	}
5351 
5352 	if (atomic_ptr_cas(&smp->auth_cb, BT_SMP_AUTH_CB_UNINITIALIZED, (atomic_ptr_val_t)cb)) {
5353 		return 0;
5354 	} else {
5355 		return -EALREADY;
5356 	}
5357 }
5358 
5359 #if defined(CONFIG_BT_PASSKEY_KEYPRESS)
smp_send_keypress_notif(struct bt_smp * smp,uint8_t type)5360 static int smp_send_keypress_notif(struct bt_smp *smp, uint8_t type)
5361 {
5362 	struct bt_smp_keypress_notif *req;
5363 	struct net_buf *buf;
5364 
5365 	buf = smp_create_pdu(smp, BT_SMP_KEYPRESS_NOTIFICATION, sizeof(*req));
5366 	if (!buf) {
5367 		return -ENOMEM;
5368 	}
5369 
5370 	req = net_buf_add(buf, sizeof(*req));
5371 	req->type = type;
5372 
5373 	smp_send(smp, buf, NULL, NULL);
5374 
5375 	return 0;
5376 }
5377 #endif
5378 
5379 #if defined(CONFIG_BT_PASSKEY_KEYPRESS)
bt_smp_auth_keypress_notify(struct bt_conn * conn,enum bt_conn_auth_keypress type)5380 int bt_smp_auth_keypress_notify(struct bt_conn *conn, enum bt_conn_auth_keypress type)
5381 {
5382 	struct bt_smp *smp;
5383 
5384 	smp = smp_chan_get(conn);
5385 	if (!smp) {
5386 		return -EINVAL;
5387 	}
5388 
5389 	CHECKIF(!IN_RANGE(type,
5390 			  BT_CONN_AUTH_KEYPRESS_ENTRY_STARTED,
5391 			  BT_CONN_AUTH_KEYPRESS_ENTRY_COMPLETED)) {
5392 		LOG_ERR("Refusing to send unknown event type %u", type);
5393 		return -EINVAL;
5394 	}
5395 
5396 	if (smp->method != PASSKEY_INPUT ||
5397 	    !atomic_test_bit(smp->flags, SMP_FLAG_USER)) {
5398 		LOG_ERR("Refusing to send keypress: Not waiting for passkey input.");
5399 		return -EINVAL;
5400 	}
5401 
5402 	return smp_send_keypress_notif(smp, type);
5403 }
5404 #endif
5405 
bt_smp_auth_passkey_entry(struct bt_conn * conn,unsigned int passkey)5406 int bt_smp_auth_passkey_entry(struct bt_conn *conn, unsigned int passkey)
5407 {
5408 	struct bt_smp *smp;
5409 	uint8_t err;
5410 
5411 	smp = smp_chan_get(conn);
5412 	if (!smp) {
5413 		return -EINVAL;
5414 	}
5415 
5416 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) {
5417 		return -EINVAL;
5418 	}
5419 
5420 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
5421 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
5422 		legacy_passkey_entry(smp, passkey);
5423 		return 0;
5424 	}
5425 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
5426 
5427 	smp->passkey = sys_cpu_to_le32(passkey);
5428 
5429 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
5430 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
5431 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM);
5432 		err = smp_send_pairing_confirm(smp);
5433 		if (err) {
5434 			smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED);
5435 			return 0;
5436 		}
5437 		return 0;
5438 	}
5439 
5440 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
5441 	    atomic_test_bit(smp->flags, SMP_FLAG_CFM_DELAYED)) {
5442 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
5443 		err = smp_send_pairing_confirm(smp);
5444 		if (err) {
5445 			smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED);
5446 			return 0;
5447 		}
5448 	}
5449 
5450 	return 0;
5451 }
5452 
bt_smp_auth_passkey_confirm(struct bt_conn * conn)5453 int bt_smp_auth_passkey_confirm(struct bt_conn *conn)
5454 {
5455 	struct bt_smp *smp;
5456 
5457 	smp = smp_chan_get(conn);
5458 	if (!smp) {
5459 		return -EINVAL;
5460 	}
5461 
5462 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) {
5463 		return -EINVAL;
5464 	}
5465 
5466 	/* wait for DHKey being generated */
5467 	if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) {
5468 		atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
5469 		return 0;
5470 	}
5471 
5472 	/* wait for remote DHKey Check */
5473 	if (atomic_test_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT)) {
5474 		atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
5475 		return 0;
5476 	}
5477 
5478 	if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_SEND)) {
5479 		uint8_t err;
5480 
5481 #if defined(CONFIG_BT_CENTRAL)
5482 		if (smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
5483 			err = compute_and_send_central_dhcheck(smp);
5484 			if (err) {
5485 				smp_error(smp, err);
5486 			}
5487 			return 0;
5488 		}
5489 #endif /* CONFIG_BT_CENTRAL */
5490 
5491 #if defined(CONFIG_BT_PERIPHERAL)
5492 		err = compute_and_check_and_send_periph_dhcheck(smp);
5493 		if (err) {
5494 			smp_error(smp, err);
5495 		}
5496 #endif /* CONFIG_BT_PERIPHERAL */
5497 	}
5498 
5499 	return 0;
5500 }
5501 
5502 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
bt_smp_le_oob_set_tk(struct bt_conn * conn,const uint8_t * tk)5503 int bt_smp_le_oob_set_tk(struct bt_conn *conn, const uint8_t *tk)
5504 {
5505 	struct bt_smp *smp;
5506 
5507 	smp = smp_chan_get(conn);
5508 	if (!smp || !tk) {
5509 		return -EINVAL;
5510 	}
5511 
5512 	LOG_DBG("%s", bt_hex(tk, 16));
5513 
5514 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) {
5515 		return -EINVAL;
5516 	}
5517 
5518 	if (IS_ENABLED(CONFIG_BT_LOG_SNIFFER_INFO)) {
5519 		uint8_t oob[16];
5520 
5521 		sys_memcpy_swap(oob, tk, 16);
5522 		LOG_INF("Legacy OOB data 0x%s", bt_hex(oob, 16));
5523 	}
5524 
5525 	memcpy(smp->tk, tk, 16*sizeof(uint8_t));
5526 
5527 	legacy_user_tk_entry(smp);
5528 
5529 	return 0;
5530 }
5531 #endif /* !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) */
5532 
bt_smp_le_oob_generate_sc_data(struct bt_le_oob_sc_data * le_sc_oob)5533 int bt_smp_le_oob_generate_sc_data(struct bt_le_oob_sc_data *le_sc_oob)
5534 {
5535 	int err;
5536 
5537 	if (!le_sc_supported()) {
5538 		return -ENOTSUP;
5539 	}
5540 
5541 	if (!sc_public_key) {
5542 		err = k_sem_take(&sc_local_pkey_ready, K_FOREVER);
5543 		if (err) {
5544 			return err;
5545 		}
5546 	}
5547 
5548 	if (IS_ENABLED(CONFIG_BT_OOB_DATA_FIXED)) {
5549 		uint8_t rand_num[] = {
5550 			0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
5551 			0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
5552 		};
5553 
5554 		memcpy(le_sc_oob->r, rand_num, sizeof(le_sc_oob->r));
5555 	} else {
5556 		err = bt_rand(le_sc_oob->r, 16);
5557 		if (err) {
5558 			return err;
5559 		}
5560 	}
5561 
5562 	err = bt_crypto_f4(sc_public_key, sc_public_key, le_sc_oob->r, 0,
5563 		     le_sc_oob->c);
5564 	if (err) {
5565 		return err;
5566 	}
5567 
5568 	return 0;
5569 }
5570 
5571 #if !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)
le_sc_oob_data_check(struct bt_smp * smp,bool oobd_local_present,bool oobd_remote_present)5572 static bool le_sc_oob_data_check(struct bt_smp *smp, bool oobd_local_present,
5573 				 bool oobd_remote_present)
5574 {
5575 	bool req_oob_present = le_sc_oob_data_req_check(smp);
5576 	bool rsp_oob_present = le_sc_oob_data_rsp_check(smp);
5577 
5578 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
5579 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
5580 		if ((req_oob_present != oobd_remote_present) &&
5581 		    (rsp_oob_present != oobd_local_present)) {
5582 			return false;
5583 		}
5584 	} else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
5585 		if ((req_oob_present != oobd_local_present) &&
5586 		    (rsp_oob_present != oobd_remote_present)) {
5587 			return false;
5588 		}
5589 	}
5590 
5591 	return true;
5592 }
5593 
le_sc_oob_pairing_continue(struct bt_smp * smp)5594 static int le_sc_oob_pairing_continue(struct bt_smp *smp)
5595 {
5596 	if (smp->oobd_remote) {
5597 		int err;
5598 		uint8_t c[16];
5599 
5600 		err = bt_crypto_f4(smp->pkey, smp->pkey, smp->oobd_remote->r, 0, c);
5601 		if (err) {
5602 			return err;
5603 		}
5604 
5605 		bool match = (memcmp(c, smp->oobd_remote->c, sizeof(c)) == 0);
5606 
5607 		if (!match) {
5608 			smp_error(smp, BT_SMP_ERR_CONFIRM_FAILED);
5609 			return 0;
5610 		}
5611 	}
5612 
5613 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
5614 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
5615 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
5616 	} else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
5617 		atomic_set_bit(smp->allowed_cmds, BT_SMP_DHKEY_CHECK);
5618 		atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT);
5619 	}
5620 
5621 	return smp_send_pairing_random(smp);
5622 }
5623 
bt_smp_le_oob_set_sc_data(struct bt_conn * conn,const struct bt_le_oob_sc_data * oobd_local,const struct bt_le_oob_sc_data * oobd_remote)5624 int bt_smp_le_oob_set_sc_data(struct bt_conn *conn,
5625 			      const struct bt_le_oob_sc_data *oobd_local,
5626 			      const struct bt_le_oob_sc_data *oobd_remote)
5627 {
5628 	struct bt_smp *smp;
5629 
5630 	smp = smp_chan_get(conn);
5631 	if (!smp) {
5632 		return -EINVAL;
5633 	}
5634 
5635 	if (!le_sc_oob_data_check(smp, (oobd_local != NULL),
5636 				  (oobd_remote != NULL))) {
5637 		return -EINVAL;
5638 	}
5639 
5640 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_OOB_PENDING)) {
5641 		return -EINVAL;
5642 	}
5643 
5644 	smp->oobd_local = oobd_local;
5645 	smp->oobd_remote = oobd_remote;
5646 
5647 	return le_sc_oob_pairing_continue(smp);
5648 }
5649 
bt_smp_le_oob_get_sc_data(struct bt_conn * conn,const struct bt_le_oob_sc_data ** oobd_local,const struct bt_le_oob_sc_data ** oobd_remote)5650 int bt_smp_le_oob_get_sc_data(struct bt_conn *conn,
5651 			      const struct bt_le_oob_sc_data **oobd_local,
5652 			      const struct bt_le_oob_sc_data **oobd_remote)
5653 {
5654 	struct bt_smp *smp;
5655 
5656 	smp = smp_chan_get(conn);
5657 	if (!smp) {
5658 		return -EINVAL;
5659 	}
5660 
5661 	if (!smp->oobd_local && !smp->oobd_remote) {
5662 		return -ESRCH;
5663 	}
5664 
5665 	if (oobd_local) {
5666 		*oobd_local = smp->oobd_local;
5667 	}
5668 
5669 	if (oobd_remote) {
5670 		*oobd_remote = smp->oobd_remote;
5671 	}
5672 
5673 	return 0;
5674 }
5675 #endif /* !CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY */
5676 
bt_smp_auth_cancel(struct bt_conn * conn)5677 int bt_smp_auth_cancel(struct bt_conn *conn)
5678 {
5679 	struct bt_smp *smp;
5680 
5681 	smp = smp_chan_get(conn);
5682 	if (!smp) {
5683 		return -EINVAL;
5684 	}
5685 
5686 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) {
5687 		return -EINVAL;
5688 	}
5689 
5690 	LOG_DBG("");
5691 
5692 	switch (smp->method) {
5693 	case PASSKEY_INPUT:
5694 	case PASSKEY_DISPLAY:
5695 		return smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED);
5696 	case PASSKEY_CONFIRM:
5697 		return smp_error(smp, BT_SMP_ERR_CONFIRM_FAILED);
5698 	case LE_SC_OOB:
5699 	case LEGACY_OOB:
5700 		return smp_error(smp, BT_SMP_ERR_OOB_NOT_AVAIL);
5701 	case JUST_WORKS:
5702 		return smp_error(smp, BT_SMP_ERR_UNSPECIFIED);
5703 	default:
5704 		LOG_ERR("Unknown pairing method (%u)", smp->method);
5705 		return 0;
5706 	}
5707 }
5708 
5709 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
bt_smp_auth_pairing_confirm(struct bt_conn * conn)5710 int bt_smp_auth_pairing_confirm(struct bt_conn *conn)
5711 {
5712 	struct bt_smp *smp;
5713 
5714 	smp = smp_chan_get(conn);
5715 	if (!smp) {
5716 		return -EINVAL;
5717 	}
5718 
5719 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) {
5720 		return -EINVAL;
5721 	}
5722 
5723 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
5724 	    conn->role == BT_CONN_ROLE_CENTRAL) {
5725 		if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
5726 			atomic_set_bit(smp->allowed_cmds,
5727 				       BT_SMP_CMD_PAIRING_CONFIRM);
5728 			return legacy_send_pairing_confirm(smp);
5729 		}
5730 
5731 		if (!sc_public_key) {
5732 			atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND);
5733 			return 0;
5734 		}
5735 
5736 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY);
5737 		return sc_send_public_key(smp);
5738 	}
5739 
5740 #if defined(CONFIG_BT_PERIPHERAL)
5741 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
5742 		atomic_set_bit(smp->allowed_cmds,
5743 			       BT_SMP_CMD_PAIRING_CONFIRM);
5744 		return send_pairing_rsp(smp);
5745 	}
5746 
5747 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY);
5748 	if (send_pairing_rsp(smp)) {
5749 		return -EIO;
5750 	}
5751 #endif /* CONFIG_BT_PERIPHERAL */
5752 
5753 	return 0;
5754 }
5755 #else
bt_smp_auth_pairing_confirm(struct bt_conn * conn)5756 int bt_smp_auth_pairing_confirm(struct bt_conn *conn)
5757 {
5758 	/* confirm_pairing will never be called in LE SC only mode */
5759 	return -EINVAL;
5760 }
5761 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
5762 
5763 #if defined(CONFIG_BT_FIXED_PASSKEY)
bt_passkey_set(unsigned int passkey)5764 int bt_passkey_set(unsigned int passkey)
5765 {
5766 	if (passkey == BT_PASSKEY_INVALID) {
5767 		fixed_passkey = BT_PASSKEY_INVALID;
5768 		return 0;
5769 	}
5770 
5771 	if (passkey > 999999) {
5772 		return -EINVAL;
5773 	}
5774 
5775 	fixed_passkey = passkey;
5776 	return 0;
5777 }
5778 #endif /* CONFIG_BT_FIXED_PASSKEY */
5779 
bt_smp_start_security(struct bt_conn * conn)5780 int bt_smp_start_security(struct bt_conn *conn)
5781 {
5782 	switch (conn->role) {
5783 #if defined(CONFIG_BT_CENTRAL)
5784 	case BT_HCI_ROLE_CENTRAL:
5785 	{
5786 		int err;
5787 		struct bt_smp *smp;
5788 
5789 		smp = smp_chan_get(conn);
5790 		if (!smp) {
5791 			return -ENOTCONN;
5792 		}
5793 
5794 		/* pairing is in progress */
5795 		if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
5796 			return -EBUSY;
5797 		}
5798 
5799 		/* Encryption is in progress */
5800 		if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) {
5801 			return -EBUSY;
5802 		}
5803 
5804 		if (!smp_keys_check(conn)) {
5805 			return smp_send_pairing_req(conn);
5806 		}
5807 
5808 		/* LE SC LTK and legacy central LTK are stored in same place */
5809 		err = bt_conn_le_start_encryption(conn,
5810 						  conn->le.keys->ltk.rand,
5811 						  conn->le.keys->ltk.ediv,
5812 						  conn->le.keys->ltk.val,
5813 						  conn->le.keys->enc_size);
5814 		if (err) {
5815 			return err;
5816 		}
5817 
5818 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST);
5819 		atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
5820 		return 0;
5821 	}
5822 #endif /* CONFIG_BT_CENTRAL && CONFIG_BT_SMP */
5823 #if defined(CONFIG_BT_PERIPHERAL)
5824 	case BT_HCI_ROLE_PERIPHERAL:
5825 		return smp_send_security_req(conn);
5826 #endif /* CONFIG_BT_PERIPHERAL && CONFIG_BT_SMP */
5827 	default:
5828 		return -EINVAL;
5829 	}
5830 }
5831 
bt_smp_update_keys(struct bt_conn * conn)5832 void bt_smp_update_keys(struct bt_conn *conn)
5833 {
5834 	struct bt_smp *smp;
5835 
5836 	smp = smp_chan_get(conn);
5837 	if (!smp) {
5838 		return;
5839 	}
5840 
5841 	if (!atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
5842 		return;
5843 	}
5844 
5845 	/*
5846 	 * If link was successfully encrypted cleanup old keys as from now on
5847 	 * only keys distributed in this pairing or LTK from LE SC will be used.
5848 	 */
5849 	if (conn->le.keys) {
5850 		bt_keys_clear(conn->le.keys);
5851 	}
5852 
5853 	conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst);
5854 	if (!conn->le.keys) {
5855 		LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst));
5856 		smp_error(smp, BT_SMP_ERR_UNSPECIFIED);
5857 		return;
5858 	}
5859 
5860 	/* mark keys as debug */
5861 	if (atomic_test_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY)) {
5862 		conn->le.keys->flags |= BT_KEYS_DEBUG;
5863 	}
5864 
5865 	/*
5866 	 * store key type deducted from pairing method used
5867 	 * it is important to store it since type is used to determine
5868 	 * security level upon encryption
5869 	 */
5870 	switch (smp->method) {
5871 	case LE_SC_OOB:
5872 	case LEGACY_OOB:
5873 		conn->le.keys->flags |= BT_KEYS_OOB;
5874 		/* fallthrough */
5875 	case PASSKEY_DISPLAY:
5876 	case PASSKEY_INPUT:
5877 	case PASSKEY_CONFIRM:
5878 		conn->le.keys->flags |= BT_KEYS_AUTHENTICATED;
5879 		break;
5880 	case JUST_WORKS:
5881 	default:
5882 		/* unauthenticated key, clear it */
5883 		conn->le.keys->flags &= ~BT_KEYS_OOB;
5884 		conn->le.keys->flags &= ~BT_KEYS_AUTHENTICATED;
5885 		break;
5886 	}
5887 
5888 	conn->le.keys->enc_size = get_encryption_key_size(smp);
5889 
5890 	/*
5891 	 * Store LTK if LE SC is used, this is safe since LE SC is mutually
5892 	 * exclusive with legacy pairing. Other keys are added on keys
5893 	 * distribution.
5894 	 */
5895 	if (atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
5896 		conn->le.keys->flags |= BT_KEYS_SC;
5897 
5898 		if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
5899 			bt_keys_add_type(conn->le.keys, BT_KEYS_LTK_P256);
5900 			memcpy(conn->le.keys->ltk.val, smp->tk,
5901 			       sizeof(conn->le.keys->ltk.val));
5902 			(void)memset(conn->le.keys->ltk.rand, 0,
5903 				     sizeof(conn->le.keys->ltk.rand));
5904 			(void)memset(conn->le.keys->ltk.ediv, 0,
5905 				     sizeof(conn->le.keys->ltk.ediv));
5906 		} else if (IS_ENABLED(CONFIG_BT_LOG_SNIFFER_INFO)) {
5907 			uint8_t ltk[16];
5908 
5909 			sys_memcpy_swap(ltk, smp->tk, conn->le.keys->enc_size);
5910 			LOG_INF("SC LTK: 0x%s (No bonding)", bt_hex(ltk, conn->le.keys->enc_size));
5911 		}
5912 	} else {
5913 		conn->le.keys->flags &= ~BT_KEYS_SC;
5914 	}
5915 }
5916 
bt_smp_accept(struct bt_conn * conn,struct bt_l2cap_chan ** chan)5917 static int bt_smp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan)
5918 {
5919 	int i;
5920 	static const struct bt_l2cap_chan_ops ops = {
5921 		.connected = bt_smp_connected,
5922 		.disconnected = bt_smp_disconnected,
5923 		.encrypt_change = bt_smp_encrypt_change,
5924 		.recv = bt_smp_recv,
5925 	};
5926 
5927 	LOG_DBG("conn %p handle %u", conn, conn->handle);
5928 
5929 	for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) {
5930 		struct bt_smp *smp = &bt_smp_pool[i];
5931 
5932 		if (smp->chan.chan.conn) {
5933 			continue;
5934 		}
5935 
5936 		smp->chan.chan.ops = &ops;
5937 
5938 		*chan = &smp->chan.chan;
5939 
5940 		return 0;
5941 	}
5942 
5943 	LOG_ERR("No available SMP context for conn %p", conn);
5944 
5945 	return -ENOMEM;
5946 }
5947 
5948 BT_L2CAP_CHANNEL_DEFINE(smp_fixed_chan, BT_L2CAP_CID_SMP, bt_smp_accept, NULL);
5949 #if defined(CONFIG_BT_BREDR)
5950 BT_L2CAP_CHANNEL_DEFINE(smp_br_fixed_chan, BT_L2CAP_CID_BR_SMP,
5951 			bt_smp_br_accept, NULL);
5952 #endif /* CONFIG_BT_BREDR */
5953 
bt_smp_init(void)5954 int bt_smp_init(void)
5955 {
5956 	static struct bt_pub_key_cb pub_key_cb = {
5957 		.func           = bt_smp_pkey_ready,
5958 	};
5959 
5960 	sc_supported = le_sc_supported();
5961 	if (IS_ENABLED(CONFIG_BT_SMP_SC_PAIR_ONLY) && !sc_supported) {
5962 		LOG_ERR("SC Pair Only Mode selected but LE SC not supported");
5963 		return -ENOENT;
5964 	}
5965 
5966 	if (IS_ENABLED(CONFIG_BT_SMP_USB_HCI_CTLR_WORKAROUND)) {
5967 		LOG_WRN("BT_SMP_USB_HCI_CTLR_WORKAROUND is enabled, which "
5968 			"exposes a security vulnerability!");
5969 	}
5970 
5971 	LOG_DBG("LE SC %s", sc_supported ? "enabled" : "disabled");
5972 
5973 	if (!IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)) {
5974 		bt_pub_key_gen(&pub_key_cb);
5975 	}
5976 
5977 	return smp_self_test();
5978 }
5979