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