bury memcpy_toiovec()
[sfrench/cifs-2.6.git] / net / bluetooth / smp.c
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/crypto.h>
24 #include <linux/scatterlist.h>
25 #include <crypto/b128ops.h>
26
27 #include <net/bluetooth/bluetooth.h>
28 #include <net/bluetooth/hci_core.h>
29 #include <net/bluetooth/l2cap.h>
30 #include <net/bluetooth/mgmt.h>
31
32 #include "smp.h"
33
34 #define SMP_ALLOW_CMD(smp, code)        set_bit(code, &smp->allow_cmd)
35
36 #define SMP_TIMEOUT     msecs_to_jiffies(30000)
37
38 #define AUTH_REQ_MASK   0x07
39 #define KEY_DIST_MASK   0x07
40
41 enum {
42         SMP_FLAG_TK_VALID,
43         SMP_FLAG_CFM_PENDING,
44         SMP_FLAG_MITM_AUTH,
45         SMP_FLAG_COMPLETE,
46         SMP_FLAG_INITIATOR,
47 };
48
49 struct smp_chan {
50         struct l2cap_conn       *conn;
51         struct delayed_work     security_timer;
52         unsigned long           allow_cmd; /* Bitmask of allowed commands */
53
54         u8              preq[7]; /* SMP Pairing Request */
55         u8              prsp[7]; /* SMP Pairing Response */
56         u8              prnd[16]; /* SMP Pairing Random (local) */
57         u8              rrnd[16]; /* SMP Pairing Random (remote) */
58         u8              pcnf[16]; /* SMP Pairing Confirm */
59         u8              tk[16]; /* SMP Temporary Key */
60         u8              enc_key_size;
61         u8              remote_key_dist;
62         bdaddr_t        id_addr;
63         u8              id_addr_type;
64         u8              irk[16];
65         struct smp_csrk *csrk;
66         struct smp_csrk *slave_csrk;
67         struct smp_ltk  *ltk;
68         struct smp_ltk  *slave_ltk;
69         struct smp_irk  *remote_irk;
70         unsigned long   flags;
71
72         struct crypto_blkcipher *tfm_aes;
73 };
74
75 static inline void swap_buf(const u8 *src, u8 *dst, size_t len)
76 {
77         size_t i;
78
79         for (i = 0; i < len; i++)
80                 dst[len - 1 - i] = src[i];
81 }
82
83 static int smp_e(struct crypto_blkcipher *tfm, const u8 *k, u8 *r)
84 {
85         struct blkcipher_desc desc;
86         struct scatterlist sg;
87         uint8_t tmp[16], data[16];
88         int err;
89
90         if (tfm == NULL) {
91                 BT_ERR("tfm %p", tfm);
92                 return -EINVAL;
93         }
94
95         desc.tfm = tfm;
96         desc.flags = 0;
97
98         /* The most significant octet of key corresponds to k[0] */
99         swap_buf(k, tmp, 16);
100
101         err = crypto_blkcipher_setkey(tfm, tmp, 16);
102         if (err) {
103                 BT_ERR("cipher setkey failed: %d", err);
104                 return err;
105         }
106
107         /* Most significant octet of plaintextData corresponds to data[0] */
108         swap_buf(r, data, 16);
109
110         sg_init_one(&sg, data, 16);
111
112         err = crypto_blkcipher_encrypt(&desc, &sg, &sg, 16);
113         if (err)
114                 BT_ERR("Encrypt data error %d", err);
115
116         /* Most significant octet of encryptedData corresponds to data[0] */
117         swap_buf(data, r, 16);
118
119         return err;
120 }
121
122 static int smp_ah(struct crypto_blkcipher *tfm, u8 irk[16], u8 r[3], u8 res[3])
123 {
124         u8 _res[16];
125         int err;
126
127         /* r' = padding || r */
128         memcpy(_res, r, 3);
129         memset(_res + 3, 0, 13);
130
131         err = smp_e(tfm, irk, _res);
132         if (err) {
133                 BT_ERR("Encrypt error");
134                 return err;
135         }
136
137         /* The output of the random address function ah is:
138          *      ah(h, r) = e(k, r') mod 2^24
139          * The output of the security function e is then truncated to 24 bits
140          * by taking the least significant 24 bits of the output of e as the
141          * result of ah.
142          */
143         memcpy(res, _res, 3);
144
145         return 0;
146 }
147
148 bool smp_irk_matches(struct hci_dev *hdev, u8 irk[16], bdaddr_t *bdaddr)
149 {
150         struct l2cap_chan *chan = hdev->smp_data;
151         struct crypto_blkcipher *tfm;
152         u8 hash[3];
153         int err;
154
155         if (!chan || !chan->data)
156                 return false;
157
158         tfm = chan->data;
159
160         BT_DBG("RPA %pMR IRK %*phN", bdaddr, 16, irk);
161
162         err = smp_ah(tfm, irk, &bdaddr->b[3], hash);
163         if (err)
164                 return false;
165
166         return !memcmp(bdaddr->b, hash, 3);
167 }
168
169 int smp_generate_rpa(struct hci_dev *hdev, u8 irk[16], bdaddr_t *rpa)
170 {
171         struct l2cap_chan *chan = hdev->smp_data;
172         struct crypto_blkcipher *tfm;
173         int err;
174
175         if (!chan || !chan->data)
176                 return -EOPNOTSUPP;
177
178         tfm = chan->data;
179
180         get_random_bytes(&rpa->b[3], 3);
181
182         rpa->b[5] &= 0x3f;      /* Clear two most significant bits */
183         rpa->b[5] |= 0x40;      /* Set second most significant bit */
184
185         err = smp_ah(tfm, irk, &rpa->b[3], rpa->b);
186         if (err < 0)
187                 return err;
188
189         BT_DBG("RPA %pMR", rpa);
190
191         return 0;
192 }
193
194 static int smp_c1(struct crypto_blkcipher *tfm_aes, u8 k[16], u8 r[16],
195                   u8 preq[7], u8 pres[7], u8 _iat, bdaddr_t *ia, u8 _rat,
196                   bdaddr_t *ra, u8 res[16])
197 {
198         u8 p1[16], p2[16];
199         int err;
200
201         memset(p1, 0, 16);
202
203         /* p1 = pres || preq || _rat || _iat */
204         p1[0] = _iat;
205         p1[1] = _rat;
206         memcpy(p1 + 2, preq, 7);
207         memcpy(p1 + 9, pres, 7);
208
209         /* p2 = padding || ia || ra */
210         memcpy(p2, ra, 6);
211         memcpy(p2 + 6, ia, 6);
212         memset(p2 + 12, 0, 4);
213
214         /* res = r XOR p1 */
215         u128_xor((u128 *) res, (u128 *) r, (u128 *) p1);
216
217         /* res = e(k, res) */
218         err = smp_e(tfm_aes, k, res);
219         if (err) {
220                 BT_ERR("Encrypt data error");
221                 return err;
222         }
223
224         /* res = res XOR p2 */
225         u128_xor((u128 *) res, (u128 *) res, (u128 *) p2);
226
227         /* res = e(k, res) */
228         err = smp_e(tfm_aes, k, res);
229         if (err)
230                 BT_ERR("Encrypt data error");
231
232         return err;
233 }
234
235 static int smp_s1(struct crypto_blkcipher *tfm_aes, u8 k[16], u8 r1[16],
236                   u8 r2[16], u8 _r[16])
237 {
238         int err;
239
240         /* Just least significant octets from r1 and r2 are considered */
241         memcpy(_r, r2, 8);
242         memcpy(_r + 8, r1, 8);
243
244         err = smp_e(tfm_aes, k, _r);
245         if (err)
246                 BT_ERR("Encrypt data error");
247
248         return err;
249 }
250
251 static void smp_send_cmd(struct l2cap_conn *conn, u8 code, u16 len, void *data)
252 {
253         struct l2cap_chan *chan = conn->smp;
254         struct smp_chan *smp;
255         struct kvec iv[2];
256         struct msghdr msg;
257
258         if (!chan)
259                 return;
260
261         BT_DBG("code 0x%2.2x", code);
262
263         iv[0].iov_base = &code;
264         iv[0].iov_len = 1;
265
266         iv[1].iov_base = data;
267         iv[1].iov_len = len;
268
269         memset(&msg, 0, sizeof(msg));
270
271         iov_iter_kvec(&msg.msg_iter, WRITE | ITER_KVEC, iv, 2, 1 + len);
272
273         l2cap_chan_send(chan, &msg, 1 + len);
274
275         if (!chan->data)
276                 return;
277
278         smp = chan->data;
279
280         cancel_delayed_work_sync(&smp->security_timer);
281         schedule_delayed_work(&smp->security_timer, SMP_TIMEOUT);
282 }
283
284 static __u8 authreq_to_seclevel(__u8 authreq)
285 {
286         if (authreq & SMP_AUTH_MITM)
287                 return BT_SECURITY_HIGH;
288         else
289                 return BT_SECURITY_MEDIUM;
290 }
291
292 static __u8 seclevel_to_authreq(__u8 sec_level)
293 {
294         switch (sec_level) {
295         case BT_SECURITY_HIGH:
296                 return SMP_AUTH_MITM | SMP_AUTH_BONDING;
297         case BT_SECURITY_MEDIUM:
298                 return SMP_AUTH_BONDING;
299         default:
300                 return SMP_AUTH_NONE;
301         }
302 }
303
304 static void build_pairing_cmd(struct l2cap_conn *conn,
305                               struct smp_cmd_pairing *req,
306                               struct smp_cmd_pairing *rsp, __u8 authreq)
307 {
308         struct l2cap_chan *chan = conn->smp;
309         struct smp_chan *smp = chan->data;
310         struct hci_conn *hcon = conn->hcon;
311         struct hci_dev *hdev = hcon->hdev;
312         u8 local_dist = 0, remote_dist = 0;
313
314         if (test_bit(HCI_BONDABLE, &conn->hcon->hdev->dev_flags)) {
315                 local_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
316                 remote_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
317                 authreq |= SMP_AUTH_BONDING;
318         } else {
319                 authreq &= ~SMP_AUTH_BONDING;
320         }
321
322         if (test_bit(HCI_RPA_RESOLVING, &hdev->dev_flags))
323                 remote_dist |= SMP_DIST_ID_KEY;
324
325         if (test_bit(HCI_PRIVACY, &hdev->dev_flags))
326                 local_dist |= SMP_DIST_ID_KEY;
327
328         if (rsp == NULL) {
329                 req->io_capability = conn->hcon->io_capability;
330                 req->oob_flag = SMP_OOB_NOT_PRESENT;
331                 req->max_key_size = SMP_MAX_ENC_KEY_SIZE;
332                 req->init_key_dist = local_dist;
333                 req->resp_key_dist = remote_dist;
334                 req->auth_req = (authreq & AUTH_REQ_MASK);
335
336                 smp->remote_key_dist = remote_dist;
337                 return;
338         }
339
340         rsp->io_capability = conn->hcon->io_capability;
341         rsp->oob_flag = SMP_OOB_NOT_PRESENT;
342         rsp->max_key_size = SMP_MAX_ENC_KEY_SIZE;
343         rsp->init_key_dist = req->init_key_dist & remote_dist;
344         rsp->resp_key_dist = req->resp_key_dist & local_dist;
345         rsp->auth_req = (authreq & AUTH_REQ_MASK);
346
347         smp->remote_key_dist = rsp->init_key_dist;
348 }
349
350 static u8 check_enc_key_size(struct l2cap_conn *conn, __u8 max_key_size)
351 {
352         struct l2cap_chan *chan = conn->smp;
353         struct smp_chan *smp = chan->data;
354
355         if ((max_key_size > SMP_MAX_ENC_KEY_SIZE) ||
356             (max_key_size < SMP_MIN_ENC_KEY_SIZE))
357                 return SMP_ENC_KEY_SIZE;
358
359         smp->enc_key_size = max_key_size;
360
361         return 0;
362 }
363
364 static void smp_chan_destroy(struct l2cap_conn *conn)
365 {
366         struct l2cap_chan *chan = conn->smp;
367         struct smp_chan *smp = chan->data;
368         bool complete;
369
370         BUG_ON(!smp);
371
372         cancel_delayed_work_sync(&smp->security_timer);
373
374         complete = test_bit(SMP_FLAG_COMPLETE, &smp->flags);
375         mgmt_smp_complete(conn->hcon, complete);
376
377         kfree(smp->csrk);
378         kfree(smp->slave_csrk);
379
380         crypto_free_blkcipher(smp->tfm_aes);
381
382         /* If pairing failed clean up any keys we might have */
383         if (!complete) {
384                 if (smp->ltk) {
385                         list_del_rcu(&smp->ltk->list);
386                         kfree_rcu(smp->ltk, rcu);
387                 }
388
389                 if (smp->slave_ltk) {
390                         list_del_rcu(&smp->slave_ltk->list);
391                         kfree_rcu(smp->slave_ltk, rcu);
392                 }
393
394                 if (smp->remote_irk) {
395                         list_del_rcu(&smp->remote_irk->list);
396                         kfree_rcu(smp->remote_irk, rcu);
397                 }
398         }
399
400         chan->data = NULL;
401         kfree(smp);
402         hci_conn_drop(conn->hcon);
403 }
404
405 static void smp_failure(struct l2cap_conn *conn, u8 reason)
406 {
407         struct hci_conn *hcon = conn->hcon;
408         struct l2cap_chan *chan = conn->smp;
409
410         if (reason)
411                 smp_send_cmd(conn, SMP_CMD_PAIRING_FAIL, sizeof(reason),
412                              &reason);
413
414         clear_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags);
415         mgmt_auth_failed(hcon, HCI_ERROR_AUTH_FAILURE);
416
417         if (chan->data)
418                 smp_chan_destroy(conn);
419 }
420
421 #define JUST_WORKS      0x00
422 #define JUST_CFM        0x01
423 #define REQ_PASSKEY     0x02
424 #define CFM_PASSKEY     0x03
425 #define REQ_OOB         0x04
426 #define OVERLAP         0xFF
427
428 static const u8 gen_method[5][5] = {
429         { JUST_WORKS,  JUST_CFM,    REQ_PASSKEY, JUST_WORKS, REQ_PASSKEY },
430         { JUST_WORKS,  JUST_CFM,    REQ_PASSKEY, JUST_WORKS, REQ_PASSKEY },
431         { CFM_PASSKEY, CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, CFM_PASSKEY },
432         { JUST_WORKS,  JUST_CFM,    JUST_WORKS,  JUST_WORKS, JUST_CFM    },
433         { CFM_PASSKEY, CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, OVERLAP     },
434 };
435
436 static u8 get_auth_method(struct smp_chan *smp, u8 local_io, u8 remote_io)
437 {
438         /* If either side has unknown io_caps, use JUST_CFM (which gets
439          * converted later to JUST_WORKS if we're initiators.
440          */
441         if (local_io > SMP_IO_KEYBOARD_DISPLAY ||
442             remote_io > SMP_IO_KEYBOARD_DISPLAY)
443                 return JUST_CFM;
444
445         return gen_method[remote_io][local_io];
446 }
447
448 static int tk_request(struct l2cap_conn *conn, u8 remote_oob, u8 auth,
449                                                 u8 local_io, u8 remote_io)
450 {
451         struct hci_conn *hcon = conn->hcon;
452         struct l2cap_chan *chan = conn->smp;
453         struct smp_chan *smp = chan->data;
454         u8 method;
455         u32 passkey = 0;
456         int ret = 0;
457
458         /* Initialize key for JUST WORKS */
459         memset(smp->tk, 0, sizeof(smp->tk));
460         clear_bit(SMP_FLAG_TK_VALID, &smp->flags);
461
462         BT_DBG("tk_request: auth:%d lcl:%d rem:%d", auth, local_io, remote_io);
463
464         /* If neither side wants MITM, either "just" confirm an incoming
465          * request or use just-works for outgoing ones. The JUST_CFM
466          * will be converted to JUST_WORKS if necessary later in this
467          * function. If either side has MITM look up the method from the
468          * table.
469          */
470         if (!(auth & SMP_AUTH_MITM))
471                 method = JUST_CFM;
472         else
473                 method = get_auth_method(smp, local_io, remote_io);
474
475         /* Don't confirm locally initiated pairing attempts */
476         if (method == JUST_CFM && test_bit(SMP_FLAG_INITIATOR, &smp->flags))
477                 method = JUST_WORKS;
478
479         /* Don't bother user space with no IO capabilities */
480         if (method == JUST_CFM && hcon->io_capability == HCI_IO_NO_INPUT_OUTPUT)
481                 method = JUST_WORKS;
482
483         /* If Just Works, Continue with Zero TK */
484         if (method == JUST_WORKS) {
485                 set_bit(SMP_FLAG_TK_VALID, &smp->flags);
486                 return 0;
487         }
488
489         /* Not Just Works/Confirm results in MITM Authentication */
490         if (method != JUST_CFM) {
491                 set_bit(SMP_FLAG_MITM_AUTH, &smp->flags);
492                 if (hcon->pending_sec_level < BT_SECURITY_HIGH)
493                         hcon->pending_sec_level = BT_SECURITY_HIGH;
494         }
495
496         /* If both devices have Keyoard-Display I/O, the master
497          * Confirms and the slave Enters the passkey.
498          */
499         if (method == OVERLAP) {
500                 if (hcon->role == HCI_ROLE_MASTER)
501                         method = CFM_PASSKEY;
502                 else
503                         method = REQ_PASSKEY;
504         }
505
506         /* Generate random passkey. */
507         if (method == CFM_PASSKEY) {
508                 memset(smp->tk, 0, sizeof(smp->tk));
509                 get_random_bytes(&passkey, sizeof(passkey));
510                 passkey %= 1000000;
511                 put_unaligned_le32(passkey, smp->tk);
512                 BT_DBG("PassKey: %d", passkey);
513                 set_bit(SMP_FLAG_TK_VALID, &smp->flags);
514         }
515
516         if (method == REQ_PASSKEY)
517                 ret = mgmt_user_passkey_request(hcon->hdev, &hcon->dst,
518                                                 hcon->type, hcon->dst_type);
519         else if (method == JUST_CFM)
520                 ret = mgmt_user_confirm_request(hcon->hdev, &hcon->dst,
521                                                 hcon->type, hcon->dst_type,
522                                                 passkey, 1);
523         else
524                 ret = mgmt_user_passkey_notify(hcon->hdev, &hcon->dst,
525                                                 hcon->type, hcon->dst_type,
526                                                 passkey, 0);
527
528         return ret;
529 }
530
531 static u8 smp_confirm(struct smp_chan *smp)
532 {
533         struct l2cap_conn *conn = smp->conn;
534         struct smp_cmd_pairing_confirm cp;
535         int ret;
536
537         BT_DBG("conn %p", conn);
538
539         ret = smp_c1(smp->tfm_aes, smp->tk, smp->prnd, smp->preq, smp->prsp,
540                      conn->hcon->init_addr_type, &conn->hcon->init_addr,
541                      conn->hcon->resp_addr_type, &conn->hcon->resp_addr,
542                      cp.confirm_val);
543         if (ret)
544                 return SMP_UNSPECIFIED;
545
546         clear_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
547
548         smp_send_cmd(smp->conn, SMP_CMD_PAIRING_CONFIRM, sizeof(cp), &cp);
549
550         if (conn->hcon->out)
551                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
552         else
553                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
554
555         return 0;
556 }
557
558 static u8 smp_random(struct smp_chan *smp)
559 {
560         struct l2cap_conn *conn = smp->conn;
561         struct hci_conn *hcon = conn->hcon;
562         u8 confirm[16];
563         int ret;
564
565         if (IS_ERR_OR_NULL(smp->tfm_aes))
566                 return SMP_UNSPECIFIED;
567
568         BT_DBG("conn %p %s", conn, conn->hcon->out ? "master" : "slave");
569
570         ret = smp_c1(smp->tfm_aes, smp->tk, smp->rrnd, smp->preq, smp->prsp,
571                      hcon->init_addr_type, &hcon->init_addr,
572                      hcon->resp_addr_type, &hcon->resp_addr, confirm);
573         if (ret)
574                 return SMP_UNSPECIFIED;
575
576         if (memcmp(smp->pcnf, confirm, sizeof(smp->pcnf)) != 0) {
577                 BT_ERR("Pairing failed (confirmation values mismatch)");
578                 return SMP_CONFIRM_FAILED;
579         }
580
581         if (hcon->out) {
582                 u8 stk[16];
583                 __le64 rand = 0;
584                 __le16 ediv = 0;
585
586                 smp_s1(smp->tfm_aes, smp->tk, smp->rrnd, smp->prnd, stk);
587
588                 memset(stk + smp->enc_key_size, 0,
589                        SMP_MAX_ENC_KEY_SIZE - smp->enc_key_size);
590
591                 if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags))
592                         return SMP_UNSPECIFIED;
593
594                 hci_le_start_enc(hcon, ediv, rand, stk);
595                 hcon->enc_key_size = smp->enc_key_size;
596                 set_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags);
597         } else {
598                 u8 stk[16], auth;
599                 __le64 rand = 0;
600                 __le16 ediv = 0;
601
602                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
603                              smp->prnd);
604
605                 smp_s1(smp->tfm_aes, smp->tk, smp->prnd, smp->rrnd, stk);
606
607                 memset(stk + smp->enc_key_size, 0,
608                        SMP_MAX_ENC_KEY_SIZE - smp->enc_key_size);
609
610                 if (hcon->pending_sec_level == BT_SECURITY_HIGH)
611                         auth = 1;
612                 else
613                         auth = 0;
614
615                 /* Even though there's no _SLAVE suffix this is the
616                  * slave STK we're adding for later lookup (the master
617                  * STK never needs to be stored).
618                  */
619                 hci_add_ltk(hcon->hdev, &hcon->dst, hcon->dst_type,
620                             SMP_STK, auth, stk, smp->enc_key_size, ediv, rand);
621         }
622
623         return 0;
624 }
625
626 static void smp_notify_keys(struct l2cap_conn *conn)
627 {
628         struct l2cap_chan *chan = conn->smp;
629         struct smp_chan *smp = chan->data;
630         struct hci_conn *hcon = conn->hcon;
631         struct hci_dev *hdev = hcon->hdev;
632         struct smp_cmd_pairing *req = (void *) &smp->preq[1];
633         struct smp_cmd_pairing *rsp = (void *) &smp->prsp[1];
634         bool persistent;
635
636         if (smp->remote_irk) {
637                 mgmt_new_irk(hdev, smp->remote_irk);
638                 /* Now that user space can be considered to know the
639                  * identity address track the connection based on it
640                  * from now on.
641                  */
642                 bacpy(&hcon->dst, &smp->remote_irk->bdaddr);
643                 hcon->dst_type = smp->remote_irk->addr_type;
644                 queue_work(hdev->workqueue, &conn->id_addr_update_work);
645
646                 /* When receiving an indentity resolving key for
647                  * a remote device that does not use a resolvable
648                  * private address, just remove the key so that
649                  * it is possible to use the controller white
650                  * list for scanning.
651                  *
652                  * Userspace will have been told to not store
653                  * this key at this point. So it is safe to
654                  * just remove it.
655                  */
656                 if (!bacmp(&smp->remote_irk->rpa, BDADDR_ANY)) {
657                         list_del_rcu(&smp->remote_irk->list);
658                         kfree_rcu(smp->remote_irk, rcu);
659                         smp->remote_irk = NULL;
660                 }
661         }
662
663         /* The LTKs and CSRKs should be persistent only if both sides
664          * had the bonding bit set in their authentication requests.
665          */
666         persistent = !!((req->auth_req & rsp->auth_req) & SMP_AUTH_BONDING);
667
668         if (smp->csrk) {
669                 smp->csrk->bdaddr_type = hcon->dst_type;
670                 bacpy(&smp->csrk->bdaddr, &hcon->dst);
671                 mgmt_new_csrk(hdev, smp->csrk, persistent);
672         }
673
674         if (smp->slave_csrk) {
675                 smp->slave_csrk->bdaddr_type = hcon->dst_type;
676                 bacpy(&smp->slave_csrk->bdaddr, &hcon->dst);
677                 mgmt_new_csrk(hdev, smp->slave_csrk, persistent);
678         }
679
680         if (smp->ltk) {
681                 smp->ltk->bdaddr_type = hcon->dst_type;
682                 bacpy(&smp->ltk->bdaddr, &hcon->dst);
683                 mgmt_new_ltk(hdev, smp->ltk, persistent);
684         }
685
686         if (smp->slave_ltk) {
687                 smp->slave_ltk->bdaddr_type = hcon->dst_type;
688                 bacpy(&smp->slave_ltk->bdaddr, &hcon->dst);
689                 mgmt_new_ltk(hdev, smp->slave_ltk, persistent);
690         }
691 }
692
693 static void smp_allow_key_dist(struct smp_chan *smp)
694 {
695         /* Allow the first expected phase 3 PDU. The rest of the PDUs
696          * will be allowed in each PDU handler to ensure we receive
697          * them in the correct order.
698          */
699         if (smp->remote_key_dist & SMP_DIST_ENC_KEY)
700                 SMP_ALLOW_CMD(smp, SMP_CMD_ENCRYPT_INFO);
701         else if (smp->remote_key_dist & SMP_DIST_ID_KEY)
702                 SMP_ALLOW_CMD(smp, SMP_CMD_IDENT_INFO);
703         else if (smp->remote_key_dist & SMP_DIST_SIGN)
704                 SMP_ALLOW_CMD(smp, SMP_CMD_SIGN_INFO);
705 }
706
707 static void smp_distribute_keys(struct smp_chan *smp)
708 {
709         struct smp_cmd_pairing *req, *rsp;
710         struct l2cap_conn *conn = smp->conn;
711         struct hci_conn *hcon = conn->hcon;
712         struct hci_dev *hdev = hcon->hdev;
713         __u8 *keydist;
714
715         BT_DBG("conn %p", conn);
716
717         rsp = (void *) &smp->prsp[1];
718
719         /* The responder sends its keys first */
720         if (hcon->out && (smp->remote_key_dist & KEY_DIST_MASK)) {
721                 smp_allow_key_dist(smp);
722                 return;
723         }
724
725         req = (void *) &smp->preq[1];
726
727         if (hcon->out) {
728                 keydist = &rsp->init_key_dist;
729                 *keydist &= req->init_key_dist;
730         } else {
731                 keydist = &rsp->resp_key_dist;
732                 *keydist &= req->resp_key_dist;
733         }
734
735         BT_DBG("keydist 0x%x", *keydist);
736
737         if (*keydist & SMP_DIST_ENC_KEY) {
738                 struct smp_cmd_encrypt_info enc;
739                 struct smp_cmd_master_ident ident;
740                 struct smp_ltk *ltk;
741                 u8 authenticated;
742                 __le16 ediv;
743                 __le64 rand;
744
745                 get_random_bytes(enc.ltk, sizeof(enc.ltk));
746                 get_random_bytes(&ediv, sizeof(ediv));
747                 get_random_bytes(&rand, sizeof(rand));
748
749                 smp_send_cmd(conn, SMP_CMD_ENCRYPT_INFO, sizeof(enc), &enc);
750
751                 authenticated = hcon->sec_level == BT_SECURITY_HIGH;
752                 ltk = hci_add_ltk(hdev, &hcon->dst, hcon->dst_type,
753                                   SMP_LTK_SLAVE, authenticated, enc.ltk,
754                                   smp->enc_key_size, ediv, rand);
755                 smp->slave_ltk = ltk;
756
757                 ident.ediv = ediv;
758                 ident.rand = rand;
759
760                 smp_send_cmd(conn, SMP_CMD_MASTER_IDENT, sizeof(ident), &ident);
761
762                 *keydist &= ~SMP_DIST_ENC_KEY;
763         }
764
765         if (*keydist & SMP_DIST_ID_KEY) {
766                 struct smp_cmd_ident_addr_info addrinfo;
767                 struct smp_cmd_ident_info idinfo;
768
769                 memcpy(idinfo.irk, hdev->irk, sizeof(idinfo.irk));
770
771                 smp_send_cmd(conn, SMP_CMD_IDENT_INFO, sizeof(idinfo), &idinfo);
772
773                 /* The hci_conn contains the local identity address
774                  * after the connection has been established.
775                  *
776                  * This is true even when the connection has been
777                  * established using a resolvable random address.
778                  */
779                 bacpy(&addrinfo.bdaddr, &hcon->src);
780                 addrinfo.addr_type = hcon->src_type;
781
782                 smp_send_cmd(conn, SMP_CMD_IDENT_ADDR_INFO, sizeof(addrinfo),
783                              &addrinfo);
784
785                 *keydist &= ~SMP_DIST_ID_KEY;
786         }
787
788         if (*keydist & SMP_DIST_SIGN) {
789                 struct smp_cmd_sign_info sign;
790                 struct smp_csrk *csrk;
791
792                 /* Generate a new random key */
793                 get_random_bytes(sign.csrk, sizeof(sign.csrk));
794
795                 csrk = kzalloc(sizeof(*csrk), GFP_KERNEL);
796                 if (csrk) {
797                         csrk->master = 0x00;
798                         memcpy(csrk->val, sign.csrk, sizeof(csrk->val));
799                 }
800                 smp->slave_csrk = csrk;
801
802                 smp_send_cmd(conn, SMP_CMD_SIGN_INFO, sizeof(sign), &sign);
803
804                 *keydist &= ~SMP_DIST_SIGN;
805         }
806
807         /* If there are still keys to be received wait for them */
808         if (smp->remote_key_dist & KEY_DIST_MASK) {
809                 smp_allow_key_dist(smp);
810                 return;
811         }
812
813         set_bit(SMP_FLAG_COMPLETE, &smp->flags);
814         smp_notify_keys(conn);
815
816         smp_chan_destroy(conn);
817 }
818
819 static void smp_timeout(struct work_struct *work)
820 {
821         struct smp_chan *smp = container_of(work, struct smp_chan,
822                                             security_timer.work);
823         struct l2cap_conn *conn = smp->conn;
824
825         BT_DBG("conn %p", conn);
826
827         hci_disconnect(conn->hcon, HCI_ERROR_REMOTE_USER_TERM);
828 }
829
830 static struct smp_chan *smp_chan_create(struct l2cap_conn *conn)
831 {
832         struct l2cap_chan *chan = conn->smp;
833         struct smp_chan *smp;
834
835         smp = kzalloc(sizeof(*smp), GFP_ATOMIC);
836         if (!smp)
837                 return NULL;
838
839         smp->tfm_aes = crypto_alloc_blkcipher("ecb(aes)", 0, CRYPTO_ALG_ASYNC);
840         if (IS_ERR(smp->tfm_aes)) {
841                 BT_ERR("Unable to create ECB crypto context");
842                 kfree(smp);
843                 return NULL;
844         }
845
846         smp->conn = conn;
847         chan->data = smp;
848
849         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_FAIL);
850
851         INIT_DELAYED_WORK(&smp->security_timer, smp_timeout);
852
853         hci_conn_hold(conn->hcon);
854
855         return smp;
856 }
857
858 int smp_user_confirm_reply(struct hci_conn *hcon, u16 mgmt_op, __le32 passkey)
859 {
860         struct l2cap_conn *conn = hcon->l2cap_data;
861         struct l2cap_chan *chan;
862         struct smp_chan *smp;
863         u32 value;
864         int err;
865
866         BT_DBG("");
867
868         if (!conn)
869                 return -ENOTCONN;
870
871         chan = conn->smp;
872         if (!chan)
873                 return -ENOTCONN;
874
875         l2cap_chan_lock(chan);
876         if (!chan->data) {
877                 err = -ENOTCONN;
878                 goto unlock;
879         }
880
881         smp = chan->data;
882
883         switch (mgmt_op) {
884         case MGMT_OP_USER_PASSKEY_REPLY:
885                 value = le32_to_cpu(passkey);
886                 memset(smp->tk, 0, sizeof(smp->tk));
887                 BT_DBG("PassKey: %d", value);
888                 put_unaligned_le32(value, smp->tk);
889                 /* Fall Through */
890         case MGMT_OP_USER_CONFIRM_REPLY:
891                 set_bit(SMP_FLAG_TK_VALID, &smp->flags);
892                 break;
893         case MGMT_OP_USER_PASSKEY_NEG_REPLY:
894         case MGMT_OP_USER_CONFIRM_NEG_REPLY:
895                 smp_failure(conn, SMP_PASSKEY_ENTRY_FAILED);
896                 err = 0;
897                 goto unlock;
898         default:
899                 smp_failure(conn, SMP_PASSKEY_ENTRY_FAILED);
900                 err = -EOPNOTSUPP;
901                 goto unlock;
902         }
903
904         err = 0;
905
906         /* If it is our turn to send Pairing Confirm, do so now */
907         if (test_bit(SMP_FLAG_CFM_PENDING, &smp->flags)) {
908                 u8 rsp = smp_confirm(smp);
909                 if (rsp)
910                         smp_failure(conn, rsp);
911         }
912
913 unlock:
914         l2cap_chan_unlock(chan);
915         return err;
916 }
917
918 static u8 smp_cmd_pairing_req(struct l2cap_conn *conn, struct sk_buff *skb)
919 {
920         struct smp_cmd_pairing rsp, *req = (void *) skb->data;
921         struct l2cap_chan *chan = conn->smp;
922         struct hci_dev *hdev = conn->hcon->hdev;
923         struct smp_chan *smp;
924         u8 key_size, auth, sec_level;
925         int ret;
926
927         BT_DBG("conn %p", conn);
928
929         if (skb->len < sizeof(*req))
930                 return SMP_INVALID_PARAMS;
931
932         if (conn->hcon->role != HCI_ROLE_SLAVE)
933                 return SMP_CMD_NOTSUPP;
934
935         if (!chan->data)
936                 smp = smp_chan_create(conn);
937         else
938                 smp = chan->data;
939
940         if (!smp)
941                 return SMP_UNSPECIFIED;
942
943         /* We didn't start the pairing, so match remote */
944         auth = req->auth_req & AUTH_REQ_MASK;
945
946         if (!test_bit(HCI_BONDABLE, &hdev->dev_flags) &&
947             (auth & SMP_AUTH_BONDING))
948                 return SMP_PAIRING_NOTSUPP;
949
950         smp->preq[0] = SMP_CMD_PAIRING_REQ;
951         memcpy(&smp->preq[1], req, sizeof(*req));
952         skb_pull(skb, sizeof(*req));
953
954         if (conn->hcon->io_capability == HCI_IO_NO_INPUT_OUTPUT)
955                 sec_level = BT_SECURITY_MEDIUM;
956         else
957                 sec_level = authreq_to_seclevel(auth);
958
959         if (sec_level > conn->hcon->pending_sec_level)
960                 conn->hcon->pending_sec_level = sec_level;
961
962         /* If we need MITM check that it can be achieved */
963         if (conn->hcon->pending_sec_level >= BT_SECURITY_HIGH) {
964                 u8 method;
965
966                 method = get_auth_method(smp, conn->hcon->io_capability,
967                                          req->io_capability);
968                 if (method == JUST_WORKS || method == JUST_CFM)
969                         return SMP_AUTH_REQUIREMENTS;
970         }
971
972         build_pairing_cmd(conn, req, &rsp, auth);
973
974         key_size = min(req->max_key_size, rsp.max_key_size);
975         if (check_enc_key_size(conn, key_size))
976                 return SMP_ENC_KEY_SIZE;
977
978         get_random_bytes(smp->prnd, sizeof(smp->prnd));
979
980         smp->prsp[0] = SMP_CMD_PAIRING_RSP;
981         memcpy(&smp->prsp[1], &rsp, sizeof(rsp));
982
983         smp_send_cmd(conn, SMP_CMD_PAIRING_RSP, sizeof(rsp), &rsp);
984         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
985
986         /* Request setup of TK */
987         ret = tk_request(conn, 0, auth, rsp.io_capability, req->io_capability);
988         if (ret)
989                 return SMP_UNSPECIFIED;
990
991         return 0;
992 }
993
994 static u8 smp_cmd_pairing_rsp(struct l2cap_conn *conn, struct sk_buff *skb)
995 {
996         struct smp_cmd_pairing *req, *rsp = (void *) skb->data;
997         struct l2cap_chan *chan = conn->smp;
998         struct smp_chan *smp = chan->data;
999         u8 key_size, auth;
1000         int ret;
1001
1002         BT_DBG("conn %p", conn);
1003
1004         if (skb->len < sizeof(*rsp))
1005                 return SMP_INVALID_PARAMS;
1006
1007         if (conn->hcon->role != HCI_ROLE_MASTER)
1008                 return SMP_CMD_NOTSUPP;
1009
1010         skb_pull(skb, sizeof(*rsp));
1011
1012         req = (void *) &smp->preq[1];
1013
1014         key_size = min(req->max_key_size, rsp->max_key_size);
1015         if (check_enc_key_size(conn, key_size))
1016                 return SMP_ENC_KEY_SIZE;
1017
1018         auth = rsp->auth_req & AUTH_REQ_MASK;
1019
1020         /* If we need MITM check that it can be achieved */
1021         if (conn->hcon->pending_sec_level >= BT_SECURITY_HIGH) {
1022                 u8 method;
1023
1024                 method = get_auth_method(smp, req->io_capability,
1025                                          rsp->io_capability);
1026                 if (method == JUST_WORKS || method == JUST_CFM)
1027                         return SMP_AUTH_REQUIREMENTS;
1028         }
1029
1030         get_random_bytes(smp->prnd, sizeof(smp->prnd));
1031
1032         smp->prsp[0] = SMP_CMD_PAIRING_RSP;
1033         memcpy(&smp->prsp[1], rsp, sizeof(*rsp));
1034
1035         /* Update remote key distribution in case the remote cleared
1036          * some bits that we had enabled in our request.
1037          */
1038         smp->remote_key_dist &= rsp->resp_key_dist;
1039
1040         auth |= req->auth_req;
1041
1042         ret = tk_request(conn, 0, auth, req->io_capability, rsp->io_capability);
1043         if (ret)
1044                 return SMP_UNSPECIFIED;
1045
1046         set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
1047
1048         /* Can't compose response until we have been confirmed */
1049         if (test_bit(SMP_FLAG_TK_VALID, &smp->flags))
1050                 return smp_confirm(smp);
1051
1052         return 0;
1053 }
1054
1055 static u8 smp_cmd_pairing_confirm(struct l2cap_conn *conn, struct sk_buff *skb)
1056 {
1057         struct l2cap_chan *chan = conn->smp;
1058         struct smp_chan *smp = chan->data;
1059
1060         BT_DBG("conn %p %s", conn, conn->hcon->out ? "master" : "slave");
1061
1062         if (skb->len < sizeof(smp->pcnf))
1063                 return SMP_INVALID_PARAMS;
1064
1065         memcpy(smp->pcnf, skb->data, sizeof(smp->pcnf));
1066         skb_pull(skb, sizeof(smp->pcnf));
1067
1068         if (conn->hcon->out) {
1069                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
1070                              smp->prnd);
1071                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
1072                 return 0;
1073         }
1074
1075         if (test_bit(SMP_FLAG_TK_VALID, &smp->flags))
1076                 return smp_confirm(smp);
1077         else
1078                 set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
1079
1080         return 0;
1081 }
1082
1083 static u8 smp_cmd_pairing_random(struct l2cap_conn *conn, struct sk_buff *skb)
1084 {
1085         struct l2cap_chan *chan = conn->smp;
1086         struct smp_chan *smp = chan->data;
1087
1088         BT_DBG("conn %p", conn);
1089
1090         if (skb->len < sizeof(smp->rrnd))
1091                 return SMP_INVALID_PARAMS;
1092
1093         memcpy(smp->rrnd, skb->data, sizeof(smp->rrnd));
1094         skb_pull(skb, sizeof(smp->rrnd));
1095
1096         return smp_random(smp);
1097 }
1098
1099 static bool smp_ltk_encrypt(struct l2cap_conn *conn, u8 sec_level)
1100 {
1101         struct smp_ltk *key;
1102         struct hci_conn *hcon = conn->hcon;
1103
1104         key = hci_find_ltk_by_addr(hcon->hdev, &hcon->dst, hcon->dst_type,
1105                                    hcon->role);
1106         if (!key)
1107                 return false;
1108
1109         if (smp_ltk_sec_level(key) < sec_level)
1110                 return false;
1111
1112         if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags))
1113                 return true;
1114
1115         hci_le_start_enc(hcon, key->ediv, key->rand, key->val);
1116         hcon->enc_key_size = key->enc_size;
1117
1118         /* We never store STKs for master role, so clear this flag */
1119         clear_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags);
1120
1121         return true;
1122 }
1123
1124 bool smp_sufficient_security(struct hci_conn *hcon, u8 sec_level,
1125                              enum smp_key_pref key_pref)
1126 {
1127         if (sec_level == BT_SECURITY_LOW)
1128                 return true;
1129
1130         /* If we're encrypted with an STK but the caller prefers using
1131          * LTK claim insufficient security. This way we allow the
1132          * connection to be re-encrypted with an LTK, even if the LTK
1133          * provides the same level of security. Only exception is if we
1134          * don't have an LTK (e.g. because of key distribution bits).
1135          */
1136         if (key_pref == SMP_USE_LTK &&
1137             test_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags) &&
1138             hci_find_ltk_by_addr(hcon->hdev, &hcon->dst, hcon->dst_type,
1139                                  hcon->role))
1140                 return false;
1141
1142         if (hcon->sec_level >= sec_level)
1143                 return true;
1144
1145         return false;
1146 }
1147
1148 static u8 smp_cmd_security_req(struct l2cap_conn *conn, struct sk_buff *skb)
1149 {
1150         struct smp_cmd_security_req *rp = (void *) skb->data;
1151         struct smp_cmd_pairing cp;
1152         struct hci_conn *hcon = conn->hcon;
1153         struct smp_chan *smp;
1154         u8 sec_level, auth;
1155
1156         BT_DBG("conn %p", conn);
1157
1158         if (skb->len < sizeof(*rp))
1159                 return SMP_INVALID_PARAMS;
1160
1161         if (hcon->role != HCI_ROLE_MASTER)
1162                 return SMP_CMD_NOTSUPP;
1163
1164         auth = rp->auth_req & AUTH_REQ_MASK;
1165
1166         if (hcon->io_capability == HCI_IO_NO_INPUT_OUTPUT)
1167                 sec_level = BT_SECURITY_MEDIUM;
1168         else
1169                 sec_level = authreq_to_seclevel(auth);
1170
1171         if (smp_sufficient_security(hcon, sec_level, SMP_USE_LTK))
1172                 return 0;
1173
1174         if (sec_level > hcon->pending_sec_level)
1175                 hcon->pending_sec_level = sec_level;
1176
1177         if (smp_ltk_encrypt(conn, hcon->pending_sec_level))
1178                 return 0;
1179
1180         smp = smp_chan_create(conn);
1181         if (!smp)
1182                 return SMP_UNSPECIFIED;
1183
1184         if (!test_bit(HCI_BONDABLE, &hcon->hdev->dev_flags) &&
1185             (auth & SMP_AUTH_BONDING))
1186                 return SMP_PAIRING_NOTSUPP;
1187
1188         skb_pull(skb, sizeof(*rp));
1189
1190         memset(&cp, 0, sizeof(cp));
1191         build_pairing_cmd(conn, &cp, NULL, auth);
1192
1193         smp->preq[0] = SMP_CMD_PAIRING_REQ;
1194         memcpy(&smp->preq[1], &cp, sizeof(cp));
1195
1196         smp_send_cmd(conn, SMP_CMD_PAIRING_REQ, sizeof(cp), &cp);
1197         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RSP);
1198
1199         return 0;
1200 }
1201
1202 int smp_conn_security(struct hci_conn *hcon, __u8 sec_level)
1203 {
1204         struct l2cap_conn *conn = hcon->l2cap_data;
1205         struct l2cap_chan *chan;
1206         struct smp_chan *smp;
1207         __u8 authreq;
1208         int ret;
1209
1210         BT_DBG("conn %p hcon %p level 0x%2.2x", conn, hcon, sec_level);
1211
1212         /* This may be NULL if there's an unexpected disconnection */
1213         if (!conn)
1214                 return 1;
1215
1216         chan = conn->smp;
1217
1218         if (!test_bit(HCI_LE_ENABLED, &hcon->hdev->dev_flags))
1219                 return 1;
1220
1221         if (smp_sufficient_security(hcon, sec_level, SMP_USE_LTK))
1222                 return 1;
1223
1224         if (sec_level > hcon->pending_sec_level)
1225                 hcon->pending_sec_level = sec_level;
1226
1227         if (hcon->role == HCI_ROLE_MASTER)
1228                 if (smp_ltk_encrypt(conn, hcon->pending_sec_level))
1229                         return 0;
1230
1231         l2cap_chan_lock(chan);
1232
1233         /* If SMP is already in progress ignore this request */
1234         if (chan->data) {
1235                 ret = 0;
1236                 goto unlock;
1237         }
1238
1239         smp = smp_chan_create(conn);
1240         if (!smp) {
1241                 ret = 1;
1242                 goto unlock;
1243         }
1244
1245         authreq = seclevel_to_authreq(sec_level);
1246
1247         /* Require MITM if IO Capability allows or the security level
1248          * requires it.
1249          */
1250         if (hcon->io_capability != HCI_IO_NO_INPUT_OUTPUT ||
1251             hcon->pending_sec_level > BT_SECURITY_MEDIUM)
1252                 authreq |= SMP_AUTH_MITM;
1253
1254         if (hcon->role == HCI_ROLE_MASTER) {
1255                 struct smp_cmd_pairing cp;
1256
1257                 build_pairing_cmd(conn, &cp, NULL, authreq);
1258                 smp->preq[0] = SMP_CMD_PAIRING_REQ;
1259                 memcpy(&smp->preq[1], &cp, sizeof(cp));
1260
1261                 smp_send_cmd(conn, SMP_CMD_PAIRING_REQ, sizeof(cp), &cp);
1262                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RSP);
1263         } else {
1264                 struct smp_cmd_security_req cp;
1265                 cp.auth_req = authreq;
1266                 smp_send_cmd(conn, SMP_CMD_SECURITY_REQ, sizeof(cp), &cp);
1267                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_REQ);
1268         }
1269
1270         set_bit(SMP_FLAG_INITIATOR, &smp->flags);
1271         ret = 0;
1272
1273 unlock:
1274         l2cap_chan_unlock(chan);
1275         return ret;
1276 }
1277
1278 static int smp_cmd_encrypt_info(struct l2cap_conn *conn, struct sk_buff *skb)
1279 {
1280         struct smp_cmd_encrypt_info *rp = (void *) skb->data;
1281         struct l2cap_chan *chan = conn->smp;
1282         struct smp_chan *smp = chan->data;
1283
1284         BT_DBG("conn %p", conn);
1285
1286         if (skb->len < sizeof(*rp))
1287                 return SMP_INVALID_PARAMS;
1288
1289         SMP_ALLOW_CMD(smp, SMP_CMD_MASTER_IDENT);
1290
1291         skb_pull(skb, sizeof(*rp));
1292
1293         memcpy(smp->tk, rp->ltk, sizeof(smp->tk));
1294
1295         return 0;
1296 }
1297
1298 static int smp_cmd_master_ident(struct l2cap_conn *conn, struct sk_buff *skb)
1299 {
1300         struct smp_cmd_master_ident *rp = (void *) skb->data;
1301         struct l2cap_chan *chan = conn->smp;
1302         struct smp_chan *smp = chan->data;
1303         struct hci_dev *hdev = conn->hcon->hdev;
1304         struct hci_conn *hcon = conn->hcon;
1305         struct smp_ltk *ltk;
1306         u8 authenticated;
1307
1308         BT_DBG("conn %p", conn);
1309
1310         if (skb->len < sizeof(*rp))
1311                 return SMP_INVALID_PARAMS;
1312
1313         /* Mark the information as received */
1314         smp->remote_key_dist &= ~SMP_DIST_ENC_KEY;
1315
1316         if (smp->remote_key_dist & SMP_DIST_ID_KEY)
1317                 SMP_ALLOW_CMD(smp, SMP_CMD_IDENT_INFO);
1318         else if (smp->remote_key_dist & SMP_DIST_SIGN)
1319                 SMP_ALLOW_CMD(smp, SMP_CMD_SIGN_INFO);
1320
1321         skb_pull(skb, sizeof(*rp));
1322
1323         authenticated = (hcon->sec_level == BT_SECURITY_HIGH);
1324         ltk = hci_add_ltk(hdev, &hcon->dst, hcon->dst_type, SMP_LTK,
1325                           authenticated, smp->tk, smp->enc_key_size,
1326                           rp->ediv, rp->rand);
1327         smp->ltk = ltk;
1328         if (!(smp->remote_key_dist & KEY_DIST_MASK))
1329                 smp_distribute_keys(smp);
1330
1331         return 0;
1332 }
1333
1334 static int smp_cmd_ident_info(struct l2cap_conn *conn, struct sk_buff *skb)
1335 {
1336         struct smp_cmd_ident_info *info = (void *) skb->data;
1337         struct l2cap_chan *chan = conn->smp;
1338         struct smp_chan *smp = chan->data;
1339
1340         BT_DBG("");
1341
1342         if (skb->len < sizeof(*info))
1343                 return SMP_INVALID_PARAMS;
1344
1345         SMP_ALLOW_CMD(smp, SMP_CMD_IDENT_ADDR_INFO);
1346
1347         skb_pull(skb, sizeof(*info));
1348
1349         memcpy(smp->irk, info->irk, 16);
1350
1351         return 0;
1352 }
1353
1354 static int smp_cmd_ident_addr_info(struct l2cap_conn *conn,
1355                                    struct sk_buff *skb)
1356 {
1357         struct smp_cmd_ident_addr_info *info = (void *) skb->data;
1358         struct l2cap_chan *chan = conn->smp;
1359         struct smp_chan *smp = chan->data;
1360         struct hci_conn *hcon = conn->hcon;
1361         bdaddr_t rpa;
1362
1363         BT_DBG("");
1364
1365         if (skb->len < sizeof(*info))
1366                 return SMP_INVALID_PARAMS;
1367
1368         /* Mark the information as received */
1369         smp->remote_key_dist &= ~SMP_DIST_ID_KEY;
1370
1371         if (smp->remote_key_dist & SMP_DIST_SIGN)
1372                 SMP_ALLOW_CMD(smp, SMP_CMD_SIGN_INFO);
1373
1374         skb_pull(skb, sizeof(*info));
1375
1376         /* Strictly speaking the Core Specification (4.1) allows sending
1377          * an empty address which would force us to rely on just the IRK
1378          * as "identity information". However, since such
1379          * implementations are not known of and in order to not over
1380          * complicate our implementation, simply pretend that we never
1381          * received an IRK for such a device.
1382          */
1383         if (!bacmp(&info->bdaddr, BDADDR_ANY)) {
1384                 BT_ERR("Ignoring IRK with no identity address");
1385                 goto distribute;
1386         }
1387
1388         bacpy(&smp->id_addr, &info->bdaddr);
1389         smp->id_addr_type = info->addr_type;
1390
1391         if (hci_bdaddr_is_rpa(&hcon->dst, hcon->dst_type))
1392                 bacpy(&rpa, &hcon->dst);
1393         else
1394                 bacpy(&rpa, BDADDR_ANY);
1395
1396         smp->remote_irk = hci_add_irk(conn->hcon->hdev, &smp->id_addr,
1397                                       smp->id_addr_type, smp->irk, &rpa);
1398
1399 distribute:
1400         if (!(smp->remote_key_dist & KEY_DIST_MASK))
1401                 smp_distribute_keys(smp);
1402
1403         return 0;
1404 }
1405
1406 static int smp_cmd_sign_info(struct l2cap_conn *conn, struct sk_buff *skb)
1407 {
1408         struct smp_cmd_sign_info *rp = (void *) skb->data;
1409         struct l2cap_chan *chan = conn->smp;
1410         struct smp_chan *smp = chan->data;
1411         struct smp_csrk *csrk;
1412
1413         BT_DBG("conn %p", conn);
1414
1415         if (skb->len < sizeof(*rp))
1416                 return SMP_INVALID_PARAMS;
1417
1418         /* Mark the information as received */
1419         smp->remote_key_dist &= ~SMP_DIST_SIGN;
1420
1421         skb_pull(skb, sizeof(*rp));
1422
1423         csrk = kzalloc(sizeof(*csrk), GFP_KERNEL);
1424         if (csrk) {
1425                 csrk->master = 0x01;
1426                 memcpy(csrk->val, rp->csrk, sizeof(csrk->val));
1427         }
1428         smp->csrk = csrk;
1429         smp_distribute_keys(smp);
1430
1431         return 0;
1432 }
1433
1434 static int smp_sig_channel(struct l2cap_chan *chan, struct sk_buff *skb)
1435 {
1436         struct l2cap_conn *conn = chan->conn;
1437         struct hci_conn *hcon = conn->hcon;
1438         struct smp_chan *smp;
1439         __u8 code, reason;
1440         int err = 0;
1441
1442         if (hcon->type != LE_LINK) {
1443                 kfree_skb(skb);
1444                 return 0;
1445         }
1446
1447         if (skb->len < 1)
1448                 return -EILSEQ;
1449
1450         if (!test_bit(HCI_LE_ENABLED, &hcon->hdev->dev_flags)) {
1451                 reason = SMP_PAIRING_NOTSUPP;
1452                 goto done;
1453         }
1454
1455         code = skb->data[0];
1456         skb_pull(skb, sizeof(code));
1457
1458         smp = chan->data;
1459
1460         if (code > SMP_CMD_MAX)
1461                 goto drop;
1462
1463         if (smp && !test_and_clear_bit(code, &smp->allow_cmd))
1464                 goto drop;
1465
1466         /* If we don't have a context the only allowed commands are
1467          * pairing request and security request.
1468          */
1469         if (!smp && code != SMP_CMD_PAIRING_REQ && code != SMP_CMD_SECURITY_REQ)
1470                 goto drop;
1471
1472         switch (code) {
1473         case SMP_CMD_PAIRING_REQ:
1474                 reason = smp_cmd_pairing_req(conn, skb);
1475                 break;
1476
1477         case SMP_CMD_PAIRING_FAIL:
1478                 smp_failure(conn, 0);
1479                 err = -EPERM;
1480                 break;
1481
1482         case SMP_CMD_PAIRING_RSP:
1483                 reason = smp_cmd_pairing_rsp(conn, skb);
1484                 break;
1485
1486         case SMP_CMD_SECURITY_REQ:
1487                 reason = smp_cmd_security_req(conn, skb);
1488                 break;
1489
1490         case SMP_CMD_PAIRING_CONFIRM:
1491                 reason = smp_cmd_pairing_confirm(conn, skb);
1492                 break;
1493
1494         case SMP_CMD_PAIRING_RANDOM:
1495                 reason = smp_cmd_pairing_random(conn, skb);
1496                 break;
1497
1498         case SMP_CMD_ENCRYPT_INFO:
1499                 reason = smp_cmd_encrypt_info(conn, skb);
1500                 break;
1501
1502         case SMP_CMD_MASTER_IDENT:
1503                 reason = smp_cmd_master_ident(conn, skb);
1504                 break;
1505
1506         case SMP_CMD_IDENT_INFO:
1507                 reason = smp_cmd_ident_info(conn, skb);
1508                 break;
1509
1510         case SMP_CMD_IDENT_ADDR_INFO:
1511                 reason = smp_cmd_ident_addr_info(conn, skb);
1512                 break;
1513
1514         case SMP_CMD_SIGN_INFO:
1515                 reason = smp_cmd_sign_info(conn, skb);
1516                 break;
1517
1518         default:
1519                 BT_DBG("Unknown command code 0x%2.2x", code);
1520                 reason = SMP_CMD_NOTSUPP;
1521                 goto done;
1522         }
1523
1524 done:
1525         if (!err) {
1526                 if (reason)
1527                         smp_failure(conn, reason);
1528                 kfree_skb(skb);
1529         }
1530
1531         return err;
1532
1533 drop:
1534         BT_ERR("%s unexpected SMP command 0x%02x from %pMR", hcon->hdev->name,
1535                code, &hcon->dst);
1536         kfree_skb(skb);
1537         return 0;
1538 }
1539
1540 static void smp_teardown_cb(struct l2cap_chan *chan, int err)
1541 {
1542         struct l2cap_conn *conn = chan->conn;
1543
1544         BT_DBG("chan %p", chan);
1545
1546         if (chan->data)
1547                 smp_chan_destroy(conn);
1548
1549         conn->smp = NULL;
1550         l2cap_chan_put(chan);
1551 }
1552
1553 static void smp_resume_cb(struct l2cap_chan *chan)
1554 {
1555         struct smp_chan *smp = chan->data;
1556         struct l2cap_conn *conn = chan->conn;
1557         struct hci_conn *hcon = conn->hcon;
1558
1559         BT_DBG("chan %p", chan);
1560
1561         if (!smp)
1562                 return;
1563
1564         if (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags))
1565                 return;
1566
1567         cancel_delayed_work(&smp->security_timer);
1568
1569         smp_distribute_keys(smp);
1570 }
1571
1572 static void smp_ready_cb(struct l2cap_chan *chan)
1573 {
1574         struct l2cap_conn *conn = chan->conn;
1575
1576         BT_DBG("chan %p", chan);
1577
1578         conn->smp = chan;
1579         l2cap_chan_hold(chan);
1580 }
1581
1582 static int smp_recv_cb(struct l2cap_chan *chan, struct sk_buff *skb)
1583 {
1584         int err;
1585
1586         BT_DBG("chan %p", chan);
1587
1588         err = smp_sig_channel(chan, skb);
1589         if (err) {
1590                 struct smp_chan *smp = chan->data;
1591
1592                 if (smp)
1593                         cancel_delayed_work_sync(&smp->security_timer);
1594
1595                 hci_disconnect(chan->conn->hcon, HCI_ERROR_AUTH_FAILURE);
1596         }
1597
1598         return err;
1599 }
1600
1601 static struct sk_buff *smp_alloc_skb_cb(struct l2cap_chan *chan,
1602                                         unsigned long hdr_len,
1603                                         unsigned long len, int nb)
1604 {
1605         struct sk_buff *skb;
1606
1607         skb = bt_skb_alloc(hdr_len + len, GFP_KERNEL);
1608         if (!skb)
1609                 return ERR_PTR(-ENOMEM);
1610
1611         skb->priority = HCI_PRIO_MAX;
1612         bt_cb(skb)->chan = chan;
1613
1614         return skb;
1615 }
1616
1617 static const struct l2cap_ops smp_chan_ops = {
1618         .name                   = "Security Manager",
1619         .ready                  = smp_ready_cb,
1620         .recv                   = smp_recv_cb,
1621         .alloc_skb              = smp_alloc_skb_cb,
1622         .teardown               = smp_teardown_cb,
1623         .resume                 = smp_resume_cb,
1624
1625         .new_connection         = l2cap_chan_no_new_connection,
1626         .state_change           = l2cap_chan_no_state_change,
1627         .close                  = l2cap_chan_no_close,
1628         .defer                  = l2cap_chan_no_defer,
1629         .suspend                = l2cap_chan_no_suspend,
1630         .set_shutdown           = l2cap_chan_no_set_shutdown,
1631         .get_sndtimeo           = l2cap_chan_no_get_sndtimeo,
1632 };
1633
1634 static inline struct l2cap_chan *smp_new_conn_cb(struct l2cap_chan *pchan)
1635 {
1636         struct l2cap_chan *chan;
1637
1638         BT_DBG("pchan %p", pchan);
1639
1640         chan = l2cap_chan_create();
1641         if (!chan)
1642                 return NULL;
1643
1644         chan->chan_type = pchan->chan_type;
1645         chan->ops       = &smp_chan_ops;
1646         chan->scid      = pchan->scid;
1647         chan->dcid      = chan->scid;
1648         chan->imtu      = pchan->imtu;
1649         chan->omtu      = pchan->omtu;
1650         chan->mode      = pchan->mode;
1651
1652         /* Other L2CAP channels may request SMP routines in order to
1653          * change the security level. This means that the SMP channel
1654          * lock must be considered in its own category to avoid lockdep
1655          * warnings.
1656          */
1657         atomic_set(&chan->nesting, L2CAP_NESTING_SMP);
1658
1659         BT_DBG("created chan %p", chan);
1660
1661         return chan;
1662 }
1663
1664 static const struct l2cap_ops smp_root_chan_ops = {
1665         .name                   = "Security Manager Root",
1666         .new_connection         = smp_new_conn_cb,
1667
1668         /* None of these are implemented for the root channel */
1669         .close                  = l2cap_chan_no_close,
1670         .alloc_skb              = l2cap_chan_no_alloc_skb,
1671         .recv                   = l2cap_chan_no_recv,
1672         .state_change           = l2cap_chan_no_state_change,
1673         .teardown               = l2cap_chan_no_teardown,
1674         .ready                  = l2cap_chan_no_ready,
1675         .defer                  = l2cap_chan_no_defer,
1676         .suspend                = l2cap_chan_no_suspend,
1677         .resume                 = l2cap_chan_no_resume,
1678         .set_shutdown           = l2cap_chan_no_set_shutdown,
1679         .get_sndtimeo           = l2cap_chan_no_get_sndtimeo,
1680 };
1681
1682 int smp_register(struct hci_dev *hdev)
1683 {
1684         struct l2cap_chan *chan;
1685         struct crypto_blkcipher *tfm_aes;
1686
1687         BT_DBG("%s", hdev->name);
1688
1689         tfm_aes = crypto_alloc_blkcipher("ecb(aes)", 0, 0);
1690         if (IS_ERR(tfm_aes)) {
1691                 int err = PTR_ERR(tfm_aes);
1692                 BT_ERR("Unable to create crypto context");
1693                 return err;
1694         }
1695
1696         chan = l2cap_chan_create();
1697         if (!chan) {
1698                 crypto_free_blkcipher(tfm_aes);
1699                 return -ENOMEM;
1700         }
1701
1702         chan->data = tfm_aes;
1703
1704         l2cap_add_scid(chan, L2CAP_CID_SMP);
1705
1706         l2cap_chan_set_defaults(chan);
1707
1708         bacpy(&chan->src, &hdev->bdaddr);
1709         chan->src_type = BDADDR_LE_PUBLIC;
1710         chan->state = BT_LISTEN;
1711         chan->mode = L2CAP_MODE_BASIC;
1712         chan->imtu = L2CAP_DEFAULT_MTU;
1713         chan->ops = &smp_root_chan_ops;
1714
1715         /* Set correct nesting level for a parent/listening channel */
1716         atomic_set(&chan->nesting, L2CAP_NESTING_PARENT);
1717
1718         hdev->smp_data = chan;
1719
1720         return 0;
1721 }
1722
1723 void smp_unregister(struct hci_dev *hdev)
1724 {
1725         struct l2cap_chan *chan = hdev->smp_data;
1726         struct crypto_blkcipher *tfm_aes;
1727
1728         if (!chan)
1729                 return;
1730
1731         BT_DBG("%s chan %p", hdev->name, chan);
1732
1733         tfm_aes = chan->data;
1734         if (tfm_aes) {
1735                 chan->data = NULL;
1736                 crypto_free_blkcipher(tfm_aes);
1737         }
1738
1739         hdev->smp_data = NULL;
1740         l2cap_chan_put(chan);
1741 }