tls_sw.c 66.4 KB
Newer Older
D
Dave Watson 已提交
1 2 3 4 5 6
/*
 * Copyright (c) 2016-2017, Mellanox Technologies. All rights reserved.
 * Copyright (c) 2016-2017, Dave Watson <davejwatson@fb.com>. All rights reserved.
 * Copyright (c) 2016-2017, Lance Chao <lancerchao@fb.com>. All rights reserved.
 * Copyright (c) 2016, Fridolin Pokorny <fridolin.pokorny@gmail.com>. All rights reserved.
 * Copyright (c) 2016, Nikos Mavrogiannopoulos <nmav@gnutls.org>. All rights reserved.
7
 * Copyright (c) 2018, Covalent IO, Inc. http://covalent.io
D
Dave Watson 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
 *
 * This software is available to you under a choice of one of two
 * licenses.  You may choose to be licensed under the terms of the GNU
 * General Public License (GPL) Version 2, available from the file
 * COPYING in the main directory of this source tree, or the
 * OpenIB.org BSD license below:
 *
 *     Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *      - Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *
 *      - Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

38
#include <linux/bug.h>
D
Dave Watson 已提交
39
#include <linux/sched/signal.h>
D
Dave Watson 已提交
40
#include <linux/module.h>
41
#include <linux/splice.h>
D
Dave Watson 已提交
42 43
#include <crypto/aead.h>

D
Dave Watson 已提交
44
#include <net/strparser.h>
D
Dave Watson 已提交
45 46
#include <net/tls.h>

J
Jakub Kicinski 已提交
47 48
#include "tls.h"

49 50 51
struct tls_decrypt_arg {
	bool zc;
	bool async;
52
	u8 tail;
53 54
};

55 56 57 58 59 60 61
struct tls_decrypt_ctx {
	u8 iv[MAX_IV_SIZE];
	u8 aad[TLS_MAX_AAD_SIZE];
	u8 tail;
	struct scatterlist sg[];
};

62 63 64 65 66 67 68 69
noinline void tls_err_abort(struct sock *sk, int err)
{
	WARN_ON_ONCE(err >= 0);
	/* sk->sk_err should contain a positive error code. */
	sk->sk_err = -err;
	sk_error_report(sk);
}

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
static int __skb_nsg(struct sk_buff *skb, int offset, int len,
                     unsigned int recursion_level)
{
        int start = skb_headlen(skb);
        int i, chunk = start - offset;
        struct sk_buff *frag_iter;
        int elt = 0;

        if (unlikely(recursion_level >= 24))
                return -EMSGSIZE;

        if (chunk > 0) {
                if (chunk > len)
                        chunk = len;
                elt++;
                len -= chunk;
                if (len == 0)
                        return elt;
                offset += chunk;
        }

        for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
                int end;

                WARN_ON(start > offset + len);

                end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
                chunk = end - offset;
                if (chunk > 0) {
                        if (chunk > len)
                                chunk = len;
                        elt++;
                        len -= chunk;
                        if (len == 0)
                                return elt;
                        offset += chunk;
                }
                start = end;
        }

        if (unlikely(skb_has_frag_list(skb))) {
                skb_walk_frags(skb, frag_iter) {
                        int end, ret;

                        WARN_ON(start > offset + len);

                        end = start + frag_iter->len;
                        chunk = end - offset;
                        if (chunk > 0) {
                                if (chunk > len)
                                        chunk = len;
                                ret = __skb_nsg(frag_iter, offset - start, chunk,
                                                recursion_level + 1);
                                if (unlikely(ret < 0))
                                        return ret;
                                elt += ret;
                                len -= chunk;
                                if (len == 0)
                                        return elt;
                                offset += chunk;
                        }
                        start = end;
                }
        }
        BUG_ON(len);
        return elt;
}

/* Return the number of scatterlist elements required to completely map the
 * skb, or -EMSGSIZE if the recursion depth is exceeded.
 */
static int skb_nsg(struct sk_buff *skb, int offset, int len)
{
        return __skb_nsg(skb, offset, len, 0);
}

146 147
static int tls_padding_length(struct tls_prot_info *prot, struct sk_buff *skb,
			      struct tls_decrypt_arg *darg)
D
Dave Watson 已提交
148 149
{
	struct strp_msg *rxm = strp_msg(skb);
150
	struct tls_msg *tlm = tls_msg(skb);
D
Dave Watson 已提交
151 152 153
	int sub = 0;

	/* Determine zero-padding length */
154
	if (prot->version == TLS_1_3_VERSION) {
155
		int offset = rxm->full_len - TLS_TAG_SIZE - 1;
156
		char content_type = darg->zc ? darg->tail : 0;
D
Dave Watson 已提交
157 158 159
		int err;

		while (content_type == 0) {
160
			if (offset < prot->prepend_size)
D
Dave Watson 已提交
161
				return -EBADMSG;
162
			err = skb_copy_bits(skb, rxm->offset + offset,
D
Dave Watson 已提交
163
					    &content_type, 1);
164 165
			if (err)
				return err;
D
Dave Watson 已提交
166 167 168
			if (content_type)
				break;
			sub++;
169
			offset--;
D
Dave Watson 已提交
170
		}
171
		tlm->control = content_type;
D
Dave Watson 已提交
172 173 174 175
	}
	return sub;
}

176 177 178 179
static void tls_decrypt_done(struct crypto_async_request *req, int err)
{
	struct aead_request *aead_req = (struct aead_request *)req;
	struct scatterlist *sgout = aead_req->dst;
180
	struct scatterlist *sgin = aead_req->src;
181 182
	struct tls_sw_context_rx *ctx;
	struct tls_context *tls_ctx;
183
	struct tls_prot_info *prot;
184
	struct scatterlist *sg;
185
	struct sk_buff *skb;
186
	unsigned int pages;
187 188 189 190

	skb = (struct sk_buff *)req->data;
	tls_ctx = tls_get_ctx(skb->sk);
	ctx = tls_sw_ctx_rx(tls_ctx);
191
	prot = &tls_ctx->prot_info;
192 193 194

	/* Propagate if there was an err */
	if (err) {
J
Jakub Kicinski 已提交
195 196 197
		if (err == -EBADMSG)
			TLS_INC_STATS(sock_net(skb->sk),
				      LINUX_MIB_TLSDECRYPTERROR);
198
		ctx->async_wait.err = err;
199
		tls_err_abort(skb->sk, err);
200 201
	} else {
		struct strp_msg *rxm = strp_msg(skb);
202 203 204 205 206 207

		/* No TLS 1.3 support with async crypto */
		WARN_ON(prot->tail_size);

		rxm->offset += prot->prepend_size;
		rxm->full_len -= prot->overhead_size;
208 209
	}

210 211 212 213 214
	/* After using skb->sk to propagate sk through crypto async callback
	 * we need to NULL it again.
	 */
	skb->sk = NULL;

215

216 217 218 219 220 221 222 223
	/* Free the destination pages if skb was not decrypted inplace */
	if (sgout != sgin) {
		/* Skip the first S/G entry as it points to AAD */
		for_each_sg(sg_next(sgout), sg, UINT_MAX, pages) {
			if (!sg)
				break;
			put_page(sg_page(sg));
		}
224 225 226 227
	}

	kfree(aead_req);

228
	spin_lock_bh(&ctx->decrypt_compl_lock);
J
Jakub Kicinski 已提交
229
	if (!atomic_dec_return(&ctx->decrypt_pending))
230
		complete(&ctx->async_wait.completion);
231
	spin_unlock_bh(&ctx->decrypt_compl_lock);
232 233
}

D
Dave Watson 已提交
234
static int tls_do_decryption(struct sock *sk,
235
			     struct sk_buff *skb,
D
Dave Watson 已提交
236 237 238 239
			     struct scatterlist *sgin,
			     struct scatterlist *sgout,
			     char *iv_recv,
			     size_t data_len,
240
			     struct aead_request *aead_req,
241
			     struct tls_decrypt_arg *darg)
D
Dave Watson 已提交
242 243
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
244
	struct tls_prot_info *prot = &tls_ctx->prot_info;
B
Boris Pismenny 已提交
245
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
246 247
	int ret;

248
	aead_request_set_tfm(aead_req, ctx->aead_recv);
249
	aead_request_set_ad(aead_req, prot->aad_size);
D
Dave Watson 已提交
250
	aead_request_set_crypt(aead_req, sgin, sgout,
251
			       data_len + prot->tag_size,
D
Dave Watson 已提交
252 253
			       (u8 *)iv_recv);

254
	if (darg->async) {
255 256 257
		/* Using skb->sk to push sk through to crypto async callback
		 * handler. This allows propagating errors up to the socket
		 * if needed. It _must_ be cleared in the async handler
258
		 * before consume_skb is called. We _know_ skb->sk is NULL
259 260 261
		 * because it is a clone from strparser.
		 */
		skb->sk = sk;
262 263 264 265 266 267 268 269 270 271 272 273
		aead_request_set_callback(aead_req,
					  CRYPTO_TFM_REQ_MAY_BACKLOG,
					  tls_decrypt_done, skb);
		atomic_inc(&ctx->decrypt_pending);
	} else {
		aead_request_set_callback(aead_req,
					  CRYPTO_TFM_REQ_MAY_BACKLOG,
					  crypto_req_done, &ctx->async_wait);
	}

	ret = crypto_aead_decrypt(aead_req);
	if (ret == -EINPROGRESS) {
274 275
		if (darg->async)
			return 0;
276 277 278

		ret = crypto_wait_req(ret, &ctx->async_wait);
	}
279 280
	darg->async = false;

D
Dave Watson 已提交
281 282 283
	return ret;
}

284
static void tls_trim_both_msgs(struct sock *sk, int target_size)
D
Dave Watson 已提交
285 286
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
287
	struct tls_prot_info *prot = &tls_ctx->prot_info;
B
Boris Pismenny 已提交
288
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
289
	struct tls_rec *rec = ctx->open_rec;
D
Dave Watson 已提交
290

291
	sk_msg_trim(sk, &rec->msg_plaintext, target_size);
D
Dave Watson 已提交
292
	if (target_size > 0)
293
		target_size += prot->overhead_size;
294
	sk_msg_trim(sk, &rec->msg_encrypted, target_size);
D
Dave Watson 已提交
295 296
}

297
static int tls_alloc_encrypted_msg(struct sock *sk, int len)
D
Dave Watson 已提交
298 299
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
300
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
301
	struct tls_rec *rec = ctx->open_rec;
302
	struct sk_msg *msg_en = &rec->msg_encrypted;
D
Dave Watson 已提交
303

304
	return sk_msg_alloc(sk, msg_en, len, 0);
D
Dave Watson 已提交
305 306
}

307
static int tls_clone_plaintext_msg(struct sock *sk, int required)
D
Dave Watson 已提交
308 309
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
310
	struct tls_prot_info *prot = &tls_ctx->prot_info;
B
Boris Pismenny 已提交
311
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
312
	struct tls_rec *rec = ctx->open_rec;
313 314
	struct sk_msg *msg_pl = &rec->msg_plaintext;
	struct sk_msg *msg_en = &rec->msg_encrypted;
315
	int skip, len;
D
Dave Watson 已提交
316

317 318
	/* We add page references worth len bytes from encrypted sg
	 * at the end of plaintext sg. It is guaranteed that msg_en
319 320
	 * has enough required room (ensured by caller).
	 */
321
	len = required - msg_pl->sg.size;
322

323 324
	/* Skip initial bytes in msg_en's data to be able to use
	 * same offset of both plain and encrypted data.
325
	 */
326
	skip = prot->prepend_size + msg_pl->sg.size;
327

328
	return sk_msg_clone(sk, msg_pl, msg_en, skip, len);
D
Dave Watson 已提交
329 330
}

331
static struct tls_rec *tls_get_rec(struct sock *sk)
D
Dave Watson 已提交
332 333
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
334
	struct tls_prot_info *prot = &tls_ctx->prot_info;
B
Boris Pismenny 已提交
335
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
336 337 338
	struct sk_msg *msg_pl, *msg_en;
	struct tls_rec *rec;
	int mem_size;
D
Dave Watson 已提交
339

340 341 342
	mem_size = sizeof(struct tls_rec) + crypto_aead_reqsize(ctx->aead_send);

	rec = kzalloc(mem_size, sk->sk_allocation);
343
	if (!rec)
344 345 346 347 348 349 350 351 352
		return NULL;

	msg_pl = &rec->msg_plaintext;
	msg_en = &rec->msg_encrypted;

	sk_msg_init(msg_pl);
	sk_msg_init(msg_en);

	sg_init_table(rec->sg_aead_in, 2);
353
	sg_set_buf(&rec->sg_aead_in[0], rec->aad_space, prot->aad_size);
354 355 356
	sg_unmark_end(&rec->sg_aead_in[1]);

	sg_init_table(rec->sg_aead_out, 2);
357
	sg_set_buf(&rec->sg_aead_out[0], rec->aad_space, prot->aad_size);
358 359 360 361
	sg_unmark_end(&rec->sg_aead_out[1]);

	return rec;
}
362

363 364
static void tls_free_rec(struct sock *sk, struct tls_rec *rec)
{
365 366
	sk_msg_free(sk, &rec->msg_encrypted);
	sk_msg_free(sk, &rec->msg_plaintext);
367
	kfree(rec);
368 369
}

370 371 372 373 374 375 376 377 378 379 380 381
static void tls_free_open_rec(struct sock *sk)
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
	struct tls_rec *rec = ctx->open_rec;

	if (rec) {
		tls_free_rec(sk, rec);
		ctx->open_rec = NULL;
	}
}

382 383 384 385 386
int tls_tx_records(struct sock *sk, int flags)
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
	struct tls_rec *rec, *tmp;
387
	struct sk_msg *msg_en;
388 389 390
	int tx_flags, rc = 0;

	if (tls_is_partially_sent_record(tls_ctx)) {
391
		rec = list_first_entry(&ctx->tx_list,
392 393 394 395 396 397 398 399 400 401 402 403
				       struct tls_rec, list);

		if (flags == -1)
			tx_flags = rec->tx_flags;
		else
			tx_flags = flags;

		rc = tls_push_partial_record(sk, tls_ctx, tx_flags);
		if (rc)
			goto tx_err;

		/* 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 409 410
		kfree(rec);
	}

411 412 413
	/* Tx all ready records */
	list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
		if (READ_ONCE(rec->tx_ready)) {
414 415 416 417 418
			if (flags == -1)
				tx_flags = rec->tx_flags;
			else
				tx_flags = flags;

419
			msg_en = &rec->msg_encrypted;
420
			rc = tls_push_sg(sk, tls_ctx,
421
					 &msg_en->sg.data[msg_en->sg.curr],
422 423 424 425 426
					 0, tx_flags);
			if (rc)
				goto tx_err;

			list_del(&rec->list);
427
			sk_msg_free(sk, &rec->msg_plaintext);
428 429 430 431 432 433 434 435
			kfree(rec);
		} else {
			break;
		}
	}

tx_err:
	if (rc < 0 && rc != -EAGAIN)
436
		tls_err_abort(sk, -EBADMSG);
437 438 439 440 441 442 443 444 445

	return rc;
}

static void tls_encrypt_done(struct crypto_async_request *req, int err)
{
	struct aead_request *aead_req = (struct aead_request *)req;
	struct sock *sk = req->data;
	struct tls_context *tls_ctx = tls_get_ctx(sk);
446
	struct tls_prot_info *prot = &tls_ctx->prot_info;
447
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
448 449
	struct scatterlist *sge;
	struct sk_msg *msg_en;
450 451 452 453 454
	struct tls_rec *rec;
	bool ready = false;
	int pending;

	rec = container_of(aead_req, struct tls_rec, aead_req);
455
	msg_en = &rec->msg_encrypted;
456

457
	sge = sk_msg_elem(msg_en, msg_en->sg.curr);
458 459
	sge->offset -= prot->prepend_size;
	sge->length += prot->prepend_size;
460

461
	/* Check if error is previously set on socket */
462 463 464 465 466
	if (err || sk->sk_err) {
		rec = NULL;

		/* If err is already set on socket, return the same code */
		if (sk->sk_err) {
467
			ctx->async_wait.err = -sk->sk_err;
468 469 470 471 472 473
		} else {
			ctx->async_wait.err = err;
			tls_err_abort(sk, err);
		}
	}

474 475 476 477 478 479 480 481 482 483 484 485
	if (rec) {
		struct tls_rec *first_rec;

		/* Mark the record as ready for transmission */
		smp_store_mb(rec->tx_ready, true);

		/* If received record is at head of tx_list, schedule tx */
		first_rec = list_first_entry(&ctx->tx_list,
					     struct tls_rec, list);
		if (rec == first_rec)
			ready = true;
	}
486

487
	spin_lock_bh(&ctx->encrypt_compl_lock);
488 489
	pending = atomic_dec_return(&ctx->encrypt_pending);

490
	if (!pending && ctx->async_notify)
491
		complete(&ctx->async_wait.completion);
492
	spin_unlock_bh(&ctx->encrypt_compl_lock);
493 494 495 496 497 498

	if (!ready)
		return;

	/* Schedule the transmission */
	if (!test_and_set_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask))
499
		schedule_delayed_work(&ctx->tx_work.work, 1);
D
Dave Watson 已提交
500 501
}

502 503
static int tls_do_encryption(struct sock *sk,
			     struct tls_context *tls_ctx,
504 505
			     struct tls_sw_context_tx *ctx,
			     struct aead_request *aead_req,
506
			     size_t data_len, u32 start)
D
Dave Watson 已提交
507
{
508
	struct tls_prot_info *prot = &tls_ctx->prot_info;
509
	struct tls_rec *rec = ctx->open_rec;
510 511
	struct sk_msg *msg_en = &rec->msg_encrypted;
	struct scatterlist *sge = sk_msg_elem(msg_en, start);
512 513 514
	int rc, iv_offset = 0;

	/* For CCM based ciphers, first byte of IV is a constant */
515 516
	switch (prot->cipher_type) {
	case TLS_CIPHER_AES_CCM_128:
517 518
		rec->iv_data[0] = TLS_AES_CCM_IV_B0_BYTE;
		iv_offset = 1;
519 520 521 522 523
		break;
	case TLS_CIPHER_SM4_CCM:
		rec->iv_data[0] = TLS_SM4_CCM_IV_B0_BYTE;
		iv_offset = 1;
		break;
524 525 526 527
	}

	memcpy(&rec->iv_data[iv_offset], tls_ctx->tx.iv,
	       prot->iv_size + prot->salt_size);
D
Dave Watson 已提交
528

J
Jakub Kicinski 已提交
529 530
	tls_xor_iv_with_seq(prot, rec->iv_data + iv_offset,
			    tls_ctx->tx.rec_seq);
531

532 533
	sge->offset += prot->prepend_size;
	sge->length -= prot->prepend_size;
D
Dave Watson 已提交
534

535
	msg_en->sg.curr = start;
536

D
Dave Watson 已提交
537
	aead_request_set_tfm(aead_req, ctx->aead_send);
538
	aead_request_set_ad(aead_req, prot->aad_size);
539 540
	aead_request_set_crypt(aead_req, rec->sg_aead_in,
			       rec->sg_aead_out,
541
			       data_len, rec->iv_data);
542 543

	aead_request_set_callback(aead_req, CRYPTO_TFM_REQ_MAY_BACKLOG,
544 545
				  tls_encrypt_done, sk);

546 547
	/* Add the record in tx_list */
	list_add_tail((struct list_head *)&rec->list, &ctx->tx_list);
548
	atomic_inc(&ctx->encrypt_pending);
549

550 551 552
	rc = crypto_aead_encrypt(aead_req);
	if (!rc || rc != -EINPROGRESS) {
		atomic_dec(&ctx->encrypt_pending);
553 554
		sge->offset -= prot->prepend_size;
		sge->length += prot->prepend_size;
555
	}
D
Dave Watson 已提交
556

557 558 559 560
	if (!rc) {
		WRITE_ONCE(rec->tx_ready, true);
	} else if (rc != -EINPROGRESS) {
		list_del(&rec->list);
561
		return rc;
562
	}
D
Dave Watson 已提交
563

564 565
	/* Unhook the record from context if encryption is not failure */
	ctx->open_rec = NULL;
566
	tls_advance_record_sn(sk, prot, &tls_ctx->tx);
D
Dave Watson 已提交
567 568 569
	return rc;
}

570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
static int 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)
{
	u32 i, j, bytes = 0, apply = msg_opl->apply_bytes;
	struct scatterlist *sge, *osge, *nsge;
	u32 orig_size = msg_opl->sg.size;
	struct scatterlist tmp = { };
	struct sk_msg *msg_npl;
	struct tls_rec *new;
	int ret;

	new = tls_get_rec(sk);
	if (!new)
		return -ENOMEM;
	ret = sk_msg_alloc(sk, &new->msg_encrypted, msg_opl->sg.size +
			   tx_overhead_size, 0);
	if (ret < 0) {
		tls_free_rec(sk, new);
		return ret;
	}

	*orig_end = msg_opl->sg.end;
	i = msg_opl->sg.start;
	sge = sk_msg_elem(msg_opl, i);
	while (apply && sge->length) {
		if (sge->length > apply) {
			u32 len = sge->length - apply;

			get_page(sg_page(sge));
			sg_set_page(&tmp, sg_page(sge), len,
				    sge->offset + apply);
			sge->length = apply;
			bytes += apply;
			apply = 0;
		} else {
			apply -= sge->length;
			bytes += sge->length;
		}

		sk_msg_iter_var_next(i);
		if (i == msg_opl->sg.end)
			break;
		sge = sk_msg_elem(msg_opl, i);
	}

	msg_opl->sg.end = i;
	msg_opl->sg.curr = i;
	msg_opl->sg.copybreak = 0;
	msg_opl->apply_bytes = 0;
	msg_opl->sg.size = bytes;

	msg_npl = &new->msg_plaintext;
	msg_npl->apply_bytes = apply;
	msg_npl->sg.size = orig_size - bytes;

	j = msg_npl->sg.start;
	nsge = sk_msg_elem(msg_npl, j);
	if (tmp.length) {
		memcpy(nsge, &tmp, sizeof(*nsge));
		sk_msg_iter_var_next(j);
		nsge = sk_msg_elem(msg_npl, j);
	}

	osge = sk_msg_elem(msg_opl, i);
	while (osge->length) {
		memcpy(nsge, osge, sizeof(*nsge));
		sg_unmark_end(nsge);
		sk_msg_iter_var_next(i);
		sk_msg_iter_var_next(j);
		if (i == *orig_end)
			break;
		osge = sk_msg_elem(msg_opl, i);
		nsge = sk_msg_elem(msg_npl, j);
	}

	msg_npl->sg.end = j;
	msg_npl->sg.curr = j;
	msg_npl->sg.copybreak = 0;

	*to = new;
	return 0;
}

static void tls_merge_open_record(struct sock *sk, struct tls_rec *to,
				  struct tls_rec *from, u32 orig_end)
{
	struct sk_msg *msg_npl = &from->msg_plaintext;
	struct sk_msg *msg_opl = &to->msg_plaintext;
	struct scatterlist *osge, *nsge;
	u32 i, j;

	i = msg_opl->sg.end;
	sk_msg_iter_var_prev(i);
	j = msg_npl->sg.start;

	osge = sk_msg_elem(msg_opl, i);
	nsge = sk_msg_elem(msg_npl, j);

	if (sg_page(osge) == sg_page(nsge) &&
	    osge->offset + osge->length == nsge->offset) {
		osge->length += nsge->length;
		put_page(sg_page(nsge));
	}

	msg_opl->sg.end = orig_end;
	msg_opl->sg.curr = orig_end;
	msg_opl->sg.copybreak = 0;
	msg_opl->apply_bytes = msg_opl->sg.size + msg_npl->sg.size;
	msg_opl->sg.size += msg_npl->sg.size;

	sk_msg_free(sk, &to->msg_encrypted);
	sk_msg_xfer_full(&to->msg_encrypted, &from->msg_encrypted);

	kfree(from);
}

D
Dave Watson 已提交
688 689 690 691
static int tls_push_record(struct sock *sk, int flags,
			   unsigned char record_type)
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
692
	struct tls_prot_info *prot = &tls_ctx->prot_info;
B
Boris Pismenny 已提交
693
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
694
	struct tls_rec *rec = ctx->open_rec, *tmp = NULL;
695
	u32 i, split_point, orig_end;
696
	struct sk_msg *msg_pl, *msg_en;
697
	struct aead_request *req;
698
	bool split;
D
Dave Watson 已提交
699 700
	int rc;

701 702
	if (!rec)
		return 0;
703

704 705 706
	msg_pl = &rec->msg_plaintext;
	msg_en = &rec->msg_encrypted;

707 708
	split_point = msg_pl->apply_bytes;
	split = split_point && split_point < msg_pl->sg.size;
709 710 711 712 713 714 715 716 717
	if (unlikely((!split &&
		      msg_pl->sg.size +
		      prot->overhead_size > msg_en->sg.size) ||
		     (split &&
		      split_point +
		      prot->overhead_size > msg_en->sg.size))) {
		split = true;
		split_point = msg_en->sg.size;
	}
718 719
	if (split) {
		rc = tls_split_open_record(sk, rec, &tmp, msg_pl, msg_en,
720
					   split_point, prot->overhead_size,
721 722 723
					   &orig_end);
		if (rc < 0)
			return rc;
724 725 726 727 728 729 730 731 732 733 734
		/* This can happen if above tls_split_open_record allocates
		 * a single large encryption buffer instead of two smaller
		 * ones. In this case adjust pointers and continue without
		 * split.
		 */
		if (!msg_pl->sg.size) {
			tls_merge_open_record(sk, rec, tmp, orig_end);
			msg_pl = &rec->msg_plaintext;
			msg_en = &rec->msg_encrypted;
			split = false;
		}
735
		sk_msg_trim(sk, msg_en, msg_pl->sg.size +
736
			    prot->overhead_size);
737 738
	}

739 740
	rec->tx_flags = flags;
	req = &rec->aead_req;
D
Dave Watson 已提交
741

742 743
	i = msg_pl->sg.end;
	sk_msg_iter_var_prev(i);
D
Dave Watson 已提交
744 745

	rec->content_type = record_type;
746
	if (prot->version == TLS_1_3_VERSION) {
D
Dave Watson 已提交
747 748 749 750 751 752 753 754
		/* Add content type to end of message.  No padding added */
		sg_set_buf(&rec->sg_content_type, &rec->content_type, 1);
		sg_mark_end(&rec->sg_content_type);
		sg_chain(msg_pl->sg.data, msg_pl->sg.end + 1,
			 &rec->sg_content_type);
	} else {
		sg_mark_end(sk_msg_elem(msg_pl, i));
	}
755

756 757 758 759 760 761
	if (msg_pl->sg.end < msg_pl->sg.start) {
		sg_chain(&msg_pl->sg.data[msg_pl->sg.start],
			 MAX_SKB_FRAGS - msg_pl->sg.start + 1,
			 msg_pl->sg.data);
	}

762
	i = msg_pl->sg.start;
763
	sg_chain(rec->sg_aead_in, 2, &msg_pl->sg.data[i]);
764 765 766 767 768 769 770 771

	i = msg_en->sg.end;
	sk_msg_iter_var_prev(i);
	sg_mark_end(sk_msg_elem(msg_en, i));

	i = msg_en->sg.start;
	sg_chain(rec->sg_aead_out, 2, &msg_en->sg.data[i]);

772
	tls_make_aad(rec->aad_space, msg_pl->sg.size + prot->tail_size,
773
		     tls_ctx->tx.rec_seq, record_type, prot);
D
Dave Watson 已提交
774 775

	tls_fill_prepend(tls_ctx,
776
			 page_address(sg_page(&msg_en->sg.data[i])) +
D
Dave Watson 已提交
777
			 msg_en->sg.data[i].offset,
778
			 msg_pl->sg.size + prot->tail_size,
779
			 record_type);
D
Dave Watson 已提交
780

781
	tls_ctx->pending_open_record_frags = false;
D
Dave Watson 已提交
782

D
Dave Watson 已提交
783
	rc = tls_do_encryption(sk, tls_ctx, ctx, req,
784
			       msg_pl->sg.size + prot->tail_size, i);
785
	if (rc < 0) {
786
		if (rc != -EINPROGRESS) {
787
			tls_err_abort(sk, -EBADMSG);
788 789 790 791 792
			if (split) {
				tls_ctx->pending_open_record_frags = true;
				tls_merge_open_record(sk, rec, tmp, orig_end);
			}
		}
793
		ctx->async_capable = 1;
794
		return rc;
795 796 797
	} else if (split) {
		msg_pl = &tmp->msg_plaintext;
		msg_en = &tmp->msg_encrypted;
798
		sk_msg_trim(sk, msg_en, msg_pl->sg.size + prot->overhead_size);
799 800
		tls_ctx->pending_open_record_frags = true;
		ctx->open_rec = tmp;
801
	}
D
Dave Watson 已提交
802

803
	return tls_tx_records(sk, flags);
D
Dave Watson 已提交
804 805
}

806 807
static int bpf_exec_tx_verdict(struct sk_msg *msg, struct sock *sk,
			       bool full_record, u8 record_type,
808
			       ssize_t *copied, int flags)
D
Dave Watson 已提交
809 810
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
811
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
812 813 814
	struct sk_msg msg_redir = { };
	struct sk_psock *psock;
	struct sock *sk_redir;
815
	struct tls_rec *rec;
816
	bool enospc, policy;
817
	int err = 0, send;
818
	u32 delta = 0;
819

820
	policy = !(flags & MSG_SENDPAGE_NOPOLICY);
821
	psock = sk_psock_get(sk);
822 823
	if (!psock || !policy) {
		err = tls_push_record(sk, flags, record_type);
824
		if (err && sk->sk_err == EBADMSG) {
825 826
			*copied -= sk_msg_free(sk, msg);
			tls_free_open_rec(sk);
827
			err = -sk->sk_err;
828
		}
829 830
		if (psock)
			sk_psock_put(sk, psock);
831 832
		return err;
	}
833 834
more_data:
	enospc = sk_msg_full(msg);
835 836
	if (psock->eval == __SK_NONE) {
		delta = msg->sg.size;
837
		psock->eval = sk_psock_msg_verdict(sk, psock, msg);
838
		delta -= msg->sg.size;
839
	}
840 841 842 843 844 845 846 847 848 849 850 851 852
	if (msg->cork_bytes && msg->cork_bytes > msg->sg.size &&
	    !enospc && !full_record) {
		err = -ENOSPC;
		goto out_err;
	}
	msg->cork_bytes = 0;
	send = msg->sg.size;
	if (msg->apply_bytes && msg->apply_bytes < send)
		send = msg->apply_bytes;

	switch (psock->eval) {
	case __SK_PASS:
		err = tls_push_record(sk, flags, record_type);
853
		if (err && sk->sk_err == EBADMSG) {
854 855
			*copied -= sk_msg_free(sk, msg);
			tls_free_open_rec(sk);
856
			err = -sk->sk_err;
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
			goto out_err;
		}
		break;
	case __SK_REDIRECT:
		sk_redir = psock->sk_redir;
		memcpy(&msg_redir, msg, sizeof(*msg));
		if (msg->apply_bytes < send)
			msg->apply_bytes = 0;
		else
			msg->apply_bytes -= send;
		sk_msg_return_zero(sk, msg, send);
		msg->sg.size -= send;
		release_sock(sk);
		err = tcp_bpf_sendmsg_redir(sk_redir, &msg_redir, send, flags);
		lock_sock(sk);
		if (err < 0) {
			*copied -= sk_msg_free_nocharge(sk, &msg_redir);
			msg->sg.size = 0;
		}
		if (msg->sg.size == 0)
			tls_free_open_rec(sk);
		break;
	case __SK_DROP:
	default:
		sk_msg_free_partial(sk, msg, send);
		if (msg->apply_bytes < send)
			msg->apply_bytes = 0;
		else
			msg->apply_bytes -= send;
		if (msg->sg.size == 0)
			tls_free_open_rec(sk);
888
		*copied -= (send + delta);
889 890
		err = -EACCES;
	}
891

892 893
	if (likely(!err)) {
		bool reset_eval = !ctx->open_rec;
894

895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
		rec = ctx->open_rec;
		if (rec) {
			msg = &rec->msg_plaintext;
			if (!msg->apply_bytes)
				reset_eval = true;
		}
		if (reset_eval) {
			psock->eval = __SK_NONE;
			if (psock->sk_redir) {
				sock_put(psock->sk_redir);
				psock->sk_redir = NULL;
			}
		}
		if (rec)
			goto more_data;
	}
 out_err:
	sk_psock_put(sk, psock);
	return err;
}

static int tls_sw_push_pending_record(struct sock *sk, int flags)
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
	struct tls_rec *rec = ctx->open_rec;
	struct sk_msg *msg_pl;
	size_t copied;
923 924

	if (!rec)
925
		return 0;
926

927
	msg_pl = &rec->msg_plaintext;
928 929 930
	copied = msg_pl->sg.size;
	if (!copied)
		return 0;
931

932 933
	return bpf_exec_tx_verdict(msg_pl, sk, true, TLS_RECORD_TYPE_DATA,
				   &copied, flags);
934 935 936 937
}

int tls_sw_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
{
D
Dave Watson 已提交
938
	long timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
939
	struct tls_context *tls_ctx = tls_get_ctx(sk);
940
	struct tls_prot_info *prot = &tls_ctx->prot_info;
941
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
942
	bool async_capable = ctx->async_capable;
943
	unsigned char record_type = TLS_RECORD_TYPE_DATA;
D
David Howells 已提交
944
	bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
D
Dave Watson 已提交
945
	bool eor = !(msg->msg_flags & MSG_MORE);
946 947
	size_t try_to_copy;
	ssize_t copied = 0;
948
	struct sk_msg *msg_pl, *msg_en;
949 950 951
	struct tls_rec *rec;
	int required_size;
	int num_async = 0;
D
Dave Watson 已提交
952
	bool full_record;
953 954
	int record_room;
	int num_zc = 0;
D
Dave Watson 已提交
955
	int orig_size;
956
	int ret = 0;
957
	int pending;
D
Dave Watson 已提交
958

959 960
	if (msg->msg_flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
			       MSG_CMSG_COMPAT))
961
		return -EOPNOTSUPP;
D
Dave Watson 已提交
962

J
Jakub Kicinski 已提交
963
	mutex_lock(&tls_ctx->tx_lock);
D
Dave Watson 已提交
964 965 966
	lock_sock(sk);

	if (unlikely(msg->msg_controllen)) {
J
Jakub Kicinski 已提交
967
		ret = tls_process_cmsg(sk, msg, &record_type);
968 969 970 971 972 973
		if (ret) {
			if (ret == -EINPROGRESS)
				num_async++;
			else if (ret != -EAGAIN)
				goto send_end;
		}
D
Dave Watson 已提交
974 975 976 977
	}

	while (msg_data_left(msg)) {
		if (sk->sk_err) {
978
			ret = -sk->sk_err;
D
Dave Watson 已提交
979 980 981
			goto send_end;
		}

982 983 984 985
		if (ctx->open_rec)
			rec = ctx->open_rec;
		else
			rec = ctx->open_rec = tls_get_rec(sk);
986 987 988 989 990
		if (!rec) {
			ret = -ENOMEM;
			goto send_end;
		}

991 992 993 994
		msg_pl = &rec->msg_plaintext;
		msg_en = &rec->msg_encrypted;

		orig_size = msg_pl->sg.size;
D
Dave Watson 已提交
995 996
		full_record = false;
		try_to_copy = msg_data_left(msg);
997
		record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
D
Dave Watson 已提交
998 999 1000 1001 1002
		if (try_to_copy >= record_room) {
			try_to_copy = record_room;
			full_record = true;
		}

1003
		required_size = msg_pl->sg.size + try_to_copy +
1004
				prot->overhead_size;
D
Dave Watson 已提交
1005 1006 1007

		if (!sk_stream_memory_free(sk))
			goto wait_for_sndbuf;
1008

D
Dave Watson 已提交
1009
alloc_encrypted:
1010
		ret = tls_alloc_encrypted_msg(sk, required_size);
D
Dave Watson 已提交
1011 1012 1013 1014 1015 1016 1017 1018
		if (ret) {
			if (ret != -ENOSPC)
				goto wait_for_memory;

			/* Adjust try_to_copy according to the amount that was
			 * actually allocated. The difference is due
			 * to max sg elements limit
			 */
1019
			try_to_copy -= required_size - msg_en->sg.size;
D
Dave Watson 已提交
1020 1021
			full_record = true;
		}
1022 1023

		if (!is_kvec && (full_record || eor) && !async_capable) {
1024 1025
			u32 first = msg_pl->sg.end;

1026 1027
			ret = sk_msg_zerocopy_from_iter(sk, &msg->msg_iter,
							msg_pl, try_to_copy);
D
Dave Watson 已提交
1028 1029 1030
			if (ret)
				goto fallback_to_reg_send;

1031
			num_zc++;
D
Dave Watson 已提交
1032
			copied += try_to_copy;
1033 1034 1035 1036 1037

			sk_msg_sg_copy_set(msg_pl, first);
			ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
						  record_type, &copied,
						  msg->msg_flags);
1038 1039 1040
			if (ret) {
				if (ret == -EINPROGRESS)
					num_async++;
1041 1042
				else if (ret == -ENOMEM)
					goto wait_for_memory;
1043
				else if (ctx->open_rec && ret == -ENOSPC)
1044
					goto rollback_iter;
1045 1046 1047
				else if (ret != -EAGAIN)
					goto send_end;
			}
1048
			continue;
1049 1050 1051 1052 1053
rollback_iter:
			copied -= try_to_copy;
			sk_msg_sg_copy_clear(msg_pl, first);
			iov_iter_revert(&msg->msg_iter,
					msg_pl->sg.size - orig_size);
D
Dave Watson 已提交
1054
fallback_to_reg_send:
1055
			sk_msg_trim(sk, msg_pl, orig_size);
D
Dave Watson 已提交
1056 1057
		}

1058
		required_size = msg_pl->sg.size + try_to_copy;
1059

1060
		ret = tls_clone_plaintext_msg(sk, required_size);
D
Dave Watson 已提交
1061 1062
		if (ret) {
			if (ret != -ENOSPC)
1063
				goto send_end;
D
Dave Watson 已提交
1064 1065 1066 1067 1068

			/* Adjust try_to_copy according to the amount that was
			 * actually allocated. The difference is due
			 * to max sg elements limit
			 */
1069
			try_to_copy -= required_size - msg_pl->sg.size;
D
Dave Watson 已提交
1070
			full_record = true;
1071 1072
			sk_msg_trim(sk, msg_en,
				    msg_pl->sg.size + prot->overhead_size);
D
Dave Watson 已提交
1073 1074
		}

1075 1076 1077 1078 1079 1080
		if (try_to_copy) {
			ret = sk_msg_memcopy_from_iter(sk, &msg->msg_iter,
						       msg_pl, try_to_copy);
			if (ret < 0)
				goto trim_sgl;
		}
D
Dave Watson 已提交
1081

1082 1083 1084 1085
		/* Open records defined only if successfully copied, otherwise
		 * we would trim the sg but not reset the open record frags.
		 */
		tls_ctx->pending_open_record_frags = true;
D
Dave Watson 已提交
1086 1087
		copied += try_to_copy;
		if (full_record || eor) {
1088 1089 1090
			ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
						  record_type, &copied,
						  msg->msg_flags);
D
Dave Watson 已提交
1091
			if (ret) {
1092 1093
				if (ret == -EINPROGRESS)
					num_async++;
1094 1095 1096 1097 1098
				else if (ret == -ENOMEM)
					goto wait_for_memory;
				else if (ret != -EAGAIN) {
					if (ret == -ENOSPC)
						ret = 0;
1099
					goto send_end;
1100
				}
D
Dave Watson 已提交
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
			}
		}

		continue;

wait_for_sndbuf:
		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
wait_for_memory:
		ret = sk_stream_wait_memory(sk, &timeo);
		if (ret) {
trim_sgl:
1112 1113
			if (ctx->open_rec)
				tls_trim_both_msgs(sk, orig_size);
D
Dave Watson 已提交
1114 1115 1116
			goto send_end;
		}

1117
		if (ctx->open_rec && msg_en->sg.size < required_size)
D
Dave Watson 已提交
1118 1119 1120
			goto alloc_encrypted;
	}

1121 1122 1123 1124
	if (!num_async) {
		goto send_end;
	} else if (num_zc) {
		/* Wait for pending encryptions to get completed */
1125 1126
		spin_lock_bh(&ctx->encrypt_compl_lock);
		ctx->async_notify = true;
1127

1128 1129 1130
		pending = atomic_read(&ctx->encrypt_pending);
		spin_unlock_bh(&ctx->encrypt_compl_lock);
		if (pending)
1131 1132 1133 1134
			crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
		else
			reinit_completion(&ctx->async_wait.completion);

1135 1136 1137
		/* There can be no concurrent accesses, since we have no
		 * pending encrypt operations
		 */
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
		WRITE_ONCE(ctx->async_notify, false);

		if (ctx->async_wait.err) {
			ret = ctx->async_wait.err;
			copied = 0;
		}
	}

	/* Transmit if any encryptions have completed */
	if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
		cancel_delayed_work(&ctx->tx_work.work);
		tls_tx_records(sk, msg->msg_flags);
	}

D
Dave Watson 已提交
1152 1153 1154 1155
send_end:
	ret = sk_stream_error(sk, msg->msg_flags, ret);

	release_sock(sk);
J
Jakub Kicinski 已提交
1156
	mutex_unlock(&tls_ctx->tx_lock);
1157
	return copied > 0 ? copied : ret;
D
Dave Watson 已提交
1158 1159
}

1160 1161
static int tls_sw_do_sendpage(struct sock *sk, struct page *page,
			      int offset, size_t size, int flags)
D
Dave Watson 已提交
1162
{
1163
	long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
D
Dave Watson 已提交
1164
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
1165
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
1166
	struct tls_prot_info *prot = &tls_ctx->prot_info;
D
Dave Watson 已提交
1167
	unsigned char record_type = TLS_RECORD_TYPE_DATA;
1168
	struct sk_msg *msg_pl;
1169 1170
	struct tls_rec *rec;
	int num_async = 0;
1171
	ssize_t copied = 0;
D
Dave Watson 已提交
1172 1173
	bool full_record;
	int record_room;
1174
	int ret = 0;
1175
	bool eor;
D
Dave Watson 已提交
1176

1177
	eor = !(flags & MSG_SENDPAGE_NOTLAST);
D
Dave Watson 已提交
1178 1179 1180 1181 1182 1183 1184
	sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);

	/* Call the sk_stream functions to manage the sndbuf mem. */
	while (size > 0) {
		size_t copy, required_size;

		if (sk->sk_err) {
1185
			ret = -sk->sk_err;
D
Dave Watson 已提交
1186 1187 1188
			goto sendpage_end;
		}

1189 1190 1191 1192
		if (ctx->open_rec)
			rec = ctx->open_rec;
		else
			rec = ctx->open_rec = tls_get_rec(sk);
1193 1194 1195 1196 1197
		if (!rec) {
			ret = -ENOMEM;
			goto sendpage_end;
		}

1198 1199
		msg_pl = &rec->msg_plaintext;

D
Dave Watson 已提交
1200
		full_record = false;
1201
		record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
D
Dave Watson 已提交
1202 1203 1204 1205 1206
		copy = size;
		if (copy >= record_room) {
			copy = record_room;
			full_record = true;
		}
1207

1208
		required_size = msg_pl->sg.size + copy + prot->overhead_size;
D
Dave Watson 已提交
1209 1210 1211 1212

		if (!sk_stream_memory_free(sk))
			goto wait_for_sndbuf;
alloc_payload:
1213
		ret = tls_alloc_encrypted_msg(sk, required_size);
D
Dave Watson 已提交
1214 1215 1216 1217 1218 1219 1220 1221
		if (ret) {
			if (ret != -ENOSPC)
				goto wait_for_memory;

			/* Adjust copy according to the amount that was
			 * actually allocated. The difference is due
			 * to max sg elements limit
			 */
1222
			copy -= required_size - msg_pl->sg.size;
D
Dave Watson 已提交
1223 1224 1225
			full_record = true;
		}

1226
		sk_msg_page_add(msg_pl, page, copy, offset);
D
Dave Watson 已提交
1227
		sk_mem_charge(sk, copy);
1228

D
Dave Watson 已提交
1229 1230
		offset += copy;
		size -= copy;
1231
		copied += copy;
D
Dave Watson 已提交
1232

1233 1234
		tls_ctx->pending_open_record_frags = true;
		if (full_record || eor || sk_msg_full(msg_pl)) {
1235 1236
			ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
						  record_type, &copied, flags);
D
Dave Watson 已提交
1237
			if (ret) {
1238 1239
				if (ret == -EINPROGRESS)
					num_async++;
1240 1241 1242 1243 1244
				else if (ret == -ENOMEM)
					goto wait_for_memory;
				else if (ret != -EAGAIN) {
					if (ret == -ENOSPC)
						ret = 0;
1245
					goto sendpage_end;
1246
				}
D
Dave Watson 已提交
1247 1248 1249 1250 1251 1252 1253 1254
			}
		}
		continue;
wait_for_sndbuf:
		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
wait_for_memory:
		ret = sk_stream_wait_memory(sk, &timeo);
		if (ret) {
1255 1256
			if (ctx->open_rec)
				tls_trim_both_msgs(sk, msg_pl->sg.size);
D
Dave Watson 已提交
1257 1258 1259
			goto sendpage_end;
		}

1260 1261
		if (ctx->open_rec)
			goto alloc_payload;
D
Dave Watson 已提交
1262 1263
	}

1264 1265 1266 1267 1268 1269 1270
	if (num_async) {
		/* Transmit if any encryptions have completed */
		if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
			cancel_delayed_work(&ctx->tx_work.work);
			tls_tx_records(sk, flags);
		}
	}
D
Dave Watson 已提交
1271
sendpage_end:
1272
	ret = sk_stream_error(sk, flags, ret);
1273
	return copied > 0 ? copied : ret;
D
Dave Watson 已提交
1274 1275
}

1276 1277 1278 1279 1280 1281
int tls_sw_sendpage_locked(struct sock *sk, struct page *page,
			   int offset, size_t size, int flags)
{
	if (flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
		      MSG_SENDPAGE_NOTLAST | MSG_SENDPAGE_NOPOLICY |
		      MSG_NO_SHARED_FRAGS))
1282
		return -EOPNOTSUPP;
1283 1284 1285 1286

	return tls_sw_do_sendpage(sk, page, offset, size, flags);
}

1287 1288 1289
int tls_sw_sendpage(struct sock *sk, struct page *page,
		    int offset, size_t size, int flags)
{
J
Jakub Kicinski 已提交
1290
	struct tls_context *tls_ctx = tls_get_ctx(sk);
1291 1292 1293 1294
	int ret;

	if (flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
		      MSG_SENDPAGE_NOTLAST | MSG_SENDPAGE_NOPOLICY))
1295
		return -EOPNOTSUPP;
1296

J
Jakub Kicinski 已提交
1297
	mutex_lock(&tls_ctx->tx_lock);
1298 1299 1300
	lock_sock(sk);
	ret = tls_sw_do_sendpage(sk, page, offset, size, flags);
	release_sock(sk);
J
Jakub Kicinski 已提交
1301
	mutex_unlock(&tls_ctx->tx_lock);
1302 1303 1304
	return ret;
}

1305 1306 1307
static int
tls_rx_rec_wait(struct sock *sk, struct sk_psock *psock, bool nonblock,
		long timeo)
D
Dave Watson 已提交
1308 1309
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
1310
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
1311 1312
	DEFINE_WAIT_FUNC(wait, woken_wake_function);

1313 1314 1315 1316 1317 1318
	while (!ctx->recv_pkt) {
		if (!sk_psock_queue_empty(psock))
			return 0;

		if (sk->sk_err)
			return sock_error(sk);
D
Dave Watson 已提交
1319

1320 1321 1322
		if (!skb_queue_empty(&sk->sk_receive_queue)) {
			__strp_unpause(&ctx->strp);
			if (ctx->recv_pkt)
1323
				break;
1324 1325
		}

1326
		if (sk->sk_shutdown & RCV_SHUTDOWN)
1327
			return 0;
1328

D
Dave Watson 已提交
1329
		if (sock_flag(sk, SOCK_DONE))
1330
			return 0;
D
Dave Watson 已提交
1331

1332 1333
		if (nonblock || !timeo)
			return -EAGAIN;
D
Dave Watson 已提交
1334 1335 1336

		add_wait_queue(sk_sleep(sk), &wait);
		sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1337
		sk_wait_event(sk, &timeo,
1338
			      ctx->recv_pkt || !sk_psock_queue_empty(psock),
1339
			      &wait);
D
Dave Watson 已提交
1340 1341 1342 1343
		sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
		remove_wait_queue(sk_sleep(sk), &wait);

		/* Handle signals */
1344 1345
		if (signal_pending(current))
			return sock_intr_errno(timeo);
D
Dave Watson 已提交
1346 1347
	}

1348
	return 1;
D
Dave Watson 已提交
1349 1350
}

1351
static int tls_setup_from_iter(struct iov_iter *from,
1352 1353 1354 1355 1356 1357
			       int length, int *pages_used,
			       struct scatterlist *to,
			       int to_max_pages)
{
	int rc = 0, i = 0, num_elem = *pages_used, maxpages;
	struct page *pages[MAX_SKB_FRAGS];
1358
	unsigned int size = 0;
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
	ssize_t copied, use;
	size_t offset;

	while (length > 0) {
		i = 0;
		maxpages = to_max_pages - num_elem;
		if (maxpages == 0) {
			rc = -EFAULT;
			goto out;
		}
		copied = iov_iter_get_pages(from, pages,
					    length,
					    maxpages, &offset);
		if (copied <= 0) {
			rc = -EFAULT;
			goto out;
		}

		iov_iter_advance(from, copied);

		length -= copied;
		size += copied;
		while (copied) {
			use = min_t(int, copied, PAGE_SIZE - offset);

			sg_set_page(&to[num_elem],
				    pages[i], use, offset);
			sg_unmark_end(&to[num_elem]);
			/* We do not uncharge memory from this API */

			offset = 0;
			copied -= use;

			i++;
			num_elem++;
		}
	}
	/* Mark the end in the last sg entry if newly added */
	if (num_elem > *pages_used)
		sg_mark_end(&to[num_elem - 1]);
out:
	if (rc)
1401
		iov_iter_revert(from, size);
1402 1403 1404 1405 1406
	*pages_used = num_elem;

	return rc;
}

1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
/* Decrypt handlers
 *
 * tls_decrypt_sg() and tls_decrypt_device() are decrypt handlers.
 * They must transform the darg in/out argument are as follows:
 *       |          Input            |         Output
 * -------------------------------------------------------------------
 *    zc | Zero-copy decrypt allowed | Zero-copy performed
 * async | Async decrypt allowed     | Async crypto used / in progress
 */

1417
/* This function decrypts the input skb into either out_iov or in out_sg
1418
 * or in skb buffers itself. The input parameter 'darg->zc' indicates if
1419 1420 1421
 * zero-copy mode needs to be tried or not. With zero-copy mode, either
 * out_iov or out_sg must be non-NULL. In case both out_iov and out_sg are
 * NULL, then the decryption happens inside skb buffers itself, i.e.
1422
 * zero-copy gets disabled and 'darg->zc' is updated.
1423
 */
1424
static int tls_decrypt_sg(struct sock *sk, struct iov_iter *out_iov,
1425 1426
			  struct scatterlist *out_sg,
			  struct tls_decrypt_arg *darg)
1427 1428 1429
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1430
	struct tls_prot_info *prot = &tls_ctx->prot_info;
1431
	int n_sgin, n_sgout, aead_size, err, pages = 0;
1432
	struct sk_buff *skb = tls_strp_msg(ctx);
1433
	struct strp_msg *rxm = strp_msg(skb);
1434
	struct tls_msg *tlm = tls_msg(skb);
1435 1436 1437 1438
	struct aead_request *aead_req;
	struct sk_buff *unused;
	struct scatterlist *sgin = NULL;
	struct scatterlist *sgout = NULL;
1439
	const int data_len = rxm->full_len - prot->overhead_size;
1440
	int tail_pages = !!prot->tail_size;
1441
	struct tls_decrypt_ctx *dctx;
1442
	int iv_offset = 0;
1443
	u8 *mem;
1444

1445
	if (darg->zc && (out_iov || out_sg)) {
1446
		if (out_iov)
1447
			n_sgout = 1 + tail_pages +
1448
				iov_iter_npages_cap(out_iov, INT_MAX, data_len);
1449 1450
		else
			n_sgout = sg_nents(out_sg);
1451 1452
		n_sgin = skb_nsg(skb, rxm->offset + prot->prepend_size,
				 rxm->full_len - prot->prepend_size);
1453 1454
	} else {
		n_sgout = 0;
1455
		darg->zc = false;
1456
		n_sgin = skb_cow_data(skb, 0, &unused);
1457 1458 1459 1460 1461 1462 1463 1464 1465
	}

	if (n_sgin < 1)
		return -EBADMSG;

	/* Increment to accommodate AAD */
	n_sgin = n_sgin + 1;

	/* Allocate a single block of memory which contains
1466 1467
	 *   aead_req || tls_decrypt_ctx.
	 * Both structs are variable length.
1468
	 */
1469 1470 1471
	aead_size = sizeof(*aead_req) + crypto_aead_reqsize(ctx->aead_recv);
	mem = kmalloc(aead_size + struct_size(dctx, sg, n_sgin + n_sgout),
		      sk->sk_allocation);
1472 1473 1474 1475 1476
	if (!mem)
		return -ENOMEM;

	/* Segment the allocated memory */
	aead_req = (struct aead_request *)mem;
1477 1478 1479
	dctx = (struct tls_decrypt_ctx *)(mem + aead_size);
	sgin = &dctx->sg[0];
	sgout = &dctx->sg[n_sgin];
1480

1481 1482 1483
	/* For CCM based ciphers, first byte of nonce+iv is a constant */
	switch (prot->cipher_type) {
	case TLS_CIPHER_AES_CCM_128:
1484
		dctx->iv[0] = TLS_AES_CCM_IV_B0_BYTE;
1485
		iv_offset = 1;
1486 1487
		break;
	case TLS_CIPHER_SM4_CCM:
1488
		dctx->iv[0] = TLS_SM4_CCM_IV_B0_BYTE;
1489 1490
		iv_offset = 1;
		break;
1491 1492
	}

1493
	/* Prepare IV */
1494
	if (prot->version == TLS_1_3_VERSION ||
1495
	    prot->cipher_type == TLS_CIPHER_CHACHA20_POLY1305) {
1496
		memcpy(&dctx->iv[iv_offset], tls_ctx->rx.iv,
1497
		       prot->iv_size + prot->salt_size);
1498 1499
	} else {
		err = skb_copy_bits(skb, rxm->offset + TLS_HEADER_SIZE,
1500
				    &dctx->iv[iv_offset] + prot->salt_size,
1501
				    prot->iv_size);
1502 1503
		if (err < 0)
			goto exit_free;
1504
		memcpy(&dctx->iv[iv_offset], tls_ctx->rx.iv, prot->salt_size);
1505
	}
J
Jakub Kicinski 已提交
1506
	tls_xor_iv_with_seq(prot, &dctx->iv[iv_offset], tls_ctx->rx.rec_seq);
1507 1508

	/* Prepare AAD */
1509
	tls_make_aad(dctx->aad, rxm->full_len - prot->overhead_size +
1510
		     prot->tail_size,
1511
		     tls_ctx->rx.rec_seq, tlm->control, prot);
1512 1513 1514

	/* Prepare sgin */
	sg_init_table(sgin, n_sgin);
1515
	sg_set_buf(&sgin[0], dctx->aad, prot->aad_size);
1516
	err = skb_to_sgvec(skb, &sgin[1],
1517 1518
			   rxm->offset + prot->prepend_size,
			   rxm->full_len - prot->prepend_size);
1519 1520
	if (err < 0)
		goto exit_free;
1521 1522 1523 1524

	if (n_sgout) {
		if (out_iov) {
			sg_init_table(sgout, n_sgout);
1525
			sg_set_buf(&sgout[0], dctx->aad, prot->aad_size);
1526

1527
			err = tls_setup_from_iter(out_iov, data_len,
1528
						  &pages, &sgout[1],
1529
						  (n_sgout - 1 - tail_pages));
1530 1531
			if (err < 0)
				goto fallback_to_reg_recv;
1532 1533 1534

			if (prot->tail_size) {
				sg_unmark_end(&sgout[pages]);
1535
				sg_set_buf(&sgout[pages + 1], &dctx->tail,
1536 1537 1538
					   prot->tail_size);
				sg_mark_end(&sgout[pages + 1]);
			}
1539 1540 1541 1542 1543 1544 1545 1546 1547
		} else if (out_sg) {
			memcpy(sgout, out_sg, n_sgout * sizeof(*sgout));
		} else {
			goto fallback_to_reg_recv;
		}
	} else {
fallback_to_reg_recv:
		sgout = sgin;
		pages = 0;
1548
		darg->zc = false;
1549 1550 1551
	}

	/* Prepare and submit AEAD request */
1552
	err = tls_do_decryption(sk, skb, sgin, sgout, dctx->iv,
1553
				data_len + prot->tail_size, aead_req, darg);
1554 1555
	if (darg->async)
		return 0;
1556

1557
	if (prot->tail_size)
1558
		darg->tail = dctx->tail;
1559

1560 1561 1562
	/* Release the pages in case iov was mapped to pages */
	for (; pages > 0; pages--)
		put_page(sg_page(&sgout[pages]));
1563
exit_free:
1564 1565 1566 1567
	kfree(mem);
	return err;
}

1568 1569
static int
tls_decrypt_device(struct sock *sk, struct tls_context *tls_ctx,
1570
		   struct tls_decrypt_arg *darg)
1571 1572 1573 1574 1575 1576
{
	int err;

	if (tls_ctx->rx_conf != TLS_HW)
		return 0;

1577
	err = tls_device_decrypted(sk, tls_ctx);
1578 1579 1580 1581 1582 1583 1584 1585
	if (err <= 0)
		return err;

	darg->zc = false;
	darg->async = false;
	return 1;
}

1586 1587
static int tls_rx_one_record(struct sock *sk, struct iov_iter *dest,
			     struct tls_decrypt_arg *darg)
1588 1589
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
1590
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1591
	struct tls_prot_info *prot = &tls_ctx->prot_info;
1592
	struct strp_msg *rxm;
1593
	int pad, err;
1594

1595
	err = tls_decrypt_device(sk, tls_ctx, darg);
1596 1597 1598 1599
	if (err < 0)
		return err;
	if (err)
		goto decrypt_done;
D
Dave Watson 已提交
1600

1601
	err = tls_decrypt_sg(sk, dest, NULL, darg);
1602 1603 1604
	if (err < 0) {
		if (err == -EBADMSG)
			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSDECRYPTERROR);
1605
		return err;
1606
	}
1607 1608
	if (darg->async)
		goto decrypt_next;
1609 1610 1611 1612
	/* If opportunistic TLS 1.3 ZC failed retry without ZC */
	if (unlikely(darg->zc && prot->version == TLS_1_3_VERSION &&
		     darg->tail != TLS_RECORD_TYPE_DATA)) {
		darg->zc = false;
1613 1614
		if (!darg->tail)
			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSRXNOPADVIOL);
J
Jakub Kicinski 已提交
1615
		TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSDECRYPTRETRY);
1616
		return tls_rx_one_record(sk, dest, darg);
1617
	}
1618

1619
decrypt_done:
1620
	pad = tls_padding_length(prot, ctx->recv_pkt, darg);
1621 1622 1623
	if (pad < 0)
		return pad;

1624
	rxm = strp_msg(ctx->recv_pkt);
1625 1626 1627
	rxm->full_len -= pad;
	rxm->offset += prot->prepend_size;
	rxm->full_len -= prot->overhead_size;
1628 1629
decrypt_next:
	tls_advance_record_sn(sk, prot, &tls_ctx->rx);
1630 1631

	return 0;
1632 1633
}

1634
int decrypt_skb(struct sock *sk, struct scatterlist *sgout)
D
Dave Watson 已提交
1635
{
1636
	struct tls_decrypt_arg darg = { .zc = true, };
D
Dave Watson 已提交
1637

1638
	return tls_decrypt_sg(sk, NULL, sgout, &darg);
D
Dave Watson 已提交
1639 1640
}

1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
static int tls_record_content_type(struct msghdr *msg, struct tls_msg *tlm,
				   u8 *control)
{
	int err;

	if (!*control) {
		*control = tlm->control;
		if (!*control)
			return -EBADMSG;

		err = put_cmsg(msg, SOL_TLS, TLS_GET_RECORD_TYPE,
			       sizeof(*control), control);
		if (*control != TLS_RECORD_TYPE_DATA) {
			if (err || msg->msg_flags & MSG_CTRUNC)
				return -EIO;
		}
	} else if (*control != tlm->control) {
		return 0;
	}

	return 1;
}

1664 1665 1666 1667 1668 1669
static void tls_rx_rec_done(struct tls_sw_context_rx *ctx)
{
	ctx->recv_pkt = NULL;
	__strp_unpause(&ctx->strp);
}

1670
/* This function traverses the rx_list in tls receive context to copies the
1671
 * decrypted records into the buffer provided by caller zero copy is not
1672 1673 1674 1675 1676
 * true. Further, the records are removed from the rx_list if it is not a peek
 * case and the record has been consumed completely.
 */
static int process_rx_list(struct tls_sw_context_rx *ctx,
			   struct msghdr *msg,
1677
			   u8 *control,
1678 1679 1680 1681 1682 1683
			   size_t skip,
			   size_t len,
			   bool zc,
			   bool is_peek)
{
	struct sk_buff *skb = skb_peek(&ctx->rx_list);
1684
	struct tls_msg *tlm;
1685
	ssize_t copied = 0;
1686
	int err;
1687

1688 1689
	while (skip && skb) {
		struct strp_msg *rxm = strp_msg(skb);
1690 1691
		tlm = tls_msg(skb);

1692 1693
		err = tls_record_content_type(msg, tlm, control);
		if (err <= 0)
1694
			goto out;
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707

		if (skip < rxm->full_len)
			break;

		skip = skip - rxm->full_len;
		skb = skb_peek_next(skb, &ctx->rx_list);
	}

	while (len && skb) {
		struct sk_buff *next_skb;
		struct strp_msg *rxm = strp_msg(skb);
		int chunk = min_t(unsigned int, rxm->full_len - skip, len);

1708 1709
		tlm = tls_msg(skb);

1710 1711
		err = tls_record_content_type(msg, tlm, control);
		if (err <= 0)
1712
			goto out;
1713

1714
		if (!zc || (rxm->full_len - skip) > len) {
1715
			err = skb_copy_datagram_msg(skb, rxm->offset + skip,
1716 1717
						    msg, chunk);
			if (err < 0)
1718
				goto out;
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
		}

		len = len - chunk;
		copied = copied + chunk;

		/* Consume the data from record if it is non-peek case*/
		if (!is_peek) {
			rxm->offset = rxm->offset + chunk;
			rxm->full_len = rxm->full_len - chunk;

			/* Return if there is unconsumed data in the record */
			if (rxm->full_len - skip)
				break;
		}

		/* The remaining skip-bytes must lie in 1st record in rx_list.
		 * So from the 2nd record, 'skip' should be 0.
		 */
		skip = 0;

		if (msg)
			msg->msg_flags |= MSG_EOR;

		next_skb = skb_peek_next(skb, &ctx->rx_list);

		if (!is_peek) {
1745
			__skb_unlink(skb, &ctx->rx_list);
1746
			consume_skb(skb);
1747 1748 1749 1750
		}

		skb = next_skb;
	}
1751
	err = 0;
1752

1753 1754
out:
	return copied ? : err;
1755 1756
}

1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
static void
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)
{
	size_t max_rec;

	if (len_left <= decrypted)
		return;

	max_rec = prot->overhead_size - prot->tail_size + TLS_MAX_PAYLOAD_SIZE;
	if (done - *flushed_at < SZ_128K && tcp_inq(sk) > max_rec)
		return;

	*flushed_at = done;
	sk_flush_backlog(sk);
}

1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
static long tls_rx_reader_lock(struct sock *sk, struct tls_sw_context_rx *ctx,
			       bool nonblock)
{
	long timeo;

	lock_sock(sk);

	timeo = sock_rcvtimeo(sk, nonblock);

	while (unlikely(ctx->reader_present)) {
		DEFINE_WAIT_FUNC(wait, woken_wake_function);

		ctx->reader_contended = 1;

		add_wait_queue(&ctx->wq, &wait);
		sk_wait_event(sk, &timeo,
			      !READ_ONCE(ctx->reader_present), &wait);
		remove_wait_queue(&ctx->wq, &wait);

		if (!timeo)
			return -EAGAIN;
		if (signal_pending(current))
			return sock_intr_errno(timeo);
	}

	WRITE_ONCE(ctx->reader_present, 1);

	return timeo;
}

static void tls_rx_reader_unlock(struct sock *sk, struct tls_sw_context_rx *ctx)
{
	if (unlikely(ctx->reader_contended)) {
		if (wq_has_sleeper(&ctx->wq))
			wake_up(&ctx->wq);
		else
			ctx->reader_contended = 0;

		WARN_ON_ONCE(!ctx->reader_present);
	}

	WRITE_ONCE(ctx->reader_present, 0);
	release_sock(sk);
}

D
Dave Watson 已提交
1820 1821 1822 1823 1824 1825 1826
int tls_sw_recvmsg(struct sock *sk,
		   struct msghdr *msg,
		   size_t len,
		   int flags,
		   int *addr_len)
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
1827
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1828
	struct tls_prot_info *prot = &tls_ctx->prot_info;
1829
	struct sk_psock *psock;
1830 1831
	unsigned char control = 0;
	ssize_t decrypted = 0;
1832
	size_t flushed_at = 0;
D
Dave Watson 已提交
1833
	struct strp_msg *rxm;
1834
	struct tls_msg *tlm;
D
Dave Watson 已提交
1835 1836
	struct sk_buff *skb;
	ssize_t copied = 0;
1837
	bool async = false;
1838
	int target, err = 0;
D
Dave Watson 已提交
1839
	long timeo;
D
David Howells 已提交
1840
	bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
1841
	bool is_peek = flags & MSG_PEEK;
1842
	bool bpf_strp_enabled;
1843
	bool zc_capable;
D
Dave Watson 已提交
1844 1845 1846 1847

	if (unlikely(flags & MSG_ERRQUEUE))
		return sock_recv_errqueue(sk, msg, len, SOL_IP, IP_RECVERR);

1848
	psock = sk_psock_get(sk);
1849 1850 1851
	timeo = tls_rx_reader_lock(sk, ctx, flags & MSG_DONTWAIT);
	if (timeo < 0)
		return timeo;
1852
	bpf_strp_enabled = sk_psock_strp_enabled(psock);
D
Dave Watson 已提交
1853

1854 1855 1856 1857 1858
	/* If crypto failed the connection is broken */
	err = ctx->async_wait.err;
	if (err)
		goto end;

1859
	/* Process pending decrypted records. It must be non-zero-copy */
1860
	err = process_rx_list(ctx, msg, &control, 0, len, false, is_peek);
1861
	if (err < 0)
1862 1863
		goto end;

1864
	copied = err;
1865
	if (len <= copied)
1866
		goto end;
1867 1868 1869

	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
	len = len - copied;
1870

1871
	zc_capable = !bpf_strp_enabled && !is_kvec && !is_peek &&
1872
		ctx->zc_capable;
1873
	decrypted = 0;
1874
	while (len && (decrypted + copied < target || ctx->recv_pkt)) {
1875
		struct tls_decrypt_arg darg = {};
1876
		int to_decrypt, chunk;
D
Dave Watson 已提交
1877

1878 1879
		err = tls_rx_rec_wait(sk, psock, flags & MSG_DONTWAIT, timeo);
		if (err <= 0) {
1880
			if (psock) {
1881 1882
				chunk = sk_msg_recvmsg(sk, psock, msg, len,
						       flags);
1883 1884 1885 1886 1887
				if (chunk > 0) {
					decrypted += chunk;
					len -= chunk;
					continue;
				}
1888
			}
D
Dave Watson 已提交
1889
			goto recv_end;
1890
		}
D
Dave Watson 已提交
1891

1892
		skb = ctx->recv_pkt;
D
Dave Watson 已提交
1893
		rxm = strp_msg(skb);
1894
		tlm = tls_msg(skb);
1895

1896
		to_decrypt = rxm->full_len - prot->overhead_size;
1897

1898 1899
		if (zc_capable && to_decrypt <= len &&
		    tlm->control == TLS_RECORD_TYPE_DATA)
1900
			darg.zc = true;
1901

1902
		/* Do not use async mode if record is non-data */
1903
		if (tlm->control == TLS_RECORD_TYPE_DATA && !bpf_strp_enabled)
1904
			darg.async = ctx->async_capable;
1905
		else
1906
			darg.async = false;
1907

1908
		err = tls_rx_one_record(sk, &msg->msg_iter, &darg);
1909
		if (err < 0) {
1910
			tls_err_abort(sk, -EBADMSG);
1911 1912 1913
			goto recv_end;
		}

1914
		async |= darg.async;
1915 1916 1917 1918 1919 1920 1921 1922

		/* If the type of records being processed is not known yet,
		 * set it to record type just dequeued. If it is already known,
		 * but does not match the record type just dequeued, go to end.
		 * We always get record type here since for tls1.2, record type
		 * is known just after record is dequeued from stream parser.
		 * For tls1.3, we disable async.
		 */
1923
		err = tls_record_content_type(msg, tlm, &control);
1924 1925 1926 1927
		if (err <= 0) {
			tls_rx_rec_done(ctx);
put_on_rx_list_err:
			__skb_queue_tail(&ctx->rx_list, skb);
1928
			goto recv_end;
1929
		}
1930

1931 1932 1933 1934
		/* periodically flush backlog, and feed strparser */
		tls_read_flush_backlog(sk, prot, len, to_decrypt,
				       decrypted + copied, &flushed_at);

1935 1936 1937
		/* TLS 1.3 may have updated the length by more than overhead */
		chunk = rxm->full_len;
		tls_rx_rec_done(ctx);
1938

1939 1940 1941
		if (async) {
			/* TLS 1.2-only, to_decrypt must be text length */
			chunk = min_t(int, to_decrypt, len);
1942
put_on_rx_list:
1943 1944
			decrypted += chunk;
			len -= chunk;
1945
			__skb_queue_tail(&ctx->rx_list, skb);
1946
			continue;
1947
		}
1948

1949
		if (!darg.zc) {
1950 1951
			bool partially_consumed = chunk > len;

1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
			if (bpf_strp_enabled) {
				err = sk_psock_tls_strp_read(psock, skb);
				if (err != __SK_PASS) {
					rxm->offset = rxm->offset + rxm->full_len;
					rxm->full_len = 0;
					if (err == __SK_DROP)
						consume_skb(skb);
					continue;
				}
			}

1963
			if (partially_consumed)
1964
				chunk = len;
1965

1966 1967
			err = skb_copy_datagram_msg(skb, rxm->offset,
						    msg, chunk);
1968 1969
			if (err < 0)
				goto put_on_rx_list_err;
1970

1971
			if (is_peek)
1972
				goto put_on_rx_list;
1973 1974 1975 1976

			if (partially_consumed) {
				rxm->offset += chunk;
				rxm->full_len -= chunk;
1977
				goto put_on_rx_list;
1978
			}
D
Dave Watson 已提交
1979 1980
		}

1981
		decrypted += chunk;
D
Dave Watson 已提交
1982
		len -= chunk;
1983

1984
		consume_skb(skb);
1985

1986 1987 1988 1989 1990 1991
		/* Return full control message to userspace before trying
		 * to parse another message type
		 */
		msg->msg_flags |= MSG_EOR;
		if (control != TLS_RECORD_TYPE_DATA)
			break;
1992
	}
D
Dave Watson 已提交
1993 1994

recv_end:
1995
	if (async) {
1996
		int ret, pending;
1997

1998
		/* Wait for all previously submitted records to be decrypted */
1999
		spin_lock_bh(&ctx->decrypt_compl_lock);
J
Jakub Kicinski 已提交
2000
		reinit_completion(&ctx->async_wait.completion);
2001 2002 2003
		pending = atomic_read(&ctx->decrypt_pending);
		spin_unlock_bh(&ctx->decrypt_compl_lock);
		if (pending) {
2004 2005 2006 2007
			ret = crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
			if (ret) {
				if (err >= 0 || err == -EINPROGRESS)
					err = ret;
2008 2009
				decrypted = 0;
				goto end;
2010 2011
			}
		}
2012

2013 2014
		/* Drain records from the rx_list & copy if required */
		if (is_peek || is_kvec)
2015
			err = process_rx_list(ctx, msg, &control, copied,
2016 2017
					      decrypted, false, is_peek);
		else
2018
			err = process_rx_list(ctx, msg, &control, 0,
2019
					      decrypted, true, is_peek);
2020
		decrypted = max(err, 0);
2021 2022
	}

2023 2024 2025
	copied += decrypted;

end:
2026
	tls_rx_reader_unlock(sk, ctx);
2027 2028
	if (psock)
		sk_psock_put(sk, psock);
D
Dave Watson 已提交
2029 2030 2031 2032 2033 2034 2035 2036
	return copied ? : err;
}

ssize_t tls_sw_splice_read(struct socket *sock,  loff_t *ppos,
			   struct pipe_inode_info *pipe,
			   size_t len, unsigned int flags)
{
	struct tls_context *tls_ctx = tls_get_ctx(sock->sk);
B
Boris Pismenny 已提交
2037
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
2038 2039
	struct strp_msg *rxm = NULL;
	struct sock *sk = sock->sk;
2040
	struct tls_msg *tlm;
D
Dave Watson 已提交
2041 2042 2043 2044 2045 2046
	struct sk_buff *skb;
	ssize_t copied = 0;
	int err = 0;
	long timeo;
	int chunk;

2047 2048 2049
	timeo = tls_rx_reader_lock(sk, ctx, flags & SPLICE_F_NONBLOCK);
	if (timeo < 0)
		return timeo;
D
Dave Watson 已提交
2050

2051
	if (!skb_queue_empty(&ctx->rx_list)) {
2052 2053
		skb = __skb_dequeue(&ctx->rx_list);
	} else {
2054 2055
		struct tls_decrypt_arg darg = {};

2056 2057 2058
		err = tls_rx_rec_wait(sk, NULL, flags & SPLICE_F_NONBLOCK,
				      timeo);
		if (err <= 0)
2059
			goto splice_read_end;
D
Dave Watson 已提交
2060

2061
		err = tls_rx_one_record(sk, NULL, &darg);
2062 2063 2064 2065
		if (err < 0) {
			tls_err_abort(sk, -EBADMSG);
			goto splice_read_end;
		}
2066

2067
		skb = ctx->recv_pkt;
2068
		tls_rx_rec_done(ctx);
2069
	}
2070

2071 2072 2073
	rxm = strp_msg(skb);
	tlm = tls_msg(skb);

2074
	/* splice does not support reading control messages */
2075
	if (tlm->control != TLS_RECORD_TYPE_DATA) {
2076
		err = -EINVAL;
2077
		goto splice_requeue;
D
Dave Watson 已提交
2078
	}
2079

D
Dave Watson 已提交
2080 2081 2082
	chunk = min_t(unsigned int, rxm->full_len, len);
	copied = skb_splice_bits(skb, sk, rxm->offset, pipe, chunk, flags);
	if (copied < 0)
2083
		goto splice_requeue;
D
Dave Watson 已提交
2084

2085 2086 2087
	if (chunk < rxm->full_len) {
		rxm->offset += len;
		rxm->full_len -= len;
2088
		goto splice_requeue;
2089
	}
D
Dave Watson 已提交
2090

2091 2092
	consume_skb(skb);

D
Dave Watson 已提交
2093
splice_read_end:
2094
	tls_rx_reader_unlock(sk, ctx);
D
Dave Watson 已提交
2095
	return copied ? : err;
2096 2097 2098 2099

splice_requeue:
	__skb_queue_head(&ctx->rx_list, skb);
	goto splice_read_end;
D
Dave Watson 已提交
2100 2101
}

2102
bool tls_sw_sock_is_readable(struct sock *sk)
D
Dave Watson 已提交
2103 2104
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
2105
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2106 2107
	bool ingress_empty = true;
	struct sk_psock *psock;
D
Dave Watson 已提交
2108

2109 2110 2111 2112 2113
	rcu_read_lock();
	psock = sk_psock(sk);
	if (psock)
		ingress_empty = list_empty(&psock->ingress_msg);
	rcu_read_unlock();
D
Dave Watson 已提交
2114

2115 2116
	return !ingress_empty || ctx->recv_pkt ||
		!skb_queue_empty(&ctx->rx_list);
D
Dave Watson 已提交
2117 2118 2119 2120 2121
}

static int tls_read_size(struct strparser *strp, struct sk_buff *skb)
{
	struct tls_context *tls_ctx = tls_get_ctx(strp->sk);
2122
	struct tls_prot_info *prot = &tls_ctx->prot_info;
K
Kees Cook 已提交
2123
	char header[TLS_HEADER_SIZE + MAX_IV_SIZE];
D
Dave Watson 已提交
2124
	struct strp_msg *rxm = strp_msg(skb);
2125
	struct tls_msg *tlm = tls_msg(skb);
D
Dave Watson 已提交
2126 2127 2128 2129 2130
	size_t cipher_overhead;
	size_t data_len = 0;
	int ret;

	/* Verify that we have a full TLS header, or wait for more data */
2131
	if (rxm->offset + prot->prepend_size > skb->len)
D
Dave Watson 已提交
2132 2133
		return 0;

K
Kees Cook 已提交
2134
	/* Sanity-check size of on-stack buffer. */
2135
	if (WARN_ON(prot->prepend_size > sizeof(header))) {
K
Kees Cook 已提交
2136 2137 2138 2139
		ret = -EINVAL;
		goto read_failure;
	}

D
Dave Watson 已提交
2140
	/* Linearize header to local buffer */
2141
	ret = skb_copy_bits(skb, rxm->offset, header, prot->prepend_size);
D
Dave Watson 已提交
2142 2143 2144
	if (ret < 0)
		goto read_failure;

2145
	tlm->control = header[0];
D
Dave Watson 已提交
2146 2147 2148

	data_len = ((header[4] & 0xFF) | (header[3] << 8));

2149
	cipher_overhead = prot->tag_size;
2150 2151
	if (prot->version != TLS_1_3_VERSION &&
	    prot->cipher_type != TLS_CIPHER_CHACHA20_POLY1305)
2152
		cipher_overhead += prot->iv_size;
D
Dave Watson 已提交
2153

D
Dave Watson 已提交
2154
	if (data_len > TLS_MAX_PAYLOAD_SIZE + cipher_overhead +
2155
	    prot->tail_size) {
D
Dave Watson 已提交
2156 2157 2158 2159 2160 2161 2162 2163
		ret = -EMSGSIZE;
		goto read_failure;
	}
	if (data_len < cipher_overhead) {
		ret = -EBADMSG;
		goto read_failure;
	}

D
Dave Watson 已提交
2164 2165 2166
	/* Note that both TLS1.3 and TLS1.2 use TLS_1_2 version here */
	if (header[1] != TLS_1_2_VERSION_MINOR ||
	    header[2] != TLS_1_2_VERSION_MAJOR) {
D
Dave Watson 已提交
2167 2168 2169
		ret = -EINVAL;
		goto read_failure;
	}
2170

2171
	tls_device_rx_resync_new_rec(strp->sk, data_len + TLS_HEADER_SIZE,
2172
				     TCP_SKB_CB(skb)->seq + rxm->offset);
D
Dave Watson 已提交
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
	return data_len + TLS_HEADER_SIZE;

read_failure:
	tls_err_abort(strp->sk, ret);

	return ret;
}

static void tls_queue(struct strparser *strp, struct sk_buff *skb)
{
	struct tls_context *tls_ctx = tls_get_ctx(strp->sk);
B
Boris Pismenny 已提交
2184
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
2185 2186 2187 2188

	ctx->recv_pkt = skb;
	strp_pause(strp);

2189
	ctx->saved_data_ready(strp->sk);
D
Dave Watson 已提交
2190 2191 2192 2193 2194
}

static void tls_data_ready(struct sock *sk)
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
2195
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2196
	struct sk_psock *psock;
D
Dave Watson 已提交
2197 2198

	strp_data_ready(&ctx->strp);
2199 2200

	psock = sk_psock_get(sk);
2201 2202 2203
	if (psock) {
		if (!list_empty(&psock->ingress_msg))
			ctx->saved_data_ready(sk);
2204 2205
		sk_psock_put(sk, psock);
	}
D
Dave Watson 已提交
2206 2207
}

2208 2209 2210 2211 2212 2213 2214 2215 2216
void tls_sw_cancel_work_tx(struct tls_context *tls_ctx)
{
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);

	set_bit(BIT_TX_CLOSING, &ctx->tx_bitmask);
	set_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask);
	cancel_delayed_work_sync(&ctx->tx_work.work);
}

2217
void tls_sw_release_resources_tx(struct sock *sk)
D
Dave Watson 已提交
2218 2219
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
2220
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2221
	struct tls_rec *rec, *tmp;
2222
	int pending;
2223 2224

	/* Wait for any pending async encryptions to complete */
2225 2226 2227 2228 2229 2230
	spin_lock_bh(&ctx->encrypt_compl_lock);
	ctx->async_notify = true;
	pending = atomic_read(&ctx->encrypt_pending);
	spin_unlock_bh(&ctx->encrypt_compl_lock);

	if (pending)
2231 2232 2233 2234
		crypto_wait_req(-EINPROGRESS, &ctx->async_wait);

	tls_tx_records(sk, -1);

2235
	/* Free up un-sent records in tx_list. First, free
2236 2237
	 * the partially sent record if any at head of tx_list.
	 */
2238 2239
	if (tls_ctx->partially_sent_record) {
		tls_free_partial_record(sk, tls_ctx);
2240
		rec = list_first_entry(&ctx->tx_list,
2241 2242
				       struct tls_rec, list);
		list_del(&rec->list);
2243
		sk_msg_free(sk, &rec->msg_plaintext);
2244 2245 2246
		kfree(rec);
	}

2247
	list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
2248
		list_del(&rec->list);
2249 2250
		sk_msg_free(sk, &rec->msg_encrypted);
		sk_msg_free(sk, &rec->msg_plaintext);
2251 2252
		kfree(rec);
	}
D
Dave Watson 已提交
2253

2254
	crypto_free_aead(ctx->aead_send);
2255
	tls_free_open_rec(sk);
2256 2257 2258 2259 2260
}

void tls_sw_free_ctx_tx(struct tls_context *tls_ctx)
{
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
B
Boris Pismenny 已提交
2261 2262 2263 2264

	kfree(ctx);
}

2265
void tls_sw_release_resources_rx(struct sock *sk)
B
Boris Pismenny 已提交
2266 2267 2268 2269
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);

2270 2271 2272
	kfree(tls_ctx->rx.rec_seq);
	kfree(tls_ctx->rx.iv);

D
Dave Watson 已提交
2273
	if (ctx->aead_recv) {
2274 2275
		kfree_skb(ctx->recv_pkt);
		ctx->recv_pkt = NULL;
2276
		__skb_queue_purge(&ctx->rx_list);
D
Dave Watson 已提交
2277 2278
		crypto_free_aead(ctx->aead_recv);
		strp_stop(&ctx->strp);
2279 2280 2281 2282 2283 2284 2285 2286 2287
		/* If tls_sw_strparser_arm() was not called (cleanup paths)
		 * we still want to strp_stop(), but sk->sk_data_ready was
		 * never swapped.
		 */
		if (ctx->saved_data_ready) {
			write_lock_bh(&sk->sk_callback_lock);
			sk->sk_data_ready = ctx->saved_data_ready;
			write_unlock_bh(&sk->sk_callback_lock);
		}
D
Dave Watson 已提交
2288
	}
2289 2290
}

2291
void tls_sw_strparser_done(struct tls_context *tls_ctx)
2292 2293 2294
{
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);

2295 2296 2297 2298 2299 2300
	strp_done(&ctx->strp);
}

void tls_sw_free_ctx_rx(struct tls_context *tls_ctx)
{
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
2301 2302 2303 2304

	kfree(ctx);
}

2305 2306 2307 2308 2309 2310 2311 2312
void tls_sw_free_resources_rx(struct sock *sk)
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);

	tls_sw_release_resources_rx(sk);
	tls_sw_free_ctx_rx(tls_ctx);
}

2313
/* The work handler to transmitt the encrypted records in tx_list */
2314 2315 2316 2317 2318 2319 2320
static void tx_work_handler(struct work_struct *work)
{
	struct delayed_work *delayed_work = to_delayed_work(work);
	struct tx_work *tx_work = container_of(delayed_work,
					       struct tx_work, work);
	struct sock *sk = tx_work->sk;
	struct tls_context *tls_ctx = tls_get_ctx(sk);
2321
	struct tls_sw_context_tx *ctx;
2322

2323
	if (unlikely(!tls_ctx))
2324 2325
		return;

2326 2327 2328 2329 2330 2331
	ctx = tls_sw_ctx_tx(tls_ctx);
	if (test_bit(BIT_TX_CLOSING, &ctx->tx_bitmask))
		return;

	if (!test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask))
		return;
J
Jakub Kicinski 已提交
2332
	mutex_lock(&tls_ctx->tx_lock);
2333 2334 2335
	lock_sock(sk);
	tls_tx_records(sk, -1);
	release_sock(sk);
J
Jakub Kicinski 已提交
2336
	mutex_unlock(&tls_ctx->tx_lock);
2337 2338
}

J
Jakub Kicinski 已提交
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349
static bool tls_is_tx_ready(struct tls_sw_context_tx *ctx)
{
	struct tls_rec *rec;

	rec = list_first_entry(&ctx->tx_list, struct tls_rec, list);
	if (!rec)
		return false;

	return READ_ONCE(rec->tx_ready);
}

B
Boris Pismenny 已提交
2350 2351 2352 2353 2354
void tls_sw_write_space(struct sock *sk, struct tls_context *ctx)
{
	struct tls_sw_context_tx *tx_ctx = tls_sw_ctx_tx(ctx);

	/* Schedule the transmission if tx list is ready */
J
Jakub Kicinski 已提交
2355
	if (tls_is_tx_ready(tx_ctx) &&
2356 2357
	    !test_and_set_bit(BIT_TX_SCHEDULED, &tx_ctx->tx_bitmask))
		schedule_delayed_work(&tx_ctx->tx_work.work, 0);
B
Boris Pismenny 已提交
2358 2359
}

2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371
void tls_sw_strparser_arm(struct sock *sk, struct tls_context *tls_ctx)
{
	struct tls_sw_context_rx *rx_ctx = tls_sw_ctx_rx(tls_ctx);

	write_lock_bh(&sk->sk_callback_lock);
	rx_ctx->saved_data_ready = sk->sk_data_ready;
	sk->sk_data_ready = tls_data_ready;
	write_unlock_bh(&sk->sk_callback_lock);

	strp_check_rcv(&rx_ctx->strp);
}

2372 2373 2374 2375 2376 2377 2378 2379
void tls_update_rx_zc_capable(struct tls_context *tls_ctx)
{
	struct tls_sw_context_rx *rx_ctx = tls_sw_ctx_rx(tls_ctx);

	rx_ctx->zc_capable = tls_ctx->rx_no_pad ||
		tls_ctx->prot_info.version != TLS_1_3_VERSION;
}

D
Dave Watson 已提交
2380
int tls_set_sw_offload(struct sock *sk, struct tls_context *ctx, int tx)
D
Dave Watson 已提交
2381
{
2382 2383
	struct tls_context *tls_ctx = tls_get_ctx(sk);
	struct tls_prot_info *prot = &tls_ctx->prot_info;
D
Dave Watson 已提交
2384
	struct tls_crypto_info *crypto_info;
B
Boris Pismenny 已提交
2385 2386
	struct tls_sw_context_tx *sw_ctx_tx = NULL;
	struct tls_sw_context_rx *sw_ctx_rx = NULL;
D
Dave Watson 已提交
2387 2388 2389
	struct cipher_context *cctx;
	struct crypto_aead **aead;
	struct strp_callbacks cb;
2390
	u16 nonce_size, tag_size, iv_size, rec_seq_size, salt_size;
2391
	struct crypto_tfm *tfm;
2392
	char *iv, *rec_seq, *key, *salt, *cipher_name;
D
Dave Watson 已提交
2393
	size_t keysize;
D
Dave Watson 已提交
2394 2395 2396 2397 2398 2399 2400
	int rc = 0;

	if (!ctx) {
		rc = -EINVAL;
		goto out;
	}

B
Boris Pismenny 已提交
2401
	if (tx) {
2402 2403 2404 2405 2406 2407 2408 2409 2410 2411
		if (!ctx->priv_ctx_tx) {
			sw_ctx_tx = kzalloc(sizeof(*sw_ctx_tx), GFP_KERNEL);
			if (!sw_ctx_tx) {
				rc = -ENOMEM;
				goto out;
			}
			ctx->priv_ctx_tx = sw_ctx_tx;
		} else {
			sw_ctx_tx =
				(struct tls_sw_context_tx *)ctx->priv_ctx_tx;
D
Dave Watson 已提交
2412 2413
		}
	} else {
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
		if (!ctx->priv_ctx_rx) {
			sw_ctx_rx = kzalloc(sizeof(*sw_ctx_rx), GFP_KERNEL);
			if (!sw_ctx_rx) {
				rc = -ENOMEM;
				goto out;
			}
			ctx->priv_ctx_rx = sw_ctx_rx;
		} else {
			sw_ctx_rx =
				(struct tls_sw_context_rx *)ctx->priv_ctx_rx;
B
Boris Pismenny 已提交
2424
		}
D
Dave Watson 已提交
2425 2426
	}

D
Dave Watson 已提交
2427
	if (tx) {
2428
		crypto_init_wait(&sw_ctx_tx->async_wait);
2429
		spin_lock_init(&sw_ctx_tx->encrypt_compl_lock);
2430
		crypto_info = &ctx->crypto_send.info;
D
Dave Watson 已提交
2431
		cctx = &ctx->tx;
B
Boris Pismenny 已提交
2432
		aead = &sw_ctx_tx->aead_send;
2433
		INIT_LIST_HEAD(&sw_ctx_tx->tx_list);
2434 2435
		INIT_DELAYED_WORK(&sw_ctx_tx->tx_work.work, tx_work_handler);
		sw_ctx_tx->tx_work.sk = sk;
D
Dave Watson 已提交
2436
	} else {
2437
		crypto_init_wait(&sw_ctx_rx->async_wait);
2438
		spin_lock_init(&sw_ctx_rx->decrypt_compl_lock);
2439
		init_waitqueue_head(&sw_ctx_rx->wq);
2440
		crypto_info = &ctx->crypto_recv.info;
D
Dave Watson 已提交
2441
		cctx = &ctx->rx;
2442
		skb_queue_head_init(&sw_ctx_rx->rx_list);
B
Boris Pismenny 已提交
2443
		aead = &sw_ctx_rx->aead_recv;
D
Dave Watson 已提交
2444 2445
	}

D
Dave Watson 已提交
2446 2447
	switch (crypto_info->cipher_type) {
	case TLS_CIPHER_AES_GCM_128: {
2448 2449 2450
		struct tls12_crypto_info_aes_gcm_128 *gcm_128_info;

		gcm_128_info = (void *)crypto_info;
D
Dave Watson 已提交
2451 2452 2453
		nonce_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
		tag_size = TLS_CIPHER_AES_GCM_128_TAG_SIZE;
		iv_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
2454
		iv = gcm_128_info->iv;
D
Dave Watson 已提交
2455
		rec_seq_size = TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE;
2456
		rec_seq = gcm_128_info->rec_seq;
D
Dave Watson 已提交
2457 2458 2459
		keysize = TLS_CIPHER_AES_GCM_128_KEY_SIZE;
		key = gcm_128_info->key;
		salt = gcm_128_info->salt;
2460 2461
		salt_size = TLS_CIPHER_AES_GCM_128_SALT_SIZE;
		cipher_name = "gcm(aes)";
D
Dave Watson 已提交
2462 2463 2464
		break;
	}
	case TLS_CIPHER_AES_GCM_256: {
2465 2466 2467
		struct tls12_crypto_info_aes_gcm_256 *gcm_256_info;

		gcm_256_info = (void *)crypto_info;
D
Dave Watson 已提交
2468 2469 2470
		nonce_size = TLS_CIPHER_AES_GCM_256_IV_SIZE;
		tag_size = TLS_CIPHER_AES_GCM_256_TAG_SIZE;
		iv_size = TLS_CIPHER_AES_GCM_256_IV_SIZE;
2471
		iv = gcm_256_info->iv;
D
Dave Watson 已提交
2472
		rec_seq_size = TLS_CIPHER_AES_GCM_256_REC_SEQ_SIZE;
2473
		rec_seq = gcm_256_info->rec_seq;
D
Dave Watson 已提交
2474 2475 2476
		keysize = TLS_CIPHER_AES_GCM_256_KEY_SIZE;
		key = gcm_256_info->key;
		salt = gcm_256_info->salt;
2477 2478 2479 2480 2481
		salt_size = TLS_CIPHER_AES_GCM_256_SALT_SIZE;
		cipher_name = "gcm(aes)";
		break;
	}
	case TLS_CIPHER_AES_CCM_128: {
2482 2483 2484
		struct tls12_crypto_info_aes_ccm_128 *ccm_128_info;

		ccm_128_info = (void *)crypto_info;
2485 2486 2487
		nonce_size = TLS_CIPHER_AES_CCM_128_IV_SIZE;
		tag_size = TLS_CIPHER_AES_CCM_128_TAG_SIZE;
		iv_size = TLS_CIPHER_AES_CCM_128_IV_SIZE;
2488
		iv = ccm_128_info->iv;
2489
		rec_seq_size = TLS_CIPHER_AES_CCM_128_REC_SEQ_SIZE;
2490
		rec_seq = ccm_128_info->rec_seq;
2491 2492 2493 2494 2495
		keysize = TLS_CIPHER_AES_CCM_128_KEY_SIZE;
		key = ccm_128_info->key;
		salt = ccm_128_info->salt;
		salt_size = TLS_CIPHER_AES_CCM_128_SALT_SIZE;
		cipher_name = "ccm(aes)";
D
Dave Watson 已提交
2496 2497
		break;
	}
2498
	case TLS_CIPHER_CHACHA20_POLY1305: {
2499 2500
		struct tls12_crypto_info_chacha20_poly1305 *chacha20_poly1305_info;

2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514
		chacha20_poly1305_info = (void *)crypto_info;
		nonce_size = 0;
		tag_size = TLS_CIPHER_CHACHA20_POLY1305_TAG_SIZE;
		iv_size = TLS_CIPHER_CHACHA20_POLY1305_IV_SIZE;
		iv = chacha20_poly1305_info->iv;
		rec_seq_size = TLS_CIPHER_CHACHA20_POLY1305_REC_SEQ_SIZE;
		rec_seq = chacha20_poly1305_info->rec_seq;
		keysize = TLS_CIPHER_CHACHA20_POLY1305_KEY_SIZE;
		key = chacha20_poly1305_info->key;
		salt = chacha20_poly1305_info->salt;
		salt_size = TLS_CIPHER_CHACHA20_POLY1305_SALT_SIZE;
		cipher_name = "rfc7539(chacha20,poly1305)";
		break;
	}
2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548
	case TLS_CIPHER_SM4_GCM: {
		struct tls12_crypto_info_sm4_gcm *sm4_gcm_info;

		sm4_gcm_info = (void *)crypto_info;
		nonce_size = TLS_CIPHER_SM4_GCM_IV_SIZE;
		tag_size = TLS_CIPHER_SM4_GCM_TAG_SIZE;
		iv_size = TLS_CIPHER_SM4_GCM_IV_SIZE;
		iv = sm4_gcm_info->iv;
		rec_seq_size = TLS_CIPHER_SM4_GCM_REC_SEQ_SIZE;
		rec_seq = sm4_gcm_info->rec_seq;
		keysize = TLS_CIPHER_SM4_GCM_KEY_SIZE;
		key = sm4_gcm_info->key;
		salt = sm4_gcm_info->salt;
		salt_size = TLS_CIPHER_SM4_GCM_SALT_SIZE;
		cipher_name = "gcm(sm4)";
		break;
	}
	case TLS_CIPHER_SM4_CCM: {
		struct tls12_crypto_info_sm4_ccm *sm4_ccm_info;

		sm4_ccm_info = (void *)crypto_info;
		nonce_size = TLS_CIPHER_SM4_CCM_IV_SIZE;
		tag_size = TLS_CIPHER_SM4_CCM_TAG_SIZE;
		iv_size = TLS_CIPHER_SM4_CCM_IV_SIZE;
		iv = sm4_ccm_info->iv;
		rec_seq_size = TLS_CIPHER_SM4_CCM_REC_SEQ_SIZE;
		rec_seq = sm4_ccm_info->rec_seq;
		keysize = TLS_CIPHER_SM4_CCM_KEY_SIZE;
		key = sm4_ccm_info->key;
		salt = sm4_ccm_info->salt;
		salt_size = TLS_CIPHER_SM4_CCM_SALT_SIZE;
		cipher_name = "ccm(sm4)";
		break;
	}
D
Dave Watson 已提交
2549 2550
	default:
		rc = -EINVAL;
S
Sabrina Dubroca 已提交
2551
		goto free_priv;
D
Dave Watson 已提交
2552 2553
	}

D
Dave Watson 已提交
2554 2555
	if (crypto_info->version == TLS_1_3_VERSION) {
		nonce_size = 0;
2556 2557
		prot->aad_size = TLS_HEADER_SIZE;
		prot->tail_size = 1;
D
Dave Watson 已提交
2558
	} else {
2559 2560
		prot->aad_size = TLS_AAD_SPACE_SIZE;
		prot->tail_size = 0;
D
Dave Watson 已提交
2561 2562
	}

2563 2564 2565 2566 2567 2568 2569 2570
	/* Sanity-check the sizes for stack allocations. */
	if (iv_size > MAX_IV_SIZE || nonce_size > MAX_IV_SIZE ||
	    rec_seq_size > TLS_MAX_REC_SEQ_SIZE || tag_size != TLS_TAG_SIZE ||
	    prot->aad_size > TLS_MAX_AAD_SIZE) {
		rc = -EINVAL;
		goto free_priv;
	}

2571 2572 2573 2574 2575 2576 2577
	prot->version = crypto_info->version;
	prot->cipher_type = crypto_info->cipher_type;
	prot->prepend_size = TLS_HEADER_SIZE + nonce_size;
	prot->tag_size = tag_size;
	prot->overhead_size = prot->prepend_size +
			      prot->tag_size + prot->tail_size;
	prot->iv_size = iv_size;
2578 2579
	prot->salt_size = salt_size;
	cctx->iv = kmalloc(iv_size + salt_size, GFP_KERNEL);
D
Dave Watson 已提交
2580
	if (!cctx->iv) {
D
Dave Watson 已提交
2581
		rc = -ENOMEM;
S
Sabrina Dubroca 已提交
2582
		goto free_priv;
D
Dave Watson 已提交
2583
	}
D
Dave Watson 已提交
2584
	/* Note: 128 & 256 bit salt are the same size */
2585
	prot->rec_seq_size = rec_seq_size;
2586 2587
	memcpy(cctx->iv, salt, salt_size);
	memcpy(cctx->iv + salt_size, iv, iv_size);
2588
	cctx->rec_seq = kmemdup(rec_seq, rec_seq_size, GFP_KERNEL);
D
Dave Watson 已提交
2589
	if (!cctx->rec_seq) {
D
Dave Watson 已提交
2590 2591 2592
		rc = -ENOMEM;
		goto free_iv;
	}
D
Dave Watson 已提交
2593 2594

	if (!*aead) {
2595
		*aead = crypto_alloc_aead(cipher_name, 0, 0);
D
Dave Watson 已提交
2596 2597 2598
		if (IS_ERR(*aead)) {
			rc = PTR_ERR(*aead);
			*aead = NULL;
D
Dave Watson 已提交
2599 2600 2601 2602 2603 2604
			goto free_rec_seq;
		}
	}

	ctx->push_pending_record = tls_sw_push_pending_record;

D
Dave Watson 已提交
2605 2606
	rc = crypto_aead_setkey(*aead, key, keysize);

D
Dave Watson 已提交
2607 2608 2609
	if (rc)
		goto free_aead;

2610
	rc = crypto_aead_setauthsize(*aead, prot->tag_size);
D
Dave Watson 已提交
2611 2612 2613
	if (rc)
		goto free_aead;

B
Boris Pismenny 已提交
2614
	if (sw_ctx_rx) {
2615
		tfm = crypto_aead_tfm(sw_ctx_rx->aead_recv);
2616

2617 2618 2619 2620
		tls_update_rx_zc_capable(ctx);
		sw_ctx_rx->async_capable =
			crypto_info->version != TLS_1_3_VERSION &&
			!!(tfm->__crt_alg->cra_flags & CRYPTO_ALG_ASYNC);
2621

D
Dave Watson 已提交
2622 2623 2624 2625 2626
		/* Set up strparser */
		memset(&cb, 0, sizeof(cb));
		cb.rcv_msg = tls_queue;
		cb.parse_msg = tls_read_size;

B
Boris Pismenny 已提交
2627
		strp_init(&sw_ctx_rx->strp, sk, &cb);
D
Dave Watson 已提交
2628 2629 2630
	}

	goto out;
D
Dave Watson 已提交
2631 2632

free_aead:
D
Dave Watson 已提交
2633 2634
	crypto_free_aead(*aead);
	*aead = NULL;
D
Dave Watson 已提交
2635
free_rec_seq:
D
Dave Watson 已提交
2636 2637
	kfree(cctx->rec_seq);
	cctx->rec_seq = NULL;
D
Dave Watson 已提交
2638
free_iv:
B
Boris Pismenny 已提交
2639 2640
	kfree(cctx->iv);
	cctx->iv = NULL;
S
Sabrina Dubroca 已提交
2641
free_priv:
B
Boris Pismenny 已提交
2642 2643 2644 2645 2646 2647 2648
	if (tx) {
		kfree(ctx->priv_ctx_tx);
		ctx->priv_ctx_tx = NULL;
	} else {
		kfree(ctx->priv_ctx_rx);
		ctx->priv_ctx_rx = NULL;
	}
D
Dave Watson 已提交
2649 2650 2651
out:
	return rc;
}