• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  * Copyright (c) 2016-2017, Lance Chao <lancerchao@fb.com>. All rights reserved.
5  * Copyright (c) 2016, Fridolin Pokorny <fridolin.pokorny@gmail.com>. All rights reserved.
6  * Copyright (c) 2016, Nikos Mavrogiannopoulos <nmav@gnutls.org>. All rights reserved.
7  * Copyright (c) 2018, Covalent IO, Inc. http://covalent.io
8  *
9  * This software is available to you under a choice of one of two
10  * licenses.  You may choose to be licensed under the terms of the GNU
11  * General Public License (GPL) Version 2, available from the file
12  * COPYING in the main directory of this source tree, or the
13  * OpenIB.org BSD license below:
14  *
15  *     Redistribution and use in source and binary forms, with or
16  *     without modification, are permitted provided that the following
17  *     conditions are met:
18  *
19  *      - Redistributions of source code must retain the above
20  *        copyright notice, this list of conditions and the following
21  *        disclaimer.
22  *
23  *      - Redistributions in binary form must reproduce the above
24  *        copyright notice, this list of conditions and the following
25  *        disclaimer in the documentation and/or other materials
26  *        provided with the distribution.
27  *
28  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
29  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
30  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
31  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
32  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
33  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
35  * SOFTWARE.
36  */
37 
38 #include <linux/bug.h>
39 #include <linux/sched/signal.h>
40 #include <linux/module.h>
41 #include <linux/kernel.h>
42 #include <linux/splice.h>
43 #include <crypto/aead.h>
44 
45 #include <net/strparser.h>
46 #include <net/tls.h>
47 
48 #include "tls.h"
49 
50 struct tls_decrypt_arg {
51 	struct_group(inargs,
52 	bool zc;
53 	bool async;
54 	u8 tail;
55 	);
56 
57 	struct sk_buff *skb;
58 };
59 
60 struct tls_decrypt_ctx {
61 	struct sock *sk;
62 	u8 iv[MAX_IV_SIZE];
63 	u8 aad[TLS_MAX_AAD_SIZE];
64 	u8 tail;
65 	bool free_sgout;
66 	struct scatterlist sg[];
67 };
68 
tls_err_abort(struct sock * sk,int err)69 noinline void tls_err_abort(struct sock *sk, int err)
70 {
71 	WARN_ON_ONCE(err >= 0);
72 	/* sk->sk_err should contain a positive error code. */
73 	WRITE_ONCE(sk->sk_err, -err);
74 	/* Paired with smp_rmb() in tcp_poll() */
75 	smp_wmb();
76 	sk_error_report(sk);
77 }
78 
__skb_nsg(struct sk_buff * skb,int offset,int len,unsigned int recursion_level)79 static int __skb_nsg(struct sk_buff *skb, int offset, int len,
80                      unsigned int recursion_level)
81 {
82         int start = skb_headlen(skb);
83         int i, chunk = start - offset;
84         struct sk_buff *frag_iter;
85         int elt = 0;
86 
87         if (unlikely(recursion_level >= 24))
88                 return -EMSGSIZE;
89 
90         if (chunk > 0) {
91                 if (chunk > len)
92                         chunk = len;
93                 elt++;
94                 len -= chunk;
95                 if (len == 0)
96                         return elt;
97                 offset += chunk;
98         }
99 
100         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
101                 int end;
102 
103                 WARN_ON(start > offset + len);
104 
105                 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
106                 chunk = end - offset;
107                 if (chunk > 0) {
108                         if (chunk > len)
109                                 chunk = len;
110                         elt++;
111                         len -= chunk;
112                         if (len == 0)
113                                 return elt;
114                         offset += chunk;
115                 }
116                 start = end;
117         }
118 
119         if (unlikely(skb_has_frag_list(skb))) {
120                 skb_walk_frags(skb, frag_iter) {
121                         int end, ret;
122 
123                         WARN_ON(start > offset + len);
124 
125                         end = start + frag_iter->len;
126                         chunk = end - offset;
127                         if (chunk > 0) {
128                                 if (chunk > len)
129                                         chunk = len;
130                                 ret = __skb_nsg(frag_iter, offset - start, chunk,
131                                                 recursion_level + 1);
132                                 if (unlikely(ret < 0))
133                                         return ret;
134                                 elt += ret;
135                                 len -= chunk;
136                                 if (len == 0)
137                                         return elt;
138                                 offset += chunk;
139                         }
140                         start = end;
141                 }
142         }
143         BUG_ON(len);
144         return elt;
145 }
146 
147 /* Return the number of scatterlist elements required to completely map the
148  * skb, or -EMSGSIZE if the recursion depth is exceeded.
149  */
skb_nsg(struct sk_buff * skb,int offset,int len)150 static int skb_nsg(struct sk_buff *skb, int offset, int len)
151 {
152         return __skb_nsg(skb, offset, len, 0);
153 }
154 
tls_padding_length(struct tls_prot_info * prot,struct sk_buff * skb,struct tls_decrypt_arg * darg)155 static int tls_padding_length(struct tls_prot_info *prot, struct sk_buff *skb,
156 			      struct tls_decrypt_arg *darg)
157 {
158 	struct strp_msg *rxm = strp_msg(skb);
159 	struct tls_msg *tlm = tls_msg(skb);
160 	int sub = 0;
161 
162 	/* Determine zero-padding length */
163 	if (prot->version == TLS_1_3_VERSION) {
164 		int offset = rxm->full_len - TLS_TAG_SIZE - 1;
165 		char content_type = darg->zc ? darg->tail : 0;
166 		int err;
167 
168 		while (content_type == 0) {
169 			if (offset < prot->prepend_size)
170 				return -EBADMSG;
171 			err = skb_copy_bits(skb, rxm->offset + offset,
172 					    &content_type, 1);
173 			if (err)
174 				return err;
175 			if (content_type)
176 				break;
177 			sub++;
178 			offset--;
179 		}
180 		tlm->control = content_type;
181 	}
182 	return sub;
183 }
184 
tls_decrypt_done(crypto_completion_data_t * data,int err)185 static void tls_decrypt_done(crypto_completion_data_t *data, int err)
186 {
187 	struct aead_request *aead_req = crypto_get_completion_data(data);
188 	struct crypto_aead *aead = crypto_aead_reqtfm(aead_req);
189 	struct scatterlist *sgout = aead_req->dst;
190 	struct tls_sw_context_rx *ctx;
191 	struct tls_decrypt_ctx *dctx;
192 	struct tls_context *tls_ctx;
193 	struct scatterlist *sg;
194 	unsigned int pages;
195 	struct sock *sk;
196 	int aead_size;
197 
198 	aead_size = sizeof(*aead_req) + crypto_aead_reqsize(aead);
199 	aead_size = ALIGN(aead_size, __alignof__(*dctx));
200 	dctx = (void *)((u8 *)aead_req + aead_size);
201 
202 	sk = dctx->sk;
203 	tls_ctx = tls_get_ctx(sk);
204 	ctx = tls_sw_ctx_rx(tls_ctx);
205 
206 	/* Propagate if there was an err */
207 	if (err) {
208 		if (err == -EBADMSG)
209 			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSDECRYPTERROR);
210 		ctx->async_wait.err = err;
211 		tls_err_abort(sk, err);
212 	}
213 
214 	/* Free the destination pages if skb was not decrypted inplace */
215 	if (dctx->free_sgout) {
216 		/* Skip the first S/G entry as it points to AAD */
217 		for_each_sg(sg_next(sgout), sg, UINT_MAX, pages) {
218 			if (!sg)
219 				break;
220 			put_page(sg_page(sg));
221 		}
222 	}
223 
224 	kfree(aead_req);
225 
226 	if (atomic_dec_and_test(&ctx->decrypt_pending))
227 		complete(&ctx->async_wait.completion);
228 }
229 
tls_decrypt_async_wait(struct tls_sw_context_rx * ctx)230 static int tls_decrypt_async_wait(struct tls_sw_context_rx *ctx)
231 {
232 	if (!atomic_dec_and_test(&ctx->decrypt_pending))
233 		crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
234 	atomic_inc(&ctx->decrypt_pending);
235 
236 	return ctx->async_wait.err;
237 }
238 
tls_do_decryption(struct sock * sk,struct scatterlist * sgin,struct scatterlist * sgout,char * iv_recv,size_t data_len,struct aead_request * aead_req,struct tls_decrypt_arg * darg)239 static int tls_do_decryption(struct sock *sk,
240 			     struct scatterlist *sgin,
241 			     struct scatterlist *sgout,
242 			     char *iv_recv,
243 			     size_t data_len,
244 			     struct aead_request *aead_req,
245 			     struct tls_decrypt_arg *darg)
246 {
247 	struct tls_context *tls_ctx = tls_get_ctx(sk);
248 	struct tls_prot_info *prot = &tls_ctx->prot_info;
249 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
250 	int ret;
251 
252 	aead_request_set_tfm(aead_req, ctx->aead_recv);
253 	aead_request_set_ad(aead_req, prot->aad_size);
254 	aead_request_set_crypt(aead_req, sgin, sgout,
255 			       data_len + prot->tag_size,
256 			       (u8 *)iv_recv);
257 
258 	if (darg->async) {
259 		aead_request_set_callback(aead_req,
260 					  CRYPTO_TFM_REQ_MAY_BACKLOG,
261 					  tls_decrypt_done, aead_req);
262 		DEBUG_NET_WARN_ON_ONCE(atomic_read(&ctx->decrypt_pending) < 1);
263 		atomic_inc(&ctx->decrypt_pending);
264 	} else {
265 		aead_request_set_callback(aead_req,
266 					  CRYPTO_TFM_REQ_MAY_BACKLOG,
267 					  crypto_req_done, &ctx->async_wait);
268 	}
269 
270 	ret = crypto_aead_decrypt(aead_req);
271 	if (ret == -EINPROGRESS) {
272 		if (darg->async)
273 			return 0;
274 
275 		ret = crypto_wait_req(ret, &ctx->async_wait);
276 	}
277 	darg->async = false;
278 
279 	return ret;
280 }
281 
tls_trim_both_msgs(struct sock * sk,int target_size)282 static void tls_trim_both_msgs(struct sock *sk, int target_size)
283 {
284 	struct tls_context *tls_ctx = tls_get_ctx(sk);
285 	struct tls_prot_info *prot = &tls_ctx->prot_info;
286 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
287 	struct tls_rec *rec = ctx->open_rec;
288 
289 	sk_msg_trim(sk, &rec->msg_plaintext, target_size);
290 	if (target_size > 0)
291 		target_size += prot->overhead_size;
292 	sk_msg_trim(sk, &rec->msg_encrypted, target_size);
293 }
294 
tls_alloc_encrypted_msg(struct sock * sk,int len)295 static int tls_alloc_encrypted_msg(struct sock *sk, int len)
296 {
297 	struct tls_context *tls_ctx = tls_get_ctx(sk);
298 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
299 	struct tls_rec *rec = ctx->open_rec;
300 	struct sk_msg *msg_en = &rec->msg_encrypted;
301 
302 	return sk_msg_alloc(sk, msg_en, len, 0);
303 }
304 
tls_clone_plaintext_msg(struct sock * sk,int required)305 static int tls_clone_plaintext_msg(struct sock *sk, int required)
306 {
307 	struct tls_context *tls_ctx = tls_get_ctx(sk);
308 	struct tls_prot_info *prot = &tls_ctx->prot_info;
309 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
310 	struct tls_rec *rec = ctx->open_rec;
311 	struct sk_msg *msg_pl = &rec->msg_plaintext;
312 	struct sk_msg *msg_en = &rec->msg_encrypted;
313 	int skip, len;
314 
315 	/* We add page references worth len bytes from encrypted sg
316 	 * at the end of plaintext sg. It is guaranteed that msg_en
317 	 * has enough required room (ensured by caller).
318 	 */
319 	len = required - msg_pl->sg.size;
320 
321 	/* Skip initial bytes in msg_en's data to be able to use
322 	 * same offset of both plain and encrypted data.
323 	 */
324 	skip = prot->prepend_size + msg_pl->sg.size;
325 
326 	return sk_msg_clone(sk, msg_pl, msg_en, skip, len);
327 }
328 
tls_get_rec(struct sock * sk)329 static struct tls_rec *tls_get_rec(struct sock *sk)
330 {
331 	struct tls_context *tls_ctx = tls_get_ctx(sk);
332 	struct tls_prot_info *prot = &tls_ctx->prot_info;
333 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
334 	struct sk_msg *msg_pl, *msg_en;
335 	struct tls_rec *rec;
336 	int mem_size;
337 
338 	mem_size = sizeof(struct tls_rec) + crypto_aead_reqsize(ctx->aead_send);
339 
340 	rec = kzalloc(mem_size, sk->sk_allocation);
341 	if (!rec)
342 		return NULL;
343 
344 	msg_pl = &rec->msg_plaintext;
345 	msg_en = &rec->msg_encrypted;
346 
347 	sk_msg_init(msg_pl);
348 	sk_msg_init(msg_en);
349 
350 	sg_init_table(rec->sg_aead_in, 2);
351 	sg_set_buf(&rec->sg_aead_in[0], rec->aad_space, prot->aad_size);
352 	sg_unmark_end(&rec->sg_aead_in[1]);
353 
354 	sg_init_table(rec->sg_aead_out, 2);
355 	sg_set_buf(&rec->sg_aead_out[0], rec->aad_space, prot->aad_size);
356 	sg_unmark_end(&rec->sg_aead_out[1]);
357 
358 	rec->sk = sk;
359 
360 	return rec;
361 }
362 
tls_free_rec(struct sock * sk,struct tls_rec * rec)363 static void tls_free_rec(struct sock *sk, struct tls_rec *rec)
364 {
365 	sk_msg_free(sk, &rec->msg_encrypted);
366 	sk_msg_free(sk, &rec->msg_plaintext);
367 	kfree(rec);
368 }
369 
tls_free_open_rec(struct sock * sk)370 static void tls_free_open_rec(struct sock *sk)
371 {
372 	struct tls_context *tls_ctx = tls_get_ctx(sk);
373 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
374 	struct tls_rec *rec = ctx->open_rec;
375 
376 	if (rec) {
377 		tls_free_rec(sk, rec);
378 		ctx->open_rec = NULL;
379 	}
380 }
381 
tls_tx_records(struct sock * sk,int flags)382 int tls_tx_records(struct sock *sk, int flags)
383 {
384 	struct tls_context *tls_ctx = tls_get_ctx(sk);
385 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
386 	struct tls_rec *rec, *tmp;
387 	struct sk_msg *msg_en;
388 	int tx_flags, rc = 0;
389 
390 	if (tls_is_partially_sent_record(tls_ctx)) {
391 		rec = list_first_entry(&ctx->tx_list,
392 				       struct tls_rec, list);
393 
394 		if (flags == -1)
395 			tx_flags = rec->tx_flags;
396 		else
397 			tx_flags = flags;
398 
399 		rc = tls_push_partial_record(sk, tls_ctx, tx_flags);
400 		if (rc)
401 			goto tx_err;
402 
403 		/* Full record has been transmitted.
404 		 * Remove the head of tx_list
405 		 */
406 		list_del(&rec->list);
407 		sk_msg_free(sk, &rec->msg_plaintext);
408 		kfree(rec);
409 	}
410 
411 	/* Tx all ready records */
412 	list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
413 		if (READ_ONCE(rec->tx_ready)) {
414 			if (flags == -1)
415 				tx_flags = rec->tx_flags;
416 			else
417 				tx_flags = flags;
418 
419 			msg_en = &rec->msg_encrypted;
420 			rc = tls_push_sg(sk, tls_ctx,
421 					 &msg_en->sg.data[msg_en->sg.curr],
422 					 0, tx_flags);
423 			if (rc)
424 				goto tx_err;
425 
426 			list_del(&rec->list);
427 			sk_msg_free(sk, &rec->msg_plaintext);
428 			kfree(rec);
429 		} else {
430 			break;
431 		}
432 	}
433 
434 tx_err:
435 	if (rc < 0 && rc != -EAGAIN)
436 		tls_err_abort(sk, -EBADMSG);
437 
438 	return rc;
439 }
440 
tls_encrypt_done(crypto_completion_data_t * data,int err)441 static void tls_encrypt_done(crypto_completion_data_t *data, int err)
442 {
443 	struct aead_request *aead_req = crypto_get_completion_data(data);
444 	struct tls_sw_context_tx *ctx;
445 	struct tls_context *tls_ctx;
446 	struct tls_prot_info *prot;
447 	struct scatterlist *sge;
448 	struct sk_msg *msg_en;
449 	struct tls_rec *rec;
450 	struct sock *sk;
451 
452 	rec = container_of(aead_req, struct tls_rec, aead_req);
453 	msg_en = &rec->msg_encrypted;
454 
455 	sk = rec->sk;
456 	tls_ctx = tls_get_ctx(sk);
457 	prot = &tls_ctx->prot_info;
458 	ctx = tls_sw_ctx_tx(tls_ctx);
459 
460 	sge = sk_msg_elem(msg_en, msg_en->sg.curr);
461 	sge->offset -= prot->prepend_size;
462 	sge->length += prot->prepend_size;
463 
464 	/* Check if error is previously set on socket */
465 	if (err || sk->sk_err) {
466 		rec = NULL;
467 
468 		/* If err is already set on socket, return the same code */
469 		if (sk->sk_err) {
470 			ctx->async_wait.err = -sk->sk_err;
471 		} else {
472 			ctx->async_wait.err = err;
473 			tls_err_abort(sk, err);
474 		}
475 	}
476 
477 	if (rec) {
478 		struct tls_rec *first_rec;
479 
480 		/* Mark the record as ready for transmission */
481 		smp_store_mb(rec->tx_ready, true);
482 
483 		/* If received record is at head of tx_list, schedule tx */
484 		first_rec = list_first_entry(&ctx->tx_list,
485 					     struct tls_rec, list);
486 		if (rec == first_rec) {
487 			/* Schedule the transmission */
488 			if (!test_and_set_bit(BIT_TX_SCHEDULED,
489 					      &ctx->tx_bitmask))
490 				schedule_delayed_work(&ctx->tx_work.work, 1);
491 		}
492 	}
493 
494 	if (atomic_dec_and_test(&ctx->encrypt_pending))
495 		complete(&ctx->async_wait.completion);
496 }
497 
tls_encrypt_async_wait(struct tls_sw_context_tx * ctx)498 static int tls_encrypt_async_wait(struct tls_sw_context_tx *ctx)
499 {
500 	if (!atomic_dec_and_test(&ctx->encrypt_pending))
501 		crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
502 	atomic_inc(&ctx->encrypt_pending);
503 
504 	return ctx->async_wait.err;
505 }
506 
tls_do_encryption(struct sock * sk,struct tls_context * tls_ctx,struct tls_sw_context_tx * ctx,struct aead_request * aead_req,size_t data_len,u32 start)507 static int tls_do_encryption(struct sock *sk,
508 			     struct tls_context *tls_ctx,
509 			     struct tls_sw_context_tx *ctx,
510 			     struct aead_request *aead_req,
511 			     size_t data_len, u32 start)
512 {
513 	struct tls_prot_info *prot = &tls_ctx->prot_info;
514 	struct tls_rec *rec = ctx->open_rec;
515 	struct sk_msg *msg_en = &rec->msg_encrypted;
516 	struct scatterlist *sge = sk_msg_elem(msg_en, start);
517 	int rc, iv_offset = 0;
518 
519 	/* For CCM based ciphers, first byte of IV is a constant */
520 	switch (prot->cipher_type) {
521 	case TLS_CIPHER_AES_CCM_128:
522 		rec->iv_data[0] = TLS_AES_CCM_IV_B0_BYTE;
523 		iv_offset = 1;
524 		break;
525 	case TLS_CIPHER_SM4_CCM:
526 		rec->iv_data[0] = TLS_SM4_CCM_IV_B0_BYTE;
527 		iv_offset = 1;
528 		break;
529 	}
530 
531 	memcpy(&rec->iv_data[iv_offset], tls_ctx->tx.iv,
532 	       prot->iv_size + prot->salt_size);
533 
534 	tls_xor_iv_with_seq(prot, rec->iv_data + iv_offset,
535 			    tls_ctx->tx.rec_seq);
536 
537 	sge->offset += prot->prepend_size;
538 	sge->length -= prot->prepend_size;
539 
540 	msg_en->sg.curr = start;
541 
542 	aead_request_set_tfm(aead_req, ctx->aead_send);
543 	aead_request_set_ad(aead_req, prot->aad_size);
544 	aead_request_set_crypt(aead_req, rec->sg_aead_in,
545 			       rec->sg_aead_out,
546 			       data_len, rec->iv_data);
547 
548 	aead_request_set_callback(aead_req, CRYPTO_TFM_REQ_MAY_BACKLOG,
549 				  tls_encrypt_done, aead_req);
550 
551 	/* Add the record in tx_list */
552 	list_add_tail((struct list_head *)&rec->list, &ctx->tx_list);
553 	DEBUG_NET_WARN_ON_ONCE(atomic_read(&ctx->encrypt_pending) < 1);
554 	atomic_inc(&ctx->encrypt_pending);
555 
556 	rc = crypto_aead_encrypt(aead_req);
557 	if (!rc || rc != -EINPROGRESS) {
558 		atomic_dec(&ctx->encrypt_pending);
559 		sge->offset -= prot->prepend_size;
560 		sge->length += prot->prepend_size;
561 	}
562 
563 	if (!rc) {
564 		WRITE_ONCE(rec->tx_ready, true);
565 	} else if (rc != -EINPROGRESS) {
566 		list_del(&rec->list);
567 		return rc;
568 	}
569 
570 	/* Unhook the record from context if encryption is not failure */
571 	ctx->open_rec = NULL;
572 	tls_advance_record_sn(sk, prot, &tls_ctx->tx);
573 	return rc;
574 }
575 
tls_split_open_record(struct sock * sk,struct tls_rec * from,struct tls_rec ** to,struct sk_msg * msg_opl,struct sk_msg * msg_oen,u32 split_point,u32 tx_overhead_size,u32 * orig_end)576 static int tls_split_open_record(struct sock *sk, struct tls_rec *from,
577 				 struct tls_rec **to, struct sk_msg *msg_opl,
578 				 struct sk_msg *msg_oen, u32 split_point,
579 				 u32 tx_overhead_size, u32 *orig_end)
580 {
581 	u32 i, j, bytes = 0, apply = msg_opl->apply_bytes;
582 	struct scatterlist *sge, *osge, *nsge;
583 	u32 orig_size = msg_opl->sg.size;
584 	struct scatterlist tmp = { };
585 	struct sk_msg *msg_npl;
586 	struct tls_rec *new;
587 	int ret;
588 
589 	new = tls_get_rec(sk);
590 	if (!new)
591 		return -ENOMEM;
592 	ret = sk_msg_alloc(sk, &new->msg_encrypted, msg_opl->sg.size +
593 			   tx_overhead_size, 0);
594 	if (ret < 0) {
595 		tls_free_rec(sk, new);
596 		return ret;
597 	}
598 
599 	*orig_end = msg_opl->sg.end;
600 	i = msg_opl->sg.start;
601 	sge = sk_msg_elem(msg_opl, i);
602 	while (apply && sge->length) {
603 		if (sge->length > apply) {
604 			u32 len = sge->length - apply;
605 
606 			get_page(sg_page(sge));
607 			sg_set_page(&tmp, sg_page(sge), len,
608 				    sge->offset + apply);
609 			sge->length = apply;
610 			bytes += apply;
611 			apply = 0;
612 		} else {
613 			apply -= sge->length;
614 			bytes += sge->length;
615 		}
616 
617 		sk_msg_iter_var_next(i);
618 		if (i == msg_opl->sg.end)
619 			break;
620 		sge = sk_msg_elem(msg_opl, i);
621 	}
622 
623 	msg_opl->sg.end = i;
624 	msg_opl->sg.curr = i;
625 	msg_opl->sg.copybreak = 0;
626 	msg_opl->apply_bytes = 0;
627 	msg_opl->sg.size = bytes;
628 
629 	msg_npl = &new->msg_plaintext;
630 	msg_npl->apply_bytes = apply;
631 	msg_npl->sg.size = orig_size - bytes;
632 
633 	j = msg_npl->sg.start;
634 	nsge = sk_msg_elem(msg_npl, j);
635 	if (tmp.length) {
636 		memcpy(nsge, &tmp, sizeof(*nsge));
637 		sk_msg_iter_var_next(j);
638 		nsge = sk_msg_elem(msg_npl, j);
639 	}
640 
641 	osge = sk_msg_elem(msg_opl, i);
642 	while (osge->length) {
643 		memcpy(nsge, osge, sizeof(*nsge));
644 		sg_unmark_end(nsge);
645 		sk_msg_iter_var_next(i);
646 		sk_msg_iter_var_next(j);
647 		if (i == *orig_end)
648 			break;
649 		osge = sk_msg_elem(msg_opl, i);
650 		nsge = sk_msg_elem(msg_npl, j);
651 	}
652 
653 	msg_npl->sg.end = j;
654 	msg_npl->sg.curr = j;
655 	msg_npl->sg.copybreak = 0;
656 
657 	*to = new;
658 	return 0;
659 }
660 
tls_merge_open_record(struct sock * sk,struct tls_rec * to,struct tls_rec * from,u32 orig_end)661 static void tls_merge_open_record(struct sock *sk, struct tls_rec *to,
662 				  struct tls_rec *from, u32 orig_end)
663 {
664 	struct sk_msg *msg_npl = &from->msg_plaintext;
665 	struct sk_msg *msg_opl = &to->msg_plaintext;
666 	struct scatterlist *osge, *nsge;
667 	u32 i, j;
668 
669 	i = msg_opl->sg.end;
670 	sk_msg_iter_var_prev(i);
671 	j = msg_npl->sg.start;
672 
673 	osge = sk_msg_elem(msg_opl, i);
674 	nsge = sk_msg_elem(msg_npl, j);
675 
676 	if (sg_page(osge) == sg_page(nsge) &&
677 	    osge->offset + osge->length == nsge->offset) {
678 		osge->length += nsge->length;
679 		put_page(sg_page(nsge));
680 	}
681 
682 	msg_opl->sg.end = orig_end;
683 	msg_opl->sg.curr = orig_end;
684 	msg_opl->sg.copybreak = 0;
685 	msg_opl->apply_bytes = msg_opl->sg.size + msg_npl->sg.size;
686 	msg_opl->sg.size += msg_npl->sg.size;
687 
688 	sk_msg_free(sk, &to->msg_encrypted);
689 	sk_msg_xfer_full(&to->msg_encrypted, &from->msg_encrypted);
690 
691 	kfree(from);
692 }
693 
tls_push_record(struct sock * sk,int flags,unsigned char record_type)694 static int tls_push_record(struct sock *sk, int flags,
695 			   unsigned char record_type)
696 {
697 	struct tls_context *tls_ctx = tls_get_ctx(sk);
698 	struct tls_prot_info *prot = &tls_ctx->prot_info;
699 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
700 	struct tls_rec *rec = ctx->open_rec, *tmp = NULL;
701 	u32 i, split_point, orig_end;
702 	struct sk_msg *msg_pl, *msg_en;
703 	struct aead_request *req;
704 	bool split;
705 	int rc;
706 
707 	if (!rec)
708 		return 0;
709 
710 	msg_pl = &rec->msg_plaintext;
711 	msg_en = &rec->msg_encrypted;
712 
713 	split_point = msg_pl->apply_bytes;
714 	split = split_point && split_point < msg_pl->sg.size;
715 	if (unlikely((!split &&
716 		      msg_pl->sg.size +
717 		      prot->overhead_size > msg_en->sg.size) ||
718 		     (split &&
719 		      split_point +
720 		      prot->overhead_size > msg_en->sg.size))) {
721 		split = true;
722 		split_point = msg_en->sg.size;
723 	}
724 	if (split) {
725 		rc = tls_split_open_record(sk, rec, &tmp, msg_pl, msg_en,
726 					   split_point, prot->overhead_size,
727 					   &orig_end);
728 		if (rc < 0)
729 			return rc;
730 		/* This can happen if above tls_split_open_record allocates
731 		 * a single large encryption buffer instead of two smaller
732 		 * ones. In this case adjust pointers and continue without
733 		 * split.
734 		 */
735 		if (!msg_pl->sg.size) {
736 			tls_merge_open_record(sk, rec, tmp, orig_end);
737 			msg_pl = &rec->msg_plaintext;
738 			msg_en = &rec->msg_encrypted;
739 			split = false;
740 		}
741 		sk_msg_trim(sk, msg_en, msg_pl->sg.size +
742 			    prot->overhead_size);
743 	}
744 
745 	rec->tx_flags = flags;
746 	req = &rec->aead_req;
747 
748 	i = msg_pl->sg.end;
749 	sk_msg_iter_var_prev(i);
750 
751 	rec->content_type = record_type;
752 	if (prot->version == TLS_1_3_VERSION) {
753 		/* Add content type to end of message.  No padding added */
754 		sg_set_buf(&rec->sg_content_type, &rec->content_type, 1);
755 		sg_mark_end(&rec->sg_content_type);
756 		sg_chain(msg_pl->sg.data, msg_pl->sg.end + 1,
757 			 &rec->sg_content_type);
758 	} else {
759 		sg_mark_end(sk_msg_elem(msg_pl, i));
760 	}
761 
762 	if (msg_pl->sg.end < msg_pl->sg.start) {
763 		sg_chain(&msg_pl->sg.data[msg_pl->sg.start],
764 			 MAX_SKB_FRAGS - msg_pl->sg.start + 1,
765 			 msg_pl->sg.data);
766 	}
767 
768 	i = msg_pl->sg.start;
769 	sg_chain(rec->sg_aead_in, 2, &msg_pl->sg.data[i]);
770 
771 	i = msg_en->sg.end;
772 	sk_msg_iter_var_prev(i);
773 	sg_mark_end(sk_msg_elem(msg_en, i));
774 
775 	i = msg_en->sg.start;
776 	sg_chain(rec->sg_aead_out, 2, &msg_en->sg.data[i]);
777 
778 	tls_make_aad(rec->aad_space, msg_pl->sg.size + prot->tail_size,
779 		     tls_ctx->tx.rec_seq, record_type, prot);
780 
781 	tls_fill_prepend(tls_ctx,
782 			 page_address(sg_page(&msg_en->sg.data[i])) +
783 			 msg_en->sg.data[i].offset,
784 			 msg_pl->sg.size + prot->tail_size,
785 			 record_type);
786 
787 	tls_ctx->pending_open_record_frags = false;
788 
789 	rc = tls_do_encryption(sk, tls_ctx, ctx, req,
790 			       msg_pl->sg.size + prot->tail_size, i);
791 	if (rc < 0) {
792 		if (rc != -EINPROGRESS) {
793 			tls_err_abort(sk, -EBADMSG);
794 			if (split) {
795 				tls_ctx->pending_open_record_frags = true;
796 				tls_merge_open_record(sk, rec, tmp, orig_end);
797 			}
798 		}
799 		ctx->async_capable = 1;
800 		return rc;
801 	} else if (split) {
802 		msg_pl = &tmp->msg_plaintext;
803 		msg_en = &tmp->msg_encrypted;
804 		sk_msg_trim(sk, msg_en, msg_pl->sg.size + prot->overhead_size);
805 		tls_ctx->pending_open_record_frags = true;
806 		ctx->open_rec = tmp;
807 	}
808 
809 	return tls_tx_records(sk, flags);
810 }
811 
bpf_exec_tx_verdict(struct sk_msg * msg,struct sock * sk,bool full_record,u8 record_type,ssize_t * copied,int flags)812 static int bpf_exec_tx_verdict(struct sk_msg *msg, struct sock *sk,
813 			       bool full_record, u8 record_type,
814 			       ssize_t *copied, int flags)
815 {
816 	struct tls_context *tls_ctx = tls_get_ctx(sk);
817 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
818 	struct sk_msg msg_redir = { };
819 	struct sk_psock *psock;
820 	struct sock *sk_redir;
821 	struct tls_rec *rec;
822 	bool enospc, policy, redir_ingress;
823 	int err = 0, send;
824 	u32 delta = 0;
825 
826 	policy = !(flags & MSG_SENDPAGE_NOPOLICY);
827 	psock = sk_psock_get(sk);
828 	if (!psock || !policy) {
829 		err = tls_push_record(sk, flags, record_type);
830 		if (err && err != -EINPROGRESS && sk->sk_err == EBADMSG) {
831 			*copied -= sk_msg_free(sk, msg);
832 			tls_free_open_rec(sk);
833 			err = -sk->sk_err;
834 		}
835 		if (psock)
836 			sk_psock_put(sk, psock);
837 		return err;
838 	}
839 more_data:
840 	enospc = sk_msg_full(msg);
841 	if (psock->eval == __SK_NONE) {
842 		delta = msg->sg.size;
843 		psock->eval = sk_psock_msg_verdict(sk, psock, msg);
844 		delta -= msg->sg.size;
845 	}
846 	if (msg->cork_bytes && msg->cork_bytes > msg->sg.size &&
847 	    !enospc && !full_record) {
848 		err = -ENOSPC;
849 		goto out_err;
850 	}
851 	msg->cork_bytes = 0;
852 	send = msg->sg.size;
853 	if (msg->apply_bytes && msg->apply_bytes < send)
854 		send = msg->apply_bytes;
855 
856 	switch (psock->eval) {
857 	case __SK_PASS:
858 		err = tls_push_record(sk, flags, record_type);
859 		if (err && err != -EINPROGRESS && sk->sk_err == EBADMSG) {
860 			*copied -= sk_msg_free(sk, msg);
861 			tls_free_open_rec(sk);
862 			err = -sk->sk_err;
863 			goto out_err;
864 		}
865 		break;
866 	case __SK_REDIRECT:
867 		redir_ingress = psock->redir_ingress;
868 		sk_redir = psock->sk_redir;
869 		memcpy(&msg_redir, msg, sizeof(*msg));
870 		if (msg->apply_bytes < send)
871 			msg->apply_bytes = 0;
872 		else
873 			msg->apply_bytes -= send;
874 		sk_msg_return_zero(sk, msg, send);
875 		msg->sg.size -= send;
876 		release_sock(sk);
877 		err = tcp_bpf_sendmsg_redir(sk_redir, redir_ingress,
878 					    &msg_redir, send, flags);
879 		lock_sock(sk);
880 		if (err < 0) {
881 			*copied -= sk_msg_free_nocharge(sk, &msg_redir);
882 			msg->sg.size = 0;
883 		}
884 		if (msg->sg.size == 0)
885 			tls_free_open_rec(sk);
886 		break;
887 	case __SK_DROP:
888 	default:
889 		sk_msg_free_partial(sk, msg, send);
890 		if (msg->apply_bytes < send)
891 			msg->apply_bytes = 0;
892 		else
893 			msg->apply_bytes -= send;
894 		if (msg->sg.size == 0)
895 			tls_free_open_rec(sk);
896 		*copied -= (send + delta);
897 		err = -EACCES;
898 	}
899 
900 	if (likely(!err)) {
901 		bool reset_eval = !ctx->open_rec;
902 
903 		rec = ctx->open_rec;
904 		if (rec) {
905 			msg = &rec->msg_plaintext;
906 			if (!msg->apply_bytes)
907 				reset_eval = true;
908 		}
909 		if (reset_eval) {
910 			psock->eval = __SK_NONE;
911 			if (psock->sk_redir) {
912 				sock_put(psock->sk_redir);
913 				psock->sk_redir = NULL;
914 			}
915 		}
916 		if (rec)
917 			goto more_data;
918 	}
919  out_err:
920 	sk_psock_put(sk, psock);
921 	return err;
922 }
923 
tls_sw_push_pending_record(struct sock * sk,int flags)924 static int tls_sw_push_pending_record(struct sock *sk, int flags)
925 {
926 	struct tls_context *tls_ctx = tls_get_ctx(sk);
927 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
928 	struct tls_rec *rec = ctx->open_rec;
929 	struct sk_msg *msg_pl;
930 	size_t copied;
931 
932 	if (!rec)
933 		return 0;
934 
935 	msg_pl = &rec->msg_plaintext;
936 	copied = msg_pl->sg.size;
937 	if (!copied)
938 		return 0;
939 
940 	return bpf_exec_tx_verdict(msg_pl, sk, true, TLS_RECORD_TYPE_DATA,
941 				   &copied, flags);
942 }
943 
tls_sw_sendmsg(struct sock * sk,struct msghdr * msg,size_t size)944 int tls_sw_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
945 {
946 	long timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
947 	struct tls_context *tls_ctx = tls_get_ctx(sk);
948 	struct tls_prot_info *prot = &tls_ctx->prot_info;
949 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
950 	bool async_capable = ctx->async_capable;
951 	unsigned char record_type = TLS_RECORD_TYPE_DATA;
952 	bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
953 	bool eor = !(msg->msg_flags & MSG_MORE);
954 	size_t try_to_copy;
955 	ssize_t copied = 0;
956 	struct sk_msg *msg_pl, *msg_en;
957 	struct tls_rec *rec;
958 	int required_size;
959 	int num_async = 0;
960 	bool full_record;
961 	int record_room;
962 	int num_zc = 0;
963 	int orig_size;
964 	int ret = 0;
965 
966 	if (msg->msg_flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
967 			       MSG_CMSG_COMPAT))
968 		return -EOPNOTSUPP;
969 
970 	ret = mutex_lock_interruptible(&tls_ctx->tx_lock);
971 	if (ret)
972 		return ret;
973 	lock_sock(sk);
974 
975 	if (unlikely(msg->msg_controllen)) {
976 		ret = tls_process_cmsg(sk, msg, &record_type);
977 		if (ret) {
978 			if (ret == -EINPROGRESS)
979 				num_async++;
980 			else if (ret != -EAGAIN)
981 				goto send_end;
982 		}
983 	}
984 
985 	while (msg_data_left(msg)) {
986 		if (sk->sk_err) {
987 			ret = -sk->sk_err;
988 			goto send_end;
989 		}
990 
991 		if (ctx->open_rec)
992 			rec = ctx->open_rec;
993 		else
994 			rec = ctx->open_rec = tls_get_rec(sk);
995 		if (!rec) {
996 			ret = -ENOMEM;
997 			goto send_end;
998 		}
999 
1000 		msg_pl = &rec->msg_plaintext;
1001 		msg_en = &rec->msg_encrypted;
1002 
1003 		orig_size = msg_pl->sg.size;
1004 		full_record = false;
1005 		try_to_copy = msg_data_left(msg);
1006 		record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
1007 		if (try_to_copy >= record_room) {
1008 			try_to_copy = record_room;
1009 			full_record = true;
1010 		}
1011 
1012 		required_size = msg_pl->sg.size + try_to_copy +
1013 				prot->overhead_size;
1014 
1015 		if (!sk_stream_memory_free(sk))
1016 			goto wait_for_sndbuf;
1017 
1018 alloc_encrypted:
1019 		ret = tls_alloc_encrypted_msg(sk, required_size);
1020 		if (ret) {
1021 			if (ret != -ENOSPC)
1022 				goto wait_for_memory;
1023 
1024 			/* Adjust try_to_copy according to the amount that was
1025 			 * actually allocated. The difference is due
1026 			 * to max sg elements limit
1027 			 */
1028 			try_to_copy -= required_size - msg_en->sg.size;
1029 			full_record = true;
1030 		}
1031 
1032 		if (!is_kvec && (full_record || eor) && !async_capable) {
1033 			u32 first = msg_pl->sg.end;
1034 
1035 			ret = sk_msg_zerocopy_from_iter(sk, &msg->msg_iter,
1036 							msg_pl, try_to_copy);
1037 			if (ret)
1038 				goto fallback_to_reg_send;
1039 
1040 			num_zc++;
1041 			copied += try_to_copy;
1042 
1043 			sk_msg_sg_copy_set(msg_pl, first);
1044 			ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1045 						  record_type, &copied,
1046 						  msg->msg_flags);
1047 			if (ret) {
1048 				if (ret == -EINPROGRESS)
1049 					num_async++;
1050 				else if (ret == -ENOMEM)
1051 					goto wait_for_memory;
1052 				else if (ctx->open_rec && ret == -ENOSPC)
1053 					goto rollback_iter;
1054 				else if (ret != -EAGAIN)
1055 					goto send_end;
1056 			}
1057 			continue;
1058 rollback_iter:
1059 			copied -= try_to_copy;
1060 			sk_msg_sg_copy_clear(msg_pl, first);
1061 			iov_iter_revert(&msg->msg_iter,
1062 					msg_pl->sg.size - orig_size);
1063 fallback_to_reg_send:
1064 			sk_msg_trim(sk, msg_pl, orig_size);
1065 		}
1066 
1067 		required_size = msg_pl->sg.size + try_to_copy;
1068 
1069 		ret = tls_clone_plaintext_msg(sk, required_size);
1070 		if (ret) {
1071 			if (ret != -ENOSPC)
1072 				goto send_end;
1073 
1074 			/* Adjust try_to_copy according to the amount that was
1075 			 * actually allocated. The difference is due
1076 			 * to max sg elements limit
1077 			 */
1078 			try_to_copy -= required_size - msg_pl->sg.size;
1079 			full_record = true;
1080 			sk_msg_trim(sk, msg_en,
1081 				    msg_pl->sg.size + prot->overhead_size);
1082 		}
1083 
1084 		if (try_to_copy) {
1085 			ret = sk_msg_memcopy_from_iter(sk, &msg->msg_iter,
1086 						       msg_pl, try_to_copy);
1087 			if (ret < 0)
1088 				goto trim_sgl;
1089 		}
1090 
1091 		/* Open records defined only if successfully copied, otherwise
1092 		 * we would trim the sg but not reset the open record frags.
1093 		 */
1094 		tls_ctx->pending_open_record_frags = true;
1095 		copied += try_to_copy;
1096 		if (full_record || eor) {
1097 			ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1098 						  record_type, &copied,
1099 						  msg->msg_flags);
1100 			if (ret) {
1101 				if (ret == -EINPROGRESS)
1102 					num_async++;
1103 				else if (ret == -ENOMEM)
1104 					goto wait_for_memory;
1105 				else if (ret != -EAGAIN) {
1106 					if (ret == -ENOSPC)
1107 						ret = 0;
1108 					goto send_end;
1109 				}
1110 			}
1111 		}
1112 
1113 		continue;
1114 
1115 wait_for_sndbuf:
1116 		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1117 wait_for_memory:
1118 		ret = sk_stream_wait_memory(sk, &timeo);
1119 		if (ret) {
1120 trim_sgl:
1121 			if (ctx->open_rec)
1122 				tls_trim_both_msgs(sk, orig_size);
1123 			goto send_end;
1124 		}
1125 
1126 		if (ctx->open_rec && msg_en->sg.size < required_size)
1127 			goto alloc_encrypted;
1128 	}
1129 
1130 	if (!num_async) {
1131 		goto send_end;
1132 	} else if (num_zc) {
1133 		int err;
1134 
1135 		/* Wait for pending encryptions to get completed */
1136 		err = tls_encrypt_async_wait(ctx);
1137 		if (err) {
1138 			ret = err;
1139 			copied = 0;
1140 		}
1141 	}
1142 
1143 	/* Transmit if any encryptions have completed */
1144 	if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
1145 		cancel_delayed_work(&ctx->tx_work.work);
1146 		tls_tx_records(sk, msg->msg_flags);
1147 	}
1148 
1149 send_end:
1150 	ret = sk_stream_error(sk, msg->msg_flags, ret);
1151 
1152 	release_sock(sk);
1153 	mutex_unlock(&tls_ctx->tx_lock);
1154 	return copied > 0 ? copied : ret;
1155 }
1156 
1157 /*
1158  * Handle unexpected EOF during splice without SPLICE_F_MORE set.
1159  */
tls_sw_splice_eof(struct socket * sock)1160 void tls_sw_splice_eof(struct socket *sock)
1161 {
1162 	struct sock *sk = sock->sk;
1163 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1164 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
1165 	struct tls_rec *rec;
1166 	struct sk_msg *msg_pl;
1167 	ssize_t copied = 0;
1168 	bool retrying = false;
1169 	int ret = 0;
1170 
1171 	if (!ctx->open_rec)
1172 		return;
1173 
1174 	mutex_lock(&tls_ctx->tx_lock);
1175 	lock_sock(sk);
1176 
1177 retry:
1178 	/* same checks as in tls_sw_push_pending_record() */
1179 	rec = ctx->open_rec;
1180 	if (!rec)
1181 		goto unlock;
1182 
1183 	msg_pl = &rec->msg_plaintext;
1184 	if (msg_pl->sg.size == 0)
1185 		goto unlock;
1186 
1187 	/* Check the BPF advisor and perform transmission. */
1188 	ret = bpf_exec_tx_verdict(msg_pl, sk, false, TLS_RECORD_TYPE_DATA,
1189 				  &copied, 0);
1190 	switch (ret) {
1191 	case 0:
1192 	case -EAGAIN:
1193 		if (retrying)
1194 			goto unlock;
1195 		retrying = true;
1196 		goto retry;
1197 	case -EINPROGRESS:
1198 		break;
1199 	default:
1200 		goto unlock;
1201 	}
1202 
1203 	/* Wait for pending encryptions to get completed */
1204 	if (tls_encrypt_async_wait(ctx))
1205 		goto unlock;
1206 
1207 	/* Transmit if any encryptions have completed */
1208 	if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
1209 		cancel_delayed_work(&ctx->tx_work.work);
1210 		tls_tx_records(sk, 0);
1211 	}
1212 
1213 unlock:
1214 	release_sock(sk);
1215 	mutex_unlock(&tls_ctx->tx_lock);
1216 }
1217 
tls_sw_do_sendpage(struct sock * sk,struct page * page,int offset,size_t size,int flags)1218 static int tls_sw_do_sendpage(struct sock *sk, struct page *page,
1219 			      int offset, size_t size, int flags)
1220 {
1221 	long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
1222 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1223 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
1224 	struct tls_prot_info *prot = &tls_ctx->prot_info;
1225 	unsigned char record_type = TLS_RECORD_TYPE_DATA;
1226 	struct sk_msg *msg_pl;
1227 	struct tls_rec *rec;
1228 	int num_async = 0;
1229 	ssize_t copied = 0;
1230 	bool full_record;
1231 	int record_room;
1232 	int ret = 0;
1233 	bool eor;
1234 
1235 	eor = !(flags & MSG_SENDPAGE_NOTLAST);
1236 	sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
1237 
1238 	/* Call the sk_stream functions to manage the sndbuf mem. */
1239 	while (size > 0) {
1240 		size_t copy, required_size;
1241 
1242 		if (sk->sk_err) {
1243 			ret = -sk->sk_err;
1244 			goto sendpage_end;
1245 		}
1246 
1247 		if (ctx->open_rec)
1248 			rec = ctx->open_rec;
1249 		else
1250 			rec = ctx->open_rec = tls_get_rec(sk);
1251 		if (!rec) {
1252 			ret = -ENOMEM;
1253 			goto sendpage_end;
1254 		}
1255 
1256 		msg_pl = &rec->msg_plaintext;
1257 
1258 		full_record = false;
1259 		record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
1260 		copy = size;
1261 		if (copy >= record_room) {
1262 			copy = record_room;
1263 			full_record = true;
1264 		}
1265 
1266 		required_size = msg_pl->sg.size + copy + prot->overhead_size;
1267 
1268 		if (!sk_stream_memory_free(sk))
1269 			goto wait_for_sndbuf;
1270 alloc_payload:
1271 		ret = tls_alloc_encrypted_msg(sk, required_size);
1272 		if (ret) {
1273 			if (ret != -ENOSPC)
1274 				goto wait_for_memory;
1275 
1276 			/* Adjust copy according to the amount that was
1277 			 * actually allocated. The difference is due
1278 			 * to max sg elements limit
1279 			 */
1280 			copy -= required_size - msg_pl->sg.size;
1281 			full_record = true;
1282 		}
1283 
1284 		sk_msg_page_add(msg_pl, page, copy, offset);
1285 		msg_pl->sg.copybreak = 0;
1286 		msg_pl->sg.curr = msg_pl->sg.end;
1287 		sk_mem_charge(sk, copy);
1288 
1289 		offset += copy;
1290 		size -= copy;
1291 		copied += copy;
1292 
1293 		tls_ctx->pending_open_record_frags = true;
1294 		if (full_record || eor || sk_msg_full(msg_pl)) {
1295 			ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1296 						  record_type, &copied, flags);
1297 			if (ret) {
1298 				if (ret == -EINPROGRESS)
1299 					num_async++;
1300 				else if (ret == -ENOMEM)
1301 					goto wait_for_memory;
1302 				else if (ret != -EAGAIN) {
1303 					if (ret == -ENOSPC)
1304 						ret = 0;
1305 					goto sendpage_end;
1306 				}
1307 			}
1308 		}
1309 		continue;
1310 wait_for_sndbuf:
1311 		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1312 wait_for_memory:
1313 		ret = sk_stream_wait_memory(sk, &timeo);
1314 		if (ret) {
1315 			if (ctx->open_rec)
1316 				tls_trim_both_msgs(sk, msg_pl->sg.size);
1317 			goto sendpage_end;
1318 		}
1319 
1320 		if (ctx->open_rec)
1321 			goto alloc_payload;
1322 	}
1323 
1324 	if (num_async) {
1325 		/* Transmit if any encryptions have completed */
1326 		if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
1327 			cancel_delayed_work(&ctx->tx_work.work);
1328 			tls_tx_records(sk, flags);
1329 		}
1330 	}
1331 sendpage_end:
1332 	ret = sk_stream_error(sk, flags, ret);
1333 	return copied > 0 ? copied : ret;
1334 }
1335 
tls_sw_sendpage_locked(struct sock * sk,struct page * page,int offset,size_t size,int flags)1336 int tls_sw_sendpage_locked(struct sock *sk, struct page *page,
1337 			   int offset, size_t size, int flags)
1338 {
1339 	if (flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
1340 		      MSG_SENDPAGE_NOTLAST | MSG_SENDPAGE_NOPOLICY |
1341 		      MSG_NO_SHARED_FRAGS))
1342 		return -EOPNOTSUPP;
1343 
1344 	return tls_sw_do_sendpage(sk, page, offset, size, flags);
1345 }
1346 
tls_sw_sendpage(struct sock * sk,struct page * page,int offset,size_t size,int flags)1347 int tls_sw_sendpage(struct sock *sk, struct page *page,
1348 		    int offset, size_t size, int flags)
1349 {
1350 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1351 	int ret;
1352 
1353 	if (flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
1354 		      MSG_SENDPAGE_NOTLAST | MSG_SENDPAGE_NOPOLICY))
1355 		return -EOPNOTSUPP;
1356 
1357 	ret = mutex_lock_interruptible(&tls_ctx->tx_lock);
1358 	if (ret)
1359 		return ret;
1360 	lock_sock(sk);
1361 	ret = tls_sw_do_sendpage(sk, page, offset, size, flags);
1362 	release_sock(sk);
1363 	mutex_unlock(&tls_ctx->tx_lock);
1364 	return ret;
1365 }
1366 
1367 static int
tls_rx_rec_wait(struct sock * sk,struct sk_psock * psock,bool nonblock,bool released)1368 tls_rx_rec_wait(struct sock *sk, struct sk_psock *psock, bool nonblock,
1369 		bool released)
1370 {
1371 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1372 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1373 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
1374 	long timeo;
1375 
1376 	timeo = sock_rcvtimeo(sk, nonblock);
1377 
1378 	while (!tls_strp_msg_ready(ctx)) {
1379 		if (!sk_psock_queue_empty(psock))
1380 			return 0;
1381 
1382 		if (sk->sk_err)
1383 			return sock_error(sk);
1384 
1385 		if (!skb_queue_empty(&sk->sk_receive_queue)) {
1386 			tls_strp_check_rcv(&ctx->strp);
1387 			if (tls_strp_msg_ready(ctx))
1388 				break;
1389 		}
1390 
1391 		if (sk->sk_shutdown & RCV_SHUTDOWN)
1392 			return 0;
1393 
1394 		if (sock_flag(sk, SOCK_DONE))
1395 			return 0;
1396 
1397 		if (!timeo)
1398 			return -EAGAIN;
1399 
1400 		released = true;
1401 		add_wait_queue(sk_sleep(sk), &wait);
1402 		sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1403 		sk_wait_event(sk, &timeo,
1404 			      tls_strp_msg_ready(ctx) ||
1405 			      !sk_psock_queue_empty(psock),
1406 			      &wait);
1407 		sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1408 		remove_wait_queue(sk_sleep(sk), &wait);
1409 
1410 		/* Handle signals */
1411 		if (signal_pending(current))
1412 			return sock_intr_errno(timeo);
1413 	}
1414 
1415 	tls_strp_msg_load(&ctx->strp, released);
1416 
1417 	return 1;
1418 }
1419 
tls_setup_from_iter(struct iov_iter * from,int length,int * pages_used,struct scatterlist * to,int to_max_pages)1420 static int tls_setup_from_iter(struct iov_iter *from,
1421 			       int length, int *pages_used,
1422 			       struct scatterlist *to,
1423 			       int to_max_pages)
1424 {
1425 	int rc = 0, i = 0, num_elem = *pages_used, maxpages;
1426 	struct page *pages[MAX_SKB_FRAGS];
1427 	unsigned int size = 0;
1428 	ssize_t copied, use;
1429 	size_t offset;
1430 
1431 	while (length > 0) {
1432 		i = 0;
1433 		maxpages = to_max_pages - num_elem;
1434 		if (maxpages == 0) {
1435 			rc = -EFAULT;
1436 			goto out;
1437 		}
1438 		copied = iov_iter_get_pages2(from, pages,
1439 					    length,
1440 					    maxpages, &offset);
1441 		if (copied <= 0) {
1442 			rc = -EFAULT;
1443 			goto out;
1444 		}
1445 
1446 		length -= copied;
1447 		size += copied;
1448 		while (copied) {
1449 			use = min_t(int, copied, PAGE_SIZE - offset);
1450 
1451 			sg_set_page(&to[num_elem],
1452 				    pages[i], use, offset);
1453 			sg_unmark_end(&to[num_elem]);
1454 			/* We do not uncharge memory from this API */
1455 
1456 			offset = 0;
1457 			copied -= use;
1458 
1459 			i++;
1460 			num_elem++;
1461 		}
1462 	}
1463 	/* Mark the end in the last sg entry if newly added */
1464 	if (num_elem > *pages_used)
1465 		sg_mark_end(&to[num_elem - 1]);
1466 out:
1467 	if (rc)
1468 		iov_iter_revert(from, size);
1469 	*pages_used = num_elem;
1470 
1471 	return rc;
1472 }
1473 
1474 static struct sk_buff *
tls_alloc_clrtxt_skb(struct sock * sk,struct sk_buff * skb,unsigned int full_len)1475 tls_alloc_clrtxt_skb(struct sock *sk, struct sk_buff *skb,
1476 		     unsigned int full_len)
1477 {
1478 	struct strp_msg *clr_rxm;
1479 	struct sk_buff *clr_skb;
1480 	int err;
1481 
1482 	clr_skb = alloc_skb_with_frags(0, full_len, TLS_PAGE_ORDER,
1483 				       &err, sk->sk_allocation);
1484 	if (!clr_skb)
1485 		return NULL;
1486 
1487 	skb_copy_header(clr_skb, skb);
1488 	clr_skb->len = full_len;
1489 	clr_skb->data_len = full_len;
1490 
1491 	clr_rxm = strp_msg(clr_skb);
1492 	clr_rxm->offset = 0;
1493 
1494 	return clr_skb;
1495 }
1496 
1497 /* Decrypt handlers
1498  *
1499  * tls_decrypt_sw() and tls_decrypt_device() are decrypt handlers.
1500  * They must transform the darg in/out argument are as follows:
1501  *       |          Input            |         Output
1502  * -------------------------------------------------------------------
1503  *    zc | Zero-copy decrypt allowed | Zero-copy performed
1504  * async | Async decrypt allowed     | Async crypto used / in progress
1505  *   skb |            *              | Output skb
1506  *
1507  * If ZC decryption was performed darg.skb will point to the input skb.
1508  */
1509 
1510 /* This function decrypts the input skb into either out_iov or in out_sg
1511  * or in skb buffers itself. The input parameter 'darg->zc' indicates if
1512  * zero-copy mode needs to be tried or not. With zero-copy mode, either
1513  * out_iov or out_sg must be non-NULL. In case both out_iov and out_sg are
1514  * NULL, then the decryption happens inside skb buffers itself, i.e.
1515  * zero-copy gets disabled and 'darg->zc' is updated.
1516  */
tls_decrypt_sg(struct sock * sk,struct iov_iter * out_iov,struct scatterlist * out_sg,struct tls_decrypt_arg * darg)1517 static int tls_decrypt_sg(struct sock *sk, struct iov_iter *out_iov,
1518 			  struct scatterlist *out_sg,
1519 			  struct tls_decrypt_arg *darg)
1520 {
1521 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1522 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1523 	struct tls_prot_info *prot = &tls_ctx->prot_info;
1524 	int n_sgin, n_sgout, aead_size, err, pages = 0;
1525 	struct sk_buff *skb = tls_strp_msg(ctx);
1526 	const struct strp_msg *rxm = strp_msg(skb);
1527 	const struct tls_msg *tlm = tls_msg(skb);
1528 	struct aead_request *aead_req;
1529 	struct scatterlist *sgin = NULL;
1530 	struct scatterlist *sgout = NULL;
1531 	const int data_len = rxm->full_len - prot->overhead_size;
1532 	int tail_pages = !!prot->tail_size;
1533 	struct tls_decrypt_ctx *dctx;
1534 	struct sk_buff *clear_skb;
1535 	int iv_offset = 0;
1536 	u8 *mem;
1537 
1538 	n_sgin = skb_nsg(skb, rxm->offset + prot->prepend_size,
1539 			 rxm->full_len - prot->prepend_size);
1540 	if (n_sgin < 1)
1541 		return n_sgin ?: -EBADMSG;
1542 
1543 	if (darg->zc && (out_iov || out_sg)) {
1544 		clear_skb = NULL;
1545 
1546 		if (out_iov)
1547 			n_sgout = 1 + tail_pages +
1548 				iov_iter_npages_cap(out_iov, INT_MAX, data_len);
1549 		else
1550 			n_sgout = sg_nents(out_sg);
1551 	} else {
1552 		darg->zc = false;
1553 
1554 		clear_skb = tls_alloc_clrtxt_skb(sk, skb, rxm->full_len);
1555 		if (!clear_skb)
1556 			return -ENOMEM;
1557 
1558 		n_sgout = 1 + skb_shinfo(clear_skb)->nr_frags;
1559 	}
1560 
1561 	/* Increment to accommodate AAD */
1562 	n_sgin = n_sgin + 1;
1563 
1564 	/* Allocate a single block of memory which contains
1565 	 *   aead_req || tls_decrypt_ctx.
1566 	 * Both structs are variable length.
1567 	 */
1568 	aead_size = sizeof(*aead_req) + crypto_aead_reqsize(ctx->aead_recv);
1569 	aead_size = ALIGN(aead_size, __alignof__(*dctx));
1570 	mem = kmalloc(aead_size + struct_size(dctx, sg, size_add(n_sgin, n_sgout)),
1571 		      sk->sk_allocation);
1572 	if (!mem) {
1573 		err = -ENOMEM;
1574 		goto exit_free_skb;
1575 	}
1576 
1577 	/* Segment the allocated memory */
1578 	aead_req = (struct aead_request *)mem;
1579 	dctx = (struct tls_decrypt_ctx *)(mem + aead_size);
1580 	dctx->sk = sk;
1581 	sgin = &dctx->sg[0];
1582 	sgout = &dctx->sg[n_sgin];
1583 
1584 	/* For CCM based ciphers, first byte of nonce+iv is a constant */
1585 	switch (prot->cipher_type) {
1586 	case TLS_CIPHER_AES_CCM_128:
1587 		dctx->iv[0] = TLS_AES_CCM_IV_B0_BYTE;
1588 		iv_offset = 1;
1589 		break;
1590 	case TLS_CIPHER_SM4_CCM:
1591 		dctx->iv[0] = TLS_SM4_CCM_IV_B0_BYTE;
1592 		iv_offset = 1;
1593 		break;
1594 	}
1595 
1596 	/* Prepare IV */
1597 	if (prot->version == TLS_1_3_VERSION ||
1598 	    prot->cipher_type == TLS_CIPHER_CHACHA20_POLY1305) {
1599 		memcpy(&dctx->iv[iv_offset], tls_ctx->rx.iv,
1600 		       prot->iv_size + prot->salt_size);
1601 	} else {
1602 		err = skb_copy_bits(skb, rxm->offset + TLS_HEADER_SIZE,
1603 				    &dctx->iv[iv_offset] + prot->salt_size,
1604 				    prot->iv_size);
1605 		if (err < 0)
1606 			goto exit_free;
1607 		memcpy(&dctx->iv[iv_offset], tls_ctx->rx.iv, prot->salt_size);
1608 	}
1609 	tls_xor_iv_with_seq(prot, &dctx->iv[iv_offset], tls_ctx->rx.rec_seq);
1610 
1611 	/* Prepare AAD */
1612 	tls_make_aad(dctx->aad, rxm->full_len - prot->overhead_size +
1613 		     prot->tail_size,
1614 		     tls_ctx->rx.rec_seq, tlm->control, prot);
1615 
1616 	/* Prepare sgin */
1617 	sg_init_table(sgin, n_sgin);
1618 	sg_set_buf(&sgin[0], dctx->aad, prot->aad_size);
1619 	err = skb_to_sgvec(skb, &sgin[1],
1620 			   rxm->offset + prot->prepend_size,
1621 			   rxm->full_len - prot->prepend_size);
1622 	if (err < 0)
1623 		goto exit_free;
1624 
1625 	if (clear_skb) {
1626 		sg_init_table(sgout, n_sgout);
1627 		sg_set_buf(&sgout[0], dctx->aad, prot->aad_size);
1628 
1629 		err = skb_to_sgvec(clear_skb, &sgout[1], prot->prepend_size,
1630 				   data_len + prot->tail_size);
1631 		if (err < 0)
1632 			goto exit_free;
1633 	} else if (out_iov) {
1634 		sg_init_table(sgout, n_sgout);
1635 		sg_set_buf(&sgout[0], dctx->aad, prot->aad_size);
1636 
1637 		err = tls_setup_from_iter(out_iov, data_len, &pages, &sgout[1],
1638 					  (n_sgout - 1 - tail_pages));
1639 		if (err < 0)
1640 			goto exit_free_pages;
1641 
1642 		if (prot->tail_size) {
1643 			sg_unmark_end(&sgout[pages]);
1644 			sg_set_buf(&sgout[pages + 1], &dctx->tail,
1645 				   prot->tail_size);
1646 			sg_mark_end(&sgout[pages + 1]);
1647 		}
1648 	} else if (out_sg) {
1649 		memcpy(sgout, out_sg, n_sgout * sizeof(*sgout));
1650 	}
1651 	dctx->free_sgout = !!pages;
1652 
1653 	/* Prepare and submit AEAD request */
1654 	err = tls_do_decryption(sk, sgin, sgout, dctx->iv,
1655 				data_len + prot->tail_size, aead_req, darg);
1656 	if (err)
1657 		goto exit_free_pages;
1658 
1659 	darg->skb = clear_skb ?: tls_strp_msg(ctx);
1660 	clear_skb = NULL;
1661 
1662 	if (unlikely(darg->async)) {
1663 		err = tls_strp_msg_hold(&ctx->strp, &ctx->async_hold);
1664 		if (err)
1665 			__skb_queue_tail(&ctx->async_hold, darg->skb);
1666 		return err;
1667 	}
1668 
1669 	if (prot->tail_size)
1670 		darg->tail = dctx->tail;
1671 
1672 exit_free_pages:
1673 	/* Release the pages in case iov was mapped to pages */
1674 	for (; pages > 0; pages--)
1675 		put_page(sg_page(&sgout[pages]));
1676 exit_free:
1677 	kfree(mem);
1678 exit_free_skb:
1679 	consume_skb(clear_skb);
1680 	return err;
1681 }
1682 
1683 static int
tls_decrypt_sw(struct sock * sk,struct tls_context * tls_ctx,struct msghdr * msg,struct tls_decrypt_arg * darg)1684 tls_decrypt_sw(struct sock *sk, struct tls_context *tls_ctx,
1685 	       struct msghdr *msg, struct tls_decrypt_arg *darg)
1686 {
1687 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1688 	struct tls_prot_info *prot = &tls_ctx->prot_info;
1689 	struct strp_msg *rxm;
1690 	int pad, err;
1691 
1692 	err = tls_decrypt_sg(sk, &msg->msg_iter, NULL, darg);
1693 	if (err < 0) {
1694 		if (err == -EBADMSG)
1695 			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSDECRYPTERROR);
1696 		return err;
1697 	}
1698 	/* keep going even for ->async, the code below is TLS 1.3 */
1699 
1700 	/* If opportunistic TLS 1.3 ZC failed retry without ZC */
1701 	if (unlikely(darg->zc && prot->version == TLS_1_3_VERSION &&
1702 		     darg->tail != TLS_RECORD_TYPE_DATA)) {
1703 		darg->zc = false;
1704 		if (!darg->tail)
1705 			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSRXNOPADVIOL);
1706 		TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSDECRYPTRETRY);
1707 		return tls_decrypt_sw(sk, tls_ctx, msg, darg);
1708 	}
1709 
1710 	pad = tls_padding_length(prot, darg->skb, darg);
1711 	if (pad < 0) {
1712 		if (darg->skb != tls_strp_msg(ctx))
1713 			consume_skb(darg->skb);
1714 		return pad;
1715 	}
1716 
1717 	rxm = strp_msg(darg->skb);
1718 	rxm->full_len -= pad;
1719 
1720 	return 0;
1721 }
1722 
1723 static int
tls_decrypt_device(struct sock * sk,struct msghdr * msg,struct tls_context * tls_ctx,struct tls_decrypt_arg * darg)1724 tls_decrypt_device(struct sock *sk, struct msghdr *msg,
1725 		   struct tls_context *tls_ctx, struct tls_decrypt_arg *darg)
1726 {
1727 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1728 	struct tls_prot_info *prot = &tls_ctx->prot_info;
1729 	struct strp_msg *rxm;
1730 	int pad, err;
1731 
1732 	if (tls_ctx->rx_conf != TLS_HW)
1733 		return 0;
1734 
1735 	err = tls_device_decrypted(sk, tls_ctx);
1736 	if (err <= 0)
1737 		return err;
1738 
1739 	pad = tls_padding_length(prot, tls_strp_msg(ctx), darg);
1740 	if (pad < 0)
1741 		return pad;
1742 
1743 	darg->async = false;
1744 	darg->skb = tls_strp_msg(ctx);
1745 	/* ->zc downgrade check, in case TLS 1.3 gets here */
1746 	darg->zc &= !(prot->version == TLS_1_3_VERSION &&
1747 		      tls_msg(darg->skb)->control != TLS_RECORD_TYPE_DATA);
1748 
1749 	rxm = strp_msg(darg->skb);
1750 	rxm->full_len -= pad;
1751 
1752 	if (!darg->zc) {
1753 		/* Non-ZC case needs a real skb */
1754 		darg->skb = tls_strp_msg_detach(ctx);
1755 		if (!darg->skb)
1756 			return -ENOMEM;
1757 	} else {
1758 		unsigned int off, len;
1759 
1760 		/* In ZC case nobody cares about the output skb.
1761 		 * Just copy the data here. Note the skb is not fully trimmed.
1762 		 */
1763 		off = rxm->offset + prot->prepend_size;
1764 		len = rxm->full_len - prot->overhead_size;
1765 
1766 		err = skb_copy_datagram_msg(darg->skb, off, msg, len);
1767 		if (err)
1768 			return err;
1769 	}
1770 	return 1;
1771 }
1772 
tls_rx_one_record(struct sock * sk,struct msghdr * msg,struct tls_decrypt_arg * darg)1773 static int tls_rx_one_record(struct sock *sk, struct msghdr *msg,
1774 			     struct tls_decrypt_arg *darg)
1775 {
1776 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1777 	struct tls_prot_info *prot = &tls_ctx->prot_info;
1778 	struct strp_msg *rxm;
1779 	int err;
1780 
1781 	err = tls_decrypt_device(sk, msg, tls_ctx, darg);
1782 	if (!err)
1783 		err = tls_decrypt_sw(sk, tls_ctx, msg, darg);
1784 	if (err < 0)
1785 		return err;
1786 
1787 	rxm = strp_msg(darg->skb);
1788 	rxm->offset += prot->prepend_size;
1789 	rxm->full_len -= prot->overhead_size;
1790 	tls_advance_record_sn(sk, prot, &tls_ctx->rx);
1791 
1792 	return 0;
1793 }
1794 
decrypt_skb(struct sock * sk,struct scatterlist * sgout)1795 int decrypt_skb(struct sock *sk, struct scatterlist *sgout)
1796 {
1797 	struct tls_decrypt_arg darg = { .zc = true, };
1798 
1799 	return tls_decrypt_sg(sk, NULL, sgout, &darg);
1800 }
1801 
tls_record_content_type(struct msghdr * msg,struct tls_msg * tlm,u8 * control)1802 static int tls_record_content_type(struct msghdr *msg, struct tls_msg *tlm,
1803 				   u8 *control)
1804 {
1805 	int err;
1806 
1807 	if (!*control) {
1808 		*control = tlm->control;
1809 		if (!*control)
1810 			return -EBADMSG;
1811 
1812 		err = put_cmsg(msg, SOL_TLS, TLS_GET_RECORD_TYPE,
1813 			       sizeof(*control), control);
1814 		if (*control != TLS_RECORD_TYPE_DATA) {
1815 			if (err || msg->msg_flags & MSG_CTRUNC)
1816 				return -EIO;
1817 		}
1818 	} else if (*control != tlm->control) {
1819 		return 0;
1820 	}
1821 
1822 	return 1;
1823 }
1824 
tls_rx_rec_done(struct tls_sw_context_rx * ctx)1825 static void tls_rx_rec_done(struct tls_sw_context_rx *ctx)
1826 {
1827 	tls_strp_msg_done(&ctx->strp);
1828 }
1829 
1830 /* This function traverses the rx_list in tls receive context to copies the
1831  * decrypted records into the buffer provided by caller zero copy is not
1832  * true. Further, the records are removed from the rx_list if it is not a peek
1833  * case and the record has been consumed completely.
1834  */
process_rx_list(struct tls_sw_context_rx * ctx,struct msghdr * msg,u8 * control,size_t skip,size_t len,bool is_peek,bool * more)1835 static int process_rx_list(struct tls_sw_context_rx *ctx,
1836 			   struct msghdr *msg,
1837 			   u8 *control,
1838 			   size_t skip,
1839 			   size_t len,
1840 			   bool is_peek,
1841 			   bool *more)
1842 {
1843 	struct sk_buff *skb = skb_peek(&ctx->rx_list);
1844 	struct tls_msg *tlm;
1845 	ssize_t copied = 0;
1846 	int err;
1847 
1848 	while (skip && skb) {
1849 		struct strp_msg *rxm = strp_msg(skb);
1850 		tlm = tls_msg(skb);
1851 
1852 		err = tls_record_content_type(msg, tlm, control);
1853 		if (err <= 0)
1854 			goto more;
1855 
1856 		if (skip < rxm->full_len)
1857 			break;
1858 
1859 		skip = skip - rxm->full_len;
1860 		skb = skb_peek_next(skb, &ctx->rx_list);
1861 	}
1862 
1863 	while (len && skb) {
1864 		struct sk_buff *next_skb;
1865 		struct strp_msg *rxm = strp_msg(skb);
1866 		int chunk = min_t(unsigned int, rxm->full_len - skip, len);
1867 
1868 		tlm = tls_msg(skb);
1869 
1870 		err = tls_record_content_type(msg, tlm, control);
1871 		if (err <= 0)
1872 			goto more;
1873 
1874 		err = skb_copy_datagram_msg(skb, rxm->offset + skip,
1875 					    msg, chunk);
1876 		if (err < 0)
1877 			goto more;
1878 
1879 		len = len - chunk;
1880 		copied = copied + chunk;
1881 
1882 		/* Consume the data from record if it is non-peek case*/
1883 		if (!is_peek) {
1884 			rxm->offset = rxm->offset + chunk;
1885 			rxm->full_len = rxm->full_len - chunk;
1886 
1887 			/* Return if there is unconsumed data in the record */
1888 			if (rxm->full_len - skip)
1889 				break;
1890 		}
1891 
1892 		/* The remaining skip-bytes must lie in 1st record in rx_list.
1893 		 * So from the 2nd record, 'skip' should be 0.
1894 		 */
1895 		skip = 0;
1896 
1897 		if (msg)
1898 			msg->msg_flags |= MSG_EOR;
1899 
1900 		next_skb = skb_peek_next(skb, &ctx->rx_list);
1901 
1902 		if (!is_peek) {
1903 			__skb_unlink(skb, &ctx->rx_list);
1904 			consume_skb(skb);
1905 		}
1906 
1907 		skb = next_skb;
1908 	}
1909 	err = 0;
1910 
1911 out:
1912 	return copied ? : err;
1913 more:
1914 	if (more)
1915 		*more = true;
1916 	goto out;
1917 }
1918 
1919 static bool
tls_read_flush_backlog(struct sock * sk,struct tls_prot_info * prot,size_t len_left,size_t decrypted,ssize_t done,size_t * flushed_at)1920 tls_read_flush_backlog(struct sock *sk, struct tls_prot_info *prot,
1921 		       size_t len_left, size_t decrypted, ssize_t done,
1922 		       size_t *flushed_at)
1923 {
1924 	size_t max_rec;
1925 
1926 	if (len_left <= decrypted)
1927 		return false;
1928 
1929 	max_rec = prot->overhead_size - prot->tail_size + TLS_MAX_PAYLOAD_SIZE;
1930 	if (done - *flushed_at < SZ_128K && tcp_inq(sk) > max_rec)
1931 		return false;
1932 
1933 	*flushed_at = done;
1934 	return sk_flush_backlog(sk);
1935 }
1936 
tls_rx_reader_acquire(struct sock * sk,struct tls_sw_context_rx * ctx,bool nonblock)1937 static int tls_rx_reader_acquire(struct sock *sk, struct tls_sw_context_rx *ctx,
1938 				 bool nonblock)
1939 {
1940 	long timeo;
1941 
1942 	timeo = sock_rcvtimeo(sk, nonblock);
1943 
1944 	while (unlikely(ctx->reader_present)) {
1945 		DEFINE_WAIT_FUNC(wait, woken_wake_function);
1946 
1947 		ctx->reader_contended = 1;
1948 
1949 		add_wait_queue(&ctx->wq, &wait);
1950 		sk_wait_event(sk, &timeo,
1951 			      !READ_ONCE(ctx->reader_present), &wait);
1952 		remove_wait_queue(&ctx->wq, &wait);
1953 
1954 		if (timeo <= 0)
1955 			return -EAGAIN;
1956 		if (signal_pending(current))
1957 			return sock_intr_errno(timeo);
1958 	}
1959 
1960 	WRITE_ONCE(ctx->reader_present, 1);
1961 
1962 	return 0;
1963 }
1964 
tls_rx_reader_lock(struct sock * sk,struct tls_sw_context_rx * ctx,bool nonblock)1965 static int tls_rx_reader_lock(struct sock *sk, struct tls_sw_context_rx *ctx,
1966 			      bool nonblock)
1967 {
1968 	int err;
1969 
1970 	lock_sock(sk);
1971 	err = tls_rx_reader_acquire(sk, ctx, nonblock);
1972 	if (err)
1973 		release_sock(sk);
1974 	return err;
1975 }
1976 
tls_rx_reader_release(struct sock * sk,struct tls_sw_context_rx * ctx)1977 static void tls_rx_reader_release(struct sock *sk, struct tls_sw_context_rx *ctx)
1978 {
1979 	if (unlikely(ctx->reader_contended)) {
1980 		if (wq_has_sleeper(&ctx->wq))
1981 			wake_up(&ctx->wq);
1982 		else
1983 			ctx->reader_contended = 0;
1984 
1985 		WARN_ON_ONCE(!ctx->reader_present);
1986 	}
1987 
1988 	WRITE_ONCE(ctx->reader_present, 0);
1989 }
1990 
tls_rx_reader_unlock(struct sock * sk,struct tls_sw_context_rx * ctx)1991 static void tls_rx_reader_unlock(struct sock *sk, struct tls_sw_context_rx *ctx)
1992 {
1993 	tls_rx_reader_release(sk, ctx);
1994 	release_sock(sk);
1995 }
1996 
tls_sw_recvmsg(struct sock * sk,struct msghdr * msg,size_t len,int flags,int * addr_len)1997 int tls_sw_recvmsg(struct sock *sk,
1998 		   struct msghdr *msg,
1999 		   size_t len,
2000 		   int flags,
2001 		   int *addr_len)
2002 {
2003 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2004 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2005 	struct tls_prot_info *prot = &tls_ctx->prot_info;
2006 	ssize_t decrypted = 0, async_copy_bytes = 0;
2007 	struct sk_psock *psock;
2008 	unsigned char control = 0;
2009 	size_t flushed_at = 0;
2010 	struct strp_msg *rxm;
2011 	struct tls_msg *tlm;
2012 	ssize_t copied = 0;
2013 	bool async = false;
2014 	int target, err;
2015 	bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
2016 	bool is_peek = flags & MSG_PEEK;
2017 	bool rx_more = false;
2018 	bool released = true;
2019 	bool bpf_strp_enabled;
2020 	bool zc_capable;
2021 
2022 	if (unlikely(flags & MSG_ERRQUEUE))
2023 		return sock_recv_errqueue(sk, msg, len, SOL_IP, IP_RECVERR);
2024 
2025 	psock = sk_psock_get(sk);
2026 	err = tls_rx_reader_lock(sk, ctx, flags & MSG_DONTWAIT);
2027 	if (err < 0)
2028 		return err;
2029 	bpf_strp_enabled = sk_psock_strp_enabled(psock);
2030 
2031 	/* If crypto failed the connection is broken */
2032 	err = ctx->async_wait.err;
2033 	if (err)
2034 		goto end;
2035 
2036 	/* Process pending decrypted records. It must be non-zero-copy */
2037 	err = process_rx_list(ctx, msg, &control, 0, len, is_peek, &rx_more);
2038 	if (err < 0)
2039 		goto end;
2040 
2041 	copied = err;
2042 	if (len <= copied || (copied && control != TLS_RECORD_TYPE_DATA) || rx_more)
2043 		goto end;
2044 
2045 	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
2046 	len = len - copied;
2047 
2048 	zc_capable = !bpf_strp_enabled && !is_kvec && !is_peek &&
2049 		ctx->zc_capable;
2050 	decrypted = 0;
2051 	while (len && (decrypted + copied < target || tls_strp_msg_ready(ctx))) {
2052 		struct tls_decrypt_arg darg;
2053 		int to_decrypt, chunk;
2054 
2055 		err = tls_rx_rec_wait(sk, psock, flags & MSG_DONTWAIT,
2056 				      released);
2057 		if (err <= 0) {
2058 			if (psock) {
2059 				chunk = sk_msg_recvmsg(sk, psock, msg, len,
2060 						       flags);
2061 				if (chunk > 0) {
2062 					decrypted += chunk;
2063 					len -= chunk;
2064 					continue;
2065 				}
2066 			}
2067 			goto recv_end;
2068 		}
2069 
2070 		memset(&darg.inargs, 0, sizeof(darg.inargs));
2071 
2072 		rxm = strp_msg(tls_strp_msg(ctx));
2073 		tlm = tls_msg(tls_strp_msg(ctx));
2074 
2075 		to_decrypt = rxm->full_len - prot->overhead_size;
2076 
2077 		if (zc_capable && to_decrypt <= len &&
2078 		    tlm->control == TLS_RECORD_TYPE_DATA)
2079 			darg.zc = true;
2080 
2081 		/* Do not use async mode if record is non-data */
2082 		if (tlm->control == TLS_RECORD_TYPE_DATA && !bpf_strp_enabled)
2083 			darg.async = ctx->async_capable;
2084 		else
2085 			darg.async = false;
2086 
2087 		err = tls_rx_one_record(sk, msg, &darg);
2088 		if (err < 0) {
2089 			tls_err_abort(sk, -EBADMSG);
2090 			goto recv_end;
2091 		}
2092 
2093 		async |= darg.async;
2094 
2095 		/* If the type of records being processed is not known yet,
2096 		 * set it to record type just dequeued. If it is already known,
2097 		 * but does not match the record type just dequeued, go to end.
2098 		 * We always get record type here since for tls1.2, record type
2099 		 * is known just after record is dequeued from stream parser.
2100 		 * For tls1.3, we disable async.
2101 		 */
2102 		err = tls_record_content_type(msg, tls_msg(darg.skb), &control);
2103 		if (err <= 0) {
2104 			DEBUG_NET_WARN_ON_ONCE(darg.zc);
2105 			tls_rx_rec_done(ctx);
2106 put_on_rx_list_err:
2107 			__skb_queue_tail(&ctx->rx_list, darg.skb);
2108 			goto recv_end;
2109 		}
2110 
2111 		/* periodically flush backlog, and feed strparser */
2112 		released = tls_read_flush_backlog(sk, prot, len, to_decrypt,
2113 						  decrypted + copied,
2114 						  &flushed_at);
2115 
2116 		/* TLS 1.3 may have updated the length by more than overhead */
2117 		rxm = strp_msg(darg.skb);
2118 		chunk = rxm->full_len;
2119 		tls_rx_rec_done(ctx);
2120 
2121 		if (!darg.zc) {
2122 			bool partially_consumed = chunk > len;
2123 			struct sk_buff *skb = darg.skb;
2124 
2125 			DEBUG_NET_WARN_ON_ONCE(darg.skb == ctx->strp.anchor);
2126 
2127 			if (async) {
2128 				/* TLS 1.2-only, to_decrypt must be text len */
2129 				chunk = min_t(int, to_decrypt, len);
2130 				async_copy_bytes += chunk;
2131 put_on_rx_list:
2132 				decrypted += chunk;
2133 				len -= chunk;
2134 				__skb_queue_tail(&ctx->rx_list, skb);
2135 				if (unlikely(control != TLS_RECORD_TYPE_DATA))
2136 					break;
2137 				continue;
2138 			}
2139 
2140 			if (bpf_strp_enabled) {
2141 				released = true;
2142 				err = sk_psock_tls_strp_read(psock, skb);
2143 				if (err != __SK_PASS) {
2144 					rxm->offset = rxm->offset + rxm->full_len;
2145 					rxm->full_len = 0;
2146 					if (err == __SK_DROP)
2147 						consume_skb(skb);
2148 					continue;
2149 				}
2150 			}
2151 
2152 			if (partially_consumed)
2153 				chunk = len;
2154 
2155 			err = skb_copy_datagram_msg(skb, rxm->offset,
2156 						    msg, chunk);
2157 			if (err < 0)
2158 				goto put_on_rx_list_err;
2159 
2160 			if (is_peek)
2161 				goto put_on_rx_list;
2162 
2163 			if (partially_consumed) {
2164 				rxm->offset += chunk;
2165 				rxm->full_len -= chunk;
2166 				goto put_on_rx_list;
2167 			}
2168 
2169 			consume_skb(skb);
2170 		}
2171 
2172 		decrypted += chunk;
2173 		len -= chunk;
2174 
2175 		/* Return full control message to userspace before trying
2176 		 * to parse another message type
2177 		 */
2178 		msg->msg_flags |= MSG_EOR;
2179 		if (control != TLS_RECORD_TYPE_DATA)
2180 			break;
2181 	}
2182 
2183 recv_end:
2184 	if (async) {
2185 		int ret;
2186 
2187 		/* Wait for all previously submitted records to be decrypted */
2188 		ret = tls_decrypt_async_wait(ctx);
2189 		__skb_queue_purge(&ctx->async_hold);
2190 
2191 		if (ret) {
2192 			if (err >= 0 || err == -EINPROGRESS)
2193 				err = ret;
2194 			decrypted = 0;
2195 			goto end;
2196 		}
2197 
2198 		/* Drain records from the rx_list & copy if required */
2199 		if (is_peek || is_kvec)
2200 			err = process_rx_list(ctx, msg, &control, copied,
2201 					      decrypted, is_peek, NULL);
2202 		else
2203 			err = process_rx_list(ctx, msg, &control, 0,
2204 					      async_copy_bytes, is_peek, NULL);
2205 	}
2206 
2207 	copied += decrypted;
2208 
2209 end:
2210 	tls_rx_reader_unlock(sk, ctx);
2211 	if (psock)
2212 		sk_psock_put(sk, psock);
2213 	return copied ? : err;
2214 }
2215 
tls_sw_splice_read(struct socket * sock,loff_t * ppos,struct pipe_inode_info * pipe,size_t len,unsigned int flags)2216 ssize_t tls_sw_splice_read(struct socket *sock,  loff_t *ppos,
2217 			   struct pipe_inode_info *pipe,
2218 			   size_t len, unsigned int flags)
2219 {
2220 	struct tls_context *tls_ctx = tls_get_ctx(sock->sk);
2221 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2222 	struct strp_msg *rxm = NULL;
2223 	struct sock *sk = sock->sk;
2224 	struct tls_msg *tlm;
2225 	struct sk_buff *skb;
2226 	ssize_t copied = 0;
2227 	int chunk;
2228 	int err;
2229 
2230 	err = tls_rx_reader_lock(sk, ctx, flags & SPLICE_F_NONBLOCK);
2231 	if (err < 0)
2232 		return err;
2233 
2234 	if (!skb_queue_empty(&ctx->rx_list)) {
2235 		skb = __skb_dequeue(&ctx->rx_list);
2236 	} else {
2237 		struct tls_decrypt_arg darg;
2238 
2239 		err = tls_rx_rec_wait(sk, NULL, flags & SPLICE_F_NONBLOCK,
2240 				      true);
2241 		if (err <= 0)
2242 			goto splice_read_end;
2243 
2244 		memset(&darg.inargs, 0, sizeof(darg.inargs));
2245 
2246 		err = tls_rx_one_record(sk, NULL, &darg);
2247 		if (err < 0) {
2248 			tls_err_abort(sk, -EBADMSG);
2249 			goto splice_read_end;
2250 		}
2251 
2252 		tls_rx_rec_done(ctx);
2253 		skb = darg.skb;
2254 	}
2255 
2256 	rxm = strp_msg(skb);
2257 	tlm = tls_msg(skb);
2258 
2259 	/* splice does not support reading control messages */
2260 	if (tlm->control != TLS_RECORD_TYPE_DATA) {
2261 		err = -EINVAL;
2262 		goto splice_requeue;
2263 	}
2264 
2265 	chunk = min_t(unsigned int, rxm->full_len, len);
2266 	copied = skb_splice_bits(skb, sk, rxm->offset, pipe, chunk, flags);
2267 	if (copied < 0)
2268 		goto splice_requeue;
2269 
2270 	if (chunk < rxm->full_len) {
2271 		rxm->offset += len;
2272 		rxm->full_len -= len;
2273 		goto splice_requeue;
2274 	}
2275 
2276 	consume_skb(skb);
2277 
2278 splice_read_end:
2279 	tls_rx_reader_unlock(sk, ctx);
2280 	return copied ? : err;
2281 
2282 splice_requeue:
2283 	__skb_queue_head(&ctx->rx_list, skb);
2284 	goto splice_read_end;
2285 }
2286 
tls_sw_sock_is_readable(struct sock * sk)2287 bool tls_sw_sock_is_readable(struct sock *sk)
2288 {
2289 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2290 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2291 	bool ingress_empty = true;
2292 	struct sk_psock *psock;
2293 
2294 	rcu_read_lock();
2295 	psock = sk_psock(sk);
2296 	if (psock)
2297 		ingress_empty = list_empty(&psock->ingress_msg);
2298 	rcu_read_unlock();
2299 
2300 	return !ingress_empty || tls_strp_msg_ready(ctx) ||
2301 		!skb_queue_empty(&ctx->rx_list);
2302 }
2303 
tls_rx_msg_size(struct tls_strparser * strp,struct sk_buff * skb)2304 int tls_rx_msg_size(struct tls_strparser *strp, struct sk_buff *skb)
2305 {
2306 	struct tls_context *tls_ctx = tls_get_ctx(strp->sk);
2307 	struct tls_prot_info *prot = &tls_ctx->prot_info;
2308 	char header[TLS_HEADER_SIZE + MAX_IV_SIZE];
2309 	size_t cipher_overhead;
2310 	size_t data_len = 0;
2311 	int ret;
2312 
2313 	/* Verify that we have a full TLS header, or wait for more data */
2314 	if (strp->stm.offset + prot->prepend_size > skb->len)
2315 		return 0;
2316 
2317 	/* Sanity-check size of on-stack buffer. */
2318 	if (WARN_ON(prot->prepend_size > sizeof(header))) {
2319 		ret = -EINVAL;
2320 		goto read_failure;
2321 	}
2322 
2323 	/* Linearize header to local buffer */
2324 	ret = skb_copy_bits(skb, strp->stm.offset, header, prot->prepend_size);
2325 	if (ret < 0)
2326 		goto read_failure;
2327 
2328 	strp->mark = header[0];
2329 
2330 	data_len = ((header[4] & 0xFF) | (header[3] << 8));
2331 
2332 	cipher_overhead = prot->tag_size;
2333 	if (prot->version != TLS_1_3_VERSION &&
2334 	    prot->cipher_type != TLS_CIPHER_CHACHA20_POLY1305)
2335 		cipher_overhead += prot->iv_size;
2336 
2337 	if (data_len > TLS_MAX_PAYLOAD_SIZE + cipher_overhead +
2338 	    prot->tail_size) {
2339 		ret = -EMSGSIZE;
2340 		goto read_failure;
2341 	}
2342 	if (data_len < cipher_overhead) {
2343 		ret = -EBADMSG;
2344 		goto read_failure;
2345 	}
2346 
2347 	/* Note that both TLS1.3 and TLS1.2 use TLS_1_2 version here */
2348 	if (header[1] != TLS_1_2_VERSION_MINOR ||
2349 	    header[2] != TLS_1_2_VERSION_MAJOR) {
2350 		ret = -EINVAL;
2351 		goto read_failure;
2352 	}
2353 
2354 	tls_device_rx_resync_new_rec(strp->sk, data_len + TLS_HEADER_SIZE,
2355 				     TCP_SKB_CB(skb)->seq + strp->stm.offset);
2356 	return data_len + TLS_HEADER_SIZE;
2357 
2358 read_failure:
2359 	tls_err_abort(strp->sk, ret);
2360 
2361 	return ret;
2362 }
2363 
tls_rx_msg_ready(struct tls_strparser * strp)2364 void tls_rx_msg_ready(struct tls_strparser *strp)
2365 {
2366 	struct tls_sw_context_rx *ctx;
2367 
2368 	ctx = container_of(strp, struct tls_sw_context_rx, strp);
2369 	ctx->saved_data_ready(strp->sk);
2370 }
2371 
tls_data_ready(struct sock * sk)2372 static void tls_data_ready(struct sock *sk)
2373 {
2374 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2375 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2376 	struct sk_psock *psock;
2377 	gfp_t alloc_save;
2378 
2379 	alloc_save = sk->sk_allocation;
2380 	sk->sk_allocation = GFP_ATOMIC;
2381 	tls_strp_data_ready(&ctx->strp);
2382 	sk->sk_allocation = alloc_save;
2383 
2384 	psock = sk_psock_get(sk);
2385 	if (psock) {
2386 		if (!list_empty(&psock->ingress_msg))
2387 			ctx->saved_data_ready(sk);
2388 		sk_psock_put(sk, psock);
2389 	}
2390 }
2391 
tls_sw_cancel_work_tx(struct tls_context * tls_ctx)2392 void tls_sw_cancel_work_tx(struct tls_context *tls_ctx)
2393 {
2394 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2395 
2396 	set_bit(BIT_TX_CLOSING, &ctx->tx_bitmask);
2397 	set_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask);
2398 	cancel_delayed_work_sync(&ctx->tx_work.work);
2399 }
2400 
tls_sw_release_resources_tx(struct sock * sk)2401 void tls_sw_release_resources_tx(struct sock *sk)
2402 {
2403 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2404 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2405 	struct tls_rec *rec, *tmp;
2406 
2407 	/* Wait for any pending async encryptions to complete */
2408 	tls_encrypt_async_wait(ctx);
2409 
2410 	tls_tx_records(sk, -1);
2411 
2412 	/* Free up un-sent records in tx_list. First, free
2413 	 * the partially sent record if any at head of tx_list.
2414 	 */
2415 	if (tls_ctx->partially_sent_record) {
2416 		tls_free_partial_record(sk, tls_ctx);
2417 		rec = list_first_entry(&ctx->tx_list,
2418 				       struct tls_rec, list);
2419 		list_del(&rec->list);
2420 		sk_msg_free(sk, &rec->msg_plaintext);
2421 		kfree(rec);
2422 	}
2423 
2424 	list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
2425 		list_del(&rec->list);
2426 		sk_msg_free(sk, &rec->msg_encrypted);
2427 		sk_msg_free(sk, &rec->msg_plaintext);
2428 		kfree(rec);
2429 	}
2430 
2431 	crypto_free_aead(ctx->aead_send);
2432 	tls_free_open_rec(sk);
2433 }
2434 
tls_sw_free_ctx_tx(struct tls_context * tls_ctx)2435 void tls_sw_free_ctx_tx(struct tls_context *tls_ctx)
2436 {
2437 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2438 
2439 	kfree(ctx);
2440 }
2441 
tls_sw_release_resources_rx(struct sock * sk)2442 void tls_sw_release_resources_rx(struct sock *sk)
2443 {
2444 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2445 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2446 
2447 	kfree(tls_ctx->rx.rec_seq);
2448 	kfree(tls_ctx->rx.iv);
2449 
2450 	if (ctx->aead_recv) {
2451 		__skb_queue_purge(&ctx->rx_list);
2452 		crypto_free_aead(ctx->aead_recv);
2453 		tls_strp_stop(&ctx->strp);
2454 		/* If tls_sw_strparser_arm() was not called (cleanup paths)
2455 		 * we still want to tls_strp_stop(), but sk->sk_data_ready was
2456 		 * never swapped.
2457 		 */
2458 		if (ctx->saved_data_ready) {
2459 			write_lock_bh(&sk->sk_callback_lock);
2460 			sk->sk_data_ready = ctx->saved_data_ready;
2461 			write_unlock_bh(&sk->sk_callback_lock);
2462 		}
2463 	}
2464 }
2465 
tls_sw_strparser_done(struct tls_context * tls_ctx)2466 void tls_sw_strparser_done(struct tls_context *tls_ctx)
2467 {
2468 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2469 
2470 	tls_strp_done(&ctx->strp);
2471 }
2472 
tls_sw_free_ctx_rx(struct tls_context * tls_ctx)2473 void tls_sw_free_ctx_rx(struct tls_context *tls_ctx)
2474 {
2475 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2476 
2477 	kfree(ctx);
2478 }
2479 
tls_sw_free_resources_rx(struct sock * sk)2480 void tls_sw_free_resources_rx(struct sock *sk)
2481 {
2482 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2483 
2484 	tls_sw_release_resources_rx(sk);
2485 	tls_sw_free_ctx_rx(tls_ctx);
2486 }
2487 
2488 /* The work handler to transmitt the encrypted records in tx_list */
tx_work_handler(struct work_struct * work)2489 static void tx_work_handler(struct work_struct *work)
2490 {
2491 	struct delayed_work *delayed_work = to_delayed_work(work);
2492 	struct tx_work *tx_work = container_of(delayed_work,
2493 					       struct tx_work, work);
2494 	struct sock *sk = tx_work->sk;
2495 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2496 	struct tls_sw_context_tx *ctx;
2497 
2498 	if (unlikely(!tls_ctx))
2499 		return;
2500 
2501 	ctx = tls_sw_ctx_tx(tls_ctx);
2502 	if (test_bit(BIT_TX_CLOSING, &ctx->tx_bitmask))
2503 		return;
2504 
2505 	if (!test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask))
2506 		return;
2507 
2508 	if (mutex_trylock(&tls_ctx->tx_lock)) {
2509 		lock_sock(sk);
2510 		tls_tx_records(sk, -1);
2511 		release_sock(sk);
2512 		mutex_unlock(&tls_ctx->tx_lock);
2513 	} else if (!test_and_set_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
2514 		/* Someone is holding the tx_lock, they will likely run Tx
2515 		 * and cancel the work on their way out of the lock section.
2516 		 * Schedule a long delay just in case.
2517 		 */
2518 		schedule_delayed_work(&ctx->tx_work.work, msecs_to_jiffies(10));
2519 	}
2520 }
2521 
tls_is_tx_ready(struct tls_sw_context_tx * ctx)2522 static bool tls_is_tx_ready(struct tls_sw_context_tx *ctx)
2523 {
2524 	struct tls_rec *rec;
2525 
2526 	rec = list_first_entry_or_null(&ctx->tx_list, struct tls_rec, list);
2527 	if (!rec)
2528 		return false;
2529 
2530 	return READ_ONCE(rec->tx_ready);
2531 }
2532 
tls_sw_write_space(struct sock * sk,struct tls_context * ctx)2533 void tls_sw_write_space(struct sock *sk, struct tls_context *ctx)
2534 {
2535 	struct tls_sw_context_tx *tx_ctx = tls_sw_ctx_tx(ctx);
2536 
2537 	/* Schedule the transmission if tx list is ready */
2538 	if (tls_is_tx_ready(tx_ctx) &&
2539 	    !test_and_set_bit(BIT_TX_SCHEDULED, &tx_ctx->tx_bitmask))
2540 		schedule_delayed_work(&tx_ctx->tx_work.work, 0);
2541 }
2542 
tls_sw_strparser_arm(struct sock * sk,struct tls_context * tls_ctx)2543 void tls_sw_strparser_arm(struct sock *sk, struct tls_context *tls_ctx)
2544 {
2545 	struct tls_sw_context_rx *rx_ctx = tls_sw_ctx_rx(tls_ctx);
2546 
2547 	write_lock_bh(&sk->sk_callback_lock);
2548 	rx_ctx->saved_data_ready = sk->sk_data_ready;
2549 	sk->sk_data_ready = tls_data_ready;
2550 	write_unlock_bh(&sk->sk_callback_lock);
2551 }
2552 
tls_update_rx_zc_capable(struct tls_context * tls_ctx)2553 void tls_update_rx_zc_capable(struct tls_context *tls_ctx)
2554 {
2555 	struct tls_sw_context_rx *rx_ctx = tls_sw_ctx_rx(tls_ctx);
2556 
2557 	rx_ctx->zc_capable = tls_ctx->rx_no_pad ||
2558 		tls_ctx->prot_info.version != TLS_1_3_VERSION;
2559 }
2560 
init_ctx_tx(struct tls_context * ctx,struct sock * sk)2561 static struct tls_sw_context_tx *init_ctx_tx(struct tls_context *ctx, struct sock *sk)
2562 {
2563 	struct tls_sw_context_tx *sw_ctx_tx;
2564 
2565 	if (!ctx->priv_ctx_tx) {
2566 		sw_ctx_tx = kzalloc(sizeof(*sw_ctx_tx), GFP_KERNEL);
2567 		if (!sw_ctx_tx)
2568 			return NULL;
2569 	} else {
2570 		sw_ctx_tx = ctx->priv_ctx_tx;
2571 	}
2572 
2573 	crypto_init_wait(&sw_ctx_tx->async_wait);
2574 	atomic_set(&sw_ctx_tx->encrypt_pending, 1);
2575 	INIT_LIST_HEAD(&sw_ctx_tx->tx_list);
2576 	INIT_DELAYED_WORK(&sw_ctx_tx->tx_work.work, tx_work_handler);
2577 	sw_ctx_tx->tx_work.sk = sk;
2578 
2579 	return sw_ctx_tx;
2580 }
2581 
init_ctx_rx(struct tls_context * ctx)2582 static struct tls_sw_context_rx *init_ctx_rx(struct tls_context *ctx)
2583 {
2584 	struct tls_sw_context_rx *sw_ctx_rx;
2585 
2586 	if (!ctx->priv_ctx_rx) {
2587 		sw_ctx_rx = kzalloc(sizeof(*sw_ctx_rx), GFP_KERNEL);
2588 		if (!sw_ctx_rx)
2589 			return NULL;
2590 	} else {
2591 		sw_ctx_rx = ctx->priv_ctx_rx;
2592 	}
2593 
2594 	crypto_init_wait(&sw_ctx_rx->async_wait);
2595 	atomic_set(&sw_ctx_rx->decrypt_pending, 1);
2596 	init_waitqueue_head(&sw_ctx_rx->wq);
2597 	skb_queue_head_init(&sw_ctx_rx->rx_list);
2598 	skb_queue_head_init(&sw_ctx_rx->async_hold);
2599 
2600 	return sw_ctx_rx;
2601 }
2602 
tls_set_sw_offload(struct sock * sk,struct tls_context * ctx,int tx)2603 int tls_set_sw_offload(struct sock *sk, struct tls_context *ctx, int tx)
2604 {
2605 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2606 	struct tls_prot_info *prot = &tls_ctx->prot_info;
2607 	struct tls_crypto_info *crypto_info;
2608 	struct tls_sw_context_tx *sw_ctx_tx = NULL;
2609 	struct tls_sw_context_rx *sw_ctx_rx = NULL;
2610 	struct cipher_context *cctx;
2611 	struct crypto_aead **aead;
2612 	u16 nonce_size, tag_size, iv_size, rec_seq_size, salt_size;
2613 	struct crypto_tfm *tfm;
2614 	char *iv, *rec_seq, *key, *salt, *cipher_name;
2615 	size_t keysize;
2616 	int rc = 0;
2617 
2618 	if (!ctx) {
2619 		rc = -EINVAL;
2620 		goto out;
2621 	}
2622 
2623 	if (tx) {
2624 		ctx->priv_ctx_tx = init_ctx_tx(ctx, sk);
2625 		if (!ctx->priv_ctx_tx)
2626 			return -ENOMEM;
2627 
2628 		sw_ctx_tx = ctx->priv_ctx_tx;
2629 		crypto_info = &ctx->crypto_send.info;
2630 		cctx = &ctx->tx;
2631 		aead = &sw_ctx_tx->aead_send;
2632 	} else {
2633 		ctx->priv_ctx_rx = init_ctx_rx(ctx);
2634 		if (!ctx->priv_ctx_rx)
2635 			return -ENOMEM;
2636 
2637 		sw_ctx_rx = ctx->priv_ctx_rx;
2638 		crypto_info = &ctx->crypto_recv.info;
2639 		cctx = &ctx->rx;
2640 		aead = &sw_ctx_rx->aead_recv;
2641 	}
2642 
2643 	switch (crypto_info->cipher_type) {
2644 	case TLS_CIPHER_AES_GCM_128: {
2645 		struct tls12_crypto_info_aes_gcm_128 *gcm_128_info;
2646 
2647 		gcm_128_info = (void *)crypto_info;
2648 		nonce_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
2649 		tag_size = TLS_CIPHER_AES_GCM_128_TAG_SIZE;
2650 		iv_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
2651 		iv = gcm_128_info->iv;
2652 		rec_seq_size = TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE;
2653 		rec_seq = gcm_128_info->rec_seq;
2654 		keysize = TLS_CIPHER_AES_GCM_128_KEY_SIZE;
2655 		key = gcm_128_info->key;
2656 		salt = gcm_128_info->salt;
2657 		salt_size = TLS_CIPHER_AES_GCM_128_SALT_SIZE;
2658 		cipher_name = "gcm(aes)";
2659 		break;
2660 	}
2661 	case TLS_CIPHER_AES_GCM_256: {
2662 		struct tls12_crypto_info_aes_gcm_256 *gcm_256_info;
2663 
2664 		gcm_256_info = (void *)crypto_info;
2665 		nonce_size = TLS_CIPHER_AES_GCM_256_IV_SIZE;
2666 		tag_size = TLS_CIPHER_AES_GCM_256_TAG_SIZE;
2667 		iv_size = TLS_CIPHER_AES_GCM_256_IV_SIZE;
2668 		iv = gcm_256_info->iv;
2669 		rec_seq_size = TLS_CIPHER_AES_GCM_256_REC_SEQ_SIZE;
2670 		rec_seq = gcm_256_info->rec_seq;
2671 		keysize = TLS_CIPHER_AES_GCM_256_KEY_SIZE;
2672 		key = gcm_256_info->key;
2673 		salt = gcm_256_info->salt;
2674 		salt_size = TLS_CIPHER_AES_GCM_256_SALT_SIZE;
2675 		cipher_name = "gcm(aes)";
2676 		break;
2677 	}
2678 	case TLS_CIPHER_AES_CCM_128: {
2679 		struct tls12_crypto_info_aes_ccm_128 *ccm_128_info;
2680 
2681 		ccm_128_info = (void *)crypto_info;
2682 		nonce_size = TLS_CIPHER_AES_CCM_128_IV_SIZE;
2683 		tag_size = TLS_CIPHER_AES_CCM_128_TAG_SIZE;
2684 		iv_size = TLS_CIPHER_AES_CCM_128_IV_SIZE;
2685 		iv = ccm_128_info->iv;
2686 		rec_seq_size = TLS_CIPHER_AES_CCM_128_REC_SEQ_SIZE;
2687 		rec_seq = ccm_128_info->rec_seq;
2688 		keysize = TLS_CIPHER_AES_CCM_128_KEY_SIZE;
2689 		key = ccm_128_info->key;
2690 		salt = ccm_128_info->salt;
2691 		salt_size = TLS_CIPHER_AES_CCM_128_SALT_SIZE;
2692 		cipher_name = "ccm(aes)";
2693 		break;
2694 	}
2695 	case TLS_CIPHER_CHACHA20_POLY1305: {
2696 		struct tls12_crypto_info_chacha20_poly1305 *chacha20_poly1305_info;
2697 
2698 		chacha20_poly1305_info = (void *)crypto_info;
2699 		nonce_size = 0;
2700 		tag_size = TLS_CIPHER_CHACHA20_POLY1305_TAG_SIZE;
2701 		iv_size = TLS_CIPHER_CHACHA20_POLY1305_IV_SIZE;
2702 		iv = chacha20_poly1305_info->iv;
2703 		rec_seq_size = TLS_CIPHER_CHACHA20_POLY1305_REC_SEQ_SIZE;
2704 		rec_seq = chacha20_poly1305_info->rec_seq;
2705 		keysize = TLS_CIPHER_CHACHA20_POLY1305_KEY_SIZE;
2706 		key = chacha20_poly1305_info->key;
2707 		salt = chacha20_poly1305_info->salt;
2708 		salt_size = TLS_CIPHER_CHACHA20_POLY1305_SALT_SIZE;
2709 		cipher_name = "rfc7539(chacha20,poly1305)";
2710 		break;
2711 	}
2712 	case TLS_CIPHER_SM4_GCM: {
2713 		struct tls12_crypto_info_sm4_gcm *sm4_gcm_info;
2714 
2715 		sm4_gcm_info = (void *)crypto_info;
2716 		nonce_size = TLS_CIPHER_SM4_GCM_IV_SIZE;
2717 		tag_size = TLS_CIPHER_SM4_GCM_TAG_SIZE;
2718 		iv_size = TLS_CIPHER_SM4_GCM_IV_SIZE;
2719 		iv = sm4_gcm_info->iv;
2720 		rec_seq_size = TLS_CIPHER_SM4_GCM_REC_SEQ_SIZE;
2721 		rec_seq = sm4_gcm_info->rec_seq;
2722 		keysize = TLS_CIPHER_SM4_GCM_KEY_SIZE;
2723 		key = sm4_gcm_info->key;
2724 		salt = sm4_gcm_info->salt;
2725 		salt_size = TLS_CIPHER_SM4_GCM_SALT_SIZE;
2726 		cipher_name = "gcm(sm4)";
2727 		break;
2728 	}
2729 	case TLS_CIPHER_SM4_CCM: {
2730 		struct tls12_crypto_info_sm4_ccm *sm4_ccm_info;
2731 
2732 		sm4_ccm_info = (void *)crypto_info;
2733 		nonce_size = TLS_CIPHER_SM4_CCM_IV_SIZE;
2734 		tag_size = TLS_CIPHER_SM4_CCM_TAG_SIZE;
2735 		iv_size = TLS_CIPHER_SM4_CCM_IV_SIZE;
2736 		iv = sm4_ccm_info->iv;
2737 		rec_seq_size = TLS_CIPHER_SM4_CCM_REC_SEQ_SIZE;
2738 		rec_seq = sm4_ccm_info->rec_seq;
2739 		keysize = TLS_CIPHER_SM4_CCM_KEY_SIZE;
2740 		key = sm4_ccm_info->key;
2741 		salt = sm4_ccm_info->salt;
2742 		salt_size = TLS_CIPHER_SM4_CCM_SALT_SIZE;
2743 		cipher_name = "ccm(sm4)";
2744 		break;
2745 	}
2746 	case TLS_CIPHER_ARIA_GCM_128: {
2747 		struct tls12_crypto_info_aria_gcm_128 *aria_gcm_128_info;
2748 
2749 		aria_gcm_128_info = (void *)crypto_info;
2750 		nonce_size = TLS_CIPHER_ARIA_GCM_128_IV_SIZE;
2751 		tag_size = TLS_CIPHER_ARIA_GCM_128_TAG_SIZE;
2752 		iv_size = TLS_CIPHER_ARIA_GCM_128_IV_SIZE;
2753 		iv = aria_gcm_128_info->iv;
2754 		rec_seq_size = TLS_CIPHER_ARIA_GCM_128_REC_SEQ_SIZE;
2755 		rec_seq = aria_gcm_128_info->rec_seq;
2756 		keysize = TLS_CIPHER_ARIA_GCM_128_KEY_SIZE;
2757 		key = aria_gcm_128_info->key;
2758 		salt = aria_gcm_128_info->salt;
2759 		salt_size = TLS_CIPHER_ARIA_GCM_128_SALT_SIZE;
2760 		cipher_name = "gcm(aria)";
2761 		break;
2762 	}
2763 	case TLS_CIPHER_ARIA_GCM_256: {
2764 		struct tls12_crypto_info_aria_gcm_256 *gcm_256_info;
2765 
2766 		gcm_256_info = (void *)crypto_info;
2767 		nonce_size = TLS_CIPHER_ARIA_GCM_256_IV_SIZE;
2768 		tag_size = TLS_CIPHER_ARIA_GCM_256_TAG_SIZE;
2769 		iv_size = TLS_CIPHER_ARIA_GCM_256_IV_SIZE;
2770 		iv = gcm_256_info->iv;
2771 		rec_seq_size = TLS_CIPHER_ARIA_GCM_256_REC_SEQ_SIZE;
2772 		rec_seq = gcm_256_info->rec_seq;
2773 		keysize = TLS_CIPHER_ARIA_GCM_256_KEY_SIZE;
2774 		key = gcm_256_info->key;
2775 		salt = gcm_256_info->salt;
2776 		salt_size = TLS_CIPHER_ARIA_GCM_256_SALT_SIZE;
2777 		cipher_name = "gcm(aria)";
2778 		break;
2779 	}
2780 	default:
2781 		rc = -EINVAL;
2782 		goto free_priv;
2783 	}
2784 
2785 	if (crypto_info->version == TLS_1_3_VERSION) {
2786 		nonce_size = 0;
2787 		prot->aad_size = TLS_HEADER_SIZE;
2788 		prot->tail_size = 1;
2789 	} else {
2790 		prot->aad_size = TLS_AAD_SPACE_SIZE;
2791 		prot->tail_size = 0;
2792 	}
2793 
2794 	/* Sanity-check the sizes for stack allocations. */
2795 	if (iv_size > MAX_IV_SIZE || nonce_size > MAX_IV_SIZE ||
2796 	    rec_seq_size > TLS_MAX_REC_SEQ_SIZE || tag_size != TLS_TAG_SIZE ||
2797 	    prot->aad_size > TLS_MAX_AAD_SIZE) {
2798 		rc = -EINVAL;
2799 		goto free_priv;
2800 	}
2801 
2802 	prot->version = crypto_info->version;
2803 	prot->cipher_type = crypto_info->cipher_type;
2804 	prot->prepend_size = TLS_HEADER_SIZE + nonce_size;
2805 	prot->tag_size = tag_size;
2806 	prot->overhead_size = prot->prepend_size +
2807 			      prot->tag_size + prot->tail_size;
2808 	prot->iv_size = iv_size;
2809 	prot->salt_size = salt_size;
2810 	cctx->iv = kmalloc(iv_size + salt_size, GFP_KERNEL);
2811 	if (!cctx->iv) {
2812 		rc = -ENOMEM;
2813 		goto free_priv;
2814 	}
2815 	/* Note: 128 & 256 bit salt are the same size */
2816 	prot->rec_seq_size = rec_seq_size;
2817 	memcpy(cctx->iv, salt, salt_size);
2818 	memcpy(cctx->iv + salt_size, iv, iv_size);
2819 	cctx->rec_seq = kmemdup(rec_seq, rec_seq_size, GFP_KERNEL);
2820 	if (!cctx->rec_seq) {
2821 		rc = -ENOMEM;
2822 		goto free_iv;
2823 	}
2824 
2825 	if (!*aead) {
2826 		*aead = crypto_alloc_aead(cipher_name, 0, 0);
2827 		if (IS_ERR(*aead)) {
2828 			rc = PTR_ERR(*aead);
2829 			*aead = NULL;
2830 			goto free_rec_seq;
2831 		}
2832 	}
2833 
2834 	ctx->push_pending_record = tls_sw_push_pending_record;
2835 
2836 	rc = crypto_aead_setkey(*aead, key, keysize);
2837 
2838 	if (rc)
2839 		goto free_aead;
2840 
2841 	rc = crypto_aead_setauthsize(*aead, prot->tag_size);
2842 	if (rc)
2843 		goto free_aead;
2844 
2845 	if (sw_ctx_rx) {
2846 		tfm = crypto_aead_tfm(sw_ctx_rx->aead_recv);
2847 
2848 		tls_update_rx_zc_capable(ctx);
2849 		sw_ctx_rx->async_capable =
2850 			crypto_info->version != TLS_1_3_VERSION &&
2851 			!!(tfm->__crt_alg->cra_flags & CRYPTO_ALG_ASYNC);
2852 
2853 		rc = tls_strp_init(&sw_ctx_rx->strp, sk);
2854 		if (rc)
2855 			goto free_aead;
2856 	}
2857 
2858 	goto out;
2859 
2860 free_aead:
2861 	crypto_free_aead(*aead);
2862 	*aead = NULL;
2863 free_rec_seq:
2864 	kfree(cctx->rec_seq);
2865 	cctx->rec_seq = NULL;
2866 free_iv:
2867 	kfree(cctx->iv);
2868 	cctx->iv = NULL;
2869 free_priv:
2870 	if (tx) {
2871 		kfree(ctx->priv_ctx_tx);
2872 		ctx->priv_ctx_tx = NULL;
2873 	} else {
2874 		kfree(ctx->priv_ctx_rx);
2875 		ctx->priv_ctx_rx = NULL;
2876 	}
2877 out:
2878 	return rc;
2879 }
2880