2 * Copyright (c) 2016-2017, Mellanox Technologies. All rights reserved.
3 * Copyright (c) 2016-2017, Dave Watson <davejwatson@fb.com>. All rights reserved.
4 * Copyright (c) 2016-2017, Lance Chao <lancerchao@fb.com>. All rights reserved.
5 * Copyright (c) 2016, Fridolin Pokorny <fridolin.pokorny@gmail.com>. All rights reserved.
6 * Copyright (c) 2016, Nikos Mavrogiannopoulos <nmav@gnutls.org>. All rights reserved.
7 * Copyright (c) 2018, Covalent IO, Inc. http://covalent.io
9 * This software is available to you under a choice of one of two
10 * licenses. You may choose to be licensed under the terms of the GNU
11 * General Public License (GPL) Version 2, available from the file
12 * COPYING in the main directory of this source tree, or the
13 * OpenIB.org BSD license below:
15 * Redistribution and use in source and binary forms, with or
16 * without modification, are permitted provided that the following
19 * - Redistributions of source code must retain the above
20 * copyright notice, this list of conditions and the following
23 * - Redistributions in binary form must reproduce the above
24 * copyright notice, this list of conditions and the following
25 * disclaimer in the documentation and/or other materials
26 * provided with the distribution.
28 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
29 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
30 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
31 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
32 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
33 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
38 #include <linux/bug.h>
39 #include <linux/sched/signal.h>
40 #include <linux/module.h>
41 #include <linux/kernel.h>
42 #include <linux/splice.h>
43 #include <crypto/aead.h>
45 #include <net/strparser.h>
47 #include <trace/events/sock.h>
51 struct tls_decrypt_arg {
61 struct tls_decrypt_ctx {
64 u8 aad[TLS_MAX_AAD_SIZE];
66 struct scatterlist sg[];
69 noinline void tls_err_abort(struct sock *sk, int err)
71 WARN_ON_ONCE(err >= 0);
72 /* sk->sk_err should contain a positive error code. */
73 WRITE_ONCE(sk->sk_err, -err);
74 /* Paired with smp_rmb() in tcp_poll() */
79 static int __skb_nsg(struct sk_buff *skb, int offset, int len,
80 unsigned int recursion_level)
82 int start = skb_headlen(skb);
83 int i, chunk = start - offset;
84 struct sk_buff *frag_iter;
87 if (unlikely(recursion_level >= 24))
100 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
103 WARN_ON(start > offset + len);
105 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
106 chunk = end - offset;
119 if (unlikely(skb_has_frag_list(skb))) {
120 skb_walk_frags(skb, frag_iter) {
123 WARN_ON(start > offset + len);
125 end = start + frag_iter->len;
126 chunk = end - offset;
130 ret = __skb_nsg(frag_iter, offset - start, chunk,
131 recursion_level + 1);
132 if (unlikely(ret < 0))
147 /* Return the number of scatterlist elements required to completely map the
148 * skb, or -EMSGSIZE if the recursion depth is exceeded.
150 static int skb_nsg(struct sk_buff *skb, int offset, int len)
152 return __skb_nsg(skb, offset, len, 0);
155 static int tls_padding_length(struct tls_prot_info *prot, struct sk_buff *skb,
156 struct tls_decrypt_arg *darg)
158 struct strp_msg *rxm = strp_msg(skb);
159 struct tls_msg *tlm = tls_msg(skb);
162 /* Determine zero-padding length */
163 if (prot->version == TLS_1_3_VERSION) {
164 int offset = rxm->full_len - TLS_TAG_SIZE - 1;
165 char content_type = darg->zc ? darg->tail : 0;
168 while (content_type == 0) {
169 if (offset < prot->prepend_size)
171 err = skb_copy_bits(skb, rxm->offset + offset,
180 tlm->control = content_type;
185 static void tls_decrypt_done(void *data, int err)
187 struct aead_request *aead_req = data;
188 struct crypto_aead *aead = crypto_aead_reqtfm(aead_req);
189 struct scatterlist *sgout = aead_req->dst;
190 struct scatterlist *sgin = aead_req->src;
191 struct tls_sw_context_rx *ctx;
192 struct tls_decrypt_ctx *dctx;
193 struct tls_context *tls_ctx;
194 struct scatterlist *sg;
199 aead_size = sizeof(*aead_req) + crypto_aead_reqsize(aead);
200 aead_size = ALIGN(aead_size, __alignof__(*dctx));
201 dctx = (void *)((u8 *)aead_req + aead_size);
204 tls_ctx = tls_get_ctx(sk);
205 ctx = tls_sw_ctx_rx(tls_ctx);
207 /* Propagate if there was an err */
210 TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSDECRYPTERROR);
211 ctx->async_wait.err = err;
212 tls_err_abort(sk, err);
215 /* Free the destination pages if skb was not decrypted inplace */
217 /* Skip the first S/G entry as it points to AAD */
218 for_each_sg(sg_next(sgout), sg, UINT_MAX, pages) {
221 put_page(sg_page(sg));
227 spin_lock_bh(&ctx->decrypt_compl_lock);
228 if (!atomic_dec_return(&ctx->decrypt_pending))
229 complete(&ctx->async_wait.completion);
230 spin_unlock_bh(&ctx->decrypt_compl_lock);
233 static int tls_do_decryption(struct sock *sk,
234 struct scatterlist *sgin,
235 struct scatterlist *sgout,
238 struct aead_request *aead_req,
239 struct tls_decrypt_arg *darg)
241 struct tls_context *tls_ctx = tls_get_ctx(sk);
242 struct tls_prot_info *prot = &tls_ctx->prot_info;
243 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
246 aead_request_set_tfm(aead_req, ctx->aead_recv);
247 aead_request_set_ad(aead_req, prot->aad_size);
248 aead_request_set_crypt(aead_req, sgin, sgout,
249 data_len + prot->tag_size,
253 aead_request_set_callback(aead_req,
254 CRYPTO_TFM_REQ_MAY_BACKLOG,
255 tls_decrypt_done, aead_req);
256 atomic_inc(&ctx->decrypt_pending);
258 aead_request_set_callback(aead_req,
259 CRYPTO_TFM_REQ_MAY_BACKLOG,
260 crypto_req_done, &ctx->async_wait);
263 ret = crypto_aead_decrypt(aead_req);
264 if (ret == -EINPROGRESS) {
268 ret = crypto_wait_req(ret, &ctx->async_wait);
275 static void tls_trim_both_msgs(struct sock *sk, int target_size)
277 struct tls_context *tls_ctx = tls_get_ctx(sk);
278 struct tls_prot_info *prot = &tls_ctx->prot_info;
279 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
280 struct tls_rec *rec = ctx->open_rec;
282 sk_msg_trim(sk, &rec->msg_plaintext, target_size);
284 target_size += prot->overhead_size;
285 sk_msg_trim(sk, &rec->msg_encrypted, target_size);
288 static int tls_alloc_encrypted_msg(struct sock *sk, int len)
290 struct tls_context *tls_ctx = tls_get_ctx(sk);
291 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
292 struct tls_rec *rec = ctx->open_rec;
293 struct sk_msg *msg_en = &rec->msg_encrypted;
295 return sk_msg_alloc(sk, msg_en, len, 0);
298 static int tls_clone_plaintext_msg(struct sock *sk, int required)
300 struct tls_context *tls_ctx = tls_get_ctx(sk);
301 struct tls_prot_info *prot = &tls_ctx->prot_info;
302 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
303 struct tls_rec *rec = ctx->open_rec;
304 struct sk_msg *msg_pl = &rec->msg_plaintext;
305 struct sk_msg *msg_en = &rec->msg_encrypted;
308 /* We add page references worth len bytes from encrypted sg
309 * at the end of plaintext sg. It is guaranteed that msg_en
310 * has enough required room (ensured by caller).
312 len = required - msg_pl->sg.size;
314 /* Skip initial bytes in msg_en's data to be able to use
315 * same offset of both plain and encrypted data.
317 skip = prot->prepend_size + msg_pl->sg.size;
319 return sk_msg_clone(sk, msg_pl, msg_en, skip, len);
322 static struct tls_rec *tls_get_rec(struct sock *sk)
324 struct tls_context *tls_ctx = tls_get_ctx(sk);
325 struct tls_prot_info *prot = &tls_ctx->prot_info;
326 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
327 struct sk_msg *msg_pl, *msg_en;
331 mem_size = sizeof(struct tls_rec) + crypto_aead_reqsize(ctx->aead_send);
333 rec = kzalloc(mem_size, sk->sk_allocation);
337 msg_pl = &rec->msg_plaintext;
338 msg_en = &rec->msg_encrypted;
343 sg_init_table(rec->sg_aead_in, 2);
344 sg_set_buf(&rec->sg_aead_in[0], rec->aad_space, prot->aad_size);
345 sg_unmark_end(&rec->sg_aead_in[1]);
347 sg_init_table(rec->sg_aead_out, 2);
348 sg_set_buf(&rec->sg_aead_out[0], rec->aad_space, prot->aad_size);
349 sg_unmark_end(&rec->sg_aead_out[1]);
356 static void tls_free_rec(struct sock *sk, struct tls_rec *rec)
358 sk_msg_free(sk, &rec->msg_encrypted);
359 sk_msg_free(sk, &rec->msg_plaintext);
363 static void tls_free_open_rec(struct sock *sk)
365 struct tls_context *tls_ctx = tls_get_ctx(sk);
366 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
367 struct tls_rec *rec = ctx->open_rec;
370 tls_free_rec(sk, rec);
371 ctx->open_rec = NULL;
375 int tls_tx_records(struct sock *sk, int flags)
377 struct tls_context *tls_ctx = tls_get_ctx(sk);
378 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
379 struct tls_rec *rec, *tmp;
380 struct sk_msg *msg_en;
381 int tx_flags, rc = 0;
383 if (tls_is_partially_sent_record(tls_ctx)) {
384 rec = list_first_entry(&ctx->tx_list,
385 struct tls_rec, list);
388 tx_flags = rec->tx_flags;
392 rc = tls_push_partial_record(sk, tls_ctx, tx_flags);
396 /* Full record has been transmitted.
397 * Remove the head of tx_list
399 list_del(&rec->list);
400 sk_msg_free(sk, &rec->msg_plaintext);
404 /* Tx all ready records */
405 list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
406 if (READ_ONCE(rec->tx_ready)) {
408 tx_flags = rec->tx_flags;
412 msg_en = &rec->msg_encrypted;
413 rc = tls_push_sg(sk, tls_ctx,
414 &msg_en->sg.data[msg_en->sg.curr],
419 list_del(&rec->list);
420 sk_msg_free(sk, &rec->msg_plaintext);
428 if (rc < 0 && rc != -EAGAIN)
429 tls_err_abort(sk, -EBADMSG);
434 static void tls_encrypt_done(void *data, int err)
436 struct tls_sw_context_tx *ctx;
437 struct tls_context *tls_ctx;
438 struct tls_prot_info *prot;
439 struct tls_rec *rec = data;
440 struct scatterlist *sge;
441 struct sk_msg *msg_en;
446 msg_en = &rec->msg_encrypted;
449 tls_ctx = tls_get_ctx(sk);
450 prot = &tls_ctx->prot_info;
451 ctx = tls_sw_ctx_tx(tls_ctx);
453 sge = sk_msg_elem(msg_en, msg_en->sg.curr);
454 sge->offset -= prot->prepend_size;
455 sge->length += prot->prepend_size;
457 /* Check if error is previously set on socket */
458 if (err || sk->sk_err) {
461 /* If err is already set on socket, return the same code */
463 ctx->async_wait.err = -sk->sk_err;
465 ctx->async_wait.err = err;
466 tls_err_abort(sk, err);
471 struct tls_rec *first_rec;
473 /* Mark the record as ready for transmission */
474 smp_store_mb(rec->tx_ready, true);
476 /* If received record is at head of tx_list, schedule tx */
477 first_rec = list_first_entry(&ctx->tx_list,
478 struct tls_rec, list);
479 if (rec == first_rec)
483 spin_lock_bh(&ctx->encrypt_compl_lock);
484 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);
493 /* Schedule the transmission */
494 if (!test_and_set_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask))
495 schedule_delayed_work(&ctx->tx_work.work, 1);
498 static int tls_do_encryption(struct sock *sk,
499 struct tls_context *tls_ctx,
500 struct tls_sw_context_tx *ctx,
501 struct aead_request *aead_req,
502 size_t data_len, u32 start)
504 struct tls_prot_info *prot = &tls_ctx->prot_info;
505 struct tls_rec *rec = ctx->open_rec;
506 struct sk_msg *msg_en = &rec->msg_encrypted;
507 struct scatterlist *sge = sk_msg_elem(msg_en, start);
508 int rc, iv_offset = 0;
510 /* For CCM based ciphers, first byte of IV is a constant */
511 switch (prot->cipher_type) {
512 case TLS_CIPHER_AES_CCM_128:
513 rec->iv_data[0] = TLS_AES_CCM_IV_B0_BYTE;
516 case TLS_CIPHER_SM4_CCM:
517 rec->iv_data[0] = TLS_SM4_CCM_IV_B0_BYTE;
522 memcpy(&rec->iv_data[iv_offset], tls_ctx->tx.iv,
523 prot->iv_size + prot->salt_size);
525 tls_xor_iv_with_seq(prot, rec->iv_data + iv_offset,
526 tls_ctx->tx.rec_seq);
528 sge->offset += prot->prepend_size;
529 sge->length -= prot->prepend_size;
531 msg_en->sg.curr = start;
533 aead_request_set_tfm(aead_req, ctx->aead_send);
534 aead_request_set_ad(aead_req, prot->aad_size);
535 aead_request_set_crypt(aead_req, rec->sg_aead_in,
537 data_len, rec->iv_data);
539 aead_request_set_callback(aead_req, CRYPTO_TFM_REQ_MAY_BACKLOG,
540 tls_encrypt_done, rec);
542 /* Add the record in tx_list */
543 list_add_tail((struct list_head *)&rec->list, &ctx->tx_list);
544 atomic_inc(&ctx->encrypt_pending);
546 rc = crypto_aead_encrypt(aead_req);
547 if (!rc || rc != -EINPROGRESS) {
548 atomic_dec(&ctx->encrypt_pending);
549 sge->offset -= prot->prepend_size;
550 sge->length += prot->prepend_size;
554 WRITE_ONCE(rec->tx_ready, true);
555 } else if (rc != -EINPROGRESS) {
556 list_del(&rec->list);
560 /* Unhook the record from context if encryption is not failure */
561 ctx->open_rec = NULL;
562 tls_advance_record_sn(sk, prot, &tls_ctx->tx);
566 static int tls_split_open_record(struct sock *sk, struct tls_rec *from,
567 struct tls_rec **to, struct sk_msg *msg_opl,
568 struct sk_msg *msg_oen, u32 split_point,
569 u32 tx_overhead_size, u32 *orig_end)
571 u32 i, j, bytes = 0, apply = msg_opl->apply_bytes;
572 struct scatterlist *sge, *osge, *nsge;
573 u32 orig_size = msg_opl->sg.size;
574 struct scatterlist tmp = { };
575 struct sk_msg *msg_npl;
579 new = tls_get_rec(sk);
582 ret = sk_msg_alloc(sk, &new->msg_encrypted, msg_opl->sg.size +
583 tx_overhead_size, 0);
585 tls_free_rec(sk, new);
589 *orig_end = msg_opl->sg.end;
590 i = msg_opl->sg.start;
591 sge = sk_msg_elem(msg_opl, i);
592 while (apply && sge->length) {
593 if (sge->length > apply) {
594 u32 len = sge->length - apply;
596 get_page(sg_page(sge));
597 sg_set_page(&tmp, sg_page(sge), len,
598 sge->offset + apply);
603 apply -= sge->length;
604 bytes += sge->length;
607 sk_msg_iter_var_next(i);
608 if (i == msg_opl->sg.end)
610 sge = sk_msg_elem(msg_opl, i);
614 msg_opl->sg.curr = i;
615 msg_opl->sg.copybreak = 0;
616 msg_opl->apply_bytes = 0;
617 msg_opl->sg.size = bytes;
619 msg_npl = &new->msg_plaintext;
620 msg_npl->apply_bytes = apply;
621 msg_npl->sg.size = orig_size - bytes;
623 j = msg_npl->sg.start;
624 nsge = sk_msg_elem(msg_npl, j);
626 memcpy(nsge, &tmp, sizeof(*nsge));
627 sk_msg_iter_var_next(j);
628 nsge = sk_msg_elem(msg_npl, j);
631 osge = sk_msg_elem(msg_opl, i);
632 while (osge->length) {
633 memcpy(nsge, osge, sizeof(*nsge));
635 sk_msg_iter_var_next(i);
636 sk_msg_iter_var_next(j);
639 osge = sk_msg_elem(msg_opl, i);
640 nsge = sk_msg_elem(msg_npl, j);
644 msg_npl->sg.curr = j;
645 msg_npl->sg.copybreak = 0;
651 static void tls_merge_open_record(struct sock *sk, struct tls_rec *to,
652 struct tls_rec *from, u32 orig_end)
654 struct sk_msg *msg_npl = &from->msg_plaintext;
655 struct sk_msg *msg_opl = &to->msg_plaintext;
656 struct scatterlist *osge, *nsge;
660 sk_msg_iter_var_prev(i);
661 j = msg_npl->sg.start;
663 osge = sk_msg_elem(msg_opl, i);
664 nsge = sk_msg_elem(msg_npl, j);
666 if (sg_page(osge) == sg_page(nsge) &&
667 osge->offset + osge->length == nsge->offset) {
668 osge->length += nsge->length;
669 put_page(sg_page(nsge));
672 msg_opl->sg.end = orig_end;
673 msg_opl->sg.curr = orig_end;
674 msg_opl->sg.copybreak = 0;
675 msg_opl->apply_bytes = msg_opl->sg.size + msg_npl->sg.size;
676 msg_opl->sg.size += msg_npl->sg.size;
678 sk_msg_free(sk, &to->msg_encrypted);
679 sk_msg_xfer_full(&to->msg_encrypted, &from->msg_encrypted);
684 static int tls_push_record(struct sock *sk, int flags,
685 unsigned char record_type)
687 struct tls_context *tls_ctx = tls_get_ctx(sk);
688 struct tls_prot_info *prot = &tls_ctx->prot_info;
689 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
690 struct tls_rec *rec = ctx->open_rec, *tmp = NULL;
691 u32 i, split_point, orig_end;
692 struct sk_msg *msg_pl, *msg_en;
693 struct aead_request *req;
700 msg_pl = &rec->msg_plaintext;
701 msg_en = &rec->msg_encrypted;
703 split_point = msg_pl->apply_bytes;
704 split = split_point && split_point < msg_pl->sg.size;
705 if (unlikely((!split &&
707 prot->overhead_size > msg_en->sg.size) ||
710 prot->overhead_size > msg_en->sg.size))) {
712 split_point = msg_en->sg.size;
715 rc = tls_split_open_record(sk, rec, &tmp, msg_pl, msg_en,
716 split_point, prot->overhead_size,
720 /* This can happen if above tls_split_open_record allocates
721 * a single large encryption buffer instead of two smaller
722 * ones. In this case adjust pointers and continue without
725 if (!msg_pl->sg.size) {
726 tls_merge_open_record(sk, rec, tmp, orig_end);
727 msg_pl = &rec->msg_plaintext;
728 msg_en = &rec->msg_encrypted;
731 sk_msg_trim(sk, msg_en, msg_pl->sg.size +
732 prot->overhead_size);
735 rec->tx_flags = flags;
736 req = &rec->aead_req;
739 sk_msg_iter_var_prev(i);
741 rec->content_type = record_type;
742 if (prot->version == TLS_1_3_VERSION) {
743 /* Add content type to end of message. No padding added */
744 sg_set_buf(&rec->sg_content_type, &rec->content_type, 1);
745 sg_mark_end(&rec->sg_content_type);
746 sg_chain(msg_pl->sg.data, msg_pl->sg.end + 1,
747 &rec->sg_content_type);
749 sg_mark_end(sk_msg_elem(msg_pl, i));
752 if (msg_pl->sg.end < msg_pl->sg.start) {
753 sg_chain(&msg_pl->sg.data[msg_pl->sg.start],
754 MAX_SKB_FRAGS - msg_pl->sg.start + 1,
758 i = msg_pl->sg.start;
759 sg_chain(rec->sg_aead_in, 2, &msg_pl->sg.data[i]);
762 sk_msg_iter_var_prev(i);
763 sg_mark_end(sk_msg_elem(msg_en, i));
765 i = msg_en->sg.start;
766 sg_chain(rec->sg_aead_out, 2, &msg_en->sg.data[i]);
768 tls_make_aad(rec->aad_space, msg_pl->sg.size + prot->tail_size,
769 tls_ctx->tx.rec_seq, record_type, prot);
771 tls_fill_prepend(tls_ctx,
772 page_address(sg_page(&msg_en->sg.data[i])) +
773 msg_en->sg.data[i].offset,
774 msg_pl->sg.size + prot->tail_size,
777 tls_ctx->pending_open_record_frags = false;
779 rc = tls_do_encryption(sk, tls_ctx, ctx, req,
780 msg_pl->sg.size + prot->tail_size, i);
782 if (rc != -EINPROGRESS) {
783 tls_err_abort(sk, -EBADMSG);
785 tls_ctx->pending_open_record_frags = true;
786 tls_merge_open_record(sk, rec, tmp, orig_end);
789 ctx->async_capable = 1;
792 msg_pl = &tmp->msg_plaintext;
793 msg_en = &tmp->msg_encrypted;
794 sk_msg_trim(sk, msg_en, msg_pl->sg.size + prot->overhead_size);
795 tls_ctx->pending_open_record_frags = true;
799 return tls_tx_records(sk, flags);
802 static int bpf_exec_tx_verdict(struct sk_msg *msg, struct sock *sk,
803 bool full_record, u8 record_type,
804 ssize_t *copied, int flags)
806 struct tls_context *tls_ctx = tls_get_ctx(sk);
807 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
808 struct sk_msg msg_redir = { };
809 struct sk_psock *psock;
810 struct sock *sk_redir;
812 bool enospc, policy, redir_ingress;
816 policy = !(flags & MSG_SENDPAGE_NOPOLICY);
817 psock = sk_psock_get(sk);
818 if (!psock || !policy) {
819 err = tls_push_record(sk, flags, record_type);
820 if (err && sk->sk_err == EBADMSG) {
821 *copied -= sk_msg_free(sk, msg);
822 tls_free_open_rec(sk);
826 sk_psock_put(sk, psock);
830 enospc = sk_msg_full(msg);
831 if (psock->eval == __SK_NONE) {
832 delta = msg->sg.size;
833 psock->eval = sk_psock_msg_verdict(sk, psock, msg);
834 delta -= msg->sg.size;
836 if (msg->cork_bytes && msg->cork_bytes > msg->sg.size &&
837 !enospc && !full_record) {
843 if (msg->apply_bytes && msg->apply_bytes < send)
844 send = msg->apply_bytes;
846 switch (psock->eval) {
848 err = tls_push_record(sk, flags, record_type);
849 if (err && sk->sk_err == EBADMSG) {
850 *copied -= sk_msg_free(sk, msg);
851 tls_free_open_rec(sk);
857 redir_ingress = psock->redir_ingress;
858 sk_redir = psock->sk_redir;
859 memcpy(&msg_redir, msg, sizeof(*msg));
860 if (msg->apply_bytes < send)
861 msg->apply_bytes = 0;
863 msg->apply_bytes -= send;
864 sk_msg_return_zero(sk, msg, send);
865 msg->sg.size -= send;
867 err = tcp_bpf_sendmsg_redir(sk_redir, redir_ingress,
868 &msg_redir, send, flags);
871 *copied -= sk_msg_free_nocharge(sk, &msg_redir);
874 if (msg->sg.size == 0)
875 tls_free_open_rec(sk);
879 sk_msg_free_partial(sk, msg, send);
880 if (msg->apply_bytes < send)
881 msg->apply_bytes = 0;
883 msg->apply_bytes -= send;
884 if (msg->sg.size == 0)
885 tls_free_open_rec(sk);
886 *copied -= (send + delta);
891 bool reset_eval = !ctx->open_rec;
895 msg = &rec->msg_plaintext;
896 if (!msg->apply_bytes)
900 psock->eval = __SK_NONE;
901 if (psock->sk_redir) {
902 sock_put(psock->sk_redir);
903 psock->sk_redir = NULL;
910 sk_psock_put(sk, psock);
914 static int tls_sw_push_pending_record(struct sock *sk, int flags)
916 struct tls_context *tls_ctx = tls_get_ctx(sk);
917 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
918 struct tls_rec *rec = ctx->open_rec;
919 struct sk_msg *msg_pl;
925 msg_pl = &rec->msg_plaintext;
926 copied = msg_pl->sg.size;
930 return bpf_exec_tx_verdict(msg_pl, sk, true, TLS_RECORD_TYPE_DATA,
934 static int tls_sw_sendmsg_splice(struct sock *sk, struct msghdr *msg,
935 struct sk_msg *msg_pl, size_t try_to_copy,
938 struct page *page = NULL, **pages = &page;
944 part = iov_iter_extract_pages(&msg->msg_iter, &pages,
945 try_to_copy, 1, 0, &off);
949 if (WARN_ON_ONCE(!sendpage_ok(page))) {
950 iov_iter_revert(&msg->msg_iter, part);
954 sk_msg_page_add(msg_pl, page, part, off);
955 sk_mem_charge(sk, part);
958 } while (try_to_copy && !sk_msg_full(msg_pl));
963 int tls_sw_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
965 long timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
966 struct tls_context *tls_ctx = tls_get_ctx(sk);
967 struct tls_prot_info *prot = &tls_ctx->prot_info;
968 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
969 bool async_capable = ctx->async_capable;
970 unsigned char record_type = TLS_RECORD_TYPE_DATA;
971 bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
972 bool eor = !(msg->msg_flags & MSG_MORE);
975 struct sk_msg *msg_pl, *msg_en;
986 if (msg->msg_flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
987 MSG_CMSG_COMPAT | MSG_SPLICE_PAGES))
990 ret = mutex_lock_interruptible(&tls_ctx->tx_lock);
995 if (unlikely(msg->msg_controllen)) {
996 ret = tls_process_cmsg(sk, msg, &record_type);
998 if (ret == -EINPROGRESS)
1000 else if (ret != -EAGAIN)
1005 while (msg_data_left(msg)) {
1012 rec = ctx->open_rec;
1014 rec = ctx->open_rec = tls_get_rec(sk);
1020 msg_pl = &rec->msg_plaintext;
1021 msg_en = &rec->msg_encrypted;
1023 orig_size = msg_pl->sg.size;
1024 full_record = false;
1025 try_to_copy = msg_data_left(msg);
1026 record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
1027 if (try_to_copy >= record_room) {
1028 try_to_copy = record_room;
1032 required_size = msg_pl->sg.size + try_to_copy +
1033 prot->overhead_size;
1035 if (!sk_stream_memory_free(sk))
1036 goto wait_for_sndbuf;
1039 ret = tls_alloc_encrypted_msg(sk, required_size);
1042 goto wait_for_memory;
1044 /* Adjust try_to_copy according to the amount that was
1045 * actually allocated. The difference is due
1046 * to max sg elements limit
1048 try_to_copy -= required_size - msg_en->sg.size;
1052 if (try_to_copy && (msg->msg_flags & MSG_SPLICE_PAGES)) {
1053 ret = tls_sw_sendmsg_splice(sk, msg, msg_pl,
1054 try_to_copy, &copied);
1057 tls_ctx->pending_open_record_frags = true;
1058 if (full_record || eor || sk_msg_full(msg_pl))
1063 if (!is_kvec && (full_record || eor) && !async_capable) {
1064 u32 first = msg_pl->sg.end;
1066 ret = sk_msg_zerocopy_from_iter(sk, &msg->msg_iter,
1067 msg_pl, try_to_copy);
1069 goto fallback_to_reg_send;
1072 copied += try_to_copy;
1074 sk_msg_sg_copy_set(msg_pl, first);
1075 ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1076 record_type, &copied,
1079 if (ret == -EINPROGRESS)
1081 else if (ret == -ENOMEM)
1082 goto wait_for_memory;
1083 else if (ctx->open_rec && ret == -ENOSPC)
1085 else if (ret != -EAGAIN)
1090 copied -= try_to_copy;
1091 sk_msg_sg_copy_clear(msg_pl, first);
1092 iov_iter_revert(&msg->msg_iter,
1093 msg_pl->sg.size - orig_size);
1094 fallback_to_reg_send:
1095 sk_msg_trim(sk, msg_pl, orig_size);
1098 required_size = msg_pl->sg.size + try_to_copy;
1100 ret = tls_clone_plaintext_msg(sk, required_size);
1105 /* Adjust try_to_copy according to the amount that was
1106 * actually allocated. The difference is due
1107 * to max sg elements limit
1109 try_to_copy -= required_size - msg_pl->sg.size;
1111 sk_msg_trim(sk, msg_en,
1112 msg_pl->sg.size + prot->overhead_size);
1116 ret = sk_msg_memcopy_from_iter(sk, &msg->msg_iter,
1117 msg_pl, try_to_copy);
1122 /* Open records defined only if successfully copied, otherwise
1123 * we would trim the sg but not reset the open record frags.
1125 tls_ctx->pending_open_record_frags = true;
1126 copied += try_to_copy;
1128 if (full_record || eor) {
1129 ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1130 record_type, &copied,
1133 if (ret == -EINPROGRESS)
1135 else if (ret == -ENOMEM)
1136 goto wait_for_memory;
1137 else if (ret != -EAGAIN) {
1148 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1150 ret = sk_stream_wait_memory(sk, &timeo);
1154 tls_trim_both_msgs(sk, orig_size);
1158 if (ctx->open_rec && msg_en->sg.size < required_size)
1159 goto alloc_encrypted;
1164 } else if (num_zc) {
1165 /* Wait for pending encryptions to get completed */
1166 spin_lock_bh(&ctx->encrypt_compl_lock);
1167 ctx->async_notify = true;
1169 pending = atomic_read(&ctx->encrypt_pending);
1170 spin_unlock_bh(&ctx->encrypt_compl_lock);
1172 crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
1174 reinit_completion(&ctx->async_wait.completion);
1176 /* There can be no concurrent accesses, since we have no
1177 * pending encrypt operations
1179 WRITE_ONCE(ctx->async_notify, false);
1181 if (ctx->async_wait.err) {
1182 ret = ctx->async_wait.err;
1187 /* Transmit if any encryptions have completed */
1188 if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
1189 cancel_delayed_work(&ctx->tx_work.work);
1190 tls_tx_records(sk, msg->msg_flags);
1194 ret = sk_stream_error(sk, msg->msg_flags, ret);
1197 mutex_unlock(&tls_ctx->tx_lock);
1198 return copied > 0 ? copied : ret;
1202 * Handle unexpected EOF during splice without SPLICE_F_MORE set.
1204 void tls_sw_splice_eof(struct socket *sock)
1206 struct sock *sk = sock->sk;
1207 struct tls_context *tls_ctx = tls_get_ctx(sk);
1208 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
1209 struct tls_rec *rec;
1210 struct sk_msg *msg_pl;
1212 bool retrying = false;
1219 mutex_lock(&tls_ctx->tx_lock);
1223 rec = ctx->open_rec;
1227 msg_pl = &rec->msg_plaintext;
1229 /* Check the BPF advisor and perform transmission. */
1230 ret = bpf_exec_tx_verdict(msg_pl, sk, false, TLS_RECORD_TYPE_DATA,
1245 /* Wait for pending encryptions to get completed */
1246 spin_lock_bh(&ctx->encrypt_compl_lock);
1247 ctx->async_notify = true;
1249 pending = atomic_read(&ctx->encrypt_pending);
1250 spin_unlock_bh(&ctx->encrypt_compl_lock);
1252 crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
1254 reinit_completion(&ctx->async_wait.completion);
1256 /* There can be no concurrent accesses, since we have no pending
1257 * encrypt operations
1259 WRITE_ONCE(ctx->async_notify, false);
1261 if (ctx->async_wait.err)
1264 /* Transmit if any encryptions have completed */
1265 if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
1266 cancel_delayed_work(&ctx->tx_work.work);
1267 tls_tx_records(sk, 0);
1272 mutex_unlock(&tls_ctx->tx_lock);
1275 static int tls_sw_do_sendpage(struct sock *sk, struct page *page,
1276 int offset, size_t size, int flags)
1278 long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
1279 struct tls_context *tls_ctx = tls_get_ctx(sk);
1280 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
1281 struct tls_prot_info *prot = &tls_ctx->prot_info;
1282 unsigned char record_type = TLS_RECORD_TYPE_DATA;
1283 struct sk_msg *msg_pl;
1284 struct tls_rec *rec;
1292 eor = !(flags & MSG_SENDPAGE_NOTLAST);
1293 sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
1295 /* Call the sk_stream functions to manage the sndbuf mem. */
1297 size_t copy, required_size;
1305 rec = ctx->open_rec;
1307 rec = ctx->open_rec = tls_get_rec(sk);
1313 msg_pl = &rec->msg_plaintext;
1315 full_record = false;
1316 record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
1318 if (copy >= record_room) {
1323 required_size = msg_pl->sg.size + copy + prot->overhead_size;
1325 if (!sk_stream_memory_free(sk))
1326 goto wait_for_sndbuf;
1328 ret = tls_alloc_encrypted_msg(sk, required_size);
1331 goto wait_for_memory;
1333 /* Adjust copy according to the amount that was
1334 * actually allocated. The difference is due
1335 * to max sg elements limit
1337 copy -= required_size - msg_pl->sg.size;
1341 sk_msg_page_add(msg_pl, page, copy, offset);
1342 sk_mem_charge(sk, copy);
1348 tls_ctx->pending_open_record_frags = true;
1349 if (full_record || eor || sk_msg_full(msg_pl)) {
1350 ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1351 record_type, &copied, flags);
1353 if (ret == -EINPROGRESS)
1355 else if (ret == -ENOMEM)
1356 goto wait_for_memory;
1357 else if (ret != -EAGAIN) {
1366 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1368 ret = sk_stream_wait_memory(sk, &timeo);
1371 tls_trim_both_msgs(sk, msg_pl->sg.size);
1380 /* Transmit if any encryptions have completed */
1381 if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
1382 cancel_delayed_work(&ctx->tx_work.work);
1383 tls_tx_records(sk, flags);
1387 ret = sk_stream_error(sk, flags, ret);
1388 return copied > 0 ? copied : ret;
1391 int tls_sw_sendpage_locked(struct sock *sk, struct page *page,
1392 int offset, size_t size, int flags)
1394 if (flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
1395 MSG_SENDPAGE_NOTLAST | MSG_SENDPAGE_NOPOLICY |
1396 MSG_NO_SHARED_FRAGS))
1399 return tls_sw_do_sendpage(sk, page, offset, size, flags);
1402 int tls_sw_sendpage(struct sock *sk, struct page *page,
1403 int offset, size_t size, int flags)
1405 struct tls_context *tls_ctx = tls_get_ctx(sk);
1408 if (flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
1409 MSG_SENDPAGE_NOTLAST | MSG_SENDPAGE_NOPOLICY))
1412 ret = mutex_lock_interruptible(&tls_ctx->tx_lock);
1416 ret = tls_sw_do_sendpage(sk, page, offset, size, flags);
1418 mutex_unlock(&tls_ctx->tx_lock);
1423 tls_rx_rec_wait(struct sock *sk, struct sk_psock *psock, bool nonblock,
1426 struct tls_context *tls_ctx = tls_get_ctx(sk);
1427 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1428 DEFINE_WAIT_FUNC(wait, woken_wake_function);
1431 timeo = sock_rcvtimeo(sk, nonblock);
1433 while (!tls_strp_msg_ready(ctx)) {
1434 if (!sk_psock_queue_empty(psock))
1438 return sock_error(sk);
1440 if (!skb_queue_empty(&sk->sk_receive_queue)) {
1441 tls_strp_check_rcv(&ctx->strp);
1442 if (tls_strp_msg_ready(ctx))
1446 if (sk->sk_shutdown & RCV_SHUTDOWN)
1449 if (sock_flag(sk, SOCK_DONE))
1456 add_wait_queue(sk_sleep(sk), &wait);
1457 sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1458 sk_wait_event(sk, &timeo,
1459 tls_strp_msg_ready(ctx) ||
1460 !sk_psock_queue_empty(psock),
1462 sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1463 remove_wait_queue(sk_sleep(sk), &wait);
1465 /* Handle signals */
1466 if (signal_pending(current))
1467 return sock_intr_errno(timeo);
1470 tls_strp_msg_load(&ctx->strp, released);
1475 static int tls_setup_from_iter(struct iov_iter *from,
1476 int length, int *pages_used,
1477 struct scatterlist *to,
1480 int rc = 0, i = 0, num_elem = *pages_used, maxpages;
1481 struct page *pages[MAX_SKB_FRAGS];
1482 unsigned int size = 0;
1483 ssize_t copied, use;
1486 while (length > 0) {
1488 maxpages = to_max_pages - num_elem;
1489 if (maxpages == 0) {
1493 copied = iov_iter_get_pages2(from, pages,
1504 use = min_t(int, copied, PAGE_SIZE - offset);
1506 sg_set_page(&to[num_elem],
1507 pages[i], use, offset);
1508 sg_unmark_end(&to[num_elem]);
1509 /* We do not uncharge memory from this API */
1518 /* Mark the end in the last sg entry if newly added */
1519 if (num_elem > *pages_used)
1520 sg_mark_end(&to[num_elem - 1]);
1523 iov_iter_revert(from, size);
1524 *pages_used = num_elem;
1529 static struct sk_buff *
1530 tls_alloc_clrtxt_skb(struct sock *sk, struct sk_buff *skb,
1531 unsigned int full_len)
1533 struct strp_msg *clr_rxm;
1534 struct sk_buff *clr_skb;
1537 clr_skb = alloc_skb_with_frags(0, full_len, TLS_PAGE_ORDER,
1538 &err, sk->sk_allocation);
1542 skb_copy_header(clr_skb, skb);
1543 clr_skb->len = full_len;
1544 clr_skb->data_len = full_len;
1546 clr_rxm = strp_msg(clr_skb);
1547 clr_rxm->offset = 0;
1554 * tls_decrypt_sw() and tls_decrypt_device() are decrypt handlers.
1555 * They must transform the darg in/out argument are as follows:
1557 * -------------------------------------------------------------------
1558 * zc | Zero-copy decrypt allowed | Zero-copy performed
1559 * async | Async decrypt allowed | Async crypto used / in progress
1560 * skb | * | Output skb
1562 * If ZC decryption was performed darg.skb will point to the input skb.
1565 /* This function decrypts the input skb into either out_iov or in out_sg
1566 * or in skb buffers itself. The input parameter 'darg->zc' indicates if
1567 * zero-copy mode needs to be tried or not. With zero-copy mode, either
1568 * out_iov or out_sg must be non-NULL. In case both out_iov and out_sg are
1569 * NULL, then the decryption happens inside skb buffers itself, i.e.
1570 * zero-copy gets disabled and 'darg->zc' is updated.
1572 static int tls_decrypt_sg(struct sock *sk, struct iov_iter *out_iov,
1573 struct scatterlist *out_sg,
1574 struct tls_decrypt_arg *darg)
1576 struct tls_context *tls_ctx = tls_get_ctx(sk);
1577 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1578 struct tls_prot_info *prot = &tls_ctx->prot_info;
1579 int n_sgin, n_sgout, aead_size, err, pages = 0;
1580 struct sk_buff *skb = tls_strp_msg(ctx);
1581 const struct strp_msg *rxm = strp_msg(skb);
1582 const struct tls_msg *tlm = tls_msg(skb);
1583 struct aead_request *aead_req;
1584 struct scatterlist *sgin = NULL;
1585 struct scatterlist *sgout = NULL;
1586 const int data_len = rxm->full_len - prot->overhead_size;
1587 int tail_pages = !!prot->tail_size;
1588 struct tls_decrypt_ctx *dctx;
1589 struct sk_buff *clear_skb;
1593 n_sgin = skb_nsg(skb, rxm->offset + prot->prepend_size,
1594 rxm->full_len - prot->prepend_size);
1596 return n_sgin ?: -EBADMSG;
1598 if (darg->zc && (out_iov || out_sg)) {
1602 n_sgout = 1 + tail_pages +
1603 iov_iter_npages_cap(out_iov, INT_MAX, data_len);
1605 n_sgout = sg_nents(out_sg);
1609 clear_skb = tls_alloc_clrtxt_skb(sk, skb, rxm->full_len);
1613 n_sgout = 1 + skb_shinfo(clear_skb)->nr_frags;
1616 /* Increment to accommodate AAD */
1617 n_sgin = n_sgin + 1;
1619 /* Allocate a single block of memory which contains
1620 * aead_req || tls_decrypt_ctx.
1621 * Both structs are variable length.
1623 aead_size = sizeof(*aead_req) + crypto_aead_reqsize(ctx->aead_recv);
1624 aead_size = ALIGN(aead_size, __alignof__(*dctx));
1625 mem = kmalloc(aead_size + struct_size(dctx, sg, n_sgin + n_sgout),
1632 /* Segment the allocated memory */
1633 aead_req = (struct aead_request *)mem;
1634 dctx = (struct tls_decrypt_ctx *)(mem + aead_size);
1636 sgin = &dctx->sg[0];
1637 sgout = &dctx->sg[n_sgin];
1639 /* For CCM based ciphers, first byte of nonce+iv is a constant */
1640 switch (prot->cipher_type) {
1641 case TLS_CIPHER_AES_CCM_128:
1642 dctx->iv[0] = TLS_AES_CCM_IV_B0_BYTE;
1645 case TLS_CIPHER_SM4_CCM:
1646 dctx->iv[0] = TLS_SM4_CCM_IV_B0_BYTE;
1652 if (prot->version == TLS_1_3_VERSION ||
1653 prot->cipher_type == TLS_CIPHER_CHACHA20_POLY1305) {
1654 memcpy(&dctx->iv[iv_offset], tls_ctx->rx.iv,
1655 prot->iv_size + prot->salt_size);
1657 err = skb_copy_bits(skb, rxm->offset + TLS_HEADER_SIZE,
1658 &dctx->iv[iv_offset] + prot->salt_size,
1662 memcpy(&dctx->iv[iv_offset], tls_ctx->rx.iv, prot->salt_size);
1664 tls_xor_iv_with_seq(prot, &dctx->iv[iv_offset], tls_ctx->rx.rec_seq);
1667 tls_make_aad(dctx->aad, rxm->full_len - prot->overhead_size +
1669 tls_ctx->rx.rec_seq, tlm->control, prot);
1672 sg_init_table(sgin, n_sgin);
1673 sg_set_buf(&sgin[0], dctx->aad, prot->aad_size);
1674 err = skb_to_sgvec(skb, &sgin[1],
1675 rxm->offset + prot->prepend_size,
1676 rxm->full_len - prot->prepend_size);
1681 sg_init_table(sgout, n_sgout);
1682 sg_set_buf(&sgout[0], dctx->aad, prot->aad_size);
1684 err = skb_to_sgvec(clear_skb, &sgout[1], prot->prepend_size,
1685 data_len + prot->tail_size);
1688 } else if (out_iov) {
1689 sg_init_table(sgout, n_sgout);
1690 sg_set_buf(&sgout[0], dctx->aad, prot->aad_size);
1692 err = tls_setup_from_iter(out_iov, data_len, &pages, &sgout[1],
1693 (n_sgout - 1 - tail_pages));
1695 goto exit_free_pages;
1697 if (prot->tail_size) {
1698 sg_unmark_end(&sgout[pages]);
1699 sg_set_buf(&sgout[pages + 1], &dctx->tail,
1701 sg_mark_end(&sgout[pages + 1]);
1703 } else if (out_sg) {
1704 memcpy(sgout, out_sg, n_sgout * sizeof(*sgout));
1707 /* Prepare and submit AEAD request */
1708 err = tls_do_decryption(sk, sgin, sgout, dctx->iv,
1709 data_len + prot->tail_size, aead_req, darg);
1711 goto exit_free_pages;
1713 darg->skb = clear_skb ?: tls_strp_msg(ctx);
1716 if (unlikely(darg->async)) {
1717 err = tls_strp_msg_hold(&ctx->strp, &ctx->async_hold);
1719 __skb_queue_tail(&ctx->async_hold, darg->skb);
1723 if (prot->tail_size)
1724 darg->tail = dctx->tail;
1727 /* Release the pages in case iov was mapped to pages */
1728 for (; pages > 0; pages--)
1729 put_page(sg_page(&sgout[pages]));
1733 consume_skb(clear_skb);
1738 tls_decrypt_sw(struct sock *sk, struct tls_context *tls_ctx,
1739 struct msghdr *msg, struct tls_decrypt_arg *darg)
1741 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1742 struct tls_prot_info *prot = &tls_ctx->prot_info;
1743 struct strp_msg *rxm;
1746 err = tls_decrypt_sg(sk, &msg->msg_iter, NULL, darg);
1748 if (err == -EBADMSG)
1749 TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSDECRYPTERROR);
1752 /* keep going even for ->async, the code below is TLS 1.3 */
1754 /* If opportunistic TLS 1.3 ZC failed retry without ZC */
1755 if (unlikely(darg->zc && prot->version == TLS_1_3_VERSION &&
1756 darg->tail != TLS_RECORD_TYPE_DATA)) {
1759 TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSRXNOPADVIOL);
1760 TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSDECRYPTRETRY);
1761 return tls_decrypt_sw(sk, tls_ctx, msg, darg);
1764 pad = tls_padding_length(prot, darg->skb, darg);
1766 if (darg->skb != tls_strp_msg(ctx))
1767 consume_skb(darg->skb);
1771 rxm = strp_msg(darg->skb);
1772 rxm->full_len -= pad;
1778 tls_decrypt_device(struct sock *sk, struct msghdr *msg,
1779 struct tls_context *tls_ctx, struct tls_decrypt_arg *darg)
1781 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1782 struct tls_prot_info *prot = &tls_ctx->prot_info;
1783 struct strp_msg *rxm;
1786 if (tls_ctx->rx_conf != TLS_HW)
1789 err = tls_device_decrypted(sk, tls_ctx);
1793 pad = tls_padding_length(prot, tls_strp_msg(ctx), darg);
1797 darg->async = false;
1798 darg->skb = tls_strp_msg(ctx);
1799 /* ->zc downgrade check, in case TLS 1.3 gets here */
1800 darg->zc &= !(prot->version == TLS_1_3_VERSION &&
1801 tls_msg(darg->skb)->control != TLS_RECORD_TYPE_DATA);
1803 rxm = strp_msg(darg->skb);
1804 rxm->full_len -= pad;
1807 /* Non-ZC case needs a real skb */
1808 darg->skb = tls_strp_msg_detach(ctx);
1812 unsigned int off, len;
1814 /* In ZC case nobody cares about the output skb.
1815 * Just copy the data here. Note the skb is not fully trimmed.
1817 off = rxm->offset + prot->prepend_size;
1818 len = rxm->full_len - prot->overhead_size;
1820 err = skb_copy_datagram_msg(darg->skb, off, msg, len);
1827 static int tls_rx_one_record(struct sock *sk, struct msghdr *msg,
1828 struct tls_decrypt_arg *darg)
1830 struct tls_context *tls_ctx = tls_get_ctx(sk);
1831 struct tls_prot_info *prot = &tls_ctx->prot_info;
1832 struct strp_msg *rxm;
1835 err = tls_decrypt_device(sk, msg, tls_ctx, darg);
1837 err = tls_decrypt_sw(sk, tls_ctx, msg, darg);
1841 rxm = strp_msg(darg->skb);
1842 rxm->offset += prot->prepend_size;
1843 rxm->full_len -= prot->overhead_size;
1844 tls_advance_record_sn(sk, prot, &tls_ctx->rx);
1849 int decrypt_skb(struct sock *sk, struct scatterlist *sgout)
1851 struct tls_decrypt_arg darg = { .zc = true, };
1853 return tls_decrypt_sg(sk, NULL, sgout, &darg);
1856 static int tls_record_content_type(struct msghdr *msg, struct tls_msg *tlm,
1862 *control = tlm->control;
1866 err = put_cmsg(msg, SOL_TLS, TLS_GET_RECORD_TYPE,
1867 sizeof(*control), control);
1868 if (*control != TLS_RECORD_TYPE_DATA) {
1869 if (err || msg->msg_flags & MSG_CTRUNC)
1872 } else if (*control != tlm->control) {
1879 static void tls_rx_rec_done(struct tls_sw_context_rx *ctx)
1881 tls_strp_msg_done(&ctx->strp);
1884 /* This function traverses the rx_list in tls receive context to copies the
1885 * decrypted records into the buffer provided by caller zero copy is not
1886 * true. Further, the records are removed from the rx_list if it is not a peek
1887 * case and the record has been consumed completely.
1889 static int process_rx_list(struct tls_sw_context_rx *ctx,
1896 struct sk_buff *skb = skb_peek(&ctx->rx_list);
1897 struct tls_msg *tlm;
1901 while (skip && skb) {
1902 struct strp_msg *rxm = strp_msg(skb);
1905 err = tls_record_content_type(msg, tlm, control);
1909 if (skip < rxm->full_len)
1912 skip = skip - rxm->full_len;
1913 skb = skb_peek_next(skb, &ctx->rx_list);
1916 while (len && skb) {
1917 struct sk_buff *next_skb;
1918 struct strp_msg *rxm = strp_msg(skb);
1919 int chunk = min_t(unsigned int, rxm->full_len - skip, len);
1923 err = tls_record_content_type(msg, tlm, control);
1927 err = skb_copy_datagram_msg(skb, rxm->offset + skip,
1933 copied = copied + chunk;
1935 /* Consume the data from record if it is non-peek case*/
1937 rxm->offset = rxm->offset + chunk;
1938 rxm->full_len = rxm->full_len - chunk;
1940 /* Return if there is unconsumed data in the record */
1941 if (rxm->full_len - skip)
1945 /* The remaining skip-bytes must lie in 1st record in rx_list.
1946 * So from the 2nd record, 'skip' should be 0.
1951 msg->msg_flags |= MSG_EOR;
1953 next_skb = skb_peek_next(skb, &ctx->rx_list);
1956 __skb_unlink(skb, &ctx->rx_list);
1965 return copied ? : err;
1969 tls_read_flush_backlog(struct sock *sk, struct tls_prot_info *prot,
1970 size_t len_left, size_t decrypted, ssize_t done,
1975 if (len_left <= decrypted)
1978 max_rec = prot->overhead_size - prot->tail_size + TLS_MAX_PAYLOAD_SIZE;
1979 if (done - *flushed_at < SZ_128K && tcp_inq(sk) > max_rec)
1983 return sk_flush_backlog(sk);
1986 static int tls_rx_reader_lock(struct sock *sk, struct tls_sw_context_rx *ctx,
1994 timeo = sock_rcvtimeo(sk, nonblock);
1996 while (unlikely(ctx->reader_present)) {
1997 DEFINE_WAIT_FUNC(wait, woken_wake_function);
1999 ctx->reader_contended = 1;
2001 add_wait_queue(&ctx->wq, &wait);
2002 sk_wait_event(sk, &timeo,
2003 !READ_ONCE(ctx->reader_present), &wait);
2004 remove_wait_queue(&ctx->wq, &wait);
2010 if (signal_pending(current)) {
2011 err = sock_intr_errno(timeo);
2016 WRITE_ONCE(ctx->reader_present, 1);
2025 static void tls_rx_reader_unlock(struct sock *sk, struct tls_sw_context_rx *ctx)
2027 if (unlikely(ctx->reader_contended)) {
2028 if (wq_has_sleeper(&ctx->wq))
2031 ctx->reader_contended = 0;
2033 WARN_ON_ONCE(!ctx->reader_present);
2036 WRITE_ONCE(ctx->reader_present, 0);
2040 int tls_sw_recvmsg(struct sock *sk,
2046 struct tls_context *tls_ctx = tls_get_ctx(sk);
2047 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2048 struct tls_prot_info *prot = &tls_ctx->prot_info;
2049 ssize_t decrypted = 0, async_copy_bytes = 0;
2050 struct sk_psock *psock;
2051 unsigned char control = 0;
2052 size_t flushed_at = 0;
2053 struct strp_msg *rxm;
2054 struct tls_msg *tlm;
2058 bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
2059 bool is_peek = flags & MSG_PEEK;
2060 bool released = true;
2061 bool bpf_strp_enabled;
2064 if (unlikely(flags & MSG_ERRQUEUE))
2065 return sock_recv_errqueue(sk, msg, len, SOL_IP, IP_RECVERR);
2067 psock = sk_psock_get(sk);
2068 err = tls_rx_reader_lock(sk, ctx, flags & MSG_DONTWAIT);
2071 bpf_strp_enabled = sk_psock_strp_enabled(psock);
2073 /* If crypto failed the connection is broken */
2074 err = ctx->async_wait.err;
2078 /* Process pending decrypted records. It must be non-zero-copy */
2079 err = process_rx_list(ctx, msg, &control, 0, len, is_peek);
2087 target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
2090 zc_capable = !bpf_strp_enabled && !is_kvec && !is_peek &&
2093 while (len && (decrypted + copied < target || tls_strp_msg_ready(ctx))) {
2094 struct tls_decrypt_arg darg;
2095 int to_decrypt, chunk;
2097 err = tls_rx_rec_wait(sk, psock, flags & MSG_DONTWAIT,
2101 chunk = sk_msg_recvmsg(sk, psock, msg, len,
2112 memset(&darg.inargs, 0, sizeof(darg.inargs));
2114 rxm = strp_msg(tls_strp_msg(ctx));
2115 tlm = tls_msg(tls_strp_msg(ctx));
2117 to_decrypt = rxm->full_len - prot->overhead_size;
2119 if (zc_capable && to_decrypt <= len &&
2120 tlm->control == TLS_RECORD_TYPE_DATA)
2123 /* Do not use async mode if record is non-data */
2124 if (tlm->control == TLS_RECORD_TYPE_DATA && !bpf_strp_enabled)
2125 darg.async = ctx->async_capable;
2129 err = tls_rx_one_record(sk, msg, &darg);
2131 tls_err_abort(sk, -EBADMSG);
2135 async |= darg.async;
2137 /* If the type of records being processed is not known yet,
2138 * set it to record type just dequeued. If it is already known,
2139 * but does not match the record type just dequeued, go to end.
2140 * We always get record type here since for tls1.2, record type
2141 * is known just after record is dequeued from stream parser.
2142 * For tls1.3, we disable async.
2144 err = tls_record_content_type(msg, tls_msg(darg.skb), &control);
2146 DEBUG_NET_WARN_ON_ONCE(darg.zc);
2147 tls_rx_rec_done(ctx);
2149 __skb_queue_tail(&ctx->rx_list, darg.skb);
2153 /* periodically flush backlog, and feed strparser */
2154 released = tls_read_flush_backlog(sk, prot, len, to_decrypt,
2158 /* TLS 1.3 may have updated the length by more than overhead */
2159 rxm = strp_msg(darg.skb);
2160 chunk = rxm->full_len;
2161 tls_rx_rec_done(ctx);
2164 bool partially_consumed = chunk > len;
2165 struct sk_buff *skb = darg.skb;
2167 DEBUG_NET_WARN_ON_ONCE(darg.skb == ctx->strp.anchor);
2170 /* TLS 1.2-only, to_decrypt must be text len */
2171 chunk = min_t(int, to_decrypt, len);
2172 async_copy_bytes += chunk;
2176 __skb_queue_tail(&ctx->rx_list, skb);
2180 if (bpf_strp_enabled) {
2182 err = sk_psock_tls_strp_read(psock, skb);
2183 if (err != __SK_PASS) {
2184 rxm->offset = rxm->offset + rxm->full_len;
2186 if (err == __SK_DROP)
2192 if (partially_consumed)
2195 err = skb_copy_datagram_msg(skb, rxm->offset,
2198 goto put_on_rx_list_err;
2201 goto put_on_rx_list;
2203 if (partially_consumed) {
2204 rxm->offset += chunk;
2205 rxm->full_len -= chunk;
2206 goto put_on_rx_list;
2215 /* Return full control message to userspace before trying
2216 * to parse another message type
2218 msg->msg_flags |= MSG_EOR;
2219 if (control != TLS_RECORD_TYPE_DATA)
2227 /* Wait for all previously submitted records to be decrypted */
2228 spin_lock_bh(&ctx->decrypt_compl_lock);
2229 reinit_completion(&ctx->async_wait.completion);
2230 pending = atomic_read(&ctx->decrypt_pending);
2231 spin_unlock_bh(&ctx->decrypt_compl_lock);
2234 ret = crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
2235 __skb_queue_purge(&ctx->async_hold);
2238 if (err >= 0 || err == -EINPROGRESS)
2244 /* Drain records from the rx_list & copy if required */
2245 if (is_peek || is_kvec)
2246 err = process_rx_list(ctx, msg, &control, copied,
2247 decrypted, is_peek);
2249 err = process_rx_list(ctx, msg, &control, 0,
2250 async_copy_bytes, is_peek);
2251 decrypted += max(err, 0);
2254 copied += decrypted;
2257 tls_rx_reader_unlock(sk, ctx);
2259 sk_psock_put(sk, psock);
2260 return copied ? : err;
2263 ssize_t tls_sw_splice_read(struct socket *sock, loff_t *ppos,
2264 struct pipe_inode_info *pipe,
2265 size_t len, unsigned int flags)
2267 struct tls_context *tls_ctx = tls_get_ctx(sock->sk);
2268 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2269 struct strp_msg *rxm = NULL;
2270 struct sock *sk = sock->sk;
2271 struct tls_msg *tlm;
2272 struct sk_buff *skb;
2277 err = tls_rx_reader_lock(sk, ctx, flags & SPLICE_F_NONBLOCK);
2281 if (!skb_queue_empty(&ctx->rx_list)) {
2282 skb = __skb_dequeue(&ctx->rx_list);
2284 struct tls_decrypt_arg darg;
2286 err = tls_rx_rec_wait(sk, NULL, flags & SPLICE_F_NONBLOCK,
2289 goto splice_read_end;
2291 memset(&darg.inargs, 0, sizeof(darg.inargs));
2293 err = tls_rx_one_record(sk, NULL, &darg);
2295 tls_err_abort(sk, -EBADMSG);
2296 goto splice_read_end;
2299 tls_rx_rec_done(ctx);
2303 rxm = strp_msg(skb);
2306 /* splice does not support reading control messages */
2307 if (tlm->control != TLS_RECORD_TYPE_DATA) {
2309 goto splice_requeue;
2312 chunk = min_t(unsigned int, rxm->full_len, len);
2313 copied = skb_splice_bits(skb, sk, rxm->offset, pipe, chunk, flags);
2315 goto splice_requeue;
2317 if (chunk < rxm->full_len) {
2319 rxm->full_len -= len;
2320 goto splice_requeue;
2326 tls_rx_reader_unlock(sk, ctx);
2327 return copied ? : err;
2330 __skb_queue_head(&ctx->rx_list, skb);
2331 goto splice_read_end;
2334 bool tls_sw_sock_is_readable(struct sock *sk)
2336 struct tls_context *tls_ctx = tls_get_ctx(sk);
2337 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2338 bool ingress_empty = true;
2339 struct sk_psock *psock;
2342 psock = sk_psock(sk);
2344 ingress_empty = list_empty(&psock->ingress_msg);
2347 return !ingress_empty || tls_strp_msg_ready(ctx) ||
2348 !skb_queue_empty(&ctx->rx_list);
2351 int tls_rx_msg_size(struct tls_strparser *strp, struct sk_buff *skb)
2353 struct tls_context *tls_ctx = tls_get_ctx(strp->sk);
2354 struct tls_prot_info *prot = &tls_ctx->prot_info;
2355 char header[TLS_HEADER_SIZE + MAX_IV_SIZE];
2356 size_t cipher_overhead;
2357 size_t data_len = 0;
2360 /* Verify that we have a full TLS header, or wait for more data */
2361 if (strp->stm.offset + prot->prepend_size > skb->len)
2364 /* Sanity-check size of on-stack buffer. */
2365 if (WARN_ON(prot->prepend_size > sizeof(header))) {
2370 /* Linearize header to local buffer */
2371 ret = skb_copy_bits(skb, strp->stm.offset, header, prot->prepend_size);
2375 strp->mark = header[0];
2377 data_len = ((header[4] & 0xFF) | (header[3] << 8));
2379 cipher_overhead = prot->tag_size;
2380 if (prot->version != TLS_1_3_VERSION &&
2381 prot->cipher_type != TLS_CIPHER_CHACHA20_POLY1305)
2382 cipher_overhead += prot->iv_size;
2384 if (data_len > TLS_MAX_PAYLOAD_SIZE + cipher_overhead +
2389 if (data_len < cipher_overhead) {
2394 /* Note that both TLS1.3 and TLS1.2 use TLS_1_2 version here */
2395 if (header[1] != TLS_1_2_VERSION_MINOR ||
2396 header[2] != TLS_1_2_VERSION_MAJOR) {
2401 tls_device_rx_resync_new_rec(strp->sk, data_len + TLS_HEADER_SIZE,
2402 TCP_SKB_CB(skb)->seq + strp->stm.offset);
2403 return data_len + TLS_HEADER_SIZE;
2406 tls_err_abort(strp->sk, ret);
2411 void tls_rx_msg_ready(struct tls_strparser *strp)
2413 struct tls_sw_context_rx *ctx;
2415 ctx = container_of(strp, struct tls_sw_context_rx, strp);
2416 ctx->saved_data_ready(strp->sk);
2419 static void tls_data_ready(struct sock *sk)
2421 struct tls_context *tls_ctx = tls_get_ctx(sk);
2422 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2423 struct sk_psock *psock;
2426 trace_sk_data_ready(sk);
2428 alloc_save = sk->sk_allocation;
2429 sk->sk_allocation = GFP_ATOMIC;
2430 tls_strp_data_ready(&ctx->strp);
2431 sk->sk_allocation = alloc_save;
2433 psock = sk_psock_get(sk);
2435 if (!list_empty(&psock->ingress_msg))
2436 ctx->saved_data_ready(sk);
2437 sk_psock_put(sk, psock);
2441 void tls_sw_cancel_work_tx(struct tls_context *tls_ctx)
2443 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2445 set_bit(BIT_TX_CLOSING, &ctx->tx_bitmask);
2446 set_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask);
2447 cancel_delayed_work_sync(&ctx->tx_work.work);
2450 void tls_sw_release_resources_tx(struct sock *sk)
2452 struct tls_context *tls_ctx = tls_get_ctx(sk);
2453 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2454 struct tls_rec *rec, *tmp;
2457 /* Wait for any pending async encryptions to complete */
2458 spin_lock_bh(&ctx->encrypt_compl_lock);
2459 ctx->async_notify = true;
2460 pending = atomic_read(&ctx->encrypt_pending);
2461 spin_unlock_bh(&ctx->encrypt_compl_lock);
2464 crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
2466 tls_tx_records(sk, -1);
2468 /* Free up un-sent records in tx_list. First, free
2469 * the partially sent record if any at head of tx_list.
2471 if (tls_ctx->partially_sent_record) {
2472 tls_free_partial_record(sk, tls_ctx);
2473 rec = list_first_entry(&ctx->tx_list,
2474 struct tls_rec, list);
2475 list_del(&rec->list);
2476 sk_msg_free(sk, &rec->msg_plaintext);
2480 list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
2481 list_del(&rec->list);
2482 sk_msg_free(sk, &rec->msg_encrypted);
2483 sk_msg_free(sk, &rec->msg_plaintext);
2487 crypto_free_aead(ctx->aead_send);
2488 tls_free_open_rec(sk);
2491 void tls_sw_free_ctx_tx(struct tls_context *tls_ctx)
2493 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2498 void tls_sw_release_resources_rx(struct sock *sk)
2500 struct tls_context *tls_ctx = tls_get_ctx(sk);
2501 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2503 kfree(tls_ctx->rx.rec_seq);
2504 kfree(tls_ctx->rx.iv);
2506 if (ctx->aead_recv) {
2507 __skb_queue_purge(&ctx->rx_list);
2508 crypto_free_aead(ctx->aead_recv);
2509 tls_strp_stop(&ctx->strp);
2510 /* If tls_sw_strparser_arm() was not called (cleanup paths)
2511 * we still want to tls_strp_stop(), but sk->sk_data_ready was
2514 if (ctx->saved_data_ready) {
2515 write_lock_bh(&sk->sk_callback_lock);
2516 sk->sk_data_ready = ctx->saved_data_ready;
2517 write_unlock_bh(&sk->sk_callback_lock);
2522 void tls_sw_strparser_done(struct tls_context *tls_ctx)
2524 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2526 tls_strp_done(&ctx->strp);
2529 void tls_sw_free_ctx_rx(struct tls_context *tls_ctx)
2531 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2536 void tls_sw_free_resources_rx(struct sock *sk)
2538 struct tls_context *tls_ctx = tls_get_ctx(sk);
2540 tls_sw_release_resources_rx(sk);
2541 tls_sw_free_ctx_rx(tls_ctx);
2544 /* The work handler to transmitt the encrypted records in tx_list */
2545 static void tx_work_handler(struct work_struct *work)
2547 struct delayed_work *delayed_work = to_delayed_work(work);
2548 struct tx_work *tx_work = container_of(delayed_work,
2549 struct tx_work, work);
2550 struct sock *sk = tx_work->sk;
2551 struct tls_context *tls_ctx = tls_get_ctx(sk);
2552 struct tls_sw_context_tx *ctx;
2554 if (unlikely(!tls_ctx))
2557 ctx = tls_sw_ctx_tx(tls_ctx);
2558 if (test_bit(BIT_TX_CLOSING, &ctx->tx_bitmask))
2561 if (!test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask))
2564 if (mutex_trylock(&tls_ctx->tx_lock)) {
2566 tls_tx_records(sk, -1);
2568 mutex_unlock(&tls_ctx->tx_lock);
2569 } else if (!test_and_set_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
2570 /* Someone is holding the tx_lock, they will likely run Tx
2571 * and cancel the work on their way out of the lock section.
2572 * Schedule a long delay just in case.
2574 schedule_delayed_work(&ctx->tx_work.work, msecs_to_jiffies(10));
2578 static bool tls_is_tx_ready(struct tls_sw_context_tx *ctx)
2580 struct tls_rec *rec;
2582 rec = list_first_entry_or_null(&ctx->tx_list, struct tls_rec, list);
2586 return READ_ONCE(rec->tx_ready);
2589 void tls_sw_write_space(struct sock *sk, struct tls_context *ctx)
2591 struct tls_sw_context_tx *tx_ctx = tls_sw_ctx_tx(ctx);
2593 /* Schedule the transmission if tx list is ready */
2594 if (tls_is_tx_ready(tx_ctx) &&
2595 !test_and_set_bit(BIT_TX_SCHEDULED, &tx_ctx->tx_bitmask))
2596 schedule_delayed_work(&tx_ctx->tx_work.work, 0);
2599 void tls_sw_strparser_arm(struct sock *sk, struct tls_context *tls_ctx)
2601 struct tls_sw_context_rx *rx_ctx = tls_sw_ctx_rx(tls_ctx);
2603 write_lock_bh(&sk->sk_callback_lock);
2604 rx_ctx->saved_data_ready = sk->sk_data_ready;
2605 sk->sk_data_ready = tls_data_ready;
2606 write_unlock_bh(&sk->sk_callback_lock);
2609 void tls_update_rx_zc_capable(struct tls_context *tls_ctx)
2611 struct tls_sw_context_rx *rx_ctx = tls_sw_ctx_rx(tls_ctx);
2613 rx_ctx->zc_capable = tls_ctx->rx_no_pad ||
2614 tls_ctx->prot_info.version != TLS_1_3_VERSION;
2617 int tls_set_sw_offload(struct sock *sk, struct tls_context *ctx, int tx)
2619 struct tls_context *tls_ctx = tls_get_ctx(sk);
2620 struct tls_prot_info *prot = &tls_ctx->prot_info;
2621 struct tls_crypto_info *crypto_info;
2622 struct tls_sw_context_tx *sw_ctx_tx = NULL;
2623 struct tls_sw_context_rx *sw_ctx_rx = NULL;
2624 struct cipher_context *cctx;
2625 struct crypto_aead **aead;
2626 u16 nonce_size, tag_size, iv_size, rec_seq_size, salt_size;
2627 struct crypto_tfm *tfm;
2628 char *iv, *rec_seq, *key, *salt, *cipher_name;
2638 if (!ctx->priv_ctx_tx) {
2639 sw_ctx_tx = kzalloc(sizeof(*sw_ctx_tx), GFP_KERNEL);
2644 ctx->priv_ctx_tx = sw_ctx_tx;
2647 (struct tls_sw_context_tx *)ctx->priv_ctx_tx;
2650 if (!ctx->priv_ctx_rx) {
2651 sw_ctx_rx = kzalloc(sizeof(*sw_ctx_rx), GFP_KERNEL);
2656 ctx->priv_ctx_rx = sw_ctx_rx;
2659 (struct tls_sw_context_rx *)ctx->priv_ctx_rx;
2664 crypto_init_wait(&sw_ctx_tx->async_wait);
2665 spin_lock_init(&sw_ctx_tx->encrypt_compl_lock);
2666 crypto_info = &ctx->crypto_send.info;
2668 aead = &sw_ctx_tx->aead_send;
2669 INIT_LIST_HEAD(&sw_ctx_tx->tx_list);
2670 INIT_DELAYED_WORK(&sw_ctx_tx->tx_work.work, tx_work_handler);
2671 sw_ctx_tx->tx_work.sk = sk;
2673 crypto_init_wait(&sw_ctx_rx->async_wait);
2674 spin_lock_init(&sw_ctx_rx->decrypt_compl_lock);
2675 init_waitqueue_head(&sw_ctx_rx->wq);
2676 crypto_info = &ctx->crypto_recv.info;
2678 skb_queue_head_init(&sw_ctx_rx->rx_list);
2679 skb_queue_head_init(&sw_ctx_rx->async_hold);
2680 aead = &sw_ctx_rx->aead_recv;
2683 switch (crypto_info->cipher_type) {
2684 case TLS_CIPHER_AES_GCM_128: {
2685 struct tls12_crypto_info_aes_gcm_128 *gcm_128_info;
2687 gcm_128_info = (void *)crypto_info;
2688 nonce_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
2689 tag_size = TLS_CIPHER_AES_GCM_128_TAG_SIZE;
2690 iv_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
2691 iv = gcm_128_info->iv;
2692 rec_seq_size = TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE;
2693 rec_seq = gcm_128_info->rec_seq;
2694 keysize = TLS_CIPHER_AES_GCM_128_KEY_SIZE;
2695 key = gcm_128_info->key;
2696 salt = gcm_128_info->salt;
2697 salt_size = TLS_CIPHER_AES_GCM_128_SALT_SIZE;
2698 cipher_name = "gcm(aes)";
2701 case TLS_CIPHER_AES_GCM_256: {
2702 struct tls12_crypto_info_aes_gcm_256 *gcm_256_info;
2704 gcm_256_info = (void *)crypto_info;
2705 nonce_size = TLS_CIPHER_AES_GCM_256_IV_SIZE;
2706 tag_size = TLS_CIPHER_AES_GCM_256_TAG_SIZE;
2707 iv_size = TLS_CIPHER_AES_GCM_256_IV_SIZE;
2708 iv = gcm_256_info->iv;
2709 rec_seq_size = TLS_CIPHER_AES_GCM_256_REC_SEQ_SIZE;
2710 rec_seq = gcm_256_info->rec_seq;
2711 keysize = TLS_CIPHER_AES_GCM_256_KEY_SIZE;
2712 key = gcm_256_info->key;
2713 salt = gcm_256_info->salt;
2714 salt_size = TLS_CIPHER_AES_GCM_256_SALT_SIZE;
2715 cipher_name = "gcm(aes)";
2718 case TLS_CIPHER_AES_CCM_128: {
2719 struct tls12_crypto_info_aes_ccm_128 *ccm_128_info;
2721 ccm_128_info = (void *)crypto_info;
2722 nonce_size = TLS_CIPHER_AES_CCM_128_IV_SIZE;
2723 tag_size = TLS_CIPHER_AES_CCM_128_TAG_SIZE;
2724 iv_size = TLS_CIPHER_AES_CCM_128_IV_SIZE;
2725 iv = ccm_128_info->iv;
2726 rec_seq_size = TLS_CIPHER_AES_CCM_128_REC_SEQ_SIZE;
2727 rec_seq = ccm_128_info->rec_seq;
2728 keysize = TLS_CIPHER_AES_CCM_128_KEY_SIZE;
2729 key = ccm_128_info->key;
2730 salt = ccm_128_info->salt;
2731 salt_size = TLS_CIPHER_AES_CCM_128_SALT_SIZE;
2732 cipher_name = "ccm(aes)";
2735 case TLS_CIPHER_CHACHA20_POLY1305: {
2736 struct tls12_crypto_info_chacha20_poly1305 *chacha20_poly1305_info;
2738 chacha20_poly1305_info = (void *)crypto_info;
2740 tag_size = TLS_CIPHER_CHACHA20_POLY1305_TAG_SIZE;
2741 iv_size = TLS_CIPHER_CHACHA20_POLY1305_IV_SIZE;
2742 iv = chacha20_poly1305_info->iv;
2743 rec_seq_size = TLS_CIPHER_CHACHA20_POLY1305_REC_SEQ_SIZE;
2744 rec_seq = chacha20_poly1305_info->rec_seq;
2745 keysize = TLS_CIPHER_CHACHA20_POLY1305_KEY_SIZE;
2746 key = chacha20_poly1305_info->key;
2747 salt = chacha20_poly1305_info->salt;
2748 salt_size = TLS_CIPHER_CHACHA20_POLY1305_SALT_SIZE;
2749 cipher_name = "rfc7539(chacha20,poly1305)";
2752 case TLS_CIPHER_SM4_GCM: {
2753 struct tls12_crypto_info_sm4_gcm *sm4_gcm_info;
2755 sm4_gcm_info = (void *)crypto_info;
2756 nonce_size = TLS_CIPHER_SM4_GCM_IV_SIZE;
2757 tag_size = TLS_CIPHER_SM4_GCM_TAG_SIZE;
2758 iv_size = TLS_CIPHER_SM4_GCM_IV_SIZE;
2759 iv = sm4_gcm_info->iv;
2760 rec_seq_size = TLS_CIPHER_SM4_GCM_REC_SEQ_SIZE;
2761 rec_seq = sm4_gcm_info->rec_seq;
2762 keysize = TLS_CIPHER_SM4_GCM_KEY_SIZE;
2763 key = sm4_gcm_info->key;
2764 salt = sm4_gcm_info->salt;
2765 salt_size = TLS_CIPHER_SM4_GCM_SALT_SIZE;
2766 cipher_name = "gcm(sm4)";
2769 case TLS_CIPHER_SM4_CCM: {
2770 struct tls12_crypto_info_sm4_ccm *sm4_ccm_info;
2772 sm4_ccm_info = (void *)crypto_info;
2773 nonce_size = TLS_CIPHER_SM4_CCM_IV_SIZE;
2774 tag_size = TLS_CIPHER_SM4_CCM_TAG_SIZE;
2775 iv_size = TLS_CIPHER_SM4_CCM_IV_SIZE;
2776 iv = sm4_ccm_info->iv;
2777 rec_seq_size = TLS_CIPHER_SM4_CCM_REC_SEQ_SIZE;
2778 rec_seq = sm4_ccm_info->rec_seq;
2779 keysize = TLS_CIPHER_SM4_CCM_KEY_SIZE;
2780 key = sm4_ccm_info->key;
2781 salt = sm4_ccm_info->salt;
2782 salt_size = TLS_CIPHER_SM4_CCM_SALT_SIZE;
2783 cipher_name = "ccm(sm4)";
2786 case TLS_CIPHER_ARIA_GCM_128: {
2787 struct tls12_crypto_info_aria_gcm_128 *aria_gcm_128_info;
2789 aria_gcm_128_info = (void *)crypto_info;
2790 nonce_size = TLS_CIPHER_ARIA_GCM_128_IV_SIZE;
2791 tag_size = TLS_CIPHER_ARIA_GCM_128_TAG_SIZE;
2792 iv_size = TLS_CIPHER_ARIA_GCM_128_IV_SIZE;
2793 iv = aria_gcm_128_info->iv;
2794 rec_seq_size = TLS_CIPHER_ARIA_GCM_128_REC_SEQ_SIZE;
2795 rec_seq = aria_gcm_128_info->rec_seq;
2796 keysize = TLS_CIPHER_ARIA_GCM_128_KEY_SIZE;
2797 key = aria_gcm_128_info->key;
2798 salt = aria_gcm_128_info->salt;
2799 salt_size = TLS_CIPHER_ARIA_GCM_128_SALT_SIZE;
2800 cipher_name = "gcm(aria)";
2803 case TLS_CIPHER_ARIA_GCM_256: {
2804 struct tls12_crypto_info_aria_gcm_256 *gcm_256_info;
2806 gcm_256_info = (void *)crypto_info;
2807 nonce_size = TLS_CIPHER_ARIA_GCM_256_IV_SIZE;
2808 tag_size = TLS_CIPHER_ARIA_GCM_256_TAG_SIZE;
2809 iv_size = TLS_CIPHER_ARIA_GCM_256_IV_SIZE;
2810 iv = gcm_256_info->iv;
2811 rec_seq_size = TLS_CIPHER_ARIA_GCM_256_REC_SEQ_SIZE;
2812 rec_seq = gcm_256_info->rec_seq;
2813 keysize = TLS_CIPHER_ARIA_GCM_256_KEY_SIZE;
2814 key = gcm_256_info->key;
2815 salt = gcm_256_info->salt;
2816 salt_size = TLS_CIPHER_ARIA_GCM_256_SALT_SIZE;
2817 cipher_name = "gcm(aria)";
2825 if (crypto_info->version == TLS_1_3_VERSION) {
2827 prot->aad_size = TLS_HEADER_SIZE;
2828 prot->tail_size = 1;
2830 prot->aad_size = TLS_AAD_SPACE_SIZE;
2831 prot->tail_size = 0;
2834 /* Sanity-check the sizes for stack allocations. */
2835 if (iv_size > MAX_IV_SIZE || nonce_size > MAX_IV_SIZE ||
2836 rec_seq_size > TLS_MAX_REC_SEQ_SIZE || tag_size != TLS_TAG_SIZE ||
2837 prot->aad_size > TLS_MAX_AAD_SIZE) {
2842 prot->version = crypto_info->version;
2843 prot->cipher_type = crypto_info->cipher_type;
2844 prot->prepend_size = TLS_HEADER_SIZE + nonce_size;
2845 prot->tag_size = tag_size;
2846 prot->overhead_size = prot->prepend_size +
2847 prot->tag_size + prot->tail_size;
2848 prot->iv_size = iv_size;
2849 prot->salt_size = salt_size;
2850 cctx->iv = kmalloc(iv_size + salt_size, GFP_KERNEL);
2855 /* Note: 128 & 256 bit salt are the same size */
2856 prot->rec_seq_size = rec_seq_size;
2857 memcpy(cctx->iv, salt, salt_size);
2858 memcpy(cctx->iv + salt_size, iv, iv_size);
2859 cctx->rec_seq = kmemdup(rec_seq, rec_seq_size, GFP_KERNEL);
2860 if (!cctx->rec_seq) {
2866 *aead = crypto_alloc_aead(cipher_name, 0, 0);
2867 if (IS_ERR(*aead)) {
2868 rc = PTR_ERR(*aead);
2874 ctx->push_pending_record = tls_sw_push_pending_record;
2876 rc = crypto_aead_setkey(*aead, key, keysize);
2881 rc = crypto_aead_setauthsize(*aead, prot->tag_size);
2886 tfm = crypto_aead_tfm(sw_ctx_rx->aead_recv);
2888 tls_update_rx_zc_capable(ctx);
2889 sw_ctx_rx->async_capable =
2890 crypto_info->version != TLS_1_3_VERSION &&
2891 !!(tfm->__crt_alg->cra_flags & CRYPTO_ALG_ASYNC);
2893 rc = tls_strp_init(&sw_ctx_rx->strp, sk);
2901 crypto_free_aead(*aead);
2904 kfree(cctx->rec_seq);
2905 cctx->rec_seq = NULL;
2911 kfree(ctx->priv_ctx_tx);
2912 ctx->priv_ctx_tx = NULL;
2914 kfree(ctx->priv_ctx_rx);
2915 ctx->priv_ctx_rx = NULL;