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