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)
xor_128(const uint8_t p[16],const uint8_t q[16],uint8_t r[16])1832 static void xor_128(const uint8_t p[16], const uint8_t q[16], uint8_t r[16])
1833 {
1834 	size_t len = 16;
1835 
1836 	while (len--) {
1837 		*r++ = *p++ ^ *q++;
1838 	}
1839 }
1840 
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])1841 static int smp_c1(const uint8_t k[16], const uint8_t r[16],
1842 		  const uint8_t preq[7], const uint8_t pres[7],
1843 		  const bt_addr_le_t *ia, const bt_addr_le_t *ra,
1844 		  uint8_t enc_data[16])
1845 {
1846 	uint8_t p1[16], p2[16];
1847 	int err;
1848 
1849 	LOG_DBG("k %s", bt_hex(k, 16));
1850 	LOG_DBG("r %s", bt_hex(r, 16));
1851 	LOG_DBG("ia %s", bt_addr_le_str(ia));
1852 	LOG_DBG("ra %s", bt_addr_le_str(ra));
1853 	LOG_DBG("preq %s", bt_hex(preq, 7));
1854 	LOG_DBG("pres %s", bt_hex(pres, 7));
1855 
1856 	/* pres, preq, rat and iat are concatenated to generate p1 */
1857 	p1[0] = ia->type;
1858 	p1[1] = ra->type;
1859 	memcpy(p1 + 2, preq, 7);
1860 	memcpy(p1 + 9, pres, 7);
1861 
1862 	LOG_DBG("p1 %s", bt_hex(p1, 16));
1863 
1864 	/* c1 = e(k, e(k, r XOR p1) XOR p2) */
1865 
1866 	/* Using enc_data as temporary output buffer */
1867 	xor_128(r, p1, enc_data);
1868 
1869 	err = bt_encrypt_le(k, enc_data, enc_data);
1870 	if (err) {
1871 		return err;
1872 	}
1873 
1874 	/* ra is concatenated with ia and padding to generate p2 */
1875 	memcpy(p2, ra->a.val, 6);
1876 	memcpy(p2 + 6, ia->a.val, 6);
1877 	(void)memset(p2 + 12, 0, 4);
1878 
1879 	LOG_DBG("p2 %s", bt_hex(p2, 16));
1880 
1881 	xor_128(enc_data, p2, enc_data);
1882 
1883 	return bt_encrypt_le(k, enc_data, enc_data);
1884 }
1885 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
1886 
smp_send_pairing_confirm(struct bt_smp * smp)1887 static uint8_t smp_send_pairing_confirm(struct bt_smp *smp)
1888 {
1889 	struct bt_smp_pairing_confirm *req;
1890 	struct net_buf *buf;
1891 	uint8_t r;
1892 
1893 	switch (smp->method) {
1894 	case PASSKEY_CONFIRM:
1895 	case JUST_WORKS:
1896 		r = 0U;
1897 		break;
1898 	case PASSKEY_DISPLAY:
1899 	case PASSKEY_INPUT:
1900 		/*
1901 		 * In the Passkey Entry protocol, the most significant
1902 		 * bit of Z is set equal to one and the least
1903 		 * significant bit is made up from one bit of the
1904 		 * passkey e.g. if the passkey bit is 1, then Z = 0x81
1905 		 * and if the passkey bit is 0, then Z = 0x80.
1906 		 */
1907 		r = (smp->passkey >> smp->passkey_round) & 0x01;
1908 		r |= 0x80;
1909 		break;
1910 	default:
1911 		LOG_ERR("Unknown pairing method (%u)", smp->method);
1912 		return BT_SMP_ERR_UNSPECIFIED;
1913 	}
1914 
1915 	buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_CONFIRM, sizeof(*req));
1916 	if (!buf) {
1917 		return BT_SMP_ERR_UNSPECIFIED;
1918 	}
1919 
1920 	req = net_buf_add(buf, sizeof(*req));
1921 
1922 	if (bt_crypto_f4(sc_public_key, smp->pkey, smp->prnd, r, req->val)) {
1923 		net_buf_unref(buf);
1924 		return BT_SMP_ERR_UNSPECIFIED;
1925 	}
1926 
1927 	smp_send(smp, buf, NULL, NULL);
1928 
1929 	atomic_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED);
1930 
1931 	return 0;
1932 }
1933 
1934 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
smp_ident_sent(struct bt_conn * conn,void * user_data,int err)1935 static void smp_ident_sent(struct bt_conn *conn, void *user_data, int err)
1936 {
1937 	if (!err) {
1938 		smp_check_complete(conn, BT_SMP_DIST_ENC_KEY);
1939 	}
1940 }
1941 
legacy_distribute_keys(struct bt_smp * smp)1942 static void legacy_distribute_keys(struct bt_smp *smp)
1943 {
1944 	struct bt_conn *conn = smp->chan.chan.conn;
1945 	struct bt_keys *keys = conn->le.keys;
1946 
1947 	if (smp->local_dist & BT_SMP_DIST_ENC_KEY) {
1948 		struct bt_smp_encrypt_info *info;
1949 		struct bt_smp_central_ident *ident;
1950 		struct net_buf *buf;
1951 		/* Use struct to get randomness in single call to bt_rand */
1952 		struct {
1953 			uint8_t key[16];
1954 			uint8_t rand[8];
1955 			uint8_t ediv[2];
1956 		} rand;
1957 
1958 		if (bt_rand((void *)&rand, sizeof(rand))) {
1959 			LOG_ERR("Unable to get random bytes");
1960 			return;
1961 		}
1962 
1963 		buf = smp_create_pdu(smp, BT_SMP_CMD_ENCRYPT_INFO,
1964 				     sizeof(*info));
1965 		if (!buf) {
1966 			LOG_ERR("Unable to allocate Encrypt Info buffer");
1967 			return;
1968 		}
1969 
1970 		info = net_buf_add(buf, sizeof(*info));
1971 
1972 		/* distributed only enc_size bytes of key */
1973 		memcpy(info->ltk, rand.key, keys->enc_size);
1974 		if (keys->enc_size < sizeof(info->ltk)) {
1975 			(void)memset(info->ltk + keys->enc_size, 0,
1976 				     sizeof(info->ltk) - keys->enc_size);
1977 		}
1978 
1979 		smp_send(smp, buf, NULL, NULL);
1980 
1981 		buf = smp_create_pdu(smp, BT_SMP_CMD_CENTRAL_IDENT,
1982 				     sizeof(*ident));
1983 		if (!buf) {
1984 			LOG_ERR("Unable to allocate Central Ident buffer");
1985 			return;
1986 		}
1987 
1988 		ident = net_buf_add(buf, sizeof(*ident));
1989 		memcpy(ident->rand, rand.rand, sizeof(ident->rand));
1990 		memcpy(ident->ediv, rand.ediv, sizeof(ident->ediv));
1991 
1992 		smp_send(smp, buf, smp_ident_sent, NULL);
1993 
1994 		if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
1995 			bt_keys_add_type(keys, BT_KEYS_PERIPH_LTK);
1996 
1997 			memcpy(keys->periph_ltk.val, rand.key,
1998 			       sizeof(keys->periph_ltk.val));
1999 			memcpy(keys->periph_ltk.rand, rand.rand,
2000 			       sizeof(keys->periph_ltk.rand));
2001 			memcpy(keys->periph_ltk.ediv, rand.ediv,
2002 			       sizeof(keys->periph_ltk.ediv));
2003 		}
2004 	}
2005 }
2006 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
2007 
bt_smp_distribute_keys(struct bt_smp * smp)2008 static uint8_t bt_smp_distribute_keys(struct bt_smp *smp)
2009 {
2010 	struct bt_conn *conn = smp->chan.chan.conn;
2011 	struct bt_keys *keys = conn->le.keys;
2012 
2013 	if (!keys) {
2014 		LOG_ERR("No keys space for %s", bt_addr_le_str(&conn->le.dst));
2015 		return BT_SMP_ERR_UNSPECIFIED;
2016 	}
2017 
2018 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
2019 	/* Distribute legacy pairing specific keys */
2020 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
2021 		legacy_distribute_keys(smp);
2022 	}
2023 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
2024 
2025 #if defined(CONFIG_BT_PRIVACY)
2026 	if (smp->local_dist & BT_SMP_DIST_ID_KEY) {
2027 		struct bt_smp_ident_info *id_info;
2028 		struct bt_smp_ident_addr_info *id_addr_info;
2029 		struct net_buf *buf;
2030 
2031 		buf = smp_create_pdu(smp, BT_SMP_CMD_IDENT_INFO,
2032 				     sizeof(*id_info));
2033 		if (!buf) {
2034 			LOG_ERR("Unable to allocate Ident Info buffer");
2035 			return BT_SMP_ERR_UNSPECIFIED;
2036 		}
2037 
2038 		id_info = net_buf_add(buf, sizeof(*id_info));
2039 		memcpy(id_info->irk, bt_dev.irk[conn->id], 16);
2040 
2041 		smp_send(smp, buf, NULL, NULL);
2042 
2043 		buf = smp_create_pdu(smp, BT_SMP_CMD_IDENT_ADDR_INFO,
2044 				     sizeof(*id_addr_info));
2045 		if (!buf) {
2046 			LOG_ERR("Unable to allocate Ident Addr Info buffer");
2047 			return BT_SMP_ERR_UNSPECIFIED;
2048 		}
2049 
2050 		id_addr_info = net_buf_add(buf, sizeof(*id_addr_info));
2051 		bt_addr_le_copy(&id_addr_info->addr, &bt_dev.id_addr[conn->id]);
2052 
2053 		smp_send(smp, buf, smp_id_sent, NULL);
2054 	}
2055 #endif /* CONFIG_BT_PRIVACY */
2056 
2057 #if defined(CONFIG_BT_SIGNING)
2058 	if (smp->local_dist & BT_SMP_DIST_SIGN) {
2059 		struct bt_smp_signing_info *info;
2060 		struct net_buf *buf;
2061 
2062 		buf = smp_create_pdu(smp, BT_SMP_CMD_SIGNING_INFO,
2063 				     sizeof(*info));
2064 		if (!buf) {
2065 			LOG_ERR("Unable to allocate Signing Info buffer");
2066 			return BT_SMP_ERR_UNSPECIFIED;
2067 		}
2068 
2069 		info = net_buf_add(buf, sizeof(*info));
2070 
2071 		if (bt_rand(info->csrk, sizeof(info->csrk))) {
2072 			return BT_SMP_ERR_UNSPECIFIED;
2073 		}
2074 
2075 		if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
2076 			bt_keys_add_type(keys, BT_KEYS_LOCAL_CSRK);
2077 			memcpy(keys->local_csrk.val, info->csrk, 16);
2078 			keys->local_csrk.cnt = 0U;
2079 		}
2080 
2081 		smp_send(smp, buf, smp_sign_info_sent, NULL);
2082 	}
2083 #endif /* CONFIG_BT_SIGNING */
2084 
2085 	return 0;
2086 }
2087 
2088 #if defined(CONFIG_BT_PERIPHERAL)
send_pairing_rsp(struct bt_smp * smp)2089 static uint8_t send_pairing_rsp(struct bt_smp *smp)
2090 {
2091 	struct bt_smp_pairing *rsp;
2092 	struct net_buf *rsp_buf;
2093 
2094 	rsp_buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_RSP, sizeof(*rsp));
2095 	if (!rsp_buf) {
2096 		return BT_SMP_ERR_UNSPECIFIED;
2097 	}
2098 
2099 	rsp = net_buf_add(rsp_buf, sizeof(*rsp));
2100 	memcpy(rsp, smp->prsp + 1, sizeof(*rsp));
2101 
2102 	smp_send(smp, rsp_buf, NULL, NULL);
2103 
2104 	return 0;
2105 }
2106 #endif /* CONFIG_BT_PERIPHERAL */
2107 
smp_pairing_accept_query(struct bt_smp * smp,struct bt_smp_pairing * pairing)2108 static uint8_t smp_pairing_accept_query(struct bt_smp *smp, struct bt_smp_pairing *pairing)
2109 {
2110 #if defined(CONFIG_BT_SMP_APP_PAIRING_ACCEPT)
2111 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
2112 	struct bt_conn *conn = smp->chan.chan.conn;
2113 
2114 	if (smp_auth_cb && smp_auth_cb->pairing_accept) {
2115 		const struct bt_conn_pairing_feat feat = {
2116 			.io_capability = pairing->io_capability,
2117 			.oob_data_flag = pairing->oob_flag,
2118 			.auth_req = pairing->auth_req,
2119 			.max_enc_key_size = pairing->max_key_size,
2120 			.init_key_dist = pairing->init_key_dist,
2121 			.resp_key_dist = pairing->resp_key_dist
2122 		};
2123 
2124 		return smp_err_get(smp_auth_cb->pairing_accept(conn, &feat));
2125 	}
2126 #endif /* CONFIG_BT_SMP_APP_PAIRING_ACCEPT */
2127 	return 0;
2128 }
2129 
2130 #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])2131 static int smp_s1(const uint8_t k[16], const uint8_t r1[16],
2132 		  const uint8_t r2[16], uint8_t out[16])
2133 {
2134 	/* The most significant 64-bits of r1 are discarded to generate
2135 	 * r1' and the most significant 64-bits of r2 are discarded to
2136 	 * generate r2'.
2137 	 * r1' is concatenated with r2' to generate r' which is used as
2138 	 * the 128-bit input parameter plaintextData to security function e:
2139 	 *
2140 	 *    r' = r1' || r2'
2141 	 */
2142 	memcpy(out, r2, 8);
2143 	memcpy(out + 8, r1, 8);
2144 
2145 	/* s1(k, r1 , r2) = e(k, r') */
2146 	return bt_encrypt_le(k, out, out);
2147 }
2148 
legacy_get_pair_method(struct bt_smp * smp,uint8_t remote_io)2149 static uint8_t legacy_get_pair_method(struct bt_smp *smp, uint8_t remote_io)
2150 {
2151 	struct bt_smp_pairing *req, *rsp;
2152 	uint8_t method;
2153 
2154 	if (remote_io > BT_SMP_IO_KEYBOARD_DISPLAY) {
2155 		return JUST_WORKS;
2156 	}
2157 
2158 	req = (struct bt_smp_pairing *)&smp->preq[1];
2159 	rsp = (struct bt_smp_pairing *)&smp->prsp[1];
2160 
2161 	/* if both sides have OOB data use OOB */
2162 	if ((req->oob_flag & rsp->oob_flag) & BT_SMP_OOB_DATA_MASK) {
2163 		return LEGACY_OOB;
2164 	}
2165 
2166 	/* if none side requires MITM use JustWorks */
2167 	if (!((req->auth_req | rsp->auth_req) & BT_SMP_AUTH_MITM)) {
2168 		return JUST_WORKS;
2169 	}
2170 
2171 	method = gen_method_legacy[remote_io][get_io_capa(smp)];
2172 
2173 	/* if both sides have KeyboardDisplay capabilities, initiator displays
2174 	 * and responder inputs
2175 	 */
2176 	if (method == PASSKEY_ROLE) {
2177 		if (smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
2178 			method = PASSKEY_DISPLAY;
2179 		} else {
2180 			method = PASSKEY_INPUT;
2181 		}
2182 	}
2183 
2184 	return method;
2185 }
2186 
legacy_request_tk(struct bt_smp * smp)2187 static uint8_t legacy_request_tk(struct bt_smp *smp)
2188 {
2189 	struct bt_conn *conn = smp->chan.chan.conn;
2190 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
2191 	struct bt_keys *keys;
2192 	uint32_t passkey;
2193 
2194 	/*
2195 	 * Fail if we have keys that are stronger than keys that will be
2196 	 * distributed in new pairing. This is to avoid replacing authenticated
2197 	 * keys with unauthenticated ones.
2198 	  */
2199 	keys = bt_keys_find_addr(conn->id, &conn->le.dst);
2200 	if (keys && (keys->flags & BT_KEYS_AUTHENTICATED) &&
2201 	    smp->method == JUST_WORKS) {
2202 		LOG_ERR("JustWorks failed, authenticated keys present");
2203 		return BT_SMP_ERR_UNSPECIFIED;
2204 	}
2205 
2206 	switch (smp->method) {
2207 	case LEGACY_OOB:
2208 		if (smp_auth_cb && smp_auth_cb->oob_data_request) {
2209 			struct bt_conn_oob_info info = {
2210 				.type = BT_CONN_OOB_LE_LEGACY,
2211 			};
2212 
2213 			atomic_set_bit(smp->flags, SMP_FLAG_USER);
2214 			smp_auth_cb->oob_data_request(smp->chan.chan.conn, &info);
2215 		} else {
2216 			return BT_SMP_ERR_OOB_NOT_AVAIL;
2217 		}
2218 
2219 		break;
2220 	case PASSKEY_DISPLAY:
2221 		if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) &&
2222 		    fixed_passkey != BT_PASSKEY_INVALID) {
2223 			passkey = fixed_passkey;
2224 		} else  {
2225 			if (bt_rand(&passkey, sizeof(passkey))) {
2226 				return BT_SMP_ERR_UNSPECIFIED;
2227 			}
2228 
2229 			passkey %= 1000000;
2230 		}
2231 
2232 		if (IS_ENABLED(CONFIG_BT_LOG_SNIFFER_INFO)) {
2233 			LOG_INF("Legacy passkey %u", passkey);
2234 		}
2235 
2236 		if (smp_auth_cb && smp_auth_cb->passkey_display) {
2237 			atomic_set_bit(smp->flags, SMP_FLAG_DISPLAY);
2238 			smp_auth_cb->passkey_display(conn, passkey);
2239 		}
2240 
2241 		sys_put_le32(passkey, smp->tk);
2242 
2243 		break;
2244 	case PASSKEY_INPUT:
2245 		atomic_set_bit(smp->flags, SMP_FLAG_USER);
2246 		smp_auth_cb->passkey_entry(conn);
2247 		break;
2248 	case JUST_WORKS:
2249 		break;
2250 	default:
2251 		LOG_ERR("Unknown pairing method (%u)", smp->method);
2252 		return BT_SMP_ERR_UNSPECIFIED;
2253 	}
2254 
2255 	return 0;
2256 }
2257 
legacy_send_pairing_confirm(struct bt_smp * smp)2258 static uint8_t legacy_send_pairing_confirm(struct bt_smp *smp)
2259 {
2260 	struct bt_conn *conn = smp->chan.chan.conn;
2261 	struct bt_smp_pairing_confirm *req;
2262 	struct net_buf *buf;
2263 
2264 	buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_CONFIRM, sizeof(*req));
2265 	if (!buf) {
2266 		return BT_SMP_ERR_UNSPECIFIED;
2267 	}
2268 
2269 	req = net_buf_add(buf, sizeof(*req));
2270 
2271 	if (smp_c1(smp->tk, smp->prnd, smp->preq, smp->prsp,
2272 		   &conn->le.init_addr, &conn->le.resp_addr, req->val)) {
2273 		net_buf_unref(buf);
2274 		return BT_SMP_ERR_UNSPECIFIED;
2275 	}
2276 
2277 	smp_send(smp, buf, NULL, NULL);
2278 
2279 	atomic_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED);
2280 
2281 	return 0;
2282 }
2283 
2284 #if defined(CONFIG_BT_PERIPHERAL)
legacy_pairing_req(struct bt_smp * smp)2285 static uint8_t legacy_pairing_req(struct bt_smp *smp)
2286 {
2287 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
2288 	uint8_t ret;
2289 
2290 	LOG_DBG("");
2291 
2292 	ret = legacy_request_tk(smp);
2293 	if (ret) {
2294 		return ret;
2295 	}
2296 
2297 	/* ask for consent if pairing is not due to sending SecReq*/
2298 	if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) &&
2299 	    !atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) &&
2300 	    smp_auth_cb && smp_auth_cb->pairing_confirm) {
2301 		atomic_set_bit(smp->flags, SMP_FLAG_USER);
2302 		smp_auth_cb->pairing_confirm(smp->chan.chan.conn);
2303 		return 0;
2304 	}
2305 
2306 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM);
2307 	atomic_set_bit(smp->allowed_cmds, BT_SMP_KEYPRESS_NOTIFICATION);
2308 	return send_pairing_rsp(smp);
2309 }
2310 #endif /* CONFIG_BT_PERIPHERAL */
2311 
legacy_pairing_random(struct bt_smp * smp)2312 static uint8_t legacy_pairing_random(struct bt_smp *smp)
2313 {
2314 	struct bt_conn *conn = smp->chan.chan.conn;
2315 	uint8_t tmp[16];
2316 	int err;
2317 
2318 	LOG_DBG("");
2319 
2320 	/* calculate confirmation */
2321 	err = smp_c1(smp->tk, smp->rrnd, smp->preq, smp->prsp,
2322 		     &conn->le.init_addr, &conn->le.resp_addr, tmp);
2323 	if (err) {
2324 		return BT_SMP_ERR_UNSPECIFIED;
2325 	}
2326 
2327 	LOG_DBG("pcnf %s", bt_hex(smp->pcnf, 16));
2328 	LOG_DBG("cfm %s", bt_hex(tmp, 16));
2329 
2330 	if (memcmp(smp->pcnf, tmp, sizeof(smp->pcnf))) {
2331 		return BT_SMP_ERR_CONFIRM_FAILED;
2332 	}
2333 
2334 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
2335 	    conn->role == BT_HCI_ROLE_CENTRAL) {
2336 		uint8_t ediv[2], rand[8];
2337 
2338 		/* No need to store central STK */
2339 		err = smp_s1(smp->tk, smp->rrnd, smp->prnd, tmp);
2340 		if (err) {
2341 			return BT_SMP_ERR_UNSPECIFIED;
2342 		}
2343 
2344 		/* Rand and EDiv are 0 for the STK */
2345 		(void)memset(ediv, 0, sizeof(ediv));
2346 		(void)memset(rand, 0, sizeof(rand));
2347 		if (bt_conn_le_start_encryption(conn, rand, ediv, tmp,
2348 						get_encryption_key_size(smp))) {
2349 			LOG_ERR("Failed to start encryption");
2350 			return BT_SMP_ERR_UNSPECIFIED;
2351 		}
2352 
2353 		atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
2354 
2355 		if (IS_ENABLED(CONFIG_BT_SMP_USB_HCI_CTLR_WORKAROUND)) {
2356 			if (smp->remote_dist & BT_SMP_DIST_ENC_KEY) {
2357 				atomic_set_bit(smp->allowed_cmds,
2358 					       BT_SMP_CMD_ENCRYPT_INFO);
2359 			} else if (smp->remote_dist & BT_SMP_DIST_ID_KEY) {
2360 				atomic_set_bit(smp->allowed_cmds,
2361 					       BT_SMP_CMD_IDENT_INFO);
2362 			} else if (smp->remote_dist & BT_SMP_DIST_SIGN) {
2363 				atomic_set_bit(smp->allowed_cmds,
2364 					       BT_SMP_CMD_SIGNING_INFO);
2365 			}
2366 		}
2367 
2368 		return 0;
2369 	}
2370 
2371 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
2372 		err = smp_s1(smp->tk, smp->prnd, smp->rrnd, tmp);
2373 		if (err) {
2374 			LOG_ERR("Calculate STK failed");
2375 			return BT_SMP_ERR_UNSPECIFIED;
2376 		}
2377 
2378 		memcpy(smp->tk, tmp, sizeof(smp->tk));
2379 		LOG_DBG("generated STK %s", bt_hex(smp->tk, 16));
2380 
2381 		atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
2382 
2383 		return smp_send_pairing_random(smp);
2384 	}
2385 
2386 	return 0;
2387 }
2388 
legacy_pairing_confirm(struct bt_smp * smp)2389 static uint8_t legacy_pairing_confirm(struct bt_smp *smp)
2390 {
2391 	LOG_DBG("");
2392 
2393 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
2394 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
2395 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM);
2396 		return legacy_send_pairing_confirm(smp);
2397 	}
2398 
2399 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
2400 		if (!atomic_test_bit(smp->flags, SMP_FLAG_USER)) {
2401 			atomic_set_bit(smp->allowed_cmds,
2402 				       BT_SMP_CMD_PAIRING_RANDOM);
2403 			return legacy_send_pairing_confirm(smp);
2404 		}
2405 
2406 		atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED);
2407 	}
2408 
2409 	return 0;
2410 }
2411 
legacy_user_tk_entry(struct bt_smp * smp)2412 static void legacy_user_tk_entry(struct bt_smp *smp)
2413 {
2414 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED)) {
2415 		return;
2416 	}
2417 
2418 	/* if confirm failed ie. due to invalid passkey, cancel pairing */
2419 	if (legacy_pairing_confirm(smp)) {
2420 		smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED);
2421 		return;
2422 	}
2423 
2424 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
2425 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
2426 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM);
2427 		return;
2428 	}
2429 
2430 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
2431 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
2432 	}
2433 }
2434 
legacy_passkey_entry(struct bt_smp * smp,unsigned int passkey)2435 static void legacy_passkey_entry(struct bt_smp *smp, unsigned int passkey)
2436 {
2437 	passkey = sys_cpu_to_le32(passkey);
2438 	memcpy(smp->tk, &passkey, sizeof(passkey));
2439 
2440 	legacy_user_tk_entry(smp);
2441 }
2442 
smp_encrypt_info(struct bt_smp * smp,struct net_buf * buf)2443 static uint8_t smp_encrypt_info(struct bt_smp *smp, struct net_buf *buf)
2444 {
2445 	LOG_DBG("");
2446 
2447 	if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
2448 		struct bt_smp_encrypt_info *req = (void *)buf->data;
2449 		struct bt_conn *conn = smp->chan.chan.conn;
2450 		struct bt_keys *keys;
2451 
2452 		keys = bt_keys_get_type(BT_KEYS_LTK, conn->id, &conn->le.dst);
2453 		if (!keys) {
2454 			LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst));
2455 			return BT_SMP_ERR_UNSPECIFIED;
2456 		}
2457 
2458 		memcpy(keys->ltk.val, req->ltk, 16);
2459 	}
2460 
2461 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_CENTRAL_IDENT);
2462 
2463 	return 0;
2464 }
2465 
smp_central_ident(struct bt_smp * smp,struct net_buf * buf)2466 static uint8_t smp_central_ident(struct bt_smp *smp, struct net_buf *buf)
2467 {
2468 	struct bt_conn *conn = smp->chan.chan.conn;
2469 	uint8_t err;
2470 
2471 	LOG_DBG("");
2472 
2473 	if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
2474 		struct bt_smp_central_ident *req = (void *)buf->data;
2475 		struct bt_keys *keys;
2476 
2477 		keys = bt_keys_get_type(BT_KEYS_LTK, conn->id, &conn->le.dst);
2478 		if (!keys) {
2479 			LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst));
2480 			return BT_SMP_ERR_UNSPECIFIED;
2481 		}
2482 
2483 		memcpy(keys->ltk.ediv, req->ediv, sizeof(keys->ltk.ediv));
2484 		memcpy(keys->ltk.rand, req->rand, sizeof(req->rand));
2485 	}
2486 
2487 	smp->remote_dist &= ~BT_SMP_DIST_ENC_KEY;
2488 
2489 	if (smp->remote_dist & BT_SMP_DIST_ID_KEY) {
2490 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO);
2491 	} else if (smp->remote_dist & BT_SMP_DIST_SIGN) {
2492 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO);
2493 	}
2494 
2495 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
2496 	    conn->role == BT_HCI_ROLE_CENTRAL && !smp->remote_dist) {
2497 		err = bt_smp_distribute_keys(smp);
2498 		if (err) {
2499 			return err;
2500 		}
2501 	}
2502 
2503 	/* if all keys were distributed, pairing is done */
2504 	if (!smp->local_dist && !smp->remote_dist) {
2505 		smp_pairing_complete(smp, 0);
2506 	}
2507 
2508 	return 0;
2509 }
2510 
2511 #if defined(CONFIG_BT_CENTRAL)
legacy_pairing_rsp(struct bt_smp * smp)2512 static uint8_t legacy_pairing_rsp(struct bt_smp *smp)
2513 {
2514 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
2515 	uint8_t ret;
2516 
2517 	LOG_DBG("");
2518 
2519 	ret = legacy_request_tk(smp);
2520 	if (ret) {
2521 		return ret;
2522 	}
2523 
2524 	/* ask for consent if this is due to received SecReq */
2525 	if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) &&
2526 	    atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) &&
2527 	    smp_auth_cb && smp_auth_cb->pairing_confirm) {
2528 		atomic_set_bit(smp->flags, SMP_FLAG_USER);
2529 		smp_auth_cb->pairing_confirm(smp->chan.chan.conn);
2530 		return 0;
2531 	}
2532 
2533 	if (!atomic_test_bit(smp->flags, SMP_FLAG_USER)) {
2534 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM);
2535 		atomic_set_bit(smp->allowed_cmds, BT_SMP_KEYPRESS_NOTIFICATION);
2536 		return legacy_send_pairing_confirm(smp);
2537 	}
2538 
2539 	atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED);
2540 
2541 	return 0;
2542 }
2543 #endif /* CONFIG_BT_CENTRAL */
2544 #else
smp_encrypt_info(struct bt_smp * smp,struct net_buf * buf)2545 static uint8_t smp_encrypt_info(struct bt_smp *smp, struct net_buf *buf)
2546 {
2547 	return BT_SMP_ERR_CMD_NOTSUPP;
2548 }
2549 
smp_central_ident(struct bt_smp * smp,struct net_buf * buf)2550 static uint8_t smp_central_ident(struct bt_smp *smp, struct net_buf *buf)
2551 {
2552 	return BT_SMP_ERR_CMD_NOTSUPP;
2553 }
2554 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
2555 
smp_init(struct bt_smp * smp)2556 static int smp_init(struct bt_smp *smp)
2557 {
2558 	/* Initialize SMP context exluding L2CAP channel context and anything
2559 	 * else declared after.
2560 	 */
2561 	(void)memset(smp, 0, offsetof(struct bt_smp, chan));
2562 
2563 	/* Generate local random number */
2564 	if (bt_rand(smp->prnd, 16)) {
2565 		return BT_SMP_ERR_UNSPECIFIED;
2566 	}
2567 
2568 	LOG_DBG("prnd %s", bt_hex(smp->prnd, 16));
2569 
2570 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_FAIL);
2571 
2572 #if !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)
2573 	sc_public_key = bt_pub_key_get();
2574 #endif
2575 
2576 	return 0;
2577 }
2578 
bt_set_bondable(bool enable)2579 void bt_set_bondable(bool enable)
2580 {
2581 	bondable = enable;
2582 }
2583 
bt_le_oob_set_sc_flag(bool enable)2584 void bt_le_oob_set_sc_flag(bool enable)
2585 {
2586 	sc_oobd_present = enable;
2587 }
2588 
bt_le_oob_set_legacy_flag(bool enable)2589 void bt_le_oob_set_legacy_flag(bool enable)
2590 {
2591 	legacy_oobd_present = enable;
2592 }
2593 
get_auth(struct bt_smp * smp,uint8_t auth)2594 static uint8_t get_auth(struct bt_smp *smp, uint8_t auth)
2595 {
2596 	struct bt_conn *conn = smp->chan.chan.conn;
2597 
2598 	if (sc_supported) {
2599 		auth &= BT_SMP_AUTH_MASK_SC;
2600 	} else {
2601 		auth &= BT_SMP_AUTH_MASK;
2602 	}
2603 
2604 	if ((get_io_capa(smp) == BT_SMP_IO_NO_INPUT_OUTPUT) ||
2605 	    (!IS_ENABLED(CONFIG_BT_SMP_ENFORCE_MITM) &&
2606 	    (conn->required_sec_level < BT_SECURITY_L3))) {
2607 		auth &= ~(BT_SMP_AUTH_MITM);
2608 	} else {
2609 		auth |= BT_SMP_AUTH_MITM;
2610 	}
2611 
2612 	if (latch_bondable(smp)) {
2613 		auth |= BT_SMP_AUTH_BONDING;
2614 	} else {
2615 		auth &= ~BT_SMP_AUTH_BONDING;
2616 	}
2617 
2618 	if (IS_ENABLED(CONFIG_BT_PASSKEY_KEYPRESS)) {
2619 		auth |= BT_SMP_AUTH_KEYPRESS;
2620 	} else {
2621 		auth &= ~BT_SMP_AUTH_KEYPRESS;
2622 	}
2623 
2624 	return auth;
2625 }
2626 
remote_sec_level_reachable(struct bt_smp * smp)2627 static uint8_t remote_sec_level_reachable(struct bt_smp *smp)
2628 {
2629 	bt_security_t sec = smp->chan.chan.conn->required_sec_level;
2630 
2631 	if (IS_ENABLED(CONFIG_BT_SMP_SC_ONLY)) {
2632 		sec = BT_SECURITY_L4;
2633 	}
2634 	if (IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)) {
2635 		sec = BT_SECURITY_L3;
2636 	}
2637 
2638 	switch (sec) {
2639 	case BT_SECURITY_L1:
2640 	case BT_SECURITY_L2:
2641 		return 0;
2642 
2643 	case BT_SECURITY_L4:
2644 		if (get_encryption_key_size(smp) != BT_SMP_MAX_ENC_KEY_SIZE) {
2645 			return BT_SMP_ERR_ENC_KEY_SIZE;
2646 		}
2647 
2648 		if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
2649 			return BT_SMP_ERR_AUTH_REQUIREMENTS;
2650 		}
2651 		__fallthrough;
2652 	case BT_SECURITY_L3:
2653 		if (smp->method == JUST_WORKS) {
2654 			return BT_SMP_ERR_AUTH_REQUIREMENTS;
2655 		}
2656 
2657 		return 0;
2658 	default:
2659 		return BT_SMP_ERR_UNSPECIFIED;
2660 	}
2661 }
2662 
sec_level_reachable(struct bt_smp * smp)2663 static bool sec_level_reachable(struct bt_smp *smp)
2664 {
2665 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
2666 
2667 	switch (smp->chan.chan.conn->required_sec_level) {
2668 	case BT_SECURITY_L1:
2669 	case BT_SECURITY_L2:
2670 		return true;
2671 	case BT_SECURITY_L3:
2672 		return get_io_capa(smp) != BT_SMP_IO_NO_INPUT_OUTPUT ||
2673 		       (smp_auth_cb && smp_auth_cb->oob_data_request);
2674 	case BT_SECURITY_L4:
2675 		return (get_io_capa(smp) != BT_SMP_IO_NO_INPUT_OUTPUT ||
2676 		       (smp_auth_cb && smp_auth_cb->oob_data_request)) && sc_supported;
2677 	default:
2678 		return false;
2679 	}
2680 }
2681 
smp_chan_get(struct bt_conn * conn)2682 static struct bt_smp *smp_chan_get(struct bt_conn *conn)
2683 {
2684 	struct bt_l2cap_chan *chan;
2685 
2686 	chan = bt_l2cap_le_lookup_rx_cid(conn, BT_L2CAP_CID_SMP);
2687 	if (!chan) {
2688 		LOG_ERR("Unable to find SMP channel");
2689 		return NULL;
2690 	}
2691 
2692 	return CONTAINER_OF(chan, struct bt_smp, chan.chan);
2693 }
2694 
bt_smp_request_ltk(struct bt_conn * conn,uint64_t rand,uint16_t ediv,uint8_t * ltk)2695 bool bt_smp_request_ltk(struct bt_conn *conn, uint64_t rand, uint16_t ediv, uint8_t *ltk)
2696 {
2697 	struct bt_smp *smp;
2698 	uint8_t enc_size;
2699 
2700 	smp = smp_chan_get(conn);
2701 	if (!smp) {
2702 		return false;
2703 	}
2704 
2705 	/*
2706 	 * Both legacy STK and LE SC LTK have rand and ediv equal to zero.
2707 	 * If pairing is in progress use the TK for encryption.
2708 	 */
2709 	if (ediv == 0U && rand == 0U &&
2710 	    atomic_test_bit(smp->flags, SMP_FLAG_PAIRING) &&
2711 	    atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) {
2712 		enc_size = get_encryption_key_size(smp);
2713 
2714 		/*
2715 		 * We keep both legacy STK and LE SC LTK in TK.
2716 		 * Also use only enc_size bytes of key for encryption.
2717 		 */
2718 		memcpy(ltk, smp->tk, enc_size);
2719 		if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) {
2720 			(void)memset(ltk + enc_size, 0,
2721 				     BT_SMP_MAX_ENC_KEY_SIZE - enc_size);
2722 		}
2723 
2724 		atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
2725 		return true;
2726 	}
2727 
2728 	if (!conn->le.keys) {
2729 		conn->le.keys = bt_keys_find(BT_KEYS_LTK_P256, conn->id,
2730 					     &conn->le.dst);
2731 		if (!conn->le.keys) {
2732 			conn->le.keys = bt_keys_find(BT_KEYS_PERIPH_LTK,
2733 						     conn->id, &conn->le.dst);
2734 		}
2735 	}
2736 
2737 	if (ediv == 0U && rand == 0U &&
2738 	    conn->le.keys && (conn->le.keys->keys & BT_KEYS_LTK_P256)) {
2739 		enc_size = conn->le.keys->enc_size;
2740 
2741 		memcpy(ltk, conn->le.keys->ltk.val, enc_size);
2742 		if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) {
2743 			(void)memset(ltk + enc_size, 0,
2744 				     BT_SMP_MAX_ENC_KEY_SIZE - enc_size);
2745 		}
2746 
2747 		atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
2748 		return true;
2749 	}
2750 
2751 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
2752 	if (conn->le.keys && (conn->le.keys->keys & BT_KEYS_PERIPH_LTK) &&
2753 	    !memcmp(conn->le.keys->periph_ltk.rand, &rand, 8) &&
2754 	    !memcmp(conn->le.keys->periph_ltk.ediv, &ediv, 2)) {
2755 		enc_size = conn->le.keys->enc_size;
2756 
2757 		memcpy(ltk, conn->le.keys->periph_ltk.val, enc_size);
2758 		if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) {
2759 			(void)memset(ltk + enc_size, 0,
2760 				     BT_SMP_MAX_ENC_KEY_SIZE - enc_size);
2761 		}
2762 
2763 		atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
2764 		return true;
2765 	}
2766 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
2767 
2768 	if (atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ)) {
2769 		/* Notify higher level that security failed if security was
2770 		 * initiated by peripheral.
2771 		 */
2772 		bt_conn_security_changed(conn, BT_HCI_ERR_PIN_OR_KEY_MISSING,
2773 					 BT_SECURITY_ERR_PIN_OR_KEY_MISSING);
2774 	}
2775 
2776 	smp_reset(smp);
2777 	return false;
2778 }
2779 
2780 #if defined(CONFIG_BT_PERIPHERAL)
smp_send_security_req(struct bt_conn * conn)2781 static int smp_send_security_req(struct bt_conn *conn)
2782 {
2783 	struct bt_smp *smp;
2784 	struct bt_smp_security_request *req;
2785 	struct net_buf *req_buf;
2786 	int err;
2787 
2788 	LOG_DBG("");
2789 	smp = smp_chan_get(conn);
2790 	if (!smp) {
2791 		return -ENOTCONN;
2792 	}
2793 
2794 	/* SMP Timeout */
2795 	if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) {
2796 		return -EIO;
2797 	}
2798 
2799 	/* pairing is in progress */
2800 	if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
2801 		return -EBUSY;
2802 	}
2803 
2804 	if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) {
2805 		return -EBUSY;
2806 	}
2807 
2808 	/* early verify if required sec level if reachable */
2809 	if (!(sec_level_reachable(smp) || smp_keys_check(conn))) {
2810 		return -EINVAL;
2811 	}
2812 
2813 	if (!conn->le.keys) {
2814 		conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst);
2815 		if (!conn->le.keys) {
2816 			return -ENOMEM;
2817 		}
2818 	}
2819 
2820 	if (smp_init(smp) != 0) {
2821 		return -ENOBUFS;
2822 	}
2823 
2824 	req_buf = smp_create_pdu(smp, BT_SMP_CMD_SECURITY_REQUEST,
2825 				 sizeof(*req));
2826 	if (!req_buf) {
2827 		return -ENOBUFS;
2828 	}
2829 
2830 	req = net_buf_add(req_buf, sizeof(*req));
2831 	req->auth_req = get_auth(smp, BT_SMP_AUTH_DEFAULT);
2832 
2833 	/* SMP timer is not restarted for SecRequest so don't use smp_send */
2834 	err = bt_l2cap_send(conn, BT_L2CAP_CID_SMP, req_buf);
2835 	if (err) {
2836 		net_buf_unref(req_buf);
2837 		return err;
2838 	}
2839 
2840 	atomic_set_bit(smp->flags, SMP_FLAG_SEC_REQ);
2841 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_REQ);
2842 
2843 	return 0;
2844 }
2845 
smp_pairing_req(struct bt_smp * smp,struct net_buf * buf)2846 static uint8_t smp_pairing_req(struct bt_smp *smp, struct net_buf *buf)
2847 {
2848 	struct bt_conn *conn = smp->chan.chan.conn;
2849 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
2850 
2851 	struct bt_smp_pairing *req = (void *)buf->data;
2852 	struct bt_smp_pairing *rsp;
2853 	uint8_t err;
2854 
2855 	LOG_DBG("req: io_capability 0x%02X, oob_flag 0x%02X, auth_req 0x%02X, "
2856 		"max_key_size 0x%02X, init_key_dist 0x%02X, resp_key_dist 0x%02X",
2857 		req->io_capability, req->oob_flag, req->auth_req,
2858 		req->max_key_size, req->init_key_dist, req->resp_key_dist);
2859 
2860 	if ((req->max_key_size > BT_SMP_MAX_ENC_KEY_SIZE) ||
2861 	    (req->max_key_size < BT_SMP_MIN_ENC_KEY_SIZE)) {
2862 		return BT_SMP_ERR_ENC_KEY_SIZE;
2863 	}
2864 
2865 	if (!conn->le.keys) {
2866 		conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst);
2867 		if (!conn->le.keys) {
2868 			LOG_DBG("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst));
2869 			return BT_SMP_ERR_UNSPECIFIED;
2870 		}
2871 	}
2872 
2873 	/* If we already sent a security request then the SMP context
2874 	 * is already initialized.
2875 	 */
2876 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ)) {
2877 		int ret = smp_init(smp);
2878 
2879 		if (ret) {
2880 			return ret;
2881 		}
2882 	}
2883 
2884 	/* Store req for later use */
2885 	smp->preq[0] = BT_SMP_CMD_PAIRING_REQ;
2886 	memcpy(smp->preq + 1, req, sizeof(*req));
2887 
2888 	/* create rsp, it will be used later on */
2889 	smp->prsp[0] = BT_SMP_CMD_PAIRING_RSP;
2890 	rsp = (struct bt_smp_pairing *)&smp->prsp[1];
2891 
2892 	rsp->auth_req = get_auth(smp, req->auth_req);
2893 	rsp->io_capability = get_io_capa(smp);
2894 	rsp->max_key_size = BT_SMP_MAX_ENC_KEY_SIZE;
2895 	rsp->init_key_dist = (req->init_key_dist & RECV_KEYS);
2896 	rsp->resp_key_dist = (req->resp_key_dist & SEND_KEYS);
2897 
2898 	if ((rsp->auth_req & BT_SMP_AUTH_SC) &&
2899 	    (req->auth_req & BT_SMP_AUTH_SC)) {
2900 		atomic_set_bit(smp->flags, SMP_FLAG_SC);
2901 
2902 		rsp->init_key_dist &= RECV_KEYS_SC;
2903 		rsp->resp_key_dist &= SEND_KEYS_SC;
2904 	}
2905 
2906 	if (atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
2907 		rsp->oob_flag = sc_oobd_present ? BT_SMP_OOB_PRESENT :
2908 				BT_SMP_OOB_NOT_PRESENT;
2909 	} else {
2910 		rsp->oob_flag = legacy_oobd_present ? BT_SMP_OOB_PRESENT :
2911 				BT_SMP_OOB_NOT_PRESENT;
2912 	}
2913 
2914 	if ((rsp->auth_req & BT_SMP_AUTH_CT2) &&
2915 	    (req->auth_req & BT_SMP_AUTH_CT2)) {
2916 		atomic_set_bit(smp->flags, SMP_FLAG_CT2);
2917 	}
2918 
2919 	if ((rsp->auth_req & BT_SMP_AUTH_BONDING) &&
2920 	    (req->auth_req & BT_SMP_AUTH_BONDING)) {
2921 		atomic_set_bit(smp->flags, SMP_FLAG_BOND);
2922 	} else if (IS_ENABLED(CONFIG_BT_BONDING_REQUIRED)) {
2923 		/* Reject pairing req if not both intend to bond */
2924 		LOG_DBG("Bonding required");
2925 		return BT_SMP_ERR_UNSPECIFIED;
2926 	} else {
2927 		rsp->init_key_dist = 0;
2928 		rsp->resp_key_dist = 0;
2929 	}
2930 
2931 	smp->local_dist = rsp->resp_key_dist;
2932 	smp->remote_dist = rsp->init_key_dist;
2933 
2934 	atomic_set_bit(smp->flags, SMP_FLAG_PAIRING);
2935 
2936 	smp->method = get_pair_method(smp, req->io_capability);
2937 
2938 	if (!update_keys_check(smp, conn->le.keys)) {
2939 		return BT_SMP_ERR_AUTH_REQUIREMENTS;
2940 	}
2941 
2942 	err = remote_sec_level_reachable(smp);
2943 	if (err) {
2944 		return err;
2945 	}
2946 
2947 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
2948 #if defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
2949 		return BT_SMP_ERR_AUTH_REQUIREMENTS;
2950 #else
2951 		if (IS_ENABLED(CONFIG_BT_SMP_APP_PAIRING_ACCEPT)) {
2952 			err = smp_pairing_accept_query(smp, req);
2953 			if (err) {
2954 				return err;
2955 			}
2956 		}
2957 
2958 		return legacy_pairing_req(smp);
2959 #endif /* CONFIG_BT_SMP_SC_PAIR_ONLY */
2960 	}
2961 
2962 	if (IS_ENABLED(CONFIG_BT_SMP_APP_PAIRING_ACCEPT)) {
2963 		err = smp_pairing_accept_query(smp, req);
2964 		if (err) {
2965 			return err;
2966 		}
2967 	}
2968 
2969 	if (!IS_ENABLED(CONFIG_BT_SMP_SC_PAIR_ONLY) &&
2970 	    (DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) &&
2971 	    !atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) &&
2972 	    smp_auth_cb && smp_auth_cb->pairing_confirm) {
2973 		atomic_set_bit(smp->flags, SMP_FLAG_USER);
2974 		smp_auth_cb->pairing_confirm(conn);
2975 		return 0;
2976 	}
2977 
2978 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY);
2979 
2980 	LOG_DBG("rsp: io_capability 0x%02X, oob_flag 0x%02X, auth_req 0x%02X, "
2981 		"max_key_size 0x%02X, init_key_dist 0x%02X, resp_key_dist 0x%02X",
2982 		rsp->io_capability, rsp->oob_flag, rsp->auth_req,
2983 		rsp->max_key_size, rsp->init_key_dist, rsp->resp_key_dist);
2984 
2985 	return send_pairing_rsp(smp);
2986 }
2987 #else
smp_pairing_req(struct bt_smp * smp,struct net_buf * buf)2988 static uint8_t smp_pairing_req(struct bt_smp *smp, struct net_buf *buf)
2989 {
2990 	return BT_SMP_ERR_CMD_NOTSUPP;
2991 }
2992 #endif /* CONFIG_BT_PERIPHERAL */
2993 
sc_send_public_key(struct bt_smp * smp)2994 static uint8_t sc_send_public_key(struct bt_smp *smp)
2995 {
2996 	struct bt_smp_public_key *req;
2997 	struct net_buf *req_buf;
2998 
2999 	req_buf = smp_create_pdu(smp, BT_SMP_CMD_PUBLIC_KEY, sizeof(*req));
3000 	if (!req_buf) {
3001 		return BT_SMP_ERR_UNSPECIFIED;
3002 	}
3003 
3004 	req = net_buf_add(req_buf, sizeof(*req));
3005 
3006 	memcpy(req->x, sc_public_key, sizeof(req->x));
3007 	memcpy(req->y, &sc_public_key[32], sizeof(req->y));
3008 
3009 	smp_send(smp, req_buf, NULL, NULL);
3010 
3011 	if (IS_ENABLED(CONFIG_BT_USE_DEBUG_KEYS)) {
3012 		atomic_set_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY);
3013 	}
3014 
3015 	return 0;
3016 }
3017 
3018 #if defined(CONFIG_BT_CENTRAL)
smp_send_pairing_req(struct bt_conn * conn)3019 static int smp_send_pairing_req(struct bt_conn *conn)
3020 {
3021 	struct bt_smp *smp;
3022 	struct bt_smp_pairing *req;
3023 	struct net_buf *req_buf;
3024 
3025 	LOG_DBG("");
3026 
3027 	smp = smp_chan_get(conn);
3028 	if (!smp) {
3029 		return -ENOTCONN;
3030 	}
3031 
3032 	/* SMP Timeout */
3033 	if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) {
3034 		return -EIO;
3035 	}
3036 
3037 	/* A higher security level is requested during the key distribution
3038 	 * phase, once pairing is complete a new pairing procedure will start.
3039 	 */
3040 	if (atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR)) {
3041 		return 0;
3042 	}
3043 
3044 	/* pairing is in progress */
3045 	if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
3046 		return -EBUSY;
3047 	}
3048 
3049 	/* Encryption is in progress */
3050 	if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) {
3051 		return -EBUSY;
3052 	}
3053 
3054 	/* early verify if required sec level if reachable */
3055 	if (!sec_level_reachable(smp)) {
3056 		return -EINVAL;
3057 	}
3058 
3059 	if (!conn->le.keys) {
3060 		conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst);
3061 		if (!conn->le.keys) {
3062 			return -ENOMEM;
3063 		}
3064 	}
3065 
3066 	if (smp_init(smp)) {
3067 		return -ENOBUFS;
3068 	}
3069 
3070 	req_buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_REQ, sizeof(*req));
3071 	if (!req_buf) {
3072 		return -ENOBUFS;
3073 	}
3074 
3075 	req = net_buf_add(req_buf, sizeof(*req));
3076 
3077 	req->auth_req = get_auth(smp, BT_SMP_AUTH_DEFAULT);
3078 	req->io_capability = get_io_capa(smp);
3079 
3080 	/* At this point is it unknown if pairing will be legacy or LE SC so
3081 	 * set OOB flag if any OOB data is present and assume to peer device
3082 	 * provides OOB data that will match it's pairing type.
3083 	 */
3084 	req->oob_flag = (legacy_oobd_present || sc_oobd_present) ?
3085 				BT_SMP_OOB_PRESENT : BT_SMP_OOB_NOT_PRESENT;
3086 
3087 	req->max_key_size = BT_SMP_MAX_ENC_KEY_SIZE;
3088 
3089 	if (req->auth_req & BT_SMP_AUTH_BONDING) {
3090 		req->init_key_dist = SEND_KEYS;
3091 		req->resp_key_dist = RECV_KEYS;
3092 	} else {
3093 		req->init_key_dist = 0;
3094 		req->resp_key_dist = 0;
3095 	}
3096 
3097 	smp->local_dist = req->init_key_dist;
3098 	smp->remote_dist = req->resp_key_dist;
3099 
3100 	/* Store req for later use */
3101 	smp->preq[0] = BT_SMP_CMD_PAIRING_REQ;
3102 	memcpy(smp->preq + 1, req, sizeof(*req));
3103 
3104 	LOG_DBG("req: io_capability 0x%02X, oob_flag 0x%02X, auth_req 0x%02X, "
3105 		"max_key_size 0x%02X, init_key_dist 0x%02X, resp_key_dist 0x%02X",
3106 		req->io_capability, req->oob_flag, req->auth_req,
3107 		req->max_key_size, req->init_key_dist, req->resp_key_dist);
3108 
3109 	smp_send(smp, req_buf, NULL, NULL);
3110 
3111 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RSP);
3112 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST);
3113 	atomic_set_bit(smp->flags, SMP_FLAG_PAIRING);
3114 
3115 	return 0;
3116 }
3117 
smp_pairing_rsp(struct bt_smp * smp,struct net_buf * buf)3118 static uint8_t smp_pairing_rsp(struct bt_smp *smp, struct net_buf *buf)
3119 {
3120 	struct bt_conn *conn = smp->chan.chan.conn;
3121 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
3122 	struct bt_smp_pairing *rsp = (void *)buf->data;
3123 	struct bt_smp_pairing *req = (struct bt_smp_pairing *)&smp->preq[1];
3124 	uint8_t err;
3125 
3126 	LOG_DBG("rsp: io_capability 0x%02X, oob_flag 0x%02X, auth_req 0x%02X, "
3127 		"max_key_size 0x%02X, init_key_dist 0x%02X, resp_key_dist 0x%02X",
3128 		rsp->io_capability, rsp->oob_flag, rsp->auth_req,
3129 		rsp->max_key_size, rsp->init_key_dist, rsp->resp_key_dist);
3130 
3131 	if ((rsp->max_key_size > BT_SMP_MAX_ENC_KEY_SIZE) ||
3132 	    (rsp->max_key_size < BT_SMP_MIN_ENC_KEY_SIZE)) {
3133 		return BT_SMP_ERR_ENC_KEY_SIZE;
3134 	}
3135 
3136 	smp->local_dist &= rsp->init_key_dist;
3137 	smp->remote_dist &= rsp->resp_key_dist;
3138 
3139 	/* Store rsp for later use */
3140 	smp->prsp[0] = BT_SMP_CMD_PAIRING_RSP;
3141 	memcpy(smp->prsp + 1, rsp, sizeof(*rsp));
3142 
3143 	if ((rsp->auth_req & BT_SMP_AUTH_SC) &&
3144 	    (req->auth_req & BT_SMP_AUTH_SC)) {
3145 		atomic_set_bit(smp->flags, SMP_FLAG_SC);
3146 	}
3147 
3148 	if ((rsp->auth_req & BT_SMP_AUTH_CT2) &&
3149 	    (req->auth_req & BT_SMP_AUTH_CT2)) {
3150 		atomic_set_bit(smp->flags, SMP_FLAG_CT2);
3151 	}
3152 
3153 	if ((rsp->auth_req & BT_SMP_AUTH_BONDING) &&
3154 	    (req->auth_req & BT_SMP_AUTH_BONDING)) {
3155 		atomic_set_bit(smp->flags, SMP_FLAG_BOND);
3156 	} else if (IS_ENABLED(CONFIG_BT_BONDING_REQUIRED)) {
3157 		/* Reject pairing req if not both intend to bond */
3158 		LOG_DBG("Bonding required");
3159 		return BT_SMP_ERR_UNSPECIFIED;
3160 	} else {
3161 		smp->local_dist = 0;
3162 		smp->remote_dist = 0;
3163 	}
3164 
3165 	smp->method = get_pair_method(smp, rsp->io_capability);
3166 
3167 	if (!update_keys_check(smp, conn->le.keys)) {
3168 		return BT_SMP_ERR_AUTH_REQUIREMENTS;
3169 	}
3170 
3171 	err = remote_sec_level_reachable(smp);
3172 	if (err) {
3173 		return err;
3174 	}
3175 
3176 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
3177 #if defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
3178 		return BT_SMP_ERR_AUTH_REQUIREMENTS;
3179 #else
3180 		if (IS_ENABLED(CONFIG_BT_SMP_APP_PAIRING_ACCEPT)) {
3181 			err = smp_pairing_accept_query(smp, rsp);
3182 			if (err) {
3183 				return err;
3184 			}
3185 		}
3186 
3187 		return legacy_pairing_rsp(smp);
3188 #endif /* CONFIG_BT_SMP_SC_PAIR_ONLY */
3189 	}
3190 
3191 	smp->local_dist &= SEND_KEYS_SC;
3192 	smp->remote_dist &= RECV_KEYS_SC;
3193 
3194 	if (IS_ENABLED(CONFIG_BT_SMP_APP_PAIRING_ACCEPT)) {
3195 		err = smp_pairing_accept_query(smp, rsp);
3196 		if (err) {
3197 			return err;
3198 		}
3199 	}
3200 
3201 	if (!IS_ENABLED(CONFIG_BT_SMP_SC_PAIR_ONLY) &&
3202 	    (DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) &&
3203 	    atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) &&
3204 	    smp_auth_cb && smp_auth_cb->pairing_confirm) {
3205 		atomic_set_bit(smp->flags, SMP_FLAG_USER);
3206 		smp_auth_cb->pairing_confirm(conn);
3207 		return 0;
3208 	}
3209 
3210 	if (!sc_public_key) {
3211 		atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND);
3212 		return 0;
3213 	}
3214 
3215 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY);
3216 	atomic_clear_bit(smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST);
3217 
3218 	return sc_send_public_key(smp);
3219 }
3220 #else
smp_pairing_rsp(struct bt_smp * smp,struct net_buf * buf)3221 static uint8_t smp_pairing_rsp(struct bt_smp *smp, struct net_buf *buf)
3222 {
3223 	return BT_SMP_ERR_CMD_NOTSUPP;
3224 }
3225 #endif /* CONFIG_BT_CENTRAL */
3226 
smp_pairing_confirm(struct bt_smp * smp,struct net_buf * buf)3227 static uint8_t smp_pairing_confirm(struct bt_smp *smp, struct net_buf *buf)
3228 {
3229 	struct bt_smp_pairing_confirm *req = (void *)buf->data;
3230 
3231 	LOG_DBG("");
3232 
3233 	atomic_clear_bit(smp->flags, SMP_FLAG_DISPLAY);
3234 
3235 	memcpy(smp->pcnf, req->val, sizeof(smp->pcnf));
3236 
3237 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
3238 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
3239 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
3240 		return smp_send_pairing_random(smp);
3241 	}
3242 
3243 	if (!IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
3244 		return 0;
3245 	}
3246 
3247 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
3248 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
3249 		return legacy_pairing_confirm(smp);
3250 	}
3251 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
3252 
3253 	switch (smp->method) {
3254 	case PASSKEY_DISPLAY:
3255 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
3256 		return smp_send_pairing_confirm(smp);
3257 	case PASSKEY_INPUT:
3258 		if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) {
3259 			atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED);
3260 			return 0;
3261 		}
3262 
3263 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
3264 		return smp_send_pairing_confirm(smp);
3265 	case JUST_WORKS:
3266 	case PASSKEY_CONFIRM:
3267 	default:
3268 		LOG_ERR("Unknown pairing method (%u)", smp->method);
3269 		return BT_SMP_ERR_UNSPECIFIED;
3270 	}
3271 }
3272 
sc_smp_send_dhkey_check(struct bt_smp * smp,const uint8_t * e)3273 static uint8_t sc_smp_send_dhkey_check(struct bt_smp *smp, const uint8_t *e)
3274 {
3275 	struct bt_smp_dhkey_check *req;
3276 	struct net_buf *buf;
3277 
3278 	LOG_DBG("");
3279 
3280 	buf = smp_create_pdu(smp, BT_SMP_DHKEY_CHECK, sizeof(*req));
3281 	if (!buf) {
3282 		return BT_SMP_ERR_UNSPECIFIED;
3283 	}
3284 
3285 	req = net_buf_add(buf, sizeof(*req));
3286 	memcpy(req->e, e, sizeof(req->e));
3287 
3288 	smp_send(smp, buf, NULL, NULL);
3289 
3290 	return 0;
3291 }
3292 
3293 #if defined(CONFIG_BT_CENTRAL)
compute_and_send_central_dhcheck(struct bt_smp * smp)3294 static uint8_t compute_and_send_central_dhcheck(struct bt_smp *smp)
3295 {
3296 	uint8_t e[16], r[16];
3297 
3298 	(void)memset(r, 0, sizeof(r));
3299 
3300 	switch (smp->method) {
3301 	case JUST_WORKS:
3302 	case PASSKEY_CONFIRM:
3303 		break;
3304 	case PASSKEY_DISPLAY:
3305 	case PASSKEY_INPUT:
3306 		memcpy(r, &smp->passkey, sizeof(smp->passkey));
3307 		break;
3308 	case LE_SC_OOB:
3309 		if (smp->oobd_remote) {
3310 			memcpy(r, smp->oobd_remote->r, sizeof(r));
3311 		}
3312 		break;
3313 	default:
3314 		LOG_ERR("Unknown pairing method (%u)", smp->method);
3315 		return BT_SMP_ERR_UNSPECIFIED;
3316 	}
3317 
3318 	/* calculate LTK and mackey */
3319 	if (bt_crypto_f5(smp->dhkey, smp->prnd, smp->rrnd, &smp->chan.chan.conn->le.init_addr,
3320 			 &smp->chan.chan.conn->le.resp_addr, smp->mackey, smp->tk)) {
3321 		LOG_ERR("Calculate LTK failed");
3322 		return BT_SMP_ERR_UNSPECIFIED;
3323 	}
3324 	/* calculate local DHKey check */
3325 	if (bt_crypto_f6(smp->mackey, smp->prnd, smp->rrnd, r, &smp->preq[1],
3326 			 &smp->chan.chan.conn->le.init_addr, &smp->chan.chan.conn->le.resp_addr,
3327 			 e)) {
3328 		LOG_ERR("Calculate local DHKey check failed");
3329 		return BT_SMP_ERR_UNSPECIFIED;
3330 	}
3331 
3332 	atomic_set_bit(smp->allowed_cmds, BT_SMP_DHKEY_CHECK);
3333 	return sc_smp_send_dhkey_check(smp, e);
3334 }
3335 #endif /* CONFIG_BT_CENTRAL */
3336 
3337 #if defined(CONFIG_BT_PERIPHERAL)
compute_and_check_and_send_periph_dhcheck(struct bt_smp * smp)3338 static uint8_t compute_and_check_and_send_periph_dhcheck(struct bt_smp *smp)
3339 {
3340 	uint8_t re[16], e[16], r[16];
3341 	uint8_t err;
3342 
3343 	(void)memset(r, 0, sizeof(r));
3344 
3345 	switch (smp->method) {
3346 	case JUST_WORKS:
3347 	case PASSKEY_CONFIRM:
3348 		break;
3349 	case PASSKEY_DISPLAY:
3350 	case PASSKEY_INPUT:
3351 		memcpy(r, &smp->passkey, sizeof(smp->passkey));
3352 		break;
3353 	case LE_SC_OOB:
3354 		if (smp->oobd_remote) {
3355 			memcpy(r, smp->oobd_remote->r, sizeof(r));
3356 		}
3357 		break;
3358 	default:
3359 		LOG_ERR("Unknown pairing method (%u)", smp->method);
3360 		return BT_SMP_ERR_UNSPECIFIED;
3361 	}
3362 
3363 	/* calculate LTK and mackey */
3364 	if (bt_crypto_f5(smp->dhkey, smp->rrnd, smp->prnd, &smp->chan.chan.conn->le.init_addr,
3365 			 &smp->chan.chan.conn->le.resp_addr, smp->mackey, smp->tk)) {
3366 		LOG_ERR("Calculate LTK failed");
3367 		return BT_SMP_ERR_UNSPECIFIED;
3368 	}
3369 
3370 	/* calculate local DHKey check */
3371 	if (bt_crypto_f6(smp->mackey, smp->prnd, smp->rrnd, r, &smp->prsp[1],
3372 			 &smp->chan.chan.conn->le.resp_addr, &smp->chan.chan.conn->le.init_addr,
3373 			 e)) {
3374 		LOG_ERR("Calculate local DHKey check failed");
3375 		return BT_SMP_ERR_UNSPECIFIED;
3376 	}
3377 
3378 	if (smp->method == LE_SC_OOB) {
3379 		if (smp->oobd_local) {
3380 			memcpy(r, smp->oobd_local->r, sizeof(r));
3381 		} else {
3382 			memset(r, 0, sizeof(r));
3383 		}
3384 	}
3385 
3386 	/* calculate remote DHKey check */
3387 	if (bt_crypto_f6(smp->mackey, smp->rrnd, smp->prnd, r, &smp->preq[1],
3388 			 &smp->chan.chan.conn->le.init_addr, &smp->chan.chan.conn->le.resp_addr,
3389 			 re)) {
3390 		LOG_ERR("Calculate remote DHKey check failed");
3391 		return BT_SMP_ERR_UNSPECIFIED;
3392 	}
3393 
3394 	/* compare received E with calculated remote */
3395 	if (memcmp(smp->e, re, 16)) {
3396 		return BT_SMP_ERR_DHKEY_CHECK_FAILED;
3397 	}
3398 
3399 	/* send local e */
3400 	err = sc_smp_send_dhkey_check(smp, e);
3401 	if (err) {
3402 		return err;
3403 	}
3404 
3405 	atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
3406 	return 0;
3407 }
3408 #endif /* CONFIG_BT_PERIPHERAL */
3409 
3410 static void bt_smp_dhkey_ready(const uint8_t *dhkey);
smp_dhkey_generate(struct bt_smp * smp)3411 static uint8_t smp_dhkey_generate(struct bt_smp *smp)
3412 {
3413 	int err;
3414 
3415 	atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_GEN);
3416 	err = bt_dh_key_gen(smp->pkey, bt_smp_dhkey_ready);
3417 	if (err) {
3418 		atomic_clear_bit(smp->flags, SMP_FLAG_DHKEY_GEN);
3419 
3420 		LOG_ERR("Failed to generate DHKey");
3421 		return BT_SMP_ERR_UNSPECIFIED;
3422 	}
3423 
3424 	return 0;
3425 }
3426 
smp_dhkey_ready(struct bt_smp * smp,const uint8_t * dhkey)3427 static uint8_t smp_dhkey_ready(struct bt_smp *smp, const uint8_t *dhkey)
3428 {
3429 	if (!dhkey) {
3430 		return BT_SMP_ERR_DHKEY_CHECK_FAILED;
3431 	}
3432 
3433 	atomic_clear_bit(smp->flags, SMP_FLAG_DHKEY_PENDING);
3434 	memcpy(smp->dhkey, dhkey, BT_DH_KEY_LEN);
3435 
3436 	/* wait for user passkey confirmation */
3437 	if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) {
3438 		atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
3439 		return 0;
3440 	}
3441 
3442 	/* wait for remote DHKey Check */
3443 	if (atomic_test_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT)) {
3444 		atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
3445 		return 0;
3446 	}
3447 
3448 	if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_SEND)) {
3449 #if defined(CONFIG_BT_CENTRAL)
3450 		if (smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
3451 			return compute_and_send_central_dhcheck(smp);
3452 		}
3453 
3454 #endif /* CONFIG_BT_CENTRAL */
3455 
3456 #if defined(CONFIG_BT_PERIPHERAL)
3457 		return  compute_and_check_and_send_periph_dhcheck(smp);
3458 #endif /* CONFIG_BT_PERIPHERAL */
3459 	}
3460 
3461 	return 0;
3462 }
3463 
smp_find(int flag)3464 static struct bt_smp *smp_find(int flag)
3465 {
3466 	for (int i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) {
3467 		if (atomic_test_bit(bt_smp_pool[i].flags, flag)) {
3468 			return &bt_smp_pool[i];
3469 		}
3470 	}
3471 
3472 	return NULL;
3473 }
3474 
bt_smp_dhkey_ready(const uint8_t * dhkey)3475 static void bt_smp_dhkey_ready(const uint8_t *dhkey)
3476 {
3477 	LOG_DBG("%p", (void *)dhkey);
3478 	int err;
3479 
3480 	struct bt_smp *smp = smp_find(SMP_FLAG_DHKEY_GEN);
3481 	if (smp) {
3482 		atomic_clear_bit(smp->flags, SMP_FLAG_DHKEY_GEN);
3483 		err = smp_dhkey_ready(smp, dhkey);
3484 		if (err) {
3485 			smp_error(smp, err);
3486 		}
3487 	}
3488 
3489 	err = 0;
3490 	do {
3491 		smp = smp_find(SMP_FLAG_DHKEY_PENDING);
3492 		if (smp) {
3493 			err = smp_dhkey_generate(smp);
3494 			if (err) {
3495 				smp_error(smp, err);
3496 			}
3497 		}
3498 	} while (smp && err);
3499 }
3500 
sc_smp_check_confirm(struct bt_smp * smp)3501 static uint8_t sc_smp_check_confirm(struct bt_smp *smp)
3502 {
3503 	uint8_t cfm[16];
3504 	uint8_t r;
3505 
3506 	switch (smp->method) {
3507 	case LE_SC_OOB:
3508 		return 0;
3509 	case PASSKEY_CONFIRM:
3510 	case JUST_WORKS:
3511 		r = 0U;
3512 		break;
3513 	case PASSKEY_DISPLAY:
3514 	case PASSKEY_INPUT:
3515 		/*
3516 		 * In the Passkey Entry protocol, the most significant
3517 		 * bit of Z is set equal to one and the least
3518 		 * significant bit is made up from one bit of the
3519 		 * passkey e.g. if the passkey bit is 1, then Z = 0x81
3520 		 * and if the passkey bit is 0, then Z = 0x80.
3521 		 */
3522 		r = (smp->passkey >> smp->passkey_round) & 0x01;
3523 		r |= 0x80;
3524 		break;
3525 	default:
3526 		LOG_ERR("Unknown pairing method (%u)", smp->method);
3527 		return BT_SMP_ERR_UNSPECIFIED;
3528 	}
3529 
3530 	if (bt_crypto_f4(smp->pkey, sc_public_key, smp->rrnd, r, cfm)) {
3531 		LOG_ERR("Calculate confirm failed");
3532 		return BT_SMP_ERR_UNSPECIFIED;
3533 	}
3534 
3535 	LOG_DBG("pcnf %s", bt_hex(smp->pcnf, 16));
3536 	LOG_DBG("cfm %s", bt_hex(cfm, 16));
3537 
3538 	if (memcmp(smp->pcnf, cfm, 16)) {
3539 		return BT_SMP_ERR_CONFIRM_FAILED;
3540 	}
3541 
3542 	return 0;
3543 }
3544 
le_sc_oob_data_req_check(struct bt_smp * smp)3545 static bool le_sc_oob_data_req_check(struct bt_smp *smp)
3546 {
3547 	struct bt_smp_pairing *req = (struct bt_smp_pairing *)&smp->preq[1];
3548 
3549 	return ((req->oob_flag & BT_SMP_OOB_DATA_MASK) == BT_SMP_OOB_PRESENT);
3550 }
3551 
le_sc_oob_data_rsp_check(struct bt_smp * smp)3552 static bool le_sc_oob_data_rsp_check(struct bt_smp *smp)
3553 {
3554 	struct bt_smp_pairing *rsp = (struct bt_smp_pairing *)&smp->prsp[1];
3555 
3556 	return ((rsp->oob_flag & BT_SMP_OOB_DATA_MASK) == BT_SMP_OOB_PRESENT);
3557 }
3558 
le_sc_oob_config_set(struct bt_smp * smp,struct bt_conn_oob_info * info)3559 static void le_sc_oob_config_set(struct bt_smp *smp,
3560 				 struct bt_conn_oob_info *info)
3561 {
3562 	bool req_oob_present = le_sc_oob_data_req_check(smp);
3563 	bool rsp_oob_present = le_sc_oob_data_rsp_check(smp);
3564 	int oob_config = BT_CONN_OOB_NO_DATA;
3565 
3566 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
3567 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
3568 		oob_config = req_oob_present ? BT_CONN_OOB_REMOTE_ONLY :
3569 					       BT_CONN_OOB_NO_DATA;
3570 
3571 		if (rsp_oob_present) {
3572 			oob_config = (oob_config == BT_CONN_OOB_REMOTE_ONLY) ?
3573 				     BT_CONN_OOB_BOTH_PEERS :
3574 				     BT_CONN_OOB_LOCAL_ONLY;
3575 		}
3576 	} else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
3577 		oob_config = req_oob_present ? BT_CONN_OOB_LOCAL_ONLY :
3578 					       BT_CONN_OOB_NO_DATA;
3579 
3580 		if (rsp_oob_present) {
3581 			oob_config = (oob_config == BT_CONN_OOB_LOCAL_ONLY) ?
3582 				     BT_CONN_OOB_BOTH_PEERS :
3583 				     BT_CONN_OOB_REMOTE_ONLY;
3584 		}
3585 	}
3586 
3587 	info->lesc.oob_config = oob_config;
3588 }
3589 
smp_pairing_random(struct bt_smp * smp,struct net_buf * buf)3590 static uint8_t smp_pairing_random(struct bt_smp *smp, struct net_buf *buf)
3591 {
3592 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
3593 	struct bt_smp_pairing_random *req = (void *)buf->data;
3594 	uint32_t passkey;
3595 	uint8_t err;
3596 
3597 	LOG_DBG("");
3598 
3599 	memcpy(smp->rrnd, req->val, sizeof(smp->rrnd));
3600 
3601 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
3602 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
3603 		return legacy_pairing_random(smp);
3604 	}
3605 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
3606 
3607 #if defined(CONFIG_BT_CENTRAL)
3608 	if (smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
3609 		err = sc_smp_check_confirm(smp);
3610 		if (err) {
3611 			return err;
3612 		}
3613 
3614 		switch (smp->method) {
3615 		case PASSKEY_CONFIRM:
3616 			/* compare passkey before calculating LTK */
3617 			if (bt_crypto_g2(sc_public_key, smp->pkey, smp->prnd, smp->rrnd,
3618 					 &passkey)) {
3619 				return BT_SMP_ERR_UNSPECIFIED;
3620 			}
3621 
3622 			atomic_set_bit(smp->flags, SMP_FLAG_USER);
3623 			atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
3624 			smp_auth_cb->passkey_confirm(smp->chan.chan.conn, passkey);
3625 			return 0;
3626 		case JUST_WORKS:
3627 			break;
3628 		case LE_SC_OOB:
3629 			break;
3630 		case PASSKEY_DISPLAY:
3631 		case PASSKEY_INPUT:
3632 			smp->passkey_round++;
3633 			if (smp->passkey_round == 20U) {
3634 				break;
3635 			}
3636 
3637 			if (bt_rand(smp->prnd, 16)) {
3638 				return BT_SMP_ERR_UNSPECIFIED;
3639 			}
3640 
3641 			atomic_set_bit(smp->allowed_cmds,
3642 				       BT_SMP_CMD_PAIRING_CONFIRM);
3643 			return smp_send_pairing_confirm(smp);
3644 		default:
3645 			LOG_ERR("Unknown pairing method (%u)", smp->method);
3646 			return BT_SMP_ERR_UNSPECIFIED;
3647 		}
3648 
3649 		/* wait for DHKey being generated */
3650 		if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) {
3651 			atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
3652 			return 0;
3653 		}
3654 
3655 		return compute_and_send_central_dhcheck(smp);
3656 	}
3657 #endif /* CONFIG_BT_CENTRAL */
3658 
3659 #if defined(CONFIG_BT_PERIPHERAL)
3660 	switch (smp->method) {
3661 	case PASSKEY_CONFIRM:
3662 		if (bt_crypto_g2(smp->pkey, sc_public_key, smp->rrnd, smp->prnd, &passkey)) {
3663 			return BT_SMP_ERR_UNSPECIFIED;
3664 		}
3665 
3666 		atomic_set_bit(smp->flags, SMP_FLAG_USER);
3667 		smp_auth_cb->passkey_confirm(smp->chan.chan.conn, passkey);
3668 		break;
3669 	case JUST_WORKS:
3670 		break;
3671 	case PASSKEY_DISPLAY:
3672 	case PASSKEY_INPUT:
3673 		err = sc_smp_check_confirm(smp);
3674 		if (err) {
3675 			return err;
3676 		}
3677 
3678 		atomic_set_bit(smp->allowed_cmds,
3679 			       BT_SMP_CMD_PAIRING_CONFIRM);
3680 		err = smp_send_pairing_random(smp);
3681 		if (err) {
3682 			return err;
3683 		}
3684 
3685 		smp->passkey_round++;
3686 		if (smp->passkey_round == 20U) {
3687 			atomic_set_bit(smp->allowed_cmds, BT_SMP_DHKEY_CHECK);
3688 			atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT);
3689 			return 0;
3690 		}
3691 
3692 		if (bt_rand(smp->prnd, 16)) {
3693 			return BT_SMP_ERR_UNSPECIFIED;
3694 		}
3695 
3696 		return 0;
3697 	case LE_SC_OOB:
3698 		/* Step 6: Select random N */
3699 		if (bt_rand(smp->prnd, 16)) {
3700 			return BT_SMP_ERR_UNSPECIFIED;
3701 		}
3702 
3703 		if (smp_auth_cb && smp_auth_cb->oob_data_request) {
3704 			struct bt_conn_oob_info info = {
3705 				.type = BT_CONN_OOB_LE_SC,
3706 				.lesc.oob_config = BT_CONN_OOB_NO_DATA,
3707 			};
3708 
3709 			le_sc_oob_config_set(smp, &info);
3710 
3711 			smp->oobd_local = NULL;
3712 			smp->oobd_remote = NULL;
3713 
3714 			atomic_set_bit(smp->flags, SMP_FLAG_OOB_PENDING);
3715 			smp_auth_cb->oob_data_request(smp->chan.chan.conn, &info);
3716 
3717 			return 0;
3718 		} else {
3719 			return BT_SMP_ERR_OOB_NOT_AVAIL;
3720 		}
3721 	default:
3722 		LOG_ERR("Unknown pairing method (%u)", smp->method);
3723 		return BT_SMP_ERR_UNSPECIFIED;
3724 	}
3725 
3726 	atomic_set_bit(smp->allowed_cmds, BT_SMP_DHKEY_CHECK);
3727 	atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT);
3728 	return smp_send_pairing_random(smp);
3729 #else
3730 	return BT_SMP_ERR_PAIRING_NOTSUPP;
3731 #endif /* CONFIG_BT_PERIPHERAL */
3732 }
3733 
smp_pairing_failed(struct bt_smp * smp,struct net_buf * buf)3734 static uint8_t smp_pairing_failed(struct bt_smp *smp, struct net_buf *buf)
3735 {
3736 	struct bt_conn *conn = smp->chan.chan.conn;
3737 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
3738 	struct bt_smp_pairing_fail *req = (void *)buf->data;
3739 
3740 	LOG_ERR("pairing failed (peer reason 0x%x)", req->reason);
3741 
3742 	if (atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER) ||
3743 	    atomic_test_and_clear_bit(smp->flags, SMP_FLAG_DISPLAY)) {
3744 		if (smp_auth_cb && smp_auth_cb->cancel) {
3745 			smp_auth_cb->cancel(conn);
3746 		}
3747 	}
3748 
3749 	smp_pairing_complete(smp, req->reason);
3750 
3751 	/* return no error to avoid sending Pairing Failed in response */
3752 	return 0;
3753 }
3754 
smp_ident_info(struct bt_smp * smp,struct net_buf * buf)3755 static uint8_t smp_ident_info(struct bt_smp *smp, struct net_buf *buf)
3756 {
3757 	LOG_DBG("");
3758 
3759 	if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
3760 		struct bt_smp_ident_info *req = (void *)buf->data;
3761 		struct bt_conn *conn = smp->chan.chan.conn;
3762 		struct bt_keys *keys;
3763 
3764 		keys = bt_keys_get_type(BT_KEYS_IRK, conn->id, &conn->le.dst);
3765 		if (!keys) {
3766 			LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst));
3767 			return BT_SMP_ERR_UNSPECIFIED;
3768 		}
3769 
3770 		memcpy(keys->irk.val, req->irk, 16);
3771 	}
3772 
3773 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_IDENT_ADDR_INFO);
3774 
3775 	return 0;
3776 }
3777 
smp_id_add_replace(struct bt_smp * smp,struct bt_keys * new_bond)3778 static uint8_t smp_id_add_replace(struct bt_smp *smp, struct bt_keys *new_bond)
3779 {
3780 	struct bt_keys *conflict;
3781 
3782 	/* Sanity check: It does not make sense to finalize a bond before we
3783 	 * have the remote identity.
3784 	 */
3785 	__ASSERT_NO_MSG(!(smp->remote_dist & BT_SMP_DIST_ID_KEY));
3786 
3787 	conflict = bt_id_find_conflict(new_bond);
3788 	if (conflict) {
3789 		LOG_DBG("New bond conflicts with a bond on id %d.", conflict->id);
3790 	}
3791 
3792 	if (conflict && !IS_ENABLED(CONFIG_BT_ID_UNPAIR_MATCHING_BONDS)) {
3793 		LOG_WRN("Refusing new pairing. The old bond must be unpaired first.");
3794 		return BT_SMP_ERR_AUTH_REQUIREMENTS;
3795 	}
3796 
3797 	if (conflict && IS_ENABLED(CONFIG_BT_ID_UNPAIR_MATCHING_BONDS)) {
3798 		bool trust_ok;
3799 		int unpair_err;
3800 
3801 		trust_ok = update_keys_check(smp, conflict);
3802 		if (!trust_ok) {
3803 			LOG_WRN("Refusing new pairing. The old bond has more trust.");
3804 			return BT_SMP_ERR_AUTH_REQUIREMENTS;
3805 		}
3806 
3807 		LOG_DBG("Un-pairing old conflicting bond and finalizing new.");
3808 
3809 		unpair_err = bt_unpair(conflict->id, &conflict->addr);
3810 		__ASSERT_NO_MSG(!unpair_err);
3811 	}
3812 
3813 	__ASSERT_NO_MSG(!bt_id_find_conflict(new_bond));
3814 	bt_id_add(new_bond);
3815 	return 0;
3816 }
3817 
3818 struct addr_match {
3819 	const bt_addr_le_t *rpa;
3820 	const bt_addr_le_t *id_addr;
3821 };
3822 
convert_to_id_on_match(struct bt_conn * conn,void * data)3823 static void convert_to_id_on_match(struct bt_conn *conn, void *data)
3824 {
3825 	struct addr_match *addr_match = data;
3826 
3827 	if (bt_addr_le_eq(&conn->le.dst, addr_match->rpa)) {
3828 		bt_addr_le_copy(&conn->le.dst, addr_match->id_addr);
3829 	}
3830 }
3831 
smp_ident_addr_info(struct bt_smp * smp,struct net_buf * buf)3832 static uint8_t smp_ident_addr_info(struct bt_smp *smp, struct net_buf *buf)
3833 {
3834 	struct bt_conn *conn = smp->chan.chan.conn;
3835 	struct bt_smp_ident_addr_info *req = (void *)buf->data;
3836 	uint8_t err;
3837 
3838 	LOG_DBG("identity %s", bt_addr_le_str(&req->addr));
3839 
3840 	smp->remote_dist &= ~BT_SMP_DIST_ID_KEY;
3841 
3842 	if (!bt_addr_le_is_identity(&req->addr)) {
3843 		LOG_ERR("Invalid identity %s", bt_addr_le_str(&req->addr));
3844 		LOG_ERR(" for %s", bt_addr_le_str(&conn->le.dst));
3845 		return BT_SMP_ERR_INVALID_PARAMS;
3846 	}
3847 
3848 	if (!bt_addr_le_eq(&conn->le.dst, &req->addr)) {
3849 		struct bt_keys *keys = bt_keys_find_addr(conn->id, &req->addr);
3850 
3851 		if (keys) {
3852 			if (!update_keys_check(smp, keys)) {
3853 				return BT_SMP_ERR_UNSPECIFIED;
3854 			}
3855 
3856 			bt_keys_clear(keys);
3857 		}
3858 	}
3859 
3860 	if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
3861 		const bt_addr_le_t *dst;
3862 		struct bt_keys *keys;
3863 
3864 		keys = bt_keys_get_type(BT_KEYS_IRK, conn->id, &conn->le.dst);
3865 		if (!keys) {
3866 			LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst));
3867 			return BT_SMP_ERR_UNSPECIFIED;
3868 		}
3869 
3870 		/*
3871 		 * We can't use conn->dst here as this might already contain
3872 		 * identity address known from previous pairing. Since all keys
3873 		 * are cleared on re-pairing we wouldn't store IRK distributed
3874 		 * in new pairing.
3875 		 */
3876 		if (conn->role == BT_HCI_ROLE_CENTRAL) {
3877 			dst = &conn->le.resp_addr;
3878 		} else {
3879 			dst = &conn->le.init_addr;
3880 		}
3881 
3882 		if (bt_addr_le_is_rpa(dst)) {
3883 			/* always update last use RPA */
3884 			bt_addr_copy(&keys->irk.rpa, &dst->a);
3885 
3886 			/*
3887 			 * Update connection address and notify about identity
3888 			 * resolved only if connection wasn't already reported
3889 			 * with identity address. This may happen if IRK was
3890 			 * present before ie. due to re-pairing.
3891 			 */
3892 			if (!bt_addr_le_is_identity(&conn->le.dst)) {
3893 				struct addr_match addr_match = {
3894 					.rpa = &conn->le.dst,
3895 					.id_addr = &req->addr,
3896 				};
3897 
3898 				bt_conn_foreach(BT_CONN_TYPE_LE,
3899 						convert_to_id_on_match,
3900 						&addr_match);
3901 				bt_addr_le_copy(&keys->addr, &req->addr);
3902 
3903 				bt_conn_identity_resolved(conn);
3904 			}
3905 		}
3906 
3907 		err = smp_id_add_replace(smp, keys);
3908 		if (err) {
3909 			return err;
3910 		}
3911 	}
3912 
3913 	if (smp->remote_dist & BT_SMP_DIST_SIGN) {
3914 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO);
3915 	}
3916 
3917 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
3918 	    conn->role == BT_HCI_ROLE_CENTRAL && !smp->remote_dist) {
3919 		err = bt_smp_distribute_keys(smp);
3920 		if (err) {
3921 			return err;
3922 		}
3923 	}
3924 
3925 	/* if all keys were distributed, pairing is done */
3926 	if (!smp->local_dist && !smp->remote_dist) {
3927 		smp_pairing_complete(smp, 0);
3928 	}
3929 
3930 	return 0;
3931 }
3932 
3933 #if defined(CONFIG_BT_SIGNING)
smp_signing_info(struct bt_smp * smp,struct net_buf * buf)3934 static uint8_t smp_signing_info(struct bt_smp *smp, struct net_buf *buf)
3935 {
3936 	struct bt_conn *conn = smp->chan.chan.conn;
3937 	uint8_t err;
3938 
3939 	LOG_DBG("");
3940 
3941 	if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
3942 		struct bt_smp_signing_info *req = (void *)buf->data;
3943 		struct bt_keys *keys;
3944 
3945 		keys = bt_keys_get_type(BT_KEYS_REMOTE_CSRK, conn->id,
3946 					&conn->le.dst);
3947 		if (!keys) {
3948 			LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst));
3949 			return BT_SMP_ERR_UNSPECIFIED;
3950 		}
3951 
3952 		memcpy(keys->remote_csrk.val, req->csrk,
3953 		       sizeof(keys->remote_csrk.val));
3954 	}
3955 
3956 	smp->remote_dist &= ~BT_SMP_DIST_SIGN;
3957 
3958 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
3959 	    conn->role == BT_HCI_ROLE_CENTRAL && !smp->remote_dist) {
3960 		err = bt_smp_distribute_keys(smp);
3961 		if (err) {
3962 			return err;
3963 		}
3964 	}
3965 
3966 	/* if all keys were distributed, pairing is done */
3967 	if (!smp->local_dist && !smp->remote_dist) {
3968 		smp_pairing_complete(smp, 0);
3969 	}
3970 
3971 	return 0;
3972 }
3973 #else
smp_signing_info(struct bt_smp * smp,struct net_buf * buf)3974 static uint8_t smp_signing_info(struct bt_smp *smp, struct net_buf *buf)
3975 {
3976 	return BT_SMP_ERR_CMD_NOTSUPP;
3977 }
3978 #endif /* CONFIG_BT_SIGNING */
3979 
3980 #if defined(CONFIG_BT_CENTRAL)
smp_security_request(struct bt_smp * smp,struct net_buf * buf)3981 static uint8_t smp_security_request(struct bt_smp *smp, struct net_buf *buf)
3982 {
3983 	struct bt_conn *conn = smp->chan.chan.conn;
3984 	struct bt_smp_security_request *req = (void *)buf->data;
3985 	uint8_t auth;
3986 
3987 	LOG_DBG("");
3988 
3989 	/* A higher security level is requested during the key distribution
3990 	 * phase, once pairing is complete a new pairing procedure will start.
3991 	 */
3992 	if (atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR)) {
3993 		return 0;
3994 	}
3995 
3996 	if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
3997 		/* We have already started pairing process */
3998 		return 0;
3999 	}
4000 
4001 	if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) {
4002 		/* We have already started encryption procedure */
4003 		return 0;
4004 	}
4005 
4006 	if (sc_supported) {
4007 		auth = req->auth_req & BT_SMP_AUTH_MASK_SC;
4008 	} else {
4009 		auth = req->auth_req & BT_SMP_AUTH_MASK;
4010 	}
4011 
4012 	if (IS_ENABLED(CONFIG_BT_SMP_SC_PAIR_ONLY) &&
4013 	    !(auth & BT_SMP_AUTH_SC)) {
4014 		return BT_SMP_ERR_AUTH_REQUIREMENTS;
4015 	}
4016 
4017 	if (IS_ENABLED(CONFIG_BT_BONDING_REQUIRED) &&
4018 	    !(latch_bondable(smp) && (auth & BT_SMP_AUTH_BONDING))) {
4019 		/* Reject security req if not both intend to bond */
4020 		LOG_DBG("Bonding required");
4021 		return BT_SMP_ERR_UNSPECIFIED;
4022 	}
4023 
4024 	if (conn->le.keys) {
4025 		/* Make sure we have an LTK to encrypt with */
4026 		if (!(conn->le.keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_LTK))) {
4027 			goto pair;
4028 		}
4029 	} else {
4030 		conn->le.keys = bt_keys_find(BT_KEYS_LTK_P256, conn->id,
4031 					     &conn->le.dst);
4032 		if (!conn->le.keys) {
4033 			conn->le.keys = bt_keys_find(BT_KEYS_LTK, conn->id,
4034 						     &conn->le.dst);
4035 		}
4036 	}
4037 
4038 	if (!conn->le.keys) {
4039 		goto pair;
4040 	}
4041 
4042 	/* if MITM required key must be authenticated */
4043 	if ((auth & BT_SMP_AUTH_MITM) &&
4044 	    !(conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) {
4045 		if (get_io_capa(smp) != BT_SMP_IO_NO_INPUT_OUTPUT) {
4046 			LOG_INF("New auth requirements: 0x%x, repairing", auth);
4047 			goto pair;
4048 		}
4049 
4050 		LOG_WRN("Unsupported auth requirements: 0x%x, repairing", auth);
4051 		goto pair;
4052 	}
4053 
4054 	/* if LE SC required and no p256 key present repair */
4055 	if ((auth & BT_SMP_AUTH_SC) &&
4056 	    !(conn->le.keys->keys & BT_KEYS_LTK_P256)) {
4057 		LOG_INF("New auth requirements: 0x%x, repairing", auth);
4058 		goto pair;
4059 	}
4060 
4061 	if (bt_conn_le_start_encryption(conn, conn->le.keys->ltk.rand,
4062 					conn->le.keys->ltk.ediv,
4063 					conn->le.keys->ltk.val,
4064 					conn->le.keys->enc_size) < 0) {
4065 		LOG_ERR("Failed to start encryption");
4066 		return BT_SMP_ERR_UNSPECIFIED;
4067 	}
4068 
4069 	atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
4070 
4071 	return 0;
4072 pair:
4073 	if (smp_send_pairing_req(conn) < 0) {
4074 		return BT_SMP_ERR_UNSPECIFIED;
4075 	}
4076 
4077 	atomic_set_bit(smp->flags, SMP_FLAG_SEC_REQ);
4078 
4079 	return 0;
4080 }
4081 #else
smp_security_request(struct bt_smp * smp,struct net_buf * buf)4082 static uint8_t smp_security_request(struct bt_smp *smp, struct net_buf *buf)
4083 {
4084 	return BT_SMP_ERR_CMD_NOTSUPP;
4085 }
4086 #endif /* CONFIG_BT_CENTRAL */
4087 
generate_dhkey(struct bt_smp * smp)4088 static uint8_t generate_dhkey(struct bt_smp *smp)
4089 {
4090 	if (IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)) {
4091 		return BT_SMP_ERR_UNSPECIFIED;
4092 	}
4093 
4094 	atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_PENDING);
4095 	if (!smp_find(SMP_FLAG_DHKEY_GEN)) {
4096 		return smp_dhkey_generate(smp);
4097 	}
4098 
4099 	return 0;
4100 }
4101 
display_passkey(struct bt_smp * smp)4102 static uint8_t display_passkey(struct bt_smp *smp)
4103 {
4104 	struct bt_conn *conn = smp->chan.chan.conn;
4105 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
4106 
4107 	if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) &&
4108 	    fixed_passkey != BT_PASSKEY_INVALID) {
4109 		smp->passkey = fixed_passkey;
4110 	} else {
4111 		if (bt_rand(&smp->passkey, sizeof(smp->passkey))) {
4112 			return BT_SMP_ERR_UNSPECIFIED;
4113 		}
4114 
4115 		smp->passkey %= 1000000;
4116 	}
4117 
4118 	smp->passkey_round = 0U;
4119 
4120 	if (smp_auth_cb && smp_auth_cb->passkey_display) {
4121 		atomic_set_bit(smp->flags, SMP_FLAG_DISPLAY);
4122 		smp_auth_cb->passkey_display(conn, smp->passkey);
4123 	}
4124 
4125 	smp->passkey = sys_cpu_to_le32(smp->passkey);
4126 
4127 	return 0;
4128 }
4129 
4130 #if defined(CONFIG_BT_PERIPHERAL)
smp_public_key_periph(struct bt_smp * smp)4131 static uint8_t smp_public_key_periph(struct bt_smp *smp)
4132 {
4133 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
4134 	uint8_t err;
4135 
4136 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY) &&
4137 	    memcmp(smp->pkey, sc_public_key, BT_PUB_KEY_COORD_LEN) == 0) {
4138 		/* Deny public key with identitcal X coordinate unless it is the
4139 		 * debug public key.
4140 		 */
4141 		LOG_WRN("Remote public key rejected");
4142 		return BT_SMP_ERR_UNSPECIFIED;
4143 	}
4144 
4145 	err = sc_send_public_key(smp);
4146 	if (err) {
4147 		return err;
4148 	}
4149 
4150 	switch (smp->method) {
4151 	case PASSKEY_CONFIRM:
4152 	case JUST_WORKS:
4153 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
4154 
4155 		err = smp_send_pairing_confirm(smp);
4156 		if (err) {
4157 			return err;
4158 		}
4159 		break;
4160 	case PASSKEY_DISPLAY:
4161 		err = display_passkey(smp);
4162 		if (err) {
4163 			return err;
4164 		}
4165 
4166 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM);
4167 		atomic_set_bit(smp->allowed_cmds, BT_SMP_KEYPRESS_NOTIFICATION);
4168 		break;
4169 	case PASSKEY_INPUT:
4170 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM);
4171 		atomic_set_bit(smp->allowed_cmds, BT_SMP_KEYPRESS_NOTIFICATION);
4172 		atomic_set_bit(smp->flags, SMP_FLAG_USER);
4173 		smp_auth_cb->passkey_entry(smp->chan.chan.conn);
4174 		break;
4175 	case LE_SC_OOB:
4176 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
4177 		break;
4178 	default:
4179 		LOG_ERR("Unknown pairing method (%u)", smp->method);
4180 		return BT_SMP_ERR_UNSPECIFIED;
4181 	}
4182 
4183 	return generate_dhkey(smp);
4184 }
4185 #endif /* CONFIG_BT_PERIPHERAL */
4186 
smp_public_key(struct bt_smp * smp,struct net_buf * buf)4187 static uint8_t smp_public_key(struct bt_smp *smp, struct net_buf *buf)
4188 {
4189 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
4190 	struct bt_smp_public_key *req = (void *)buf->data;
4191 	uint8_t err;
4192 
4193 	LOG_DBG("");
4194 
4195 	memcpy(smp->pkey, req->x, BT_PUB_KEY_COORD_LEN);
4196 	memcpy(&smp->pkey[BT_PUB_KEY_COORD_LEN], req->y, BT_PUB_KEY_COORD_LEN);
4197 
4198 	/* mark key as debug if remote is using it */
4199 	if (bt_pub_key_is_debug(smp->pkey)) {
4200 		LOG_INF("Remote is using Debug Public key");
4201 		atomic_set_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY);
4202 
4203 		/* Don't allow a bond established without debug key to be
4204 		 * updated using LTK generated from debug key.
4205 		 */
4206 		if (!update_debug_keys_check(smp)) {
4207 			return BT_SMP_ERR_AUTH_REQUIREMENTS;
4208 		}
4209 	}
4210 
4211 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
4212 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
4213 		if (!atomic_test_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY) &&
4214 		    memcmp(smp->pkey, sc_public_key, BT_PUB_KEY_COORD_LEN) == 0) {
4215 			/* Deny public key with identitcal X coordinate unless
4216 			 * it is the debug public key.
4217 			 */
4218 			LOG_WRN("Remote public key rejected");
4219 			return BT_SMP_ERR_UNSPECIFIED;
4220 		}
4221 
4222 		switch (smp->method) {
4223 		case PASSKEY_CONFIRM:
4224 		case JUST_WORKS:
4225 			atomic_set_bit(smp->allowed_cmds,
4226 				       BT_SMP_CMD_PAIRING_CONFIRM);
4227 			break;
4228 		case PASSKEY_DISPLAY:
4229 			err = display_passkey(smp);
4230 			if (err) {
4231 				return err;
4232 			}
4233 
4234 			atomic_set_bit(smp->allowed_cmds,
4235 				       BT_SMP_CMD_PAIRING_CONFIRM);
4236 
4237 			atomic_set_bit(smp->allowed_cmds,
4238 				       BT_SMP_KEYPRESS_NOTIFICATION);
4239 
4240 			err = smp_send_pairing_confirm(smp);
4241 			if (err) {
4242 				return err;
4243 			}
4244 			break;
4245 		case PASSKEY_INPUT:
4246 			atomic_set_bit(smp->flags, SMP_FLAG_USER);
4247 			smp_auth_cb->passkey_entry(smp->chan.chan.conn);
4248 
4249 			atomic_set_bit(smp->allowed_cmds,
4250 				       BT_SMP_KEYPRESS_NOTIFICATION);
4251 
4252 			break;
4253 		case LE_SC_OOB:
4254 			/* Step 6: Select random N */
4255 			if (bt_rand(smp->prnd, 16)) {
4256 				return BT_SMP_ERR_UNSPECIFIED;
4257 			}
4258 
4259 			if (smp_auth_cb && smp_auth_cb->oob_data_request) {
4260 				struct bt_conn_oob_info info = {
4261 					.type = BT_CONN_OOB_LE_SC,
4262 					.lesc.oob_config = BT_CONN_OOB_NO_DATA,
4263 				};
4264 
4265 				le_sc_oob_config_set(smp, &info);
4266 
4267 				smp->oobd_local = NULL;
4268 				smp->oobd_remote = NULL;
4269 
4270 				atomic_set_bit(smp->flags,
4271 					       SMP_FLAG_OOB_PENDING);
4272 				smp_auth_cb->oob_data_request(smp->chan.chan.conn, &info);
4273 			} else {
4274 				return BT_SMP_ERR_OOB_NOT_AVAIL;
4275 			}
4276 			break;
4277 		default:
4278 			LOG_ERR("Unknown pairing method (%u)", smp->method);
4279 			return BT_SMP_ERR_UNSPECIFIED;
4280 		}
4281 
4282 		return generate_dhkey(smp);
4283 	}
4284 
4285 #if defined(CONFIG_BT_PERIPHERAL)
4286 	if (!sc_public_key) {
4287 		atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND);
4288 		return 0;
4289 	}
4290 
4291 	err = smp_public_key_periph(smp);
4292 	if (err) {
4293 		return err;
4294 	}
4295 #endif /* CONFIG_BT_PERIPHERAL */
4296 
4297 	return 0;
4298 }
4299 
smp_dhkey_check(struct bt_smp * smp,struct net_buf * buf)4300 static uint8_t smp_dhkey_check(struct bt_smp *smp, struct net_buf *buf)
4301 {
4302 	struct bt_smp_dhkey_check *req = (void *)buf->data;
4303 
4304 	LOG_DBG("");
4305 
4306 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
4307 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
4308 		uint8_t e[16], r[16], enc_size;
4309 		uint8_t ediv[2], rand[8];
4310 
4311 		(void)memset(r, 0, sizeof(r));
4312 
4313 		switch (smp->method) {
4314 		case JUST_WORKS:
4315 		case PASSKEY_CONFIRM:
4316 			break;
4317 		case PASSKEY_DISPLAY:
4318 		case PASSKEY_INPUT:
4319 			memcpy(r, &smp->passkey, sizeof(smp->passkey));
4320 			break;
4321 		case LE_SC_OOB:
4322 			if (smp->oobd_local) {
4323 				memcpy(r, smp->oobd_local->r, sizeof(r));
4324 			}
4325 			break;
4326 		default:
4327 			LOG_ERR("Unknown pairing method (%u)", smp->method);
4328 			return BT_SMP_ERR_UNSPECIFIED;
4329 		}
4330 
4331 		/* calculate remote DHKey check for comparison */
4332 		if (bt_crypto_f6(smp->mackey, smp->rrnd, smp->prnd, r, &smp->prsp[1],
4333 				 &smp->chan.chan.conn->le.resp_addr,
4334 				 &smp->chan.chan.conn->le.init_addr, e)) {
4335 			return BT_SMP_ERR_UNSPECIFIED;
4336 		}
4337 
4338 		if (memcmp(e, req->e, 16)) {
4339 			return BT_SMP_ERR_DHKEY_CHECK_FAILED;
4340 		}
4341 
4342 		enc_size = get_encryption_key_size(smp);
4343 
4344 		/* Rand and EDiv are 0 */
4345 		(void)memset(ediv, 0, sizeof(ediv));
4346 		(void)memset(rand, 0, sizeof(rand));
4347 		if (bt_conn_le_start_encryption(smp->chan.chan.conn, rand, ediv,
4348 						smp->tk, enc_size) < 0) {
4349 			LOG_ERR("Failed to start encryption");
4350 			return BT_SMP_ERR_UNSPECIFIED;
4351 		}
4352 
4353 		atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
4354 
4355 		if (IS_ENABLED(CONFIG_BT_SMP_USB_HCI_CTLR_WORKAROUND)) {
4356 			if (smp->remote_dist & BT_SMP_DIST_ID_KEY) {
4357 				atomic_set_bit(smp->allowed_cmds,
4358 					       BT_SMP_CMD_IDENT_INFO);
4359 			} else if (smp->remote_dist & BT_SMP_DIST_SIGN) {
4360 				atomic_set_bit(smp->allowed_cmds,
4361 					       BT_SMP_CMD_SIGNING_INFO);
4362 			}
4363 		}
4364 
4365 		return 0;
4366 	}
4367 
4368 #if defined(CONFIG_BT_PERIPHERAL)
4369 	if (smp->chan.chan.conn->role == BT_HCI_ROLE_PERIPHERAL) {
4370 		atomic_clear_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT);
4371 		memcpy(smp->e, req->e, sizeof(smp->e));
4372 
4373 		/* wait for DHKey being generated */
4374 		if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) {
4375 			atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
4376 			return 0;
4377 		}
4378 
4379 		/* waiting for user to confirm passkey */
4380 		if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) {
4381 			atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
4382 			return 0;
4383 		}
4384 
4385 		return compute_and_check_and_send_periph_dhcheck(smp);
4386 	}
4387 #endif /* CONFIG_BT_PERIPHERAL */
4388 
4389 	return 0;
4390 }
4391 
4392 #if defined(CONFIG_BT_PASSKEY_KEYPRESS)
smp_keypress_notif(struct bt_smp * smp,struct net_buf * buf)4393 static uint8_t smp_keypress_notif(struct bt_smp *smp, struct net_buf *buf)
4394 {
4395 	const struct bt_conn_auth_cb *smp_auth_cb = latch_auth_cb(smp);
4396 	struct bt_conn *conn = smp->chan.chan.conn;
4397 	struct bt_smp_keypress_notif *notif = (void *)buf->data;
4398 	enum bt_conn_auth_keypress type = notif->type;
4399 
4400 	LOG_DBG("Keypress from conn %u, type %u", bt_conn_index(conn), type);
4401 
4402 	/* For now, keypress notifications are always accepted. In the future we
4403 	 * should be smarter about this. We might also want to enforce something
4404 	 * about the 'start' and 'end' messages.
4405 	 */
4406 	atomic_set_bit(smp->allowed_cmds, BT_SMP_KEYPRESS_NOTIFICATION);
4407 
4408 	if (!IN_RANGE(type,
4409 		      BT_CONN_AUTH_KEYPRESS_ENTRY_STARTED,
4410 		      BT_CONN_AUTH_KEYPRESS_ENTRY_COMPLETED)) {
4411 		LOG_WRN("Received unknown keypress event type %u. Discarding.", type);
4412 		return BT_SMP_ERR_INVALID_PARAMS;
4413 	}
4414 
4415 	/* Reset SMP timeout, like the spec says. */
4416 	k_work_reschedule(&smp->work, SMP_TIMEOUT);
4417 
4418 	if (smp_auth_cb->passkey_display_keypress) {
4419 		smp_auth_cb->passkey_display_keypress(conn, type);
4420 	}
4421 
4422 	return 0;
4423 }
4424 #else
smp_keypress_notif(struct bt_smp * smp,struct net_buf * buf)4425 static uint8_t smp_keypress_notif(struct bt_smp *smp, struct net_buf *buf)
4426 {
4427 	ARG_UNUSED(smp);
4428 	ARG_UNUSED(buf);
4429 
4430 	LOG_DBG("");
4431 
4432 	/* Ignore packets until keypress notifications are fully supported. */
4433 	atomic_set_bit(smp->allowed_cmds, BT_SMP_KEYPRESS_NOTIFICATION);
4434 	return 0;
4435 }
4436 #endif
4437 
4438 static const struct {
4439 	uint8_t  (*func)(struct bt_smp *smp, struct net_buf *buf);
4440 	uint8_t  expect_len;
4441 } handlers[] = {
4442 	{ }, /* No op-code defined for 0x00 */
4443 	{ smp_pairing_req,         sizeof(struct bt_smp_pairing) },
4444 	{ smp_pairing_rsp,         sizeof(struct bt_smp_pairing) },
4445 	{ smp_pairing_confirm,     sizeof(struct bt_smp_pairing_confirm) },
4446 	{ smp_pairing_random,      sizeof(struct bt_smp_pairing_random) },
4447 	{ smp_pairing_failed,      sizeof(struct bt_smp_pairing_fail) },
4448 	{ smp_encrypt_info,        sizeof(struct bt_smp_encrypt_info) },
4449 	{ smp_central_ident,       sizeof(struct bt_smp_central_ident) },
4450 	{ smp_ident_info,          sizeof(struct bt_smp_ident_info) },
4451 	{ smp_ident_addr_info,     sizeof(struct bt_smp_ident_addr_info) },
4452 	{ smp_signing_info,        sizeof(struct bt_smp_signing_info) },
4453 	{ smp_security_request,    sizeof(struct bt_smp_security_request) },
4454 	{ smp_public_key,          sizeof(struct bt_smp_public_key) },
4455 	{ smp_dhkey_check,         sizeof(struct bt_smp_dhkey_check) },
4456 	{ smp_keypress_notif,      sizeof(struct bt_smp_keypress_notif) },
4457 };
4458 
is_in_pairing_procedure(struct bt_smp * smp)4459 static bool is_in_pairing_procedure(struct bt_smp *smp)
4460 {
4461 	return atomic_test_bit(smp->flags, SMP_FLAG_PAIRING);
4462 }
4463 
bt_smp_recv(struct bt_l2cap_chan * chan,struct net_buf * buf)4464 static int bt_smp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
4465 {
4466 	struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan.chan);
4467 	struct bt_smp_hdr *hdr;
4468 	uint8_t err;
4469 
4470 	if (buf->len < sizeof(*hdr)) {
4471 		LOG_ERR("Too small SMP PDU received");
4472 		return 0;
4473 	}
4474 
4475 	hdr = net_buf_pull_mem(buf, sizeof(*hdr));
4476 	LOG_DBG("Received SMP code 0x%02x len %u", hdr->code, buf->len);
4477 
4478 	/*
4479 	 * If SMP timeout occurred "no further SMP commands shall be sent over
4480 	 * the L2CAP Security Manager Channel. A new SM procedure shall only be
4481 	 * performed when a new physical link has been established."
4482 	 */
4483 	if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) {
4484 		LOG_WRN("SMP command (code 0x%02x) received after timeout", hdr->code);
4485 		return 0;
4486 	}
4487 
4488 	/*
4489 	 * Bluetooth Core Specification Version 5.2, Vol 3, Part H, page 1667:
4490 	 * If a packet is received with a Code that is reserved for future use
4491 	 * it shall be ignored.
4492 	 */
4493 	if (hdr->code >= ARRAY_SIZE(handlers)) {
4494 		LOG_WRN("Received reserved SMP code 0x%02x", hdr->code);
4495 		return 0;
4496 	}
4497 
4498 	if (!handlers[hdr->code].func) {
4499 		LOG_WRN("Unhandled SMP code 0x%02x", hdr->code);
4500 		smp_error(smp, BT_SMP_ERR_CMD_NOTSUPP);
4501 		return 0;
4502 	}
4503 
4504 	if (!atomic_test_and_clear_bit(smp->allowed_cmds, hdr->code)) {
4505 		LOG_WRN("Unexpected SMP code 0x%02x", hdr->code);
4506 		/* Do not send errors outside of pairing procedure. */
4507 		if (is_in_pairing_procedure(smp)) {
4508 			smp_error(smp, BT_SMP_ERR_UNSPECIFIED);
4509 		}
4510 		return 0;
4511 	}
4512 
4513 	if (buf->len != handlers[hdr->code].expect_len) {
4514 		LOG_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code);
4515 		smp_error(smp, BT_SMP_ERR_INVALID_PARAMS);
4516 		return 0;
4517 	}
4518 
4519 	err = handlers[hdr->code].func(smp, buf);
4520 	if (err) {
4521 		smp_error(smp, err);
4522 	}
4523 
4524 	return 0;
4525 }
4526 
bt_smp_pkey_ready(const uint8_t * pkey)4527 static void bt_smp_pkey_ready(const uint8_t *pkey)
4528 {
4529 	int i;
4530 
4531 	LOG_DBG("");
4532 
4533 	sc_public_key = pkey;
4534 
4535 	if (!pkey) {
4536 		LOG_WRN("Public key not available");
4537 		return;
4538 	}
4539 
4540 	k_sem_give(&sc_local_pkey_ready);
4541 
4542 	for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) {
4543 		struct bt_smp *smp = &bt_smp_pool[i];
4544 		uint8_t err;
4545 
4546 		if (!atomic_test_bit(smp->flags, SMP_FLAG_PKEY_SEND)) {
4547 			continue;
4548 		}
4549 
4550 		if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
4551 		    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
4552 			err = sc_send_public_key(smp);
4553 			if (err) {
4554 				smp_error(smp, err);
4555 			}
4556 
4557 			atomic_set_bit(smp->allowed_cmds,
4558 				       BT_SMP_CMD_PUBLIC_KEY);
4559 			continue;
4560 		}
4561 
4562 #if defined(CONFIG_BT_PERIPHERAL)
4563 		err = smp_public_key_periph(smp);
4564 		if (err) {
4565 			smp_error(smp, err);
4566 		}
4567 #endif /* CONFIG_BT_PERIPHERAL */
4568 	}
4569 }
4570 
bt_smp_connected(struct bt_l2cap_chan * chan)4571 static void bt_smp_connected(struct bt_l2cap_chan *chan)
4572 {
4573 	struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan.chan);
4574 
4575 	LOG_DBG("chan %p cid 0x%04x", chan,
4576 		CONTAINER_OF(chan, struct bt_l2cap_le_chan, chan)->tx.cid);
4577 
4578 	k_work_init_delayable(&smp->work, smp_timeout);
4579 	smp_reset(smp);
4580 
4581 	atomic_ptr_set(&smp->auth_cb, BT_SMP_AUTH_CB_UNINITIALIZED);
4582 	atomic_set(&smp->bondable, BT_SMP_BONDABLE_UNINITIALIZED);
4583 }
4584 
bt_smp_disconnected(struct bt_l2cap_chan * chan)4585 static void bt_smp_disconnected(struct bt_l2cap_chan *chan)
4586 {
4587 	struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan.chan);
4588 	struct bt_keys *keys = chan->conn->le.keys;
4589 
4590 	LOG_DBG("chan %p cid 0x%04x", chan,
4591 		CONTAINER_OF(chan, struct bt_l2cap_le_chan, chan)->tx.cid);
4592 
4593 	/* Channel disconnected callback is always called from a work handler
4594 	 * so canceling of the timeout work should always succeed.
4595 	 */
4596 	(void)k_work_cancel_delayable(&smp->work);
4597 
4598 	if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING) ||
4599 	    atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING) ||
4600 	    atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ)) {
4601 		/* reset context and report */
4602 		smp_pairing_complete(smp, BT_SMP_ERR_UNSPECIFIED);
4603 	}
4604 
4605 	if (keys) {
4606 		/*
4607 		 * If debug keys were used for pairing remove them.
4608 		 * No keys indicate no bonding so free keys storage.
4609 		 */
4610 		if (!keys->keys || (!IS_ENABLED(CONFIG_BT_STORE_DEBUG_KEYS) &&
4611 		    (keys->flags & BT_KEYS_DEBUG))) {
4612 			bt_keys_clear(keys);
4613 		}
4614 	}
4615 
4616 	(void)memset(smp, 0, sizeof(*smp));
4617 }
4618 
bt_smp_encrypt_change(struct bt_l2cap_chan * chan,uint8_t hci_status)4619 static void bt_smp_encrypt_change(struct bt_l2cap_chan *chan,
4620 				  uint8_t hci_status)
4621 {
4622 	struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan.chan);
4623 	struct bt_conn *conn = chan->conn;
4624 
4625 	LOG_DBG("chan %p conn %p handle %u encrypt 0x%02x hci status 0x%02x", chan, conn,
4626 		conn->handle, conn->encrypt, hci_status);
4627 
4628 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_ENC_PENDING)) {
4629 		/* We where not waiting for encryption procedure.
4630 		 * This happens when encrypt change is called to notify that
4631 		 * security has failed before starting encryption.
4632 		 */
4633 		return;
4634 	}
4635 
4636 	if (hci_status) {
4637 		if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
4638 			uint8_t smp_err = smp_err_get(
4639 				bt_security_err_get(hci_status));
4640 
4641 			/* Fail as if it happened during key distribution */
4642 			atomic_set_bit(smp->flags, SMP_FLAG_KEYS_DISTR);
4643 			smp_pairing_complete(smp, smp_err);
4644 		}
4645 
4646 		return;
4647 	}
4648 
4649 	if (!conn->encrypt) {
4650 		return;
4651 	}
4652 
4653 	/* We were waiting for encryption but with no pairing in progress.
4654 	 * This can happen if paired peripheral sent Security Request and we
4655 	 * enabled encryption.
4656 	 */
4657 	if (!atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
4658 		smp_reset(smp);
4659 		return;
4660 	}
4661 
4662 	/* derive BR/EDR LinkKey if supported by both sides */
4663 	if (atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
4664 		if ((smp->local_dist & BT_SMP_DIST_LINK_KEY) &&
4665 		    (smp->remote_dist & BT_SMP_DIST_LINK_KEY)) {
4666 			/*
4667 			 * Link Key will be derived after key distribution to
4668 			 * make sure remote device identity is known
4669 			 */
4670 			atomic_set_bit(smp->flags, SMP_FLAG_DERIVE_LK);
4671 		}
4672 		/*
4673 		 * Those are used as pairing finished indicator so generated
4674 		 * but not distributed keys must be cleared here.
4675 		 */
4676 		smp->local_dist &= ~BT_SMP_DIST_LINK_KEY;
4677 		smp->remote_dist &= ~BT_SMP_DIST_LINK_KEY;
4678 	}
4679 
4680 	if (smp->remote_dist & BT_SMP_DIST_ENC_KEY) {
4681 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_ENCRYPT_INFO);
4682 	} else if (smp->remote_dist & BT_SMP_DIST_ID_KEY) {
4683 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO);
4684 	} else if (smp->remote_dist & BT_SMP_DIST_SIGN) {
4685 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO);
4686 	}
4687 
4688 	/* This is the last point that is common for all code paths in the
4689 	 * pairing process (during which we still have the option to send
4690 	 * Pairing Failed). That makes it convenient to update the RL here. We
4691 	 * want to update the RL during the pairing process so that we can fail
4692 	 * it in case there is a conflict with an existing bond.
4693 	 *
4694 	 * We can do the update here only if the peer does not intend to send us
4695 	 * any identity information. In this case we already have everything
4696 	 * that goes into the RL.
4697 	 *
4698 	 * We need an entry in the RL despite the remote not using privacy. This
4699 	 * is because we are using privacy locally and need to associate correct
4700 	 * local IRK with the peer.
4701 	 *
4702 	 * If the peer does intend to send us identity information, we must wait
4703 	 * for that information to enter it in the RL. In that case, we call
4704 	 * `smp_id_add_replace` not here, but later. If neither we nor the peer
4705 	 * are using privacy, there is no need for an entry in the RL.
4706 	 */
4707 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
4708 	    IS_ENABLED(CONFIG_BT_PRIVACY) &&
4709 	    conn->role == BT_HCI_ROLE_CENTRAL &&
4710 	    !(smp->remote_dist & BT_SMP_DIST_ID_KEY)) {
4711 		uint8_t smp_err;
4712 
4713 		smp_err = smp_id_add_replace(smp, conn->le.keys);
4714 		if (smp_err) {
4715 			smp_pairing_complete(smp, smp_err);
4716 		}
4717 	}
4718 
4719 	atomic_set_bit(smp->flags, SMP_FLAG_KEYS_DISTR);
4720 
4721 	/* Peripheral distributes it's keys first */
4722 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
4723 	    conn->role == BT_HCI_ROLE_CENTRAL && smp->remote_dist) {
4724 		return;
4725 	}
4726 
4727 	if (IS_ENABLED(CONFIG_BT_TESTING)) {
4728 		/* Avoid the HCI-USB race condition where HCI data and
4729 		 * HCI events can be re-ordered, and pairing information appears
4730 		 * to be sent unencrypted.
4731 		 */
4732 		k_sleep(K_MSEC(100));
4733 	}
4734 
4735 	if (bt_smp_distribute_keys(smp)) {
4736 		return;
4737 	}
4738 
4739 	/* if all keys were distributed, pairing is done */
4740 	if (!smp->local_dist && !smp->remote_dist) {
4741 		smp_pairing_complete(smp, 0);
4742 	}
4743 }
4744 
4745 #if defined(CONFIG_BT_SIGNING) || defined(CONFIG_BT_SMP_SELFTEST)
4746 /* Sign message using msg as a buffer, len is a size of the message,
4747  * msg buffer contains message itself, 32 bit count and signature,
4748  * so total buffer size is len + 4 + 8 octets.
4749  * API is Little Endian to make it suitable for Bluetooth.
4750  */
smp_sign_buf(const uint8_t * key,uint8_t * msg,uint16_t len)4751 static int smp_sign_buf(const uint8_t *key, uint8_t *msg, uint16_t len)
4752 {
4753 	uint8_t *m = msg;
4754 	uint32_t cnt = UNALIGNED_GET((uint32_t *)&msg[len]);
4755 	uint8_t *sig = msg + len;
4756 	uint8_t key_s[16], tmp[16];
4757 	int err;
4758 
4759 	LOG_DBG("Signing msg %s len %u key %s", bt_hex(msg, len), len, bt_hex(key, 16));
4760 
4761 	sys_mem_swap(m, len + sizeof(cnt));
4762 	sys_memcpy_swap(key_s, key, 16);
4763 
4764 	err = bt_crypto_aes_cmac(key_s, m, len + sizeof(cnt), tmp);
4765 	if (err) {
4766 		LOG_ERR("Data signing failed");
4767 		return err;
4768 	}
4769 
4770 	sys_mem_swap(tmp, sizeof(tmp));
4771 	memcpy(tmp + 4, &cnt, sizeof(cnt));
4772 
4773 	/* Swap original message back */
4774 	sys_mem_swap(m, len + sizeof(cnt));
4775 
4776 	memcpy(sig, tmp + 4, 12);
4777 
4778 	LOG_DBG("sig %s", bt_hex(sig, 12));
4779 
4780 	return 0;
4781 }
4782 #endif
4783 
4784 #if defined(CONFIG_BT_SIGNING)
bt_smp_sign_verify(struct bt_conn * conn,struct net_buf * buf)4785 int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf)
4786 {
4787 	struct bt_keys *keys;
4788 	uint8_t sig[12];
4789 	uint32_t cnt;
4790 	int err;
4791 
4792 	/* Store signature incl. count */
4793 	memcpy(sig, net_buf_tail(buf) - sizeof(sig), sizeof(sig));
4794 
4795 	keys = bt_keys_find(BT_KEYS_REMOTE_CSRK, conn->id, &conn->le.dst);
4796 	if (!keys) {
4797 		LOG_ERR("Unable to find Remote CSRK for %s", bt_addr_le_str(&conn->le.dst));
4798 		return -ENOENT;
4799 	}
4800 
4801 	/* Copy signing count */
4802 	cnt = sys_cpu_to_le32(keys->remote_csrk.cnt);
4803 	memcpy(net_buf_tail(buf) - sizeof(sig), &cnt, sizeof(cnt));
4804 
4805 	LOG_DBG("Sign data len %zu key %s count %u", buf->len - sizeof(sig),
4806 		bt_hex(keys->remote_csrk.val, 16), keys->remote_csrk.cnt);
4807 
4808 	err = smp_sign_buf(keys->remote_csrk.val, buf->data,
4809 			   buf->len - sizeof(sig));
4810 	if (err) {
4811 		LOG_ERR("Unable to create signature for %s", bt_addr_le_str(&conn->le.dst));
4812 		return -EIO;
4813 	}
4814 
4815 	if (memcmp(sig, net_buf_tail(buf) - sizeof(sig), sizeof(sig))) {
4816 		LOG_ERR("Unable to verify signature for %s", bt_addr_le_str(&conn->le.dst));
4817 		return -EBADMSG;
4818 	}
4819 
4820 	keys->remote_csrk.cnt++;
4821 
4822 	return 0;
4823 }
4824 
bt_smp_sign(struct bt_conn * conn,struct net_buf * buf)4825 int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf)
4826 {
4827 	struct bt_keys *keys;
4828 	uint32_t cnt;
4829 	int err;
4830 
4831 	keys = bt_keys_find(BT_KEYS_LOCAL_CSRK, conn->id, &conn->le.dst);
4832 	if (!keys) {
4833 		LOG_ERR("Unable to find local CSRK for %s", bt_addr_le_str(&conn->le.dst));
4834 		return -ENOENT;
4835 	}
4836 
4837 	/* Reserve space for data signature */
4838 	net_buf_add(buf, 12);
4839 
4840 	/* Copy signing count */
4841 	cnt = sys_cpu_to_le32(keys->local_csrk.cnt);
4842 	memcpy(net_buf_tail(buf) - 12, &cnt, sizeof(cnt));
4843 
4844 	LOG_DBG("Sign data len %u key %s count %u", buf->len, bt_hex(keys->local_csrk.val, 16),
4845 		keys->local_csrk.cnt);
4846 
4847 	err = smp_sign_buf(keys->local_csrk.val, buf->data, buf->len - 12);
4848 	if (err) {
4849 		LOG_ERR("Unable to create signature for %s", bt_addr_le_str(&conn->le.dst));
4850 		return -EIO;
4851 	}
4852 
4853 	keys->local_csrk.cnt++;
4854 
4855 	return 0;
4856 }
4857 #else
bt_smp_sign_verify(struct bt_conn * conn,struct net_buf * buf)4858 int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf)
4859 {
4860 	return -ENOTSUP;
4861 }
4862 
bt_smp_sign(struct bt_conn * conn,struct net_buf * buf)4863 int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf)
4864 {
4865 	return -ENOTSUP;
4866 }
4867 #endif /* CONFIG_BT_SIGNING */
4868 
smp_d1(const uint8_t * key,uint16_t d,uint16_t r,uint8_t res[16])4869 static int smp_d1(const uint8_t *key, uint16_t d, uint16_t r, uint8_t res[16])
4870 {
4871 	int err;
4872 
4873 	LOG_DBG("key %s d %u r %u", bt_hex(key, 16), d, r);
4874 
4875 	sys_put_le16(d, &res[0]);
4876 	sys_put_le16(r, &res[2]);
4877 	memset(&res[4], 0, 16 - 4);
4878 
4879 	err = bt_encrypt_le(key, res, res);
4880 	if (err) {
4881 		return err;
4882 	}
4883 
4884 	LOG_DBG("res %s", bt_hex(res, 16));
4885 	return 0;
4886 }
4887 
bt_smp_irk_get(uint8_t * ir,uint8_t * irk)4888 int bt_smp_irk_get(uint8_t *ir, uint8_t *irk)
4889 {
4890 	uint8_t invalid_ir[16] = { 0 };
4891 
4892 	if (!memcmp(ir, invalid_ir, 16)) {
4893 		return -EINVAL;
4894 	}
4895 
4896 	return smp_d1(ir, 1, 0, irk);
4897 }
4898 
4899 #if defined(CONFIG_BT_SMP_SELFTEST)
4900 /* Test vectors are taken from RFC 4493
4901  * https://tools.ietf.org/html/rfc4493
4902  * Same mentioned in the Bluetooth Spec.
4903  */
4904 static const uint8_t key[] = {
4905 	0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
4906 	0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c
4907 };
4908 
4909 static const uint8_t M[] = {
4910 	0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96,
4911 	0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
4912 	0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c,
4913 	0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
4914 	0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11,
4915 	0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
4916 	0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17,
4917 	0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10
4918 };
4919 
aes_test(const char * prefix,const uint8_t * in_key,const uint8_t * m,uint16_t len,const uint8_t * mac)4920 static int aes_test(const char *prefix, const uint8_t *in_key, const uint8_t *m,
4921 		    uint16_t len, const uint8_t *mac)
4922 {
4923 	uint8_t out[16];
4924 
4925 	LOG_DBG("%s: AES CMAC of message with len %u", prefix, len);
4926 
4927 	bt_crypto_aes_cmac(in_key, m, len, out);
4928 	if (!memcmp(out, mac, 16)) {
4929 		LOG_DBG("%s: Success", prefix);
4930 	} else {
4931 		LOG_ERR("%s: Failed", prefix);
4932 		return -1;
4933 	}
4934 
4935 	return 0;
4936 }
4937 
smp_aes_cmac_test(void)4938 static int smp_aes_cmac_test(void)
4939 {
4940 	uint8_t mac1[] = {
4941 		0xbb, 0x1d, 0x69, 0x29, 0xe9, 0x59, 0x37, 0x28,
4942 		0x7f, 0xa3, 0x7d, 0x12, 0x9b, 0x75, 0x67, 0x46
4943 	};
4944 	uint8_t mac2[] = {
4945 		0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44,
4946 		0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a, 0x28, 0x7c
4947 	};
4948 	uint8_t mac3[] = {
4949 		0xdf, 0xa6, 0x67, 0x47, 0xde, 0x9a, 0xe6, 0x30,
4950 		0x30, 0xca, 0x32, 0x61, 0x14, 0x97, 0xc8, 0x27
4951 	};
4952 	uint8_t mac4[] = {
4953 		0x51, 0xf0, 0xbe, 0xbf, 0x7e, 0x3b, 0x9d, 0x92,
4954 		0xfc, 0x49, 0x74, 0x17, 0x79, 0x36, 0x3c, 0xfe
4955 	};
4956 	int err;
4957 
4958 	err = aes_test("Test aes-cmac0", key, M, 0, mac1);
4959 	if (err) {
4960 		return err;
4961 	}
4962 
4963 	err = aes_test("Test aes-cmac16", key, M, 16, mac2);
4964 	if (err) {
4965 		return err;
4966 	}
4967 
4968 	err = aes_test("Test aes-cmac40", key, M, 40, mac3);
4969 	if (err) {
4970 		return err;
4971 	}
4972 
4973 	err = aes_test("Test aes-cmac64", key, M, 64, mac4);
4974 	if (err) {
4975 		return err;
4976 	}
4977 
4978 	return 0;
4979 }
4980 
sign_test(const char * prefix,const uint8_t * sign_key,const uint8_t * m,uint16_t len,const uint8_t * sig)4981 static int sign_test(const char *prefix, const uint8_t *sign_key, const uint8_t *m,
4982 		     uint16_t len, const uint8_t *sig)
4983 {
4984 	uint8_t msg[len + sizeof(uint32_t) + 8];
4985 	uint8_t orig[len + sizeof(uint32_t) + 8];
4986 	uint8_t *out = msg + len;
4987 	int err;
4988 
4989 	LOG_DBG("%s: Sign message with len %u", prefix, len);
4990 
4991 	(void)memset(msg, 0, sizeof(msg));
4992 	memcpy(msg, m, len);
4993 	(void)memset(msg + len, 0, sizeof(uint32_t));
4994 
4995 	memcpy(orig, msg, sizeof(msg));
4996 
4997 	err = smp_sign_buf(sign_key, msg, len);
4998 	if (err) {
4999 		return err;
5000 	}
5001 
5002 	/* Check original message */
5003 	if (!memcmp(msg, orig, len + sizeof(uint32_t))) {
5004 		LOG_DBG("%s: Original message intact", prefix);
5005 	} else {
5006 		LOG_ERR("%s: Original message modified", prefix);
5007 		LOG_DBG("%s: orig %s", prefix, bt_hex(orig, sizeof(orig)));
5008 		LOG_DBG("%s: msg %s", prefix, bt_hex(msg, sizeof(msg)));
5009 		return -1;
5010 	}
5011 
5012 	if (!memcmp(out, sig, 12)) {
5013 		LOG_DBG("%s: Success", prefix);
5014 	} else {
5015 		LOG_ERR("%s: Failed", prefix);
5016 		return -1;
5017 	}
5018 
5019 	return 0;
5020 }
5021 
smp_sign_test(void)5022 static int smp_sign_test(void)
5023 {
5024 	const uint8_t sig1[] = {
5025 		0x00, 0x00, 0x00, 0x00, 0xb3, 0xa8, 0x59, 0x41,
5026 		0x27, 0xeb, 0xc2, 0xc0
5027 	};
5028 	const uint8_t sig2[] = {
5029 		0x00, 0x00, 0x00, 0x00, 0x27, 0x39, 0x74, 0xf4,
5030 		0x39, 0x2a, 0x23, 0x2a
5031 	};
5032 	const uint8_t sig3[] = {
5033 		0x00, 0x00, 0x00, 0x00, 0xb7, 0xca, 0x94, 0xab,
5034 		0x87, 0xc7, 0x82, 0x18
5035 	};
5036 	const uint8_t sig4[] = {
5037 		0x00, 0x00, 0x00, 0x00, 0x44, 0xe1, 0xe6, 0xce,
5038 		0x1d, 0xf5, 0x13, 0x68
5039 	};
5040 	uint8_t key_s[16];
5041 	int err;
5042 
5043 	/* Use the same key as aes-cmac but swap bytes */
5044 	sys_memcpy_swap(key_s, key, 16);
5045 
5046 	err = sign_test("Test sign0", key_s, M, 0, sig1);
5047 	if (err) {
5048 		return err;
5049 	}
5050 
5051 	err = sign_test("Test sign16", key_s, M, 16, sig2);
5052 	if (err) {
5053 		return err;
5054 	}
5055 
5056 	err = sign_test("Test sign40", key_s, M, 40, sig3);
5057 	if (err) {
5058 		return err;
5059 	}
5060 
5061 	err = sign_test("Test sign64", key_s, M, 64, sig4);
5062 	if (err) {
5063 		return err;
5064 	}
5065 
5066 	return 0;
5067 }
5068 
smp_f4_test(void)5069 static int smp_f4_test(void)
5070 {
5071 	uint8_t u[32] = { 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc,
5072 			  0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef,
5073 			  0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
5074 			  0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 };
5075 	uint8_t v[32] = { 0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b,
5076 			  0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59,
5077 			  0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90,
5078 			  0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 };
5079 	uint8_t x[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
5080 			  0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
5081 	uint8_t z = 0x00;
5082 	uint8_t exp[16] = { 0x2d, 0x87, 0x74, 0xa9, 0xbe, 0xa1, 0xed, 0xf1,
5083 			    0x1c, 0xbd, 0xa9, 0x07, 0xf1, 0x16, 0xc9, 0xf2 };
5084 	uint8_t res[16];
5085 	int err;
5086 
5087 	err = bt_crypto_f4(u, v, x, z, res);
5088 	if (err) {
5089 		return err;
5090 	}
5091 
5092 	if (memcmp(res, exp, 16)) {
5093 		return -EINVAL;
5094 	}
5095 
5096 	return 0;
5097 }
5098 
smp_f5_test(void)5099 static int smp_f5_test(void)
5100 {
5101 	uint8_t w[32] = { 0x98, 0xa6, 0xbf, 0x73, 0xf3, 0x34, 0x8d, 0x86,
5102 			  0xf1, 0x66, 0xf8, 0xb4, 0x13, 0x6b, 0x79, 0x99,
5103 			  0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
5104 			  0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
5105 	uint8_t n1[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
5106 			   0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
5107 	uint8_t n2[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
5108 			   0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
5109 	bt_addr_le_t a1 = { .type = 0x00,
5110 			    .a.val = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56 } };
5111 	bt_addr_le_t a2 = { .type = 0x00,
5112 			    .a.val = {0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7 } };
5113 	uint8_t exp_ltk[16] = { 0x38, 0x0a, 0x75, 0x94, 0xb5, 0x22, 0x05,
5114 				0x98, 0x23, 0xcd, 0xd7, 0x69, 0x11, 0x79,
5115 				0x86, 0x69 };
5116 	uint8_t exp_mackey[16] = { 0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f,
5117 				   0xfd, 0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1,
5118 				   0x65, 0x29 };
5119 	uint8_t mackey[16], ltk[16];
5120 	int err;
5121 
5122 	err = bt_crypto_f5(w, n1, n2, &a1, &a2, mackey, ltk);
5123 	if (err) {
5124 		return err;
5125 	}
5126 
5127 	if (memcmp(mackey, exp_mackey, 16) || memcmp(ltk, exp_ltk, 16)) {
5128 		return -EINVAL;
5129 	}
5130 
5131 	return 0;
5132 }
5133 
smp_f6_test(void)5134 static int smp_f6_test(void)
5135 {
5136 	uint8_t w[16] = { 0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f, 0xfd,
5137 			  0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1, 0x65, 0x29 };
5138 	uint8_t n1[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
5139 			   0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
5140 	uint8_t n2[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
5141 			   0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
5142 	uint8_t r[16] = { 0xc8, 0x0f, 0x2d, 0x0c, 0xd2, 0x42, 0xda, 0x08,
5143 			  0x54, 0xbb, 0x53, 0xb4, 0x3b, 0x34, 0xa3, 0x12 };
5144 	uint8_t io_cap[3] = { 0x02, 0x01, 0x01 };
5145 	bt_addr_le_t a1 = { .type = 0x00,
5146 			    .a.val = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56 } };
5147 	bt_addr_le_t a2 = { .type = 0x00,
5148 			    .a.val = {0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7 } };
5149 	uint8_t exp[16] = { 0x61, 0x8f, 0x95, 0xda, 0x09, 0x0b, 0x6c, 0xd2,
5150 			    0xc5, 0xe8, 0xd0, 0x9c, 0x98, 0x73, 0xc4, 0xe3 };
5151 	uint8_t res[16];
5152 	int err;
5153 
5154 	err = bt_crypto_f6(w, n1, n2, r, io_cap, &a1, &a2, res);
5155 	if (err)
5156 		return err;
5157 
5158 	if (memcmp(res, exp, 16))
5159 		return -EINVAL;
5160 
5161 	return 0;
5162 }
5163 
smp_g2_test(void)5164 static int smp_g2_test(void)
5165 {
5166 	uint8_t u[32] = { 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc,
5167 			  0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef,
5168 			  0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
5169 			  0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 };
5170 	uint8_t v[32] = { 0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b,
5171 			  0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59,
5172 			  0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90,
5173 			  0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 };
5174 	uint8_t x[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
5175 			  0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
5176 	uint8_t y[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
5177 			  0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
5178 	uint32_t exp_val = 0x2f9ed5ba % 1000000;
5179 	uint32_t val;
5180 	int err;
5181 
5182 	err = bt_crypto_g2(u, v, x, y, &val);
5183 	if (err) {
5184 		return err;
5185 	}
5186 
5187 	if (val != exp_val) {
5188 		return -EINVAL;
5189 	}
5190 
5191 	return 0;
5192 }
5193 
5194 #if defined(CONFIG_BT_BREDR)
smp_h6_test(void)5195 static int smp_h6_test(void)
5196 {
5197 	uint8_t w[16] = { 0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
5198 			  0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
5199 	uint8_t key_id[4] = { 0x72, 0x62, 0x65, 0x6c };
5200 	uint8_t exp_res[16] = { 0x99, 0x63, 0xb1, 0x80, 0xe2, 0xa9, 0xd3, 0xe8,
5201 				0x1c, 0xc9, 0x6d, 0xe7, 0x02, 0xe1, 0x9a, 0x2d};
5202 	uint8_t res[16];
5203 	int err;
5204 
5205 	err = bt_crypto_h6(w, key_id, res);
5206 	if (err) {
5207 		return err;
5208 	}
5209 
5210 	if (memcmp(res, exp_res, 16)) {
5211 		return -EINVAL;
5212 	}
5213 
5214 	return 0;
5215 }
5216 
smp_h7_test(void)5217 static int smp_h7_test(void)
5218 {
5219 	uint8_t salt[16] = { 0x31, 0x70, 0x6d, 0x74, 0x00, 0x00, 0x00, 0x00,
5220 			     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
5221 	uint8_t w[16] = { 0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
5222 			  0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
5223 	uint8_t exp_res[16] = { 0x11, 0x70, 0xa5, 0x75, 0x2a, 0x8c, 0x99, 0xd2,
5224 				0xec, 0xc0, 0xa3, 0xc6, 0x97, 0x35, 0x17, 0xfb};
5225 	uint8_t res[16];
5226 	int err;
5227 
5228 	err = bt_crypto_h7(salt, w, res);
5229 	if (err) {
5230 		return err;
5231 	}
5232 
5233 	if (memcmp(res, exp_res, 16)) {
5234 		return -EINVAL;
5235 	}
5236 
5237 	return 0;
5238 }
5239 #endif /* CONFIG_BT_BREDR */
5240 
smp_h8_test(void)5241 static int smp_h8_test(void)
5242 {
5243 	uint8_t k[16] = {0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05,
5244 			 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b};
5245 	uint8_t s[16] = {0x15, 0x36, 0xd1, 0x8d, 0xe3, 0xd2, 0x0d, 0xf9,
5246 			 0x9b, 0x70, 0x44, 0xc1, 0x2f, 0x9e, 0xd5, 0xba};
5247 	uint8_t key_id[4] = {0xcc, 0x03, 0x01, 0x48};
5248 
5249 	uint8_t exp_res[16] = {0xe5, 0xe5, 0xbe, 0xba, 0xae, 0x72, 0x28, 0xe7,
5250 			       0x22, 0xa3, 0x89, 0x04, 0xed, 0x35, 0x0f, 0x6d};
5251 	uint8_t res[16];
5252 	int err;
5253 
5254 	err = bt_crypto_h8(k, s, key_id, res);
5255 	if (err) {
5256 		return err;
5257 	}
5258 
5259 	if (memcmp(res, exp_res, 16)) {
5260 		return -EINVAL;
5261 	}
5262 
5263 	return 0;
5264 }
5265 
smp_self_test(void)5266 static int smp_self_test(void)
5267 {
5268 	int err;
5269 
5270 	err = smp_aes_cmac_test();
5271 	if (err) {
5272 		LOG_ERR("SMP AES-CMAC self tests failed");
5273 		return err;
5274 	}
5275 
5276 	err = smp_sign_test();
5277 	if (err) {
5278 		LOG_ERR("SMP signing self tests failed");
5279 		return err;
5280 	}
5281 
5282 	err = smp_f4_test();
5283 	if (err) {
5284 		LOG_ERR("SMP f4 self test failed");
5285 		return err;
5286 	}
5287 
5288 	err = smp_f5_test();
5289 	if (err) {
5290 		LOG_ERR("SMP f5 self test failed");
5291 		return err;
5292 	}
5293 
5294 	err = smp_f6_test();
5295 	if (err) {
5296 		LOG_ERR("SMP f6 self test failed");
5297 		return err;
5298 	}
5299 
5300 	err = smp_g2_test();
5301 	if (err) {
5302 		LOG_ERR("SMP g2 self test failed");
5303 		return err;
5304 	}
5305 
5306 #if defined(CONFIG_BT_BREDR)
5307 	err = smp_h6_test();
5308 	if (err) {
5309 		LOG_ERR("SMP h6 self test failed");
5310 		return err;
5311 	}
5312 
5313 	err = smp_h7_test();
5314 	if (err) {
5315 		LOG_ERR("SMP h7 self test failed");
5316 		return err;
5317 	}
5318 #endif /* CONFIG_BT_BREDR */
5319 	err = smp_h8_test();
5320 	if (err) {
5321 		LOG_ERR("SMP h8 self test failed");
5322 		return err;
5323 	}
5324 
5325 	return 0;
5326 }
5327 #else
smp_self_test(void)5328 static inline int smp_self_test(void)
5329 {
5330 	return 0;
5331 }
5332 #endif
5333 
5334 #if defined(CONFIG_BT_BONDABLE_PER_CONNECTION)
bt_conn_set_bondable(struct bt_conn * conn,bool enable)5335 int bt_conn_set_bondable(struct bt_conn *conn, bool enable)
5336 {
5337 	struct bt_smp *smp;
5338 
5339 	smp = smp_chan_get(conn);
5340 	if (!smp) {
5341 		return -EINVAL;
5342 	}
5343 
5344 	if (atomic_cas(&smp->bondable, BT_SMP_BONDABLE_UNINITIALIZED, (atomic_val_t)enable)) {
5345 		return 0;
5346 	} else {
5347 		return -EALREADY;
5348 	}
5349 }
5350 #endif
5351 
bt_smp_auth_cb_overlay(struct bt_conn * conn,const struct bt_conn_auth_cb * cb)5352 int bt_smp_auth_cb_overlay(struct bt_conn *conn, const struct bt_conn_auth_cb *cb)
5353 {
5354 	struct bt_smp *smp;
5355 
5356 	smp = smp_chan_get(conn);
5357 	if (!smp) {
5358 		return -EINVAL;
5359 	}
5360 
5361 	if (atomic_ptr_cas(&smp->auth_cb, BT_SMP_AUTH_CB_UNINITIALIZED, (atomic_ptr_val_t)cb)) {
5362 		return 0;
5363 	} else {
5364 		return -EALREADY;
5365 	}
5366 }
5367 
5368 #if defined(CONFIG_BT_PASSKEY_KEYPRESS)
smp_send_keypress_notif(struct bt_smp * smp,uint8_t type)5369 static int smp_send_keypress_notif(struct bt_smp *smp, uint8_t type)
5370 {
5371 	struct bt_smp_keypress_notif *req;
5372 	struct net_buf *buf;
5373 
5374 	buf = smp_create_pdu(smp, BT_SMP_KEYPRESS_NOTIFICATION, sizeof(*req));
5375 	if (!buf) {
5376 		return -ENOMEM;
5377 	}
5378 
5379 	req = net_buf_add(buf, sizeof(*req));
5380 	req->type = type;
5381 
5382 	smp_send(smp, buf, NULL, NULL);
5383 
5384 	return 0;
5385 }
5386 #endif
5387 
5388 #if defined(CONFIG_BT_PASSKEY_KEYPRESS)
bt_smp_auth_keypress_notify(struct bt_conn * conn,enum bt_conn_auth_keypress type)5389 int bt_smp_auth_keypress_notify(struct bt_conn *conn, enum bt_conn_auth_keypress type)
5390 {
5391 	struct bt_smp *smp;
5392 
5393 	smp = smp_chan_get(conn);
5394 	if (!smp) {
5395 		return -EINVAL;
5396 	}
5397 
5398 	CHECKIF(!IN_RANGE(type,
5399 			  BT_CONN_AUTH_KEYPRESS_ENTRY_STARTED,
5400 			  BT_CONN_AUTH_KEYPRESS_ENTRY_COMPLETED)) {
5401 		LOG_ERR("Refusing to send unknown event type %u", type);
5402 		return -EINVAL;
5403 	}
5404 
5405 	if (smp->method != PASSKEY_INPUT ||
5406 	    !atomic_test_bit(smp->flags, SMP_FLAG_USER)) {
5407 		LOG_ERR("Refusing to send keypress: Not waiting for passkey input.");
5408 		return -EINVAL;
5409 	}
5410 
5411 	return smp_send_keypress_notif(smp, type);
5412 }
5413 #endif
5414 
bt_smp_auth_passkey_entry(struct bt_conn * conn,unsigned int passkey)5415 int bt_smp_auth_passkey_entry(struct bt_conn *conn, unsigned int passkey)
5416 {
5417 	struct bt_smp *smp;
5418 	uint8_t err;
5419 
5420 	smp = smp_chan_get(conn);
5421 	if (!smp) {
5422 		return -EINVAL;
5423 	}
5424 
5425 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) {
5426 		return -EINVAL;
5427 	}
5428 
5429 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
5430 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
5431 		legacy_passkey_entry(smp, passkey);
5432 		return 0;
5433 	}
5434 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
5435 
5436 	smp->passkey = sys_cpu_to_le32(passkey);
5437 
5438 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
5439 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
5440 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM);
5441 		err = smp_send_pairing_confirm(smp);
5442 		if (err) {
5443 			smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED);
5444 			return 0;
5445 		}
5446 		return 0;
5447 	}
5448 
5449 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
5450 	    atomic_test_bit(smp->flags, SMP_FLAG_CFM_DELAYED)) {
5451 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
5452 		err = smp_send_pairing_confirm(smp);
5453 		if (err) {
5454 			smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED);
5455 			return 0;
5456 		}
5457 	}
5458 
5459 	return 0;
5460 }
5461 
bt_smp_auth_passkey_confirm(struct bt_conn * conn)5462 int bt_smp_auth_passkey_confirm(struct bt_conn *conn)
5463 {
5464 	struct bt_smp *smp;
5465 
5466 	smp = smp_chan_get(conn);
5467 	if (!smp) {
5468 		return -EINVAL;
5469 	}
5470 
5471 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) {
5472 		return -EINVAL;
5473 	}
5474 
5475 	/* wait for DHKey being generated */
5476 	if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) {
5477 		atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
5478 		return 0;
5479 	}
5480 
5481 	/* wait for remote DHKey Check */
5482 	if (atomic_test_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT)) {
5483 		atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND);
5484 		return 0;
5485 	}
5486 
5487 	if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_SEND)) {
5488 		uint8_t err;
5489 
5490 #if defined(CONFIG_BT_CENTRAL)
5491 		if (smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
5492 			err = compute_and_send_central_dhcheck(smp);
5493 			if (err) {
5494 				smp_error(smp, err);
5495 			}
5496 			return 0;
5497 		}
5498 #endif /* CONFIG_BT_CENTRAL */
5499 
5500 #if defined(CONFIG_BT_PERIPHERAL)
5501 		err = compute_and_check_and_send_periph_dhcheck(smp);
5502 		if (err) {
5503 			smp_error(smp, err);
5504 		}
5505 #endif /* CONFIG_BT_PERIPHERAL */
5506 	}
5507 
5508 	return 0;
5509 }
5510 
5511 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
bt_smp_le_oob_set_tk(struct bt_conn * conn,const uint8_t * tk)5512 int bt_smp_le_oob_set_tk(struct bt_conn *conn, const uint8_t *tk)
5513 {
5514 	struct bt_smp *smp;
5515 
5516 	smp = smp_chan_get(conn);
5517 	if (!smp || !tk) {
5518 		return -EINVAL;
5519 	}
5520 
5521 	LOG_DBG("%s", bt_hex(tk, 16));
5522 
5523 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) {
5524 		return -EINVAL;
5525 	}
5526 
5527 	if (IS_ENABLED(CONFIG_BT_LOG_SNIFFER_INFO)) {
5528 		uint8_t oob[16];
5529 
5530 		sys_memcpy_swap(oob, tk, 16);
5531 		LOG_INF("Legacy OOB data 0x%s", bt_hex(oob, 16));
5532 	}
5533 
5534 	memcpy(smp->tk, tk, 16*sizeof(uint8_t));
5535 
5536 	legacy_user_tk_entry(smp);
5537 
5538 	return 0;
5539 }
5540 #endif /* !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) */
5541 
bt_smp_le_oob_generate_sc_data(struct bt_le_oob_sc_data * le_sc_oob)5542 int bt_smp_le_oob_generate_sc_data(struct bt_le_oob_sc_data *le_sc_oob)
5543 {
5544 	int err;
5545 
5546 	if (!le_sc_supported()) {
5547 		return -ENOTSUP;
5548 	}
5549 
5550 	if (!sc_public_key) {
5551 		err = k_sem_take(&sc_local_pkey_ready, K_FOREVER);
5552 		if (err) {
5553 			return err;
5554 		}
5555 	}
5556 
5557 	if (IS_ENABLED(CONFIG_BT_OOB_DATA_FIXED)) {
5558 		uint8_t rand_num[] = {
5559 			0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
5560 			0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
5561 		};
5562 
5563 		memcpy(le_sc_oob->r, rand_num, sizeof(le_sc_oob->r));
5564 	} else {
5565 		err = bt_rand(le_sc_oob->r, 16);
5566 		if (err) {
5567 			return err;
5568 		}
5569 	}
5570 
5571 	err = bt_crypto_f4(sc_public_key, sc_public_key, le_sc_oob->r, 0,
5572 		     le_sc_oob->c);
5573 	if (err) {
5574 		return err;
5575 	}
5576 
5577 	return 0;
5578 }
5579 
5580 #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)5581 static bool le_sc_oob_data_check(struct bt_smp *smp, bool oobd_local_present,
5582 				 bool oobd_remote_present)
5583 {
5584 	bool req_oob_present = le_sc_oob_data_req_check(smp);
5585 	bool rsp_oob_present = le_sc_oob_data_rsp_check(smp);
5586 
5587 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
5588 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
5589 		if ((req_oob_present != oobd_remote_present) &&
5590 		    (rsp_oob_present != oobd_local_present)) {
5591 			return false;
5592 		}
5593 	} else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
5594 		if ((req_oob_present != oobd_local_present) &&
5595 		    (rsp_oob_present != oobd_remote_present)) {
5596 			return false;
5597 		}
5598 	}
5599 
5600 	return true;
5601 }
5602 
le_sc_oob_pairing_continue(struct bt_smp * smp)5603 static int le_sc_oob_pairing_continue(struct bt_smp *smp)
5604 {
5605 	if (smp->oobd_remote) {
5606 		int err;
5607 		uint8_t c[16];
5608 
5609 		err = bt_crypto_f4(smp->pkey, smp->pkey, smp->oobd_remote->r, 0, c);
5610 		if (err) {
5611 			return err;
5612 		}
5613 
5614 		bool match = (memcmp(c, smp->oobd_remote->c, sizeof(c)) == 0);
5615 
5616 		if (!match) {
5617 			smp_error(smp, BT_SMP_ERR_CONFIRM_FAILED);
5618 			return 0;
5619 		}
5620 	}
5621 
5622 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
5623 	    smp->chan.chan.conn->role == BT_HCI_ROLE_CENTRAL) {
5624 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM);
5625 	} else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
5626 		atomic_set_bit(smp->allowed_cmds, BT_SMP_DHKEY_CHECK);
5627 		atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT);
5628 	}
5629 
5630 	return smp_send_pairing_random(smp);
5631 }
5632 
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)5633 int bt_smp_le_oob_set_sc_data(struct bt_conn *conn,
5634 			      const struct bt_le_oob_sc_data *oobd_local,
5635 			      const struct bt_le_oob_sc_data *oobd_remote)
5636 {
5637 	struct bt_smp *smp;
5638 
5639 	smp = smp_chan_get(conn);
5640 	if (!smp) {
5641 		return -EINVAL;
5642 	}
5643 
5644 	if (!le_sc_oob_data_check(smp, (oobd_local != NULL),
5645 				  (oobd_remote != NULL))) {
5646 		return -EINVAL;
5647 	}
5648 
5649 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_OOB_PENDING)) {
5650 		return -EINVAL;
5651 	}
5652 
5653 	smp->oobd_local = oobd_local;
5654 	smp->oobd_remote = oobd_remote;
5655 
5656 	return le_sc_oob_pairing_continue(smp);
5657 }
5658 
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)5659 int bt_smp_le_oob_get_sc_data(struct bt_conn *conn,
5660 			      const struct bt_le_oob_sc_data **oobd_local,
5661 			      const struct bt_le_oob_sc_data **oobd_remote)
5662 {
5663 	struct bt_smp *smp;
5664 
5665 	smp = smp_chan_get(conn);
5666 	if (!smp) {
5667 		return -EINVAL;
5668 	}
5669 
5670 	if (!smp->oobd_local && !smp->oobd_remote) {
5671 		return -ESRCH;
5672 	}
5673 
5674 	if (oobd_local) {
5675 		*oobd_local = smp->oobd_local;
5676 	}
5677 
5678 	if (oobd_remote) {
5679 		*oobd_remote = smp->oobd_remote;
5680 	}
5681 
5682 	return 0;
5683 }
5684 #endif /* !CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY */
5685 
bt_smp_auth_cancel(struct bt_conn * conn)5686 int bt_smp_auth_cancel(struct bt_conn *conn)
5687 {
5688 	struct bt_smp *smp;
5689 
5690 	smp = smp_chan_get(conn);
5691 	if (!smp) {
5692 		return -EINVAL;
5693 	}
5694 
5695 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) {
5696 		return -EINVAL;
5697 	}
5698 
5699 	LOG_DBG("");
5700 
5701 	switch (smp->method) {
5702 	case PASSKEY_INPUT:
5703 	case PASSKEY_DISPLAY:
5704 		return smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED);
5705 	case PASSKEY_CONFIRM:
5706 		return smp_error(smp, BT_SMP_ERR_CONFIRM_FAILED);
5707 	case LE_SC_OOB:
5708 	case LEGACY_OOB:
5709 		return smp_error(smp, BT_SMP_ERR_OOB_NOT_AVAIL);
5710 	case JUST_WORKS:
5711 		return smp_error(smp, BT_SMP_ERR_UNSPECIFIED);
5712 	default:
5713 		LOG_ERR("Unknown pairing method (%u)", smp->method);
5714 		return 0;
5715 	}
5716 }
5717 
5718 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
bt_smp_auth_pairing_confirm(struct bt_conn * conn)5719 int bt_smp_auth_pairing_confirm(struct bt_conn *conn)
5720 {
5721 	struct bt_smp *smp;
5722 
5723 	smp = smp_chan_get(conn);
5724 	if (!smp) {
5725 		return -EINVAL;
5726 	}
5727 
5728 	if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) {
5729 		return -EINVAL;
5730 	}
5731 
5732 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
5733 	    conn->role == BT_CONN_ROLE_CENTRAL) {
5734 		if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
5735 			atomic_set_bit(smp->allowed_cmds,
5736 				       BT_SMP_CMD_PAIRING_CONFIRM);
5737 			return legacy_send_pairing_confirm(smp);
5738 		}
5739 
5740 		if (!sc_public_key) {
5741 			atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND);
5742 			return 0;
5743 		}
5744 
5745 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY);
5746 		return sc_send_public_key(smp);
5747 	}
5748 
5749 #if defined(CONFIG_BT_PERIPHERAL)
5750 	if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
5751 		atomic_set_bit(smp->allowed_cmds,
5752 			       BT_SMP_CMD_PAIRING_CONFIRM);
5753 		return send_pairing_rsp(smp);
5754 	}
5755 
5756 	atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY);
5757 	if (send_pairing_rsp(smp)) {
5758 		return -EIO;
5759 	}
5760 #endif /* CONFIG_BT_PERIPHERAL */
5761 
5762 	return 0;
5763 }
5764 #else
bt_smp_auth_pairing_confirm(struct bt_conn * conn)5765 int bt_smp_auth_pairing_confirm(struct bt_conn *conn)
5766 {
5767 	/* confirm_pairing will never be called in LE SC only mode */
5768 	return -EINVAL;
5769 }
5770 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
5771 
5772 #if defined(CONFIG_BT_FIXED_PASSKEY)
bt_passkey_set(unsigned int passkey)5773 int bt_passkey_set(unsigned int passkey)
5774 {
5775 	if (passkey == BT_PASSKEY_INVALID) {
5776 		fixed_passkey = BT_PASSKEY_INVALID;
5777 		return 0;
5778 	}
5779 
5780 	if (passkey > 999999) {
5781 		return -EINVAL;
5782 	}
5783 
5784 	fixed_passkey = passkey;
5785 	return 0;
5786 }
5787 #endif /* CONFIG_BT_FIXED_PASSKEY */
5788 
bt_smp_start_security(struct bt_conn * conn)5789 int bt_smp_start_security(struct bt_conn *conn)
5790 {
5791 	switch (conn->role) {
5792 #if defined(CONFIG_BT_CENTRAL)
5793 	case BT_HCI_ROLE_CENTRAL:
5794 	{
5795 		int err;
5796 		struct bt_smp *smp;
5797 
5798 		smp = smp_chan_get(conn);
5799 		if (!smp) {
5800 			return -ENOTCONN;
5801 		}
5802 
5803 		/* pairing is in progress */
5804 		if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
5805 			return -EBUSY;
5806 		}
5807 
5808 		/* Encryption is in progress */
5809 		if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) {
5810 			return -EBUSY;
5811 		}
5812 
5813 		if (!smp_keys_check(conn)) {
5814 			return smp_send_pairing_req(conn);
5815 		}
5816 
5817 		/* LE SC LTK and legacy central LTK are stored in same place */
5818 		err = bt_conn_le_start_encryption(conn,
5819 						  conn->le.keys->ltk.rand,
5820 						  conn->le.keys->ltk.ediv,
5821 						  conn->le.keys->ltk.val,
5822 						  conn->le.keys->enc_size);
5823 		if (err) {
5824 			return err;
5825 		}
5826 
5827 		atomic_set_bit(smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST);
5828 		atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING);
5829 		return 0;
5830 	}
5831 #endif /* CONFIG_BT_CENTRAL && CONFIG_BT_SMP */
5832 #if defined(CONFIG_BT_PERIPHERAL)
5833 	case BT_HCI_ROLE_PERIPHERAL:
5834 		return smp_send_security_req(conn);
5835 #endif /* CONFIG_BT_PERIPHERAL && CONFIG_BT_SMP */
5836 	default:
5837 		return -EINVAL;
5838 	}
5839 }
5840 
bt_smp_update_keys(struct bt_conn * conn)5841 void bt_smp_update_keys(struct bt_conn *conn)
5842 {
5843 	struct bt_smp *smp;
5844 
5845 	smp = smp_chan_get(conn);
5846 	if (!smp) {
5847 		return;
5848 	}
5849 
5850 	if (!atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) {
5851 		return;
5852 	}
5853 
5854 	/*
5855 	 * If link was successfully encrypted cleanup old keys as from now on
5856 	 * only keys distributed in this pairing or LTK from LE SC will be used.
5857 	 */
5858 	if (conn->le.keys) {
5859 		bt_keys_clear(conn->le.keys);
5860 	}
5861 
5862 	conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst);
5863 	if (!conn->le.keys) {
5864 		LOG_ERR("Unable to get keys for %s", bt_addr_le_str(&conn->le.dst));
5865 		smp_error(smp, BT_SMP_ERR_UNSPECIFIED);
5866 		return;
5867 	}
5868 
5869 	/* mark keys as debug */
5870 	if (atomic_test_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY)) {
5871 		conn->le.keys->flags |= BT_KEYS_DEBUG;
5872 	}
5873 
5874 	/*
5875 	 * store key type deducted from pairing method used
5876 	 * it is important to store it since type is used to determine
5877 	 * security level upon encryption
5878 	 */
5879 	switch (smp->method) {
5880 	case LE_SC_OOB:
5881 	case LEGACY_OOB:
5882 		conn->le.keys->flags |= BT_KEYS_OOB;
5883 		/* fallthrough */
5884 	case PASSKEY_DISPLAY:
5885 	case PASSKEY_INPUT:
5886 	case PASSKEY_CONFIRM:
5887 		conn->le.keys->flags |= BT_KEYS_AUTHENTICATED;
5888 		break;
5889 	case JUST_WORKS:
5890 	default:
5891 		/* unauthenticated key, clear it */
5892 		conn->le.keys->flags &= ~BT_KEYS_OOB;
5893 		conn->le.keys->flags &= ~BT_KEYS_AUTHENTICATED;
5894 		break;
5895 	}
5896 
5897 	conn->le.keys->enc_size = get_encryption_key_size(smp);
5898 
5899 	/*
5900 	 * Store LTK if LE SC is used, this is safe since LE SC is mutually
5901 	 * exclusive with legacy pairing. Other keys are added on keys
5902 	 * distribution.
5903 	 */
5904 	if (atomic_test_bit(smp->flags, SMP_FLAG_SC)) {
5905 		conn->le.keys->flags |= BT_KEYS_SC;
5906 
5907 		if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) {
5908 			bt_keys_add_type(conn->le.keys, BT_KEYS_LTK_P256);
5909 			memcpy(conn->le.keys->ltk.val, smp->tk,
5910 			       sizeof(conn->le.keys->ltk.val));
5911 			(void)memset(conn->le.keys->ltk.rand, 0,
5912 				     sizeof(conn->le.keys->ltk.rand));
5913 			(void)memset(conn->le.keys->ltk.ediv, 0,
5914 				     sizeof(conn->le.keys->ltk.ediv));
5915 		} else if (IS_ENABLED(CONFIG_BT_LOG_SNIFFER_INFO)) {
5916 			uint8_t ltk[16];
5917 
5918 			sys_memcpy_swap(ltk, smp->tk, conn->le.keys->enc_size);
5919 			LOG_INF("SC LTK: 0x%s (No bonding)", bt_hex(ltk, conn->le.keys->enc_size));
5920 		}
5921 	} else {
5922 		conn->le.keys->flags &= ~BT_KEYS_SC;
5923 	}
5924 }
5925 
bt_smp_accept(struct bt_conn * conn,struct bt_l2cap_chan ** chan)5926 static int bt_smp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan)
5927 {
5928 	int i;
5929 	static const struct bt_l2cap_chan_ops ops = {
5930 		.connected = bt_smp_connected,
5931 		.disconnected = bt_smp_disconnected,
5932 		.encrypt_change = bt_smp_encrypt_change,
5933 		.recv = bt_smp_recv,
5934 	};
5935 
5936 	LOG_DBG("conn %p handle %u", conn, conn->handle);
5937 
5938 	for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) {
5939 		struct bt_smp *smp = &bt_smp_pool[i];
5940 
5941 		if (smp->chan.chan.conn) {
5942 			continue;
5943 		}
5944 
5945 		smp->chan.chan.ops = &ops;
5946 
5947 		*chan = &smp->chan.chan;
5948 
5949 		return 0;
5950 	}
5951 
5952 	LOG_ERR("No available SMP context for conn %p", conn);
5953 
5954 	return -ENOMEM;
5955 }
5956 
5957 BT_L2CAP_CHANNEL_DEFINE(smp_fixed_chan, BT_L2CAP_CID_SMP, bt_smp_accept, NULL);
5958 #if defined(CONFIG_BT_BREDR)
5959 BT_L2CAP_CHANNEL_DEFINE(smp_br_fixed_chan, BT_L2CAP_CID_BR_SMP,
5960 			bt_smp_br_accept, NULL);
5961 #endif /* CONFIG_BT_BREDR */
5962 
bt_smp_init(void)5963 int bt_smp_init(void)
5964 {
5965 	static struct bt_pub_key_cb pub_key_cb = {
5966 		.func           = bt_smp_pkey_ready,
5967 	};
5968 
5969 	sc_supported = le_sc_supported();
5970 	if (IS_ENABLED(CONFIG_BT_SMP_SC_PAIR_ONLY) && !sc_supported) {
5971 		LOG_ERR("SC Pair Only Mode selected but LE SC not supported");
5972 		return -ENOENT;
5973 	}
5974 
5975 	if (IS_ENABLED(CONFIG_BT_SMP_USB_HCI_CTLR_WORKAROUND)) {
5976 		LOG_WRN("BT_SMP_USB_HCI_CTLR_WORKAROUND is enabled, which "
5977 			"exposes a security vulnerability!");
5978 	}
5979 
5980 	LOG_DBG("LE SC %s", sc_supported ? "enabled" : "disabled");
5981 
5982 	if (!IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)) {
5983 		bt_pub_key_gen(&pub_key_cb);
5984 	}
5985 
5986 	return smp_self_test();
5987 }
5988