tls_sw.c 55.9 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.
 */

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

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

K
Kees Cook 已提交
45 46
#define MAX_IV_SIZE	TLS_CIPHER_AES_GCM_128_IV_SIZE

47 48 49 50 51 52 53 54 55 56 57 58 59 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
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);
}

D
Dave Watson 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
static int padding_length(struct tls_sw_context_rx *ctx,
			  struct tls_context *tls_ctx, struct sk_buff *skb)
{
	struct strp_msg *rxm = strp_msg(skb);
	int sub = 0;

	/* Determine zero-padding length */
	if (tls_ctx->crypto_recv.info.version == TLS_1_3_VERSION) {
		char content_type = 0;
		int err;
		int back = 17;

		while (content_type == 0) {
			if (back > rxm->full_len)
				return -EBADMSG;
			err = skb_copy_bits(skb,
					    rxm->offset + rxm->full_len - back,
					    &content_type, 1);
			if (content_type)
				break;
			sub++;
			back++;
		}
		ctx->control = content_type;
	}
	return sub;
}

151 152 153 154
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;
155
	struct scatterlist *sgin = aead_req->src;
156 157
	struct tls_sw_context_rx *ctx;
	struct tls_context *tls_ctx;
158
	struct scatterlist *sg;
159
	struct sk_buff *skb;
160
	unsigned int pages;
161 162 163 164 165
	int pending;

	skb = (struct sk_buff *)req->data;
	tls_ctx = tls_get_ctx(skb->sk);
	ctx = tls_sw_ctx_rx(tls_ctx);
166 167 168 169

	/* Propagate if there was an err */
	if (err) {
		ctx->async_wait.err = err;
170
		tls_err_abort(skb->sk, err);
171 172
	} else {
		struct strp_msg *rxm = strp_msg(skb);
D
Dave Watson 已提交
173
		rxm->full_len -= padding_length(ctx, tls_ctx, skb);
174 175
		rxm->offset += tls_ctx->rx.prepend_size;
		rxm->full_len -= tls_ctx->rx.overhead_size;
176 177
	}

178 179 180 181 182
	/* After using skb->sk to propagate sk through crypto async callback
	 * we need to NULL it again.
	 */
	skb->sk = NULL;

183

184 185 186 187 188 189 190 191
	/* 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));
		}
192 193 194 195
	}

	kfree(aead_req);

196 197
	pending = atomic_dec_return(&ctx->decrypt_pending);

198 199 200 201
	if (!pending && READ_ONCE(ctx->async_notify))
		complete(&ctx->async_wait.completion);
}

D
Dave Watson 已提交
202
static int tls_do_decryption(struct sock *sk,
203
			     struct sk_buff *skb,
D
Dave Watson 已提交
204 205 206 207
			     struct scatterlist *sgin,
			     struct scatterlist *sgout,
			     char *iv_recv,
			     size_t data_len,
208 209
			     struct aead_request *aead_req,
			     bool async)
D
Dave Watson 已提交
210 211
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
212
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
213 214
	int ret;

215
	aead_request_set_tfm(aead_req, ctx->aead_recv);
216
	aead_request_set_ad(aead_req, tls_ctx->rx.aad_size);
D
Dave Watson 已提交
217 218 219 220
	aead_request_set_crypt(aead_req, sgin, sgout,
			       data_len + tls_ctx->rx.tag_size,
			       (u8 *)iv_recv);

221
	if (async) {
222 223 224 225 226 227 228
		/* 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
		 * before kfree_skb is called. We _know_ skb->sk is NULL
		 * because it is a clone from strparser.
		 */
		skb->sk = sk;
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
		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 已提交
250 251 252
	return ret;
}

253
static void tls_trim_both_msgs(struct sock *sk, int target_size)
D
Dave Watson 已提交
254 255
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
256
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
257
	struct tls_rec *rec = ctx->open_rec;
D
Dave Watson 已提交
258

259
	sk_msg_trim(sk, &rec->msg_plaintext, target_size);
D
Dave Watson 已提交
260
	if (target_size > 0)
261
		target_size += tls_ctx->tx.overhead_size;
262
	sk_msg_trim(sk, &rec->msg_encrypted, target_size);
D
Dave Watson 已提交
263 264
}

265
static int tls_alloc_encrypted_msg(struct sock *sk, int len)
D
Dave Watson 已提交
266 267
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
268
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
269
	struct tls_rec *rec = ctx->open_rec;
270
	struct sk_msg *msg_en = &rec->msg_encrypted;
D
Dave Watson 已提交
271

272
	return sk_msg_alloc(sk, msg_en, len, 0);
D
Dave Watson 已提交
273 274
}

275
static int tls_clone_plaintext_msg(struct sock *sk, int required)
D
Dave Watson 已提交
276 277
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
278
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
279
	struct tls_rec *rec = ctx->open_rec;
280 281
	struct sk_msg *msg_pl = &rec->msg_plaintext;
	struct sk_msg *msg_en = &rec->msg_encrypted;
282
	int skip, len;
D
Dave Watson 已提交
283

284 285
	/* We add page references worth len bytes from encrypted sg
	 * at the end of plaintext sg. It is guaranteed that msg_en
286 287
	 * has enough required room (ensured by caller).
	 */
288
	len = required - msg_pl->sg.size;
289

290 291
	/* Skip initial bytes in msg_en's data to be able to use
	 * same offset of both plain and encrypted data.
292
	 */
293
	skip = tls_ctx->tx.prepend_size + msg_pl->sg.size;
294

295
	return sk_msg_clone(sk, msg_pl, msg_en, skip, len);
D
Dave Watson 已提交
296 297
}

298
static struct tls_rec *tls_get_rec(struct sock *sk)
D
Dave Watson 已提交
299 300
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
301
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
302 303 304
	struct sk_msg *msg_pl, *msg_en;
	struct tls_rec *rec;
	int mem_size;
D
Dave Watson 已提交
305

306 307 308
	mem_size = sizeof(struct tls_rec) + crypto_aead_reqsize(ctx->aead_send);

	rec = kzalloc(mem_size, sk->sk_allocation);
309
	if (!rec)
310 311 312 313 314 315 316 317 318 319
		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);
	sg_set_buf(&rec->sg_aead_in[0], rec->aad_space,
320
		   tls_ctx->tx.aad_size);
321 322 323 324
	sg_unmark_end(&rec->sg_aead_in[1]);

	sg_init_table(rec->sg_aead_out, 2);
	sg_set_buf(&rec->sg_aead_out[0], rec->aad_space,
325
		   tls_ctx->tx.aad_size);
326 327 328 329
	sg_unmark_end(&rec->sg_aead_out[1]);

	return rec;
}
330

331 332
static void tls_free_rec(struct sock *sk, struct tls_rec *rec)
{
333 334
	sk_msg_free(sk, &rec->msg_encrypted);
	sk_msg_free(sk, &rec->msg_plaintext);
335
	kfree(rec);
336 337
}

338 339 340 341 342 343 344 345 346 347 348 349
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;
	}
}

350 351 352 353 354
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;
355
	struct sk_msg *msg_en;
356 357 358
	int tx_flags, rc = 0;

	if (tls_is_partially_sent_record(tls_ctx)) {
359
		rec = list_first_entry(&ctx->tx_list,
360 361 362 363 364 365 366 367 368 369 370 371
				       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.
372
		 * Remove the head of tx_list
373 374
		 */
		list_del(&rec->list);
375
		sk_msg_free(sk, &rec->msg_plaintext);
376 377 378
		kfree(rec);
	}

379 380 381
	/* Tx all ready records */
	list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
		if (READ_ONCE(rec->tx_ready)) {
382 383 384 385 386
			if (flags == -1)
				tx_flags = rec->tx_flags;
			else
				tx_flags = flags;

387
			msg_en = &rec->msg_encrypted;
388
			rc = tls_push_sg(sk, tls_ctx,
389
					 &msg_en->sg.data[msg_en->sg.curr],
390 391 392 393 394
					 0, tx_flags);
			if (rc)
				goto tx_err;

			list_del(&rec->list);
395
			sk_msg_free(sk, &rec->msg_plaintext);
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
			kfree(rec);
		} else {
			break;
		}
	}

tx_err:
	if (rc < 0 && rc != -EAGAIN)
		tls_err_abort(sk, EBADMSG);

	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);
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
415 416
	struct scatterlist *sge;
	struct sk_msg *msg_en;
417 418 419 420 421
	struct tls_rec *rec;
	bool ready = false;
	int pending;

	rec = container_of(aead_req, struct tls_rec, aead_req);
422
	msg_en = &rec->msg_encrypted;
423

424 425 426
	sge = sk_msg_elem(msg_en, msg_en->sg.curr);
	sge->offset -= tls_ctx->tx.prepend_size;
	sge->length += tls_ctx->tx.prepend_size;
427

428
	/* Check if error is previously set on socket */
429 430 431 432 433 434 435 436 437 438 439 440
	if (err || sk->sk_err) {
		rec = NULL;

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

441 442 443 444 445 446 447 448 449 450 451 452
	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;
	}
453 454 455 456 457 458 459 460 461 462 463

	pending = atomic_dec_return(&ctx->encrypt_pending);

	if (!pending && READ_ONCE(ctx->async_notify))
		complete(&ctx->async_wait.completion);

	if (!ready)
		return;

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

467 468
static int tls_do_encryption(struct sock *sk,
			     struct tls_context *tls_ctx,
469 470
			     struct tls_sw_context_tx *ctx,
			     struct aead_request *aead_req,
471
			     size_t data_len, u32 start)
D
Dave Watson 已提交
472
{
473
	struct tls_rec *rec = ctx->open_rec;
474 475
	struct sk_msg *msg_en = &rec->msg_encrypted;
	struct scatterlist *sge = sk_msg_elem(msg_en, start);
D
Dave Watson 已提交
476 477
	int rc;

478
	memcpy(rec->iv_data, tls_ctx->tx.iv, sizeof(rec->iv_data));
D
Dave Watson 已提交
479 480
	xor_iv_with_seq(tls_ctx->crypto_send.info.version, rec->iv_data,
			tls_ctx->tx.rec_seq);
481

482 483
	sge->offset += tls_ctx->tx.prepend_size;
	sge->length -= tls_ctx->tx.prepend_size;
D
Dave Watson 已提交
484

485
	msg_en->sg.curr = start;
486

D
Dave Watson 已提交
487
	aead_request_set_tfm(aead_req, ctx->aead_send);
488
	aead_request_set_ad(aead_req, tls_ctx->tx.aad_size);
489 490
	aead_request_set_crypt(aead_req, rec->sg_aead_in,
			       rec->sg_aead_out,
491
			       data_len, rec->iv_data);
492 493

	aead_request_set_callback(aead_req, CRYPTO_TFM_REQ_MAY_BACKLOG,
494 495
				  tls_encrypt_done, sk);

496 497
	/* Add the record in tx_list */
	list_add_tail((struct list_head *)&rec->list, &ctx->tx_list);
498
	atomic_inc(&ctx->encrypt_pending);
499

500 501 502
	rc = crypto_aead_encrypt(aead_req);
	if (!rc || rc != -EINPROGRESS) {
		atomic_dec(&ctx->encrypt_pending);
503 504
		sge->offset -= tls_ctx->tx.prepend_size;
		sge->length += tls_ctx->tx.prepend_size;
505
	}
D
Dave Watson 已提交
506

507 508 509 510
	if (!rc) {
		WRITE_ONCE(rec->tx_ready, true);
	} else if (rc != -EINPROGRESS) {
		list_del(&rec->list);
511
		return rc;
512
	}
D
Dave Watson 已提交
513

514 515
	/* Unhook the record from context if encryption is not failure */
	ctx->open_rec = NULL;
D
Dave Watson 已提交
516 517
	tls_advance_record_sn(sk, &tls_ctx->tx,
			      tls_ctx->crypto_send.info.version);
D
Dave Watson 已提交
518 519 520
	return rc;
}

521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 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
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 已提交
639 640 641 642
static int tls_push_record(struct sock *sk, int flags,
			   unsigned char record_type)
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
643
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
644 645
	struct tls_rec *rec = ctx->open_rec, *tmp = NULL;
	u32 i, split_point, uninitialized_var(orig_end);
646
	struct sk_msg *msg_pl, *msg_en;
647
	struct aead_request *req;
648
	bool split;
D
Dave Watson 已提交
649 650
	int rc;

651 652
	if (!rec)
		return 0;
653

654 655 656
	msg_pl = &rec->msg_plaintext;
	msg_en = &rec->msg_encrypted;

657 658 659 660 661 662 663 664 665 666 667 668
	split_point = msg_pl->apply_bytes;
	split = split_point && split_point < msg_pl->sg.size;
	if (split) {
		rc = tls_split_open_record(sk, rec, &tmp, msg_pl, msg_en,
					   split_point, tls_ctx->tx.overhead_size,
					   &orig_end);
		if (rc < 0)
			return rc;
		sk_msg_trim(sk, msg_en, msg_pl->sg.size +
			    tls_ctx->tx.overhead_size);
	}

669 670
	rec->tx_flags = flags;
	req = &rec->aead_req;
D
Dave Watson 已提交
671

672 673
	i = msg_pl->sg.end;
	sk_msg_iter_var_prev(i);
D
Dave Watson 已提交
674 675 676 677 678 679 680 681 682 683 684

	rec->content_type = record_type;
	if (tls_ctx->crypto_send.info.version == TLS_1_3_VERSION) {
		/* 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));
	}
685

686 687 688 689 690 691 692 693 694 695 696
	i = msg_pl->sg.start;
	sg_chain(rec->sg_aead_in, 2, rec->inplace_crypto ?
		 &msg_en->sg.data[i] : &msg_pl->sg.data[i]);

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

D
Dave Watson 已提交
697
	tls_make_aad(rec->aad_space, msg_pl->sg.size + tls_ctx->tx.tail_size,
698
		     tls_ctx->tx.rec_seq, tls_ctx->tx.rec_seq_size,
D
Dave Watson 已提交
699 700
		     record_type,
		     tls_ctx->crypto_send.info.version);
D
Dave Watson 已提交
701 702

	tls_fill_prepend(tls_ctx,
703
			 page_address(sg_page(&msg_en->sg.data[i])) +
D
Dave Watson 已提交
704 705 706 707
			 msg_en->sg.data[i].offset,
			 msg_pl->sg.size + tls_ctx->tx.tail_size,
			 record_type,
			 tls_ctx->crypto_send.info.version);
D
Dave Watson 已提交
708

709
	tls_ctx->pending_open_record_frags = false;
D
Dave Watson 已提交
710

D
Dave Watson 已提交
711 712
	rc = tls_do_encryption(sk, tls_ctx, ctx, req,
			       msg_pl->sg.size + tls_ctx->tx.tail_size, i);
713
	if (rc < 0) {
714
		if (rc != -EINPROGRESS) {
715
			tls_err_abort(sk, EBADMSG);
716 717 718 719 720
			if (split) {
				tls_ctx->pending_open_record_frags = true;
				tls_merge_open_record(sk, rec, tmp, orig_end);
			}
		}
721
		ctx->async_capable = 1;
722
		return rc;
723 724 725 726 727 728 729
	} else if (split) {
		msg_pl = &tmp->msg_plaintext;
		msg_en = &tmp->msg_encrypted;
		sk_msg_trim(sk, msg_en, msg_pl->sg.size +
			    tls_ctx->tx.overhead_size);
		tls_ctx->pending_open_record_frags = true;
		ctx->open_rec = tmp;
730
	}
D
Dave Watson 已提交
731

732
	return tls_tx_records(sk, flags);
D
Dave Watson 已提交
733 734
}

735 736 737
static int bpf_exec_tx_verdict(struct sk_msg *msg, struct sock *sk,
			       bool full_record, u8 record_type,
			       size_t *copied, int flags)
D
Dave Watson 已提交
738 739
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
740
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
741 742 743
	struct sk_msg msg_redir = { };
	struct sk_psock *psock;
	struct sock *sk_redir;
744
	struct tls_rec *rec;
745
	bool enospc, policy;
746
	int err = 0, send;
747
	u32 delta = 0;
748

749
	policy = !(flags & MSG_SENDPAGE_NOPOLICY);
750
	psock = sk_psock_get(sk);
751
	if (!psock || !policy)
752 753 754
		return tls_push_record(sk, flags, record_type);
more_data:
	enospc = sk_msg_full(msg);
755 756
	if (psock->eval == __SK_NONE) {
		delta = msg->sg.size;
757
		psock->eval = sk_psock_msg_verdict(sk, psock, msg);
758 759 760 761 762
		if (delta < msg->sg.size)
			delta -= msg->sg.size;
		else
			delta = 0;
	}
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
	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);
		if (err < 0) {
			*copied -= sk_msg_free(sk, msg);
			tls_free_open_rec(sk);
			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);
810
		*copied -= (send + delta);
811 812
		err = -EACCES;
	}
813

814 815
	if (likely(!err)) {
		bool reset_eval = !ctx->open_rec;
816

817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
		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;
845 846

	if (!rec)
847
		return 0;
848

849
	msg_pl = &rec->msg_plaintext;
850 851 852
	copied = msg_pl->sg.size;
	if (!copied)
		return 0;
853

854 855
	return bpf_exec_tx_verdict(msg_pl, sk, true, TLS_RECORD_TYPE_DATA,
				   &copied, flags);
856 857 858 859
}

int tls_sw_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
{
D
Dave Watson 已提交
860
	long timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
861 862
	struct tls_context *tls_ctx = tls_get_ctx(sk);
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
863
	bool async_capable = ctx->async_capable;
864
	unsigned char record_type = TLS_RECORD_TYPE_DATA;
D
David Howells 已提交
865
	bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
D
Dave Watson 已提交
866 867
	bool eor = !(msg->msg_flags & MSG_MORE);
	size_t try_to_copy, copied = 0;
868
	struct sk_msg *msg_pl, *msg_en;
869 870 871
	struct tls_rec *rec;
	int required_size;
	int num_async = 0;
D
Dave Watson 已提交
872
	bool full_record;
873 874
	int record_room;
	int num_zc = 0;
D
Dave Watson 已提交
875
	int orig_size;
876
	int ret = 0;
D
Dave Watson 已提交
877 878 879 880 881 882

	if (msg->msg_flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL))
		return -ENOTSUPP;

	lock_sock(sk);

883 884 885 886 887 888
	/* Wait till there is any pending write on socket */
	if (unlikely(sk->sk_write_pending)) {
		ret = wait_on_pending_writer(sk, &timeo);
		if (unlikely(ret))
			goto send_end;
	}
D
Dave Watson 已提交
889 890 891

	if (unlikely(msg->msg_controllen)) {
		ret = tls_proccess_cmsg(sk, msg, &record_type);
892 893 894 895 896 897
		if (ret) {
			if (ret == -EINPROGRESS)
				num_async++;
			else if (ret != -EAGAIN)
				goto send_end;
		}
D
Dave Watson 已提交
898 899 900 901
	}

	while (msg_data_left(msg)) {
		if (sk->sk_err) {
902
			ret = -sk->sk_err;
D
Dave Watson 已提交
903 904 905
			goto send_end;
		}

906 907 908 909
		if (ctx->open_rec)
			rec = ctx->open_rec;
		else
			rec = ctx->open_rec = tls_get_rec(sk);
910 911 912 913 914
		if (!rec) {
			ret = -ENOMEM;
			goto send_end;
		}

915 916 917 918
		msg_pl = &rec->msg_plaintext;
		msg_en = &rec->msg_encrypted;

		orig_size = msg_pl->sg.size;
D
Dave Watson 已提交
919 920
		full_record = false;
		try_to_copy = msg_data_left(msg);
921
		record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
D
Dave Watson 已提交
922 923 924 925 926
		if (try_to_copy >= record_room) {
			try_to_copy = record_room;
			full_record = true;
		}

927
		required_size = msg_pl->sg.size + try_to_copy +
928
				tls_ctx->tx.overhead_size;
D
Dave Watson 已提交
929 930 931

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

D
Dave Watson 已提交
933
alloc_encrypted:
934
		ret = tls_alloc_encrypted_msg(sk, required_size);
D
Dave Watson 已提交
935 936 937 938 939 940 941 942
		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
			 */
943
			try_to_copy -= required_size - msg_en->sg.size;
D
Dave Watson 已提交
944 945
			full_record = true;
		}
946 947

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

950 951
			ret = sk_msg_zerocopy_from_iter(sk, &msg->msg_iter,
							msg_pl, try_to_copy);
D
Dave Watson 已提交
952 953 954
			if (ret)
				goto fallback_to_reg_send;

955 956
			rec->inplace_crypto = 0;

957
			num_zc++;
D
Dave Watson 已提交
958
			copied += try_to_copy;
959 960 961 962 963

			sk_msg_sg_copy_set(msg_pl, first);
			ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
						  record_type, &copied,
						  msg->msg_flags);
964 965 966
			if (ret) {
				if (ret == -EINPROGRESS)
					num_async++;
967 968 969 970
				else if (ret == -ENOMEM)
					goto wait_for_memory;
				else if (ret == -ENOSPC)
					goto rollback_iter;
971 972 973
				else if (ret != -EAGAIN)
					goto send_end;
			}
974
			continue;
975 976 977 978 979
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 已提交
980
fallback_to_reg_send:
981
			sk_msg_trim(sk, msg_pl, orig_size);
D
Dave Watson 已提交
982 983
		}

984
		required_size = msg_pl->sg.size + try_to_copy;
985

986
		ret = tls_clone_plaintext_msg(sk, required_size);
D
Dave Watson 已提交
987 988
		if (ret) {
			if (ret != -ENOSPC)
989
				goto send_end;
D
Dave Watson 已提交
990 991 992 993 994

			/* Adjust try_to_copy according to the amount that was
			 * actually allocated. The difference is due
			 * to max sg elements limit
			 */
995
			try_to_copy -= required_size - msg_pl->sg.size;
D
Dave Watson 已提交
996
			full_record = true;
997 998
			sk_msg_trim(sk, msg_en, msg_pl->sg.size +
				    tls_ctx->tx.overhead_size);
D
Dave Watson 已提交
999 1000
		}

1001 1002 1003 1004 1005 1006
		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 已提交
1007

1008 1009 1010 1011
		/* 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 已提交
1012 1013
		copied += try_to_copy;
		if (full_record || eor) {
1014 1015 1016
			ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
						  record_type, &copied,
						  msg->msg_flags);
D
Dave Watson 已提交
1017
			if (ret) {
1018 1019
				if (ret == -EINPROGRESS)
					num_async++;
1020 1021 1022 1023 1024
				else if (ret == -ENOMEM)
					goto wait_for_memory;
				else if (ret != -EAGAIN) {
					if (ret == -ENOSPC)
						ret = 0;
1025
					goto send_end;
1026
				}
D
Dave Watson 已提交
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
			}
		}

		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:
1038
			tls_trim_both_msgs(sk, orig_size);
D
Dave Watson 已提交
1039 1040 1041
			goto send_end;
		}

1042
		if (msg_en->sg.size < required_size)
D
Dave Watson 已提交
1043 1044 1045
			goto alloc_encrypted;
	}

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
	if (!num_async) {
		goto send_end;
	} else if (num_zc) {
		/* Wait for pending encryptions to get completed */
		smp_store_mb(ctx->async_notify, true);

		if (atomic_read(&ctx->encrypt_pending))
			crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
		else
			reinit_completion(&ctx->async_wait.completion);

		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 已提交
1071 1072 1073 1074 1075 1076 1077
send_end:
	ret = sk_stream_error(sk, msg->msg_flags, ret);

	release_sock(sk);
	return copied ? copied : ret;
}

1078 1079
static int tls_sw_do_sendpage(struct sock *sk, struct page *page,
			      int offset, size_t size, int flags)
D
Dave Watson 已提交
1080
{
1081
	long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
D
Dave Watson 已提交
1082
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
1083
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
D
Dave Watson 已提交
1084
	unsigned char record_type = TLS_RECORD_TYPE_DATA;
1085
	struct sk_msg *msg_pl;
1086 1087
	struct tls_rec *rec;
	int num_async = 0;
1088
	size_t copied = 0;
D
Dave Watson 已提交
1089 1090
	bool full_record;
	int record_room;
1091
	int ret = 0;
1092
	bool eor;
D
Dave Watson 已提交
1093 1094 1095 1096

	eor = !(flags & (MSG_MORE | MSG_SENDPAGE_NOTLAST));
	sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);

1097 1098 1099 1100 1101 1102
	/* Wait till there is any pending write on socket */
	if (unlikely(sk->sk_write_pending)) {
		ret = wait_on_pending_writer(sk, &timeo);
		if (unlikely(ret))
			goto sendpage_end;
	}
D
Dave Watson 已提交
1103 1104 1105 1106 1107 1108

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

		if (sk->sk_err) {
1109
			ret = -sk->sk_err;
D
Dave Watson 已提交
1110 1111 1112
			goto sendpage_end;
		}

1113 1114 1115 1116
		if (ctx->open_rec)
			rec = ctx->open_rec;
		else
			rec = ctx->open_rec = tls_get_rec(sk);
1117 1118 1119 1120 1121
		if (!rec) {
			ret = -ENOMEM;
			goto sendpage_end;
		}

1122 1123
		msg_pl = &rec->msg_plaintext;

D
Dave Watson 已提交
1124
		full_record = false;
1125
		record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
1126
		copied = 0;
D
Dave Watson 已提交
1127 1128 1129 1130 1131
		copy = size;
		if (copy >= record_room) {
			copy = record_room;
			full_record = true;
		}
1132 1133 1134

		required_size = msg_pl->sg.size + copy +
				tls_ctx->tx.overhead_size;
D
Dave Watson 已提交
1135 1136 1137 1138

		if (!sk_stream_memory_free(sk))
			goto wait_for_sndbuf;
alloc_payload:
1139
		ret = tls_alloc_encrypted_msg(sk, required_size);
D
Dave Watson 已提交
1140 1141 1142 1143 1144 1145 1146 1147
		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
			 */
1148
			copy -= required_size - msg_pl->sg.size;
D
Dave Watson 已提交
1149 1150 1151
			full_record = true;
		}

1152
		sk_msg_page_add(msg_pl, page, copy, offset);
D
Dave Watson 已提交
1153
		sk_mem_charge(sk, copy);
1154

D
Dave Watson 已提交
1155 1156
		offset += copy;
		size -= copy;
1157
		copied += copy;
D
Dave Watson 已提交
1158

1159 1160
		tls_ctx->pending_open_record_frags = true;
		if (full_record || eor || sk_msg_full(msg_pl)) {
1161
			rec->inplace_crypto = 0;
1162 1163
			ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
						  record_type, &copied, flags);
D
Dave Watson 已提交
1164
			if (ret) {
1165 1166
				if (ret == -EINPROGRESS)
					num_async++;
1167 1168 1169 1170 1171
				else if (ret == -ENOMEM)
					goto wait_for_memory;
				else if (ret != -EAGAIN) {
					if (ret == -ENOSPC)
						ret = 0;
1172
					goto sendpage_end;
1173
				}
D
Dave Watson 已提交
1174 1175 1176 1177 1178 1179 1180 1181
			}
		}
		continue;
wait_for_sndbuf:
		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
wait_for_memory:
		ret = sk_stream_wait_memory(sk, &timeo);
		if (ret) {
1182
			tls_trim_both_msgs(sk, msg_pl->sg.size);
D
Dave Watson 已提交
1183 1184 1185 1186 1187 1188
			goto sendpage_end;
		}

		goto alloc_payload;
	}

1189 1190 1191 1192 1193 1194 1195
	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 已提交
1196
sendpage_end:
1197 1198
	ret = sk_stream_error(sk, flags, ret);
	return copied ? copied : ret;
D
Dave Watson 已提交
1199 1200
}

1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
int tls_sw_sendpage(struct sock *sk, struct page *page,
		    int offset, size_t size, int flags)
{
	int ret;

	if (flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
		      MSG_SENDPAGE_NOTLAST | MSG_SENDPAGE_NOPOLICY))
		return -ENOTSUPP;

	lock_sock(sk);
	ret = tls_sw_do_sendpage(sk, page, offset, size, flags);
	release_sock(sk);
	return ret;
}

1216 1217
static struct sk_buff *tls_wait_data(struct sock *sk, struct sk_psock *psock,
				     int flags, long timeo, int *err)
D
Dave Watson 已提交
1218 1219
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
1220
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
1221 1222 1223
	struct sk_buff *skb;
	DEFINE_WAIT_FUNC(wait, woken_wake_function);

1224
	while (!(skb = ctx->recv_pkt) && sk_psock_queue_empty(psock)) {
D
Dave Watson 已提交
1225 1226 1227 1228 1229
		if (sk->sk_err) {
			*err = sock_error(sk);
			return NULL;
		}

1230 1231 1232
		if (sk->sk_shutdown & RCV_SHUTDOWN)
			return NULL;

D
Dave Watson 已提交
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
		if (sock_flag(sk, SOCK_DONE))
			return NULL;

		if ((flags & MSG_DONTWAIT) || !timeo) {
			*err = -EAGAIN;
			return NULL;
		}

		add_wait_queue(sk_sleep(sk), &wait);
		sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1243 1244 1245 1246
		sk_wait_event(sk, &timeo,
			      ctx->recv_pkt != skb ||
			      !sk_psock_queue_empty(psock),
			      &wait);
D
Dave Watson 已提交
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
		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;
}

1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
static int tls_setup_from_iter(struct sock *sk, struct iov_iter *from,
			       int length, int *pages_used,
			       unsigned int *size_used,
			       struct scatterlist *to,
			       int to_max_pages)
{
	int rc = 0, i = 0, num_elem = *pages_used, maxpages;
	struct page *pages[MAX_SKB_FRAGS];
	unsigned int size = *size_used;
	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)
		iov_iter_revert(from, size - *size_used);
	*size_used = size;
	*pages_used = num_elem;

	return rc;
}

1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
/* 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,
1329
			    int *chunk, bool *zc, bool async)
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
	struct strp_msg *rxm = strp_msg(skb);
	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;
D
Dave Watson 已提交
1340 1341
	const int data_len = rxm->full_len - tls_ctx->rx.overhead_size +
		tls_ctx->rx.tail_size;
1342 1343 1344 1345 1346 1347

	if (*zc && (out_iov || out_sg)) {
		if (out_iov)
			n_sgout = iov_iter_npages(out_iov, INT_MAX) + 1;
		else
			n_sgout = sg_nents(out_sg);
1348 1349
		n_sgin = skb_nsg(skb, rxm->offset + tls_ctx->rx.prepend_size,
				 rxm->full_len - tls_ctx->rx.prepend_size);
1350 1351 1352
	} else {
		n_sgout = 0;
		*zc = false;
1353
		n_sgin = skb_cow_data(skb, 0, &unused);
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
	}

	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));
1366
	mem_size = mem_size + tls_ctx->rx.aad_size;
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
	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);
1382
	iv = aad + tls_ctx->rx.aad_size;
1383 1384 1385 1386 1387 1388 1389 1390 1391

	/* Prepare IV */
	err = skb_copy_bits(skb, rxm->offset + TLS_HEADER_SIZE,
			    iv + TLS_CIPHER_AES_GCM_128_SALT_SIZE,
			    tls_ctx->rx.iv_size);
	if (err < 0) {
		kfree(mem);
		return err;
	}
D
Dave Watson 已提交
1392 1393 1394 1395 1396 1397 1398
	if (tls_ctx->crypto_recv.info.version == TLS_1_3_VERSION)
		memcpy(iv, tls_ctx->rx.iv, crypto_aead_ivsize(ctx->aead_recv));
	else
		memcpy(iv, tls_ctx->rx.iv, TLS_CIPHER_AES_GCM_128_SALT_SIZE);

	xor_iv_with_seq(tls_ctx->crypto_recv.info.version, iv,
			tls_ctx->rx.rec_seq);
1399 1400

	/* Prepare AAD */
D
Dave Watson 已提交
1401 1402
	tls_make_aad(aad, rxm->full_len - tls_ctx->rx.overhead_size +
		     tls_ctx->rx.tail_size,
1403
		     tls_ctx->rx.rec_seq, tls_ctx->rx.rec_seq_size,
D
Dave Watson 已提交
1404 1405
		     ctx->control,
		     tls_ctx->crypto_recv.info.version);
1406 1407 1408

	/* Prepare sgin */
	sg_init_table(sgin, n_sgin);
1409
	sg_set_buf(&sgin[0], aad, tls_ctx->rx.aad_size);
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
	err = skb_to_sgvec(skb, &sgin[1],
			   rxm->offset + tls_ctx->rx.prepend_size,
			   rxm->full_len - tls_ctx->rx.prepend_size);
	if (err < 0) {
		kfree(mem);
		return err;
	}

	if (n_sgout) {
		if (out_iov) {
			sg_init_table(sgout, n_sgout);
1421
			sg_set_buf(&sgout[0], aad, tls_ctx->rx.aad_size);
1422 1423

			*chunk = 0;
1424 1425 1426
			err = tls_setup_from_iter(sk, out_iov, data_len,
						  &pages, chunk, &sgout[1],
						  (n_sgout - 1));
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
			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;
1438
		*chunk = data_len;
1439 1440 1441 1442
		*zc = false;
	}

	/* Prepare and submit AEAD request */
1443
	err = tls_do_decryption(sk, skb, sgin, sgout, iv,
1444
				data_len, aead_req, async);
1445 1446
	if (err == -EINPROGRESS)
		return err;
1447 1448 1449 1450 1451 1452 1453 1454 1455

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

	kfree(mem);
	return err;
}

1456
static int decrypt_skb_update(struct sock *sk, struct sk_buff *skb,
1457 1458
			      struct iov_iter *dest, int *chunk, bool *zc,
			      bool async)
1459 1460 1461
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
1462
	int version = tls_ctx->crypto_recv.info.version;
1463 1464 1465
	struct strp_msg *rxm = strp_msg(skb);
	int err = 0;

1466 1467
#ifdef CONFIG_TLS_DEVICE
	err = tls_device_decrypted(sk, skb);
1468 1469
	if (err < 0)
		return err;
1470 1471
#endif
	if (!ctx->decrypted) {
1472
		err = decrypt_internal(sk, skb, dest, NULL, chunk, zc, async);
1473 1474
		if (err < 0) {
			if (err == -EINPROGRESS)
D
Dave Watson 已提交
1475 1476
				tls_advance_record_sn(sk, &tls_ctx->rx,
						      version);
1477

1478
			return err;
1479
		}
D
Dave Watson 已提交
1480 1481 1482

		rxm->full_len -= padding_length(ctx, tls_ctx, skb);

1483 1484
		rxm->offset += tls_ctx->rx.prepend_size;
		rxm->full_len -= tls_ctx->rx.overhead_size;
D
Dave Watson 已提交
1485
		tls_advance_record_sn(sk, &tls_ctx->rx, version);
1486 1487
		ctx->decrypted = true;
		ctx->saved_data_ready(sk);
1488 1489 1490
	} else {
		*zc = false;
	}
1491 1492 1493 1494 1495 1496

	return err;
}

int decrypt_skb(struct sock *sk, struct sk_buff *skb,
		struct scatterlist *sgout)
D
Dave Watson 已提交
1497
{
1498 1499
	bool zc = true;
	int chunk;
D
Dave Watson 已提交
1500

1501
	return decrypt_internal(sk, skb, NULL, sgout, &chunk, &zc, false);
D
Dave Watson 已提交
1502 1503 1504 1505 1506 1507
}

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 已提交
1508
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
1509

1510 1511
	if (skb) {
		struct strp_msg *rxm = strp_msg(skb);
D
Dave Watson 已提交
1512

1513 1514 1515 1516 1517 1518
		if (len < rxm->full_len) {
			rxm->offset += len;
			rxm->full_len -= len;
			return false;
		}
		kfree_skb(skb);
D
Dave Watson 已提交
1519 1520 1521 1522
	}

	/* Finished with message */
	ctx->recv_pkt = NULL;
1523
	__strp_unpause(&ctx->strp);
D
Dave Watson 已提交
1524 1525 1526 1527

	return true;
}

1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
/* This function traverses the rx_list in tls receive context to copies the
 * decrypted data records into the buffer provided by caller zero copy is not
 * 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,
			   size_t skip,
			   size_t len,
			   bool zc,
			   bool is_peek)
{
	struct sk_buff *skb = skb_peek(&ctx->rx_list);
	ssize_t copied = 0;

	while (skip && skb) {
		struct strp_msg *rxm = strp_msg(skb);

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

		if (!zc || (rxm->full_len - skip) > len) {
			int err = skb_copy_datagram_msg(skb, rxm->offset + skip,
						    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);
			kfree_skb(skb);
		}

		skb = next_skb;
	}

	return copied;
}

D
Dave Watson 已提交
1599 1600 1601 1602 1603 1604 1605 1606
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 已提交
1607
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1608
	struct sk_psock *psock;
1609 1610
	unsigned char control = 0;
	ssize_t decrypted = 0;
D
Dave Watson 已提交
1611 1612 1613 1614
	struct strp_msg *rxm;
	struct sk_buff *skb;
	ssize_t copied = 0;
	bool cmsg = false;
1615
	int target, err = 0;
D
Dave Watson 已提交
1616
	long timeo;
D
David Howells 已提交
1617
	bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
1618
	bool is_peek = flags & MSG_PEEK;
1619
	int num_async = 0;
D
Dave Watson 已提交
1620 1621 1622 1623 1624 1625

	flags |= nonblock;

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

1626
	psock = sk_psock_get(sk);
D
Dave Watson 已提交
1627 1628
	lock_sock(sk);

1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
	/* Process pending decrypted records. It must be non-zero-copy */
	err = process_rx_list(ctx, msg, 0, len, false, is_peek);
	if (err < 0) {
		tls_err_abort(sk, err);
		goto end;
	} else {
		copied = err;
	}

	len = len - copied;
	if (len) {
		target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
		timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
	} else {
		goto recv_end;
	}

D
Dave Watson 已提交
1646
	do {
1647 1648 1649
		bool retain_skb = false;
		bool zc = false;
		int to_decrypt;
D
Dave Watson 已提交
1650
		int chunk = 0;
1651
		bool async;
D
Dave Watson 已提交
1652

1653 1654 1655
		skb = tls_wait_data(sk, psock, flags, timeo, &err);
		if (!skb) {
			if (psock) {
1656 1657
				int ret = __tcp_bpf_recvmsg(sk, psock,
							    msg, len, flags);
1658 1659

				if (ret > 0) {
1660
					decrypted += ret;
1661 1662 1663 1664
					len -= ret;
					continue;
				}
			}
D
Dave Watson 已提交
1665
			goto recv_end;
1666
		}
D
Dave Watson 已提交
1667 1668

		rxm = strp_msg(skb);
1669

1670 1671 1672
		to_decrypt = rxm->full_len - tls_ctx->rx.overhead_size;

		if (to_decrypt <= len && !is_kvec && !is_peek &&
D
Dave Watson 已提交
1673 1674
		    ctx->control == TLS_RECORD_TYPE_DATA &&
		    tls_ctx->crypto_recv.info.version != TLS_1_3_VERSION)
1675 1676
			zc = true;

1677 1678 1679 1680 1681 1682
		/* Do not use async mode if record is non-data */
		if (ctx->control == TLS_RECORD_TYPE_DATA)
			async = ctx->async_capable;
		else
			async = false;

1683
		err = decrypt_skb_update(sk, skb, &msg->msg_iter,
1684
					 &chunk, &zc, async);
1685 1686 1687 1688 1689
		if (err < 0 && err != -EINPROGRESS) {
			tls_err_abort(sk, EBADMSG);
			goto recv_end;
		}

1690
		if (err == -EINPROGRESS)
1691 1692
			num_async++;

D
Dave Watson 已提交
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
		if (!cmsg) {
			int cerr;

			cerr = put_cmsg(msg, SOL_TLS, TLS_GET_RECORD_TYPE,
					sizeof(ctx->control), &ctx->control);
			cmsg = true;
			control = ctx->control;
			if (ctx->control != TLS_RECORD_TYPE_DATA) {
				if (cerr || msg->msg_flags & MSG_CTRUNC) {
					err = -EIO;
					goto recv_end;
				}
			}
		} else if (control != ctx->control) {
			goto recv_end;
		}

1710 1711 1712
		if (async)
			goto pick_next_record;

1713 1714 1715 1716 1717 1718 1719
		if (!zc) {
			if (rxm->full_len > len) {
				retain_skb = true;
				chunk = len;
			} else {
				chunk = rxm->full_len;
			}
1720

1721 1722 1723 1724
			err = skb_copy_datagram_msg(skb, rxm->offset,
						    msg, chunk);
			if (err < 0)
				goto recv_end;
1725

1726 1727 1728
			if (!is_peek) {
				rxm->offset = rxm->offset + chunk;
				rxm->full_len = rxm->full_len - chunk;
1729
			}
D
Dave Watson 已提交
1730 1731
		}

1732
pick_next_record:
1733 1734 1735 1736
		if (chunk > len)
			chunk = len;

		decrypted += chunk;
D
Dave Watson 已提交
1737
		len -= chunk;
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748

		/* For async or peek case, queue the current skb */
		if (async || is_peek || retain_skb) {
			skb_queue_tail(&ctx->rx_list, skb);
			skb = NULL;
		}

		if (tls_sw_advance_skb(sk, skb, chunk)) {
			/* Return full control message to
			 * userspace before trying to parse
			 * another message type
1749
			 */
1750 1751 1752 1753
			msg->msg_flags |= MSG_EOR;
			if (ctx->control != TLS_RECORD_TYPE_DATA)
				goto recv_end;
		} else {
1754
			break;
D
Dave Watson 已提交
1755
		}
1756

1757
		/* If we have a new message from strparser, continue now. */
1758
		if (decrypted >= target && !ctx->recv_pkt)
1759
			break;
D
Dave Watson 已提交
1760 1761 1762
	} while (len);

recv_end:
1763 1764 1765 1766 1767 1768 1769 1770 1771
	if (num_async) {
		/* Wait for all previously submitted records to be decrypted */
		smp_store_mb(ctx->async_notify, true);
		if (atomic_read(&ctx->decrypt_pending)) {
			err = crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
			if (err) {
				/* one of async decrypt failed */
				tls_err_abort(sk, err);
				copied = 0;
1772 1773
				decrypted = 0;
				goto end;
1774 1775 1776 1777 1778
			}
		} else {
			reinit_completion(&ctx->async_wait.completion);
		}
		WRITE_ONCE(ctx->async_notify, false);
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793

		/* Drain records from the rx_list & copy if required */
		if (is_peek || is_kvec)
			err = process_rx_list(ctx, msg, copied,
					      decrypted, false, is_peek);
		else
			err = process_rx_list(ctx, msg, 0,
					      decrypted, true, is_peek);
		if (err < 0) {
			tls_err_abort(sk, err);
			copied = 0;
			goto end;
		}

		WARN_ON(decrypted != err);
1794 1795
	}

1796 1797 1798
	copied += decrypted;

end:
D
Dave Watson 已提交
1799
	release_sock(sk);
1800 1801
	if (psock)
		sk_psock_put(sk, psock);
D
Dave Watson 已提交
1802 1803 1804 1805 1806 1807 1808 1809
	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 已提交
1810
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
1811 1812 1813 1814 1815 1816 1817
	struct strp_msg *rxm = NULL;
	struct sock *sk = sock->sk;
	struct sk_buff *skb;
	ssize_t copied = 0;
	int err = 0;
	long timeo;
	int chunk;
1818
	bool zc = false;
D
Dave Watson 已提交
1819 1820 1821 1822 1823

	lock_sock(sk);

	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);

1824
	skb = tls_wait_data(sk, NULL, flags, timeo, &err);
D
Dave Watson 已提交
1825 1826 1827 1828
	if (!skb)
		goto splice_read_end;

	if (!ctx->decrypted) {
1829
		err = decrypt_skb_update(sk, skb, NULL, &chunk, &zc, false);
D
Dave Watson 已提交
1830

1831 1832 1833 1834 1835 1836
		/* splice does not support reading control messages */
		if (ctx->control != TLS_RECORD_TYPE_DATA) {
			err = -ENOTSUPP;
			goto splice_read_end;
		}

D
Dave Watson 已提交
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
		if (err < 0) {
			tls_err_abort(sk, EBADMSG);
			goto splice_read_end;
		}
		ctx->decrypted = true;
	}
	rxm = strp_msg(skb);

	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;

	if (likely(!(flags & MSG_PEEK)))
		tls_sw_advance_skb(sk, skb, copied);

splice_read_end:
	release_sock(sk);
	return copied ? : err;
}

1858
bool tls_sw_stream_read(const struct sock *sk)
D
Dave Watson 已提交
1859 1860
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
1861
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1862 1863
	bool ingress_empty = true;
	struct sk_psock *psock;
D
Dave Watson 已提交
1864

1865 1866 1867 1868 1869
	rcu_read_lock();
	psock = sk_psock(sk);
	if (psock)
		ingress_empty = list_empty(&psock->ingress_msg);
	rcu_read_unlock();
D
Dave Watson 已提交
1870

1871
	return !ingress_empty || ctx->recv_pkt;
D
Dave Watson 已提交
1872 1873 1874 1875 1876
}

static int tls_read_size(struct strparser *strp, struct sk_buff *skb)
{
	struct tls_context *tls_ctx = tls_get_ctx(strp->sk);
B
Boris Pismenny 已提交
1877
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
K
Kees Cook 已提交
1878
	char header[TLS_HEADER_SIZE + MAX_IV_SIZE];
D
Dave Watson 已提交
1879 1880 1881 1882 1883 1884 1885 1886 1887
	struct strp_msg *rxm = strp_msg(skb);
	size_t cipher_overhead;
	size_t data_len = 0;
	int ret;

	/* Verify that we have a full TLS header, or wait for more data */
	if (rxm->offset + tls_ctx->rx.prepend_size > skb->len)
		return 0;

K
Kees Cook 已提交
1888 1889 1890 1891 1892 1893
	/* Sanity-check size of on-stack buffer. */
	if (WARN_ON(tls_ctx->rx.prepend_size > sizeof(header))) {
		ret = -EINVAL;
		goto read_failure;
	}

D
Dave Watson 已提交
1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
	/* Linearize header to local buffer */
	ret = skb_copy_bits(skb, rxm->offset, header, tls_ctx->rx.prepend_size);

	if (ret < 0)
		goto read_failure;

	ctx->control = header[0];

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

D
Dave Watson 已提交
1904 1905 1906
	cipher_overhead = tls_ctx->rx.tag_size;
	if (tls_ctx->crypto_recv.info.version != TLS_1_3_VERSION)
		cipher_overhead += tls_ctx->rx.iv_size;
D
Dave Watson 已提交
1907

D
Dave Watson 已提交
1908 1909
	if (data_len > TLS_MAX_PAYLOAD_SIZE + cipher_overhead +
	    tls_ctx->rx.tail_size) {
D
Dave Watson 已提交
1910 1911 1912 1913 1914 1915 1916 1917
		ret = -EMSGSIZE;
		goto read_failure;
	}
	if (data_len < cipher_overhead) {
		ret = -EBADMSG;
		goto read_failure;
	}

D
Dave Watson 已提交
1918 1919 1920
	/* 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 已提交
1921 1922 1923
		ret = -EINVAL;
		goto read_failure;
	}
1924 1925 1926 1927
#ifdef CONFIG_TLS_DEVICE
	handle_device_resync(strp->sk, TCP_SKB_CB(skb)->seq + rxm->offset,
			     *(u64*)tls_ctx->rx.rec_seq);
#endif
D
Dave Watson 已提交
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
	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 已提交
1939
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
D
Dave Watson 已提交
1940 1941 1942 1943 1944 1945

	ctx->decrypted = false;

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

1946
	ctx->saved_data_ready(strp->sk);
D
Dave Watson 已提交
1947 1948 1949 1950 1951
}

static void tls_data_ready(struct sock *sk)
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
1952
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1953
	struct sk_psock *psock;
D
Dave Watson 已提交
1954 1955

	strp_data_ready(&ctx->strp);
1956 1957 1958 1959 1960 1961

	psock = sk_psock_get(sk);
	if (psock && !list_empty(&psock->ingress_msg)) {
		ctx->saved_data_ready(sk);
		sk_psock_put(sk, psock);
	}
D
Dave Watson 已提交
1962 1963
}

B
Boris Pismenny 已提交
1964
void tls_sw_free_resources_tx(struct sock *sk)
D
Dave Watson 已提交
1965 1966
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
B
Boris Pismenny 已提交
1967
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
1968 1969 1970 1971 1972 1973 1974
	struct tls_rec *rec, *tmp;

	/* Wait for any pending async encryptions to complete */
	smp_store_mb(ctx->async_notify, true);
	if (atomic_read(&ctx->encrypt_pending))
		crypto_wait_req(-EINPROGRESS, &ctx->async_wait);

1975
	release_sock(sk);
1976
	cancel_delayed_work_sync(&ctx->tx_work.work);
1977
	lock_sock(sk);
1978 1979 1980 1981

	/* Tx whatever records we can transmit and abandon the rest */
	tls_tx_records(sk, -1);

1982
	/* Free up un-sent records in tx_list. First, free
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
	 * the partially sent record if any at head of tx_list.
	 */
	if (tls_ctx->partially_sent_record) {
		struct scatterlist *sg = tls_ctx->partially_sent_record;

		while (1) {
			put_page(sg_page(sg));
			sk_mem_uncharge(sk, sg->length);

			if (sg_is_last(sg))
				break;
			sg++;
		}

		tls_ctx->partially_sent_record = NULL;

1999
		rec = list_first_entry(&ctx->tx_list,
2000 2001
				       struct tls_rec, list);
		list_del(&rec->list);
2002
		sk_msg_free(sk, &rec->msg_plaintext);
2003 2004 2005
		kfree(rec);
	}

2006
	list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
2007
		list_del(&rec->list);
2008 2009
		sk_msg_free(sk, &rec->msg_encrypted);
		sk_msg_free(sk, &rec->msg_plaintext);
2010 2011
		kfree(rec);
	}
D
Dave Watson 已提交
2012

2013
	crypto_free_aead(ctx->aead_send);
2014
	tls_free_open_rec(sk);
B
Boris Pismenny 已提交
2015 2016 2017 2018

	kfree(ctx);
}

2019
void tls_sw_release_resources_rx(struct sock *sk)
B
Boris Pismenny 已提交
2020 2021 2022 2023
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);

D
Dave Watson 已提交
2024
	if (ctx->aead_recv) {
2025 2026
		kfree_skb(ctx->recv_pkt);
		ctx->recv_pkt = NULL;
2027
		skb_queue_purge(&ctx->rx_list);
D
Dave Watson 已提交
2028 2029 2030 2031 2032 2033 2034 2035 2036
		crypto_free_aead(ctx->aead_recv);
		strp_stop(&ctx->strp);
		write_lock_bh(&sk->sk_callback_lock);
		sk->sk_data_ready = ctx->saved_data_ready;
		write_unlock_bh(&sk->sk_callback_lock);
		release_sock(sk);
		strp_done(&ctx->strp);
		lock_sock(sk);
	}
2037 2038 2039 2040 2041 2042 2043 2044
}

void tls_sw_free_resources_rx(struct sock *sk)
{
	struct tls_context *tls_ctx = tls_get_ctx(sk);
	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);

	tls_sw_release_resources_rx(sk);
D
Dave Watson 已提交
2045 2046 2047 2048

	kfree(ctx);
}

2049
/* The work handler to transmitt the encrypted records in tx_list */
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
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);
	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);

	if (!test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask))
		return;

	lock_sock(sk);
	tls_tx_records(sk, -1);
	release_sock(sk);
}

D
Dave Watson 已提交
2067
int tls_set_sw_offload(struct sock *sk, struct tls_context *ctx, int tx)
D
Dave Watson 已提交
2068 2069 2070
{
	struct tls_crypto_info *crypto_info;
	struct tls12_crypto_info_aes_gcm_128 *gcm_128_info;
D
Dave Watson 已提交
2071
	struct tls12_crypto_info_aes_gcm_256 *gcm_256_info;
B
Boris Pismenny 已提交
2072 2073
	struct tls_sw_context_tx *sw_ctx_tx = NULL;
	struct tls_sw_context_rx *sw_ctx_rx = NULL;
D
Dave Watson 已提交
2074 2075 2076
	struct cipher_context *cctx;
	struct crypto_aead **aead;
	struct strp_callbacks cb;
D
Dave Watson 已提交
2077
	u16 nonce_size, tag_size, iv_size, rec_seq_size;
2078
	struct crypto_tfm *tfm;
D
Dave Watson 已提交
2079 2080
	char *iv, *rec_seq, *key, *salt;
	size_t keysize;
D
Dave Watson 已提交
2081 2082 2083 2084 2085 2086 2087
	int rc = 0;

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

B
Boris Pismenny 已提交
2088
	if (tx) {
2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
		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 已提交
2099 2100
		}
	} else {
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
		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 已提交
2111
		}
D
Dave Watson 已提交
2112 2113
	}

D
Dave Watson 已提交
2114
	if (tx) {
2115
		crypto_init_wait(&sw_ctx_tx->async_wait);
2116
		crypto_info = &ctx->crypto_send.info;
D
Dave Watson 已提交
2117
		cctx = &ctx->tx;
B
Boris Pismenny 已提交
2118
		aead = &sw_ctx_tx->aead_send;
2119
		INIT_LIST_HEAD(&sw_ctx_tx->tx_list);
2120 2121
		INIT_DELAYED_WORK(&sw_ctx_tx->tx_work.work, tx_work_handler);
		sw_ctx_tx->tx_work.sk = sk;
D
Dave Watson 已提交
2122
	} else {
2123
		crypto_init_wait(&sw_ctx_rx->async_wait);
2124
		crypto_info = &ctx->crypto_recv.info;
D
Dave Watson 已提交
2125
		cctx = &ctx->rx;
2126
		skb_queue_head_init(&sw_ctx_rx->rx_list);
B
Boris Pismenny 已提交
2127
		aead = &sw_ctx_rx->aead_recv;
D
Dave Watson 已提交
2128 2129
	}

D
Dave Watson 已提交
2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
	switch (crypto_info->cipher_type) {
	case TLS_CIPHER_AES_GCM_128: {
		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;
		iv = ((struct tls12_crypto_info_aes_gcm_128 *)crypto_info)->iv;
		rec_seq_size = TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE;
		rec_seq =
		 ((struct tls12_crypto_info_aes_gcm_128 *)crypto_info)->rec_seq;
		gcm_128_info =
			(struct tls12_crypto_info_aes_gcm_128 *)crypto_info;
D
Dave Watson 已提交
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
		keysize = TLS_CIPHER_AES_GCM_128_KEY_SIZE;
		key = gcm_128_info->key;
		salt = gcm_128_info->salt;
		break;
	}
	case TLS_CIPHER_AES_GCM_256: {
		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;
		iv = ((struct tls12_crypto_info_aes_gcm_256 *)crypto_info)->iv;
		rec_seq_size = TLS_CIPHER_AES_GCM_256_REC_SEQ_SIZE;
		rec_seq =
		 ((struct tls12_crypto_info_aes_gcm_256 *)crypto_info)->rec_seq;
		gcm_256_info =
			(struct tls12_crypto_info_aes_gcm_256 *)crypto_info;
		keysize = TLS_CIPHER_AES_GCM_256_KEY_SIZE;
		key = gcm_256_info->key;
		salt = gcm_256_info->salt;
D
Dave Watson 已提交
2159 2160 2161 2162
		break;
	}
	default:
		rc = -EINVAL;
S
Sabrina Dubroca 已提交
2163
		goto free_priv;
D
Dave Watson 已提交
2164 2165
	}

K
Kees Cook 已提交
2166
	/* Sanity-check the IV size for stack allocations. */
K
Kees Cook 已提交
2167
	if (iv_size > MAX_IV_SIZE || nonce_size > MAX_IV_SIZE) {
K
Kees Cook 已提交
2168 2169 2170 2171
		rc = -EINVAL;
		goto free_priv;
	}

D
Dave Watson 已提交
2172 2173 2174 2175 2176 2177 2178 2179 2180
	if (crypto_info->version == TLS_1_3_VERSION) {
		nonce_size = 0;
		cctx->aad_size = TLS_HEADER_SIZE;
		cctx->tail_size = 1;
	} else {
		cctx->aad_size = TLS_AAD_SPACE_SIZE;
		cctx->tail_size = 0;
	}

D
Dave Watson 已提交
2181 2182
	cctx->prepend_size = TLS_HEADER_SIZE + nonce_size;
	cctx->tag_size = tag_size;
D
Dave Watson 已提交
2183 2184
	cctx->overhead_size = cctx->prepend_size + cctx->tag_size +
		cctx->tail_size;
D
Dave Watson 已提交
2185 2186 2187 2188
	cctx->iv_size = iv_size;
	cctx->iv = kmalloc(iv_size + TLS_CIPHER_AES_GCM_128_SALT_SIZE,
			   GFP_KERNEL);
	if (!cctx->iv) {
D
Dave Watson 已提交
2189
		rc = -ENOMEM;
S
Sabrina Dubroca 已提交
2190
		goto free_priv;
D
Dave Watson 已提交
2191
	}
D
Dave Watson 已提交
2192 2193
	/* Note: 128 & 256 bit salt are the same size */
	memcpy(cctx->iv, salt, TLS_CIPHER_AES_GCM_128_SALT_SIZE);
D
Dave Watson 已提交
2194 2195
	memcpy(cctx->iv + TLS_CIPHER_AES_GCM_128_SALT_SIZE, iv, iv_size);
	cctx->rec_seq_size = rec_seq_size;
2196
	cctx->rec_seq = kmemdup(rec_seq, rec_seq_size, GFP_KERNEL);
D
Dave Watson 已提交
2197
	if (!cctx->rec_seq) {
D
Dave Watson 已提交
2198 2199 2200
		rc = -ENOMEM;
		goto free_iv;
	}
D
Dave Watson 已提交
2201 2202 2203 2204 2205 2206

	if (!*aead) {
		*aead = crypto_alloc_aead("gcm(aes)", 0, 0);
		if (IS_ERR(*aead)) {
			rc = PTR_ERR(*aead);
			*aead = NULL;
D
Dave Watson 已提交
2207 2208 2209 2210 2211 2212
			goto free_rec_seq;
		}
	}

	ctx->push_pending_record = tls_sw_push_pending_record;

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

D
Dave Watson 已提交
2215 2216 2217
	if (rc)
		goto free_aead;

D
Dave Watson 已提交
2218 2219 2220 2221
	rc = crypto_aead_setauthsize(*aead, cctx->tag_size);
	if (rc)
		goto free_aead;

B
Boris Pismenny 已提交
2222
	if (sw_ctx_rx) {
2223
		tfm = crypto_aead_tfm(sw_ctx_rx->aead_recv);
2224 2225 2226 2227 2228 2229

		if (crypto_info->version == TLS_1_3_VERSION)
			sw_ctx_rx->async_capable = false;
		else
			sw_ctx_rx->async_capable =
				tfm->__crt_alg->cra_flags & CRYPTO_ALG_ASYNC;
2230

D
Dave Watson 已提交
2231 2232 2233 2234 2235
		/* Set up strparser */
		memset(&cb, 0, sizeof(cb));
		cb.rcv_msg = tls_queue;
		cb.parse_msg = tls_read_size;

B
Boris Pismenny 已提交
2236
		strp_init(&sw_ctx_rx->strp, sk, &cb);
D
Dave Watson 已提交
2237 2238

		write_lock_bh(&sk->sk_callback_lock);
B
Boris Pismenny 已提交
2239
		sw_ctx_rx->saved_data_ready = sk->sk_data_ready;
D
Dave Watson 已提交
2240 2241 2242
		sk->sk_data_ready = tls_data_ready;
		write_unlock_bh(&sk->sk_callback_lock);

B
Boris Pismenny 已提交
2243
		strp_check_rcv(&sw_ctx_rx->strp);
D
Dave Watson 已提交
2244 2245 2246
	}

	goto out;
D
Dave Watson 已提交
2247 2248

free_aead:
D
Dave Watson 已提交
2249 2250
	crypto_free_aead(*aead);
	*aead = NULL;
D
Dave Watson 已提交
2251
free_rec_seq:
D
Dave Watson 已提交
2252 2253
	kfree(cctx->rec_seq);
	cctx->rec_seq = NULL;
D
Dave Watson 已提交
2254
free_iv:
B
Boris Pismenny 已提交
2255 2256
	kfree(cctx->iv);
	cctx->iv = NULL;
S
Sabrina Dubroca 已提交
2257
free_priv:
B
Boris Pismenny 已提交
2258 2259 2260 2261 2262 2263 2264
	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 已提交
2265 2266 2267
out:
	return rc;
}