xref: /linux/net/tls/tls_main.c (revision 24aeeb107f0724fa15e16d5f28b39f3c3ecfc746)
1 /*
2  * Copyright (c) 2016-2017, Mellanox Technologies. All rights reserved.
3  * Copyright (c) 2016-2017, Dave Watson <davejwatson@fb.com>. All rights reserved.
4  *
5  * This software is available to you under a choice of one of two
6  * licenses.  You may choose to be licensed under the terms of the GNU
7  * General Public License (GPL) Version 2, available from the file
8  * COPYING in the main directory of this source tree, or the
9  * OpenIB.org BSD license below:
10  *
11  *     Redistribution and use in source and binary forms, with or
12  *     without modification, are permitted provided that the following
13  *     conditions are met:
14  *
15  *      - Redistributions of source code must retain the above
16  *        copyright notice, this list of conditions and the following
17  *        disclaimer.
18  *
19  *      - Redistributions in binary form must reproduce the above
20  *        copyright notice, this list of conditions and the following
21  *        disclaimer in the documentation and/or other materials
22  *        provided with the distribution.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31  * SOFTWARE.
32  */
33 
34 #include <linux/module.h>
35 
36 #include <net/tcp.h>
37 #include <net/inet_common.h>
38 #include <linux/highmem.h>
39 #include <linux/netdevice.h>
40 #include <linux/sched/signal.h>
41 #include <linux/inetdevice.h>
42 #include <linux/inet_diag.h>
43 
44 #include <net/snmp.h>
45 #include <net/tls.h>
46 #include <net/tls_toe.h>
47 
48 #include "tls.h"
49 
50 MODULE_AUTHOR("Mellanox Technologies");
51 MODULE_DESCRIPTION("Transport Layer Security Support");
52 MODULE_LICENSE("Dual BSD/GPL");
53 MODULE_ALIAS_TCP_ULP("tls");
54 
55 enum {
56 	TLSV4,
57 	TLSV6,
58 	TLS_NUM_PROTS,
59 };
60 
61 #define CIPHER_SIZE_DESC(cipher) [cipher] = { \
62 	.iv = cipher ## _IV_SIZE, \
63 	.key = cipher ## _KEY_SIZE, \
64 	.salt = cipher ## _SALT_SIZE, \
65 	.tag = cipher ## _TAG_SIZE, \
66 	.rec_seq = cipher ## _REC_SEQ_SIZE, \
67 }
68 
69 const struct tls_cipher_size_desc tls_cipher_size_desc[] = {
70 	CIPHER_SIZE_DESC(TLS_CIPHER_AES_GCM_128),
71 	CIPHER_SIZE_DESC(TLS_CIPHER_AES_GCM_256),
72 	CIPHER_SIZE_DESC(TLS_CIPHER_AES_CCM_128),
73 	CIPHER_SIZE_DESC(TLS_CIPHER_CHACHA20_POLY1305),
74 	CIPHER_SIZE_DESC(TLS_CIPHER_SM4_GCM),
75 	CIPHER_SIZE_DESC(TLS_CIPHER_SM4_CCM),
76 };
77 
78 static const struct proto *saved_tcpv6_prot;
79 static DEFINE_MUTEX(tcpv6_prot_mutex);
80 static const struct proto *saved_tcpv4_prot;
81 static DEFINE_MUTEX(tcpv4_prot_mutex);
82 static struct proto tls_prots[TLS_NUM_PROTS][TLS_NUM_CONFIG][TLS_NUM_CONFIG];
83 static struct proto_ops tls_proto_ops[TLS_NUM_PROTS][TLS_NUM_CONFIG][TLS_NUM_CONFIG];
84 static void build_protos(struct proto prot[TLS_NUM_CONFIG][TLS_NUM_CONFIG],
85 			 const struct proto *base);
86 
87 void update_sk_prot(struct sock *sk, struct tls_context *ctx)
88 {
89 	int ip_ver = sk->sk_family == AF_INET6 ? TLSV6 : TLSV4;
90 
91 	WRITE_ONCE(sk->sk_prot,
92 		   &tls_prots[ip_ver][ctx->tx_conf][ctx->rx_conf]);
93 	WRITE_ONCE(sk->sk_socket->ops,
94 		   &tls_proto_ops[ip_ver][ctx->tx_conf][ctx->rx_conf]);
95 }
96 
97 int wait_on_pending_writer(struct sock *sk, long *timeo)
98 {
99 	int rc = 0;
100 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
101 
102 	add_wait_queue(sk_sleep(sk), &wait);
103 	while (1) {
104 		if (!*timeo) {
105 			rc = -EAGAIN;
106 			break;
107 		}
108 
109 		if (signal_pending(current)) {
110 			rc = sock_intr_errno(*timeo);
111 			break;
112 		}
113 
114 		if (sk_wait_event(sk, timeo, !sk->sk_write_pending, &wait))
115 			break;
116 	}
117 	remove_wait_queue(sk_sleep(sk), &wait);
118 	return rc;
119 }
120 
121 int tls_push_sg(struct sock *sk,
122 		struct tls_context *ctx,
123 		struct scatterlist *sg,
124 		u16 first_offset,
125 		int flags)
126 {
127 	int sendpage_flags = flags | MSG_SENDPAGE_NOTLAST;
128 	int ret = 0;
129 	struct page *p;
130 	size_t size;
131 	int offset = first_offset;
132 
133 	size = sg->length - offset;
134 	offset += sg->offset;
135 
136 	ctx->in_tcp_sendpages = true;
137 	while (1) {
138 		if (sg_is_last(sg))
139 			sendpage_flags = flags;
140 
141 		/* is sending application-limited? */
142 		tcp_rate_check_app_limited(sk);
143 		p = sg_page(sg);
144 retry:
145 		ret = do_tcp_sendpages(sk, p, offset, size, sendpage_flags);
146 
147 		if (ret != size) {
148 			if (ret > 0) {
149 				offset += ret;
150 				size -= ret;
151 				goto retry;
152 			}
153 
154 			offset -= sg->offset;
155 			ctx->partially_sent_offset = offset;
156 			ctx->partially_sent_record = (void *)sg;
157 			ctx->in_tcp_sendpages = false;
158 			return ret;
159 		}
160 
161 		put_page(p);
162 		sk_mem_uncharge(sk, sg->length);
163 		sg = sg_next(sg);
164 		if (!sg)
165 			break;
166 
167 		offset = sg->offset;
168 		size = sg->length;
169 	}
170 
171 	ctx->in_tcp_sendpages = false;
172 
173 	return 0;
174 }
175 
176 static int tls_handle_open_record(struct sock *sk, int flags)
177 {
178 	struct tls_context *ctx = tls_get_ctx(sk);
179 
180 	if (tls_is_pending_open_record(ctx))
181 		return ctx->push_pending_record(sk, flags);
182 
183 	return 0;
184 }
185 
186 int tls_process_cmsg(struct sock *sk, struct msghdr *msg,
187 		     unsigned char *record_type)
188 {
189 	struct cmsghdr *cmsg;
190 	int rc = -EINVAL;
191 
192 	for_each_cmsghdr(cmsg, msg) {
193 		if (!CMSG_OK(msg, cmsg))
194 			return -EINVAL;
195 		if (cmsg->cmsg_level != SOL_TLS)
196 			continue;
197 
198 		switch (cmsg->cmsg_type) {
199 		case TLS_SET_RECORD_TYPE:
200 			if (cmsg->cmsg_len < CMSG_LEN(sizeof(*record_type)))
201 				return -EINVAL;
202 
203 			if (msg->msg_flags & MSG_MORE)
204 				return -EINVAL;
205 
206 			rc = tls_handle_open_record(sk, msg->msg_flags);
207 			if (rc)
208 				return rc;
209 
210 			*record_type = *(unsigned char *)CMSG_DATA(cmsg);
211 			rc = 0;
212 			break;
213 		default:
214 			return -EINVAL;
215 		}
216 	}
217 
218 	return rc;
219 }
220 
221 int tls_push_partial_record(struct sock *sk, struct tls_context *ctx,
222 			    int flags)
223 {
224 	struct scatterlist *sg;
225 	u16 offset;
226 
227 	sg = ctx->partially_sent_record;
228 	offset = ctx->partially_sent_offset;
229 
230 	ctx->partially_sent_record = NULL;
231 	return tls_push_sg(sk, ctx, sg, offset, flags);
232 }
233 
234 void tls_free_partial_record(struct sock *sk, struct tls_context *ctx)
235 {
236 	struct scatterlist *sg;
237 
238 	for (sg = ctx->partially_sent_record; sg; sg = sg_next(sg)) {
239 		put_page(sg_page(sg));
240 		sk_mem_uncharge(sk, sg->length);
241 	}
242 	ctx->partially_sent_record = NULL;
243 }
244 
245 static void tls_write_space(struct sock *sk)
246 {
247 	struct tls_context *ctx = tls_get_ctx(sk);
248 
249 	/* If in_tcp_sendpages call lower protocol write space handler
250 	 * to ensure we wake up any waiting operations there. For example
251 	 * if do_tcp_sendpages where to call sk_wait_event.
252 	 */
253 	if (ctx->in_tcp_sendpages) {
254 		ctx->sk_write_space(sk);
255 		return;
256 	}
257 
258 #ifdef CONFIG_TLS_DEVICE
259 	if (ctx->tx_conf == TLS_HW)
260 		tls_device_write_space(sk, ctx);
261 	else
262 #endif
263 		tls_sw_write_space(sk, ctx);
264 
265 	ctx->sk_write_space(sk);
266 }
267 
268 /**
269  * tls_ctx_free() - free TLS ULP context
270  * @sk:  socket to with @ctx is attached
271  * @ctx: TLS context structure
272  *
273  * Free TLS context. If @sk is %NULL caller guarantees that the socket
274  * to which @ctx was attached has no outstanding references.
275  */
276 void tls_ctx_free(struct sock *sk, struct tls_context *ctx)
277 {
278 	if (!ctx)
279 		return;
280 
281 	memzero_explicit(&ctx->crypto_send, sizeof(ctx->crypto_send));
282 	memzero_explicit(&ctx->crypto_recv, sizeof(ctx->crypto_recv));
283 	mutex_destroy(&ctx->tx_lock);
284 
285 	if (sk)
286 		kfree_rcu(ctx, rcu);
287 	else
288 		kfree(ctx);
289 }
290 
291 static void tls_sk_proto_cleanup(struct sock *sk,
292 				 struct tls_context *ctx, long timeo)
293 {
294 	if (unlikely(sk->sk_write_pending) &&
295 	    !wait_on_pending_writer(sk, &timeo))
296 		tls_handle_open_record(sk, 0);
297 
298 	/* We need these for tls_sw_fallback handling of other packets */
299 	if (ctx->tx_conf == TLS_SW) {
300 		kfree(ctx->tx.rec_seq);
301 		kfree(ctx->tx.iv);
302 		tls_sw_release_resources_tx(sk);
303 		TLS_DEC_STATS(sock_net(sk), LINUX_MIB_TLSCURRTXSW);
304 	} else if (ctx->tx_conf == TLS_HW) {
305 		tls_device_free_resources_tx(sk);
306 		TLS_DEC_STATS(sock_net(sk), LINUX_MIB_TLSCURRTXDEVICE);
307 	}
308 
309 	if (ctx->rx_conf == TLS_SW) {
310 		tls_sw_release_resources_rx(sk);
311 		TLS_DEC_STATS(sock_net(sk), LINUX_MIB_TLSCURRRXSW);
312 	} else if (ctx->rx_conf == TLS_HW) {
313 		tls_device_offload_cleanup_rx(sk);
314 		TLS_DEC_STATS(sock_net(sk), LINUX_MIB_TLSCURRRXDEVICE);
315 	}
316 }
317 
318 static void tls_sk_proto_close(struct sock *sk, long timeout)
319 {
320 	struct inet_connection_sock *icsk = inet_csk(sk);
321 	struct tls_context *ctx = tls_get_ctx(sk);
322 	long timeo = sock_sndtimeo(sk, 0);
323 	bool free_ctx;
324 
325 	if (ctx->tx_conf == TLS_SW)
326 		tls_sw_cancel_work_tx(ctx);
327 
328 	lock_sock(sk);
329 	free_ctx = ctx->tx_conf != TLS_HW && ctx->rx_conf != TLS_HW;
330 
331 	if (ctx->tx_conf != TLS_BASE || ctx->rx_conf != TLS_BASE)
332 		tls_sk_proto_cleanup(sk, ctx, timeo);
333 
334 	write_lock_bh(&sk->sk_callback_lock);
335 	if (free_ctx)
336 		rcu_assign_pointer(icsk->icsk_ulp_data, NULL);
337 	WRITE_ONCE(sk->sk_prot, ctx->sk_proto);
338 	if (sk->sk_write_space == tls_write_space)
339 		sk->sk_write_space = ctx->sk_write_space;
340 	write_unlock_bh(&sk->sk_callback_lock);
341 	release_sock(sk);
342 	if (ctx->tx_conf == TLS_SW)
343 		tls_sw_free_ctx_tx(ctx);
344 	if (ctx->rx_conf == TLS_SW || ctx->rx_conf == TLS_HW)
345 		tls_sw_strparser_done(ctx);
346 	if (ctx->rx_conf == TLS_SW)
347 		tls_sw_free_ctx_rx(ctx);
348 	ctx->sk_proto->close(sk, timeout);
349 
350 	if (free_ctx)
351 		tls_ctx_free(sk, ctx);
352 }
353 
354 static int do_tls_getsockopt_conf(struct sock *sk, char __user *optval,
355 				  int __user *optlen, int tx)
356 {
357 	int rc = 0;
358 	struct tls_context *ctx = tls_get_ctx(sk);
359 	struct tls_crypto_info *crypto_info;
360 	struct cipher_context *cctx;
361 	int len;
362 
363 	if (get_user(len, optlen))
364 		return -EFAULT;
365 
366 	if (!optval || (len < sizeof(*crypto_info))) {
367 		rc = -EINVAL;
368 		goto out;
369 	}
370 
371 	if (!ctx) {
372 		rc = -EBUSY;
373 		goto out;
374 	}
375 
376 	/* get user crypto info */
377 	if (tx) {
378 		crypto_info = &ctx->crypto_send.info;
379 		cctx = &ctx->tx;
380 	} else {
381 		crypto_info = &ctx->crypto_recv.info;
382 		cctx = &ctx->rx;
383 	}
384 
385 	if (!TLS_CRYPTO_INFO_READY(crypto_info)) {
386 		rc = -EBUSY;
387 		goto out;
388 	}
389 
390 	if (len == sizeof(*crypto_info)) {
391 		if (copy_to_user(optval, crypto_info, sizeof(*crypto_info)))
392 			rc = -EFAULT;
393 		goto out;
394 	}
395 
396 	switch (crypto_info->cipher_type) {
397 	case TLS_CIPHER_AES_GCM_128: {
398 		struct tls12_crypto_info_aes_gcm_128 *
399 		  crypto_info_aes_gcm_128 =
400 		  container_of(crypto_info,
401 			       struct tls12_crypto_info_aes_gcm_128,
402 			       info);
403 
404 		if (len != sizeof(*crypto_info_aes_gcm_128)) {
405 			rc = -EINVAL;
406 			goto out;
407 		}
408 		lock_sock(sk);
409 		memcpy(crypto_info_aes_gcm_128->iv,
410 		       cctx->iv + TLS_CIPHER_AES_GCM_128_SALT_SIZE,
411 		       TLS_CIPHER_AES_GCM_128_IV_SIZE);
412 		memcpy(crypto_info_aes_gcm_128->rec_seq, cctx->rec_seq,
413 		       TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
414 		release_sock(sk);
415 		if (copy_to_user(optval,
416 				 crypto_info_aes_gcm_128,
417 				 sizeof(*crypto_info_aes_gcm_128)))
418 			rc = -EFAULT;
419 		break;
420 	}
421 	case TLS_CIPHER_AES_GCM_256: {
422 		struct tls12_crypto_info_aes_gcm_256 *
423 		  crypto_info_aes_gcm_256 =
424 		  container_of(crypto_info,
425 			       struct tls12_crypto_info_aes_gcm_256,
426 			       info);
427 
428 		if (len != sizeof(*crypto_info_aes_gcm_256)) {
429 			rc = -EINVAL;
430 			goto out;
431 		}
432 		lock_sock(sk);
433 		memcpy(crypto_info_aes_gcm_256->iv,
434 		       cctx->iv + TLS_CIPHER_AES_GCM_256_SALT_SIZE,
435 		       TLS_CIPHER_AES_GCM_256_IV_SIZE);
436 		memcpy(crypto_info_aes_gcm_256->rec_seq, cctx->rec_seq,
437 		       TLS_CIPHER_AES_GCM_256_REC_SEQ_SIZE);
438 		release_sock(sk);
439 		if (copy_to_user(optval,
440 				 crypto_info_aes_gcm_256,
441 				 sizeof(*crypto_info_aes_gcm_256)))
442 			rc = -EFAULT;
443 		break;
444 	}
445 	case TLS_CIPHER_AES_CCM_128: {
446 		struct tls12_crypto_info_aes_ccm_128 *aes_ccm_128 =
447 			container_of(crypto_info,
448 				struct tls12_crypto_info_aes_ccm_128, info);
449 
450 		if (len != sizeof(*aes_ccm_128)) {
451 			rc = -EINVAL;
452 			goto out;
453 		}
454 		lock_sock(sk);
455 		memcpy(aes_ccm_128->iv,
456 		       cctx->iv + TLS_CIPHER_AES_CCM_128_SALT_SIZE,
457 		       TLS_CIPHER_AES_CCM_128_IV_SIZE);
458 		memcpy(aes_ccm_128->rec_seq, cctx->rec_seq,
459 		       TLS_CIPHER_AES_CCM_128_REC_SEQ_SIZE);
460 		release_sock(sk);
461 		if (copy_to_user(optval, aes_ccm_128, sizeof(*aes_ccm_128)))
462 			rc = -EFAULT;
463 		break;
464 	}
465 	case TLS_CIPHER_CHACHA20_POLY1305: {
466 		struct tls12_crypto_info_chacha20_poly1305 *chacha20_poly1305 =
467 			container_of(crypto_info,
468 				struct tls12_crypto_info_chacha20_poly1305,
469 				info);
470 
471 		if (len != sizeof(*chacha20_poly1305)) {
472 			rc = -EINVAL;
473 			goto out;
474 		}
475 		lock_sock(sk);
476 		memcpy(chacha20_poly1305->iv,
477 		       cctx->iv + TLS_CIPHER_CHACHA20_POLY1305_SALT_SIZE,
478 		       TLS_CIPHER_CHACHA20_POLY1305_IV_SIZE);
479 		memcpy(chacha20_poly1305->rec_seq, cctx->rec_seq,
480 		       TLS_CIPHER_CHACHA20_POLY1305_REC_SEQ_SIZE);
481 		release_sock(sk);
482 		if (copy_to_user(optval, chacha20_poly1305,
483 				sizeof(*chacha20_poly1305)))
484 			rc = -EFAULT;
485 		break;
486 	}
487 	case TLS_CIPHER_SM4_GCM: {
488 		struct tls12_crypto_info_sm4_gcm *sm4_gcm_info =
489 			container_of(crypto_info,
490 				struct tls12_crypto_info_sm4_gcm, info);
491 
492 		if (len != sizeof(*sm4_gcm_info)) {
493 			rc = -EINVAL;
494 			goto out;
495 		}
496 		lock_sock(sk);
497 		memcpy(sm4_gcm_info->iv,
498 		       cctx->iv + TLS_CIPHER_SM4_GCM_SALT_SIZE,
499 		       TLS_CIPHER_SM4_GCM_IV_SIZE);
500 		memcpy(sm4_gcm_info->rec_seq, cctx->rec_seq,
501 		       TLS_CIPHER_SM4_GCM_REC_SEQ_SIZE);
502 		release_sock(sk);
503 		if (copy_to_user(optval, sm4_gcm_info, sizeof(*sm4_gcm_info)))
504 			rc = -EFAULT;
505 		break;
506 	}
507 	case TLS_CIPHER_SM4_CCM: {
508 		struct tls12_crypto_info_sm4_ccm *sm4_ccm_info =
509 			container_of(crypto_info,
510 				struct tls12_crypto_info_sm4_ccm, info);
511 
512 		if (len != sizeof(*sm4_ccm_info)) {
513 			rc = -EINVAL;
514 			goto out;
515 		}
516 		lock_sock(sk);
517 		memcpy(sm4_ccm_info->iv,
518 		       cctx->iv + TLS_CIPHER_SM4_CCM_SALT_SIZE,
519 		       TLS_CIPHER_SM4_CCM_IV_SIZE);
520 		memcpy(sm4_ccm_info->rec_seq, cctx->rec_seq,
521 		       TLS_CIPHER_SM4_CCM_REC_SEQ_SIZE);
522 		release_sock(sk);
523 		if (copy_to_user(optval, sm4_ccm_info, sizeof(*sm4_ccm_info)))
524 			rc = -EFAULT;
525 		break;
526 	}
527 	default:
528 		rc = -EINVAL;
529 	}
530 
531 out:
532 	return rc;
533 }
534 
535 static int do_tls_getsockopt_tx_zc(struct sock *sk, char __user *optval,
536 				   int __user *optlen)
537 {
538 	struct tls_context *ctx = tls_get_ctx(sk);
539 	unsigned int value;
540 	int len;
541 
542 	if (get_user(len, optlen))
543 		return -EFAULT;
544 
545 	if (len != sizeof(value))
546 		return -EINVAL;
547 
548 	value = ctx->zerocopy_sendfile;
549 	if (copy_to_user(optval, &value, sizeof(value)))
550 		return -EFAULT;
551 
552 	return 0;
553 }
554 
555 static int do_tls_getsockopt_no_pad(struct sock *sk, char __user *optval,
556 				    int __user *optlen)
557 {
558 	struct tls_context *ctx = tls_get_ctx(sk);
559 	int value, len;
560 
561 	if (ctx->prot_info.version != TLS_1_3_VERSION)
562 		return -EINVAL;
563 
564 	if (get_user(len, optlen))
565 		return -EFAULT;
566 	if (len < sizeof(value))
567 		return -EINVAL;
568 
569 	lock_sock(sk);
570 	value = -EINVAL;
571 	if (ctx->rx_conf == TLS_SW || ctx->rx_conf == TLS_HW)
572 		value = ctx->rx_no_pad;
573 	release_sock(sk);
574 	if (value < 0)
575 		return value;
576 
577 	if (put_user(sizeof(value), optlen))
578 		return -EFAULT;
579 	if (copy_to_user(optval, &value, sizeof(value)))
580 		return -EFAULT;
581 
582 	return 0;
583 }
584 
585 static int do_tls_getsockopt(struct sock *sk, int optname,
586 			     char __user *optval, int __user *optlen)
587 {
588 	int rc = 0;
589 
590 	switch (optname) {
591 	case TLS_TX:
592 	case TLS_RX:
593 		rc = do_tls_getsockopt_conf(sk, optval, optlen,
594 					    optname == TLS_TX);
595 		break;
596 	case TLS_TX_ZEROCOPY_RO:
597 		rc = do_tls_getsockopt_tx_zc(sk, optval, optlen);
598 		break;
599 	case TLS_RX_EXPECT_NO_PAD:
600 		rc = do_tls_getsockopt_no_pad(sk, optval, optlen);
601 		break;
602 	default:
603 		rc = -ENOPROTOOPT;
604 		break;
605 	}
606 	return rc;
607 }
608 
609 static int tls_getsockopt(struct sock *sk, int level, int optname,
610 			  char __user *optval, int __user *optlen)
611 {
612 	struct tls_context *ctx = tls_get_ctx(sk);
613 
614 	if (level != SOL_TLS)
615 		return ctx->sk_proto->getsockopt(sk, level,
616 						 optname, optval, optlen);
617 
618 	return do_tls_getsockopt(sk, optname, optval, optlen);
619 }
620 
621 static int do_tls_setsockopt_conf(struct sock *sk, sockptr_t optval,
622 				  unsigned int optlen, int tx)
623 {
624 	struct tls_crypto_info *crypto_info;
625 	struct tls_crypto_info *alt_crypto_info;
626 	struct tls_context *ctx = tls_get_ctx(sk);
627 	size_t optsize;
628 	int rc = 0;
629 	int conf;
630 
631 	if (sockptr_is_null(optval) || (optlen < sizeof(*crypto_info)))
632 		return -EINVAL;
633 
634 	if (tx) {
635 		crypto_info = &ctx->crypto_send.info;
636 		alt_crypto_info = &ctx->crypto_recv.info;
637 	} else {
638 		crypto_info = &ctx->crypto_recv.info;
639 		alt_crypto_info = &ctx->crypto_send.info;
640 	}
641 
642 	/* Currently we don't support set crypto info more than one time */
643 	if (TLS_CRYPTO_INFO_READY(crypto_info))
644 		return -EBUSY;
645 
646 	rc = copy_from_sockptr(crypto_info, optval, sizeof(*crypto_info));
647 	if (rc) {
648 		rc = -EFAULT;
649 		goto err_crypto_info;
650 	}
651 
652 	/* check version */
653 	if (crypto_info->version != TLS_1_2_VERSION &&
654 	    crypto_info->version != TLS_1_3_VERSION) {
655 		rc = -EINVAL;
656 		goto err_crypto_info;
657 	}
658 
659 	/* Ensure that TLS version and ciphers are same in both directions */
660 	if (TLS_CRYPTO_INFO_READY(alt_crypto_info)) {
661 		if (alt_crypto_info->version != crypto_info->version ||
662 		    alt_crypto_info->cipher_type != crypto_info->cipher_type) {
663 			rc = -EINVAL;
664 			goto err_crypto_info;
665 		}
666 	}
667 
668 	switch (crypto_info->cipher_type) {
669 	case TLS_CIPHER_AES_GCM_128:
670 		optsize = sizeof(struct tls12_crypto_info_aes_gcm_128);
671 		break;
672 	case TLS_CIPHER_AES_GCM_256: {
673 		optsize = sizeof(struct tls12_crypto_info_aes_gcm_256);
674 		break;
675 	}
676 	case TLS_CIPHER_AES_CCM_128:
677 		optsize = sizeof(struct tls12_crypto_info_aes_ccm_128);
678 		break;
679 	case TLS_CIPHER_CHACHA20_POLY1305:
680 		optsize = sizeof(struct tls12_crypto_info_chacha20_poly1305);
681 		break;
682 	case TLS_CIPHER_SM4_GCM:
683 		optsize = sizeof(struct tls12_crypto_info_sm4_gcm);
684 		break;
685 	case TLS_CIPHER_SM4_CCM:
686 		optsize = sizeof(struct tls12_crypto_info_sm4_ccm);
687 		break;
688 	default:
689 		rc = -EINVAL;
690 		goto err_crypto_info;
691 	}
692 
693 	if (optlen != optsize) {
694 		rc = -EINVAL;
695 		goto err_crypto_info;
696 	}
697 
698 	rc = copy_from_sockptr_offset(crypto_info + 1, optval,
699 				      sizeof(*crypto_info),
700 				      optlen - sizeof(*crypto_info));
701 	if (rc) {
702 		rc = -EFAULT;
703 		goto err_crypto_info;
704 	}
705 
706 	if (tx) {
707 		rc = tls_set_device_offload(sk, ctx);
708 		conf = TLS_HW;
709 		if (!rc) {
710 			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSTXDEVICE);
711 			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSCURRTXDEVICE);
712 		} else {
713 			rc = tls_set_sw_offload(sk, ctx, 1);
714 			if (rc)
715 				goto err_crypto_info;
716 			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSTXSW);
717 			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSCURRTXSW);
718 			conf = TLS_SW;
719 		}
720 	} else {
721 		rc = tls_set_device_offload_rx(sk, ctx);
722 		conf = TLS_HW;
723 		if (!rc) {
724 			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSRXDEVICE);
725 			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSCURRRXDEVICE);
726 		} else {
727 			rc = tls_set_sw_offload(sk, ctx, 0);
728 			if (rc)
729 				goto err_crypto_info;
730 			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSRXSW);
731 			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSCURRRXSW);
732 			conf = TLS_SW;
733 		}
734 		tls_sw_strparser_arm(sk, ctx);
735 	}
736 
737 	if (tx)
738 		ctx->tx_conf = conf;
739 	else
740 		ctx->rx_conf = conf;
741 	update_sk_prot(sk, ctx);
742 	if (tx) {
743 		ctx->sk_write_space = sk->sk_write_space;
744 		sk->sk_write_space = tls_write_space;
745 	} else {
746 		struct tls_sw_context_rx *rx_ctx = tls_sw_ctx_rx(ctx);
747 
748 		tls_strp_check_rcv(&rx_ctx->strp);
749 	}
750 	return 0;
751 
752 err_crypto_info:
753 	memzero_explicit(crypto_info, sizeof(union tls_crypto_context));
754 	return rc;
755 }
756 
757 static int do_tls_setsockopt_tx_zc(struct sock *sk, sockptr_t optval,
758 				   unsigned int optlen)
759 {
760 	struct tls_context *ctx = tls_get_ctx(sk);
761 	unsigned int value;
762 
763 	if (sockptr_is_null(optval) || optlen != sizeof(value))
764 		return -EINVAL;
765 
766 	if (copy_from_sockptr(&value, optval, sizeof(value)))
767 		return -EFAULT;
768 
769 	if (value > 1)
770 		return -EINVAL;
771 
772 	ctx->zerocopy_sendfile = value;
773 
774 	return 0;
775 }
776 
777 static int do_tls_setsockopt_no_pad(struct sock *sk, sockptr_t optval,
778 				    unsigned int optlen)
779 {
780 	struct tls_context *ctx = tls_get_ctx(sk);
781 	u32 val;
782 	int rc;
783 
784 	if (ctx->prot_info.version != TLS_1_3_VERSION ||
785 	    sockptr_is_null(optval) || optlen < sizeof(val))
786 		return -EINVAL;
787 
788 	rc = copy_from_sockptr(&val, optval, sizeof(val));
789 	if (rc)
790 		return -EFAULT;
791 	if (val > 1)
792 		return -EINVAL;
793 	rc = check_zeroed_sockptr(optval, sizeof(val), optlen - sizeof(val));
794 	if (rc < 1)
795 		return rc == 0 ? -EINVAL : rc;
796 
797 	lock_sock(sk);
798 	rc = -EINVAL;
799 	if (ctx->rx_conf == TLS_SW || ctx->rx_conf == TLS_HW) {
800 		ctx->rx_no_pad = val;
801 		tls_update_rx_zc_capable(ctx);
802 		rc = 0;
803 	}
804 	release_sock(sk);
805 
806 	return rc;
807 }
808 
809 static int do_tls_setsockopt(struct sock *sk, int optname, sockptr_t optval,
810 			     unsigned int optlen)
811 {
812 	int rc = 0;
813 
814 	switch (optname) {
815 	case TLS_TX:
816 	case TLS_RX:
817 		lock_sock(sk);
818 		rc = do_tls_setsockopt_conf(sk, optval, optlen,
819 					    optname == TLS_TX);
820 		release_sock(sk);
821 		break;
822 	case TLS_TX_ZEROCOPY_RO:
823 		lock_sock(sk);
824 		rc = do_tls_setsockopt_tx_zc(sk, optval, optlen);
825 		release_sock(sk);
826 		break;
827 	case TLS_RX_EXPECT_NO_PAD:
828 		rc = do_tls_setsockopt_no_pad(sk, optval, optlen);
829 		break;
830 	default:
831 		rc = -ENOPROTOOPT;
832 		break;
833 	}
834 	return rc;
835 }
836 
837 static int tls_setsockopt(struct sock *sk, int level, int optname,
838 			  sockptr_t optval, unsigned int optlen)
839 {
840 	struct tls_context *ctx = tls_get_ctx(sk);
841 
842 	if (level != SOL_TLS)
843 		return ctx->sk_proto->setsockopt(sk, level, optname, optval,
844 						 optlen);
845 
846 	return do_tls_setsockopt(sk, optname, optval, optlen);
847 }
848 
849 struct tls_context *tls_ctx_create(struct sock *sk)
850 {
851 	struct inet_connection_sock *icsk = inet_csk(sk);
852 	struct tls_context *ctx;
853 
854 	ctx = kzalloc(sizeof(*ctx), GFP_ATOMIC);
855 	if (!ctx)
856 		return NULL;
857 
858 	mutex_init(&ctx->tx_lock);
859 	rcu_assign_pointer(icsk->icsk_ulp_data, ctx);
860 	ctx->sk_proto = READ_ONCE(sk->sk_prot);
861 	ctx->sk = sk;
862 	return ctx;
863 }
864 
865 static void build_proto_ops(struct proto_ops ops[TLS_NUM_CONFIG][TLS_NUM_CONFIG],
866 			    const struct proto_ops *base)
867 {
868 	ops[TLS_BASE][TLS_BASE] = *base;
869 
870 	ops[TLS_SW  ][TLS_BASE] = ops[TLS_BASE][TLS_BASE];
871 	ops[TLS_SW  ][TLS_BASE].sendpage_locked	= tls_sw_sendpage_locked;
872 
873 	ops[TLS_BASE][TLS_SW  ] = ops[TLS_BASE][TLS_BASE];
874 	ops[TLS_BASE][TLS_SW  ].splice_read	= tls_sw_splice_read;
875 
876 	ops[TLS_SW  ][TLS_SW  ] = ops[TLS_SW  ][TLS_BASE];
877 	ops[TLS_SW  ][TLS_SW  ].splice_read	= tls_sw_splice_read;
878 
879 #ifdef CONFIG_TLS_DEVICE
880 	ops[TLS_HW  ][TLS_BASE] = ops[TLS_BASE][TLS_BASE];
881 	ops[TLS_HW  ][TLS_BASE].sendpage_locked	= NULL;
882 
883 	ops[TLS_HW  ][TLS_SW  ] = ops[TLS_BASE][TLS_SW  ];
884 	ops[TLS_HW  ][TLS_SW  ].sendpage_locked	= NULL;
885 
886 	ops[TLS_BASE][TLS_HW  ] = ops[TLS_BASE][TLS_SW  ];
887 
888 	ops[TLS_SW  ][TLS_HW  ] = ops[TLS_SW  ][TLS_SW  ];
889 
890 	ops[TLS_HW  ][TLS_HW  ] = ops[TLS_HW  ][TLS_SW  ];
891 	ops[TLS_HW  ][TLS_HW  ].sendpage_locked	= NULL;
892 #endif
893 #ifdef CONFIG_TLS_TOE
894 	ops[TLS_HW_RECORD][TLS_HW_RECORD] = *base;
895 #endif
896 }
897 
898 static void tls_build_proto(struct sock *sk)
899 {
900 	int ip_ver = sk->sk_family == AF_INET6 ? TLSV6 : TLSV4;
901 	struct proto *prot = READ_ONCE(sk->sk_prot);
902 
903 	/* Build IPv6 TLS whenever the address of tcpv6 _prot changes */
904 	if (ip_ver == TLSV6 &&
905 	    unlikely(prot != smp_load_acquire(&saved_tcpv6_prot))) {
906 		mutex_lock(&tcpv6_prot_mutex);
907 		if (likely(prot != saved_tcpv6_prot)) {
908 			build_protos(tls_prots[TLSV6], prot);
909 			build_proto_ops(tls_proto_ops[TLSV6],
910 					sk->sk_socket->ops);
911 			smp_store_release(&saved_tcpv6_prot, prot);
912 		}
913 		mutex_unlock(&tcpv6_prot_mutex);
914 	}
915 
916 	if (ip_ver == TLSV4 &&
917 	    unlikely(prot != smp_load_acquire(&saved_tcpv4_prot))) {
918 		mutex_lock(&tcpv4_prot_mutex);
919 		if (likely(prot != saved_tcpv4_prot)) {
920 			build_protos(tls_prots[TLSV4], prot);
921 			build_proto_ops(tls_proto_ops[TLSV4],
922 					sk->sk_socket->ops);
923 			smp_store_release(&saved_tcpv4_prot, prot);
924 		}
925 		mutex_unlock(&tcpv4_prot_mutex);
926 	}
927 }
928 
929 static void build_protos(struct proto prot[TLS_NUM_CONFIG][TLS_NUM_CONFIG],
930 			 const struct proto *base)
931 {
932 	prot[TLS_BASE][TLS_BASE] = *base;
933 	prot[TLS_BASE][TLS_BASE].setsockopt	= tls_setsockopt;
934 	prot[TLS_BASE][TLS_BASE].getsockopt	= tls_getsockopt;
935 	prot[TLS_BASE][TLS_BASE].close		= tls_sk_proto_close;
936 
937 	prot[TLS_SW][TLS_BASE] = prot[TLS_BASE][TLS_BASE];
938 	prot[TLS_SW][TLS_BASE].sendmsg		= tls_sw_sendmsg;
939 	prot[TLS_SW][TLS_BASE].sendpage		= tls_sw_sendpage;
940 
941 	prot[TLS_BASE][TLS_SW] = prot[TLS_BASE][TLS_BASE];
942 	prot[TLS_BASE][TLS_SW].recvmsg		  = tls_sw_recvmsg;
943 	prot[TLS_BASE][TLS_SW].sock_is_readable   = tls_sw_sock_is_readable;
944 	prot[TLS_BASE][TLS_SW].close		  = tls_sk_proto_close;
945 
946 	prot[TLS_SW][TLS_SW] = prot[TLS_SW][TLS_BASE];
947 	prot[TLS_SW][TLS_SW].recvmsg		= tls_sw_recvmsg;
948 	prot[TLS_SW][TLS_SW].sock_is_readable   = tls_sw_sock_is_readable;
949 	prot[TLS_SW][TLS_SW].close		= tls_sk_proto_close;
950 
951 #ifdef CONFIG_TLS_DEVICE
952 	prot[TLS_HW][TLS_BASE] = prot[TLS_BASE][TLS_BASE];
953 	prot[TLS_HW][TLS_BASE].sendmsg		= tls_device_sendmsg;
954 	prot[TLS_HW][TLS_BASE].sendpage		= tls_device_sendpage;
955 
956 	prot[TLS_HW][TLS_SW] = prot[TLS_BASE][TLS_SW];
957 	prot[TLS_HW][TLS_SW].sendmsg		= tls_device_sendmsg;
958 	prot[TLS_HW][TLS_SW].sendpage		= tls_device_sendpage;
959 
960 	prot[TLS_BASE][TLS_HW] = prot[TLS_BASE][TLS_SW];
961 
962 	prot[TLS_SW][TLS_HW] = prot[TLS_SW][TLS_SW];
963 
964 	prot[TLS_HW][TLS_HW] = prot[TLS_HW][TLS_SW];
965 #endif
966 #ifdef CONFIG_TLS_TOE
967 	prot[TLS_HW_RECORD][TLS_HW_RECORD] = *base;
968 	prot[TLS_HW_RECORD][TLS_HW_RECORD].hash		= tls_toe_hash;
969 	prot[TLS_HW_RECORD][TLS_HW_RECORD].unhash	= tls_toe_unhash;
970 #endif
971 }
972 
973 static int tls_init(struct sock *sk)
974 {
975 	struct tls_context *ctx;
976 	int rc = 0;
977 
978 	tls_build_proto(sk);
979 
980 #ifdef CONFIG_TLS_TOE
981 	if (tls_toe_bypass(sk))
982 		return 0;
983 #endif
984 
985 	/* The TLS ulp is currently supported only for TCP sockets
986 	 * in ESTABLISHED state.
987 	 * Supporting sockets in LISTEN state will require us
988 	 * to modify the accept implementation to clone rather then
989 	 * share the ulp context.
990 	 */
991 	if (sk->sk_state != TCP_ESTABLISHED)
992 		return -ENOTCONN;
993 
994 	/* allocate tls context */
995 	write_lock_bh(&sk->sk_callback_lock);
996 	ctx = tls_ctx_create(sk);
997 	if (!ctx) {
998 		rc = -ENOMEM;
999 		goto out;
1000 	}
1001 
1002 	ctx->tx_conf = TLS_BASE;
1003 	ctx->rx_conf = TLS_BASE;
1004 	update_sk_prot(sk, ctx);
1005 out:
1006 	write_unlock_bh(&sk->sk_callback_lock);
1007 	return rc;
1008 }
1009 
1010 static void tls_update(struct sock *sk, struct proto *p,
1011 		       void (*write_space)(struct sock *sk))
1012 {
1013 	struct tls_context *ctx;
1014 
1015 	WARN_ON_ONCE(sk->sk_prot == p);
1016 
1017 	ctx = tls_get_ctx(sk);
1018 	if (likely(ctx)) {
1019 		ctx->sk_write_space = write_space;
1020 		ctx->sk_proto = p;
1021 	} else {
1022 		/* Pairs with lockless read in sk_clone_lock(). */
1023 		WRITE_ONCE(sk->sk_prot, p);
1024 		sk->sk_write_space = write_space;
1025 	}
1026 }
1027 
1028 static u16 tls_user_config(struct tls_context *ctx, bool tx)
1029 {
1030 	u16 config = tx ? ctx->tx_conf : ctx->rx_conf;
1031 
1032 	switch (config) {
1033 	case TLS_BASE:
1034 		return TLS_CONF_BASE;
1035 	case TLS_SW:
1036 		return TLS_CONF_SW;
1037 	case TLS_HW:
1038 		return TLS_CONF_HW;
1039 	case TLS_HW_RECORD:
1040 		return TLS_CONF_HW_RECORD;
1041 	}
1042 	return 0;
1043 }
1044 
1045 static int tls_get_info(const struct sock *sk, struct sk_buff *skb)
1046 {
1047 	u16 version, cipher_type;
1048 	struct tls_context *ctx;
1049 	struct nlattr *start;
1050 	int err;
1051 
1052 	start = nla_nest_start_noflag(skb, INET_ULP_INFO_TLS);
1053 	if (!start)
1054 		return -EMSGSIZE;
1055 
1056 	rcu_read_lock();
1057 	ctx = rcu_dereference(inet_csk(sk)->icsk_ulp_data);
1058 	if (!ctx) {
1059 		err = 0;
1060 		goto nla_failure;
1061 	}
1062 	version = ctx->prot_info.version;
1063 	if (version) {
1064 		err = nla_put_u16(skb, TLS_INFO_VERSION, version);
1065 		if (err)
1066 			goto nla_failure;
1067 	}
1068 	cipher_type = ctx->prot_info.cipher_type;
1069 	if (cipher_type) {
1070 		err = nla_put_u16(skb, TLS_INFO_CIPHER, cipher_type);
1071 		if (err)
1072 			goto nla_failure;
1073 	}
1074 	err = nla_put_u16(skb, TLS_INFO_TXCONF, tls_user_config(ctx, true));
1075 	if (err)
1076 		goto nla_failure;
1077 
1078 	err = nla_put_u16(skb, TLS_INFO_RXCONF, tls_user_config(ctx, false));
1079 	if (err)
1080 		goto nla_failure;
1081 
1082 	if (ctx->tx_conf == TLS_HW && ctx->zerocopy_sendfile) {
1083 		err = nla_put_flag(skb, TLS_INFO_ZC_RO_TX);
1084 		if (err)
1085 			goto nla_failure;
1086 	}
1087 	if (ctx->rx_no_pad) {
1088 		err = nla_put_flag(skb, TLS_INFO_RX_NO_PAD);
1089 		if (err)
1090 			goto nla_failure;
1091 	}
1092 
1093 	rcu_read_unlock();
1094 	nla_nest_end(skb, start);
1095 	return 0;
1096 
1097 nla_failure:
1098 	rcu_read_unlock();
1099 	nla_nest_cancel(skb, start);
1100 	return err;
1101 }
1102 
1103 static size_t tls_get_info_size(const struct sock *sk)
1104 {
1105 	size_t size = 0;
1106 
1107 	size += nla_total_size(0) +		/* INET_ULP_INFO_TLS */
1108 		nla_total_size(sizeof(u16)) +	/* TLS_INFO_VERSION */
1109 		nla_total_size(sizeof(u16)) +	/* TLS_INFO_CIPHER */
1110 		nla_total_size(sizeof(u16)) +	/* TLS_INFO_RXCONF */
1111 		nla_total_size(sizeof(u16)) +	/* TLS_INFO_TXCONF */
1112 		nla_total_size(0) +		/* TLS_INFO_ZC_RO_TX */
1113 		nla_total_size(0) +		/* TLS_INFO_RX_NO_PAD */
1114 		0;
1115 
1116 	return size;
1117 }
1118 
1119 static int __net_init tls_init_net(struct net *net)
1120 {
1121 	int err;
1122 
1123 	net->mib.tls_statistics = alloc_percpu(struct linux_tls_mib);
1124 	if (!net->mib.tls_statistics)
1125 		return -ENOMEM;
1126 
1127 	err = tls_proc_init(net);
1128 	if (err)
1129 		goto err_free_stats;
1130 
1131 	return 0;
1132 err_free_stats:
1133 	free_percpu(net->mib.tls_statistics);
1134 	return err;
1135 }
1136 
1137 static void __net_exit tls_exit_net(struct net *net)
1138 {
1139 	tls_proc_fini(net);
1140 	free_percpu(net->mib.tls_statistics);
1141 }
1142 
1143 static struct pernet_operations tls_proc_ops = {
1144 	.init = tls_init_net,
1145 	.exit = tls_exit_net,
1146 };
1147 
1148 static struct tcp_ulp_ops tcp_tls_ulp_ops __read_mostly = {
1149 	.name			= "tls",
1150 	.owner			= THIS_MODULE,
1151 	.init			= tls_init,
1152 	.update			= tls_update,
1153 	.get_info		= tls_get_info,
1154 	.get_info_size		= tls_get_info_size,
1155 };
1156 
1157 static int __init tls_register(void)
1158 {
1159 	int err;
1160 
1161 	err = register_pernet_subsys(&tls_proc_ops);
1162 	if (err)
1163 		return err;
1164 
1165 	err = tls_strp_dev_init();
1166 	if (err)
1167 		goto err_pernet;
1168 
1169 	err = tls_device_init();
1170 	if (err)
1171 		goto err_strp;
1172 
1173 	tcp_register_ulp(&tcp_tls_ulp_ops);
1174 
1175 	return 0;
1176 err_strp:
1177 	tls_strp_dev_exit();
1178 err_pernet:
1179 	unregister_pernet_subsys(&tls_proc_ops);
1180 	return err;
1181 }
1182 
1183 static void __exit tls_unregister(void)
1184 {
1185 	tcp_unregister_ulp(&tcp_tls_ulp_ops);
1186 	tls_strp_dev_exit();
1187 	tls_device_cleanup();
1188 	unregister_pernet_subsys(&tls_proc_ops);
1189 }
1190 
1191 module_init(tls_register);
1192 module_exit(tls_unregister);
1193