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