xref: /linux/crypto/af_alg.c (revision a664bf3d603dc3bdcf9ae47cc21e0daec706d7a5)
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_kmalloc(&ask->sk, key_datalen, GFP_KERNEL);
328 	if (!key_data) {
329 		up_read(&key->sem);
330 		key_put(key);
331 		return -ENOMEM;
332 	}
333 
334 	memcpy(key_data, ret, key_datalen);
335 
336 	up_read(&key->sem);
337 	key_put(key);
338 
339 	err = type->setkey(ask->private, key_data, key_datalen);
340 
341 	sock_kzfree_s(&ask->sk, key_data, key_datalen);
342 
343 	return err;
344 }
345 
346 #else
347 
348 static inline int alg_setkey_by_key_serial(struct alg_sock *ask,
349 					   sockptr_t optval,
350 					   unsigned int optlen)
351 {
352 	return -ENOPROTOOPT;
353 }
354 
355 #endif
356 
357 static int alg_setsockopt(struct socket *sock, int level, int optname,
358 			  sockptr_t optval, unsigned int optlen)
359 {
360 	struct sock *sk = sock->sk;
361 	struct alg_sock *ask = alg_sk(sk);
362 	const struct af_alg_type *type;
363 	int err = -EBUSY;
364 
365 	lock_sock(sk);
366 	if (atomic_read(&ask->refcnt) != atomic_read(&ask->nokey_refcnt))
367 		goto unlock;
368 
369 	type = ask->type;
370 
371 	err = -ENOPROTOOPT;
372 	if (level != SOL_ALG || !type)
373 		goto unlock;
374 
375 	switch (optname) {
376 	case ALG_SET_KEY:
377 	case ALG_SET_KEY_BY_KEY_SERIAL:
378 		if (sock->state == SS_CONNECTED)
379 			goto unlock;
380 		if (!type->setkey)
381 			goto unlock;
382 
383 		if (optname == ALG_SET_KEY_BY_KEY_SERIAL)
384 			err = alg_setkey_by_key_serial(ask, optval, optlen);
385 		else
386 			err = alg_setkey(sk, optval, optlen);
387 		break;
388 	case ALG_SET_AEAD_AUTHSIZE:
389 		if (sock->state == SS_CONNECTED)
390 			goto unlock;
391 		if (!type->setauthsize)
392 			goto unlock;
393 		err = type->setauthsize(ask->private, optlen);
394 		break;
395 	case ALG_SET_DRBG_ENTROPY:
396 		if (sock->state == SS_CONNECTED)
397 			goto unlock;
398 		if (!type->setentropy)
399 			goto unlock;
400 
401 		err = type->setentropy(ask->private, optval, optlen);
402 	}
403 
404 unlock:
405 	release_sock(sk);
406 
407 	return err;
408 }
409 
410 int af_alg_accept(struct sock *sk, struct socket *newsock,
411 		  struct proto_accept_arg *arg)
412 {
413 	struct alg_sock *ask = alg_sk(sk);
414 	const struct af_alg_type *type;
415 	struct sock *sk2;
416 	unsigned int nokey;
417 	int err;
418 
419 	lock_sock(sk);
420 	type = ask->type;
421 
422 	err = -EINVAL;
423 	if (!type)
424 		goto unlock;
425 
426 	sk2 = sk_alloc(sock_net(sk), PF_ALG, GFP_KERNEL, &alg_proto, arg->kern);
427 	err = -ENOMEM;
428 	if (!sk2)
429 		goto unlock;
430 
431 	sock_init_data(newsock, sk2);
432 	security_sock_graft(sk2, newsock);
433 	security_sk_clone(sk, sk2);
434 
435 	/*
436 	 * newsock->ops assigned here to allow type->accept call to override
437 	 * them when required.
438 	 */
439 	newsock->ops = type->ops;
440 	err = type->accept(ask->private, sk2);
441 
442 	nokey = err == -ENOKEY;
443 	if (nokey && type->accept_nokey)
444 		err = type->accept_nokey(ask->private, sk2);
445 
446 	if (err)
447 		goto unlock;
448 
449 	if (atomic_inc_return_relaxed(&ask->refcnt) == 1)
450 		sock_hold(sk);
451 	if (nokey) {
452 		atomic_inc(&ask->nokey_refcnt);
453 		atomic_set(&alg_sk(sk2)->nokey_refcnt, 1);
454 	}
455 	alg_sk(sk2)->parent = sk;
456 	alg_sk(sk2)->type = type;
457 
458 	newsock->state = SS_CONNECTED;
459 
460 	if (nokey)
461 		newsock->ops = type->ops_nokey;
462 
463 	err = 0;
464 
465 unlock:
466 	release_sock(sk);
467 
468 	return err;
469 }
470 EXPORT_SYMBOL_GPL(af_alg_accept);
471 
472 static int alg_accept(struct socket *sock, struct socket *newsock,
473 		      struct proto_accept_arg *arg)
474 {
475 	return af_alg_accept(sock->sk, newsock, arg);
476 }
477 
478 static const struct proto_ops alg_proto_ops = {
479 	.family		=	PF_ALG,
480 	.owner		=	THIS_MODULE,
481 
482 	.connect	=	sock_no_connect,
483 	.socketpair	=	sock_no_socketpair,
484 	.getname	=	sock_no_getname,
485 	.ioctl		=	sock_no_ioctl,
486 	.listen		=	sock_no_listen,
487 	.shutdown	=	sock_no_shutdown,
488 	.mmap		=	sock_no_mmap,
489 	.sendmsg	=	sock_no_sendmsg,
490 	.recvmsg	=	sock_no_recvmsg,
491 
492 	.bind		=	alg_bind,
493 	.release	=	af_alg_release,
494 	.setsockopt	=	alg_setsockopt,
495 	.accept		=	alg_accept,
496 };
497 
498 static void alg_sock_destruct(struct sock *sk)
499 {
500 	struct alg_sock *ask = alg_sk(sk);
501 
502 	alg_do_release(ask->type, ask->private);
503 }
504 
505 static int alg_create(struct net *net, struct socket *sock, int protocol,
506 		      int kern)
507 {
508 	struct sock *sk;
509 	int err;
510 
511 	if (sock->type != SOCK_SEQPACKET)
512 		return -ESOCKTNOSUPPORT;
513 	if (protocol != 0)
514 		return -EPROTONOSUPPORT;
515 
516 	err = -ENOMEM;
517 	sk = sk_alloc(net, PF_ALG, GFP_KERNEL, &alg_proto, kern);
518 	if (!sk)
519 		goto out;
520 
521 	sock->ops = &alg_proto_ops;
522 	sock_init_data(sock, sk);
523 
524 	sk->sk_destruct = alg_sock_destruct;
525 
526 	return 0;
527 out:
528 	return err;
529 }
530 
531 static const struct net_proto_family alg_family = {
532 	.family	=	PF_ALG,
533 	.create	=	alg_create,
534 	.owner	=	THIS_MODULE,
535 };
536 
537 static void af_alg_link_sg(struct af_alg_sgl *sgl_prev,
538 			   struct af_alg_sgl *sgl_new)
539 {
540 	sg_unmark_end(sgl_prev->sgt.sgl + sgl_prev->sgt.nents - 1);
541 	sg_chain(sgl_prev->sgt.sgl, sgl_prev->sgt.nents + 1, sgl_new->sgt.sgl);
542 }
543 
544 void af_alg_free_sg(struct af_alg_sgl *sgl)
545 {
546 	int i;
547 
548 	if (sgl->sgt.sgl) {
549 		if (sgl->need_unpin)
550 			for (i = 0; i < sgl->sgt.nents; i++)
551 				unpin_user_page(sg_page(&sgl->sgt.sgl[i]));
552 		if (sgl->sgt.sgl != sgl->sgl)
553 			kvfree(sgl->sgt.sgl);
554 		sgl->sgt.sgl = NULL;
555 	}
556 }
557 EXPORT_SYMBOL_GPL(af_alg_free_sg);
558 
559 static int af_alg_cmsg_send(struct msghdr *msg, struct af_alg_control *con)
560 {
561 	struct cmsghdr *cmsg;
562 
563 	for_each_cmsghdr(cmsg, msg) {
564 		if (!CMSG_OK(msg, cmsg))
565 			return -EINVAL;
566 		if (cmsg->cmsg_level != SOL_ALG)
567 			continue;
568 
569 		switch (cmsg->cmsg_type) {
570 		case ALG_SET_IV:
571 			if (cmsg->cmsg_len < CMSG_LEN(sizeof(*con->iv)))
572 				return -EINVAL;
573 			con->iv = (void *)CMSG_DATA(cmsg);
574 			if (cmsg->cmsg_len < CMSG_LEN(con->iv->ivlen +
575 						      sizeof(*con->iv)))
576 				return -EINVAL;
577 			break;
578 
579 		case ALG_SET_OP:
580 			if (cmsg->cmsg_len < CMSG_LEN(sizeof(u32)))
581 				return -EINVAL;
582 			con->op = *(u32 *)CMSG_DATA(cmsg);
583 			break;
584 
585 		case ALG_SET_AEAD_ASSOCLEN:
586 			if (cmsg->cmsg_len < CMSG_LEN(sizeof(u32)))
587 				return -EINVAL;
588 			con->aead_assoclen = *(u32 *)CMSG_DATA(cmsg);
589 			break;
590 
591 		default:
592 			return -EINVAL;
593 		}
594 	}
595 
596 	return 0;
597 }
598 
599 /**
600  * af_alg_alloc_tsgl - allocate the TX SGL
601  *
602  * @sk: socket of connection to user space
603  * Return: 0 upon success, < 0 upon error
604  */
605 static int af_alg_alloc_tsgl(struct sock *sk)
606 {
607 	struct alg_sock *ask = alg_sk(sk);
608 	struct af_alg_ctx *ctx = ask->private;
609 	struct af_alg_tsgl *sgl;
610 	struct scatterlist *sg = NULL;
611 
612 	sgl = list_entry(ctx->tsgl_list.prev, struct af_alg_tsgl, list);
613 	if (!list_empty(&ctx->tsgl_list))
614 		sg = sgl->sg;
615 
616 	if (!sg || sgl->cur >= MAX_SGL_ENTS) {
617 		sgl = sock_kmalloc(sk,
618 				   struct_size(sgl, sg, (MAX_SGL_ENTS + 1)),
619 				   GFP_KERNEL);
620 		if (!sgl)
621 			return -ENOMEM;
622 
623 		sg_init_table(sgl->sg, MAX_SGL_ENTS + 1);
624 		sgl->cur = 0;
625 
626 		if (sg) {
627 			sg_unmark_end(sg + MAX_SGL_ENTS - 1);
628 			sg_chain(sg, MAX_SGL_ENTS + 1, sgl->sg);
629 		}
630 
631 		list_add_tail(&sgl->list, &ctx->tsgl_list);
632 	}
633 
634 	return 0;
635 }
636 
637 /**
638  * af_alg_count_tsgl - Count number of TX SG entries
639  *
640  * The counting starts from the beginning of the SGL to @bytes.
641  *
642  * @sk: socket of connection to user space
643  * @bytes: Count the number of SG entries holding given number of bytes.
644  * Return: Number of TX SG entries found given the constraints
645  */
646 unsigned int af_alg_count_tsgl(struct sock *sk, size_t bytes)
647 {
648 	const struct alg_sock *ask = alg_sk(sk);
649 	const struct af_alg_ctx *ctx = ask->private;
650 	const struct af_alg_tsgl *sgl;
651 	unsigned int i;
652 	unsigned int sgl_count = 0;
653 
654 	if (!bytes)
655 		return 0;
656 
657 	list_for_each_entry(sgl, &ctx->tsgl_list, list) {
658 		const struct scatterlist *sg = sgl->sg;
659 
660 		for (i = 0; i < sgl->cur; i++) {
661 			sgl_count++;
662 			if (sg[i].length >= bytes)
663 				return sgl_count;
664 
665 			bytes -= sg[i].length;
666 		}
667 	}
668 
669 	return sgl_count;
670 }
671 EXPORT_SYMBOL_GPL(af_alg_count_tsgl);
672 
673 /**
674  * af_alg_pull_tsgl - Release the specified buffers from TX SGL
675  *
676  * If @dst is non-null, reassign the pages to @dst. The caller must release
677  * the pages.
678  *
679  * @sk: socket of connection to user space
680  * @used: Number of bytes to pull from TX SGL
681  * @dst: If non-NULL, buffer is reassigned to dst SGL instead of releasing. The
682  *	 caller must release the buffers in dst.
683  */
684 void af_alg_pull_tsgl(struct sock *sk, size_t used, struct scatterlist *dst)
685 {
686 	struct alg_sock *ask = alg_sk(sk);
687 	struct af_alg_ctx *ctx = ask->private;
688 	struct af_alg_tsgl *sgl;
689 	struct scatterlist *sg;
690 	unsigned int i, j = 0;
691 
692 	while (!list_empty(&ctx->tsgl_list)) {
693 		sgl = list_first_entry(&ctx->tsgl_list, struct af_alg_tsgl,
694 				       list);
695 		sg = sgl->sg;
696 
697 		for (i = 0; i < sgl->cur; i++) {
698 			size_t plen = min_t(size_t, used, sg[i].length);
699 			struct page *page = sg_page(sg + i);
700 
701 			if (!page)
702 				continue;
703 
704 			/*
705 			 * Assumption: caller created af_alg_count_tsgl(len)
706 			 * SG entries in dst.
707 			 */
708 			if (dst) {
709 				/* reassign page to dst after offset */
710 				get_page(page);
711 				sg_set_page(dst + j, page, plen, sg[i].offset);
712 				j++;
713 			}
714 
715 			sg[i].length -= plen;
716 			sg[i].offset += plen;
717 
718 			used -= plen;
719 			ctx->used -= plen;
720 
721 			if (sg[i].length)
722 				return;
723 
724 			put_page(page);
725 			sg_assign_page(sg + i, NULL);
726 		}
727 
728 		list_del(&sgl->list);
729 		sock_kfree_s(sk, sgl, struct_size(sgl, sg, MAX_SGL_ENTS + 1));
730 	}
731 
732 	if (!ctx->used)
733 		ctx->merge = 0;
734 	ctx->init = ctx->more;
735 }
736 EXPORT_SYMBOL_GPL(af_alg_pull_tsgl);
737 
738 /**
739  * af_alg_free_areq_sgls - Release TX and RX SGLs of the request
740  *
741  * @areq: Request holding the TX and RX SGL
742  */
743 static void af_alg_free_areq_sgls(struct af_alg_async_req *areq)
744 {
745 	struct sock *sk = areq->sk;
746 	struct alg_sock *ask = alg_sk(sk);
747 	struct af_alg_ctx *ctx = ask->private;
748 	struct af_alg_rsgl *rsgl, *tmp;
749 	struct scatterlist *tsgl;
750 	struct scatterlist *sg;
751 	unsigned int i;
752 
753 	list_for_each_entry_safe(rsgl, tmp, &areq->rsgl_list, list) {
754 		atomic_sub(rsgl->sg_num_bytes, &ctx->rcvused);
755 		af_alg_free_sg(&rsgl->sgl);
756 		list_del(&rsgl->list);
757 		if (rsgl != &areq->first_rsgl)
758 			sock_kfree_s(sk, rsgl, sizeof(*rsgl));
759 	}
760 
761 	tsgl = areq->tsgl;
762 	if (tsgl) {
763 		for_each_sg(tsgl, sg, areq->tsgl_entries, i) {
764 			if (!sg_page(sg))
765 				continue;
766 			put_page(sg_page(sg));
767 		}
768 
769 		sock_kfree_s(sk, tsgl, areq->tsgl_entries * sizeof(*tsgl));
770 	}
771 }
772 
773 /**
774  * af_alg_wait_for_wmem - wait for availability of writable memory
775  *
776  * @sk: socket of connection to user space
777  * @flags: If MSG_DONTWAIT is set, then only report if function would sleep
778  * Return: 0 when writable memory is available, < 0 upon error
779  */
780 static int af_alg_wait_for_wmem(struct sock *sk, unsigned int flags)
781 {
782 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
783 	int err = -ERESTARTSYS;
784 	long timeout;
785 
786 	if (flags & MSG_DONTWAIT)
787 		return -EAGAIN;
788 
789 	sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
790 
791 	add_wait_queue(sk_sleep(sk), &wait);
792 	for (;;) {
793 		if (signal_pending(current))
794 			break;
795 		timeout = MAX_SCHEDULE_TIMEOUT;
796 		if (sk_wait_event(sk, &timeout, af_alg_writable(sk), &wait)) {
797 			err = 0;
798 			break;
799 		}
800 	}
801 	remove_wait_queue(sk_sleep(sk), &wait);
802 
803 	return err;
804 }
805 
806 /**
807  * af_alg_wmem_wakeup - wakeup caller when writable memory is available
808  *
809  * @sk: socket of connection to user space
810  */
811 void af_alg_wmem_wakeup(struct sock *sk)
812 {
813 	struct socket_wq *wq;
814 
815 	if (!af_alg_writable(sk))
816 		return;
817 
818 	rcu_read_lock();
819 	wq = rcu_dereference(sk->sk_wq);
820 	if (skwq_has_sleeper(wq))
821 		wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN |
822 							   EPOLLRDNORM |
823 							   EPOLLRDBAND);
824 	sk_wake_async_rcu(sk, SOCK_WAKE_WAITD, POLL_IN);
825 	rcu_read_unlock();
826 }
827 EXPORT_SYMBOL_GPL(af_alg_wmem_wakeup);
828 
829 /**
830  * af_alg_wait_for_data - wait for availability of TX data
831  *
832  * @sk: socket of connection to user space
833  * @flags: If MSG_DONTWAIT is set, then only report if function would sleep
834  * @min: Set to minimum request size if partial requests are allowed.
835  * Return: 0 when writable memory is available, < 0 upon error
836  */
837 int af_alg_wait_for_data(struct sock *sk, unsigned flags, unsigned min)
838 {
839 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
840 	struct alg_sock *ask = alg_sk(sk);
841 	struct af_alg_ctx *ctx = ask->private;
842 	long timeout;
843 	int err = -ERESTARTSYS;
844 
845 	if (flags & MSG_DONTWAIT)
846 		return -EAGAIN;
847 
848 	sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
849 
850 	add_wait_queue(sk_sleep(sk), &wait);
851 	for (;;) {
852 		if (signal_pending(current))
853 			break;
854 		timeout = MAX_SCHEDULE_TIMEOUT;
855 		if (sk_wait_event(sk, &timeout,
856 				  ctx->init && (!ctx->more ||
857 						(min && ctx->used >= min)),
858 				  &wait)) {
859 			err = 0;
860 			break;
861 		}
862 	}
863 	remove_wait_queue(sk_sleep(sk), &wait);
864 
865 	sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
866 
867 	return err;
868 }
869 EXPORT_SYMBOL_GPL(af_alg_wait_for_data);
870 
871 /**
872  * af_alg_data_wakeup - wakeup caller when new data can be sent to kernel
873  *
874  * @sk: socket of connection to user space
875  */
876 static void af_alg_data_wakeup(struct sock *sk)
877 {
878 	struct alg_sock *ask = alg_sk(sk);
879 	struct af_alg_ctx *ctx = ask->private;
880 	struct socket_wq *wq;
881 
882 	if (!ctx->used)
883 		return;
884 
885 	rcu_read_lock();
886 	wq = rcu_dereference(sk->sk_wq);
887 	if (skwq_has_sleeper(wq))
888 		wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT |
889 							   EPOLLRDNORM |
890 							   EPOLLRDBAND);
891 	sk_wake_async_rcu(sk, SOCK_WAKE_SPACE, POLL_OUT);
892 	rcu_read_unlock();
893 }
894 
895 /**
896  * af_alg_sendmsg - implementation of sendmsg system call handler
897  *
898  * The sendmsg system call handler obtains the user data and stores it
899  * in ctx->tsgl_list. This implies allocation of the required numbers of
900  * struct af_alg_tsgl.
901  *
902  * In addition, the ctx is filled with the information sent via CMSG.
903  *
904  * @sock: socket of connection to user space
905  * @msg: message from user space
906  * @size: size of message from user space
907  * @ivsize: the size of the IV for the cipher operation to verify that the
908  *	   user-space-provided IV has the right size
909  * Return: the number of copied data upon success, < 0 upon error
910  */
911 int af_alg_sendmsg(struct socket *sock, struct msghdr *msg, size_t size,
912 		   unsigned int ivsize)
913 {
914 	struct sock *sk = sock->sk;
915 	struct alg_sock *ask = alg_sk(sk);
916 	struct af_alg_ctx *ctx = ask->private;
917 	struct af_alg_tsgl *sgl;
918 	struct af_alg_control con = {};
919 	long copied = 0;
920 	bool enc = false;
921 	bool init = false;
922 	int err = 0;
923 
924 	if (msg->msg_controllen) {
925 		err = af_alg_cmsg_send(msg, &con);
926 		if (err)
927 			return err;
928 
929 		init = true;
930 		switch (con.op) {
931 		case ALG_OP_ENCRYPT:
932 			enc = true;
933 			break;
934 		case ALG_OP_DECRYPT:
935 			enc = false;
936 			break;
937 		default:
938 			return -EINVAL;
939 		}
940 
941 		if (con.iv && con.iv->ivlen != ivsize)
942 			return -EINVAL;
943 	}
944 
945 	lock_sock(sk);
946 	if (ctx->write) {
947 		release_sock(sk);
948 		return -EBUSY;
949 	}
950 	ctx->write = true;
951 
952 	if (ctx->init && !ctx->more) {
953 		if (ctx->used) {
954 			err = -EINVAL;
955 			goto unlock;
956 		}
957 
958 		pr_info_once(
959 			"%s sent an empty control message without MSG_MORE.\n",
960 			current->comm);
961 	}
962 	ctx->init = true;
963 
964 	if (init) {
965 		ctx->enc = enc;
966 		if (con.iv)
967 			memcpy(ctx->iv, con.iv->iv, ivsize);
968 
969 		ctx->aead_assoclen = con.aead_assoclen;
970 	}
971 
972 	while (size) {
973 		struct scatterlist *sg;
974 		size_t len = size;
975 		ssize_t plen;
976 
977 		/* use the existing memory in an allocated page */
978 		if (ctx->merge && !(msg->msg_flags & MSG_SPLICE_PAGES)) {
979 			sgl = list_entry(ctx->tsgl_list.prev,
980 					 struct af_alg_tsgl, list);
981 			sg = sgl->sg + sgl->cur - 1;
982 			len = min_t(size_t, len,
983 				    PAGE_SIZE - sg->offset - sg->length);
984 
985 			err = memcpy_from_msg(page_address(sg_page(sg)) +
986 					      sg->offset + sg->length,
987 					      msg, len);
988 			if (err)
989 				goto unlock;
990 
991 			sg->length += len;
992 			ctx->merge = (sg->offset + sg->length) &
993 				     (PAGE_SIZE - 1);
994 
995 			ctx->used += len;
996 			copied += len;
997 			size -= len;
998 			continue;
999 		}
1000 
1001 		ctx->merge = 0;
1002 
1003 		if (!af_alg_writable(sk)) {
1004 			err = af_alg_wait_for_wmem(sk, msg->msg_flags);
1005 			if (err)
1006 				goto unlock;
1007 		}
1008 
1009 		/* allocate a new page */
1010 		len = min_t(unsigned long, len, af_alg_sndbuf(sk));
1011 
1012 		err = af_alg_alloc_tsgl(sk);
1013 		if (err)
1014 			goto unlock;
1015 
1016 		sgl = list_entry(ctx->tsgl_list.prev, struct af_alg_tsgl,
1017 				 list);
1018 		sg = sgl->sg;
1019 		if (sgl->cur)
1020 			sg_unmark_end(sg + sgl->cur - 1);
1021 
1022 		if (msg->msg_flags & MSG_SPLICE_PAGES) {
1023 			struct sg_table sgtable = {
1024 				.sgl		= sg,
1025 				.nents		= sgl->cur,
1026 				.orig_nents	= sgl->cur,
1027 			};
1028 
1029 			plen = extract_iter_to_sg(&msg->msg_iter, len, &sgtable,
1030 						  MAX_SGL_ENTS - sgl->cur, 0);
1031 			if (plen < 0) {
1032 				err = plen;
1033 				goto unlock;
1034 			}
1035 
1036 			for (; sgl->cur < sgtable.nents; sgl->cur++)
1037 				get_page(sg_page(&sg[sgl->cur]));
1038 			len -= plen;
1039 			ctx->used += plen;
1040 			copied += plen;
1041 			size -= plen;
1042 		} else {
1043 			do {
1044 				struct page *pg;
1045 				unsigned int i = sgl->cur;
1046 
1047 				plen = min_t(size_t, len, PAGE_SIZE);
1048 
1049 				pg = alloc_page(GFP_KERNEL);
1050 				if (!pg) {
1051 					err = -ENOMEM;
1052 					goto unlock;
1053 				}
1054 
1055 				sg_assign_page(sg + i, pg);
1056 
1057 				err = memcpy_from_msg(
1058 					page_address(sg_page(sg + i)),
1059 					msg, plen);
1060 				if (err) {
1061 					__free_page(sg_page(sg + i));
1062 					sg_assign_page(sg + i, NULL);
1063 					goto unlock;
1064 				}
1065 
1066 				sg[i].length = plen;
1067 				len -= plen;
1068 				ctx->used += plen;
1069 				copied += plen;
1070 				size -= plen;
1071 				sgl->cur++;
1072 			} while (len && sgl->cur < MAX_SGL_ENTS);
1073 
1074 			ctx->merge = plen & (PAGE_SIZE - 1);
1075 		}
1076 
1077 		if (!size)
1078 			sg_mark_end(sg + sgl->cur - 1);
1079 	}
1080 
1081 	err = 0;
1082 
1083 	ctx->more = msg->msg_flags & MSG_MORE;
1084 
1085 unlock:
1086 	af_alg_data_wakeup(sk);
1087 	ctx->write = false;
1088 	release_sock(sk);
1089 
1090 	return copied ?: err;
1091 }
1092 EXPORT_SYMBOL_GPL(af_alg_sendmsg);
1093 
1094 /**
1095  * af_alg_free_resources - release resources required for crypto request
1096  * @areq: Request holding the TX and RX SGL
1097  */
1098 void af_alg_free_resources(struct af_alg_async_req *areq)
1099 {
1100 	struct sock *sk = areq->sk;
1101 	struct af_alg_ctx *ctx;
1102 
1103 	af_alg_free_areq_sgls(areq);
1104 	sock_kfree_s(sk, areq, areq->areqlen);
1105 
1106 	ctx = alg_sk(sk)->private;
1107 	ctx->inflight = false;
1108 }
1109 EXPORT_SYMBOL_GPL(af_alg_free_resources);
1110 
1111 /**
1112  * af_alg_async_cb - AIO callback handler
1113  * @data: async request completion data
1114  * @err: if non-zero, error result to be returned via ki_complete();
1115  *       otherwise return the AIO output length via ki_complete().
1116  *
1117  * This handler cleans up the struct af_alg_async_req upon completion of the
1118  * AIO operation.
1119  *
1120  * The number of bytes to be generated with the AIO operation must be set
1121  * in areq->outlen before the AIO callback handler is invoked.
1122  */
1123 void af_alg_async_cb(void *data, int err)
1124 {
1125 	struct af_alg_async_req *areq = data;
1126 	struct sock *sk = areq->sk;
1127 	struct kiocb *iocb = areq->iocb;
1128 	unsigned int resultlen;
1129 
1130 	/* Buffer size written by crypto operation. */
1131 	resultlen = areq->outlen;
1132 
1133 	af_alg_free_resources(areq);
1134 	sock_put(sk);
1135 
1136 	iocb->ki_complete(iocb, err ? err : (int)resultlen);
1137 }
1138 EXPORT_SYMBOL_GPL(af_alg_async_cb);
1139 
1140 /**
1141  * af_alg_poll - poll system call handler
1142  * @file: file pointer
1143  * @sock: socket to poll
1144  * @wait: poll_table
1145  */
1146 __poll_t af_alg_poll(struct file *file, struct socket *sock,
1147 			 poll_table *wait)
1148 {
1149 	struct sock *sk = sock->sk;
1150 	struct alg_sock *ask = alg_sk(sk);
1151 	struct af_alg_ctx *ctx = ask->private;
1152 	__poll_t mask;
1153 
1154 	sock_poll_wait(file, sock, wait);
1155 	mask = 0;
1156 
1157 	if (!ctx->more || ctx->used)
1158 		mask |= EPOLLIN | EPOLLRDNORM;
1159 
1160 	if (af_alg_writable(sk))
1161 		mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
1162 
1163 	return mask;
1164 }
1165 EXPORT_SYMBOL_GPL(af_alg_poll);
1166 
1167 /**
1168  * af_alg_alloc_areq - allocate struct af_alg_async_req
1169  *
1170  * @sk: socket of connection to user space
1171  * @areqlen: size of struct af_alg_async_req + crypto_*_reqsize
1172  * Return: allocated data structure or ERR_PTR upon error
1173  */
1174 struct af_alg_async_req *af_alg_alloc_areq(struct sock *sk,
1175 					   unsigned int areqlen)
1176 {
1177 	struct af_alg_ctx *ctx = alg_sk(sk)->private;
1178 	struct af_alg_async_req *areq;
1179 
1180 	/* Only one AIO request can be in flight. */
1181 	if (ctx->inflight)
1182 		return ERR_PTR(-EBUSY);
1183 
1184 	areq = sock_kmalloc(sk, areqlen, GFP_KERNEL);
1185 	if (unlikely(!areq))
1186 		return ERR_PTR(-ENOMEM);
1187 
1188 	memset(areq, 0, areqlen);
1189 
1190 	ctx->inflight = true;
1191 
1192 	areq->areqlen = areqlen;
1193 	areq->sk = sk;
1194 	areq->first_rsgl.sgl.sgt.sgl = areq->first_rsgl.sgl.sgl;
1195 	INIT_LIST_HEAD(&areq->rsgl_list);
1196 
1197 	return areq;
1198 }
1199 EXPORT_SYMBOL_GPL(af_alg_alloc_areq);
1200 
1201 /**
1202  * af_alg_get_rsgl - create the RX SGL for the output data from the crypto
1203  *		     operation
1204  *
1205  * @sk: socket of connection to user space
1206  * @msg: user space message
1207  * @flags: flags used to invoke recvmsg with
1208  * @areq: instance of the cryptographic request that will hold the RX SGL
1209  * @maxsize: maximum number of bytes to be pulled from user space
1210  * @outlen: number of bytes in the RX SGL
1211  * Return: 0 on success, < 0 upon error
1212  */
1213 int af_alg_get_rsgl(struct sock *sk, struct msghdr *msg, int flags,
1214 		    struct af_alg_async_req *areq, size_t maxsize,
1215 		    size_t *outlen)
1216 {
1217 	struct alg_sock *ask = alg_sk(sk);
1218 	struct af_alg_ctx *ctx = ask->private;
1219 	size_t len = 0;
1220 
1221 	while (maxsize > len && msg_data_left(msg)) {
1222 		struct af_alg_rsgl *rsgl;
1223 		ssize_t err;
1224 		size_t seglen;
1225 
1226 		/* limit the amount of readable buffers */
1227 		if (!af_alg_readable(sk))
1228 			break;
1229 
1230 		seglen = min_t(size_t, (maxsize - len),
1231 			       msg_data_left(msg));
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