xref: /linux/crypto/af_alg.c (revision e2683c8868d03382da7e1ce8453b543a043066d1)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * af_alg: User-space algorithm interface
4  *
5  * This file provides the user-space API for algorithms.
6  *
7  * Copyright (c) 2010 Herbert Xu <herbert@gondor.apana.org.au>
8  */
9 
10 #include <linux/atomic.h>
11 #include <crypto/if_alg.h>
12 #include <linux/crypto.h>
13 #include <linux/init.h>
14 #include <linux/kernel.h>
15 #include <linux/key.h>
16 #include <linux/key-type.h>
17 #include <linux/list.h>
18 #include <linux/module.h>
19 #include <linux/net.h>
20 #include <linux/rwsem.h>
21 #include <linux/sched.h>
22 #include <linux/sched/signal.h>
23 #include <linux/security.h>
24 #include <linux/string.h>
25 #include <keys/user-type.h>
26 #include <keys/trusted-type.h>
27 #include <keys/encrypted-type.h>
28 
29 struct alg_type_list {
30 	const struct af_alg_type *type;
31 	struct list_head list;
32 };
33 
34 static struct proto alg_proto = {
35 	.name			= "ALG",
36 	.owner			= THIS_MODULE,
37 	.obj_size		= sizeof(struct alg_sock),
38 };
39 
40 static LIST_HEAD(alg_types);
41 static DECLARE_RWSEM(alg_types_sem);
42 
43 static const struct af_alg_type *alg_get_type(const char *name)
44 {
45 	const struct af_alg_type *type = ERR_PTR(-ENOENT);
46 	struct alg_type_list *node;
47 
48 	down_read(&alg_types_sem);
49 	list_for_each_entry(node, &alg_types, list) {
50 		if (strcmp(node->type->name, name))
51 			continue;
52 
53 		if (try_module_get(node->type->owner))
54 			type = node->type;
55 		break;
56 	}
57 	up_read(&alg_types_sem);
58 
59 	return type;
60 }
61 
62 int af_alg_register_type(const struct af_alg_type *type)
63 {
64 	struct alg_type_list *node;
65 	int err = -EEXIST;
66 
67 	down_write(&alg_types_sem);
68 	list_for_each_entry(node, &alg_types, list) {
69 		if (!strcmp(node->type->name, type->name))
70 			goto unlock;
71 	}
72 
73 	node = kmalloc_obj(*node);
74 	err = -ENOMEM;
75 	if (!node)
76 		goto unlock;
77 
78 	type->ops->owner = THIS_MODULE;
79 	if (type->ops_nokey)
80 		type->ops_nokey->owner = THIS_MODULE;
81 	node->type = type;
82 	list_add(&node->list, &alg_types);
83 	err = 0;
84 
85 unlock:
86 	up_write(&alg_types_sem);
87 
88 	return err;
89 }
90 EXPORT_SYMBOL_GPL(af_alg_register_type);
91 
92 int af_alg_unregister_type(const struct af_alg_type *type)
93 {
94 	struct alg_type_list *node;
95 	int err = -ENOENT;
96 
97 	down_write(&alg_types_sem);
98 	list_for_each_entry(node, &alg_types, list) {
99 		if (strcmp(node->type->name, type->name))
100 			continue;
101 
102 		list_del(&node->list);
103 		kfree(node);
104 		err = 0;
105 		break;
106 	}
107 	up_write(&alg_types_sem);
108 
109 	return err;
110 }
111 EXPORT_SYMBOL_GPL(af_alg_unregister_type);
112 
113 static void alg_do_release(const struct af_alg_type *type, void *private)
114 {
115 	if (!type)
116 		return;
117 
118 	type->release(private);
119 	module_put(type->owner);
120 }
121 
122 int af_alg_release(struct socket *sock)
123 {
124 	if (sock->sk) {
125 		sock_put(sock->sk);
126 		sock->sk = NULL;
127 	}
128 	return 0;
129 }
130 EXPORT_SYMBOL_GPL(af_alg_release);
131 
132 void af_alg_release_parent(struct sock *sk)
133 {
134 	struct alg_sock *ask = alg_sk(sk);
135 	unsigned int nokey = atomic_read(&ask->nokey_refcnt);
136 
137 	sk = ask->parent;
138 	ask = alg_sk(sk);
139 
140 	if (nokey)
141 		atomic_dec(&ask->nokey_refcnt);
142 
143 	if (atomic_dec_and_test(&ask->refcnt))
144 		sock_put(sk);
145 }
146 EXPORT_SYMBOL_GPL(af_alg_release_parent);
147 
148 static int alg_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int addr_len)
149 {
150 	const u32 allowed = CRYPTO_ALG_KERN_DRIVER_ONLY;
151 	struct sock *sk = sock->sk;
152 	struct alg_sock *ask = alg_sk(sk);
153 	struct sockaddr_alg_new *sa = (void *)uaddr;
154 	const struct af_alg_type *type;
155 	void *private;
156 	int err;
157 
158 	if (sock->state == SS_CONNECTED)
159 		return -EINVAL;
160 
161 	BUILD_BUG_ON(offsetof(struct sockaddr_alg_new, salg_name) !=
162 		     offsetof(struct sockaddr_alg, salg_name));
163 	BUILD_BUG_ON(offsetof(struct sockaddr_alg, salg_name) != sizeof(*sa));
164 
165 	if (addr_len < sizeof(*sa) + 1)
166 		return -EINVAL;
167 
168 	/* If caller uses non-allowed flag, return error. */
169 	if ((sa->salg_feat & ~allowed) || (sa->salg_mask & ~allowed))
170 		return -EINVAL;
171 
172 	sa->salg_type[sizeof(sa->salg_type) - 1] = 0;
173 	sa->salg_name[addr_len - sizeof(*sa) - 1] = 0;
174 
175 	type = alg_get_type(sa->salg_type);
176 	if (PTR_ERR(type) == -ENOENT) {
177 		request_module("algif-%s", sa->salg_type);
178 		type = alg_get_type(sa->salg_type);
179 	}
180 
181 	if (IS_ERR(type))
182 		return PTR_ERR(type);
183 
184 	private = type->bind(sa->salg_name, sa->salg_feat, sa->salg_mask);
185 	if (IS_ERR(private)) {
186 		module_put(type->owner);
187 		return PTR_ERR(private);
188 	}
189 
190 	err = -EBUSY;
191 	lock_sock(sk);
192 	if (atomic_read(&ask->refcnt))
193 		goto unlock;
194 
195 	swap(ask->type, type);
196 	swap(ask->private, private);
197 
198 	err = 0;
199 
200 unlock:
201 	release_sock(sk);
202 
203 	alg_do_release(type, private);
204 
205 	return err;
206 }
207 
208 static int alg_setkey(struct sock *sk, sockptr_t ukey, unsigned int keylen)
209 {
210 	struct alg_sock *ask = alg_sk(sk);
211 	const struct af_alg_type *type = ask->type;
212 	u8 *key;
213 	int err;
214 
215 	key = sock_kmalloc(sk, keylen, GFP_KERNEL);
216 	if (!key)
217 		return -ENOMEM;
218 
219 	err = -EFAULT;
220 	if (copy_from_sockptr(key, ukey, keylen))
221 		goto out;
222 
223 	err = type->setkey(ask->private, key, keylen);
224 
225 out:
226 	sock_kzfree_s(sk, key, keylen);
227 
228 	return err;
229 }
230 
231 #ifdef CONFIG_KEYS
232 
233 static const u8 *key_data_ptr_user(const struct key *key,
234 				   unsigned int *datalen)
235 {
236 	const struct user_key_payload *ukp;
237 
238 	ukp = user_key_payload_locked(key);
239 	if (IS_ERR_OR_NULL(ukp))
240 		return ERR_PTR(-EKEYREVOKED);
241 
242 	*datalen = key->datalen;
243 
244 	return ukp->data;
245 }
246 
247 static const u8 *key_data_ptr_encrypted(const struct key *key,
248 					unsigned int *datalen)
249 {
250 	const struct encrypted_key_payload *ekp;
251 
252 	ekp = dereference_key_locked(key);
253 	if (IS_ERR_OR_NULL(ekp))
254 		return ERR_PTR(-EKEYREVOKED);
255 
256 	*datalen = ekp->decrypted_datalen;
257 
258 	return ekp->decrypted_data;
259 }
260 
261 static const u8 *key_data_ptr_trusted(const struct key *key,
262 				      unsigned int *datalen)
263 {
264 	const struct trusted_key_payload *tkp;
265 
266 	tkp = dereference_key_locked(key);
267 	if (IS_ERR_OR_NULL(tkp))
268 		return ERR_PTR(-EKEYREVOKED);
269 
270 	*datalen = tkp->key_len;
271 
272 	return tkp->key;
273 }
274 
275 static struct key *lookup_key(key_serial_t serial)
276 {
277 	key_ref_t key_ref;
278 
279 	key_ref = lookup_user_key(serial, 0, KEY_NEED_SEARCH);
280 	if (IS_ERR(key_ref))
281 		return ERR_CAST(key_ref);
282 
283 	return key_ref_to_ptr(key_ref);
284 }
285 
286 static int alg_setkey_by_key_serial(struct alg_sock *ask, sockptr_t optval,
287 				    unsigned int optlen)
288 {
289 	const struct af_alg_type *type = ask->type;
290 	u8 *key_data = NULL;
291 	unsigned int key_datalen;
292 	key_serial_t serial;
293 	struct key *key;
294 	const u8 *ret;
295 	int err;
296 
297 	if (optlen != sizeof(serial))
298 		return -EINVAL;
299 
300 	if (copy_from_sockptr(&serial, optval, optlen))
301 		return -EFAULT;
302 
303 	key = lookup_key(serial);
304 	if (IS_ERR(key))
305 		return PTR_ERR(key);
306 
307 	down_read(&key->sem);
308 
309 	ret = ERR_PTR(-ENOPROTOOPT);
310 	if (!strcmp(key->type->name, "user") ||
311 	    !strcmp(key->type->name, "logon")) {
312 		ret = key_data_ptr_user(key, &key_datalen);
313 	} else if (IS_REACHABLE(CONFIG_ENCRYPTED_KEYS) &&
314 			   !strcmp(key->type->name, "encrypted")) {
315 		ret = key_data_ptr_encrypted(key, &key_datalen);
316 	} else if (IS_REACHABLE(CONFIG_TRUSTED_KEYS) &&
317 			   !strcmp(key->type->name, "trusted")) {
318 		ret = key_data_ptr_trusted(key, &key_datalen);
319 	}
320 
321 	if (IS_ERR(ret)) {
322 		up_read(&key->sem);
323 		key_put(key);
324 		return PTR_ERR(ret);
325 	}
326 
327 	key_data = sock_kmemdup(&ask->sk, ret, key_datalen, GFP_KERNEL);
328 	if (!key_data) {
329 		up_read(&key->sem);
330 		key_put(key);
331 		return -ENOMEM;
332 	}
333 
334 	up_read(&key->sem);
335 	key_put(key);
336 
337 	err = type->setkey(ask->private, key_data, key_datalen);
338 
339 	sock_kzfree_s(&ask->sk, key_data, key_datalen);
340 
341 	return err;
342 }
343 
344 #else
345 
346 static inline int alg_setkey_by_key_serial(struct alg_sock *ask,
347 					   sockptr_t optval,
348 					   unsigned int optlen)
349 {
350 	return -ENOPROTOOPT;
351 }
352 
353 #endif
354 
355 static int alg_setsockopt(struct socket *sock, int level, int optname,
356 			  sockptr_t optval, unsigned int optlen)
357 {
358 	struct sock *sk = sock->sk;
359 	struct alg_sock *ask = alg_sk(sk);
360 	const struct af_alg_type *type;
361 	int err = -EBUSY;
362 
363 	lock_sock(sk);
364 	if (atomic_read(&ask->refcnt) != atomic_read(&ask->nokey_refcnt))
365 		goto unlock;
366 
367 	type = ask->type;
368 
369 	err = -ENOPROTOOPT;
370 	if (level != SOL_ALG || !type)
371 		goto unlock;
372 
373 	switch (optname) {
374 	case ALG_SET_KEY:
375 	case ALG_SET_KEY_BY_KEY_SERIAL:
376 		if (sock->state == SS_CONNECTED)
377 			goto unlock;
378 		if (!type->setkey)
379 			goto unlock;
380 
381 		if (optname == ALG_SET_KEY_BY_KEY_SERIAL)
382 			err = alg_setkey_by_key_serial(ask, optval, optlen);
383 		else
384 			err = alg_setkey(sk, optval, optlen);
385 		break;
386 	case ALG_SET_AEAD_AUTHSIZE:
387 		if (sock->state == SS_CONNECTED)
388 			goto unlock;
389 		if (!type->setauthsize)
390 			goto unlock;
391 		err = type->setauthsize(ask->private, optlen);
392 		break;
393 	case ALG_SET_DRBG_ENTROPY:
394 		if (sock->state == SS_CONNECTED)
395 			goto unlock;
396 		if (!type->setentropy)
397 			goto unlock;
398 
399 		err = type->setentropy(ask->private, optval, optlen);
400 	}
401 
402 unlock:
403 	release_sock(sk);
404 
405 	return err;
406 }
407 
408 int af_alg_accept(struct sock *sk, struct socket *newsock,
409 		  struct proto_accept_arg *arg)
410 {
411 	struct alg_sock *ask = alg_sk(sk);
412 	const struct af_alg_type *type;
413 	struct sock *sk2;
414 	unsigned int nokey;
415 	int err;
416 
417 	lock_sock(sk);
418 	type = ask->type;
419 
420 	err = -EINVAL;
421 	if (!type)
422 		goto unlock;
423 
424 	sk2 = sk_alloc(sock_net(sk), PF_ALG, GFP_KERNEL, &alg_proto, arg->kern);
425 	err = -ENOMEM;
426 	if (!sk2)
427 		goto unlock;
428 
429 	sock_init_data(newsock, sk2);
430 	security_sock_graft(sk2, newsock);
431 	security_sk_clone(sk, sk2);
432 
433 	/*
434 	 * newsock->ops assigned here to allow type->accept call to override
435 	 * them when required.
436 	 */
437 	newsock->ops = type->ops;
438 	err = type->accept(ask->private, sk2);
439 
440 	nokey = err == -ENOKEY;
441 	if (nokey && type->accept_nokey)
442 		err = type->accept_nokey(ask->private, sk2);
443 
444 	if (err)
445 		goto unlock;
446 
447 	if (atomic_inc_return_relaxed(&ask->refcnt) == 1)
448 		sock_hold(sk);
449 	if (nokey) {
450 		atomic_inc(&ask->nokey_refcnt);
451 		atomic_set(&alg_sk(sk2)->nokey_refcnt, 1);
452 	}
453 	alg_sk(sk2)->parent = sk;
454 	alg_sk(sk2)->type = type;
455 
456 	newsock->state = SS_CONNECTED;
457 
458 	if (nokey)
459 		newsock->ops = type->ops_nokey;
460 
461 	err = 0;
462 
463 unlock:
464 	release_sock(sk);
465 
466 	return err;
467 }
468 EXPORT_SYMBOL_GPL(af_alg_accept);
469 
470 static int alg_accept(struct socket *sock, struct socket *newsock,
471 		      struct proto_accept_arg *arg)
472 {
473 	return af_alg_accept(sock->sk, newsock, arg);
474 }
475 
476 static const struct proto_ops alg_proto_ops = {
477 	.family		=	PF_ALG,
478 	.owner		=	THIS_MODULE,
479 
480 	.connect	=	sock_no_connect,
481 	.socketpair	=	sock_no_socketpair,
482 	.getname	=	sock_no_getname,
483 	.ioctl		=	sock_no_ioctl,
484 	.listen		=	sock_no_listen,
485 	.shutdown	=	sock_no_shutdown,
486 	.mmap		=	sock_no_mmap,
487 	.sendmsg	=	sock_no_sendmsg,
488 	.recvmsg	=	sock_no_recvmsg,
489 
490 	.bind		=	alg_bind,
491 	.release	=	af_alg_release,
492 	.setsockopt	=	alg_setsockopt,
493 	.accept		=	alg_accept,
494 };
495 
496 static void alg_sock_destruct(struct sock *sk)
497 {
498 	struct alg_sock *ask = alg_sk(sk);
499 
500 	alg_do_release(ask->type, ask->private);
501 }
502 
503 static int alg_create(struct net *net, struct socket *sock, int protocol,
504 		      int kern)
505 {
506 	struct sock *sk;
507 	int err;
508 
509 	if (sock->type != SOCK_SEQPACKET)
510 		return -ESOCKTNOSUPPORT;
511 	if (protocol != 0)
512 		return -EPROTONOSUPPORT;
513 
514 	err = -ENOMEM;
515 	sk = sk_alloc(net, PF_ALG, GFP_KERNEL, &alg_proto, kern);
516 	if (!sk)
517 		goto out;
518 
519 	sock->ops = &alg_proto_ops;
520 	sock_init_data(sock, sk);
521 
522 	sk->sk_destruct = alg_sock_destruct;
523 
524 	return 0;
525 out:
526 	return err;
527 }
528 
529 static const struct net_proto_family alg_family = {
530 	.family	=	PF_ALG,
531 	.create	=	alg_create,
532 	.owner	=	THIS_MODULE,
533 };
534 
535 static void af_alg_link_sg(struct af_alg_sgl *sgl_prev,
536 			   struct af_alg_sgl *sgl_new)
537 {
538 	sg_unmark_end(sgl_prev->sgt.sgl + sgl_prev->sgt.nents - 1);
539 	sg_chain(sgl_prev->sgt.sgl, sgl_prev->sgt.nents + 1, sgl_new->sgt.sgl);
540 }
541 
542 void af_alg_free_sg(struct af_alg_sgl *sgl)
543 {
544 	int i;
545 
546 	if (sgl->sgt.sgl) {
547 		if (sgl->need_unpin)
548 			for (i = 0; i < sgl->sgt.nents; i++)
549 				unpin_user_page(sg_page(&sgl->sgt.sgl[i]));
550 		if (sgl->sgt.sgl != sgl->sgl)
551 			kvfree(sgl->sgt.sgl);
552 		sgl->sgt.sgl = NULL;
553 	}
554 }
555 EXPORT_SYMBOL_GPL(af_alg_free_sg);
556 
557 static int af_alg_cmsg_send(struct msghdr *msg, struct af_alg_control *con)
558 {
559 	struct cmsghdr *cmsg;
560 
561 	for_each_cmsghdr(cmsg, msg) {
562 		if (!CMSG_OK(msg, cmsg))
563 			return -EINVAL;
564 		if (cmsg->cmsg_level != SOL_ALG)
565 			continue;
566 
567 		switch (cmsg->cmsg_type) {
568 		case ALG_SET_IV:
569 			if (cmsg->cmsg_len < CMSG_LEN(sizeof(*con->iv)))
570 				return -EINVAL;
571 			con->iv = (void *)CMSG_DATA(cmsg);
572 			if (cmsg->cmsg_len < CMSG_LEN(con->iv->ivlen +
573 						      sizeof(*con->iv)))
574 				return -EINVAL;
575 			break;
576 
577 		case ALG_SET_OP:
578 			if (cmsg->cmsg_len < CMSG_LEN(sizeof(u32)))
579 				return -EINVAL;
580 			con->op = *(u32 *)CMSG_DATA(cmsg);
581 			break;
582 
583 		case ALG_SET_AEAD_ASSOCLEN:
584 			if (cmsg->cmsg_len < CMSG_LEN(sizeof(u32)))
585 				return -EINVAL;
586 			con->aead_assoclen = *(u32 *)CMSG_DATA(cmsg);
587 			break;
588 
589 		default:
590 			return -EINVAL;
591 		}
592 	}
593 
594 	return 0;
595 }
596 
597 /**
598  * af_alg_alloc_tsgl - allocate the TX SGL
599  *
600  * @sk: socket of connection to user space
601  * Return: 0 upon success, < 0 upon error
602  */
603 static int af_alg_alloc_tsgl(struct sock *sk)
604 {
605 	struct alg_sock *ask = alg_sk(sk);
606 	struct af_alg_ctx *ctx = ask->private;
607 	struct af_alg_tsgl *sgl;
608 	struct scatterlist *sg = NULL;
609 
610 	sgl = list_entry(ctx->tsgl_list.prev, struct af_alg_tsgl, list);
611 	if (!list_empty(&ctx->tsgl_list))
612 		sg = sgl->sg;
613 
614 	if (!sg || sgl->cur >= MAX_SGL_ENTS) {
615 		sgl = sock_kmalloc(sk,
616 				   struct_size(sgl, sg, (MAX_SGL_ENTS + 1)),
617 				   GFP_KERNEL);
618 		if (!sgl)
619 			return -ENOMEM;
620 
621 		sg_init_table(sgl->sg, MAX_SGL_ENTS + 1);
622 		sgl->cur = 0;
623 
624 		if (sg) {
625 			sg_unmark_end(sg + MAX_SGL_ENTS - 1);
626 			sg_chain(sg, MAX_SGL_ENTS + 1, sgl->sg);
627 		}
628 
629 		list_add_tail(&sgl->list, &ctx->tsgl_list);
630 	}
631 
632 	return 0;
633 }
634 
635 /**
636  * af_alg_count_tsgl - Count number of TX SG entries
637  *
638  * The counting starts from the beginning of the SGL to @bytes.
639  *
640  * @sk: socket of connection to user space
641  * @bytes: Count the number of SG entries holding given number of bytes.
642  * Return: Number of TX SG entries found given the constraints
643  */
644 unsigned int af_alg_count_tsgl(struct sock *sk, size_t bytes)
645 {
646 	const struct alg_sock *ask = alg_sk(sk);
647 	const struct af_alg_ctx *ctx = ask->private;
648 	const struct af_alg_tsgl *sgl;
649 	unsigned int i;
650 	unsigned int sgl_count = 0;
651 
652 	if (!bytes)
653 		return 0;
654 
655 	list_for_each_entry(sgl, &ctx->tsgl_list, list) {
656 		const struct scatterlist *sg = sgl->sg;
657 
658 		for (i = 0; i < sgl->cur; i++) {
659 			sgl_count++;
660 			if (sg[i].length >= bytes)
661 				return sgl_count;
662 
663 			bytes -= sg[i].length;
664 		}
665 	}
666 
667 	return sgl_count;
668 }
669 EXPORT_SYMBOL_GPL(af_alg_count_tsgl);
670 
671 /**
672  * af_alg_pull_tsgl - Release the specified buffers from TX SGL
673  *
674  * If @dst is non-null, reassign the pages to @dst. The caller must release
675  * the pages.
676  *
677  * @sk: socket of connection to user space
678  * @used: Number of bytes to pull from TX SGL
679  * @dst: If non-NULL, buffer is reassigned to dst SGL instead of releasing. The
680  *	 caller must release the buffers in dst.
681  */
682 void af_alg_pull_tsgl(struct sock *sk, size_t used, struct scatterlist *dst)
683 {
684 	struct alg_sock *ask = alg_sk(sk);
685 	struct af_alg_ctx *ctx = ask->private;
686 	struct af_alg_tsgl *sgl;
687 	struct scatterlist *sg;
688 	unsigned int i, j = 0;
689 
690 	while (!list_empty(&ctx->tsgl_list)) {
691 		sgl = list_first_entry(&ctx->tsgl_list, struct af_alg_tsgl,
692 				       list);
693 		sg = sgl->sg;
694 
695 		for (i = 0; i < sgl->cur; i++) {
696 			size_t plen = min_t(size_t, used, sg[i].length);
697 			struct page *page = sg_page(sg + i);
698 
699 			if (!page)
700 				continue;
701 
702 			/*
703 			 * Assumption: caller created af_alg_count_tsgl(len)
704 			 * SG entries in dst.
705 			 */
706 			if (dst && plen) {
707 				/* reassign page to dst */
708 				get_page(page);
709 				sg_set_page(dst + j, page, plen, sg[i].offset);
710 				j++;
711 			}
712 
713 			sg[i].length -= plen;
714 			sg[i].offset += plen;
715 
716 			used -= plen;
717 			ctx->used -= plen;
718 
719 			if (sg[i].length)
720 				return;
721 
722 			put_page(page);
723 			sg_assign_page(sg + i, NULL);
724 		}
725 
726 		list_del(&sgl->list);
727 		sock_kfree_s(sk, sgl, struct_size(sgl, sg, MAX_SGL_ENTS + 1));
728 	}
729 
730 	if (!ctx->used)
731 		ctx->merge = 0;
732 	ctx->init = ctx->more;
733 }
734 EXPORT_SYMBOL_GPL(af_alg_pull_tsgl);
735 
736 /**
737  * af_alg_free_areq_sgls - Release TX and RX SGLs of the request
738  *
739  * @areq: Request holding the TX and RX SGL
740  */
741 static void af_alg_free_areq_sgls(struct af_alg_async_req *areq)
742 {
743 	struct sock *sk = areq->sk;
744 	struct alg_sock *ask = alg_sk(sk);
745 	struct af_alg_ctx *ctx = ask->private;
746 	struct af_alg_rsgl *rsgl, *tmp;
747 	struct scatterlist *tsgl;
748 	struct scatterlist *sg;
749 	unsigned int i;
750 
751 	list_for_each_entry_safe(rsgl, tmp, &areq->rsgl_list, list) {
752 		atomic_sub(rsgl->sg_num_bytes, &ctx->rcvused);
753 		af_alg_free_sg(&rsgl->sgl);
754 		list_del(&rsgl->list);
755 		if (rsgl != &areq->first_rsgl)
756 			sock_kfree_s(sk, rsgl, sizeof(*rsgl));
757 	}
758 
759 	tsgl = areq->tsgl;
760 	if (tsgl) {
761 		for_each_sg(tsgl, sg, areq->tsgl_entries, i) {
762 			if (!sg_page(sg))
763 				continue;
764 			put_page(sg_page(sg));
765 		}
766 
767 		sock_kfree_s(sk, tsgl, areq->tsgl_entries * sizeof(*tsgl));
768 	}
769 }
770 
771 /**
772  * af_alg_wait_for_wmem - wait for availability of writable memory
773  *
774  * @sk: socket of connection to user space
775  * @flags: If MSG_DONTWAIT is set, then only report if function would sleep
776  * Return: 0 when writable memory is available, < 0 upon error
777  */
778 static int af_alg_wait_for_wmem(struct sock *sk, unsigned int flags)
779 {
780 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
781 	int err = -ERESTARTSYS;
782 	long timeout;
783 
784 	if (flags & MSG_DONTWAIT)
785 		return -EAGAIN;
786 
787 	sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
788 
789 	add_wait_queue(sk_sleep(sk), &wait);
790 	for (;;) {
791 		if (signal_pending(current))
792 			break;
793 		timeout = MAX_SCHEDULE_TIMEOUT;
794 		if (sk_wait_event(sk, &timeout, af_alg_writable(sk), &wait)) {
795 			err = 0;
796 			break;
797 		}
798 	}
799 	remove_wait_queue(sk_sleep(sk), &wait);
800 
801 	return err;
802 }
803 
804 /**
805  * af_alg_wmem_wakeup - wakeup caller when writable memory is available
806  *
807  * @sk: socket of connection to user space
808  */
809 void af_alg_wmem_wakeup(struct sock *sk)
810 {
811 	struct socket_wq *wq;
812 
813 	if (!af_alg_writable(sk))
814 		return;
815 
816 	rcu_read_lock();
817 	wq = rcu_dereference(sk->sk_wq);
818 	if (skwq_has_sleeper(wq))
819 		wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN |
820 							   EPOLLRDNORM |
821 							   EPOLLRDBAND);
822 	sk_wake_async_rcu(sk, SOCK_WAKE_WAITD, POLL_IN);
823 	rcu_read_unlock();
824 }
825 EXPORT_SYMBOL_GPL(af_alg_wmem_wakeup);
826 
827 /**
828  * af_alg_wait_for_data - wait for availability of TX data
829  *
830  * @sk: socket of connection to user space
831  * @flags: If MSG_DONTWAIT is set, then only report if function would sleep
832  * @min: Set to minimum request size if partial requests are allowed.
833  * Return: 0 when writable memory is available, < 0 upon error
834  */
835 int af_alg_wait_for_data(struct sock *sk, unsigned flags, unsigned min)
836 {
837 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
838 	struct alg_sock *ask = alg_sk(sk);
839 	struct af_alg_ctx *ctx = ask->private;
840 	long timeout;
841 	int err = -ERESTARTSYS;
842 
843 	if (flags & MSG_DONTWAIT)
844 		return -EAGAIN;
845 
846 	sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
847 
848 	add_wait_queue(sk_sleep(sk), &wait);
849 	for (;;) {
850 		if (signal_pending(current))
851 			break;
852 		timeout = MAX_SCHEDULE_TIMEOUT;
853 		if (sk_wait_event(sk, &timeout,
854 				  ctx->init && (!ctx->more ||
855 						(min && ctx->used >= min)),
856 				  &wait)) {
857 			err = 0;
858 			break;
859 		}
860 	}
861 	remove_wait_queue(sk_sleep(sk), &wait);
862 
863 	sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
864 
865 	return err;
866 }
867 EXPORT_SYMBOL_GPL(af_alg_wait_for_data);
868 
869 /**
870  * af_alg_data_wakeup - wakeup caller when new data can be sent to kernel
871  *
872  * @sk: socket of connection to user space
873  */
874 static void af_alg_data_wakeup(struct sock *sk)
875 {
876 	struct alg_sock *ask = alg_sk(sk);
877 	struct af_alg_ctx *ctx = ask->private;
878 	struct socket_wq *wq;
879 
880 	if (!ctx->used)
881 		return;
882 
883 	rcu_read_lock();
884 	wq = rcu_dereference(sk->sk_wq);
885 	if (skwq_has_sleeper(wq))
886 		wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT |
887 							   EPOLLRDNORM |
888 							   EPOLLRDBAND);
889 	sk_wake_async_rcu(sk, SOCK_WAKE_SPACE, POLL_OUT);
890 	rcu_read_unlock();
891 }
892 
893 /**
894  * af_alg_sendmsg - implementation of sendmsg system call handler
895  *
896  * The sendmsg system call handler obtains the user data and stores it
897  * in ctx->tsgl_list. This implies allocation of the required numbers of
898  * struct af_alg_tsgl.
899  *
900  * In addition, the ctx is filled with the information sent via CMSG.
901  *
902  * @sock: socket of connection to user space
903  * @msg: message from user space
904  * @size: size of message from user space
905  * @ivsize: the size of the IV for the cipher operation to verify that the
906  *	   user-space-provided IV has the right size
907  * Return: the number of copied data upon success, < 0 upon error
908  */
909 int af_alg_sendmsg(struct socket *sock, struct msghdr *msg, size_t size,
910 		   unsigned int ivsize)
911 {
912 	struct sock *sk = sock->sk;
913 	struct alg_sock *ask = alg_sk(sk);
914 	struct af_alg_ctx *ctx = ask->private;
915 	struct af_alg_tsgl *sgl;
916 	struct af_alg_control con = {};
917 	long copied = 0;
918 	bool enc = false;
919 	bool init = false;
920 	int err = 0;
921 
922 	if (msg->msg_controllen) {
923 		err = af_alg_cmsg_send(msg, &con);
924 		if (err)
925 			return err;
926 
927 		init = true;
928 		switch (con.op) {
929 		case ALG_OP_ENCRYPT:
930 			enc = true;
931 			break;
932 		case ALG_OP_DECRYPT:
933 			enc = false;
934 			break;
935 		default:
936 			return -EINVAL;
937 		}
938 
939 		if (con.iv && con.iv->ivlen != ivsize)
940 			return -EINVAL;
941 	}
942 
943 	lock_sock(sk);
944 	if (ctx->write) {
945 		release_sock(sk);
946 		return -EBUSY;
947 	}
948 	ctx->write = true;
949 
950 	if (ctx->init && !ctx->more) {
951 		if (ctx->used) {
952 			err = -EINVAL;
953 			goto unlock;
954 		}
955 
956 		pr_info_once(
957 			"%s sent an empty control message without MSG_MORE.\n",
958 			current->comm);
959 	}
960 	ctx->init = true;
961 
962 	if (init) {
963 		ctx->enc = enc;
964 		if (con.iv)
965 			memcpy(ctx->iv, con.iv->iv, ivsize);
966 
967 		ctx->aead_assoclen = con.aead_assoclen;
968 	}
969 
970 	while (size) {
971 		struct scatterlist *sg;
972 		size_t len = size;
973 		ssize_t plen;
974 
975 		/* use the existing memory in an allocated page */
976 		if (ctx->merge && !(msg->msg_flags & MSG_SPLICE_PAGES)) {
977 			sgl = list_entry(ctx->tsgl_list.prev,
978 					 struct af_alg_tsgl, list);
979 			sg = sgl->sg + sgl->cur - 1;
980 			len = min_t(size_t, len,
981 				    PAGE_SIZE - sg->offset - sg->length);
982 
983 			err = memcpy_from_msg(page_address(sg_page(sg)) +
984 					      sg->offset + sg->length,
985 					      msg, len);
986 			if (err)
987 				goto unlock;
988 
989 			sg->length += len;
990 			ctx->merge = (sg->offset + sg->length) &
991 				     (PAGE_SIZE - 1);
992 
993 			ctx->used += len;
994 			copied += len;
995 			size -= len;
996 			continue;
997 		}
998 
999 		ctx->merge = 0;
1000 
1001 		if (!af_alg_writable(sk)) {
1002 			err = af_alg_wait_for_wmem(sk, msg->msg_flags);
1003 			if (err)
1004 				goto unlock;
1005 		}
1006 
1007 		/* allocate a new page */
1008 		len = min_t(unsigned long, len, af_alg_sndbuf(sk));
1009 
1010 		err = af_alg_alloc_tsgl(sk);
1011 		if (err)
1012 			goto unlock;
1013 
1014 		sgl = list_entry(ctx->tsgl_list.prev, struct af_alg_tsgl,
1015 				 list);
1016 		sg = sgl->sg;
1017 		if (sgl->cur)
1018 			sg_unmark_end(sg + sgl->cur - 1);
1019 
1020 		if (msg->msg_flags & MSG_SPLICE_PAGES) {
1021 			struct sg_table sgtable = {
1022 				.sgl		= sg,
1023 				.nents		= sgl->cur,
1024 				.orig_nents	= sgl->cur,
1025 			};
1026 
1027 			plen = extract_iter_to_sg(&msg->msg_iter, len, &sgtable,
1028 						  MAX_SGL_ENTS - sgl->cur, 0);
1029 			if (plen < 0) {
1030 				err = plen;
1031 				goto unlock;
1032 			}
1033 
1034 			for (; sgl->cur < sgtable.nents; sgl->cur++)
1035 				get_page(sg_page(&sg[sgl->cur]));
1036 			len -= plen;
1037 			ctx->used += plen;
1038 			copied += plen;
1039 			size -= plen;
1040 		} else {
1041 			do {
1042 				struct page *pg;
1043 				unsigned int i = sgl->cur;
1044 
1045 				plen = min_t(size_t, len, PAGE_SIZE);
1046 
1047 				pg = alloc_page(GFP_KERNEL);
1048 				if (!pg) {
1049 					err = -ENOMEM;
1050 					goto unlock;
1051 				}
1052 
1053 				sg_assign_page(sg + i, pg);
1054 
1055 				err = memcpy_from_msg(
1056 					page_address(sg_page(sg + i)),
1057 					msg, plen);
1058 				if (err) {
1059 					__free_page(sg_page(sg + i));
1060 					sg_assign_page(sg + i, NULL);
1061 					goto unlock;
1062 				}
1063 
1064 				sg[i].length = plen;
1065 				len -= plen;
1066 				ctx->used += plen;
1067 				copied += plen;
1068 				size -= plen;
1069 				sgl->cur++;
1070 			} while (len && sgl->cur < MAX_SGL_ENTS);
1071 
1072 			ctx->merge = plen & (PAGE_SIZE - 1);
1073 		}
1074 
1075 		if (!size)
1076 			sg_mark_end(sg + sgl->cur - 1);
1077 	}
1078 
1079 	err = 0;
1080 
1081 	ctx->more = msg->msg_flags & MSG_MORE;
1082 
1083 unlock:
1084 	af_alg_data_wakeup(sk);
1085 	ctx->write = false;
1086 	release_sock(sk);
1087 
1088 	return copied ?: err;
1089 }
1090 EXPORT_SYMBOL_GPL(af_alg_sendmsg);
1091 
1092 /**
1093  * af_alg_free_resources - release resources required for crypto request
1094  * @areq: Request holding the TX and RX SGL
1095  */
1096 void af_alg_free_resources(struct af_alg_async_req *areq)
1097 {
1098 	struct sock *sk = areq->sk;
1099 	struct af_alg_ctx *ctx;
1100 
1101 	af_alg_free_areq_sgls(areq);
1102 	sock_kfree_s(sk, areq, areq->areqlen);
1103 
1104 	ctx = alg_sk(sk)->private;
1105 	ctx->inflight = false;
1106 }
1107 EXPORT_SYMBOL_GPL(af_alg_free_resources);
1108 
1109 /**
1110  * af_alg_async_cb - AIO callback handler
1111  * @data: async request completion data
1112  * @err: if non-zero, error result to be returned via ki_complete();
1113  *       otherwise return the AIO output length via ki_complete().
1114  *
1115  * This handler cleans up the struct af_alg_async_req upon completion of the
1116  * AIO operation.
1117  *
1118  * The number of bytes to be generated with the AIO operation must be set
1119  * in areq->outlen before the AIO callback handler is invoked.
1120  */
1121 void af_alg_async_cb(void *data, int err)
1122 {
1123 	struct af_alg_async_req *areq = data;
1124 	struct sock *sk = areq->sk;
1125 	struct kiocb *iocb = areq->iocb;
1126 	unsigned int resultlen;
1127 
1128 	/* Buffer size written by crypto operation. */
1129 	resultlen = areq->outlen;
1130 
1131 	af_alg_free_resources(areq);
1132 	sock_put(sk);
1133 
1134 	iocb->ki_complete(iocb, err ? err : (int)resultlen);
1135 }
1136 EXPORT_SYMBOL_GPL(af_alg_async_cb);
1137 
1138 /**
1139  * af_alg_poll - poll system call handler
1140  * @file: file pointer
1141  * @sock: socket to poll
1142  * @wait: poll_table
1143  */
1144 __poll_t af_alg_poll(struct file *file, struct socket *sock,
1145 			 poll_table *wait)
1146 {
1147 	struct sock *sk = sock->sk;
1148 	struct alg_sock *ask = alg_sk(sk);
1149 	struct af_alg_ctx *ctx = ask->private;
1150 	__poll_t mask;
1151 
1152 	sock_poll_wait(file, sock, wait);
1153 	mask = 0;
1154 
1155 	if (!ctx->more || ctx->used)
1156 		mask |= EPOLLIN | EPOLLRDNORM;
1157 
1158 	if (af_alg_writable(sk))
1159 		mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
1160 
1161 	return mask;
1162 }
1163 EXPORT_SYMBOL_GPL(af_alg_poll);
1164 
1165 /**
1166  * af_alg_alloc_areq - allocate struct af_alg_async_req
1167  *
1168  * @sk: socket of connection to user space
1169  * @areqlen: size of struct af_alg_async_req + crypto_*_reqsize
1170  * Return: allocated data structure or ERR_PTR upon error
1171  */
1172 struct af_alg_async_req *af_alg_alloc_areq(struct sock *sk,
1173 					   unsigned int areqlen)
1174 {
1175 	struct af_alg_ctx *ctx = alg_sk(sk)->private;
1176 	struct af_alg_async_req *areq;
1177 
1178 	/* Only one AIO request can be in flight. */
1179 	if (ctx->inflight)
1180 		return ERR_PTR(-EBUSY);
1181 
1182 	areq = sock_kmalloc(sk, areqlen, GFP_KERNEL);
1183 	if (unlikely(!areq))
1184 		return ERR_PTR(-ENOMEM);
1185 
1186 	memset(areq, 0, areqlen);
1187 
1188 	ctx->inflight = true;
1189 
1190 	areq->areqlen = areqlen;
1191 	areq->sk = sk;
1192 	areq->first_rsgl.sgl.sgt.sgl = areq->first_rsgl.sgl.sgl;
1193 	INIT_LIST_HEAD(&areq->rsgl_list);
1194 
1195 	return areq;
1196 }
1197 EXPORT_SYMBOL_GPL(af_alg_alloc_areq);
1198 
1199 /**
1200  * af_alg_get_rsgl - create the RX SGL for the output data from the crypto
1201  *		     operation
1202  *
1203  * @sk: socket of connection to user space
1204  * @msg: user space message
1205  * @flags: flags used to invoke recvmsg with
1206  * @areq: instance of the cryptographic request that will hold the RX SGL
1207  * @maxsize: maximum number of bytes to be pulled from user space
1208  * @outlen: number of bytes in the RX SGL
1209  * Return: 0 on success, < 0 upon error
1210  */
1211 int af_alg_get_rsgl(struct sock *sk, struct msghdr *msg, int flags,
1212 		    struct af_alg_async_req *areq, size_t maxsize,
1213 		    size_t *outlen)
1214 {
1215 	struct alg_sock *ask = alg_sk(sk);
1216 	struct af_alg_ctx *ctx = ask->private;
1217 	size_t len = 0;
1218 
1219 	while (maxsize > len && msg_data_left(msg)) {
1220 		struct af_alg_rsgl *rsgl;
1221 		ssize_t err;
1222 		size_t seglen;
1223 
1224 		/* limit the amount of readable buffers */
1225 		if (!af_alg_readable(sk))
1226 			break;
1227 
1228 		seglen = min_t(size_t, (maxsize - len),
1229 			       msg_data_left(msg));
1230 		/* Never pin more pages than the remaining RX accounting budget. */
1231 		seglen = min_t(size_t, seglen, af_alg_rcvbuf(sk));
1232 
1233 		if (list_empty(&areq->rsgl_list)) {
1234 			rsgl = &areq->first_rsgl;
1235 		} else {
1236 			rsgl = sock_kmalloc(sk, sizeof(*rsgl), GFP_KERNEL);
1237 			if (unlikely(!rsgl))
1238 				return -ENOMEM;
1239 		}
1240 
1241 		rsgl->sgl.need_unpin =
1242 			iov_iter_extract_will_pin(&msg->msg_iter);
1243 		rsgl->sgl.sgt.sgl = rsgl->sgl.sgl;
1244 		rsgl->sgl.sgt.nents = 0;
1245 		rsgl->sgl.sgt.orig_nents = 0;
1246 		list_add_tail(&rsgl->list, &areq->rsgl_list);
1247 
1248 		sg_init_table(rsgl->sgl.sgt.sgl, ALG_MAX_PAGES);
1249 		err = extract_iter_to_sg(&msg->msg_iter, seglen, &rsgl->sgl.sgt,
1250 					 ALG_MAX_PAGES, 0);
1251 		if (err < 0) {
1252 			rsgl->sg_num_bytes = 0;
1253 			return err;
1254 		}
1255 
1256 		sg_mark_end(rsgl->sgl.sgt.sgl + rsgl->sgl.sgt.nents - 1);
1257 
1258 		/* chain the new scatterlist with previous one */
1259 		if (areq->last_rsgl)
1260 			af_alg_link_sg(&areq->last_rsgl->sgl, &rsgl->sgl);
1261 
1262 		areq->last_rsgl = rsgl;
1263 		len += err;
1264 		atomic_add(err, &ctx->rcvused);
1265 		rsgl->sg_num_bytes = err;
1266 	}
1267 
1268 	*outlen = len;
1269 	return 0;
1270 }
1271 EXPORT_SYMBOL_GPL(af_alg_get_rsgl);
1272 
1273 static int __init af_alg_init(void)
1274 {
1275 	int err = proto_register(&alg_proto, 0);
1276 
1277 	if (err)
1278 		goto out;
1279 
1280 	err = sock_register(&alg_family);
1281 	if (err != 0)
1282 		goto out_unregister_proto;
1283 
1284 out:
1285 	return err;
1286 
1287 out_unregister_proto:
1288 	proto_unregister(&alg_proto);
1289 	goto out;
1290 }
1291 
1292 static void __exit af_alg_exit(void)
1293 {
1294 	sock_unregister(PF_ALG);
1295 	proto_unregister(&alg_proto);
1296 }
1297 
1298 module_init(af_alg_init);
1299 module_exit(af_alg_exit);
1300 MODULE_DESCRIPTION("Crypto userspace interface");
1301 MODULE_LICENSE("GPL");
1302 MODULE_ALIAS_NETPROTO(AF_ALG);
1303