tls_sw.c 64.0 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>

47 48 49 50 51
struct tls_decrypt_arg {
	bool zc;
	bool async;
};

52 53 54 55 56 57 58 59
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);
}

60 61 62 63 64 65 66 67 68 69 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
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);
}

136
static int padding_length(struct tls_prot_info *prot, struct sk_buff *skb)
D
Dave Watson 已提交
137 138
{
	struct strp_msg *rxm = strp_msg(skb);
139
	struct tls_msg *tlm = tls_msg(skb);
D
Dave Watson 已提交
140 141 142
	int sub = 0;

	/* Determine zero-padding length */
143
	if (prot->version == TLS_1_3_VERSION) {
144
		int offset = rxm->full_len - TLS_TAG_SIZE - 1;
D
Dave Watson 已提交
145 146 147 148
		char content_type = 0;
		int err;

		while (content_type == 0) {
149
			if (offset < prot->prepend_size)
D
Dave Watson 已提交
150
				return -EBADMSG;
151
			err = skb_copy_bits(skb, rxm->offset + offset,
D
Dave Watson 已提交
152
					    &content_type, 1);
153 154
			if (err)
				return err;
D
Dave Watson 已提交
155 156 157
			if (content_type)
				break;
			sub++;
158
			offset--;
D
Dave Watson 已提交
159
		}
160
		tlm->control = content_type;
D
Dave Watson 已提交
161 162 163 164
	}
	return sub;
}

165 166 167 168
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;
169
	struct scatterlist *sgin = aead_req->src;
170 171
	struct tls_sw_context_rx *ctx;
	struct tls_context *tls_ctx;
172
	struct tls_prot_info *prot;
173
	struct scatterlist *sg;
174
	struct sk_buff *skb;
175
	unsigned int pages;
176 177 178 179

	skb = (struct sk_buff *)req->data;
	tls_ctx = tls_get_ctx(skb->sk);
	ctx = tls_sw_ctx_rx(tls_ctx);
180
	prot = &tls_ctx->prot_info;
181 182 183

	/* Propagate if there was an err */
	if (err) {
J
Jakub Kicinski 已提交
184 185 186
		if (err == -EBADMSG)
			TLS_INC_STATS(sock_net(skb->sk),
				      LINUX_MIB_TLSDECRYPTERROR);
187
		ctx->async_wait.err = err;
188
		tls_err_abort(skb->sk, err);
189 190
	} else {
		struct strp_msg *rxm = strp_msg(skb);
191 192
		int pad;

193
		pad = padding_length(prot, skb);
194 195 196 197 198 199 200 201
		if (pad < 0) {
			ctx->async_wait.err = pad;
			tls_err_abort(skb->sk, pad);
		} else {
			rxm->full_len -= pad;
			rxm->offset += prot->prepend_size;
			rxm->full_len -= prot->overhead_size;
		}
202 203
	}

204 205 206 207 208
	/* After using skb->sk to propagate sk through crypto async callback
	 * we need to NULL it again.
	 */
	skb->sk = NULL;

209

210 211 212 213 214 215 216 217
	/* 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));
		}
218 219 220 221
	}

	kfree(aead_req);

222
	spin_lock_bh(&ctx->decrypt_compl_lock);
J
Jakub Kicinski 已提交
223
	if (!atomic_dec_return(&ctx->decrypt_pending))
224
		complete(&ctx->async_wait.completion);
225
	spin_unlock_bh(&ctx->decrypt_compl_lock);
226 227
}

D
Dave Watson 已提交
228
static int tls_do_decryption(struct sock *sk,
229
			     struct sk_buff *skb,
D
Dave Watson 已提交
230 231 232 233
			     struct scatterlist *sgin,
			     struct scatterlist *sgout,
			     char *iv_recv,
			     size_t data_len,
234 235
			     struct aead_request *aead_req,
			     bool async)
D
Dave Watson 已提交
236 237
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
238
	struct tls_prot_info *prot = &tls_ctx->prot_info;
B
Boris Pismenny 已提交
239
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
240 241
	int ret;

242
	aead_request_set_tfm(aead_req, ctx->aead_recv);
243
	aead_request_set_ad(aead_req, prot->aad_size);
D
Dave Watson 已提交
244
	aead_request_set_crypt(aead_req, sgin, sgout,
245
			       data_len + prot->tag_size,
D
Dave Watson 已提交
246 247
			       (u8 *)iv_recv);

248
	if (async) {
249 250 251
		/* 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
252
		 * before consume_skb is called. We _know_ skb->sk is NULL
253 254 255
		 * because it is a clone from strparser.
		 */
		skb->sk = sk;
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
		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) {
		if (async)
			return ret;

		ret = crypto_wait_req(ret, &ctx->async_wait);
	}

	if (async)
		atomic_dec(&ctx->decrypt_pending);

D
Dave Watson 已提交
277 278 279
	return ret;
}

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

287
	sk_msg_trim(sk, &rec->msg_plaintext, target_size);
D
Dave Watson 已提交
288
	if (target_size > 0)
289
		target_size += prot->overhead_size;
290
	sk_msg_trim(sk, &rec->msg_encrypted, target_size);
D
Dave Watson 已提交
291 292
}

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

300
	return sk_msg_alloc(sk, msg_en, len, 0);
D
Dave Watson 已提交
301 302
}

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

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

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

324
	return sk_msg_clone(sk, msg_pl, msg_en, skip, len);
D
Dave Watson 已提交
325 326
}

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

336 337 338
	mem_size = sizeof(struct tls_rec) + crypto_aead_reqsize(ctx->aead_send);

	rec = kzalloc(mem_size, sk->sk_allocation);
339
	if (!rec)
340 341 342 343 344 345 346 347 348
		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);
349
	sg_set_buf(&rec->sg_aead_in[0], rec->aad_space, prot->aad_size);
350 351 352
	sg_unmark_end(&rec->sg_aead_in[1]);

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

	return rec;
}
358

359 360
static void tls_free_rec(struct sock *sk, struct tls_rec *rec)
{
361 362
	sk_msg_free(sk, &rec->msg_encrypted);
	sk_msg_free(sk, &rec->msg_plaintext);
363
	kfree(rec);
364 365
}

366 367 368 369 370 371 372 373 374 375 376 377
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;
	}
}

378 379 380 381 382
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;
383
	struct sk_msg *msg_en;
384 385 386
	int tx_flags, rc = 0;

	if (tls_is_partially_sent_record(tls_ctx)) {
387
		rec = list_first_entry(&ctx->tx_list,
388 389 390 391 392 393 394 395 396 397 398 399
				       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.
400
		 * Remove the head of tx_list
401 402
		 */
		list_del(&rec->list);
403
		sk_msg_free(sk, &rec->msg_plaintext);
404 405 406
		kfree(rec);
	}

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

415
			msg_en = &rec->msg_encrypted;
416
			rc = tls_push_sg(sk, tls_ctx,
417
					 &msg_en->sg.data[msg_en->sg.curr],
418 419 420 421 422
					 0, tx_flags);
			if (rc)
				goto tx_err;

			list_del(&rec->list);
423
			sk_msg_free(sk, &rec->msg_plaintext);
424 425 426 427 428 429 430 431
			kfree(rec);
		} else {
			break;
		}
	}

tx_err:
	if (rc < 0 && rc != -EAGAIN)
432
		tls_err_abort(sk, -EBADMSG);
433 434 435 436 437 438 439 440 441

	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);
442
	struct tls_prot_info *prot = &tls_ctx->prot_info;
443
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
444 445
	struct scatterlist *sge;
	struct sk_msg *msg_en;
446 447 448 449 450
	struct tls_rec *rec;
	bool ready = false;
	int pending;

	rec = container_of(aead_req, struct tls_rec, aead_req);
451
	msg_en = &rec->msg_encrypted;
452

453
	sge = sk_msg_elem(msg_en, msg_en->sg.curr);
454 455
	sge->offset -= prot->prepend_size;
	sge->length += prot->prepend_size;
456

457
	/* Check if error is previously set on socket */
458 459 460 461 462
	if (err || sk->sk_err) {
		rec = NULL;

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

470 471 472 473 474 475 476 477 478 479 480 481
	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;
	}
482

483
	spin_lock_bh(&ctx->encrypt_compl_lock);
484 485
	pending = atomic_dec_return(&ctx->encrypt_pending);

486
	if (!pending && ctx->async_notify)
487
		complete(&ctx->async_wait.completion);
488
	spin_unlock_bh(&ctx->encrypt_compl_lock);
489 490 491 492 493 494

	if (!ready)
		return;

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

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

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

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

525
	xor_iv_with_seq(prot, rec->iv_data + iv_offset, tls_ctx->tx.rec_seq);
526

527 528
	sge->offset += prot->prepend_size;
	sge->length -= prot->prepend_size;
D
Dave Watson 已提交
529

530
	msg_en->sg.curr = start;
531

D
Dave Watson 已提交
532
	aead_request_set_tfm(aead_req, ctx->aead_send);
533
	aead_request_set_ad(aead_req, prot->aad_size);
534 535
	aead_request_set_crypt(aead_req, rec->sg_aead_in,
			       rec->sg_aead_out,
536
			       data_len, rec->iv_data);
537 538

	aead_request_set_callback(aead_req, CRYPTO_TFM_REQ_MAY_BACKLOG,
539 540
				  tls_encrypt_done, sk);

541 542
	/* Add the record in tx_list */
	list_add_tail((struct list_head *)&rec->list, &ctx->tx_list);
543
	atomic_inc(&ctx->encrypt_pending);
544

545 546 547
	rc = crypto_aead_encrypt(aead_req);
	if (!rc || rc != -EINPROGRESS) {
		atomic_dec(&ctx->encrypt_pending);
548 549
		sge->offset -= prot->prepend_size;
		sge->length += prot->prepend_size;
550
	}
D
Dave Watson 已提交
551

552 553 554 555
	if (!rc) {
		WRITE_ONCE(rec->tx_ready, true);
	} else if (rc != -EINPROGRESS) {
		list_del(&rec->list);
556
		return rc;
557
	}
D
Dave Watson 已提交
558

559 560
	/* Unhook the record from context if encryption is not failure */
	ctx->open_rec = NULL;
561
	tls_advance_record_sn(sk, prot, &tls_ctx->tx);
D
Dave Watson 已提交
562 563 564
	return rc;
}

565 566 567 568 569 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
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 已提交
683 684 685 686
static int tls_push_record(struct sock *sk, int flags,
			   unsigned char record_type)
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
687
	struct tls_prot_info *prot = &tls_ctx->prot_info;
B
Boris Pismenny 已提交
688
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
689
	struct tls_rec *rec = ctx->open_rec, *tmp = NULL;
690
	u32 i, split_point, orig_end;
691
	struct sk_msg *msg_pl, *msg_en;
692
	struct aead_request *req;
693
	bool split;
D
Dave Watson 已提交
694 695
	int rc;

696 697
	if (!rec)
		return 0;
698

699 700 701
	msg_pl = &rec->msg_plaintext;
	msg_en = &rec->msg_encrypted;

702 703
	split_point = msg_pl->apply_bytes;
	split = split_point && split_point < msg_pl->sg.size;
704 705 706 707 708 709 710 711 712
	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;
	}
713 714
	if (split) {
		rc = tls_split_open_record(sk, rec, &tmp, msg_pl, msg_en,
715
					   split_point, prot->overhead_size,
716 717 718
					   &orig_end);
		if (rc < 0)
			return rc;
719 720 721 722 723 724 725 726 727 728 729
		/* 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;
		}
730
		sk_msg_trim(sk, msg_en, msg_pl->sg.size +
731
			    prot->overhead_size);
732 733
	}

734 735
	rec->tx_flags = flags;
	req = &rec->aead_req;
D
Dave Watson 已提交
736

737 738
	i = msg_pl->sg.end;
	sk_msg_iter_var_prev(i);
D
Dave Watson 已提交
739 740

	rec->content_type = record_type;
741
	if (prot->version == TLS_1_3_VERSION) {
D
Dave Watson 已提交
742 743 744 745 746 747 748 749
		/* 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));
	}
750

751 752 753 754 755 756
	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);
	}

757
	i = msg_pl->sg.start;
758
	sg_chain(rec->sg_aead_in, 2, &msg_pl->sg.data[i]);
759 760 761 762 763 764 765 766

	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]);

767
	tls_make_aad(rec->aad_space, msg_pl->sg.size + prot->tail_size,
768
		     tls_ctx->tx.rec_seq, record_type, prot);
D
Dave Watson 已提交
769 770

	tls_fill_prepend(tls_ctx,
771
			 page_address(sg_page(&msg_en->sg.data[i])) +
D
Dave Watson 已提交
772
			 msg_en->sg.data[i].offset,
773
			 msg_pl->sg.size + prot->tail_size,
774
			 record_type);
D
Dave Watson 已提交
775

776
	tls_ctx->pending_open_record_frags = false;
D
Dave Watson 已提交
777

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

798
	return tls_tx_records(sk, flags);
D
Dave Watson 已提交
799 800
}

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

815
	policy = !(flags & MSG_SENDPAGE_NOPOLICY);
816
	psock = sk_psock_get(sk);
817 818
	if (!psock || !policy) {
		err = tls_push_record(sk, flags, record_type);
819
		if (err && sk->sk_err == EBADMSG) {
820 821
			*copied -= sk_msg_free(sk, msg);
			tls_free_open_rec(sk);
822
			err = -sk->sk_err;
823
		}
824 825
		if (psock)
			sk_psock_put(sk, psock);
826 827
		return err;
	}
828 829
more_data:
	enospc = sk_msg_full(msg);
830 831
	if (psock->eval == __SK_NONE) {
		delta = msg->sg.size;
832
		psock->eval = sk_psock_msg_verdict(sk, psock, msg);
833
		delta -= msg->sg.size;
834
	}
835 836 837 838 839 840 841 842 843 844 845 846 847
	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);
848
		if (err && sk->sk_err == EBADMSG) {
849 850
			*copied -= sk_msg_free(sk, msg);
			tls_free_open_rec(sk);
851
			err = -sk->sk_err;
852 853 854 855 856 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
			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);
883
		*copied -= (send + delta);
884 885
		err = -EACCES;
	}
886

887 888
	if (likely(!err)) {
		bool reset_eval = !ctx->open_rec;
889

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
		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;
918 919

	if (!rec)
920
		return 0;
921

922
	msg_pl = &rec->msg_plaintext;
923 924 925
	copied = msg_pl->sg.size;
	if (!copied)
		return 0;
926

927 928
	return bpf_exec_tx_verdict(msg_pl, sk, true, TLS_RECORD_TYPE_DATA,
				   &copied, flags);
929 930 931 932
}

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

954 955
	if (msg->msg_flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
			       MSG_CMSG_COMPAT))
956
		return -EOPNOTSUPP;
D
Dave Watson 已提交
957

J
Jakub Kicinski 已提交
958
	mutex_lock(&tls_ctx->tx_lock);
D
Dave Watson 已提交
959 960 961 962
	lock_sock(sk);

	if (unlikely(msg->msg_controllen)) {
		ret = tls_proccess_cmsg(sk, msg, &record_type);
963 964 965 966 967 968
		if (ret) {
			if (ret == -EINPROGRESS)
				num_async++;
			else if (ret != -EAGAIN)
				goto send_end;
		}
D
Dave Watson 已提交
969 970 971 972
	}

	while (msg_data_left(msg)) {
		if (sk->sk_err) {
973
			ret = -sk->sk_err;
D
Dave Watson 已提交
974 975 976
			goto send_end;
		}

977 978 979 980
		if (ctx->open_rec)
			rec = ctx->open_rec;
		else
			rec = ctx->open_rec = tls_get_rec(sk);
981 982 983 984 985
		if (!rec) {
			ret = -ENOMEM;
			goto send_end;
		}

986 987 988 989
		msg_pl = &rec->msg_plaintext;
		msg_en = &rec->msg_encrypted;

		orig_size = msg_pl->sg.size;
D
Dave Watson 已提交
990 991
		full_record = false;
		try_to_copy = msg_data_left(msg);
992
		record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
D
Dave Watson 已提交
993 994 995 996 997
		if (try_to_copy >= record_room) {
			try_to_copy = record_room;
			full_record = true;
		}

998
		required_size = msg_pl->sg.size + try_to_copy +
999
				prot->overhead_size;
D
Dave Watson 已提交
1000 1001 1002

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

D
Dave Watson 已提交
1004
alloc_encrypted:
1005
		ret = tls_alloc_encrypted_msg(sk, required_size);
D
Dave Watson 已提交
1006 1007 1008 1009 1010 1011 1012 1013
		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
			 */
1014
			try_to_copy -= required_size - msg_en->sg.size;
D
Dave Watson 已提交
1015 1016
			full_record = true;
		}
1017 1018

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

1021 1022
			ret = sk_msg_zerocopy_from_iter(sk, &msg->msg_iter,
							msg_pl, try_to_copy);
D
Dave Watson 已提交
1023 1024 1025
			if (ret)
				goto fallback_to_reg_send;

1026
			num_zc++;
D
Dave Watson 已提交
1027
			copied += try_to_copy;
1028 1029 1030 1031 1032

			sk_msg_sg_copy_set(msg_pl, first);
			ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
						  record_type, &copied,
						  msg->msg_flags);
1033 1034 1035
			if (ret) {
				if (ret == -EINPROGRESS)
					num_async++;
1036 1037
				else if (ret == -ENOMEM)
					goto wait_for_memory;
1038
				else if (ctx->open_rec && ret == -ENOSPC)
1039
					goto rollback_iter;
1040 1041 1042
				else if (ret != -EAGAIN)
					goto send_end;
			}
1043
			continue;
1044 1045 1046 1047 1048
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 已提交
1049
fallback_to_reg_send:
1050
			sk_msg_trim(sk, msg_pl, orig_size);
D
Dave Watson 已提交
1051 1052
		}

1053
		required_size = msg_pl->sg.size + try_to_copy;
1054

1055
		ret = tls_clone_plaintext_msg(sk, required_size);
D
Dave Watson 已提交
1056 1057
		if (ret) {
			if (ret != -ENOSPC)
1058
				goto send_end;
D
Dave Watson 已提交
1059 1060 1061 1062 1063

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

1070 1071 1072 1073 1074 1075
		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 已提交
1076

1077 1078 1079 1080
		/* 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 已提交
1081 1082
		copied += try_to_copy;
		if (full_record || eor) {
1083 1084 1085
			ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
						  record_type, &copied,
						  msg->msg_flags);
D
Dave Watson 已提交
1086
			if (ret) {
1087 1088
				if (ret == -EINPROGRESS)
					num_async++;
1089 1090 1091 1092 1093
				else if (ret == -ENOMEM)
					goto wait_for_memory;
				else if (ret != -EAGAIN) {
					if (ret == -ENOSPC)
						ret = 0;
1094
					goto send_end;
1095
				}
D
Dave Watson 已提交
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
			}
		}

		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:
1107 1108
			if (ctx->open_rec)
				tls_trim_both_msgs(sk, orig_size);
D
Dave Watson 已提交
1109 1110 1111
			goto send_end;
		}

1112
		if (ctx->open_rec && msg_en->sg.size < required_size)
D
Dave Watson 已提交
1113 1114 1115
			goto alloc_encrypted;
	}

1116 1117 1118 1119
	if (!num_async) {
		goto send_end;
	} else if (num_zc) {
		/* Wait for pending encryptions to get completed */
1120 1121
		spin_lock_bh(&ctx->encrypt_compl_lock);
		ctx->async_notify = true;
1122

1123 1124 1125
		pending = atomic_read(&ctx->encrypt_pending);
		spin_unlock_bh(&ctx->encrypt_compl_lock);
		if (pending)
1126 1127 1128 1129
			crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
		else
			reinit_completion(&ctx->async_wait.completion);

1130 1131 1132
		/* There can be no concurrent accesses, since we have no
		 * pending encrypt operations
		 */
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
		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 已提交
1147 1148 1149 1150
send_end:
	ret = sk_stream_error(sk, msg->msg_flags, ret);

	release_sock(sk);
J
Jakub Kicinski 已提交
1151
	mutex_unlock(&tls_ctx->tx_lock);
1152
	return copied > 0 ? copied : ret;
D
Dave Watson 已提交
1153 1154
}

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

1172
	eor = !(flags & MSG_SENDPAGE_NOTLAST);
D
Dave Watson 已提交
1173 1174 1175 1176 1177 1178 1179
	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) {
1180
			ret = -sk->sk_err;
D
Dave Watson 已提交
1181 1182 1183
			goto sendpage_end;
		}

1184 1185 1186 1187
		if (ctx->open_rec)
			rec = ctx->open_rec;
		else
			rec = ctx->open_rec = tls_get_rec(sk);
1188 1189 1190 1191 1192
		if (!rec) {
			ret = -ENOMEM;
			goto sendpage_end;
		}

1193 1194
		msg_pl = &rec->msg_plaintext;

D
Dave Watson 已提交
1195
		full_record = false;
1196
		record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
D
Dave Watson 已提交
1197 1198 1199 1200 1201
		copy = size;
		if (copy >= record_room) {
			copy = record_room;
			full_record = true;
		}
1202

1203
		required_size = msg_pl->sg.size + copy + prot->overhead_size;
D
Dave Watson 已提交
1204 1205 1206 1207

		if (!sk_stream_memory_free(sk))
			goto wait_for_sndbuf;
alloc_payload:
1208
		ret = tls_alloc_encrypted_msg(sk, required_size);
D
Dave Watson 已提交
1209 1210 1211 1212 1213 1214 1215 1216
		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
			 */
1217
			copy -= required_size - msg_pl->sg.size;
D
Dave Watson 已提交
1218 1219 1220
			full_record = true;
		}

1221
		sk_msg_page_add(msg_pl, page, copy, offset);
D
Dave Watson 已提交
1222
		sk_mem_charge(sk, copy);
1223

D
Dave Watson 已提交
1224 1225
		offset += copy;
		size -= copy;
1226
		copied += copy;
D
Dave Watson 已提交
1227

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

1255 1256
		if (ctx->open_rec)
			goto alloc_payload;
D
Dave Watson 已提交
1257 1258
	}

1259 1260 1261 1262 1263 1264 1265
	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 已提交
1266
sendpage_end:
1267
	ret = sk_stream_error(sk, flags, ret);
1268
	return copied > 0 ? copied : ret;
D
Dave Watson 已提交
1269 1270
}

1271 1272 1273 1274 1275 1276
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))
1277
		return -EOPNOTSUPP;
1278 1279 1280 1281

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

1282 1283 1284
int tls_sw_sendpage(struct sock *sk, struct page *page,
		    int offset, size_t size, int flags)
{
J
Jakub Kicinski 已提交
1285
	struct tls_context *tls_ctx = tls_get_ctx(sk);
1286 1287 1288 1289
	int ret;

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

J
Jakub Kicinski 已提交
1292
	mutex_lock(&tls_ctx->tx_lock);
1293 1294 1295
	lock_sock(sk);
	ret = tls_sw_do_sendpage(sk, page, offset, size, flags);
	release_sock(sk);
J
Jakub Kicinski 已提交
1296
	mutex_unlock(&tls_ctx->tx_lock);
1297 1298 1299
	return ret;
}

1300
static struct sk_buff *tls_wait_data(struct sock *sk, struct sk_psock *psock,
1301
				     bool nonblock, long timeo, int *err)
D
Dave Watson 已提交
1302 1303
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
1304
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
1305 1306 1307
	struct sk_buff *skb;
	DEFINE_WAIT_FUNC(wait, woken_wake_function);

1308
	while (!(skb = ctx->recv_pkt) && sk_psock_queue_empty(psock)) {
D
Dave Watson 已提交
1309 1310 1311 1312 1313
		if (sk->sk_err) {
			*err = sock_error(sk);
			return NULL;
		}

1314 1315 1316 1317 1318 1319
		if (!skb_queue_empty(&sk->sk_receive_queue)) {
			__strp_unpause(&ctx->strp);
			if (ctx->recv_pkt)
				return ctx->recv_pkt;
		}

1320 1321 1322
		if (sk->sk_shutdown & RCV_SHUTDOWN)
			return NULL;

D
Dave Watson 已提交
1323 1324 1325
		if (sock_flag(sk, SOCK_DONE))
			return NULL;

1326
		if (nonblock || !timeo) {
D
Dave Watson 已提交
1327 1328 1329 1330 1331 1332
			*err = -EAGAIN;
			return NULL;
		}

		add_wait_queue(sk_sleep(sk), &wait);
		sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1333 1334 1335 1336
		sk_wait_event(sk, &timeo,
			      ctx->recv_pkt != skb ||
			      !sk_psock_queue_empty(psock),
			      &wait);
D
Dave Watson 已提交
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
		sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
		remove_wait_queue(sk_sleep(sk), &wait);

		/* Handle signals */
		if (signal_pending(current)) {
			*err = sock_intr_errno(timeo);
			return NULL;
		}
	}

	return skb;
}

1350
static int tls_setup_from_iter(struct iov_iter *from,
1351 1352 1353 1354 1355 1356
			       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];
1357
	unsigned int size = 0;
1358 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
	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)
1400
		iov_iter_revert(from, size);
1401 1402 1403 1404 1405
	*pages_used = num_elem;

	return rc;
}

1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
/* This function decrypts the input skb into either out_iov or in out_sg
 * or in skb buffers itself. The input parameter 'zc' indicates if
 * 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.
 * zero-copy gets disabled and 'zc' is updated.
 */

static int decrypt_internal(struct sock *sk, struct sk_buff *skb,
			    struct iov_iter *out_iov,
			    struct scatterlist *out_sg,
1417
			    struct tls_decrypt_arg *darg)
1418 1419 1420
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1421
	struct tls_prot_info *prot = &tls_ctx->prot_info;
1422
	struct strp_msg *rxm = strp_msg(skb);
1423
	struct tls_msg *tlm = tls_msg(skb);
1424 1425 1426 1427 1428 1429
	int n_sgin, n_sgout, nsg, mem_size, aead_size, err, pages = 0;
	struct aead_request *aead_req;
	struct sk_buff *unused;
	u8 *aad, *iv, *mem = NULL;
	struct scatterlist *sgin = NULL;
	struct scatterlist *sgout = NULL;
1430 1431
	const int data_len = rxm->full_len - prot->overhead_size +
			     prot->tail_size;
1432
	int iv_offset = 0;
1433

1434
	if (darg->zc && (out_iov || out_sg)) {
1435
		if (out_iov)
1436 1437
			n_sgout = 1 +
				iov_iter_npages_cap(out_iov, INT_MAX, data_len);
1438 1439
		else
			n_sgout = sg_nents(out_sg);
1440 1441
		n_sgin = skb_nsg(skb, rxm->offset + prot->prepend_size,
				 rxm->full_len - prot->prepend_size);
1442 1443
	} else {
		n_sgout = 0;
1444
		darg->zc = false;
1445
		n_sgin = skb_cow_data(skb, 0, &unused);
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
	}

	if (n_sgin < 1)
		return -EBADMSG;

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

	nsg = n_sgin + n_sgout;

	aead_size = sizeof(*aead_req) + crypto_aead_reqsize(ctx->aead_recv);
	mem_size = aead_size + (nsg * sizeof(struct scatterlist));
1458
	mem_size = mem_size + prot->aad_size;
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
	mem_size = mem_size + crypto_aead_ivsize(ctx->aead_recv);

	/* Allocate a single block of memory which contains
	 * aead_req || sgin[] || sgout[] || aad || iv.
	 * This order achieves correct alignment for aead_req, sgin, sgout.
	 */
	mem = kmalloc(mem_size, sk->sk_allocation);
	if (!mem)
		return -ENOMEM;

	/* Segment the allocated memory */
	aead_req = (struct aead_request *)mem;
	sgin = (struct scatterlist *)(mem + aead_size);
	sgout = sgin + n_sgin;
	aad = (u8 *)(sgout + n_sgout);
1474
	iv = aad + prot->aad_size;
1475

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

1488 1489
	/* Prepare IV */
	err = skb_copy_bits(skb, rxm->offset + TLS_HEADER_SIZE,
1490
			    iv + iv_offset + prot->salt_size,
1491
			    prot->iv_size);
1492 1493 1494 1495
	if (err < 0) {
		kfree(mem);
		return err;
	}
1496 1497
	if (prot->version == TLS_1_3_VERSION ||
	    prot->cipher_type == TLS_CIPHER_CHACHA20_POLY1305)
1498
		memcpy(iv + iv_offset, tls_ctx->rx.iv,
1499
		       prot->iv_size + prot->salt_size);
D
Dave Watson 已提交
1500
	else
1501
		memcpy(iv + iv_offset, tls_ctx->rx.iv, prot->salt_size);
D
Dave Watson 已提交
1502

1503
	xor_iv_with_seq(prot, iv + iv_offset, tls_ctx->rx.rec_seq);
1504 1505

	/* Prepare AAD */
1506 1507
	tls_make_aad(aad, rxm->full_len - prot->overhead_size +
		     prot->tail_size,
1508
		     tls_ctx->rx.rec_seq, tlm->control, prot);
1509 1510 1511

	/* Prepare sgin */
	sg_init_table(sgin, n_sgin);
1512
	sg_set_buf(&sgin[0], aad, prot->aad_size);
1513
	err = skb_to_sgvec(skb, &sgin[1],
1514 1515
			   rxm->offset + prot->prepend_size,
			   rxm->full_len - prot->prepend_size);
1516 1517 1518 1519 1520 1521 1522 1523
	if (err < 0) {
		kfree(mem);
		return err;
	}

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

1526 1527
			err = tls_setup_from_iter(out_iov, data_len,
						  &pages, &sgout[1],
1528
						  (n_sgout - 1));
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
			if (err < 0)
				goto fallback_to_reg_recv;
		} 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;
1540
		darg->zc = false;
1541 1542 1543
	}

	/* Prepare and submit AEAD request */
1544
	err = tls_do_decryption(sk, skb, sgin, sgout, iv,
1545
				data_len, aead_req, darg->async);
1546 1547
	if (err == -EINPROGRESS)
		return err;
1548 1549 1550 1551 1552 1553 1554 1555 1556

	/* Release the pages in case iov was mapped to pages */
	for (; pages > 0; pages--)
		put_page(sg_page(&sgout[pages]));

	kfree(mem);
	return err;
}

1557
static int decrypt_skb_update(struct sock *sk, struct sk_buff *skb,
1558 1559
			      struct iov_iter *dest,
			      struct tls_decrypt_arg *darg)
1560 1561
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
1562
	struct tls_prot_info *prot = &tls_ctx->prot_info;
1563
	struct strp_msg *rxm = strp_msg(skb);
1564
	struct tls_msg *tlm = tls_msg(skb);
1565
	int pad, err;
1566

1567
	if (tlm->decrypted) {
1568
		darg->zc = false;
1569 1570
		return 0;
	}
1571

1572 1573 1574 1575
	if (tls_ctx->rx_conf == TLS_HW) {
		err = tls_device_decrypted(sk, tls_ctx, skb, rxm);
		if (err < 0)
			return err;
1576 1577
		if (err > 0) {
			tlm->decrypted = 1;
1578
			darg->zc = false;
1579
			goto decrypt_done;
1580
		}
1581
	}
D
Dave Watson 已提交
1582

1583
	err = decrypt_internal(sk, skb, dest, NULL, darg);
1584 1585 1586 1587 1588 1589
	if (err < 0) {
		if (err == -EINPROGRESS)
			tls_advance_record_sn(sk, prot, &tls_ctx->rx);
		else if (err == -EBADMSG)
			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSDECRYPTERROR);
		return err;
1590
	}
1591

1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
decrypt_done:
	pad = padding_length(prot, skb);
	if (pad < 0)
		return pad;

	rxm->full_len -= pad;
	rxm->offset += prot->prepend_size;
	rxm->full_len -= prot->overhead_size;
	tls_advance_record_sn(sk, prot, &tls_ctx->rx);
	tlm->decrypted = 1;

	return 0;
1604 1605 1606 1607
}

int decrypt_skb(struct sock *sk, struct sk_buff *skb,
		struct scatterlist *sgout)
D
Dave Watson 已提交
1608
{
1609
	struct tls_decrypt_arg darg = { .zc = true, };
D
Dave Watson 已提交
1610

1611
	return decrypt_internal(sk, skb, NULL, sgout, &darg);
D
Dave Watson 已提交
1612 1613 1614 1615 1616 1617
}

static bool tls_sw_advance_skb(struct sock *sk, struct sk_buff *skb,
			       unsigned int len)
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
1618
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1619
	struct strp_msg *rxm = strp_msg(skb);
D
Dave Watson 已提交
1620

1621 1622 1623 1624
	if (len < rxm->full_len) {
		rxm->offset += len;
		rxm->full_len -= len;
		return false;
D
Dave Watson 已提交
1625
	}
1626
	consume_skb(skb);
D
Dave Watson 已提交
1627 1628 1629

	/* Finished with message */
	ctx->recv_pkt = NULL;
1630
	__strp_unpause(&ctx->strp);
D
Dave Watson 已提交
1631 1632 1633 1634

	return true;
}

1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
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;
}

1658
/* This function traverses the rx_list in tls receive context to copies the
1659
 * decrypted records into the buffer provided by caller zero copy is not
1660 1661 1662 1663 1664
 * 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,
1665
			   u8 *control,
1666 1667 1668 1669 1670 1671
			   size_t skip,
			   size_t len,
			   bool zc,
			   bool is_peek)
{
	struct sk_buff *skb = skb_peek(&ctx->rx_list);
1672
	struct tls_msg *tlm;
1673
	ssize_t copied = 0;
1674
	int err;
1675

1676 1677
	while (skip && skb) {
		struct strp_msg *rxm = strp_msg(skb);
1678 1679
		tlm = tls_msg(skb);

1680 1681 1682
		err = tls_record_content_type(msg, tlm, control);
		if (err <= 0)
			return err;
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695

		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);

1696 1697
		tlm = tls_msg(skb);

1698 1699 1700
		err = tls_record_content_type(msg, tlm, control);
		if (err <= 0)
			return err;
1701

1702
		if (!zc || (rxm->full_len - skip) > len) {
1703
			err = skb_copy_datagram_msg(skb, rxm->offset + skip,
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
						    msg, chunk);
			if (err < 0)
				return err;
		}

		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) {
			skb_unlink(skb, &ctx->rx_list);
1734
			consume_skb(skb);
1735 1736 1737 1738 1739 1740 1741 1742
		}

		skb = next_skb;
	}

	return copied;
}

D
Dave Watson 已提交
1743 1744 1745 1746 1747 1748 1749 1750
int tls_sw_recvmsg(struct sock *sk,
		   struct msghdr *msg,
		   size_t len,
		   int nonblock,
		   int flags,
		   int *addr_len)
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
1751
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1752
	struct tls_prot_info *prot = &tls_ctx->prot_info;
1753
	struct sk_psock *psock;
1754
	int num_async, pending;
1755 1756
	unsigned char control = 0;
	ssize_t decrypted = 0;
D
Dave Watson 已提交
1757
	struct strp_msg *rxm;
1758
	struct tls_msg *tlm;
D
Dave Watson 已提交
1759 1760
	struct sk_buff *skb;
	ssize_t copied = 0;
1761
	int target, err = 0;
D
Dave Watson 已提交
1762
	long timeo;
D
David Howells 已提交
1763
	bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
1764
	bool is_peek = flags & MSG_PEEK;
1765
	bool bpf_strp_enabled;
D
Dave Watson 已提交
1766 1767 1768 1769 1770 1771

	flags |= nonblock;

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

1772
	psock = sk_psock_get(sk);
D
Dave Watson 已提交
1773
	lock_sock(sk);
1774
	bpf_strp_enabled = sk_psock_strp_enabled(psock);
D
Dave Watson 已提交
1775

1776
	/* Process pending decrypted records. It must be non-zero-copy */
1777
	err = process_rx_list(ctx, msg, &control, 0, len, false, is_peek);
1778 1779 1780 1781 1782
	if (err < 0) {
		tls_err_abort(sk, err);
		goto end;
	}

1783
	copied = err;
1784
	if (len <= copied)
1785
		goto end;
1786 1787 1788 1789

	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
	len = len - copied;
	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1790

1791 1792
	decrypted = 0;
	num_async = 0;
1793
	while (len && (decrypted + copied < target || ctx->recv_pkt)) {
1794
		struct tls_decrypt_arg darg = {};
1795
		bool retain_skb = false;
1796
		int to_decrypt, chunk;
1797
		bool async;
D
Dave Watson 已提交
1798

1799
		skb = tls_wait_data(sk, psock, flags & MSG_DONTWAIT, timeo, &err);
1800 1801
		if (!skb) {
			if (psock) {
1802 1803
				int ret = sk_msg_recvmsg(sk, psock, msg, len,
							 flags);
1804 1805

				if (ret > 0) {
1806
					decrypted += ret;
1807 1808 1809 1810
					len -= ret;
					continue;
				}
			}
D
Dave Watson 已提交
1811
			goto recv_end;
1812
		}
D
Dave Watson 已提交
1813 1814

		rxm = strp_msg(skb);
1815
		tlm = tls_msg(skb);
1816

1817
		to_decrypt = rxm->full_len - prot->overhead_size;
1818 1819

		if (to_decrypt <= len && !is_kvec && !is_peek &&
1820
		    tlm->control == TLS_RECORD_TYPE_DATA &&
1821 1822
		    prot->version != TLS_1_3_VERSION &&
		    !bpf_strp_enabled)
1823
			darg.zc = true;
1824

1825
		/* Do not use async mode if record is non-data */
1826
		if (tlm->control == TLS_RECORD_TYPE_DATA && !bpf_strp_enabled)
1827
			darg.async = ctx->async_capable;
1828
		else
1829
			darg.async = false;
1830

1831
		err = decrypt_skb_update(sk, skb, &msg->msg_iter, &darg);
1832
		if (err < 0 && err != -EINPROGRESS) {
1833
			tls_err_abort(sk, -EBADMSG);
1834 1835 1836
			goto recv_end;
		}

1837 1838
		if (err == -EINPROGRESS) {
			async = true;
1839
			num_async++;
1840
		}
1841 1842 1843 1844 1845 1846 1847 1848

		/* 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.
		 */
1849 1850
		err = tls_record_content_type(msg, tlm, &control);
		if (err <= 0)
1851
			goto recv_end;
1852

1853 1854 1855
		if (async) {
			/* TLS 1.2-only, to_decrypt must be text length */
			chunk = min_t(int, to_decrypt, len);
1856
			goto pick_next_record;
1857 1858 1859
		}
		/* TLS 1.3 may have updated the length by more than overhead */
		chunk = rxm->full_len;
1860

1861
		if (!darg.zc) {
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
			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);
					ctx->recv_pkt = NULL;
					__strp_unpause(&ctx->strp);
					continue;
				}
			}

1875
			if (chunk > len) {
1876 1877 1878
				retain_skb = true;
				chunk = len;
			}
1879

1880 1881 1882 1883
			err = skb_copy_datagram_msg(skb, rxm->offset,
						    msg, chunk);
			if (err < 0)
				goto recv_end;
1884

1885 1886 1887
			if (!is_peek) {
				rxm->offset = rxm->offset + chunk;
				rxm->full_len = rxm->full_len - chunk;
1888
			}
D
Dave Watson 已提交
1889 1890
		}

1891
pick_next_record:
1892
		decrypted += chunk;
D
Dave Watson 已提交
1893
		len -= chunk;
1894 1895 1896 1897

		/* For async or peek case, queue the current skb */
		if (async || is_peek || retain_skb) {
			skb_queue_tail(&ctx->rx_list, skb);
1898 1899 1900
			ctx->recv_pkt = NULL;
			__strp_unpause(&ctx->strp);
		} else if (tls_sw_advance_skb(sk, skb, chunk)) {
1901 1902 1903
			/* Return full control message to
			 * userspace before trying to parse
			 * another message type
1904
			 */
1905
			msg->msg_flags |= MSG_EOR;
1906
			if (control != TLS_RECORD_TYPE_DATA)
1907 1908
				goto recv_end;
		} else {
1909
			break;
D
Dave Watson 已提交
1910
		}
1911
	}
D
Dave Watson 已提交
1912 1913

recv_end:
1914 1915
	if (num_async) {
		/* Wait for all previously submitted records to be decrypted */
1916
		spin_lock_bh(&ctx->decrypt_compl_lock);
J
Jakub Kicinski 已提交
1917
		reinit_completion(&ctx->async_wait.completion);
1918 1919 1920
		pending = atomic_read(&ctx->decrypt_pending);
		spin_unlock_bh(&ctx->decrypt_compl_lock);
		if (pending) {
1921 1922 1923 1924 1925
			err = crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
			if (err) {
				/* one of async decrypt failed */
				tls_err_abort(sk, err);
				copied = 0;
1926 1927
				decrypted = 0;
				goto end;
1928 1929
			}
		}
1930

1931 1932
		/* Drain records from the rx_list & copy if required */
		if (is_peek || is_kvec)
1933
			err = process_rx_list(ctx, msg, &control, copied,
1934 1935
					      decrypted, false, is_peek);
		else
1936
			err = process_rx_list(ctx, msg, &control, 0,
1937 1938 1939 1940 1941 1942
					      decrypted, true, is_peek);
		if (err < 0) {
			tls_err_abort(sk, err);
			copied = 0;
			goto end;
		}
1943 1944
	}

1945 1946 1947
	copied += decrypted;

end:
D
Dave Watson 已提交
1948
	release_sock(sk);
1949
	sk_defer_free_flush(sk);
1950 1951
	if (psock)
		sk_psock_put(sk, psock);
D
Dave Watson 已提交
1952 1953 1954 1955 1956 1957 1958 1959
	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 已提交
1960
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
1961 1962
	struct strp_msg *rxm = NULL;
	struct sock *sk = sock->sk;
1963
	struct tls_msg *tlm;
D
Dave Watson 已提交
1964 1965
	struct sk_buff *skb;
	ssize_t copied = 0;
1966
	bool from_queue;
D
Dave Watson 已提交
1967 1968 1969 1970 1971 1972
	int err = 0;
	long timeo;
	int chunk;

	lock_sock(sk);

1973
	timeo = sock_rcvtimeo(sk, flags & SPLICE_F_NONBLOCK);
D
Dave Watson 已提交
1974

1975 1976 1977 1978
	from_queue = !skb_queue_empty(&ctx->rx_list);
	if (from_queue) {
		skb = __skb_dequeue(&ctx->rx_list);
	} else {
1979 1980
		struct tls_decrypt_arg darg = {};

1981 1982 1983 1984
		skb = tls_wait_data(sk, NULL, flags & SPLICE_F_NONBLOCK, timeo,
				    &err);
		if (!skb)
			goto splice_read_end;
D
Dave Watson 已提交
1985

1986
		err = decrypt_skb_update(sk, skb, NULL, &darg);
1987 1988 1989 1990
		if (err < 0) {
			tls_err_abort(sk, -EBADMSG);
			goto splice_read_end;
		}
1991
	}
1992

1993 1994 1995
	rxm = strp_msg(skb);
	tlm = tls_msg(skb);

1996
	/* splice does not support reading control messages */
1997
	if (tlm->control != TLS_RECORD_TYPE_DATA) {
1998 1999
		err = -EINVAL;
		goto splice_read_end;
D
Dave Watson 已提交
2000
	}
2001

D
Dave Watson 已提交
2002 2003 2004 2005 2006
	chunk = min_t(unsigned int, rxm->full_len, len);
	copied = skb_splice_bits(skb, sk, rxm->offset, pipe, chunk, flags);
	if (copied < 0)
		goto splice_read_end;

2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
	if (!from_queue) {
		ctx->recv_pkt = NULL;
		__strp_unpause(&ctx->strp);
	}
	if (chunk < rxm->full_len) {
		__skb_queue_head(&ctx->rx_list, skb);
		rxm->offset += len;
		rxm->full_len -= len;
	} else {
		consume_skb(skb);
	}
D
Dave Watson 已提交
2018 2019 2020

splice_read_end:
	release_sock(sk);
2021
	sk_defer_free_flush(sk);
D
Dave Watson 已提交
2022 2023 2024
	return copied ? : err;
}

2025
bool tls_sw_sock_is_readable(struct sock *sk)
D
Dave Watson 已提交
2026 2027
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
2028
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2029 2030
	bool ingress_empty = true;
	struct sk_psock *psock;
D
Dave Watson 已提交
2031

2032 2033 2034 2035 2036
	rcu_read_lock();
	psock = sk_psock(sk);
	if (psock)
		ingress_empty = list_empty(&psock->ingress_msg);
	rcu_read_unlock();
D
Dave Watson 已提交
2037

2038 2039
	return !ingress_empty || ctx->recv_pkt ||
		!skb_queue_empty(&ctx->rx_list);
D
Dave Watson 已提交
2040 2041 2042 2043 2044
}

static int tls_read_size(struct strparser *strp, struct sk_buff *skb)
{
	struct tls_context *tls_ctx = tls_get_ctx(strp->sk);
2045
	struct tls_prot_info *prot = &tls_ctx->prot_info;
K
Kees Cook 已提交
2046
	char header[TLS_HEADER_SIZE + MAX_IV_SIZE];
D
Dave Watson 已提交
2047
	struct strp_msg *rxm = strp_msg(skb);
2048
	struct tls_msg *tlm = tls_msg(skb);
D
Dave Watson 已提交
2049 2050 2051 2052 2053
	size_t cipher_overhead;
	size_t data_len = 0;
	int ret;

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

K
Kees Cook 已提交
2057
	/* Sanity-check size of on-stack buffer. */
2058
	if (WARN_ON(prot->prepend_size > sizeof(header))) {
K
Kees Cook 已提交
2059 2060 2061 2062
		ret = -EINVAL;
		goto read_failure;
	}

D
Dave Watson 已提交
2063
	/* Linearize header to local buffer */
2064
	ret = skb_copy_bits(skb, rxm->offset, header, prot->prepend_size);
D
Dave Watson 已提交
2065 2066 2067
	if (ret < 0)
		goto read_failure;

2068
	tlm->decrypted = 0;
2069
	tlm->control = header[0];
D
Dave Watson 已提交
2070 2071 2072

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

2073
	cipher_overhead = prot->tag_size;
2074 2075
	if (prot->version != TLS_1_3_VERSION &&
	    prot->cipher_type != TLS_CIPHER_CHACHA20_POLY1305)
2076
		cipher_overhead += prot->iv_size;
D
Dave Watson 已提交
2077

D
Dave Watson 已提交
2078
	if (data_len > TLS_MAX_PAYLOAD_SIZE + cipher_overhead +
2079
	    prot->tail_size) {
D
Dave Watson 已提交
2080 2081 2082 2083 2084 2085 2086 2087
		ret = -EMSGSIZE;
		goto read_failure;
	}
	if (data_len < cipher_overhead) {
		ret = -EBADMSG;
		goto read_failure;
	}

D
Dave Watson 已提交
2088 2089 2090
	/* 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 已提交
2091 2092 2093
		ret = -EINVAL;
		goto read_failure;
	}
2094

2095
	tls_device_rx_resync_new_rec(strp->sk, data_len + TLS_HEADER_SIZE,
2096
				     TCP_SKB_CB(skb)->seq + rxm->offset);
D
Dave Watson 已提交
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107
	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 已提交
2108
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
2109 2110 2111 2112

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

2113
	ctx->saved_data_ready(strp->sk);
D
Dave Watson 已提交
2114 2115 2116 2117 2118
}

static void tls_data_ready(struct sock *sk)
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
2119
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2120
	struct sk_psock *psock;
D
Dave Watson 已提交
2121 2122

	strp_data_ready(&ctx->strp);
2123 2124

	psock = sk_psock_get(sk);
2125 2126 2127
	if (psock) {
		if (!list_empty(&psock->ingress_msg))
			ctx->saved_data_ready(sk);
2128 2129
		sk_psock_put(sk, psock);
	}
D
Dave Watson 已提交
2130 2131
}

2132 2133 2134 2135 2136 2137 2138 2139 2140
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);
}

2141
void tls_sw_release_resources_tx(struct sock *sk)
D
Dave Watson 已提交
2142 2143
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
2144
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2145
	struct tls_rec *rec, *tmp;
2146
	int pending;
2147 2148

	/* Wait for any pending async encryptions to complete */
2149 2150 2151 2152 2153 2154
	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)
2155 2156 2157 2158
		crypto_wait_req(-EINPROGRESS, &ctx->async_wait);

	tls_tx_records(sk, -1);

2159
	/* Free up un-sent records in tx_list. First, free
2160 2161
	 * the partially sent record if any at head of tx_list.
	 */
2162 2163
	if (tls_ctx->partially_sent_record) {
		tls_free_partial_record(sk, tls_ctx);
2164
		rec = list_first_entry(&ctx->tx_list,
2165 2166
				       struct tls_rec, list);
		list_del(&rec->list);
2167
		sk_msg_free(sk, &rec->msg_plaintext);
2168 2169 2170
		kfree(rec);
	}

2171
	list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
2172
		list_del(&rec->list);
2173 2174
		sk_msg_free(sk, &rec->msg_encrypted);
		sk_msg_free(sk, &rec->msg_plaintext);
2175 2176
		kfree(rec);
	}
D
Dave Watson 已提交
2177

2178
	crypto_free_aead(ctx->aead_send);
2179
	tls_free_open_rec(sk);
2180 2181 2182 2183 2184
}

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 已提交
2185 2186 2187 2188

	kfree(ctx);
}

2189
void tls_sw_release_resources_rx(struct sock *sk)
B
Boris Pismenny 已提交
2190 2191 2192 2193
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);

2194 2195 2196
	kfree(tls_ctx->rx.rec_seq);
	kfree(tls_ctx->rx.iv);

D
Dave Watson 已提交
2197
	if (ctx->aead_recv) {
2198 2199
		kfree_skb(ctx->recv_pkt);
		ctx->recv_pkt = NULL;
2200
		skb_queue_purge(&ctx->rx_list);
D
Dave Watson 已提交
2201 2202
		crypto_free_aead(ctx->aead_recv);
		strp_stop(&ctx->strp);
2203 2204 2205 2206 2207 2208 2209 2210 2211
		/* 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 已提交
2212
	}
2213 2214
}

2215
void tls_sw_strparser_done(struct tls_context *tls_ctx)
2216 2217 2218
{
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);

2219 2220 2221 2222 2223 2224
	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 已提交
2225 2226 2227 2228

	kfree(ctx);
}

2229 2230 2231 2232 2233 2234 2235 2236
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);
}

2237
/* The work handler to transmitt the encrypted records in tx_list */
2238 2239 2240 2241 2242 2243 2244
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);
2245
	struct tls_sw_context_tx *ctx;
2246

2247
	if (unlikely(!tls_ctx))
2248 2249
		return;

2250 2251 2252 2253 2254 2255
	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 已提交
2256
	mutex_lock(&tls_ctx->tx_lock);
2257 2258 2259
	lock_sock(sk);
	tls_tx_records(sk, -1);
	release_sock(sk);
J
Jakub Kicinski 已提交
2260
	mutex_unlock(&tls_ctx->tx_lock);
2261 2262
}

B
Boris Pismenny 已提交
2263 2264 2265 2266 2267
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 */
2268 2269 2270
	if (is_tx_ready(tx_ctx) &&
	    !test_and_set_bit(BIT_TX_SCHEDULED, &tx_ctx->tx_bitmask))
		schedule_delayed_work(&tx_ctx->tx_work.work, 0);
B
Boris Pismenny 已提交
2271 2272
}

2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
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);
}

D
Dave Watson 已提交
2285
int tls_set_sw_offload(struct sock *sk, struct tls_context *ctx, int tx)
D
Dave Watson 已提交
2286
{
2287 2288
	struct tls_context *tls_ctx = tls_get_ctx(sk);
	struct tls_prot_info *prot = &tls_ctx->prot_info;
D
Dave Watson 已提交
2289
	struct tls_crypto_info *crypto_info;
B
Boris Pismenny 已提交
2290 2291
	struct tls_sw_context_tx *sw_ctx_tx = NULL;
	struct tls_sw_context_rx *sw_ctx_rx = NULL;
D
Dave Watson 已提交
2292 2293 2294
	struct cipher_context *cctx;
	struct crypto_aead **aead;
	struct strp_callbacks cb;
2295
	u16 nonce_size, tag_size, iv_size, rec_seq_size, salt_size;
2296
	struct crypto_tfm *tfm;
2297
	char *iv, *rec_seq, *key, *salt, *cipher_name;
D
Dave Watson 已提交
2298
	size_t keysize;
D
Dave Watson 已提交
2299 2300 2301 2302 2303 2304 2305
	int rc = 0;

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

B
Boris Pismenny 已提交
2306
	if (tx) {
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
		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 已提交
2317 2318
		}
	} else {
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
		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 已提交
2329
		}
D
Dave Watson 已提交
2330 2331
	}

D
Dave Watson 已提交
2332
	if (tx) {
2333
		crypto_init_wait(&sw_ctx_tx->async_wait);
2334
		spin_lock_init(&sw_ctx_tx->encrypt_compl_lock);
2335
		crypto_info = &ctx->crypto_send.info;
D
Dave Watson 已提交
2336
		cctx = &ctx->tx;
B
Boris Pismenny 已提交
2337
		aead = &sw_ctx_tx->aead_send;
2338
		INIT_LIST_HEAD(&sw_ctx_tx->tx_list);
2339 2340
		INIT_DELAYED_WORK(&sw_ctx_tx->tx_work.work, tx_work_handler);
		sw_ctx_tx->tx_work.sk = sk;
D
Dave Watson 已提交
2341
	} else {
2342
		crypto_init_wait(&sw_ctx_rx->async_wait);
2343
		spin_lock_init(&sw_ctx_rx->decrypt_compl_lock);
2344
		crypto_info = &ctx->crypto_recv.info;
D
Dave Watson 已提交
2345
		cctx = &ctx->rx;
2346
		skb_queue_head_init(&sw_ctx_rx->rx_list);
B
Boris Pismenny 已提交
2347
		aead = &sw_ctx_rx->aead_recv;
D
Dave Watson 已提交
2348 2349
	}

D
Dave Watson 已提交
2350 2351
	switch (crypto_info->cipher_type) {
	case TLS_CIPHER_AES_GCM_128: {
2352 2353 2354
		struct tls12_crypto_info_aes_gcm_128 *gcm_128_info;

		gcm_128_info = (void *)crypto_info;
D
Dave Watson 已提交
2355 2356 2357
		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;
2358
		iv = gcm_128_info->iv;
D
Dave Watson 已提交
2359
		rec_seq_size = TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE;
2360
		rec_seq = gcm_128_info->rec_seq;
D
Dave Watson 已提交
2361 2362 2363
		keysize = TLS_CIPHER_AES_GCM_128_KEY_SIZE;
		key = gcm_128_info->key;
		salt = gcm_128_info->salt;
2364 2365
		salt_size = TLS_CIPHER_AES_GCM_128_SALT_SIZE;
		cipher_name = "gcm(aes)";
D
Dave Watson 已提交
2366 2367 2368
		break;
	}
	case TLS_CIPHER_AES_GCM_256: {
2369 2370 2371
		struct tls12_crypto_info_aes_gcm_256 *gcm_256_info;

		gcm_256_info = (void *)crypto_info;
D
Dave Watson 已提交
2372 2373 2374
		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;
2375
		iv = gcm_256_info->iv;
D
Dave Watson 已提交
2376
		rec_seq_size = TLS_CIPHER_AES_GCM_256_REC_SEQ_SIZE;
2377
		rec_seq = gcm_256_info->rec_seq;
D
Dave Watson 已提交
2378 2379 2380
		keysize = TLS_CIPHER_AES_GCM_256_KEY_SIZE;
		key = gcm_256_info->key;
		salt = gcm_256_info->salt;
2381 2382 2383 2384 2385
		salt_size = TLS_CIPHER_AES_GCM_256_SALT_SIZE;
		cipher_name = "gcm(aes)";
		break;
	}
	case TLS_CIPHER_AES_CCM_128: {
2386 2387 2388
		struct tls12_crypto_info_aes_ccm_128 *ccm_128_info;

		ccm_128_info = (void *)crypto_info;
2389 2390 2391
		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;
2392
		iv = ccm_128_info->iv;
2393
		rec_seq_size = TLS_CIPHER_AES_CCM_128_REC_SEQ_SIZE;
2394
		rec_seq = ccm_128_info->rec_seq;
2395 2396 2397 2398 2399
		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 已提交
2400 2401
		break;
	}
2402
	case TLS_CIPHER_CHACHA20_POLY1305: {
2403 2404
		struct tls12_crypto_info_chacha20_poly1305 *chacha20_poly1305_info;

2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418
		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;
	}
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452
	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 已提交
2453 2454
	default:
		rc = -EINVAL;
S
Sabrina Dubroca 已提交
2455
		goto free_priv;
D
Dave Watson 已提交
2456 2457
	}

2458 2459
	/* Sanity-check the sizes for stack allocations. */
	if (iv_size > MAX_IV_SIZE || nonce_size > MAX_IV_SIZE ||
2460
	    rec_seq_size > TLS_MAX_REC_SEQ_SIZE || tag_size != TLS_TAG_SIZE) {
K
Kees Cook 已提交
2461 2462 2463 2464
		rc = -EINVAL;
		goto free_priv;
	}

D
Dave Watson 已提交
2465 2466
	if (crypto_info->version == TLS_1_3_VERSION) {
		nonce_size = 0;
2467 2468
		prot->aad_size = TLS_HEADER_SIZE;
		prot->tail_size = 1;
D
Dave Watson 已提交
2469
	} else {
2470 2471
		prot->aad_size = TLS_AAD_SPACE_SIZE;
		prot->tail_size = 0;
D
Dave Watson 已提交
2472 2473
	}

2474 2475 2476 2477 2478 2479 2480
	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;
2481 2482
	prot->salt_size = salt_size;
	cctx->iv = kmalloc(iv_size + salt_size, GFP_KERNEL);
D
Dave Watson 已提交
2483
	if (!cctx->iv) {
D
Dave Watson 已提交
2484
		rc = -ENOMEM;
S
Sabrina Dubroca 已提交
2485
		goto free_priv;
D
Dave Watson 已提交
2486
	}
D
Dave Watson 已提交
2487
	/* Note: 128 & 256 bit salt are the same size */
2488
	prot->rec_seq_size = rec_seq_size;
2489 2490
	memcpy(cctx->iv, salt, salt_size);
	memcpy(cctx->iv + salt_size, iv, iv_size);
2491
	cctx->rec_seq = kmemdup(rec_seq, rec_seq_size, GFP_KERNEL);
D
Dave Watson 已提交
2492
	if (!cctx->rec_seq) {
D
Dave Watson 已提交
2493 2494 2495
		rc = -ENOMEM;
		goto free_iv;
	}
D
Dave Watson 已提交
2496 2497

	if (!*aead) {
2498
		*aead = crypto_alloc_aead(cipher_name, 0, 0);
D
Dave Watson 已提交
2499 2500 2501
		if (IS_ERR(*aead)) {
			rc = PTR_ERR(*aead);
			*aead = NULL;
D
Dave Watson 已提交
2502 2503 2504 2505 2506 2507
			goto free_rec_seq;
		}
	}

	ctx->push_pending_record = tls_sw_push_pending_record;

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

D
Dave Watson 已提交
2510 2511 2512
	if (rc)
		goto free_aead;

2513
	rc = crypto_aead_setauthsize(*aead, prot->tag_size);
D
Dave Watson 已提交
2514 2515 2516
	if (rc)
		goto free_aead;

B
Boris Pismenny 已提交
2517
	if (sw_ctx_rx) {
2518
		tfm = crypto_aead_tfm(sw_ctx_rx->aead_recv);
2519 2520

		if (crypto_info->version == TLS_1_3_VERSION)
2521
			sw_ctx_rx->async_capable = 0;
2522 2523
		else
			sw_ctx_rx->async_capable =
2524 2525
				!!(tfm->__crt_alg->cra_flags &
				   CRYPTO_ALG_ASYNC);
2526

D
Dave Watson 已提交
2527 2528 2529 2530 2531
		/* Set up strparser */
		memset(&cb, 0, sizeof(cb));
		cb.rcv_msg = tls_queue;
		cb.parse_msg = tls_read_size;

B
Boris Pismenny 已提交
2532
		strp_init(&sw_ctx_rx->strp, sk, &cb);
D
Dave Watson 已提交
2533 2534 2535
	}

	goto out;
D
Dave Watson 已提交
2536 2537

free_aead:
D
Dave Watson 已提交
2538 2539
	crypto_free_aead(*aead);
	*aead = NULL;
D
Dave Watson 已提交
2540
free_rec_seq:
D
Dave Watson 已提交
2541 2542
	kfree(cctx->rec_seq);
	cctx->rec_seq = NULL;
D
Dave Watson 已提交
2543
free_iv:
B
Boris Pismenny 已提交
2544 2545
	kfree(cctx->iv);
	cctx->iv = NULL;
S
Sabrina Dubroca 已提交
2546
free_priv:
B
Boris Pismenny 已提交
2547 2548 2549 2550 2551 2552 2553
	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 已提交
2554 2555 2556
out:
	return rc;
}