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