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