]> git.karo-electronics.de Git - linux-beck.git/blob - crypto/algif_aead.c
crypto: algif_aead - Include crypto/aead.h
[linux-beck.git] / crypto / algif_aead.c
1 /*
2  * algif_aead: User-space interface for AEAD algorithms
3  *
4  * Copyright (C) 2014, Stephan Mueller <smueller@chronox.de>
5  *
6  * This file provides the user-space API for AEAD ciphers.
7  *
8  * This file is derived from algif_skcipher.c.
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 2 of the License, or (at your option)
13  * any later version.
14  */
15
16 #include <crypto/aead.h>
17 #include <crypto/scatterwalk.h>
18 #include <crypto/if_alg.h>
19 #include <linux/init.h>
20 #include <linux/list.h>
21 #include <linux/kernel.h>
22 #include <linux/mm.h>
23 #include <linux/module.h>
24 #include <linux/net.h>
25 #include <net/sock.h>
26
27 struct aead_sg_list {
28         unsigned int cur;
29         struct scatterlist sg[ALG_MAX_PAGES];
30 };
31
32 struct aead_ctx {
33         struct aead_sg_list tsgl;
34         /*
35          * RSGL_MAX_ENTRIES is an artificial limit where user space at maximum
36          * can cause the kernel to allocate RSGL_MAX_ENTRIES * ALG_MAX_PAGES
37          * bytes
38          */
39 #define RSGL_MAX_ENTRIES ALG_MAX_PAGES
40         struct af_alg_sgl rsgl[RSGL_MAX_ENTRIES];
41
42         void *iv;
43
44         struct af_alg_completion completion;
45
46         unsigned long used;
47
48         unsigned int len;
49         bool more;
50         bool merge;
51         bool enc;
52
53         size_t aead_assoclen;
54         struct aead_request aead_req;
55 };
56
57 static inline int aead_sndbuf(struct sock *sk)
58 {
59         struct alg_sock *ask = alg_sk(sk);
60         struct aead_ctx *ctx = ask->private;
61
62         return max_t(int, max_t(int, sk->sk_sndbuf & PAGE_MASK, PAGE_SIZE) -
63                           ctx->used, 0);
64 }
65
66 static inline bool aead_writable(struct sock *sk)
67 {
68         return PAGE_SIZE <= aead_sndbuf(sk);
69 }
70
71 static inline bool aead_sufficient_data(struct aead_ctx *ctx)
72 {
73         unsigned as = crypto_aead_authsize(crypto_aead_reqtfm(&ctx->aead_req));
74
75         return (ctx->used >= (ctx->aead_assoclen + (ctx->enc ? 0 : as)));
76 }
77
78 static void aead_put_sgl(struct sock *sk)
79 {
80         struct alg_sock *ask = alg_sk(sk);
81         struct aead_ctx *ctx = ask->private;
82         struct aead_sg_list *sgl = &ctx->tsgl;
83         struct scatterlist *sg = sgl->sg;
84         unsigned int i;
85
86         for (i = 0; i < sgl->cur; i++) {
87                 if (!sg_page(sg + i))
88                         continue;
89
90                 put_page(sg_page(sg + i));
91                 sg_assign_page(sg + i, NULL);
92         }
93         sgl->cur = 0;
94         ctx->used = 0;
95         ctx->more = 0;
96         ctx->merge = 0;
97 }
98
99 static void aead_wmem_wakeup(struct sock *sk)
100 {
101         struct socket_wq *wq;
102
103         if (!aead_writable(sk))
104                 return;
105
106         rcu_read_lock();
107         wq = rcu_dereference(sk->sk_wq);
108         if (wq_has_sleeper(wq))
109                 wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
110                                                            POLLRDNORM |
111                                                            POLLRDBAND);
112         sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
113         rcu_read_unlock();
114 }
115
116 static int aead_wait_for_data(struct sock *sk, unsigned flags)
117 {
118         struct alg_sock *ask = alg_sk(sk);
119         struct aead_ctx *ctx = ask->private;
120         long timeout;
121         DEFINE_WAIT(wait);
122         int err = -ERESTARTSYS;
123
124         if (flags & MSG_DONTWAIT)
125                 return -EAGAIN;
126
127         set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
128
129         for (;;) {
130                 if (signal_pending(current))
131                         break;
132                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
133                 timeout = MAX_SCHEDULE_TIMEOUT;
134                 if (sk_wait_event(sk, &timeout, !ctx->more)) {
135                         err = 0;
136                         break;
137                 }
138         }
139         finish_wait(sk_sleep(sk), &wait);
140
141         clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
142
143         return err;
144 }
145
146 static void aead_data_wakeup(struct sock *sk)
147 {
148         struct alg_sock *ask = alg_sk(sk);
149         struct aead_ctx *ctx = ask->private;
150         struct socket_wq *wq;
151
152         if (ctx->more)
153                 return;
154         if (!ctx->used)
155                 return;
156
157         rcu_read_lock();
158         wq = rcu_dereference(sk->sk_wq);
159         if (wq_has_sleeper(wq))
160                 wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
161                                                            POLLRDNORM |
162                                                            POLLRDBAND);
163         sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
164         rcu_read_unlock();
165 }
166
167 static int aead_sendmsg(struct socket *sock, struct msghdr *msg, size_t size)
168 {
169         struct sock *sk = sock->sk;
170         struct alg_sock *ask = alg_sk(sk);
171         struct aead_ctx *ctx = ask->private;
172         unsigned ivsize =
173                 crypto_aead_ivsize(crypto_aead_reqtfm(&ctx->aead_req));
174         struct aead_sg_list *sgl = &ctx->tsgl;
175         struct af_alg_control con = {};
176         long copied = 0;
177         bool enc = 0;
178         bool init = 0;
179         int err = -EINVAL;
180
181         if (msg->msg_controllen) {
182                 err = af_alg_cmsg_send(msg, &con);
183                 if (err)
184                         return err;
185
186                 init = 1;
187                 switch (con.op) {
188                 case ALG_OP_ENCRYPT:
189                         enc = 1;
190                         break;
191                 case ALG_OP_DECRYPT:
192                         enc = 0;
193                         break;
194                 default:
195                         return -EINVAL;
196                 }
197
198                 if (con.iv && con.iv->ivlen != ivsize)
199                         return -EINVAL;
200         }
201
202         lock_sock(sk);
203         if (!ctx->more && ctx->used)
204                 goto unlock;
205
206         if (init) {
207                 ctx->enc = enc;
208                 if (con.iv)
209                         memcpy(ctx->iv, con.iv->iv, ivsize);
210
211                 ctx->aead_assoclen = con.aead_assoclen;
212         }
213
214         while (size) {
215                 unsigned long len = size;
216                 struct scatterlist *sg = NULL;
217
218                 /* use the existing memory in an allocated page */
219                 if (ctx->merge) {
220                         sg = sgl->sg + sgl->cur - 1;
221                         len = min_t(unsigned long, len,
222                                     PAGE_SIZE - sg->offset - sg->length);
223                         err = memcpy_from_msg(page_address(sg_page(sg)) +
224                                               sg->offset + sg->length,
225                                               msg, len);
226                         if (err)
227                                 goto unlock;
228
229                         sg->length += len;
230                         ctx->merge = (sg->offset + sg->length) &
231                                      (PAGE_SIZE - 1);
232
233                         ctx->used += len;
234                         copied += len;
235                         size -= len;
236                         continue;
237                 }
238
239                 if (!aead_writable(sk)) {
240                         /* user space sent too much data */
241                         aead_put_sgl(sk);
242                         err = -EMSGSIZE;
243                         goto unlock;
244                 }
245
246                 /* allocate a new page */
247                 len = min_t(unsigned long, size, aead_sndbuf(sk));
248                 while (len) {
249                         int plen = 0;
250
251                         if (sgl->cur >= ALG_MAX_PAGES) {
252                                 aead_put_sgl(sk);
253                                 err = -E2BIG;
254                                 goto unlock;
255                         }
256
257                         sg = sgl->sg + sgl->cur;
258                         plen = min_t(int, len, PAGE_SIZE);
259
260                         sg_assign_page(sg, alloc_page(GFP_KERNEL));
261                         err = -ENOMEM;
262                         if (!sg_page(sg))
263                                 goto unlock;
264
265                         err = memcpy_from_msg(page_address(sg_page(sg)),
266                                               msg, plen);
267                         if (err) {
268                                 __free_page(sg_page(sg));
269                                 sg_assign_page(sg, NULL);
270                                 goto unlock;
271                         }
272
273                         sg->offset = 0;
274                         sg->length = plen;
275                         len -= plen;
276                         ctx->used += plen;
277                         copied += plen;
278                         sgl->cur++;
279                         size -= plen;
280                         ctx->merge = plen & (PAGE_SIZE - 1);
281                 }
282         }
283
284         err = 0;
285
286         ctx->more = msg->msg_flags & MSG_MORE;
287         if (!ctx->more && !aead_sufficient_data(ctx)) {
288                 aead_put_sgl(sk);
289                 err = -EMSGSIZE;
290         }
291
292 unlock:
293         aead_data_wakeup(sk);
294         release_sock(sk);
295
296         return err ?: copied;
297 }
298
299 static ssize_t aead_sendpage(struct socket *sock, struct page *page,
300                              int offset, size_t size, int flags)
301 {
302         struct sock *sk = sock->sk;
303         struct alg_sock *ask = alg_sk(sk);
304         struct aead_ctx *ctx = ask->private;
305         struct aead_sg_list *sgl = &ctx->tsgl;
306         int err = -EINVAL;
307
308         if (flags & MSG_SENDPAGE_NOTLAST)
309                 flags |= MSG_MORE;
310
311         if (sgl->cur >= ALG_MAX_PAGES)
312                 return -E2BIG;
313
314         lock_sock(sk);
315         if (!ctx->more && ctx->used)
316                 goto unlock;
317
318         if (!size)
319                 goto done;
320
321         if (!aead_writable(sk)) {
322                 /* user space sent too much data */
323                 aead_put_sgl(sk);
324                 err = -EMSGSIZE;
325                 goto unlock;
326         }
327
328         ctx->merge = 0;
329
330         get_page(page);
331         sg_set_page(sgl->sg + sgl->cur, page, size, offset);
332         sgl->cur++;
333         ctx->used += size;
334
335         err = 0;
336
337 done:
338         ctx->more = flags & MSG_MORE;
339         if (!ctx->more && !aead_sufficient_data(ctx)) {
340                 aead_put_sgl(sk);
341                 err = -EMSGSIZE;
342         }
343
344 unlock:
345         aead_data_wakeup(sk);
346         release_sock(sk);
347
348         return err ?: size;
349 }
350
351 static int aead_recvmsg(struct socket *sock, struct msghdr *msg, size_t ignored, int flags)
352 {
353         struct sock *sk = sock->sk;
354         struct alg_sock *ask = alg_sk(sk);
355         struct aead_ctx *ctx = ask->private;
356         unsigned bs = crypto_aead_blocksize(crypto_aead_reqtfm(&ctx->aead_req));
357         unsigned as = crypto_aead_authsize(crypto_aead_reqtfm(&ctx->aead_req));
358         struct aead_sg_list *sgl = &ctx->tsgl;
359         struct scatterlist *sg = NULL;
360         struct scatterlist assoc[ALG_MAX_PAGES];
361         size_t assoclen = 0;
362         unsigned int i = 0;
363         int err = -EINVAL;
364         unsigned long used = 0;
365         size_t outlen = 0;
366         size_t usedpages = 0;
367         unsigned int cnt = 0;
368
369         /* Limit number of IOV blocks to be accessed below */
370         if (msg->msg_iter.nr_segs > RSGL_MAX_ENTRIES)
371                 return -ENOMSG;
372
373         lock_sock(sk);
374
375         /*
376          * AEAD memory structure: For encryption, the tag is appended to the
377          * ciphertext which implies that the memory allocated for the ciphertext
378          * must be increased by the tag length. For decryption, the tag
379          * is expected to be concatenated to the ciphertext. The plaintext
380          * therefore has a memory size of the ciphertext minus the tag length.
381          *
382          * The memory structure for cipher operation has the following
383          * structure:
384          *      AEAD encryption input:  assoc data || plaintext
385          *      AEAD encryption output: cipherntext || auth tag
386          *      AEAD decryption input:  assoc data || ciphertext || auth tag
387          *      AEAD decryption output: plaintext
388          */
389
390         if (ctx->more) {
391                 err = aead_wait_for_data(sk, flags);
392                 if (err)
393                         goto unlock;
394         }
395
396         used = ctx->used;
397
398         /*
399          * Make sure sufficient data is present -- note, the same check is
400          * is also present in sendmsg/sendpage. The checks in sendpage/sendmsg
401          * shall provide an information to the data sender that something is
402          * wrong, but they are irrelevant to maintain the kernel integrity.
403          * We need this check here too in case user space decides to not honor
404          * the error message in sendmsg/sendpage and still call recvmsg. This
405          * check here protects the kernel integrity.
406          */
407         if (!aead_sufficient_data(ctx))
408                 goto unlock;
409
410         /*
411          * The cipher operation input data is reduced by the associated data
412          * length as this data is processed separately later on.
413          */
414         used -= ctx->aead_assoclen;
415
416         if (ctx->enc) {
417                 /* round up output buffer to multiple of block size */
418                 outlen = ((used + bs - 1) / bs * bs);
419                 /* add the size needed for the auth tag to be created */
420                 outlen += as;
421         } else {
422                 /* output data size is input without the authentication tag */
423                 outlen = used - as;
424                 /* round up output buffer to multiple of block size */
425                 outlen = ((outlen + bs - 1) / bs * bs);
426         }
427
428         /* convert iovecs of output buffers into scatterlists */
429         while (iov_iter_count(&msg->msg_iter)) {
430                 size_t seglen = min_t(size_t, iov_iter_count(&msg->msg_iter),
431                                       (outlen - usedpages));
432
433                 /* make one iovec available as scatterlist */
434                 err = af_alg_make_sg(&ctx->rsgl[cnt], &msg->msg_iter,
435                                      seglen);
436                 if (err < 0)
437                         goto unlock;
438                 usedpages += err;
439                 /* chain the new scatterlist with initial list */
440                 if (cnt)
441                         scatterwalk_crypto_chain(ctx->rsgl[0].sg,
442                                         ctx->rsgl[cnt].sg, 1,
443                                         sg_nents(ctx->rsgl[cnt-1].sg));
444                 /* we do not need more iovecs as we have sufficient memory */
445                 if (outlen <= usedpages)
446                         break;
447                 iov_iter_advance(&msg->msg_iter, err);
448                 cnt++;
449         }
450
451         err = -EINVAL;
452         /* ensure output buffer is sufficiently large */
453         if (usedpages < outlen)
454                 goto unlock;
455
456         sg_init_table(assoc, ALG_MAX_PAGES);
457         assoclen = ctx->aead_assoclen;
458         /*
459          * Split scatterlist into two: first part becomes AD, second part
460          * is plaintext / ciphertext. The first part is assigned to assoc
461          * scatterlist. When this loop finishes, sg points to the start of the
462          * plaintext / ciphertext.
463          */
464         for (i = 0; i < ctx->tsgl.cur; i++) {
465                 sg = sgl->sg + i;
466                 if (sg->length <= assoclen) {
467                         /* AD is larger than one page */
468                         sg_set_page(assoc + i, sg_page(sg),
469                                     sg->length, sg->offset);
470                         assoclen -= sg->length;
471                         if (i >= ctx->tsgl.cur)
472                                 goto unlock;
473                 } else if (!assoclen) {
474                         /* current page is to start of plaintext / ciphertext */
475                         if (i)
476                                 /* AD terminates at page boundary */
477                                 sg_mark_end(assoc + i - 1);
478                         else
479                                 /* AD size is zero */
480                                 sg_mark_end(assoc);
481                         break;
482                 } else {
483                         /* AD does not terminate at page boundary */
484                         sg_set_page(assoc + i, sg_page(sg),
485                                     assoclen, sg->offset);
486                         sg_mark_end(assoc + i);
487                         /* plaintext / ciphertext starts after AD */
488                         sg->length -= assoclen;
489                         sg->offset += assoclen;
490                         break;
491                 }
492         }
493
494         aead_request_set_assoc(&ctx->aead_req, assoc, ctx->aead_assoclen);
495         aead_request_set_crypt(&ctx->aead_req, sg, ctx->rsgl[0].sg, used,
496                                ctx->iv);
497
498         err = af_alg_wait_for_completion(ctx->enc ?
499                                          crypto_aead_encrypt(&ctx->aead_req) :
500                                          crypto_aead_decrypt(&ctx->aead_req),
501                                          &ctx->completion);
502
503         if (err) {
504                 /* EBADMSG implies a valid cipher operation took place */
505                 if (err == -EBADMSG)
506                         aead_put_sgl(sk);
507                 goto unlock;
508         }
509
510         aead_put_sgl(sk);
511
512         err = 0;
513
514 unlock:
515         for (i = 0; i < cnt; i++)
516                 af_alg_free_sg(&ctx->rsgl[i]);
517
518         aead_wmem_wakeup(sk);
519         release_sock(sk);
520
521         return err ? err : outlen;
522 }
523
524 static unsigned int aead_poll(struct file *file, struct socket *sock,
525                               poll_table *wait)
526 {
527         struct sock *sk = sock->sk;
528         struct alg_sock *ask = alg_sk(sk);
529         struct aead_ctx *ctx = ask->private;
530         unsigned int mask;
531
532         sock_poll_wait(file, sk_sleep(sk), wait);
533         mask = 0;
534
535         if (!ctx->more)
536                 mask |= POLLIN | POLLRDNORM;
537
538         if (aead_writable(sk))
539                 mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
540
541         return mask;
542 }
543
544 static struct proto_ops algif_aead_ops = {
545         .family         =       PF_ALG,
546
547         .connect        =       sock_no_connect,
548         .socketpair     =       sock_no_socketpair,
549         .getname        =       sock_no_getname,
550         .ioctl          =       sock_no_ioctl,
551         .listen         =       sock_no_listen,
552         .shutdown       =       sock_no_shutdown,
553         .getsockopt     =       sock_no_getsockopt,
554         .mmap           =       sock_no_mmap,
555         .bind           =       sock_no_bind,
556         .accept         =       sock_no_accept,
557         .setsockopt     =       sock_no_setsockopt,
558
559         .release        =       af_alg_release,
560         .sendmsg        =       aead_sendmsg,
561         .sendpage       =       aead_sendpage,
562         .recvmsg        =       aead_recvmsg,
563         .poll           =       aead_poll,
564 };
565
566 static void *aead_bind(const char *name, u32 type, u32 mask)
567 {
568         return crypto_alloc_aead(name, type, mask);
569 }
570
571 static void aead_release(void *private)
572 {
573         crypto_free_aead(private);
574 }
575
576 static int aead_setauthsize(void *private, unsigned int authsize)
577 {
578         return crypto_aead_setauthsize(private, authsize);
579 }
580
581 static int aead_setkey(void *private, const u8 *key, unsigned int keylen)
582 {
583         return crypto_aead_setkey(private, key, keylen);
584 }
585
586 static void aead_sock_destruct(struct sock *sk)
587 {
588         struct alg_sock *ask = alg_sk(sk);
589         struct aead_ctx *ctx = ask->private;
590         unsigned int ivlen = crypto_aead_ivsize(
591                                 crypto_aead_reqtfm(&ctx->aead_req));
592
593         aead_put_sgl(sk);
594         sock_kzfree_s(sk, ctx->iv, ivlen);
595         sock_kfree_s(sk, ctx, ctx->len);
596         af_alg_release_parent(sk);
597 }
598
599 static int aead_accept_parent(void *private, struct sock *sk)
600 {
601         struct aead_ctx *ctx;
602         struct alg_sock *ask = alg_sk(sk);
603         unsigned int len = sizeof(*ctx) + crypto_aead_reqsize(private);
604         unsigned int ivlen = crypto_aead_ivsize(private);
605
606         ctx = sock_kmalloc(sk, len, GFP_KERNEL);
607         if (!ctx)
608                 return -ENOMEM;
609         memset(ctx, 0, len);
610
611         ctx->iv = sock_kmalloc(sk, ivlen, GFP_KERNEL);
612         if (!ctx->iv) {
613                 sock_kfree_s(sk, ctx, len);
614                 return -ENOMEM;
615         }
616         memset(ctx->iv, 0, ivlen);
617
618         ctx->len = len;
619         ctx->used = 0;
620         ctx->more = 0;
621         ctx->merge = 0;
622         ctx->enc = 0;
623         ctx->tsgl.cur = 0;
624         ctx->aead_assoclen = 0;
625         af_alg_init_completion(&ctx->completion);
626         sg_init_table(ctx->tsgl.sg, ALG_MAX_PAGES);
627
628         ask->private = ctx;
629
630         aead_request_set_tfm(&ctx->aead_req, private);
631         aead_request_set_callback(&ctx->aead_req, CRYPTO_TFM_REQ_MAY_BACKLOG,
632                                   af_alg_complete, &ctx->completion);
633
634         sk->sk_destruct = aead_sock_destruct;
635
636         return 0;
637 }
638
639 static const struct af_alg_type algif_type_aead = {
640         .bind           =       aead_bind,
641         .release        =       aead_release,
642         .setkey         =       aead_setkey,
643         .setauthsize    =       aead_setauthsize,
644         .accept         =       aead_accept_parent,
645         .ops            =       &algif_aead_ops,
646         .name           =       "aead",
647         .owner          =       THIS_MODULE
648 };
649
650 static int __init algif_aead_init(void)
651 {
652         return af_alg_register_type(&algif_type_aead);
653 }
654
655 static void __exit algif_aead_exit(void)
656 {
657         int err = af_alg_unregister_type(&algif_type_aead);
658         BUG_ON(err);
659 }
660
661 module_init(algif_aead_init);
662 module_exit(algif_aead_exit);
663 MODULE_LICENSE("GPL");
664 MODULE_AUTHOR("Stephan Mueller <smueller@chronox.de>");
665 MODULE_DESCRIPTION("AEAD kernel crypto API user space interface");