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