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