thermal: enable thermal subsystem with step_wise governor
[platform/kernel/linux-starfive.git] / crypto / algif_aead.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * algif_aead: User-space interface for AEAD algorithms
4  *
5  * Copyright (C) 2014, Stephan Mueller <smueller@chronox.de>
6  *
7  * This file provides the user-space API for AEAD ciphers.
8  *
9  * The following concept of the memory management is used:
10  *
11  * The kernel maintains two SGLs, the TX SGL and the RX SGL. The TX SGL is
12  * filled by user space with the data submitted via sendpage/sendmsg. Filling
13  * up the TX SGL does not cause a crypto operation -- the data will only be
14  * tracked by the kernel. Upon receipt of one recvmsg call, the caller must
15  * provide a buffer which is tracked with the RX SGL.
16  *
17  * During the processing of the recvmsg operation, the cipher request is
18  * allocated and prepared. As part of the recvmsg operation, the processed
19  * TX buffers are extracted from the TX SGL into a separate SGL.
20  *
21  * After the completion of the crypto operation, the RX SGL and the cipher
22  * request is released. The extracted TX SGL parts are released together with
23  * the RX SGL release.
24  */
25
26 #include <crypto/internal/aead.h>
27 #include <crypto/scatterwalk.h>
28 #include <crypto/if_alg.h>
29 #include <crypto/skcipher.h>
30 #include <crypto/null.h>
31 #include <linux/init.h>
32 #include <linux/list.h>
33 #include <linux/kernel.h>
34 #include <linux/mm.h>
35 #include <linux/module.h>
36 #include <linux/net.h>
37 #include <net/sock.h>
38
39 struct aead_tfm {
40         struct crypto_aead *aead;
41         struct crypto_sync_skcipher *null_tfm;
42 };
43
44 static inline bool aead_sufficient_data(struct sock *sk)
45 {
46         struct alg_sock *ask = alg_sk(sk);
47         struct sock *psk = ask->parent;
48         struct alg_sock *pask = alg_sk(psk);
49         struct af_alg_ctx *ctx = ask->private;
50         struct aead_tfm *aeadc = pask->private;
51         struct crypto_aead *tfm = aeadc->aead;
52         unsigned int as = crypto_aead_authsize(tfm);
53
54         /*
55          * The minimum amount of memory needed for an AEAD cipher is
56          * the AAD and in case of decryption the tag.
57          */
58         return ctx->used >= ctx->aead_assoclen + (ctx->op ? 0 : as);
59 }
60
61 static int aead_sendmsg(struct socket *sock, struct msghdr *msg, size_t size)
62 {
63         struct sock *sk = sock->sk;
64         struct alg_sock *ask = alg_sk(sk);
65         struct sock *psk = ask->parent;
66         struct alg_sock *pask = alg_sk(psk);
67         struct aead_tfm *aeadc = pask->private;
68         struct crypto_aead *tfm = aeadc->aead;
69         unsigned int ivsize = crypto_aead_ivsize(tfm);
70
71         return af_alg_sendmsg(sock, msg, size, ivsize);
72 }
73
74 static inline int aead_cipher_op(struct af_alg_ctx *ctx,
75                                  struct af_alg_async_req *areq)
76 {
77         switch (ctx->op) {
78         case ALG_OP_ENCRYPT:
79                 return crypto_aead_encrypt(&areq->cra_u.aead_req);
80         case ALG_OP_DECRYPT:
81                 return crypto_aead_decrypt(&areq->cra_u.aead_req);
82         default:
83                 return -EOPNOTSUPP;
84         }
85 }
86
87 static int crypto_aead_copy_sgl(struct crypto_sync_skcipher *null_tfm,
88                                 struct scatterlist *src,
89                                 struct scatterlist *dst, unsigned int len)
90 {
91         SYNC_SKCIPHER_REQUEST_ON_STACK(skreq, null_tfm);
92
93         skcipher_request_set_sync_tfm(skreq, null_tfm);
94         skcipher_request_set_callback(skreq, CRYPTO_TFM_REQ_MAY_SLEEP,
95                                       NULL, NULL);
96         skcipher_request_set_crypt(skreq, src, dst, len, NULL);
97
98         return crypto_skcipher_encrypt(skreq);
99 }
100
101 static int _aead_recvmsg(struct socket *sock, struct msghdr *msg,
102                          size_t ignored, int flags)
103 {
104         struct sock *sk = sock->sk;
105         struct alg_sock *ask = alg_sk(sk);
106         struct sock *psk = ask->parent;
107         struct alg_sock *pask = alg_sk(psk);
108         struct af_alg_ctx *ctx = ask->private;
109         struct aead_tfm *aeadc = pask->private;
110         struct crypto_aead *tfm = aeadc->aead;
111         struct crypto_sync_skcipher *null_tfm = aeadc->null_tfm;
112         unsigned int i, as = crypto_aead_authsize(tfm);
113         struct af_alg_async_req *areq;
114         struct af_alg_tsgl *tsgl, *tmp;
115         struct scatterlist *rsgl_src, *tsgl_src = NULL;
116         int err = 0;
117         size_t used = 0;                /* [in]  TX bufs to be en/decrypted */
118         size_t outlen = 0;              /* [out] RX bufs produced by kernel */
119         size_t usedpages = 0;           /* [in]  RX bufs to be used from user */
120         size_t processed = 0;           /* [in]  TX bufs to be consumed */
121
122         if (!ctx->init || ctx->more) {
123                 err = af_alg_wait_for_data(sk, flags, 0);
124                 if (err)
125                         return err;
126         }
127
128         /*
129          * Data length provided by caller via sendmsg/sendpage that has not
130          * yet been processed.
131          */
132         used = ctx->used;
133
134         /*
135          * Make sure sufficient data is present -- note, the same check is
136          * also present in sendmsg/sendpage. The checks in sendpage/sendmsg
137          * shall provide an information to the data sender that something is
138          * wrong, but they are irrelevant to maintain the kernel integrity.
139          * We need this check here too in case user space decides to not honor
140          * the error message in sendmsg/sendpage and still call recvmsg. This
141          * check here protects the kernel integrity.
142          */
143         if (!aead_sufficient_data(sk))
144                 return -EINVAL;
145
146         /*
147          * Calculate the minimum output buffer size holding the result of the
148          * cipher operation. When encrypting data, the receiving buffer is
149          * larger by the tag length compared to the input buffer as the
150          * encryption operation generates the tag. For decryption, the input
151          * buffer provides the tag which is consumed resulting in only the
152          * plaintext without a buffer for the tag returned to the caller.
153          */
154         if (ctx->op)
155                 outlen = used + as;
156         else
157                 outlen = used - as;
158
159         /*
160          * The cipher operation input data is reduced by the associated data
161          * length as this data is processed separately later on.
162          */
163         used -= ctx->aead_assoclen;
164
165         /* Allocate cipher request for current operation. */
166         areq = af_alg_alloc_areq(sk, sizeof(struct af_alg_async_req) +
167                                      crypto_aead_reqsize(tfm));
168         if (IS_ERR(areq))
169                 return PTR_ERR(areq);
170
171         /* convert iovecs of output buffers into RX SGL */
172         err = af_alg_get_rsgl(sk, msg, flags, areq, outlen, &usedpages);
173         if (err)
174                 goto free;
175
176         /*
177          * Ensure output buffer is sufficiently large. If the caller provides
178          * less buffer space, only use the relative required input size. This
179          * allows AIO operation where the caller sent all data to be processed
180          * and the AIO operation performs the operation on the different chunks
181          * of the input data.
182          */
183         if (usedpages < outlen) {
184                 size_t less = outlen - usedpages;
185
186                 if (used < less) {
187                         err = -EINVAL;
188                         goto free;
189                 }
190                 used -= less;
191                 outlen -= less;
192         }
193
194         processed = used + ctx->aead_assoclen;
195         list_for_each_entry_safe(tsgl, tmp, &ctx->tsgl_list, list) {
196                 for (i = 0; i < tsgl->cur; i++) {
197                         struct scatterlist *process_sg = tsgl->sg + i;
198
199                         if (!(process_sg->length) || !sg_page(process_sg))
200                                 continue;
201                         tsgl_src = process_sg;
202                         break;
203                 }
204                 if (tsgl_src)
205                         break;
206         }
207         if (processed && !tsgl_src) {
208                 err = -EFAULT;
209                 goto free;
210         }
211
212         /*
213          * Copy of AAD from source to destination
214          *
215          * The AAD is copied to the destination buffer without change. Even
216          * when user space uses an in-place cipher operation, the kernel
217          * will copy the data as it does not see whether such in-place operation
218          * is initiated.
219          *
220          * To ensure efficiency, the following implementation ensure that the
221          * ciphers are invoked to perform a crypto operation in-place. This
222          * is achieved by memory management specified as follows.
223          */
224
225         /* Use the RX SGL as source (and destination) for crypto op. */
226         rsgl_src = areq->first_rsgl.sgl.sg;
227
228         if (ctx->op == ALG_OP_ENCRYPT) {                
229                 /*
230                  * Encryption operation - The in-place cipher operation is
231                  * achieved by the following operation:
232                  *
233                  * TX SGL: AAD || PT
234                  *          |      |
235                  *          | copy |
236                  *          v      v
237                  * RX SGL: AAD || PT || Tag
238                  */
239                 err = crypto_aead_copy_sgl(null_tfm, tsgl_src,
240                                            areq->first_rsgl.sgl.sg, processed);
241                 if (err)
242                         goto free;
243                 af_alg_pull_tsgl(sk, processed, NULL, 0);
244         } else if (ctx->op == ALG_OP_DECRYPT) {         
245                 /*
246                  * Decryption operation - To achieve an in-place cipher
247                  * operation, the following  SGL structure is used:
248                  *
249                  * TX SGL: AAD || CT || Tag
250                  *          |      |     ^
251                  *          | copy |     | Create SGL link.
252                  *          v      v     |
253                  * RX SGL: AAD || CT ----+
254                  */
255
256                  /* Copy AAD || CT to RX SGL buffer for in-place operation. */
257                 err = crypto_aead_copy_sgl(null_tfm, tsgl_src,
258                                            areq->first_rsgl.sgl.sg, outlen);
259                 if (err)
260                         goto free;
261
262                 /* Create TX SGL for tag and chain it to RX SGL. */
263                 areq->tsgl_entries = af_alg_count_tsgl(sk, processed,
264                                                        processed - as);
265                 if (!areq->tsgl_entries)
266                         areq->tsgl_entries = 1;
267                 areq->tsgl = sock_kmalloc(sk, array_size(sizeof(*areq->tsgl),
268                                                          areq->tsgl_entries),
269                                           GFP_KERNEL);
270                 if (!areq->tsgl) {
271                         err = -ENOMEM;
272                         goto free;
273                 }
274                 sg_init_table(areq->tsgl, areq->tsgl_entries);
275
276                 /* Release TX SGL, except for tag data and reassign tag data. */
277                 af_alg_pull_tsgl(sk, processed, areq->tsgl, processed - as);
278
279                 /* chain the areq TX SGL holding the tag with RX SGL */
280                 if (usedpages) {
281                         /* RX SGL present */
282                         struct af_alg_sgl *sgl_prev = &areq->last_rsgl->sgl;
283
284                         sg_unmark_end(sgl_prev->sg + sgl_prev->npages - 1);
285                         sg_chain(sgl_prev->sg, sgl_prev->npages + 1,
286                                  areq->tsgl);
287                 } else
288                         /* no RX SGL present (e.g. authentication only) */
289                         rsgl_src = areq->tsgl;
290         }
291
292         /* Initialize the crypto operation */
293         aead_request_set_crypt(&areq->cra_u.aead_req, rsgl_src,
294                                areq->first_rsgl.sgl.sg, used, ctx->iv);
295         aead_request_set_ad(&areq->cra_u.aead_req, ctx->aead_assoclen);
296         aead_request_set_tfm(&areq->cra_u.aead_req, tfm);
297
298         if (msg->msg_iocb && !is_sync_kiocb(msg->msg_iocb)) {
299                 /* AIO operation */
300                 sock_hold(sk);
301                 areq->iocb = msg->msg_iocb;
302
303                 /* Remember output size that will be generated. */
304                 areq->outlen = outlen;
305
306                 aead_request_set_callback(&areq->cra_u.aead_req,
307                                           CRYPTO_TFM_REQ_MAY_SLEEP,
308                                           af_alg_async_cb, areq);
309                 err = aead_cipher_op(ctx, areq);
310  
311                 /* AIO operation in progress */
312                 if (err == -EINPROGRESS)
313                         return -EIOCBQUEUED;
314
315                 sock_put(sk);
316         } else {
317                 /* Synchronous operation */
318                 aead_request_set_callback(&areq->cra_u.aead_req,
319                                           CRYPTO_TFM_REQ_MAY_SLEEP |
320                                           CRYPTO_TFM_REQ_MAY_BACKLOG,
321                                           crypto_req_done, &ctx->wait);
322                 err = crypto_wait_req(aead_cipher_op(ctx, areq), &ctx->wait);
323         }
324
325
326 free:
327         af_alg_free_resources(areq);
328
329         return err ? err : outlen;
330 }
331
332 static int aead_recvmsg(struct socket *sock, struct msghdr *msg,
333                         size_t ignored, int flags)
334 {
335         struct sock *sk = sock->sk;
336         int ret = 0;
337
338         lock_sock(sk);
339         while (msg_data_left(msg)) {
340                 int err = _aead_recvmsg(sock, msg, ignored, flags);
341
342                 /*
343                  * This error covers -EIOCBQUEUED which implies that we can
344                  * only handle one AIO request. If the caller wants to have
345                  * multiple AIO requests in parallel, he must make multiple
346                  * separate AIO calls.
347                  *
348                  * Also return the error if no data has been processed so far.
349                  */
350                 if (err <= 0) {
351                         if (err == -EIOCBQUEUED || err == -EBADMSG || !ret)
352                                 ret = err;
353                         goto out;
354                 }
355
356                 ret += err;
357         }
358
359 out:
360         af_alg_wmem_wakeup(sk);
361         release_sock(sk);
362         return ret;
363 }
364
365 static struct proto_ops algif_aead_ops = {
366         .family         =       PF_ALG,
367
368         .connect        =       sock_no_connect,
369         .socketpair     =       sock_no_socketpair,
370         .getname        =       sock_no_getname,
371         .ioctl          =       sock_no_ioctl,
372         .listen         =       sock_no_listen,
373         .shutdown       =       sock_no_shutdown,
374         .mmap           =       sock_no_mmap,
375         .bind           =       sock_no_bind,
376         .accept         =       sock_no_accept,
377
378         .release        =       af_alg_release,
379         .sendmsg        =       aead_sendmsg,
380         .sendpage       =       af_alg_sendpage,
381         .recvmsg        =       aead_recvmsg,
382         .poll           =       af_alg_poll,
383 };
384
385 static int aead_check_key(struct socket *sock)
386 {
387         int err = 0;
388         struct sock *psk;
389         struct alg_sock *pask;
390         struct aead_tfm *tfm;
391         struct sock *sk = sock->sk;
392         struct alg_sock *ask = alg_sk(sk);
393
394         lock_sock(sk);
395         if (!atomic_read(&ask->nokey_refcnt))
396                 goto unlock_child;
397
398         psk = ask->parent;
399         pask = alg_sk(ask->parent);
400         tfm = pask->private;
401
402         err = -ENOKEY;
403         lock_sock_nested(psk, SINGLE_DEPTH_NESTING);
404         if (crypto_aead_get_flags(tfm->aead) & CRYPTO_TFM_NEED_KEY)
405                 goto unlock;
406
407         atomic_dec(&pask->nokey_refcnt);
408         atomic_set(&ask->nokey_refcnt, 0);
409
410         err = 0;
411
412 unlock:
413         release_sock(psk);
414 unlock_child:
415         release_sock(sk);
416
417         return err;
418 }
419
420 static int aead_sendmsg_nokey(struct socket *sock, struct msghdr *msg,
421                                   size_t size)
422 {
423         int err;
424
425         err = aead_check_key(sock);
426         if (err)
427                 return err;
428
429         return aead_sendmsg(sock, msg, size);
430 }
431
432 static ssize_t aead_sendpage_nokey(struct socket *sock, struct page *page,
433                                        int offset, size_t size, int flags)
434 {
435         int err;
436
437         err = aead_check_key(sock);
438         if (err)
439                 return err;
440
441         return af_alg_sendpage(sock, page, offset, size, flags);
442 }
443
444 static int aead_recvmsg_nokey(struct socket *sock, struct msghdr *msg,
445                                   size_t ignored, int flags)
446 {
447         int err;
448
449         err = aead_check_key(sock);
450         if (err)
451                 return err;
452
453         return aead_recvmsg(sock, msg, ignored, flags);
454 }
455
456 static struct proto_ops algif_aead_ops_nokey = {
457         .family         =       PF_ALG,
458
459         .connect        =       sock_no_connect,
460         .socketpair     =       sock_no_socketpair,
461         .getname        =       sock_no_getname,
462         .ioctl          =       sock_no_ioctl,
463         .listen         =       sock_no_listen,
464         .shutdown       =       sock_no_shutdown,
465         .mmap           =       sock_no_mmap,
466         .bind           =       sock_no_bind,
467         .accept         =       sock_no_accept,
468
469         .release        =       af_alg_release,
470         .sendmsg        =       aead_sendmsg_nokey,
471         .sendpage       =       aead_sendpage_nokey,
472         .recvmsg        =       aead_recvmsg_nokey,
473         .poll           =       af_alg_poll,
474 };
475
476 static void *aead_bind(const char *name, u32 type, u32 mask)
477 {
478         struct aead_tfm *tfm;
479         struct crypto_aead *aead;
480         struct crypto_sync_skcipher *null_tfm;
481
482         tfm = kzalloc(sizeof(*tfm), GFP_KERNEL);
483         if (!tfm)
484                 return ERR_PTR(-ENOMEM);
485
486         aead = crypto_alloc_aead(name, type, mask);
487         if (IS_ERR(aead)) {
488                 kfree(tfm);
489                 return ERR_CAST(aead);
490         }
491
492         null_tfm = crypto_get_default_null_skcipher();
493         if (IS_ERR(null_tfm)) {
494                 crypto_free_aead(aead);
495                 kfree(tfm);
496                 return ERR_CAST(null_tfm);
497         }
498
499         tfm->aead = aead;
500         tfm->null_tfm = null_tfm;
501
502         return tfm;
503 }
504
505 static void aead_release(void *private)
506 {
507         struct aead_tfm *tfm = private;
508
509         crypto_free_aead(tfm->aead);
510         crypto_put_default_null_skcipher();
511         kfree(tfm);
512 }
513
514 static int aead_setauthsize(void *private, unsigned int authsize)
515 {
516         struct aead_tfm *tfm = private;
517
518         return crypto_aead_setauthsize(tfm->aead, authsize);
519 }
520
521 static int aead_setkey(void *private, const u8 *key, unsigned int keylen)
522 {
523         struct aead_tfm *tfm = private;
524
525         return crypto_aead_setkey(tfm->aead, key, keylen);
526 }
527
528 static void aead_sock_destruct(struct sock *sk)
529 {
530         struct alg_sock *ask = alg_sk(sk);
531         struct af_alg_ctx *ctx = ask->private;
532         struct sock *psk = ask->parent;
533         struct alg_sock *pask = alg_sk(psk);
534         struct aead_tfm *aeadc = pask->private;
535         struct crypto_aead *tfm = aeadc->aead;
536         unsigned int ivlen = crypto_aead_ivsize(tfm);
537
538         af_alg_pull_tsgl(sk, ctx->used, NULL, 0);
539         sock_kzfree_s(sk, ctx->iv, ivlen);
540         sock_kfree_s(sk, ctx, ctx->len);
541         af_alg_release_parent(sk);
542 }
543
544 static int aead_accept_parent_nokey(void *private, struct sock *sk)
545 {
546         struct af_alg_ctx *ctx;
547         struct alg_sock *ask = alg_sk(sk);
548         struct aead_tfm *tfm = private;
549         struct crypto_aead *aead = tfm->aead;
550         unsigned int len = sizeof(*ctx);
551         unsigned int ivlen = crypto_aead_ivsize(aead);
552
553         ctx = sock_kmalloc(sk, len, GFP_KERNEL);
554         if (!ctx)
555                 return -ENOMEM;
556         memset(ctx, 0, len);
557
558         ctx->iv = sock_kmalloc(sk, ivlen, GFP_KERNEL);
559         if (!ctx->iv) {
560                 sock_kfree_s(sk, ctx, len);
561                 return -ENOMEM;
562         }
563         memset(ctx->iv, 0, ivlen);
564
565         INIT_LIST_HEAD(&ctx->tsgl_list);
566         ctx->len = len;
567         crypto_init_wait(&ctx->wait);
568
569         ask->private = ctx;
570
571         sk->sk_destruct = aead_sock_destruct;
572
573         return 0;
574 }
575
576 static int aead_accept_parent(void *private, struct sock *sk)
577 {
578         struct aead_tfm *tfm = private;
579
580         if (crypto_aead_get_flags(tfm->aead) & CRYPTO_TFM_NEED_KEY)
581                 return -ENOKEY;
582
583         return aead_accept_parent_nokey(private, sk);
584 }
585
586 static const struct af_alg_type algif_type_aead = {
587         .bind           =       aead_bind,
588         .release        =       aead_release,
589         .setkey         =       aead_setkey,
590         .setauthsize    =       aead_setauthsize,
591         .accept         =       aead_accept_parent,
592         .accept_nokey   =       aead_accept_parent_nokey,
593         .ops            =       &algif_aead_ops,
594         .ops_nokey      =       &algif_aead_ops_nokey,
595         .name           =       "aead",
596         .owner          =       THIS_MODULE
597 };
598
599 static int __init algif_aead_init(void)
600 {
601         return af_alg_register_type(&algif_type_aead);
602 }
603
604 static void __exit algif_aead_exit(void)
605 {
606         int err = af_alg_unregister_type(&algif_type_aead);
607         BUG_ON(err);
608 }
609
610 module_init(algif_aead_init);
611 module_exit(algif_aead_exit);
612 MODULE_LICENSE("GPL");
613 MODULE_AUTHOR("Stephan Mueller <smueller@chronox.de>");
614 MODULE_DESCRIPTION("AEAD kernel crypto API user space interface");