xref: /linux/net/bluetooth/smp.c (revision f033482d76a9f18080c7a40c5f9c678bd7adc8f3)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3    BlueZ - Bluetooth protocol stack for Linux
4    Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
5 
6    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
8    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
9    IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
10    CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
11    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 
15    ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
16    COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
17    SOFTWARE IS DISCLAIMED.
18 */
19 
20 #include <linux/debugfs.h>
21 #include <linux/scatterlist.h>
22 #include <crypto/aes-cbc-macs.h>
23 #include <crypto/aes.h>
24 #include <crypto/kpp.h>
25 #include <crypto/utils.h>
26 
27 #include <net/bluetooth/bluetooth.h>
28 #include <net/bluetooth/hci_core.h>
29 #include <net/bluetooth/l2cap.h>
30 #include <net/bluetooth/mgmt.h>
31 
32 #include "ecdh_helper.h"
33 #include "smp.h"
34 
35 #define SMP_DEV(hdev) \
36 	((struct smp_dev *)((struct l2cap_chan *)((hdev)->smp_data))->data)
37 
38 /* Low-level debug macros to be used for stuff that we don't want
39  * accidentally in dmesg, i.e. the values of the various crypto keys
40  * and the inputs & outputs of crypto functions.
41  */
42 #ifdef DEBUG
43 #define SMP_DBG(fmt, ...) printk(KERN_DEBUG "%s: " fmt, __func__, \
44 				 ##__VA_ARGS__)
45 #else
46 #define SMP_DBG(fmt, ...) no_printk(KERN_DEBUG "%s: " fmt, __func__, \
47 				    ##__VA_ARGS__)
48 #endif
49 
50 #define SMP_ALLOW_CMD(smp, code)	set_bit(code, &smp->allow_cmd)
51 
52 /* Keys which are not distributed with Secure Connections */
53 #define SMP_SC_NO_DIST (SMP_DIST_ENC_KEY | SMP_DIST_LINK_KEY)
54 
55 #define SMP_TIMEOUT	secs_to_jiffies(30)
56 
57 #define ID_ADDR_TIMEOUT	msecs_to_jiffies(200)
58 
59 #define AUTH_REQ_MASK(dev)	(hci_dev_test_flag(dev, HCI_SC_ENABLED) ? \
60 				 0x3f : 0x07)
61 #define KEY_DIST_MASK		0x07
62 
63 /* Maximum message length that can be passed to smp_aes_cmac */
64 #define CMAC_MSG_MAX	80
65 
66 enum {
67 	SMP_FLAG_TK_VALID,
68 	SMP_FLAG_CFM_PENDING,
69 	SMP_FLAG_MITM_AUTH,
70 	SMP_FLAG_COMPLETE,
71 	SMP_FLAG_INITIATOR,
72 	SMP_FLAG_SC,
73 	SMP_FLAG_REMOTE_PK,
74 	SMP_FLAG_DEBUG_KEY,
75 	SMP_FLAG_WAIT_USER,
76 	SMP_FLAG_DHKEY_PENDING,
77 	SMP_FLAG_REMOTE_OOB,
78 	SMP_FLAG_LOCAL_OOB,
79 	SMP_FLAG_CT2,
80 };
81 
82 struct smp_dev {
83 	/* Secure Connections OOB data */
84 	bool			local_oob;
85 	u8			local_pk[64];
86 	u8			local_rand[16];
87 	bool			debug_key;
88 
89 	struct crypto_kpp	*tfm_ecdh;
90 };
91 
92 struct smp_chan {
93 	struct l2cap_conn	*conn;
94 	struct delayed_work	security_timer;
95 	unsigned long           allow_cmd; /* Bitmask of allowed commands */
96 
97 	u8		preq[7]; /* SMP Pairing Request */
98 	u8		prsp[7]; /* SMP Pairing Response */
99 	u8		prnd[16]; /* SMP Pairing Random (local) */
100 	u8		rrnd[16]; /* SMP Pairing Random (remote) */
101 	u8		pcnf[16]; /* SMP Pairing Confirm */
102 	u8		tk[16]; /* SMP Temporary Key */
103 	u8		rr[16]; /* Remote OOB ra/rb value */
104 	u8		lr[16]; /* Local OOB ra/rb value */
105 	u8		enc_key_size;
106 	u8		remote_key_dist;
107 	bdaddr_t	id_addr;
108 	u8		id_addr_type;
109 	u8		irk[16];
110 	struct smp_csrk	*csrk;
111 	struct smp_csrk	*responder_csrk;
112 	struct smp_ltk	*ltk;
113 	struct smp_ltk	*responder_ltk;
114 	struct smp_irk	*remote_irk;
115 	u8		*link_key;
116 	unsigned long	flags;
117 	u8		method;
118 	u8		passkey_round;
119 
120 	/* Secure Connections variables */
121 	u8			local_pk[64];
122 	u8			remote_pk[64];
123 	u8			dhkey[32];
124 	u8			mackey[16];
125 
126 	struct crypto_kpp	*tfm_ecdh;
127 };
128 
129 /* These debug key values are defined in the SMP section of the core
130  * specification. debug_pk is the public debug key and debug_sk the
131  * private debug key.
132  */
133 static const u8 debug_pk[64] = {
134 		0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc,
135 		0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef,
136 		0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
137 		0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20,
138 
139 		0x8b, 0xd2, 0x89, 0x15, 0xd0, 0x8e, 0x1c, 0x74,
140 		0x24, 0x30, 0xed, 0x8f, 0xc2, 0x45, 0x63, 0x76,
141 		0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63,
142 		0x6d, 0xeb, 0x2a, 0x65, 0x49, 0x9c, 0x80, 0xdc,
143 };
144 
145 static const u8 debug_sk[32] = {
146 		0xbd, 0x1a, 0x3c, 0xcd, 0xa6, 0xb8, 0x99, 0x58,
147 		0x99, 0xb7, 0x40, 0xeb, 0x7b, 0x60, 0xff, 0x4a,
148 		0x50, 0x3f, 0x10, 0xd2, 0xe3, 0xb3, 0xc9, 0x74,
149 		0x38, 0x5f, 0xc5, 0xa3, 0xd4, 0xf6, 0x49, 0x3f,
150 };
151 
152 static inline void swap_buf(const u8 *src, u8 *dst, size_t len)
153 {
154 	size_t i;
155 
156 	for (i = 0; i < len; i++)
157 		dst[len - 1 - i] = src[i];
158 }
159 
160 /* The following functions map to the LE SC SMP crypto functions
161  * AES-CMAC, f4, f5, f6, g2 and h6.
162  */
163 
164 static int smp_aes_cmac(const u8 k[16], const u8 *m, size_t len, u8 mac[16])
165 {
166 	uint8_t tmp[16], mac_msb[16], msg_msb[CMAC_MSG_MAX];
167 	struct aes_cmac_key key __cleanup(aes_cmac_zeroize_key);
168 	int err;
169 
170 	if (len > CMAC_MSG_MAX)
171 		return -EFBIG;
172 
173 	/* Swap key and message from LSB to MSB */
174 	swap_buf(k, tmp, 16);
175 	swap_buf(m, msg_msb, len);
176 
177 	SMP_DBG("msg (len %zu) %*phN", len, (int) len, m);
178 	SMP_DBG("key %16phN", k);
179 
180 	err = aes_cmac_preparekey(&key, tmp, 16);
181 	memzero_explicit(tmp, sizeof(tmp));
182 	if (WARN_ON_ONCE(err)) /* Should never happen, as 16 is valid keylen */
183 		return err;
184 	aes_cmac(&key, msg_msb, len, mac_msb);
185 
186 	swap_buf(mac_msb, mac, 16);
187 
188 	SMP_DBG("mac %16phN", mac);
189 
190 	return 0;
191 }
192 
193 static int smp_f4(const u8 u[32], const u8 v[32], const u8 x[16], u8 z,
194 		  u8 res[16])
195 {
196 	u8 m[65];
197 	int err;
198 
199 	SMP_DBG("u %32phN", u);
200 	SMP_DBG("v %32phN", v);
201 	SMP_DBG("x %16phN z %02x", x, z);
202 
203 	m[0] = z;
204 	memcpy(m + 1, v, 32);
205 	memcpy(m + 33, u, 32);
206 
207 	err = smp_aes_cmac(x, m, sizeof(m), res);
208 	if (err)
209 		return err;
210 
211 	SMP_DBG("res %16phN", res);
212 
213 	return err;
214 }
215 
216 static int smp_f5(const u8 w[32], const u8 n1[16], const u8 n2[16],
217 		  const u8 a1[7], const u8 a2[7], u8 mackey[16], u8 ltk[16])
218 {
219 	/* The btle, salt and length "magic" values are as defined in
220 	 * the SMP section of the Bluetooth core specification. In ASCII
221 	 * the btle value ends up being 'btle'. The salt is just a
222 	 * random number whereas length is the value 256 in little
223 	 * endian format.
224 	 */
225 	const u8 btle[4] = { 0x65, 0x6c, 0x74, 0x62 };
226 	const u8 salt[16] = { 0xbe, 0x83, 0x60, 0x5a, 0xdb, 0x0b, 0x37, 0x60,
227 			      0x38, 0xa5, 0xf5, 0xaa, 0x91, 0x83, 0x88, 0x6c };
228 	const u8 length[2] = { 0x00, 0x01 };
229 	u8 m[53], t[16];
230 	int err;
231 
232 	SMP_DBG("w %32phN", w);
233 	SMP_DBG("n1 %16phN n2 %16phN", n1, n2);
234 	SMP_DBG("a1 %7phN a2 %7phN", a1, a2);
235 
236 	err = smp_aes_cmac(salt, w, 32, t);
237 	if (err)
238 		return err;
239 
240 	SMP_DBG("t %16phN", t);
241 
242 	memcpy(m, length, 2);
243 	memcpy(m + 2, a2, 7);
244 	memcpy(m + 9, a1, 7);
245 	memcpy(m + 16, n2, 16);
246 	memcpy(m + 32, n1, 16);
247 	memcpy(m + 48, btle, 4);
248 
249 	m[52] = 0; /* Counter */
250 
251 	err = smp_aes_cmac(t, m, sizeof(m), mackey);
252 	if (err)
253 		return err;
254 
255 	SMP_DBG("mackey %16phN", mackey);
256 
257 	m[52] = 1; /* Counter */
258 
259 	err = smp_aes_cmac(t, m, sizeof(m), ltk);
260 	if (err)
261 		return err;
262 
263 	SMP_DBG("ltk %16phN", ltk);
264 
265 	return 0;
266 }
267 
268 static int smp_f6(const u8 w[16], const u8 n1[16], const u8 n2[16],
269 		  const u8 r[16], const u8 io_cap[3], const u8 a1[7],
270 		  const u8 a2[7], u8 res[16])
271 {
272 	u8 m[65];
273 	int err;
274 
275 	SMP_DBG("w %16phN", w);
276 	SMP_DBG("n1 %16phN n2 %16phN", n1, n2);
277 	SMP_DBG("r %16phN io_cap %3phN a1 %7phN a2 %7phN", r, io_cap, a1, a2);
278 
279 	memcpy(m, a2, 7);
280 	memcpy(m + 7, a1, 7);
281 	memcpy(m + 14, io_cap, 3);
282 	memcpy(m + 17, r, 16);
283 	memcpy(m + 33, n2, 16);
284 	memcpy(m + 49, n1, 16);
285 
286 	err = smp_aes_cmac(w, m, sizeof(m), res);
287 	if (err)
288 		return err;
289 
290 	SMP_DBG("res %16phN", res);
291 
292 	return err;
293 }
294 
295 static int smp_g2(const u8 u[32], const u8 v[32], const u8 x[16],
296 		  const u8 y[16], u32 *val)
297 {
298 	u8 m[80], tmp[16];
299 	int err;
300 
301 	SMP_DBG("u %32phN", u);
302 	SMP_DBG("v %32phN", v);
303 	SMP_DBG("x %16phN y %16phN", x, y);
304 
305 	memcpy(m, y, 16);
306 	memcpy(m + 16, v, 32);
307 	memcpy(m + 48, u, 32);
308 
309 	err = smp_aes_cmac(x, m, sizeof(m), tmp);
310 	if (err)
311 		return err;
312 
313 	*val = get_unaligned_le32(tmp);
314 	*val %= 1000000;
315 
316 	SMP_DBG("val %06u", *val);
317 
318 	return 0;
319 }
320 
321 static int smp_h6(const u8 w[16], const u8 key_id[4], u8 res[16])
322 {
323 	int err;
324 
325 	SMP_DBG("w %16phN key_id %4phN", w, key_id);
326 
327 	err = smp_aes_cmac(w, key_id, 4, res);
328 	if (err)
329 		return err;
330 
331 	SMP_DBG("res %16phN", res);
332 
333 	return err;
334 }
335 
336 static int smp_h7(const u8 w[16], const u8 salt[16], u8 res[16])
337 {
338 	int err;
339 
340 	SMP_DBG("w %16phN salt %16phN", w, salt);
341 
342 	err = smp_aes_cmac(salt, w, 16, res);
343 	if (err)
344 		return err;
345 
346 	SMP_DBG("res %16phN", res);
347 
348 	return err;
349 }
350 
351 /* The following functions map to the legacy SMP crypto functions e, c1,
352  * s1 and ah.
353  */
354 
355 static int smp_e(const u8 *k, u8 *r)
356 {
357 	struct aes_enckey aes;
358 	uint8_t tmp[16], data[16];
359 	int err;
360 
361 	SMP_DBG("k %16phN r %16phN", k, r);
362 
363 	/* The most significant octet of key corresponds to k[0] */
364 	swap_buf(k, tmp, 16);
365 
366 	err = aes_prepareenckey(&aes, tmp, 16);
367 	if (err) {
368 		BT_ERR("cipher setkey failed: %d", err);
369 		return err;
370 	}
371 
372 	/* Most significant octet of plaintextData corresponds to data[0] */
373 	swap_buf(r, data, 16);
374 
375 	aes_encrypt(&aes, data, data);
376 
377 	/* Most significant octet of encryptedData corresponds to data[0] */
378 	swap_buf(data, r, 16);
379 
380 	SMP_DBG("r %16phN", r);
381 
382 	memzero_explicit(&aes, sizeof(aes));
383 	return err;
384 }
385 
386 static int smp_c1(const u8 k[16],
387 		  const u8 r[16], const u8 preq[7], const u8 pres[7], u8 _iat,
388 		  const bdaddr_t *ia, u8 _rat, const bdaddr_t *ra, u8 res[16])
389 {
390 	u8 p1[16], p2[16];
391 	int err;
392 
393 	SMP_DBG("k %16phN r %16phN", k, r);
394 	SMP_DBG("iat %u ia %6phN rat %u ra %6phN", _iat, ia, _rat, ra);
395 	SMP_DBG("preq %7phN pres %7phN", preq, pres);
396 
397 	memset(p1, 0, 16);
398 
399 	/* p1 = pres || preq || _rat || _iat */
400 	p1[0] = _iat;
401 	p1[1] = _rat;
402 	memcpy(p1 + 2, preq, 7);
403 	memcpy(p1 + 9, pres, 7);
404 
405 	SMP_DBG("p1 %16phN", p1);
406 
407 	/* res = r XOR p1 */
408 	crypto_xor_cpy(res, r, p1, sizeof(p1));
409 
410 	/* res = e(k, res) */
411 	err = smp_e(k, res);
412 	if (err) {
413 		BT_ERR("Encrypt data error");
414 		return err;
415 	}
416 
417 	/* p2 = padding || ia || ra */
418 	memcpy(p2, ra, 6);
419 	memcpy(p2 + 6, ia, 6);
420 	memset(p2 + 12, 0, 4);
421 
422 	SMP_DBG("p2 %16phN", p2);
423 
424 	/* res = res XOR p2 */
425 	crypto_xor(res, p2, sizeof(p2));
426 
427 	/* res = e(k, res) */
428 	err = smp_e(k, res);
429 	if (err)
430 		BT_ERR("Encrypt data error");
431 
432 	return err;
433 }
434 
435 static int smp_s1(const u8 k[16],
436 		  const u8 r1[16], const u8 r2[16], u8 _r[16])
437 {
438 	int err;
439 
440 	/* Just least significant octets from r1 and r2 are considered */
441 	memcpy(_r, r2, 8);
442 	memcpy(_r + 8, r1, 8);
443 
444 	err = smp_e(k, _r);
445 	if (err)
446 		BT_ERR("Encrypt data error");
447 
448 	return err;
449 }
450 
451 static int smp_ah(const u8 irk[16], const u8 r[3], u8 res[3])
452 {
453 	u8 _res[16];
454 	int err;
455 
456 	/* r' = padding || r */
457 	memcpy(_res, r, 3);
458 	memset(_res + 3, 0, 13);
459 
460 	err = smp_e(irk, _res);
461 	if (err) {
462 		BT_ERR("Encrypt error");
463 		return err;
464 	}
465 
466 	/* The output of the random address function ah is:
467 	 *	ah(k, r) = e(k, r') mod 2^24
468 	 * The output of the security function e is then truncated to 24 bits
469 	 * by taking the least significant 24 bits of the output of e as the
470 	 * result of ah.
471 	 */
472 	memcpy(res, _res, 3);
473 
474 	return 0;
475 }
476 
477 bool smp_irk_matches(struct hci_dev *hdev, const u8 irk[16],
478 		     const bdaddr_t *bdaddr)
479 {
480 	struct l2cap_chan *chan = hdev->smp_data;
481 	u8 hash[3];
482 	int err;
483 
484 	if (!chan || !chan->data)
485 		return false;
486 
487 	bt_dev_dbg(hdev, "RPA %pMR IRK %*phN", bdaddr, 16, irk);
488 
489 	err = smp_ah(irk, &bdaddr->b[3], hash);
490 	if (err)
491 		return false;
492 
493 	return !crypto_memneq(bdaddr->b, hash, 3);
494 }
495 
496 int smp_generate_rpa(struct hci_dev *hdev, const u8 irk[16], bdaddr_t *rpa)
497 {
498 	struct l2cap_chan *chan = hdev->smp_data;
499 	int err;
500 
501 	if (!chan || !chan->data)
502 		return -EOPNOTSUPP;
503 
504 	get_random_bytes(&rpa->b[3], 3);
505 
506 	rpa->b[5] &= 0x3f;	/* Clear two most significant bits */
507 	rpa->b[5] |= 0x40;	/* Set second most significant bit */
508 
509 	err = smp_ah(irk, &rpa->b[3], rpa->b);
510 	if (err < 0)
511 		return err;
512 
513 	bt_dev_dbg(hdev, "RPA %pMR", rpa);
514 
515 	return 0;
516 }
517 
518 int smp_generate_oob(struct hci_dev *hdev, u8 hash[16], u8 rand[16])
519 {
520 	struct l2cap_chan *chan = hdev->smp_data;
521 	struct smp_dev *smp;
522 	int err;
523 
524 	if (!chan || !chan->data)
525 		return -EOPNOTSUPP;
526 
527 	smp = chan->data;
528 
529 	if (hci_dev_test_flag(hdev, HCI_USE_DEBUG_KEYS)) {
530 		bt_dev_dbg(hdev, "Using debug keys");
531 		err = set_ecdh_privkey(smp->tfm_ecdh, debug_sk);
532 		if (err)
533 			return err;
534 		memcpy(smp->local_pk, debug_pk, 64);
535 		smp->debug_key = true;
536 	} else {
537 		while (true) {
538 			/* Generate key pair for Secure Connections */
539 			err = generate_ecdh_keys(smp->tfm_ecdh, smp->local_pk);
540 			if (err)
541 				return err;
542 
543 			/* This is unlikely, but we need to check that
544 			 * we didn't accidentally generate a debug key.
545 			 */
546 			if (crypto_memneq(smp->local_pk, debug_pk, 64))
547 				break;
548 		}
549 		smp->debug_key = false;
550 	}
551 
552 	SMP_DBG("OOB Public Key X: %32phN", smp->local_pk);
553 	SMP_DBG("OOB Public Key Y: %32phN", smp->local_pk + 32);
554 
555 	get_random_bytes(smp->local_rand, 16);
556 
557 	err = smp_f4(smp->local_pk, smp->local_pk, smp->local_rand, 0, hash);
558 	if (err < 0)
559 		return err;
560 
561 	memcpy(rand, smp->local_rand, 16);
562 
563 	smp->local_oob = true;
564 
565 	return 0;
566 }
567 
568 static void smp_send_cmd(struct l2cap_conn *conn, u8 code, u16 len, void *data)
569 {
570 	struct l2cap_chan *chan = conn->smp;
571 	struct smp_chan *smp;
572 	struct kvec iv[2];
573 	struct msghdr msg;
574 
575 	if (!chan)
576 		return;
577 
578 	bt_dev_dbg(conn->hcon->hdev, "code 0x%2.2x", code);
579 
580 	iv[0].iov_base = &code;
581 	iv[0].iov_len = 1;
582 
583 	iv[1].iov_base = data;
584 	iv[1].iov_len = len;
585 
586 	memset(&msg, 0, sizeof(msg));
587 
588 	iov_iter_kvec(&msg.msg_iter, ITER_SOURCE, iv, 2, 1 + len);
589 
590 	l2cap_chan_send(chan, &msg, 1 + len, NULL);
591 
592 	if (!chan->data)
593 		return;
594 
595 	smp = chan->data;
596 
597 	cancel_delayed_work_sync(&smp->security_timer);
598 	schedule_delayed_work(&smp->security_timer, SMP_TIMEOUT);
599 }
600 
601 static u8 authreq_to_seclevel(u8 authreq)
602 {
603 	if (authreq & SMP_AUTH_MITM) {
604 		if (authreq & SMP_AUTH_SC)
605 			return BT_SECURITY_FIPS;
606 		else
607 			return BT_SECURITY_HIGH;
608 	} else {
609 		return BT_SECURITY_MEDIUM;
610 	}
611 }
612 
613 static __u8 seclevel_to_authreq(__u8 sec_level)
614 {
615 	switch (sec_level) {
616 	case BT_SECURITY_FIPS:
617 	case BT_SECURITY_HIGH:
618 		return SMP_AUTH_MITM | SMP_AUTH_BONDING;
619 	case BT_SECURITY_MEDIUM:
620 		return SMP_AUTH_BONDING;
621 	default:
622 		return SMP_AUTH_NONE;
623 	}
624 }
625 
626 static void build_pairing_cmd(struct l2cap_conn *conn,
627 			      struct smp_cmd_pairing *req,
628 			      struct smp_cmd_pairing *rsp, __u8 authreq)
629 {
630 	struct l2cap_chan *chan = conn->smp;
631 	struct smp_chan *smp = chan->data;
632 	struct hci_conn *hcon = conn->hcon;
633 	struct hci_dev *hdev = hcon->hdev;
634 	u8 local_dist = 0, remote_dist = 0, oob_flag = SMP_OOB_NOT_PRESENT;
635 
636 	if (hci_dev_test_flag(hdev, HCI_BONDABLE)) {
637 		local_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
638 		remote_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
639 		authreq |= SMP_AUTH_BONDING;
640 	} else {
641 		authreq &= ~SMP_AUTH_BONDING;
642 	}
643 
644 	if (hci_dev_test_flag(hdev, HCI_RPA_RESOLVING))
645 		remote_dist |= SMP_DIST_ID_KEY;
646 
647 	if (hci_dev_test_flag(hdev, HCI_PRIVACY))
648 		local_dist |= SMP_DIST_ID_KEY;
649 
650 	if (hci_dev_test_flag(hdev, HCI_SC_ENABLED) &&
651 	    (authreq & SMP_AUTH_SC)) {
652 		struct oob_data *oob_data;
653 		u8 bdaddr_type;
654 
655 		if (hci_dev_test_flag(hdev, HCI_SSP_ENABLED)) {
656 			local_dist |= SMP_DIST_LINK_KEY;
657 			remote_dist |= SMP_DIST_LINK_KEY;
658 		}
659 
660 		if (hcon->dst_type == ADDR_LE_DEV_PUBLIC)
661 			bdaddr_type = BDADDR_LE_PUBLIC;
662 		else
663 			bdaddr_type = BDADDR_LE_RANDOM;
664 
665 		oob_data = hci_find_remote_oob_data(hdev, &hcon->dst,
666 						    bdaddr_type);
667 		if (oob_data && oob_data->present) {
668 			set_bit(SMP_FLAG_REMOTE_OOB, &smp->flags);
669 			oob_flag = SMP_OOB_PRESENT;
670 			memcpy(smp->rr, oob_data->rand256, 16);
671 			memcpy(smp->pcnf, oob_data->hash256, 16);
672 			SMP_DBG("OOB Remote Confirmation: %16phN", smp->pcnf);
673 			SMP_DBG("OOB Remote Random: %16phN", smp->rr);
674 		}
675 
676 	} else {
677 		authreq &= ~SMP_AUTH_SC;
678 	}
679 
680 	if (rsp == NULL) {
681 		req->io_capability = conn->hcon->io_capability;
682 		req->oob_flag = oob_flag;
683 		req->max_key_size = hdev->le_max_key_size;
684 		req->init_key_dist = local_dist;
685 		req->resp_key_dist = remote_dist;
686 		req->auth_req = (authreq & AUTH_REQ_MASK(hdev));
687 
688 		smp->remote_key_dist = remote_dist;
689 		return;
690 	}
691 
692 	rsp->io_capability = conn->hcon->io_capability;
693 	rsp->oob_flag = oob_flag;
694 	rsp->max_key_size = hdev->le_max_key_size;
695 	rsp->init_key_dist = req->init_key_dist & remote_dist;
696 	rsp->resp_key_dist = req->resp_key_dist & local_dist;
697 	rsp->auth_req = (authreq & AUTH_REQ_MASK(hdev));
698 
699 	smp->remote_key_dist = rsp->init_key_dist;
700 }
701 
702 static u8 check_enc_key_size(struct l2cap_conn *conn, __u8 max_key_size)
703 {
704 	struct l2cap_chan *chan = conn->smp;
705 	struct hci_dev *hdev = conn->hcon->hdev;
706 	struct smp_chan *smp = chan->data;
707 
708 	if (conn->hcon->pending_sec_level == BT_SECURITY_FIPS &&
709 	    max_key_size != SMP_MAX_ENC_KEY_SIZE)
710 		return SMP_ENC_KEY_SIZE;
711 
712 	if (max_key_size > hdev->le_max_key_size ||
713 	    max_key_size < SMP_MIN_ENC_KEY_SIZE)
714 		return SMP_ENC_KEY_SIZE;
715 
716 	smp->enc_key_size = max_key_size;
717 
718 	return 0;
719 }
720 
721 static void smp_chan_destroy(struct l2cap_conn *conn)
722 {
723 	struct l2cap_chan *chan = conn->smp;
724 	struct smp_chan *smp = chan->data;
725 	struct hci_conn *hcon = conn->hcon;
726 	bool complete;
727 
728 	BUG_ON(!smp);
729 
730 	cancel_delayed_work_sync(&smp->security_timer);
731 
732 	complete = test_bit(SMP_FLAG_COMPLETE, &smp->flags);
733 	mgmt_smp_complete(hcon, complete);
734 
735 	kfree_sensitive(smp->csrk);
736 	kfree_sensitive(smp->responder_csrk);
737 	kfree_sensitive(smp->link_key);
738 
739 	crypto_free_kpp(smp->tfm_ecdh);
740 
741 	/* Ensure that we don't leave any debug key around if debug key
742 	 * support hasn't been explicitly enabled.
743 	 */
744 	if (smp->ltk && smp->ltk->type == SMP_LTK_P256_DEBUG &&
745 	    !hci_dev_test_flag(hcon->hdev, HCI_KEEP_DEBUG_KEYS)) {
746 		list_del_rcu(&smp->ltk->list);
747 		kfree_rcu(smp->ltk, rcu);
748 		smp->ltk = NULL;
749 	}
750 
751 	/* If pairing failed clean up any keys we might have */
752 	if (!complete) {
753 		if (smp->ltk) {
754 			list_del_rcu(&smp->ltk->list);
755 			kfree_rcu(smp->ltk, rcu);
756 		}
757 
758 		if (smp->responder_ltk) {
759 			list_del_rcu(&smp->responder_ltk->list);
760 			kfree_rcu(smp->responder_ltk, rcu);
761 		}
762 
763 		if (smp->remote_irk) {
764 			list_del_rcu(&smp->remote_irk->list);
765 			kfree_rcu(smp->remote_irk, rcu);
766 		}
767 	}
768 
769 	chan->data = NULL;
770 	kfree_sensitive(smp);
771 	hci_conn_drop(hcon);
772 }
773 
774 static void smp_failure(struct l2cap_conn *conn, u8 reason)
775 {
776 	struct hci_conn *hcon = conn->hcon;
777 	struct l2cap_chan *chan = conn->smp;
778 
779 	if (reason)
780 		smp_send_cmd(conn, SMP_CMD_PAIRING_FAIL, sizeof(reason),
781 			     &reason);
782 
783 	mgmt_auth_failed(hcon, HCI_ERROR_AUTH_FAILURE);
784 
785 	if (chan->data)
786 		smp_chan_destroy(conn);
787 }
788 
789 #define JUST_WORKS	0x00
790 #define JUST_CFM	0x01
791 #define REQ_PASSKEY	0x02
792 #define CFM_PASSKEY	0x03
793 #define REQ_OOB		0x04
794 #define DSP_PASSKEY	0x05
795 #define OVERLAP		0xFF
796 
797 static const u8 gen_method[5][5] = {
798 	{ JUST_WORKS,  JUST_CFM,    REQ_PASSKEY, JUST_WORKS, REQ_PASSKEY },
799 	{ JUST_WORKS,  JUST_CFM,    REQ_PASSKEY, JUST_WORKS, REQ_PASSKEY },
800 	{ CFM_PASSKEY, CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, CFM_PASSKEY },
801 	{ JUST_WORKS,  JUST_CFM,    JUST_WORKS,  JUST_WORKS, JUST_CFM    },
802 	{ CFM_PASSKEY, CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, OVERLAP     },
803 };
804 
805 static const u8 sc_method[5][5] = {
806 	{ JUST_WORKS,  JUST_CFM,    REQ_PASSKEY, JUST_WORKS, REQ_PASSKEY },
807 	{ JUST_WORKS,  CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, CFM_PASSKEY },
808 	{ DSP_PASSKEY, DSP_PASSKEY, REQ_PASSKEY, JUST_WORKS, DSP_PASSKEY },
809 	{ JUST_WORKS,  JUST_CFM,    JUST_WORKS,  JUST_WORKS, JUST_CFM    },
810 	{ DSP_PASSKEY, CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, CFM_PASSKEY },
811 };
812 
813 static u8 get_auth_method(struct smp_chan *smp, u8 local_io, u8 remote_io)
814 {
815 	/* If either side has unknown io_caps, use JUST_CFM (which gets
816 	 * converted later to JUST_WORKS if we're initiators.
817 	 */
818 	if (local_io > SMP_IO_KEYBOARD_DISPLAY ||
819 	    remote_io > SMP_IO_KEYBOARD_DISPLAY)
820 		return JUST_CFM;
821 
822 	if (test_bit(SMP_FLAG_SC, &smp->flags))
823 		return sc_method[remote_io][local_io];
824 
825 	return gen_method[remote_io][local_io];
826 }
827 
828 static int tk_request(struct l2cap_conn *conn, u8 remote_oob, u8 auth,
829 						u8 local_io, u8 remote_io)
830 {
831 	struct hci_conn *hcon = conn->hcon;
832 	struct l2cap_chan *chan = conn->smp;
833 	struct smp_chan *smp = chan->data;
834 	u32 passkey = 0;
835 	int ret;
836 
837 	/* Initialize key for JUST WORKS */
838 	memset(smp->tk, 0, sizeof(smp->tk));
839 	clear_bit(SMP_FLAG_TK_VALID, &smp->flags);
840 
841 	bt_dev_dbg(hcon->hdev, "auth:%u lcl:%u rem:%u", auth, local_io,
842 		   remote_io);
843 
844 	/* If neither side wants MITM, either "just" confirm an incoming
845 	 * request or use just-works for outgoing ones. The JUST_CFM
846 	 * will be converted to JUST_WORKS if necessary later in this
847 	 * function. If either side has MITM look up the method from the
848 	 * table.
849 	 */
850 	if (!(auth & SMP_AUTH_MITM))
851 		smp->method = JUST_CFM;
852 	else
853 		smp->method = get_auth_method(smp, local_io, remote_io);
854 
855 	/* Don't confirm locally initiated pairing attempts */
856 	if (smp->method == JUST_CFM && test_bit(SMP_FLAG_INITIATOR,
857 						&smp->flags))
858 		smp->method = JUST_WORKS;
859 
860 	/* Don't bother user space with no IO capabilities */
861 	if (smp->method == JUST_CFM &&
862 	    hcon->io_capability == HCI_IO_NO_INPUT_OUTPUT)
863 		smp->method = JUST_WORKS;
864 
865 	/* If Just Works, Continue with Zero TK and ask user-space for
866 	 * confirmation */
867 	if (smp->method == JUST_WORKS) {
868 		ret = mgmt_user_confirm_request(hcon->hdev, &hcon->dst,
869 						hcon->type,
870 						hcon->dst_type,
871 						passkey, 1);
872 		if (ret)
873 			return ret;
874 		set_bit(SMP_FLAG_WAIT_USER, &smp->flags);
875 		return 0;
876 	}
877 
878 	/* If this function is used for SC -> legacy fallback we
879 	 * can only recover the just-works case.
880 	 */
881 	if (test_bit(SMP_FLAG_SC, &smp->flags))
882 		return -EINVAL;
883 
884 	/* Not Just Works/Confirm results in MITM Authentication */
885 	if (smp->method != JUST_CFM) {
886 		set_bit(SMP_FLAG_MITM_AUTH, &smp->flags);
887 		if (hcon->pending_sec_level < BT_SECURITY_HIGH)
888 			hcon->pending_sec_level = BT_SECURITY_HIGH;
889 	}
890 
891 	/* If both devices have Keyboard-Display I/O, the initiator
892 	 * Confirms and the responder Enters the passkey.
893 	 */
894 	if (smp->method == OVERLAP) {
895 		if (test_bit(SMP_FLAG_INITIATOR, &smp->flags))
896 			smp->method = CFM_PASSKEY;
897 		else
898 			smp->method = REQ_PASSKEY;
899 	}
900 
901 	/* Generate random passkey. */
902 	if (smp->method == CFM_PASSKEY) {
903 		memset(smp->tk, 0, sizeof(smp->tk));
904 		get_random_bytes(&passkey, sizeof(passkey));
905 		passkey %= 1000000;
906 		put_unaligned_le32(passkey, smp->tk);
907 		bt_dev_dbg(hcon->hdev, "PassKey: %u", passkey);
908 		set_bit(SMP_FLAG_TK_VALID, &smp->flags);
909 	}
910 
911 	if (smp->method == REQ_PASSKEY)
912 		ret = mgmt_user_passkey_request(hcon->hdev, &hcon->dst,
913 						hcon->type, hcon->dst_type);
914 	else if (smp->method == JUST_CFM)
915 		ret = mgmt_user_confirm_request(hcon->hdev, &hcon->dst,
916 						hcon->type, hcon->dst_type,
917 						passkey, 1);
918 	else
919 		ret = mgmt_user_passkey_notify(hcon->hdev, &hcon->dst,
920 						hcon->type, hcon->dst_type,
921 						passkey, 0);
922 
923 	return ret;
924 }
925 
926 static u8 smp_confirm(struct smp_chan *smp)
927 {
928 	struct l2cap_conn *conn = smp->conn;
929 	struct smp_cmd_pairing_confirm cp;
930 	int ret;
931 
932 	bt_dev_dbg(conn->hcon->hdev, "conn %p", conn);
933 
934 	ret = smp_c1(smp->tk, smp->prnd, smp->preq, smp->prsp,
935 		     conn->hcon->init_addr_type, &conn->hcon->init_addr,
936 		     conn->hcon->resp_addr_type, &conn->hcon->resp_addr,
937 		     cp.confirm_val);
938 	if (ret)
939 		return SMP_UNSPECIFIED;
940 
941 	clear_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
942 
943 	smp_send_cmd(smp->conn, SMP_CMD_PAIRING_CONFIRM, sizeof(cp), &cp);
944 
945 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags))
946 		SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
947 	else
948 		SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
949 
950 	return 0;
951 }
952 
953 static u8 smp_random(struct smp_chan *smp)
954 {
955 	struct l2cap_conn *conn = smp->conn;
956 	struct hci_conn *hcon = conn->hcon;
957 	u8 confirm[16];
958 	int ret;
959 
960 	bt_dev_dbg(conn->hcon->hdev, "conn %p %s", conn,
961 		   test_bit(SMP_FLAG_INITIATOR, &smp->flags) ? "initiator" :
962 		   "responder");
963 
964 	ret = smp_c1(smp->tk, smp->rrnd, smp->preq, smp->prsp,
965 		     hcon->init_addr_type, &hcon->init_addr,
966 		     hcon->resp_addr_type, &hcon->resp_addr, confirm);
967 	if (ret)
968 		return SMP_UNSPECIFIED;
969 
970 	if (crypto_memneq(smp->pcnf, confirm, sizeof(smp->pcnf))) {
971 		bt_dev_err(hcon->hdev, "pairing failed "
972 			   "(confirmation values mismatch)");
973 		return SMP_CONFIRM_FAILED;
974 	}
975 
976 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
977 		u8 stk[16];
978 		__le64 rand = 0;
979 		__le16 ediv = 0;
980 
981 		smp_s1(smp->tk, smp->rrnd, smp->prnd, stk);
982 
983 		if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags))
984 			return SMP_UNSPECIFIED;
985 
986 		hci_le_start_enc(hcon, ediv, rand, stk, smp->enc_key_size);
987 		hcon->enc_key_size = smp->enc_key_size;
988 		set_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags);
989 	} else {
990 		u8 stk[16], auth;
991 		__le64 rand = 0;
992 		__le16 ediv = 0;
993 
994 		smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
995 			     smp->prnd);
996 
997 		smp_s1(smp->tk, smp->prnd, smp->rrnd, stk);
998 
999 		auth = test_bit(SMP_FLAG_MITM_AUTH, &smp->flags) ? 1 : 0;
1000 
1001 		/* Even though there's no _RESPONDER suffix this is the
1002 		 * responder STK we're adding for later lookup (the initiator
1003 		 * STK never needs to be stored).
1004 		 */
1005 		hci_add_ltk(hcon->hdev, &hcon->dst, hcon->dst_type,
1006 			    SMP_STK, auth, stk, smp->enc_key_size, ediv, rand);
1007 	}
1008 
1009 	return 0;
1010 }
1011 
1012 static void smp_notify_keys(struct l2cap_conn *conn)
1013 {
1014 	struct l2cap_chan *chan = conn->smp;
1015 	struct smp_chan *smp = chan->data;
1016 	struct hci_conn *hcon = conn->hcon;
1017 	struct hci_dev *hdev = hcon->hdev;
1018 	struct smp_cmd_pairing *req = (void *) &smp->preq[1];
1019 	struct smp_cmd_pairing *rsp = (void *) &smp->prsp[1];
1020 	bool persistent;
1021 
1022 	if (hcon->type == ACL_LINK) {
1023 		if (hcon->key_type == HCI_LK_DEBUG_COMBINATION)
1024 			persistent = false;
1025 		else
1026 			persistent = !test_bit(HCI_CONN_FLUSH_KEY,
1027 					       &hcon->flags);
1028 	} else {
1029 		/* The LTKs, IRKs and CSRKs should be persistent only if
1030 		 * both sides had the bonding bit set in their
1031 		 * authentication requests.
1032 		 */
1033 		persistent = !!((req->auth_req & rsp->auth_req) &
1034 				SMP_AUTH_BONDING);
1035 	}
1036 
1037 	if (smp->remote_irk) {
1038 		mgmt_new_irk(hdev, smp->remote_irk, persistent);
1039 
1040 		/* Now that user space can be considered to know the
1041 		 * identity address track the connection based on it
1042 		 * from now on (assuming this is an LE link).
1043 		 */
1044 		if (hcon->type == LE_LINK) {
1045 			bacpy(&hcon->dst, &smp->remote_irk->bdaddr);
1046 			hcon->dst_type = smp->remote_irk->addr_type;
1047 			/* Use a short delay to make sure the new address is
1048 			 * propagated _before_ the channels.
1049 			 */
1050 			queue_delayed_work(hdev->workqueue,
1051 					   &conn->id_addr_timer,
1052 					   ID_ADDR_TIMEOUT);
1053 		}
1054 	}
1055 
1056 	if (smp->csrk) {
1057 		smp->csrk->bdaddr_type = hcon->dst_type;
1058 		bacpy(&smp->csrk->bdaddr, &hcon->dst);
1059 		mgmt_new_csrk(hdev, smp->csrk, persistent);
1060 	}
1061 
1062 	if (smp->responder_csrk) {
1063 		smp->responder_csrk->bdaddr_type = hcon->dst_type;
1064 		bacpy(&smp->responder_csrk->bdaddr, &hcon->dst);
1065 		mgmt_new_csrk(hdev, smp->responder_csrk, persistent);
1066 	}
1067 
1068 	if (smp->ltk) {
1069 		smp->ltk->bdaddr_type = hcon->dst_type;
1070 		bacpy(&smp->ltk->bdaddr, &hcon->dst);
1071 		mgmt_new_ltk(hdev, smp->ltk, persistent);
1072 	}
1073 
1074 	if (smp->responder_ltk) {
1075 		smp->responder_ltk->bdaddr_type = hcon->dst_type;
1076 		bacpy(&smp->responder_ltk->bdaddr, &hcon->dst);
1077 		mgmt_new_ltk(hdev, smp->responder_ltk, persistent);
1078 	}
1079 
1080 	if (smp->link_key) {
1081 		struct link_key *key;
1082 		u8 type;
1083 
1084 		if (test_bit(SMP_FLAG_DEBUG_KEY, &smp->flags))
1085 			type = HCI_LK_DEBUG_COMBINATION;
1086 		else if (hcon->sec_level == BT_SECURITY_FIPS)
1087 			type = HCI_LK_AUTH_COMBINATION_P256;
1088 		else
1089 			type = HCI_LK_UNAUTH_COMBINATION_P256;
1090 
1091 		key = hci_add_link_key(hdev, smp->conn->hcon, &hcon->dst,
1092 				       smp->link_key, type, 0, &persistent);
1093 		if (key) {
1094 			mgmt_new_link_key(hdev, key, persistent);
1095 
1096 			/* Don't keep debug keys around if the relevant
1097 			 * flag is not set.
1098 			 */
1099 			if (!hci_dev_test_flag(hdev, HCI_KEEP_DEBUG_KEYS) &&
1100 			    key->type == HCI_LK_DEBUG_COMBINATION) {
1101 				list_del_rcu(&key->list);
1102 				kfree_rcu(key, rcu);
1103 			}
1104 		}
1105 	}
1106 }
1107 
1108 static void sc_add_ltk(struct smp_chan *smp)
1109 {
1110 	struct hci_conn *hcon = smp->conn->hcon;
1111 	u8 key_type, auth;
1112 
1113 	if (test_bit(SMP_FLAG_DEBUG_KEY, &smp->flags))
1114 		key_type = SMP_LTK_P256_DEBUG;
1115 	else
1116 		key_type = SMP_LTK_P256;
1117 
1118 	if (hcon->pending_sec_level == BT_SECURITY_FIPS)
1119 		auth = 1;
1120 	else
1121 		auth = 0;
1122 
1123 	smp->ltk = hci_add_ltk(hcon->hdev, &hcon->dst, hcon->dst_type,
1124 			       key_type, auth, smp->tk, smp->enc_key_size,
1125 			       0, 0);
1126 }
1127 
1128 static void sc_generate_link_key(struct smp_chan *smp)
1129 {
1130 	/* From core spec. Spells out in ASCII as 'lebr'. */
1131 	const u8 lebr[4] = { 0x72, 0x62, 0x65, 0x6c };
1132 
1133 	smp->link_key = kzalloc(16, GFP_KERNEL);
1134 	if (!smp->link_key)
1135 		return;
1136 
1137 	if (test_bit(SMP_FLAG_CT2, &smp->flags)) {
1138 		/* SALT = 0x000000000000000000000000746D7031 */
1139 		const u8 salt[16] = { 0x31, 0x70, 0x6d, 0x74 };
1140 
1141 		if (smp_h7(smp->tk, salt, smp->link_key)) {
1142 			kfree_sensitive(smp->link_key);
1143 			smp->link_key = NULL;
1144 			return;
1145 		}
1146 	} else {
1147 		/* From core spec. Spells out in ASCII as 'tmp1'. */
1148 		const u8 tmp1[4] = { 0x31, 0x70, 0x6d, 0x74 };
1149 
1150 		if (smp_h6(smp->tk, tmp1, smp->link_key)) {
1151 			kfree_sensitive(smp->link_key);
1152 			smp->link_key = NULL;
1153 			return;
1154 		}
1155 	}
1156 
1157 	if (smp_h6(smp->link_key, lebr, smp->link_key)) {
1158 		kfree_sensitive(smp->link_key);
1159 		smp->link_key = NULL;
1160 		return;
1161 	}
1162 }
1163 
1164 static void smp_allow_key_dist(struct smp_chan *smp)
1165 {
1166 	/* Allow the first expected phase 3 PDU. The rest of the PDUs
1167 	 * will be allowed in each PDU handler to ensure we receive
1168 	 * them in the correct order.
1169 	 */
1170 	if (smp->remote_key_dist & SMP_DIST_ENC_KEY)
1171 		SMP_ALLOW_CMD(smp, SMP_CMD_ENCRYPT_INFO);
1172 	else if (smp->remote_key_dist & SMP_DIST_ID_KEY)
1173 		SMP_ALLOW_CMD(smp, SMP_CMD_IDENT_INFO);
1174 	else if (smp->remote_key_dist & SMP_DIST_SIGN)
1175 		SMP_ALLOW_CMD(smp, SMP_CMD_SIGN_INFO);
1176 }
1177 
1178 static void sc_generate_ltk(struct smp_chan *smp)
1179 {
1180 	/* From core spec. Spells out in ASCII as 'brle'. */
1181 	const u8 brle[4] = { 0x65, 0x6c, 0x72, 0x62 };
1182 	struct hci_conn *hcon = smp->conn->hcon;
1183 	struct hci_dev *hdev = hcon->hdev;
1184 	struct link_key *key;
1185 
1186 	key = hci_find_link_key(hdev, &hcon->dst);
1187 	if (!key) {
1188 		bt_dev_err(hdev, "no Link Key found to generate LTK");
1189 		return;
1190 	}
1191 
1192 	if (key->type == HCI_LK_DEBUG_COMBINATION)
1193 		set_bit(SMP_FLAG_DEBUG_KEY, &smp->flags);
1194 
1195 	if (test_bit(SMP_FLAG_CT2, &smp->flags)) {
1196 		/* SALT = 0x000000000000000000000000746D7032 */
1197 		const u8 salt[16] = { 0x32, 0x70, 0x6d, 0x74 };
1198 
1199 		if (smp_h7(key->val, salt, smp->tk))
1200 			return;
1201 	} else {
1202 		/* From core spec. Spells out in ASCII as 'tmp2'. */
1203 		const u8 tmp2[4] = { 0x32, 0x70, 0x6d, 0x74 };
1204 
1205 		if (smp_h6(key->val, tmp2, smp->tk))
1206 			return;
1207 	}
1208 
1209 	if (smp_h6(smp->tk, brle, smp->tk))
1210 		return;
1211 
1212 	sc_add_ltk(smp);
1213 }
1214 
1215 static void smp_distribute_keys(struct smp_chan *smp)
1216 {
1217 	struct smp_cmd_pairing *req, *rsp;
1218 	struct l2cap_conn *conn = smp->conn;
1219 	struct hci_conn *hcon = conn->hcon;
1220 	struct hci_dev *hdev = hcon->hdev;
1221 	__u8 *keydist;
1222 
1223 	bt_dev_dbg(hdev, "conn %p", conn);
1224 
1225 	rsp = (void *) &smp->prsp[1];
1226 
1227 	/* The responder sends its keys first */
1228 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags) &&
1229 	    (smp->remote_key_dist & KEY_DIST_MASK)) {
1230 		smp_allow_key_dist(smp);
1231 		return;
1232 	}
1233 
1234 	req = (void *) &smp->preq[1];
1235 
1236 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
1237 		keydist = &rsp->init_key_dist;
1238 		*keydist &= req->init_key_dist;
1239 	} else {
1240 		keydist = &rsp->resp_key_dist;
1241 		*keydist &= req->resp_key_dist;
1242 	}
1243 
1244 	if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1245 		if (hcon->type == LE_LINK && (*keydist & SMP_DIST_LINK_KEY))
1246 			sc_generate_link_key(smp);
1247 		if (hcon->type == ACL_LINK && (*keydist & SMP_DIST_ENC_KEY))
1248 			sc_generate_ltk(smp);
1249 
1250 		/* Clear the keys which are generated but not distributed */
1251 		*keydist &= ~SMP_SC_NO_DIST;
1252 	}
1253 
1254 	bt_dev_dbg(hdev, "keydist 0x%x", *keydist);
1255 
1256 	if (*keydist & SMP_DIST_ENC_KEY) {
1257 		struct smp_cmd_encrypt_info enc;
1258 		struct smp_cmd_initiator_ident ident;
1259 		struct smp_ltk *ltk;
1260 		u8 authenticated;
1261 		__le16 ediv;
1262 		__le64 rand;
1263 
1264 		/* Make sure we generate only the significant amount of
1265 		 * bytes based on the encryption key size, and set the rest
1266 		 * of the value to zeroes.
1267 		 */
1268 		get_random_bytes(enc.ltk, smp->enc_key_size);
1269 		memset(enc.ltk + smp->enc_key_size, 0,
1270 		       sizeof(enc.ltk) - smp->enc_key_size);
1271 
1272 		get_random_bytes(&ediv, sizeof(ediv));
1273 		get_random_bytes(&rand, sizeof(rand));
1274 
1275 		smp_send_cmd(conn, SMP_CMD_ENCRYPT_INFO, sizeof(enc), &enc);
1276 
1277 		authenticated = hcon->sec_level == BT_SECURITY_HIGH;
1278 		ltk = hci_add_ltk(hdev, &hcon->dst, hcon->dst_type,
1279 				  SMP_LTK_RESPONDER, authenticated, enc.ltk,
1280 				  smp->enc_key_size, ediv, rand);
1281 		smp->responder_ltk = ltk;
1282 
1283 		ident.ediv = ediv;
1284 		ident.rand = rand;
1285 
1286 		smp_send_cmd(conn, SMP_CMD_INITIATOR_IDENT, sizeof(ident),
1287 			     &ident);
1288 
1289 		*keydist &= ~SMP_DIST_ENC_KEY;
1290 	}
1291 
1292 	if (*keydist & SMP_DIST_ID_KEY) {
1293 		struct smp_cmd_ident_addr_info addrinfo;
1294 		struct smp_cmd_ident_info idinfo;
1295 
1296 		memcpy(idinfo.irk, hdev->irk, sizeof(idinfo.irk));
1297 
1298 		smp_send_cmd(conn, SMP_CMD_IDENT_INFO, sizeof(idinfo), &idinfo);
1299 
1300 		/* The hci_conn contains the local identity address
1301 		 * after the connection has been established.
1302 		 *
1303 		 * This is true even when the connection has been
1304 		 * established using a resolvable random address.
1305 		 */
1306 		bacpy(&addrinfo.bdaddr, &hcon->src);
1307 		addrinfo.addr_type = hcon->src_type;
1308 
1309 		smp_send_cmd(conn, SMP_CMD_IDENT_ADDR_INFO, sizeof(addrinfo),
1310 			     &addrinfo);
1311 
1312 		*keydist &= ~SMP_DIST_ID_KEY;
1313 	}
1314 
1315 	if (*keydist & SMP_DIST_SIGN) {
1316 		struct smp_cmd_sign_info sign;
1317 		struct smp_csrk *csrk;
1318 
1319 		/* Generate a new random key */
1320 		get_random_bytes(sign.csrk, sizeof(sign.csrk));
1321 
1322 		csrk = kzalloc_obj(*csrk);
1323 		if (csrk) {
1324 			if (hcon->sec_level > BT_SECURITY_MEDIUM)
1325 				csrk->type = MGMT_CSRK_LOCAL_AUTHENTICATED;
1326 			else
1327 				csrk->type = MGMT_CSRK_LOCAL_UNAUTHENTICATED;
1328 			memcpy(csrk->val, sign.csrk, sizeof(csrk->val));
1329 		}
1330 		smp->responder_csrk = csrk;
1331 
1332 		smp_send_cmd(conn, SMP_CMD_SIGN_INFO, sizeof(sign), &sign);
1333 
1334 		*keydist &= ~SMP_DIST_SIGN;
1335 	}
1336 
1337 	/* If there are still keys to be received wait for them */
1338 	if (smp->remote_key_dist & KEY_DIST_MASK) {
1339 		smp_allow_key_dist(smp);
1340 		return;
1341 	}
1342 
1343 	set_bit(SMP_FLAG_COMPLETE, &smp->flags);
1344 	smp_notify_keys(conn);
1345 
1346 	smp_chan_destroy(conn);
1347 }
1348 
1349 static void smp_timeout(struct work_struct *work)
1350 {
1351 	struct smp_chan *smp = container_of(work, struct smp_chan,
1352 					    security_timer.work);
1353 	struct l2cap_conn *conn = smp->conn;
1354 
1355 	bt_dev_dbg(conn->hcon->hdev, "conn %p", conn);
1356 
1357 	hci_disconnect(conn->hcon, HCI_ERROR_AUTH_FAILURE);
1358 }
1359 
1360 static struct smp_chan *smp_chan_create(struct l2cap_conn *conn)
1361 {
1362 	struct hci_conn *hcon = conn->hcon;
1363 	struct l2cap_chan *chan = conn->smp;
1364 	struct smp_chan *smp;
1365 
1366 	smp = kzalloc_obj(*smp, GFP_ATOMIC);
1367 	if (!smp)
1368 		return NULL;
1369 
1370 	smp->tfm_ecdh = crypto_alloc_kpp("ecdh-nist-p256", 0, 0);
1371 	if (IS_ERR(smp->tfm_ecdh)) {
1372 		bt_dev_err(hcon->hdev, "Unable to create ECDH crypto context");
1373 		goto zfree_smp;
1374 	}
1375 
1376 	smp->conn = conn;
1377 	chan->data = smp;
1378 
1379 	SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_FAIL);
1380 
1381 	INIT_DELAYED_WORK(&smp->security_timer, smp_timeout);
1382 
1383 	hci_conn_hold(hcon);
1384 
1385 	return smp;
1386 
1387 zfree_smp:
1388 	kfree_sensitive(smp);
1389 	return NULL;
1390 }
1391 
1392 static int sc_mackey_and_ltk(struct smp_chan *smp, u8 mackey[16], u8 ltk[16])
1393 {
1394 	struct hci_conn *hcon = smp->conn->hcon;
1395 	u8 *na, *nb, a[7], b[7];
1396 
1397 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
1398 		na   = smp->prnd;
1399 		nb   = smp->rrnd;
1400 	} else {
1401 		na   = smp->rrnd;
1402 		nb   = smp->prnd;
1403 	}
1404 
1405 	memcpy(a, &hcon->init_addr, 6);
1406 	memcpy(b, &hcon->resp_addr, 6);
1407 	a[6] = hcon->init_addr_type;
1408 	b[6] = hcon->resp_addr_type;
1409 
1410 	return smp_f5(smp->dhkey, na, nb, a, b, mackey, ltk);
1411 }
1412 
1413 static void sc_dhkey_check(struct smp_chan *smp)
1414 {
1415 	struct hci_conn *hcon = smp->conn->hcon;
1416 	struct smp_cmd_dhkey_check check;
1417 	u8 a[7], b[7], *local_addr, *remote_addr;
1418 	u8 io_cap[3], r[16];
1419 
1420 	memcpy(a, &hcon->init_addr, 6);
1421 	memcpy(b, &hcon->resp_addr, 6);
1422 	a[6] = hcon->init_addr_type;
1423 	b[6] = hcon->resp_addr_type;
1424 
1425 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
1426 		local_addr = a;
1427 		remote_addr = b;
1428 		memcpy(io_cap, &smp->preq[1], 3);
1429 	} else {
1430 		local_addr = b;
1431 		remote_addr = a;
1432 		memcpy(io_cap, &smp->prsp[1], 3);
1433 	}
1434 
1435 	memset(r, 0, sizeof(r));
1436 
1437 	if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
1438 		put_unaligned_le32(hcon->passkey_notify, r);
1439 
1440 	if (smp->method == REQ_OOB)
1441 		memcpy(r, smp->rr, 16);
1442 
1443 	smp_f6(smp->mackey, smp->prnd, smp->rrnd, r, io_cap, local_addr,
1444 	       remote_addr, check.e);
1445 
1446 	smp_send_cmd(smp->conn, SMP_CMD_DHKEY_CHECK, sizeof(check), &check);
1447 }
1448 
1449 static u8 sc_passkey_send_confirm(struct smp_chan *smp)
1450 {
1451 	struct l2cap_conn *conn = smp->conn;
1452 	struct hci_conn *hcon = conn->hcon;
1453 	struct smp_cmd_pairing_confirm cfm;
1454 	u8 r;
1455 
1456 	r = ((hcon->passkey_notify >> smp->passkey_round) & 0x01);
1457 	r |= 0x80;
1458 
1459 	get_random_bytes(smp->prnd, sizeof(smp->prnd));
1460 
1461 	if (smp_f4(smp->local_pk, smp->remote_pk, smp->prnd, r,
1462 		   cfm.confirm_val))
1463 		return SMP_UNSPECIFIED;
1464 
1465 	smp_send_cmd(conn, SMP_CMD_PAIRING_CONFIRM, sizeof(cfm), &cfm);
1466 
1467 	return 0;
1468 }
1469 
1470 static u8 sc_passkey_round(struct smp_chan *smp, u8 smp_op)
1471 {
1472 	struct l2cap_conn *conn = smp->conn;
1473 	struct hci_conn *hcon = conn->hcon;
1474 	struct hci_dev *hdev = hcon->hdev;
1475 	u8 cfm[16], r;
1476 
1477 	/* Ignore the PDU if we've already done 20 rounds (0 - 19) */
1478 	if (smp->passkey_round >= 20)
1479 		return 0;
1480 
1481 	switch (smp_op) {
1482 	case SMP_CMD_PAIRING_RANDOM:
1483 		r = ((hcon->passkey_notify >> smp->passkey_round) & 0x01);
1484 		r |= 0x80;
1485 
1486 		if (smp_f4(smp->remote_pk, smp->local_pk, smp->rrnd, r, cfm))
1487 			return SMP_UNSPECIFIED;
1488 
1489 		if (crypto_memneq(smp->pcnf, cfm, 16))
1490 			return SMP_CONFIRM_FAILED;
1491 
1492 		smp->passkey_round++;
1493 
1494 		if (smp->passkey_round == 20) {
1495 			/* Generate MacKey and LTK */
1496 			if (sc_mackey_and_ltk(smp, smp->mackey, smp->tk))
1497 				return SMP_UNSPECIFIED;
1498 		}
1499 
1500 		/* The round is only complete when the initiator
1501 		 * receives pairing random.
1502 		 */
1503 		if (!test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
1504 			smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM,
1505 				     sizeof(smp->prnd), smp->prnd);
1506 			if (smp->passkey_round == 20)
1507 				SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1508 			else
1509 				SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
1510 			return 0;
1511 		}
1512 
1513 		/* Start the next round */
1514 		if (smp->passkey_round != 20)
1515 			return sc_passkey_round(smp, 0);
1516 
1517 		/* Passkey rounds are complete - start DHKey Check */
1518 		sc_dhkey_check(smp);
1519 		SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1520 
1521 		break;
1522 
1523 	case SMP_CMD_PAIRING_CONFIRM:
1524 		if (test_bit(SMP_FLAG_WAIT_USER, &smp->flags)) {
1525 			set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
1526 			return 0;
1527 		}
1528 
1529 		SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
1530 
1531 		if (test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
1532 			smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM,
1533 				     sizeof(smp->prnd), smp->prnd);
1534 			return 0;
1535 		}
1536 
1537 		return sc_passkey_send_confirm(smp);
1538 
1539 	case SMP_CMD_PUBLIC_KEY:
1540 	default:
1541 		/* Initiating device starts the round */
1542 		if (!test_bit(SMP_FLAG_INITIATOR, &smp->flags))
1543 			return 0;
1544 
1545 		bt_dev_dbg(hdev, "Starting passkey round %u",
1546 			   smp->passkey_round + 1);
1547 
1548 		SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
1549 
1550 		return sc_passkey_send_confirm(smp);
1551 	}
1552 
1553 	return 0;
1554 }
1555 
1556 static int sc_user_reply(struct smp_chan *smp, u16 mgmt_op, __le32 passkey)
1557 {
1558 	struct l2cap_conn *conn = smp->conn;
1559 	struct hci_conn *hcon = conn->hcon;
1560 	u8 smp_op;
1561 
1562 	clear_bit(SMP_FLAG_WAIT_USER, &smp->flags);
1563 
1564 	switch (mgmt_op) {
1565 	case MGMT_OP_USER_PASSKEY_NEG_REPLY:
1566 		smp_failure(smp->conn, SMP_PASSKEY_ENTRY_FAILED);
1567 		return 0;
1568 	case MGMT_OP_USER_CONFIRM_NEG_REPLY:
1569 		smp_failure(smp->conn, SMP_NUMERIC_COMP_FAILED);
1570 		return 0;
1571 	case MGMT_OP_USER_PASSKEY_REPLY:
1572 		hcon->passkey_notify = le32_to_cpu(passkey);
1573 		smp->passkey_round = 0;
1574 
1575 		if (test_and_clear_bit(SMP_FLAG_CFM_PENDING, &smp->flags))
1576 			smp_op = SMP_CMD_PAIRING_CONFIRM;
1577 		else
1578 			smp_op = 0;
1579 
1580 		if (sc_passkey_round(smp, smp_op))
1581 			return -EIO;
1582 
1583 		return 0;
1584 	}
1585 
1586 	/* Initiator sends DHKey check first */
1587 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
1588 		sc_dhkey_check(smp);
1589 		SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1590 	} else if (test_and_clear_bit(SMP_FLAG_DHKEY_PENDING, &smp->flags)) {
1591 		sc_dhkey_check(smp);
1592 		sc_add_ltk(smp);
1593 	}
1594 
1595 	return 0;
1596 }
1597 
1598 int smp_user_confirm_reply(struct hci_conn *hcon, u16 mgmt_op, __le32 passkey)
1599 {
1600 	struct l2cap_conn *conn = hcon->l2cap_data;
1601 	struct l2cap_chan *chan;
1602 	struct smp_chan *smp;
1603 	u32 value;
1604 	int err;
1605 
1606 	if (!conn)
1607 		return -ENOTCONN;
1608 
1609 	bt_dev_dbg(conn->hcon->hdev, "");
1610 
1611 	chan = conn->smp;
1612 	if (!chan)
1613 		return -ENOTCONN;
1614 
1615 	l2cap_chan_lock(chan);
1616 	if (!chan->data) {
1617 		err = -ENOTCONN;
1618 		goto unlock;
1619 	}
1620 
1621 	smp = chan->data;
1622 
1623 	if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1624 		err = sc_user_reply(smp, mgmt_op, passkey);
1625 		goto unlock;
1626 	}
1627 
1628 	switch (mgmt_op) {
1629 	case MGMT_OP_USER_PASSKEY_REPLY:
1630 		value = le32_to_cpu(passkey);
1631 		memset(smp->tk, 0, sizeof(smp->tk));
1632 		bt_dev_dbg(conn->hcon->hdev, "PassKey: %u", value);
1633 		put_unaligned_le32(value, smp->tk);
1634 		fallthrough;
1635 	case MGMT_OP_USER_CONFIRM_REPLY:
1636 		set_bit(SMP_FLAG_TK_VALID, &smp->flags);
1637 		break;
1638 	case MGMT_OP_USER_PASSKEY_NEG_REPLY:
1639 	case MGMT_OP_USER_CONFIRM_NEG_REPLY:
1640 		smp_failure(conn, SMP_PASSKEY_ENTRY_FAILED);
1641 		err = 0;
1642 		goto unlock;
1643 	default:
1644 		smp_failure(conn, SMP_PASSKEY_ENTRY_FAILED);
1645 		err = -EOPNOTSUPP;
1646 		goto unlock;
1647 	}
1648 
1649 	err = 0;
1650 
1651 	/* If it is our turn to send Pairing Confirm, do so now */
1652 	if (test_bit(SMP_FLAG_CFM_PENDING, &smp->flags)) {
1653 		u8 rsp = smp_confirm(smp);
1654 		if (rsp)
1655 			smp_failure(conn, rsp);
1656 	}
1657 
1658 unlock:
1659 	l2cap_chan_unlock(chan);
1660 	return err;
1661 }
1662 
1663 static void build_bredr_pairing_cmd(struct smp_chan *smp,
1664 				    struct smp_cmd_pairing *req,
1665 				    struct smp_cmd_pairing *rsp)
1666 {
1667 	struct l2cap_conn *conn = smp->conn;
1668 	struct hci_dev *hdev = conn->hcon->hdev;
1669 	u8 local_dist = 0, remote_dist = 0;
1670 
1671 	if (hci_dev_test_flag(hdev, HCI_BONDABLE)) {
1672 		local_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
1673 		remote_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
1674 	}
1675 
1676 	if (hci_dev_test_flag(hdev, HCI_RPA_RESOLVING))
1677 		remote_dist |= SMP_DIST_ID_KEY;
1678 
1679 	if (hci_dev_test_flag(hdev, HCI_PRIVACY))
1680 		local_dist |= SMP_DIST_ID_KEY;
1681 
1682 	if (!rsp) {
1683 		memset(req, 0, sizeof(*req));
1684 
1685 		req->auth_req        = SMP_AUTH_CT2;
1686 		req->init_key_dist   = local_dist;
1687 		req->resp_key_dist   = remote_dist;
1688 		req->max_key_size    = conn->hcon->enc_key_size;
1689 
1690 		smp->remote_key_dist = remote_dist;
1691 
1692 		return;
1693 	}
1694 
1695 	memset(rsp, 0, sizeof(*rsp));
1696 
1697 	rsp->auth_req        = SMP_AUTH_CT2;
1698 	rsp->max_key_size    = conn->hcon->enc_key_size;
1699 	rsp->init_key_dist   = req->init_key_dist & remote_dist;
1700 	rsp->resp_key_dist   = req->resp_key_dist & local_dist;
1701 
1702 	smp->remote_key_dist = rsp->init_key_dist;
1703 }
1704 
1705 static u8 smp_cmd_pairing_req(struct l2cap_conn *conn, struct sk_buff *skb)
1706 {
1707 	struct smp_cmd_pairing rsp, *req = (void *) skb->data;
1708 	struct l2cap_chan *chan = conn->smp;
1709 	struct hci_dev *hdev = conn->hcon->hdev;
1710 	struct smp_chan *smp = chan->data;
1711 	u8 key_size, auth, sec_level;
1712 	int ret;
1713 
1714 	bt_dev_dbg(hdev, "conn %p", conn);
1715 
1716 	if (skb->len < sizeof(*req))
1717 		return SMP_INVALID_PARAMS;
1718 
1719 	if (smp && test_bit(SMP_FLAG_INITIATOR, &smp->flags))
1720 		return SMP_CMD_NOTSUPP;
1721 
1722 	if (!smp) {
1723 		smp = smp_chan_create(conn);
1724 		if (!smp)
1725 			return SMP_UNSPECIFIED;
1726 	}
1727 
1728 	/* We didn't start the pairing, so match remote */
1729 	auth = req->auth_req & AUTH_REQ_MASK(hdev);
1730 
1731 	if (!hci_dev_test_flag(hdev, HCI_BONDABLE) &&
1732 	    (auth & SMP_AUTH_BONDING))
1733 		return SMP_PAIRING_NOTSUPP;
1734 
1735 	if (hci_dev_test_flag(hdev, HCI_SC_ONLY) && !(auth & SMP_AUTH_SC))
1736 		return SMP_AUTH_REQUIREMENTS;
1737 
1738 	smp->preq[0] = SMP_CMD_PAIRING_REQ;
1739 	memcpy(&smp->preq[1], req, sizeof(*req));
1740 	skb_pull(skb, sizeof(*req));
1741 
1742 	/* If the remote side's OOB flag is set it means it has
1743 	 * successfully received our local OOB data - therefore set the
1744 	 * flag to indicate that local OOB is in use.
1745 	 */
1746 	if (req->oob_flag == SMP_OOB_PRESENT && SMP_DEV(hdev)->local_oob)
1747 		set_bit(SMP_FLAG_LOCAL_OOB, &smp->flags);
1748 
1749 	/* SMP over BR/EDR requires special treatment */
1750 	if (conn->hcon->type == ACL_LINK) {
1751 		/* We must have a BR/EDR SC link */
1752 		if (!test_bit(HCI_CONN_AES_CCM, &conn->hcon->flags) &&
1753 		    !hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP))
1754 			return SMP_CROSS_TRANSP_NOT_ALLOWED;
1755 
1756 		set_bit(SMP_FLAG_SC, &smp->flags);
1757 
1758 		build_bredr_pairing_cmd(smp, req, &rsp);
1759 
1760 		if (req->auth_req & SMP_AUTH_CT2)
1761 			set_bit(SMP_FLAG_CT2, &smp->flags);
1762 
1763 		key_size = min(req->max_key_size, rsp.max_key_size);
1764 		if (check_enc_key_size(conn, key_size))
1765 			return SMP_ENC_KEY_SIZE;
1766 
1767 		/* Clear bits which are generated but not distributed */
1768 		smp->remote_key_dist &= ~SMP_SC_NO_DIST;
1769 
1770 		smp->prsp[0] = SMP_CMD_PAIRING_RSP;
1771 		memcpy(&smp->prsp[1], &rsp, sizeof(rsp));
1772 		smp_send_cmd(conn, SMP_CMD_PAIRING_RSP, sizeof(rsp), &rsp);
1773 
1774 		smp_distribute_keys(smp);
1775 		return 0;
1776 	}
1777 
1778 	build_pairing_cmd(conn, req, &rsp, auth);
1779 
1780 	if (rsp.auth_req & SMP_AUTH_SC) {
1781 		set_bit(SMP_FLAG_SC, &smp->flags);
1782 
1783 		if (rsp.auth_req & SMP_AUTH_CT2)
1784 			set_bit(SMP_FLAG_CT2, &smp->flags);
1785 	}
1786 
1787 	if (conn->hcon->io_capability == HCI_IO_NO_INPUT_OUTPUT)
1788 		sec_level = BT_SECURITY_MEDIUM;
1789 	else
1790 		sec_level = authreq_to_seclevel(auth);
1791 
1792 	if (sec_level > conn->hcon->pending_sec_level)
1793 		conn->hcon->pending_sec_level = sec_level;
1794 
1795 	/* If we need MITM check that it can be achieved. */
1796 	if (conn->hcon->pending_sec_level >= BT_SECURITY_HIGH) {
1797 		u8 method;
1798 
1799 		method = get_auth_method(smp, conn->hcon->io_capability,
1800 					 req->io_capability);
1801 		if (method == JUST_WORKS || method == JUST_CFM)
1802 			return SMP_AUTH_REQUIREMENTS;
1803 
1804 		/* Force MITM bit if it isn't set by the initiator. */
1805 		auth |= SMP_AUTH_MITM;
1806 		rsp.auth_req |= SMP_AUTH_MITM;
1807 	}
1808 
1809 	key_size = min(req->max_key_size, rsp.max_key_size);
1810 	if (check_enc_key_size(conn, key_size))
1811 		return SMP_ENC_KEY_SIZE;
1812 
1813 	get_random_bytes(smp->prnd, sizeof(smp->prnd));
1814 
1815 	smp->prsp[0] = SMP_CMD_PAIRING_RSP;
1816 	memcpy(&smp->prsp[1], &rsp, sizeof(rsp));
1817 
1818 	smp_send_cmd(conn, SMP_CMD_PAIRING_RSP, sizeof(rsp), &rsp);
1819 
1820 	clear_bit(SMP_FLAG_INITIATOR, &smp->flags);
1821 
1822 	/* Strictly speaking we shouldn't allow Pairing Confirm for the
1823 	 * SC case, however some implementations incorrectly copy RFU auth
1824 	 * req bits from our security request, which may create a false
1825 	 * positive SC enablement.
1826 	 */
1827 	SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
1828 
1829 	if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1830 		SMP_ALLOW_CMD(smp, SMP_CMD_PUBLIC_KEY);
1831 		/* Clear bits which are generated but not distributed */
1832 		smp->remote_key_dist &= ~SMP_SC_NO_DIST;
1833 		/* Wait for Public Key from Initiating Device */
1834 		return 0;
1835 	}
1836 
1837 	/* Request setup of TK */
1838 	ret = tk_request(conn, 0, auth, rsp.io_capability, req->io_capability);
1839 	if (ret)
1840 		return SMP_UNSPECIFIED;
1841 
1842 	return 0;
1843 }
1844 
1845 static u8 sc_send_public_key(struct smp_chan *smp)
1846 {
1847 	struct hci_dev *hdev = smp->conn->hcon->hdev;
1848 
1849 	bt_dev_dbg(hdev, "");
1850 
1851 	if (test_bit(SMP_FLAG_LOCAL_OOB, &smp->flags)) {
1852 		struct l2cap_chan *chan = hdev->smp_data;
1853 		struct smp_dev *smp_dev;
1854 
1855 		if (!chan || !chan->data)
1856 			return SMP_UNSPECIFIED;
1857 
1858 		smp_dev = chan->data;
1859 
1860 		memcpy(smp->local_pk, smp_dev->local_pk, 64);
1861 		memcpy(smp->lr, smp_dev->local_rand, 16);
1862 
1863 		if (smp_dev->debug_key)
1864 			set_bit(SMP_FLAG_DEBUG_KEY, &smp->flags);
1865 
1866 		goto done;
1867 	}
1868 
1869 	if (hci_dev_test_flag(hdev, HCI_USE_DEBUG_KEYS)) {
1870 		bt_dev_dbg(hdev, "Using debug keys");
1871 		if (set_ecdh_privkey(smp->tfm_ecdh, debug_sk))
1872 			return SMP_UNSPECIFIED;
1873 		memcpy(smp->local_pk, debug_pk, 64);
1874 		set_bit(SMP_FLAG_DEBUG_KEY, &smp->flags);
1875 	} else {
1876 		while (true) {
1877 			/* Generate key pair for Secure Connections */
1878 			if (generate_ecdh_keys(smp->tfm_ecdh, smp->local_pk))
1879 				return SMP_UNSPECIFIED;
1880 
1881 			/* This is unlikely, but we need to check that
1882 			 * we didn't accidentally generate a debug key.
1883 			 */
1884 			if (crypto_memneq(smp->local_pk, debug_pk, 64))
1885 				break;
1886 		}
1887 	}
1888 
1889 done:
1890 	SMP_DBG("Local Public Key X: %32phN", smp->local_pk);
1891 	SMP_DBG("Local Public Key Y: %32phN", smp->local_pk + 32);
1892 
1893 	smp_send_cmd(smp->conn, SMP_CMD_PUBLIC_KEY, 64, smp->local_pk);
1894 
1895 	return 0;
1896 }
1897 
1898 static u8 smp_cmd_pairing_rsp(struct l2cap_conn *conn, struct sk_buff *skb)
1899 {
1900 	struct smp_cmd_pairing *req, *rsp = (void *) skb->data;
1901 	struct l2cap_chan *chan = conn->smp;
1902 	struct smp_chan *smp = chan->data;
1903 	struct hci_dev *hdev = conn->hcon->hdev;
1904 	u8 key_size, auth;
1905 	int ret;
1906 
1907 	bt_dev_dbg(hdev, "conn %p", conn);
1908 
1909 	if (skb->len < sizeof(*rsp))
1910 		return SMP_INVALID_PARAMS;
1911 
1912 	if (!test_bit(SMP_FLAG_INITIATOR, &smp->flags))
1913 		return SMP_CMD_NOTSUPP;
1914 
1915 	skb_pull(skb, sizeof(*rsp));
1916 
1917 	req = (void *) &smp->preq[1];
1918 
1919 	key_size = min(req->max_key_size, rsp->max_key_size);
1920 	if (check_enc_key_size(conn, key_size))
1921 		return SMP_ENC_KEY_SIZE;
1922 
1923 	auth = rsp->auth_req & AUTH_REQ_MASK(hdev);
1924 
1925 	if (hci_dev_test_flag(hdev, HCI_SC_ONLY) && !(auth & SMP_AUTH_SC))
1926 		return SMP_AUTH_REQUIREMENTS;
1927 
1928 	/* If the remote side's OOB flag is set it means it has
1929 	 * successfully received our local OOB data - therefore set the
1930 	 * flag to indicate that local OOB is in use.
1931 	 */
1932 	if (rsp->oob_flag == SMP_OOB_PRESENT && SMP_DEV(hdev)->local_oob)
1933 		set_bit(SMP_FLAG_LOCAL_OOB, &smp->flags);
1934 
1935 	smp->prsp[0] = SMP_CMD_PAIRING_RSP;
1936 	memcpy(&smp->prsp[1], rsp, sizeof(*rsp));
1937 
1938 	/* Update remote key distribution in case the remote cleared
1939 	 * some bits that we had enabled in our request.
1940 	 */
1941 	smp->remote_key_dist &= rsp->resp_key_dist;
1942 
1943 	if ((req->auth_req & SMP_AUTH_CT2) && (auth & SMP_AUTH_CT2))
1944 		set_bit(SMP_FLAG_CT2, &smp->flags);
1945 
1946 	/* For BR/EDR this means we're done and can start phase 3 */
1947 	if (conn->hcon->type == ACL_LINK) {
1948 		/* Clear bits which are generated but not distributed */
1949 		smp->remote_key_dist &= ~SMP_SC_NO_DIST;
1950 		smp_distribute_keys(smp);
1951 		return 0;
1952 	}
1953 
1954 	if ((req->auth_req & SMP_AUTH_SC) && (auth & SMP_AUTH_SC))
1955 		set_bit(SMP_FLAG_SC, &smp->flags);
1956 	else if (conn->hcon->pending_sec_level > BT_SECURITY_HIGH)
1957 		conn->hcon->pending_sec_level = BT_SECURITY_HIGH;
1958 
1959 	/* If we need MITM check that it can be achieved */
1960 	if (conn->hcon->pending_sec_level >= BT_SECURITY_HIGH) {
1961 		u8 method;
1962 
1963 		method = get_auth_method(smp, req->io_capability,
1964 					 rsp->io_capability);
1965 		if (method == JUST_WORKS || method == JUST_CFM)
1966 			return SMP_AUTH_REQUIREMENTS;
1967 	}
1968 
1969 	get_random_bytes(smp->prnd, sizeof(smp->prnd));
1970 
1971 	/* Update remote key distribution in case the remote cleared
1972 	 * some bits that we had enabled in our request.
1973 	 */
1974 	smp->remote_key_dist &= rsp->resp_key_dist;
1975 
1976 	if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1977 		/* Clear bits which are generated but not distributed */
1978 		smp->remote_key_dist &= ~SMP_SC_NO_DIST;
1979 		SMP_ALLOW_CMD(smp, SMP_CMD_PUBLIC_KEY);
1980 		return sc_send_public_key(smp);
1981 	}
1982 
1983 	auth |= req->auth_req;
1984 
1985 	ret = tk_request(conn, 0, auth, req->io_capability, rsp->io_capability);
1986 	if (ret)
1987 		return SMP_UNSPECIFIED;
1988 
1989 	set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
1990 
1991 	/* Can't compose response until we have been confirmed */
1992 	if (test_bit(SMP_FLAG_TK_VALID, &smp->flags))
1993 		return smp_confirm(smp);
1994 
1995 	return 0;
1996 }
1997 
1998 static u8 sc_check_confirm(struct smp_chan *smp)
1999 {
2000 	struct l2cap_conn *conn = smp->conn;
2001 
2002 	bt_dev_dbg(conn->hcon->hdev, "");
2003 
2004 	if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
2005 		return sc_passkey_round(smp, SMP_CMD_PAIRING_CONFIRM);
2006 
2007 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
2008 		smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
2009 			     smp->prnd);
2010 		SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
2011 	}
2012 
2013 	return 0;
2014 }
2015 
2016 /* Work-around for some implementations that incorrectly copy RFU bits
2017  * from our security request and thereby create the impression that
2018  * we're doing SC when in fact the remote doesn't support it.
2019  */
2020 static int fixup_sc_false_positive(struct smp_chan *smp)
2021 {
2022 	struct l2cap_conn *conn = smp->conn;
2023 	struct hci_conn *hcon = conn->hcon;
2024 	struct hci_dev *hdev = hcon->hdev;
2025 	struct smp_cmd_pairing *req, *rsp;
2026 	u8 auth;
2027 
2028 	/* The issue is only observed when we're in responder role */
2029 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags))
2030 		return SMP_UNSPECIFIED;
2031 
2032 	if (hci_dev_test_flag(hdev, HCI_SC_ONLY)) {
2033 		bt_dev_err(hdev, "refusing legacy fallback in SC-only mode");
2034 		return SMP_UNSPECIFIED;
2035 	}
2036 
2037 	bt_dev_err(hdev, "trying to fall back to legacy SMP");
2038 
2039 	req = (void *) &smp->preq[1];
2040 	rsp = (void *) &smp->prsp[1];
2041 
2042 	/* Rebuild key dist flags which may have been cleared for SC */
2043 	smp->remote_key_dist = (req->init_key_dist & rsp->resp_key_dist);
2044 
2045 	auth = req->auth_req & AUTH_REQ_MASK(hdev);
2046 
2047 	if (tk_request(conn, 0, auth, rsp->io_capability, req->io_capability)) {
2048 		bt_dev_err(hdev, "failed to fall back to legacy SMP");
2049 		return SMP_UNSPECIFIED;
2050 	}
2051 
2052 	clear_bit(SMP_FLAG_SC, &smp->flags);
2053 
2054 	return 0;
2055 }
2056 
2057 static u8 smp_cmd_pairing_confirm(struct l2cap_conn *conn, struct sk_buff *skb)
2058 {
2059 	struct l2cap_chan *chan = conn->smp;
2060 	struct smp_chan *smp = chan->data;
2061 	struct hci_conn *hcon = conn->hcon;
2062 	struct hci_dev *hdev = hcon->hdev;
2063 
2064 	bt_dev_dbg(hdev, "conn %p %s", conn,
2065 		   test_bit(SMP_FLAG_INITIATOR, &smp->flags) ? "initiator" :
2066 		   "responder");
2067 
2068 	if (skb->len < sizeof(smp->pcnf))
2069 		return SMP_INVALID_PARAMS;
2070 
2071 	memcpy(smp->pcnf, skb->data, sizeof(smp->pcnf));
2072 	skb_pull(skb, sizeof(smp->pcnf));
2073 
2074 	if (test_bit(SMP_FLAG_SC, &smp->flags)) {
2075 		int ret;
2076 
2077 		/* Public Key exchange must happen before any other steps */
2078 		if (test_bit(SMP_FLAG_REMOTE_PK, &smp->flags))
2079 			return sc_check_confirm(smp);
2080 
2081 		bt_dev_err(hdev, "Unexpected SMP Pairing Confirm");
2082 
2083 		ret = fixup_sc_false_positive(smp);
2084 		if (ret)
2085 			return ret;
2086 	}
2087 
2088 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
2089 		smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
2090 			     smp->prnd);
2091 		SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
2092 		return 0;
2093 	}
2094 
2095 	if (test_bit(SMP_FLAG_TK_VALID, &smp->flags))
2096 		return smp_confirm(smp);
2097 
2098 	set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
2099 
2100 	return 0;
2101 }
2102 
2103 static u8 smp_cmd_pairing_random(struct l2cap_conn *conn, struct sk_buff *skb)
2104 {
2105 	struct l2cap_chan *chan = conn->smp;
2106 	struct smp_chan *smp = chan->data;
2107 	struct hci_conn *hcon = conn->hcon;
2108 	u8 *pkax, *pkbx, *na, *nb, confirm_hint;
2109 	u32 passkey = 0;
2110 	int err;
2111 
2112 	bt_dev_dbg(hcon->hdev, "conn %p", conn);
2113 
2114 	if (skb->len < sizeof(smp->rrnd))
2115 		return SMP_INVALID_PARAMS;
2116 
2117 	memcpy(smp->rrnd, skb->data, sizeof(smp->rrnd));
2118 	skb_pull(skb, sizeof(smp->rrnd));
2119 
2120 	if (!test_bit(SMP_FLAG_SC, &smp->flags))
2121 		return smp_random(smp);
2122 
2123 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
2124 		pkax = smp->local_pk;
2125 		pkbx = smp->remote_pk;
2126 		na   = smp->prnd;
2127 		nb   = smp->rrnd;
2128 	} else {
2129 		pkax = smp->remote_pk;
2130 		pkbx = smp->local_pk;
2131 		na   = smp->rrnd;
2132 		nb   = smp->prnd;
2133 	}
2134 
2135 	if (smp->method == REQ_OOB) {
2136 		if (!test_bit(SMP_FLAG_INITIATOR, &smp->flags))
2137 			smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM,
2138 				     sizeof(smp->prnd), smp->prnd);
2139 		SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
2140 		goto mackey_and_ltk;
2141 	}
2142 
2143 	/* Passkey entry has special treatment */
2144 	if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
2145 		return sc_passkey_round(smp, SMP_CMD_PAIRING_RANDOM);
2146 
2147 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
2148 		u8 cfm[16];
2149 
2150 		err = smp_f4(smp->remote_pk, smp->local_pk, smp->rrnd, 0, cfm);
2151 		if (err)
2152 			return SMP_UNSPECIFIED;
2153 
2154 		if (crypto_memneq(smp->pcnf, cfm, 16))
2155 			return SMP_CONFIRM_FAILED;
2156 	} else {
2157 		smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
2158 			     smp->prnd);
2159 		SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
2160 	}
2161 
2162 mackey_and_ltk:
2163 	/* Generate MacKey and LTK */
2164 	err = sc_mackey_and_ltk(smp, smp->mackey, smp->tk);
2165 	if (err)
2166 		return SMP_UNSPECIFIED;
2167 
2168 	if (smp->method == REQ_OOB) {
2169 		if (test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
2170 			sc_dhkey_check(smp);
2171 			SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
2172 		}
2173 		return 0;
2174 	}
2175 
2176 	err = smp_g2(pkax, pkbx, na, nb, &passkey);
2177 	if (err)
2178 		return SMP_UNSPECIFIED;
2179 
2180 	/* Always require user confirmation for Just-Works pairing to prevent
2181 	 * impersonation attacks, or in case of a legitimate device that is
2182 	 * repairing use the confirmation as acknowledgment to proceed with the
2183 	 * creation of new keys.
2184 	 */
2185 	confirm_hint = smp->method == JUST_WORKS ? 1 : 0;
2186 
2187 	err = mgmt_user_confirm_request(hcon->hdev, &hcon->dst, hcon->type,
2188 					hcon->dst_type, passkey, confirm_hint);
2189 	if (err)
2190 		return SMP_UNSPECIFIED;
2191 
2192 	set_bit(SMP_FLAG_WAIT_USER, &smp->flags);
2193 
2194 	return 0;
2195 }
2196 
2197 static bool smp_ltk_encrypt(struct l2cap_conn *conn, u8 sec_level)
2198 {
2199 	struct smp_ltk *key;
2200 	struct hci_conn *hcon = conn->hcon;
2201 
2202 	key = hci_find_ltk(hcon->hdev, &hcon->dst, hcon->dst_type, hcon->role);
2203 	if (!key)
2204 		return false;
2205 
2206 	if (smp_ltk_sec_level(key) < sec_level)
2207 		return false;
2208 
2209 	if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags))
2210 		return true;
2211 
2212 	hci_le_start_enc(hcon, key->ediv, key->rand, key->val, key->enc_size);
2213 	hcon->enc_key_size = key->enc_size;
2214 
2215 	/* We never store STKs for initiator role, so clear this flag */
2216 	clear_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags);
2217 
2218 	return true;
2219 }
2220 
2221 bool smp_sufficient_security(struct hci_conn *hcon, u8 sec_level,
2222 			     enum smp_key_pref key_pref)
2223 {
2224 	if (sec_level == BT_SECURITY_LOW)
2225 		return true;
2226 
2227 	/* If we're encrypted with an STK but the caller prefers using
2228 	 * LTK claim insufficient security. This way we allow the
2229 	 * connection to be re-encrypted with an LTK, even if the LTK
2230 	 * provides the same level of security. Only exception is if we
2231 	 * don't have an LTK (e.g. because of key distribution bits).
2232 	 */
2233 	if (key_pref == SMP_USE_LTK &&
2234 	    test_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags) &&
2235 	    hci_find_ltk(hcon->hdev, &hcon->dst, hcon->dst_type, hcon->role))
2236 		return false;
2237 
2238 	if (hcon->sec_level >= sec_level)
2239 		return true;
2240 
2241 	return false;
2242 }
2243 
2244 static void smp_send_pairing_req(struct smp_chan *smp, __u8 auth)
2245 {
2246 	struct smp_cmd_pairing cp;
2247 
2248 	if (smp->conn->hcon->type == ACL_LINK)
2249 		build_bredr_pairing_cmd(smp, &cp, NULL);
2250 	else
2251 		build_pairing_cmd(smp->conn, &cp, NULL, auth);
2252 
2253 	smp->preq[0] = SMP_CMD_PAIRING_REQ;
2254 	memcpy(&smp->preq[1], &cp, sizeof(cp));
2255 
2256 	smp_send_cmd(smp->conn, SMP_CMD_PAIRING_REQ, sizeof(cp), &cp);
2257 	SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RSP);
2258 
2259 	set_bit(SMP_FLAG_INITIATOR, &smp->flags);
2260 }
2261 
2262 static u8 smp_cmd_security_req(struct l2cap_conn *conn, struct sk_buff *skb)
2263 {
2264 	struct smp_cmd_security_req *rp = (void *) skb->data;
2265 	struct hci_conn *hcon = conn->hcon;
2266 	struct hci_dev *hdev = hcon->hdev;
2267 	struct smp_chan *smp;
2268 	u8 sec_level, auth;
2269 
2270 	bt_dev_dbg(hdev, "conn %p", conn);
2271 
2272 	/* SMP over BR/EDR only covers cross-transport key derivation; the
2273 	 * Security Request procedure has no BR/EDR counterpart. Reject it
2274 	 * here, otherwise smp_ltk_encrypt() finds the peer's LE LTK
2275 	 * (ADDR_LE_DEV_PUBLIC and BDADDR_BREDR are both 0) and issues
2276 	 * HCI_OP_LE_START_ENC on the ACL handle, which the controller
2277 	 * rejects and hci_cs_le_start_enc() turns into a disconnect. Reply
2278 	 * without smp_failure(): this is not an authentication failure, and
2279 	 * MGMT_EV_AUTH_FAILED would make bluetoothd drop the device.
2280 	 */
2281 	if (hcon->type != LE_LINK) {
2282 		u8 reason = SMP_CMD_NOTSUPP;
2283 
2284 		smp_send_cmd(conn, SMP_CMD_PAIRING_FAIL, sizeof(reason),
2285 			     &reason);
2286 		return 0;
2287 	}
2288 
2289 	if (skb->len < sizeof(*rp))
2290 		return SMP_INVALID_PARAMS;
2291 
2292 	if (hcon->role != HCI_ROLE_MASTER)
2293 		return SMP_CMD_NOTSUPP;
2294 
2295 	auth = rp->auth_req & AUTH_REQ_MASK(hdev);
2296 
2297 	if (hci_dev_test_flag(hdev, HCI_SC_ONLY) && !(auth & SMP_AUTH_SC))
2298 		return SMP_AUTH_REQUIREMENTS;
2299 
2300 	if (hcon->io_capability == HCI_IO_NO_INPUT_OUTPUT)
2301 		sec_level = BT_SECURITY_MEDIUM;
2302 	else
2303 		sec_level = authreq_to_seclevel(auth);
2304 
2305 	if (smp_sufficient_security(hcon, sec_level, SMP_USE_LTK)) {
2306 		/* If link is already encrypted with sufficient security we
2307 		 * still need refresh encryption as per Core Spec 5.0 Vol 3,
2308 		 * Part H 2.4.6
2309 		 */
2310 		smp_ltk_encrypt(conn, hcon->sec_level);
2311 		return 0;
2312 	}
2313 
2314 	if (sec_level > hcon->pending_sec_level)
2315 		hcon->pending_sec_level = sec_level;
2316 
2317 	if (smp_ltk_encrypt(conn, hcon->pending_sec_level))
2318 		return 0;
2319 
2320 	smp = smp_chan_create(conn);
2321 	if (!smp)
2322 		return SMP_UNSPECIFIED;
2323 
2324 	if (!hci_dev_test_flag(hdev, HCI_BONDABLE) &&
2325 	    (auth & SMP_AUTH_BONDING))
2326 		return SMP_PAIRING_NOTSUPP;
2327 
2328 	skb_pull(skb, sizeof(*rp));
2329 
2330 	smp_send_pairing_req(smp, auth);
2331 
2332 	return 0;
2333 }
2334 
2335 static void smp_send_security_req(struct smp_chan *smp, __u8 auth)
2336 {
2337 	struct smp_cmd_security_req cp;
2338 
2339 	cp.auth_req = auth;
2340 	smp_send_cmd(smp->conn, SMP_CMD_SECURITY_REQ, sizeof(cp), &cp);
2341 	SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_REQ);
2342 
2343 	clear_bit(SMP_FLAG_INITIATOR, &smp->flags);
2344 }
2345 
2346 int smp_conn_security(struct hci_conn *hcon, __u8 sec_level)
2347 {
2348 	struct l2cap_conn *conn;
2349 	struct l2cap_chan *chan;
2350 	struct smp_chan *smp;
2351 	__u8 authreq;
2352 	int ret;
2353 
2354 	/* Caller shall ensure there can be no race with l2cap_conn_del() */
2355 	conn = context_unsafe(hcon->l2cap_data);
2356 
2357 	bt_dev_dbg(hcon->hdev, "conn %p hcon %p level 0x%2.2x", conn, hcon,
2358 		   sec_level);
2359 
2360 	/* This may be NULL if there's an unexpected disconnection */
2361 	if (!conn)
2362 		return 1;
2363 
2364 	if (!hci_dev_test_flag(hcon->hdev, HCI_LE_ENABLED))
2365 		return 1;
2366 
2367 	if (smp_sufficient_security(hcon, sec_level, SMP_USE_LTK))
2368 		return 1;
2369 
2370 	if (sec_level > hcon->pending_sec_level)
2371 		hcon->pending_sec_level = sec_level;
2372 
2373 	if (hcon->role == HCI_ROLE_MASTER)
2374 		if (smp_ltk_encrypt(conn, hcon->pending_sec_level))
2375 			return 0;
2376 
2377 	chan = conn->smp;
2378 	if (!chan) {
2379 		bt_dev_err(hcon->hdev, "security requested but not available");
2380 		return 1;
2381 	}
2382 
2383 	l2cap_chan_lock(chan);
2384 
2385 	/* If SMP is already in progress ignore this request */
2386 	if (chan->data) {
2387 		ret = 0;
2388 		goto unlock;
2389 	}
2390 
2391 	smp = smp_chan_create(conn);
2392 	if (!smp) {
2393 		ret = 1;
2394 		goto unlock;
2395 	}
2396 
2397 	authreq = seclevel_to_authreq(sec_level);
2398 
2399 	if (hci_dev_test_flag(hcon->hdev, HCI_SC_ENABLED)) {
2400 		authreq |= SMP_AUTH_SC;
2401 		if (hci_dev_test_flag(hcon->hdev, HCI_SSP_ENABLED))
2402 			authreq |= SMP_AUTH_CT2;
2403 	}
2404 
2405 	/* Don't attempt to set MITM if setting is overridden by debugfs
2406 	 * Needed to pass certification test SM/MAS/PKE/BV-01-C
2407 	 */
2408 	if (!hci_dev_test_flag(hcon->hdev, HCI_FORCE_NO_MITM)) {
2409 		/* Require MITM if IO Capability allows or the security level
2410 		 * requires it.
2411 		 */
2412 		if (hcon->io_capability != HCI_IO_NO_INPUT_OUTPUT ||
2413 		    hcon->pending_sec_level > BT_SECURITY_MEDIUM)
2414 			authreq |= SMP_AUTH_MITM;
2415 	}
2416 
2417 	if (hcon->role == HCI_ROLE_MASTER)
2418 		smp_send_pairing_req(smp, authreq);
2419 	else
2420 		smp_send_security_req(smp, authreq);
2421 
2422 	ret = 0;
2423 
2424 unlock:
2425 	l2cap_chan_unlock(chan);
2426 	return ret;
2427 }
2428 
2429 int smp_cancel_and_remove_pairing(struct hci_dev *hdev, bdaddr_t *bdaddr,
2430 				  u8 addr_type)
2431 {
2432 	struct hci_conn *hcon;
2433 	struct l2cap_conn *conn;
2434 	struct l2cap_chan *chan;
2435 	struct smp_chan *smp;
2436 	int err;
2437 
2438 	err = hci_remove_ltk(hdev, bdaddr, addr_type);
2439 	hci_remove_irk(hdev, bdaddr, addr_type);
2440 
2441 	hcon = hci_conn_hash_lookup_le(hdev, bdaddr, addr_type);
2442 	if (!hcon)
2443 		goto done;
2444 
2445 	lockdep_assert_held(&hcon->hdev->lock);
2446 
2447 	conn = hcon->l2cap_data;
2448 	if (!conn)
2449 		goto done;
2450 
2451 	chan = conn->smp;
2452 	if (!chan)
2453 		goto done;
2454 
2455 	l2cap_chan_lock(chan);
2456 
2457 	smp = chan->data;
2458 	if (smp) {
2459 		/* Set keys to NULL to make sure smp_failure() does not try to
2460 		 * remove and free already invalidated rcu list entries. */
2461 		smp->ltk = NULL;
2462 		smp->responder_ltk = NULL;
2463 		smp->remote_irk = NULL;
2464 
2465 		if (test_bit(SMP_FLAG_COMPLETE, &smp->flags))
2466 			smp_failure(conn, 0);
2467 		else
2468 			smp_failure(conn, SMP_UNSPECIFIED);
2469 		err = 0;
2470 	}
2471 
2472 	l2cap_chan_unlock(chan);
2473 
2474 done:
2475 	return err;
2476 }
2477 
2478 static int smp_cmd_encrypt_info(struct l2cap_conn *conn, struct sk_buff *skb)
2479 {
2480 	struct smp_cmd_encrypt_info *rp = (void *) skb->data;
2481 	struct l2cap_chan *chan = conn->smp;
2482 	struct smp_chan *smp = chan->data;
2483 
2484 	bt_dev_dbg(conn->hcon->hdev, "conn %p", conn);
2485 
2486 	if (skb->len < sizeof(*rp))
2487 		return SMP_INVALID_PARAMS;
2488 
2489 	/* Pairing is aborted if any blocked keys are distributed */
2490 	if (hci_is_blocked_key(conn->hcon->hdev, HCI_BLOCKED_KEY_TYPE_LTK,
2491 			       rp->ltk)) {
2492 		bt_dev_warn_ratelimited(conn->hcon->hdev,
2493 					"LTK blocked for %pMR",
2494 					&conn->hcon->dst);
2495 		return SMP_INVALID_PARAMS;
2496 	}
2497 
2498 	SMP_ALLOW_CMD(smp, SMP_CMD_INITIATOR_IDENT);
2499 
2500 	skb_pull(skb, sizeof(*rp));
2501 
2502 	memcpy(smp->tk, rp->ltk, sizeof(smp->tk));
2503 
2504 	return 0;
2505 }
2506 
2507 static int smp_cmd_initiator_ident(struct l2cap_conn *conn, struct sk_buff *skb)
2508 {
2509 	struct smp_cmd_initiator_ident *rp = (void *)skb->data;
2510 	struct l2cap_chan *chan = conn->smp;
2511 	struct smp_chan *smp = chan->data;
2512 	struct hci_dev *hdev = conn->hcon->hdev;
2513 	struct hci_conn *hcon = conn->hcon;
2514 	struct smp_ltk *ltk;
2515 	u8 authenticated;
2516 
2517 	bt_dev_dbg(hdev, "conn %p", conn);
2518 
2519 	if (skb->len < sizeof(*rp))
2520 		return SMP_INVALID_PARAMS;
2521 
2522 	/* Mark the information as received */
2523 	smp->remote_key_dist &= ~SMP_DIST_ENC_KEY;
2524 
2525 	if (smp->remote_key_dist & SMP_DIST_ID_KEY)
2526 		SMP_ALLOW_CMD(smp, SMP_CMD_IDENT_INFO);
2527 	else if (smp->remote_key_dist & SMP_DIST_SIGN)
2528 		SMP_ALLOW_CMD(smp, SMP_CMD_SIGN_INFO);
2529 
2530 	skb_pull(skb, sizeof(*rp));
2531 
2532 	authenticated = (hcon->sec_level == BT_SECURITY_HIGH);
2533 	ltk = hci_add_ltk(hdev, &hcon->dst, hcon->dst_type, SMP_LTK,
2534 			  authenticated, smp->tk, smp->enc_key_size,
2535 			  rp->ediv, rp->rand);
2536 	smp->ltk = ltk;
2537 	if (!(smp->remote_key_dist & KEY_DIST_MASK))
2538 		smp_distribute_keys(smp);
2539 
2540 	return 0;
2541 }
2542 
2543 static int smp_cmd_ident_info(struct l2cap_conn *conn, struct sk_buff *skb)
2544 {
2545 	struct smp_cmd_ident_info *info = (void *) skb->data;
2546 	struct l2cap_chan *chan = conn->smp;
2547 	struct smp_chan *smp = chan->data;
2548 
2549 	bt_dev_dbg(conn->hcon->hdev, "");
2550 
2551 	if (skb->len < sizeof(*info))
2552 		return SMP_INVALID_PARAMS;
2553 
2554 	/* Pairing is aborted if any blocked keys are distributed */
2555 	if (hci_is_blocked_key(conn->hcon->hdev, HCI_BLOCKED_KEY_TYPE_IRK,
2556 			       info->irk)) {
2557 		bt_dev_warn_ratelimited(conn->hcon->hdev,
2558 					"Identity key blocked for %pMR",
2559 					&conn->hcon->dst);
2560 		return SMP_INVALID_PARAMS;
2561 	}
2562 
2563 	SMP_ALLOW_CMD(smp, SMP_CMD_IDENT_ADDR_INFO);
2564 
2565 	skb_pull(skb, sizeof(*info));
2566 
2567 	memcpy(smp->irk, info->irk, 16);
2568 
2569 	return 0;
2570 }
2571 
2572 static int smp_cmd_ident_addr_info(struct l2cap_conn *conn,
2573 				   struct sk_buff *skb)
2574 {
2575 	struct smp_cmd_ident_addr_info *info = (void *) skb->data;
2576 	struct l2cap_chan *chan = conn->smp;
2577 	struct smp_chan *smp = chan->data;
2578 	struct hci_conn *hcon = conn->hcon;
2579 	bdaddr_t rpa;
2580 
2581 	bt_dev_dbg(hcon->hdev, "");
2582 
2583 	if (skb->len < sizeof(*info))
2584 		return SMP_INVALID_PARAMS;
2585 
2586 	/* Mark the information as received */
2587 	smp->remote_key_dist &= ~SMP_DIST_ID_KEY;
2588 
2589 	if (smp->remote_key_dist & SMP_DIST_SIGN)
2590 		SMP_ALLOW_CMD(smp, SMP_CMD_SIGN_INFO);
2591 
2592 	skb_pull(skb, sizeof(*info));
2593 
2594 	/* Strictly speaking the Core Specification (4.1) allows sending
2595 	 * an empty address which would force us to rely on just the IRK
2596 	 * as "identity information". However, since such
2597 	 * implementations are not known of and in order to not over
2598 	 * complicate our implementation, simply pretend that we never
2599 	 * received an IRK for such a device.
2600 	 *
2601 	 * The Identity Address must also be a Static Random or Public
2602 	 * Address, which hci_is_identity_address() checks for.
2603 	 */
2604 	if (!bacmp(&info->bdaddr, BDADDR_ANY) ||
2605 	    !hci_is_identity_address(&info->bdaddr, info->addr_type)) {
2606 		bt_dev_err(hcon->hdev, "ignoring IRK with no identity address");
2607 		goto distribute;
2608 	}
2609 
2610 	/* Drop IRK if peer is using identity address during pairing but is
2611 	 * providing different address as identity information.
2612 	 *
2613 	 * Microsoft Surface Precision Mouse is known to have this bug.
2614 	 */
2615 	if (hci_is_identity_address(&hcon->dst, hcon->dst_type) &&
2616 	    (bacmp(&info->bdaddr, &hcon->dst) ||
2617 	     info->addr_type != hcon->dst_type)) {
2618 		bt_dev_err(hcon->hdev,
2619 			   "ignoring IRK with invalid identity address");
2620 		goto distribute;
2621 	}
2622 
2623 	bacpy(&smp->id_addr, &info->bdaddr);
2624 	smp->id_addr_type = info->addr_type;
2625 
2626 	if (hci_bdaddr_is_rpa(&hcon->dst, hcon->dst_type))
2627 		bacpy(&rpa, &hcon->dst);
2628 	else
2629 		bacpy(&rpa, BDADDR_ANY);
2630 
2631 	smp->remote_irk = hci_add_irk(conn->hcon->hdev, &smp->id_addr,
2632 				      smp->id_addr_type, smp->irk, &rpa);
2633 
2634 distribute:
2635 	if (!(smp->remote_key_dist & KEY_DIST_MASK))
2636 		smp_distribute_keys(smp);
2637 
2638 	return 0;
2639 }
2640 
2641 static int smp_cmd_sign_info(struct l2cap_conn *conn, struct sk_buff *skb)
2642 {
2643 	struct smp_cmd_sign_info *rp = (void *) skb->data;
2644 	struct l2cap_chan *chan = conn->smp;
2645 	struct smp_chan *smp = chan->data;
2646 	struct smp_csrk *csrk;
2647 
2648 	bt_dev_dbg(conn->hcon->hdev, "conn %p", conn);
2649 
2650 	if (skb->len < sizeof(*rp))
2651 		return SMP_INVALID_PARAMS;
2652 
2653 	/* Mark the information as received */
2654 	smp->remote_key_dist &= ~SMP_DIST_SIGN;
2655 
2656 	skb_pull(skb, sizeof(*rp));
2657 
2658 	csrk = kzalloc_obj(*csrk);
2659 	if (csrk) {
2660 		if (conn->hcon->sec_level > BT_SECURITY_MEDIUM)
2661 			csrk->type = MGMT_CSRK_REMOTE_AUTHENTICATED;
2662 		else
2663 			csrk->type = MGMT_CSRK_REMOTE_UNAUTHENTICATED;
2664 		memcpy(csrk->val, rp->csrk, sizeof(csrk->val));
2665 	}
2666 	smp->csrk = csrk;
2667 	smp_distribute_keys(smp);
2668 
2669 	return 0;
2670 }
2671 
2672 static u8 sc_select_method(struct smp_chan *smp)
2673 {
2674 	struct smp_cmd_pairing *local, *remote;
2675 	u8 local_mitm, remote_mitm, local_io, remote_io, method;
2676 
2677 	if (test_bit(SMP_FLAG_REMOTE_OOB, &smp->flags) ||
2678 	    test_bit(SMP_FLAG_LOCAL_OOB, &smp->flags))
2679 		return REQ_OOB;
2680 
2681 	/* The preq/prsp contain the raw Pairing Request/Response PDUs
2682 	 * which are needed as inputs to some crypto functions. To get
2683 	 * the "struct smp_cmd_pairing" from them we need to skip the
2684 	 * first byte which contains the opcode.
2685 	 */
2686 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
2687 		local = (void *) &smp->preq[1];
2688 		remote = (void *) &smp->prsp[1];
2689 	} else {
2690 		local = (void *) &smp->prsp[1];
2691 		remote = (void *) &smp->preq[1];
2692 	}
2693 
2694 	local_io = local->io_capability;
2695 	remote_io = remote->io_capability;
2696 
2697 	local_mitm = (local->auth_req & SMP_AUTH_MITM);
2698 	remote_mitm = (remote->auth_req & SMP_AUTH_MITM);
2699 
2700 	/* If either side wants MITM, look up the method from the table,
2701 	 * otherwise use JUST WORKS.
2702 	 */
2703 	if (local_mitm || remote_mitm)
2704 		method = get_auth_method(smp, local_io, remote_io);
2705 	else
2706 		method = JUST_WORKS;
2707 
2708 	/* Don't confirm locally initiated pairing attempts */
2709 	if (method == JUST_CFM && test_bit(SMP_FLAG_INITIATOR, &smp->flags))
2710 		method = JUST_WORKS;
2711 
2712 	return method;
2713 }
2714 
2715 static int smp_cmd_public_key(struct l2cap_conn *conn, struct sk_buff *skb)
2716 {
2717 	struct smp_cmd_public_key *key = (void *) skb->data;
2718 	struct hci_conn *hcon = conn->hcon;
2719 	struct l2cap_chan *chan = conn->smp;
2720 	struct smp_chan *smp = chan->data;
2721 	struct hci_dev *hdev = hcon->hdev;
2722 	struct crypto_kpp *tfm_ecdh;
2723 	struct smp_cmd_pairing_confirm cfm;
2724 	int err;
2725 
2726 	bt_dev_dbg(hdev, "conn %p", conn);
2727 
2728 	if (skb->len < sizeof(*key))
2729 		return SMP_INVALID_PARAMS;
2730 
2731 	/* Check if remote and local public keys are the same and debug key is
2732 	 * not in use.
2733 	 */
2734 	if (!test_bit(SMP_FLAG_DEBUG_KEY, &smp->flags) &&
2735 	    !crypto_memneq(key, smp->local_pk, 64)) {
2736 		bt_dev_err(hdev, "Remote and local public keys are identical");
2737 		return SMP_DHKEY_CHECK_FAILED;
2738 	}
2739 
2740 	memcpy(smp->remote_pk, key, 64);
2741 
2742 	if (test_bit(SMP_FLAG_REMOTE_OOB, &smp->flags)) {
2743 		err = smp_f4(smp->remote_pk, smp->remote_pk, smp->rr, 0,
2744 			     cfm.confirm_val);
2745 		if (err)
2746 			return SMP_UNSPECIFIED;
2747 
2748 		if (crypto_memneq(cfm.confirm_val, smp->pcnf, 16))
2749 			return SMP_CONFIRM_FAILED;
2750 	}
2751 
2752 	/* Non-initiating device sends its public key after receiving
2753 	 * the key from the initiating device.
2754 	 */
2755 	if (!test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
2756 		err = sc_send_public_key(smp);
2757 		if (err)
2758 			return err;
2759 	}
2760 
2761 	SMP_DBG("Remote Public Key X: %32phN", smp->remote_pk);
2762 	SMP_DBG("Remote Public Key Y: %32phN", smp->remote_pk + 32);
2763 
2764 	/* Compute the shared secret on the same crypto tfm on which the private
2765 	 * key was set/generated.
2766 	 */
2767 	if (test_bit(SMP_FLAG_LOCAL_OOB, &smp->flags)) {
2768 		struct l2cap_chan *hchan = hdev->smp_data;
2769 		struct smp_dev *smp_dev;
2770 
2771 		if (!hchan || !hchan->data)
2772 			return SMP_UNSPECIFIED;
2773 
2774 		smp_dev = hchan->data;
2775 
2776 		tfm_ecdh = smp_dev->tfm_ecdh;
2777 	} else {
2778 		tfm_ecdh = smp->tfm_ecdh;
2779 	}
2780 
2781 	if (compute_ecdh_secret(tfm_ecdh, smp->remote_pk, smp->dhkey))
2782 		return SMP_UNSPECIFIED;
2783 
2784 	SMP_DBG("DHKey %32phN", smp->dhkey);
2785 
2786 	set_bit(SMP_FLAG_REMOTE_PK, &smp->flags);
2787 
2788 	smp->method = sc_select_method(smp);
2789 
2790 	bt_dev_dbg(hdev, "selected method 0x%02x", smp->method);
2791 
2792 	/* JUST_WORKS and JUST_CFM result in an unauthenticated key */
2793 	if (smp->method == JUST_WORKS || smp->method == JUST_CFM)
2794 		hcon->pending_sec_level = BT_SECURITY_MEDIUM;
2795 	else
2796 		hcon->pending_sec_level = BT_SECURITY_FIPS;
2797 
2798 	if (!crypto_memneq(debug_pk, smp->remote_pk, 64))
2799 		set_bit(SMP_FLAG_DEBUG_KEY, &smp->flags);
2800 
2801 	if (smp->method == DSP_PASSKEY) {
2802 		get_random_bytes(&hcon->passkey_notify,
2803 				 sizeof(hcon->passkey_notify));
2804 		hcon->passkey_notify %= 1000000;
2805 		hcon->passkey_entered = 0;
2806 		smp->passkey_round = 0;
2807 		if (mgmt_user_passkey_notify(hdev, &hcon->dst, hcon->type,
2808 					     hcon->dst_type,
2809 					     hcon->passkey_notify,
2810 					     hcon->passkey_entered))
2811 			return SMP_UNSPECIFIED;
2812 		SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
2813 		return sc_passkey_round(smp, SMP_CMD_PUBLIC_KEY);
2814 	}
2815 
2816 	if (smp->method == REQ_OOB) {
2817 		if (test_bit(SMP_FLAG_INITIATOR, &smp->flags))
2818 			smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM,
2819 				     sizeof(smp->prnd), smp->prnd);
2820 
2821 		SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
2822 
2823 		return 0;
2824 	}
2825 
2826 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags))
2827 		SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
2828 
2829 	if (smp->method == REQ_PASSKEY) {
2830 		if (mgmt_user_passkey_request(hdev, &hcon->dst, hcon->type,
2831 					      hcon->dst_type))
2832 			return SMP_UNSPECIFIED;
2833 		SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
2834 		set_bit(SMP_FLAG_WAIT_USER, &smp->flags);
2835 		return 0;
2836 	}
2837 
2838 	/* The Initiating device waits for the non-initiating device to
2839 	 * send the confirm value.
2840 	 */
2841 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags))
2842 		return 0;
2843 
2844 	err = smp_f4(smp->local_pk, smp->remote_pk, smp->prnd, 0,
2845 		     cfm.confirm_val);
2846 	if (err)
2847 		return SMP_UNSPECIFIED;
2848 
2849 	smp_send_cmd(conn, SMP_CMD_PAIRING_CONFIRM, sizeof(cfm), &cfm);
2850 	SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
2851 
2852 	return 0;
2853 }
2854 
2855 static int smp_cmd_dhkey_check(struct l2cap_conn *conn, struct sk_buff *skb)
2856 {
2857 	struct smp_cmd_dhkey_check *check = (void *) skb->data;
2858 	struct l2cap_chan *chan = conn->smp;
2859 	struct hci_conn *hcon = conn->hcon;
2860 	struct smp_chan *smp = chan->data;
2861 	u8 a[7], b[7], *local_addr, *remote_addr;
2862 	u8 io_cap[3], r[16], e[16];
2863 	int err;
2864 
2865 	bt_dev_dbg(hcon->hdev, "conn %p", conn);
2866 
2867 	if (skb->len < sizeof(*check))
2868 		return SMP_INVALID_PARAMS;
2869 
2870 	memcpy(a, &hcon->init_addr, 6);
2871 	memcpy(b, &hcon->resp_addr, 6);
2872 	a[6] = hcon->init_addr_type;
2873 	b[6] = hcon->resp_addr_type;
2874 
2875 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
2876 		local_addr = a;
2877 		remote_addr = b;
2878 		memcpy(io_cap, &smp->prsp[1], 3);
2879 	} else {
2880 		local_addr = b;
2881 		remote_addr = a;
2882 		memcpy(io_cap, &smp->preq[1], 3);
2883 	}
2884 
2885 	memset(r, 0, sizeof(r));
2886 
2887 	if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
2888 		put_unaligned_le32(hcon->passkey_notify, r);
2889 	else if (smp->method == REQ_OOB)
2890 		memcpy(r, smp->lr, 16);
2891 
2892 	err = smp_f6(smp->mackey, smp->rrnd, smp->prnd, r, io_cap, remote_addr,
2893 		     local_addr, e);
2894 	if (err)
2895 		return SMP_UNSPECIFIED;
2896 
2897 	if (crypto_memneq(check->e, e, 16))
2898 		return SMP_DHKEY_CHECK_FAILED;
2899 
2900 	if (!test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
2901 		if (test_bit(SMP_FLAG_WAIT_USER, &smp->flags)) {
2902 			set_bit(SMP_FLAG_DHKEY_PENDING, &smp->flags);
2903 			return 0;
2904 		}
2905 
2906 		/* Responder sends DHKey check as response to initiator */
2907 		sc_dhkey_check(smp);
2908 	}
2909 
2910 	sc_add_ltk(smp);
2911 
2912 	if (test_bit(SMP_FLAG_INITIATOR, &smp->flags)) {
2913 		hci_le_start_enc(hcon, 0, 0, smp->tk, smp->enc_key_size);
2914 		hcon->enc_key_size = smp->enc_key_size;
2915 	}
2916 
2917 	return 0;
2918 }
2919 
2920 static int smp_cmd_keypress_notify(struct l2cap_conn *conn,
2921 				   struct sk_buff *skb)
2922 {
2923 	struct smp_cmd_keypress_notify *kp = (void *) skb->data;
2924 
2925 	bt_dev_dbg(conn->hcon->hdev, "value 0x%02x", kp->value);
2926 
2927 	return 0;
2928 }
2929 
2930 static int smp_sig_channel(struct l2cap_chan *chan, struct sk_buff *skb)
2931 {
2932 	struct l2cap_conn *conn = chan->conn;
2933 	struct hci_conn *hcon = conn->hcon;
2934 	struct smp_chan *smp;
2935 	__u8 code, reason;
2936 	int err = 0;
2937 
2938 	if (skb->len < 1)
2939 		return -EILSEQ;
2940 
2941 	if (!hci_dev_test_flag(hcon->hdev, HCI_LE_ENABLED)) {
2942 		reason = SMP_PAIRING_NOTSUPP;
2943 		goto done;
2944 	}
2945 
2946 	code = skb->data[0];
2947 	skb_pull(skb, sizeof(code));
2948 
2949 	smp = chan->data;
2950 
2951 	if (code > SMP_CMD_MAX)
2952 		goto drop;
2953 
2954 	if (smp && !test_and_clear_bit(code, &smp->allow_cmd)) {
2955 		/* If there is a context and the command is not allowed consider
2956 		 * it a failure so the session is cleanup properly.
2957 		 */
2958 		switch (code) {
2959 		case SMP_CMD_IDENT_INFO:
2960 		case SMP_CMD_IDENT_ADDR_INFO:
2961 		case SMP_CMD_SIGN_INFO:
2962 			/* 3.6.1. Key distribution and generation
2963 			 *
2964 			 * A device may reject a distributed key by sending the
2965 			 * Pairing Failed command with the reason set to
2966 			 * "Key Rejected".
2967 			 */
2968 			smp_failure(conn, SMP_KEY_REJECTED);
2969 			break;
2970 		}
2971 		goto drop;
2972 	}
2973 
2974 	/* If we don't have a context the only allowed commands are
2975 	 * pairing request and security request.
2976 	 */
2977 	if (!smp && code != SMP_CMD_PAIRING_REQ && code != SMP_CMD_SECURITY_REQ)
2978 		goto drop;
2979 
2980 	switch (code) {
2981 	case SMP_CMD_PAIRING_REQ:
2982 		reason = smp_cmd_pairing_req(conn, skb);
2983 		break;
2984 
2985 	case SMP_CMD_PAIRING_FAIL:
2986 		smp_failure(conn, 0);
2987 		err = -EPERM;
2988 		break;
2989 
2990 	case SMP_CMD_PAIRING_RSP:
2991 		reason = smp_cmd_pairing_rsp(conn, skb);
2992 		break;
2993 
2994 	case SMP_CMD_SECURITY_REQ:
2995 		reason = smp_cmd_security_req(conn, skb);
2996 		break;
2997 
2998 	case SMP_CMD_PAIRING_CONFIRM:
2999 		reason = smp_cmd_pairing_confirm(conn, skb);
3000 		break;
3001 
3002 	case SMP_CMD_PAIRING_RANDOM:
3003 		reason = smp_cmd_pairing_random(conn, skb);
3004 		break;
3005 
3006 	case SMP_CMD_ENCRYPT_INFO:
3007 		reason = smp_cmd_encrypt_info(conn, skb);
3008 		break;
3009 
3010 	case SMP_CMD_INITIATOR_IDENT:
3011 		reason = smp_cmd_initiator_ident(conn, skb);
3012 		break;
3013 
3014 	case SMP_CMD_IDENT_INFO:
3015 		reason = smp_cmd_ident_info(conn, skb);
3016 		break;
3017 
3018 	case SMP_CMD_IDENT_ADDR_INFO:
3019 		reason = smp_cmd_ident_addr_info(conn, skb);
3020 		break;
3021 
3022 	case SMP_CMD_SIGN_INFO:
3023 		reason = smp_cmd_sign_info(conn, skb);
3024 		break;
3025 
3026 	case SMP_CMD_PUBLIC_KEY:
3027 		reason = smp_cmd_public_key(conn, skb);
3028 		break;
3029 
3030 	case SMP_CMD_DHKEY_CHECK:
3031 		reason = smp_cmd_dhkey_check(conn, skb);
3032 		break;
3033 
3034 	case SMP_CMD_KEYPRESS_NOTIFY:
3035 		reason = smp_cmd_keypress_notify(conn, skb);
3036 		break;
3037 
3038 	default:
3039 		bt_dev_dbg(hcon->hdev, "Unknown command code 0x%2.2x", code);
3040 		reason = SMP_CMD_NOTSUPP;
3041 		goto done;
3042 	}
3043 
3044 done:
3045 	if (!err) {
3046 		if (reason)
3047 			smp_failure(conn, reason);
3048 		kfree_skb(skb);
3049 	}
3050 
3051 	return err;
3052 
3053 drop:
3054 	bt_dev_err(hcon->hdev, "unexpected SMP command 0x%02x from %pMR",
3055 		   code, &hcon->dst);
3056 	kfree_skb(skb);
3057 	return 0;
3058 }
3059 
3060 static void smp_teardown_cb(struct l2cap_chan *chan, int err)
3061 {
3062 	struct l2cap_conn *conn = chan->conn;
3063 
3064 	bt_dev_dbg(conn->hcon->hdev, "chan %p", chan);
3065 
3066 	if (chan->data)
3067 		smp_chan_destroy(conn);
3068 
3069 	conn->smp = NULL;
3070 	l2cap_chan_put(chan);
3071 }
3072 
3073 static void bredr_pairing(struct l2cap_chan *chan)
3074 {
3075 	struct l2cap_conn *conn = chan->conn;
3076 	struct hci_conn *hcon = conn->hcon;
3077 	struct hci_dev *hdev = hcon->hdev;
3078 	struct smp_chan *smp;
3079 
3080 	bt_dev_dbg(hdev, "chan %p", chan);
3081 
3082 	/* Only new pairings are interesting */
3083 	if (!test_bit(HCI_CONN_NEW_LINK_KEY, &hcon->flags))
3084 		return;
3085 
3086 	/* Don't bother if we're not encrypted */
3087 	if (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags))
3088 		return;
3089 
3090 	/* Only initiator may initiate SMP over BR/EDR */
3091 	if (hcon->role != HCI_ROLE_MASTER)
3092 		return;
3093 
3094 	/* Secure Connections support must be enabled */
3095 	if (!hci_dev_test_flag(hdev, HCI_SC_ENABLED))
3096 		return;
3097 
3098 	/* BR/EDR must use Secure Connections for SMP */
3099 	if (!test_bit(HCI_CONN_AES_CCM, &hcon->flags) &&
3100 	    !hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP))
3101 		return;
3102 
3103 	/* If our LE support is not enabled don't do anything */
3104 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
3105 		return;
3106 
3107 	/* Don't bother if remote LE support is not enabled */
3108 	if (!lmp_host_le_capable(hcon))
3109 		return;
3110 
3111 	/* Remote must support SMP fixed chan for BR/EDR */
3112 	if (!(conn->remote_fixed_chan & L2CAP_FC_SMP_BREDR))
3113 		return;
3114 
3115 	/* Don't bother if SMP is already ongoing */
3116 	if (chan->data)
3117 		return;
3118 
3119 	smp = smp_chan_create(conn);
3120 	if (!smp) {
3121 		bt_dev_err(hdev, "unable to create SMP context for BR/EDR");
3122 		return;
3123 	}
3124 
3125 	set_bit(SMP_FLAG_SC, &smp->flags);
3126 
3127 	bt_dev_dbg(hdev, "starting SMP over BR/EDR");
3128 
3129 	smp_send_pairing_req(smp, 0x00);
3130 }
3131 
3132 static void smp_resume_cb(struct l2cap_chan *chan)
3133 {
3134 	struct smp_chan *smp = chan->data;
3135 	struct l2cap_conn *conn = chan->conn;
3136 	struct hci_conn *hcon = conn->hcon;
3137 
3138 	bt_dev_dbg(hcon->hdev, "chan %p", chan);
3139 
3140 	if (hcon->type == ACL_LINK) {
3141 		bredr_pairing(chan);
3142 		return;
3143 	}
3144 
3145 	if (!smp)
3146 		return;
3147 
3148 	if (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags))
3149 		return;
3150 
3151 	cancel_delayed_work(&smp->security_timer);
3152 
3153 	smp_distribute_keys(smp);
3154 }
3155 
3156 static void smp_ready_cb(struct l2cap_chan *chan)
3157 {
3158 	struct l2cap_conn *conn = chan->conn;
3159 	struct hci_conn *hcon = conn->hcon;
3160 
3161 	bt_dev_dbg(hcon->hdev, "chan %p", chan);
3162 
3163 	/* No need to call l2cap_chan_hold() here since we already own
3164 	 * the reference taken in smp_new_conn_cb(). This is just the
3165 	 * first time that we tie it to a specific pointer. The code in
3166 	 * l2cap_core.c ensures that there's no risk this function won't
3167 	 * get called if smp_new_conn_cb was previously called.
3168 	 */
3169 	conn->smp = chan;
3170 
3171 	if (hcon->type == ACL_LINK && test_bit(HCI_CONN_ENCRYPT, &hcon->flags))
3172 		bredr_pairing(chan);
3173 }
3174 
3175 static int smp_recv_cb(struct l2cap_chan *chan, struct sk_buff *skb)
3176 {
3177 	int err;
3178 
3179 	bt_dev_dbg(chan->conn->hcon->hdev, "chan %p", chan);
3180 
3181 	err = smp_sig_channel(chan, skb);
3182 	if (err) {
3183 		struct smp_chan *smp = chan->data;
3184 
3185 		if (smp)
3186 			cancel_delayed_work_sync(&smp->security_timer);
3187 
3188 		hci_disconnect(chan->conn->hcon, HCI_ERROR_AUTH_FAILURE);
3189 	}
3190 
3191 	return err;
3192 }
3193 
3194 static struct sk_buff *smp_alloc_skb_cb(struct l2cap_chan *chan,
3195 					unsigned long hdr_len,
3196 					unsigned long len, int nb)
3197 {
3198 	struct sk_buff *skb;
3199 
3200 	skb = bt_skb_alloc(hdr_len + len, GFP_KERNEL);
3201 	if (!skb)
3202 		return ERR_PTR(-ENOMEM);
3203 
3204 	skb->priority = HCI_PRIO_MAX;
3205 	bt_cb(skb)->l2cap.chan = chan;
3206 
3207 	return skb;
3208 }
3209 
3210 static const struct l2cap_ops smp_chan_ops = {
3211 	.name			= "Security Manager",
3212 	.ready			= smp_ready_cb,
3213 	.recv			= smp_recv_cb,
3214 	.alloc_skb		= smp_alloc_skb_cb,
3215 	.teardown		= smp_teardown_cb,
3216 	.resume			= smp_resume_cb,
3217 
3218 	.new_connection		= l2cap_chan_no_new_connection,
3219 	.state_change		= l2cap_chan_no_state_change,
3220 	.close			= l2cap_chan_no_close,
3221 	.defer			= l2cap_chan_no_defer,
3222 	.suspend		= l2cap_chan_no_suspend,
3223 	.set_shutdown		= l2cap_chan_no_set_shutdown,
3224 	.get_sndtimeo		= l2cap_chan_no_get_sndtimeo,
3225 };
3226 
3227 static inline int smp_new_conn_cb(struct l2cap_chan *chan,
3228 				  struct l2cap_chan *new_chan)
3229 {
3230 	new_chan->ops = &smp_chan_ops;
3231 
3232 	/* Other L2CAP channels may request SMP routines in order to
3233 	 * change the security level. This means that the SMP channel
3234 	 * lock must be considered in its own category to avoid lockdep
3235 	 * warnings.
3236 	 */
3237 	atomic_set(&new_chan->nesting, L2CAP_NESTING_SMP);
3238 
3239 	return 0;
3240 }
3241 
3242 static const struct l2cap_ops smp_root_chan_ops = {
3243 	.name			= "Security Manager Root",
3244 	.new_connection		= smp_new_conn_cb,
3245 
3246 	/* None of these are implemented for the root channel */
3247 	.close			= l2cap_chan_no_close,
3248 	.alloc_skb		= l2cap_chan_no_alloc_skb,
3249 	.recv			= l2cap_chan_no_recv,
3250 	.state_change		= l2cap_chan_no_state_change,
3251 	.teardown		= l2cap_chan_no_teardown,
3252 	.ready			= l2cap_chan_no_ready,
3253 	.defer			= l2cap_chan_no_defer,
3254 	.suspend		= l2cap_chan_no_suspend,
3255 	.resume			= l2cap_chan_no_resume,
3256 	.set_shutdown		= l2cap_chan_no_set_shutdown,
3257 	.get_sndtimeo		= l2cap_chan_no_get_sndtimeo,
3258 };
3259 
3260 static struct l2cap_chan *smp_add_cid(struct hci_dev *hdev, u16 cid)
3261 {
3262 	struct l2cap_chan *chan;
3263 	struct smp_dev *smp;
3264 	struct crypto_kpp *tfm_ecdh;
3265 
3266 	if (cid == L2CAP_CID_SMP_BREDR) {
3267 		smp = NULL;
3268 		goto create_chan;
3269 	}
3270 
3271 	smp = kzalloc_obj(*smp);
3272 	if (!smp)
3273 		return ERR_PTR(-ENOMEM);
3274 
3275 	tfm_ecdh = crypto_alloc_kpp("ecdh-nist-p256", 0, 0);
3276 	if (IS_ERR(tfm_ecdh)) {
3277 		bt_dev_err(hdev, "Unable to create ECDH crypto context");
3278 		kfree_sensitive(smp);
3279 		return ERR_CAST(tfm_ecdh);
3280 	}
3281 
3282 	smp->local_oob = false;
3283 	smp->tfm_ecdh = tfm_ecdh;
3284 
3285 create_chan:
3286 	chan = l2cap_chan_create();
3287 	if (!chan) {
3288 		if (smp) {
3289 			crypto_free_kpp(smp->tfm_ecdh);
3290 			kfree_sensitive(smp);
3291 		}
3292 		return ERR_PTR(-ENOMEM);
3293 	}
3294 
3295 	chan->data = smp;
3296 
3297 	l2cap_add_scid(chan, cid);
3298 
3299 	l2cap_chan_set_defaults(chan, NULL);
3300 
3301 	if (cid == L2CAP_CID_SMP) {
3302 		u8 bdaddr_type;
3303 
3304 		hci_copy_identity_address(hdev, &chan->src, &bdaddr_type);
3305 
3306 		if (bdaddr_type == ADDR_LE_DEV_PUBLIC)
3307 			chan->src_type = BDADDR_LE_PUBLIC;
3308 		else
3309 			chan->src_type = BDADDR_LE_RANDOM;
3310 	} else {
3311 		bacpy(&chan->src, &hdev->bdaddr);
3312 		chan->src_type = BDADDR_BREDR;
3313 	}
3314 
3315 	chan->state = BT_LISTEN;
3316 	chan->mode = L2CAP_MODE_BASIC;
3317 	chan->imtu = L2CAP_DEFAULT_MTU;
3318 	chan->ops = &smp_root_chan_ops;
3319 
3320 	/* Set correct nesting level for a parent/listening channel */
3321 	atomic_set(&chan->nesting, L2CAP_NESTING_PARENT);
3322 
3323 	return chan;
3324 }
3325 
3326 static void smp_del_chan(struct l2cap_chan *chan)
3327 {
3328 	struct smp_dev *smp;
3329 
3330 	BT_DBG("chan %p", chan);
3331 
3332 	smp = chan->data;
3333 	if (smp) {
3334 		chan->data = NULL;
3335 		crypto_free_kpp(smp->tfm_ecdh);
3336 		kfree_sensitive(smp);
3337 	}
3338 
3339 	l2cap_chan_put(chan);
3340 }
3341 
3342 int smp_force_bredr(struct hci_dev *hdev, bool enable)
3343 {
3344 	if (enable == hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP))
3345 		return -EALREADY;
3346 
3347 	if (enable) {
3348 		struct l2cap_chan *chan;
3349 
3350 		chan = smp_add_cid(hdev, L2CAP_CID_SMP_BREDR);
3351 		if (IS_ERR(chan))
3352 			return PTR_ERR(chan);
3353 
3354 		hdev->smp_bredr_data = chan;
3355 	} else {
3356 		struct l2cap_chan *chan;
3357 
3358 		chan = hdev->smp_bredr_data;
3359 		hdev->smp_bredr_data = NULL;
3360 		smp_del_chan(chan);
3361 	}
3362 
3363 	hci_dev_change_flag(hdev, HCI_FORCE_BREDR_SMP);
3364 
3365 	return 0;
3366 }
3367 
3368 int smp_register(struct hci_dev *hdev)
3369 {
3370 	struct l2cap_chan *chan;
3371 
3372 	bt_dev_dbg(hdev, "");
3373 
3374 	/* If the controller does not support Low Energy operation, then
3375 	 * there is also no need to register any SMP channel.
3376 	 */
3377 	if (!lmp_le_capable(hdev))
3378 		return 0;
3379 
3380 	if (WARN_ON(hdev->smp_data)) {
3381 		chan = hdev->smp_data;
3382 		hdev->smp_data = NULL;
3383 		smp_del_chan(chan);
3384 	}
3385 
3386 	chan = smp_add_cid(hdev, L2CAP_CID_SMP);
3387 	if (IS_ERR(chan))
3388 		return PTR_ERR(chan);
3389 
3390 	hdev->smp_data = chan;
3391 
3392 	if (!lmp_sc_capable(hdev)) {
3393 		/* Flag can be already set here (due to power toggle) */
3394 		if (!hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP))
3395 			return 0;
3396 	}
3397 
3398 	if (WARN_ON(hdev->smp_bredr_data)) {
3399 		chan = hdev->smp_bredr_data;
3400 		hdev->smp_bredr_data = NULL;
3401 		smp_del_chan(chan);
3402 	}
3403 
3404 	chan = smp_add_cid(hdev, L2CAP_CID_SMP_BREDR);
3405 	if (IS_ERR(chan)) {
3406 		int err = PTR_ERR(chan);
3407 		chan = hdev->smp_data;
3408 		hdev->smp_data = NULL;
3409 		smp_del_chan(chan);
3410 		return err;
3411 	}
3412 
3413 	hdev->smp_bredr_data = chan;
3414 
3415 	return 0;
3416 }
3417 
3418 void smp_unregister(struct hci_dev *hdev)
3419 {
3420 	struct l2cap_chan *chan;
3421 
3422 	if (hdev->smp_bredr_data) {
3423 		chan = hdev->smp_bredr_data;
3424 		hdev->smp_bredr_data = NULL;
3425 		smp_del_chan(chan);
3426 	}
3427 
3428 	if (hdev->smp_data) {
3429 		chan = hdev->smp_data;
3430 		hdev->smp_data = NULL;
3431 		smp_del_chan(chan);
3432 	}
3433 }
3434 
3435 #if IS_ENABLED(CONFIG_BT_SELFTEST_SMP)
3436 
3437 static int __init test_debug_key(struct crypto_kpp *tfm_ecdh)
3438 {
3439 	u8 pk[64];
3440 	int err;
3441 
3442 	err = set_ecdh_privkey(tfm_ecdh, debug_sk);
3443 	if (err)
3444 		return err;
3445 
3446 	err = generate_ecdh_public_key(tfm_ecdh, pk);
3447 	if (err)
3448 		return err;
3449 
3450 	if (crypto_memneq(pk, debug_pk, 64))
3451 		return -EINVAL;
3452 
3453 	return 0;
3454 }
3455 
3456 static int __init test_ah(void)
3457 {
3458 	const u8 irk[16] = {
3459 			0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
3460 			0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
3461 	const u8 r[3] = { 0x94, 0x81, 0x70 };
3462 	const u8 exp[3] = { 0xaa, 0xfb, 0x0d };
3463 	u8 res[3];
3464 	int err;
3465 
3466 	err = smp_ah(irk, r, res);
3467 	if (err)
3468 		return err;
3469 
3470 	if (crypto_memneq(res, exp, 3))
3471 		return -EINVAL;
3472 
3473 	return 0;
3474 }
3475 
3476 static int __init test_c1(void)
3477 {
3478 	const u8 k[16] = {
3479 			0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3480 			0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
3481 	const u8 r[16] = {
3482 			0xe0, 0x2e, 0x70, 0xc6, 0x4e, 0x27, 0x88, 0x63,
3483 			0x0e, 0x6f, 0xad, 0x56, 0x21, 0xd5, 0x83, 0x57 };
3484 	const u8 preq[7] = { 0x01, 0x01, 0x00, 0x00, 0x10, 0x07, 0x07 };
3485 	const u8 pres[7] = { 0x02, 0x03, 0x00, 0x00, 0x08, 0x00, 0x05 };
3486 	const u8 _iat = 0x01;
3487 	const u8 _rat = 0x00;
3488 	const bdaddr_t ra = { { 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1 } };
3489 	const bdaddr_t ia = { { 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1 } };
3490 	const u8 exp[16] = {
3491 			0x86, 0x3b, 0xf1, 0xbe, 0xc5, 0x4d, 0xa7, 0xd2,
3492 			0xea, 0x88, 0x89, 0x87, 0xef, 0x3f, 0x1e, 0x1e };
3493 	u8 res[16];
3494 	int err;
3495 
3496 	err = smp_c1(k, r, preq, pres, _iat, &ia, _rat, &ra, res);
3497 	if (err)
3498 		return err;
3499 
3500 	if (crypto_memneq(res, exp, 16))
3501 		return -EINVAL;
3502 
3503 	return 0;
3504 }
3505 
3506 static int __init test_s1(void)
3507 {
3508 	const u8 k[16] = {
3509 			0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3510 			0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
3511 	const u8 r1[16] = {
3512 			0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 };
3513 	const u8 r2[16] = {
3514 			0x00, 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99 };
3515 	const u8 exp[16] = {
3516 			0x62, 0xa0, 0x6d, 0x79, 0xae, 0x16, 0x42, 0x5b,
3517 			0x9b, 0xf4, 0xb0, 0xe8, 0xf0, 0xe1, 0x1f, 0x9a };
3518 	u8 res[16];
3519 	int err;
3520 
3521 	err = smp_s1(k, r1, r2, res);
3522 	if (err)
3523 		return err;
3524 
3525 	if (crypto_memneq(res, exp, 16))
3526 		return -EINVAL;
3527 
3528 	return 0;
3529 }
3530 
3531 static int __init test_f4(void)
3532 {
3533 	const u8 u[32] = {
3534 			0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc,
3535 			0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef,
3536 			0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
3537 			0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 };
3538 	const u8 v[32] = {
3539 			0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b,
3540 			0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59,
3541 			0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90,
3542 			0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 };
3543 	const u8 x[16] = {
3544 			0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
3545 			0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
3546 	const u8 z = 0x00;
3547 	const u8 exp[16] = {
3548 			0x2d, 0x87, 0x74, 0xa9, 0xbe, 0xa1, 0xed, 0xf1,
3549 			0x1c, 0xbd, 0xa9, 0x07, 0xf1, 0x16, 0xc9, 0xf2 };
3550 	u8 res[16];
3551 	int err;
3552 
3553 	err = smp_f4(u, v, x, z, res);
3554 	if (err)
3555 		return err;
3556 
3557 	if (crypto_memneq(res, exp, 16))
3558 		return -EINVAL;
3559 
3560 	return 0;
3561 }
3562 
3563 static int __init test_f5(void)
3564 {
3565 	const u8 w[32] = {
3566 			0x98, 0xa6, 0xbf, 0x73, 0xf3, 0x34, 0x8d, 0x86,
3567 			0xf1, 0x66, 0xf8, 0xb4, 0x13, 0x6b, 0x79, 0x99,
3568 			0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
3569 			0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
3570 	const u8 n1[16] = {
3571 			0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
3572 			0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
3573 	const u8 n2[16] = {
3574 			0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
3575 			0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
3576 	const u8 a1[7] = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56, 0x00 };
3577 	const u8 a2[7] = { 0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7, 0x00 };
3578 	const u8 exp_ltk[16] = {
3579 			0x38, 0x0a, 0x75, 0x94, 0xb5, 0x22, 0x05, 0x98,
3580 			0x23, 0xcd, 0xd7, 0x69, 0x11, 0x79, 0x86, 0x69 };
3581 	const u8 exp_mackey[16] = {
3582 			0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f, 0xfd,
3583 			0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1, 0x65, 0x29 };
3584 	u8 mackey[16], ltk[16];
3585 	int err;
3586 
3587 	err = smp_f5(w, n1, n2, a1, a2, mackey, ltk);
3588 	if (err)
3589 		return err;
3590 
3591 	if (crypto_memneq(mackey, exp_mackey, 16))
3592 		return -EINVAL;
3593 
3594 	if (crypto_memneq(ltk, exp_ltk, 16))
3595 		return -EINVAL;
3596 
3597 	return 0;
3598 }
3599 
3600 static int __init test_f6(void)
3601 {
3602 	const u8 w[16] = {
3603 			0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f, 0xfd,
3604 			0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1, 0x65, 0x29 };
3605 	const u8 n1[16] = {
3606 			0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
3607 			0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
3608 	const u8 n2[16] = {
3609 			0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
3610 			0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
3611 	const u8 r[16] = {
3612 			0xc8, 0x0f, 0x2d, 0x0c, 0xd2, 0x42, 0xda, 0x08,
3613 			0x54, 0xbb, 0x53, 0xb4, 0x3b, 0x34, 0xa3, 0x12 };
3614 	const u8 io_cap[3] = { 0x02, 0x01, 0x01 };
3615 	const u8 a1[7] = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56, 0x00 };
3616 	const u8 a2[7] = { 0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7, 0x00 };
3617 	const u8 exp[16] = {
3618 			0x61, 0x8f, 0x95, 0xda, 0x09, 0x0b, 0x6c, 0xd2,
3619 			0xc5, 0xe8, 0xd0, 0x9c, 0x98, 0x73, 0xc4, 0xe3 };
3620 	u8 res[16];
3621 	int err;
3622 
3623 	err = smp_f6(w, n1, n2, r, io_cap, a1, a2, res);
3624 	if (err)
3625 		return err;
3626 
3627 	if (crypto_memneq(res, exp, 16))
3628 		return -EINVAL;
3629 
3630 	return 0;
3631 }
3632 
3633 static int __init test_g2(void)
3634 {
3635 	const u8 u[32] = {
3636 			0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc,
3637 			0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef,
3638 			0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
3639 			0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 };
3640 	const u8 v[32] = {
3641 			0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b,
3642 			0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59,
3643 			0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90,
3644 			0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 };
3645 	const u8 x[16] = {
3646 			0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
3647 			0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
3648 	const u8 y[16] = {
3649 			0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
3650 			0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
3651 	const u32 exp_val = 0x2f9ed5ba % 1000000;
3652 	u32 val;
3653 	int err;
3654 
3655 	err = smp_g2(u, v, x, y, &val);
3656 	if (err)
3657 		return err;
3658 
3659 	if (val != exp_val)
3660 		return -EINVAL;
3661 
3662 	return 0;
3663 }
3664 
3665 static int __init test_h6(void)
3666 {
3667 	const u8 w[16] = {
3668 			0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
3669 			0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
3670 	const u8 key_id[4] = { 0x72, 0x62, 0x65, 0x6c };
3671 	const u8 exp[16] = {
3672 			0x99, 0x63, 0xb1, 0x80, 0xe2, 0xa9, 0xd3, 0xe8,
3673 			0x1c, 0xc9, 0x6d, 0xe7, 0x02, 0xe1, 0x9a, 0x2d };
3674 	u8 res[16];
3675 	int err;
3676 
3677 	err = smp_h6(w, key_id, res);
3678 	if (err)
3679 		return err;
3680 
3681 	if (crypto_memneq(res, exp, 16))
3682 		return -EINVAL;
3683 
3684 	return 0;
3685 }
3686 
3687 static char test_smp_buffer[32];
3688 
3689 static ssize_t test_smp_read(struct file *file, char __user *user_buf,
3690 			     size_t count, loff_t *ppos)
3691 {
3692 	return simple_read_from_buffer(user_buf, count, ppos, test_smp_buffer,
3693 				       strlen(test_smp_buffer));
3694 }
3695 
3696 static const struct file_operations test_smp_fops = {
3697 	.open		= simple_open,
3698 	.read		= test_smp_read,
3699 	.llseek		= default_llseek,
3700 };
3701 
3702 static int __init run_selftests(struct crypto_kpp *tfm_ecdh)
3703 {
3704 	ktime_t calltime, delta, rettime;
3705 	unsigned long long duration;
3706 	int err;
3707 
3708 	calltime = ktime_get();
3709 
3710 	err = test_debug_key(tfm_ecdh);
3711 	if (err) {
3712 		BT_ERR("debug_key test failed");
3713 		goto done;
3714 	}
3715 
3716 	err = test_ah();
3717 	if (err) {
3718 		BT_ERR("smp_ah test failed");
3719 		goto done;
3720 	}
3721 
3722 	err = test_c1();
3723 	if (err) {
3724 		BT_ERR("smp_c1 test failed");
3725 		goto done;
3726 	}
3727 
3728 	err = test_s1();
3729 	if (err) {
3730 		BT_ERR("smp_s1 test failed");
3731 		goto done;
3732 	}
3733 
3734 	err = test_f4();
3735 	if (err) {
3736 		BT_ERR("smp_f4 test failed");
3737 		goto done;
3738 	}
3739 
3740 	err = test_f5();
3741 	if (err) {
3742 		BT_ERR("smp_f5 test failed");
3743 		goto done;
3744 	}
3745 
3746 	err = test_f6();
3747 	if (err) {
3748 		BT_ERR("smp_f6 test failed");
3749 		goto done;
3750 	}
3751 
3752 	err = test_g2();
3753 	if (err) {
3754 		BT_ERR("smp_g2 test failed");
3755 		goto done;
3756 	}
3757 
3758 	err = test_h6();
3759 	if (err) {
3760 		BT_ERR("smp_h6 test failed");
3761 		goto done;
3762 	}
3763 
3764 	rettime = ktime_get();
3765 	delta = ktime_sub(rettime, calltime);
3766 	duration = (unsigned long long) ktime_to_ns(delta) >> 10;
3767 
3768 	BT_INFO("SMP test passed in %llu usecs", duration);
3769 
3770 done:
3771 	if (!err)
3772 		snprintf(test_smp_buffer, sizeof(test_smp_buffer),
3773 			 "PASS (%llu usecs)\n", duration);
3774 	else
3775 		snprintf(test_smp_buffer, sizeof(test_smp_buffer), "FAIL\n");
3776 
3777 	debugfs_create_file("selftest_smp", 0444, bt_debugfs, NULL,
3778 			    &test_smp_fops);
3779 
3780 	return err;
3781 }
3782 
3783 int __init bt_selftest_smp(void)
3784 {
3785 	struct crypto_kpp *tfm_ecdh;
3786 	int err;
3787 
3788 	tfm_ecdh = crypto_alloc_kpp("ecdh-nist-p256", 0, 0);
3789 	if (IS_ERR(tfm_ecdh)) {
3790 		BT_ERR("Unable to create ECDH crypto context");
3791 		return PTR_ERR(tfm_ecdh);
3792 	}
3793 
3794 	err = run_selftests(tfm_ecdh);
3795 
3796 	crypto_free_kpp(tfm_ecdh);
3797 
3798 	return err;
3799 }
3800 
3801 #endif
3802