2 * Copyright (c) 2016-2017, Mellanox Technologies. 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/sched/signal.h>
39 #include <linux/module.h>
40 #include <crypto/aead.h>
42 #include <net/strparser.h>
45 static int __skb_nsg(struct sk_buff *skb, int offset, int len,
46 unsigned int recursion_level)
48 int start = skb_headlen(skb);
49 int i, chunk = start - offset;
50 struct sk_buff *frag_iter;
53 if (unlikely(recursion_level >= 24))
66 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
69 WARN_ON(start > offset + len);
71 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
85 if (unlikely(skb_has_frag_list(skb))) {
86 skb_walk_frags(skb, frag_iter) {
89 WARN_ON(start > offset + len);
91 end = start + frag_iter->len;
96 ret = __skb_nsg(frag_iter, offset - start, chunk,
98 if (unlikely(ret < 0))
113 /* Return the number of scatterlist elements required to completely map the
114 * skb, or -EMSGSIZE if the recursion depth is exceeded.
116 static int skb_nsg(struct sk_buff *skb, int offset, int len)
118 return __skb_nsg(skb, offset, len, 0);
121 static int padding_length(struct tls_sw_context_rx *ctx,
122 struct tls_context *tls_ctx, struct sk_buff *skb)
124 struct strp_msg *rxm = strp_msg(skb);
127 /* Determine zero-padding length */
128 if (tls_ctx->prot_info.version == TLS_1_3_VERSION) {
129 char content_type = 0;
133 while (content_type == 0) {
134 if (back > rxm->full_len)
136 err = skb_copy_bits(skb,
137 rxm->offset + rxm->full_len - back,
144 ctx->control = content_type;
149 static void tls_decrypt_done(struct crypto_async_request *req, int err)
151 struct aead_request *aead_req = (struct aead_request *)req;
152 struct scatterlist *sgout = aead_req->dst;
153 struct scatterlist *sgin = aead_req->src;
154 struct tls_sw_context_rx *ctx;
155 struct tls_context *tls_ctx;
156 struct tls_prot_info *prot;
157 struct scatterlist *sg;
162 skb = (struct sk_buff *)req->data;
163 tls_ctx = tls_get_ctx(skb->sk);
164 ctx = tls_sw_ctx_rx(tls_ctx);
165 prot = &tls_ctx->prot_info;
167 /* Propagate if there was an err */
169 ctx->async_wait.err = err;
170 tls_err_abort(skb->sk, err);
172 struct strp_msg *rxm = strp_msg(skb);
173 rxm->full_len -= padding_length(ctx, tls_ctx, skb);
174 rxm->offset += prot->prepend_size;
175 rxm->full_len -= prot->overhead_size;
178 /* After using skb->sk to propagate sk through crypto async callback
179 * we need to NULL it again.
184 /* Free the destination pages if skb was not decrypted inplace */
186 /* Skip the first S/G entry as it points to AAD */
187 for_each_sg(sg_next(sgout), sg, UINT_MAX, pages) {
190 put_page(sg_page(sg));
196 pending = atomic_dec_return(&ctx->decrypt_pending);
198 if (!pending && READ_ONCE(ctx->async_notify))
199 complete(&ctx->async_wait.completion);
202 static int tls_do_decryption(struct sock *sk,
204 struct scatterlist *sgin,
205 struct scatterlist *sgout,
208 struct aead_request *aead_req,
211 struct tls_context *tls_ctx = tls_get_ctx(sk);
212 struct tls_prot_info *prot = &tls_ctx->prot_info;
213 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
216 aead_request_set_tfm(aead_req, ctx->aead_recv);
217 aead_request_set_ad(aead_req, prot->aad_size);
218 aead_request_set_crypt(aead_req, sgin, sgout,
219 data_len + prot->tag_size,
223 /* Using skb->sk to push sk through to crypto async callback
224 * handler. This allows propagating errors up to the socket
225 * if needed. It _must_ be cleared in the async handler
226 * before consume_skb is called. We _know_ skb->sk is NULL
227 * because it is a clone from strparser.
230 aead_request_set_callback(aead_req,
231 CRYPTO_TFM_REQ_MAY_BACKLOG,
232 tls_decrypt_done, skb);
233 atomic_inc(&ctx->decrypt_pending);
235 aead_request_set_callback(aead_req,
236 CRYPTO_TFM_REQ_MAY_BACKLOG,
237 crypto_req_done, &ctx->async_wait);
240 ret = crypto_aead_decrypt(aead_req);
241 if (ret == -EINPROGRESS) {
245 ret = crypto_wait_req(ret, &ctx->async_wait);
249 atomic_dec(&ctx->decrypt_pending);
254 static void tls_trim_both_msgs(struct sock *sk, int target_size)
256 struct tls_context *tls_ctx = tls_get_ctx(sk);
257 struct tls_prot_info *prot = &tls_ctx->prot_info;
258 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
259 struct tls_rec *rec = ctx->open_rec;
261 sk_msg_trim(sk, &rec->msg_plaintext, target_size);
263 target_size += prot->overhead_size;
264 sk_msg_trim(sk, &rec->msg_encrypted, target_size);
267 static int tls_alloc_encrypted_msg(struct sock *sk, int len)
269 struct tls_context *tls_ctx = tls_get_ctx(sk);
270 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
271 struct tls_rec *rec = ctx->open_rec;
272 struct sk_msg *msg_en = &rec->msg_encrypted;
274 return sk_msg_alloc(sk, msg_en, len, 0);
277 static int tls_clone_plaintext_msg(struct sock *sk, int required)
279 struct tls_context *tls_ctx = tls_get_ctx(sk);
280 struct tls_prot_info *prot = &tls_ctx->prot_info;
281 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
282 struct tls_rec *rec = ctx->open_rec;
283 struct sk_msg *msg_pl = &rec->msg_plaintext;
284 struct sk_msg *msg_en = &rec->msg_encrypted;
287 /* We add page references worth len bytes from encrypted sg
288 * at the end of plaintext sg. It is guaranteed that msg_en
289 * has enough required room (ensured by caller).
291 len = required - msg_pl->sg.size;
293 /* Skip initial bytes in msg_en's data to be able to use
294 * same offset of both plain and encrypted data.
296 skip = prot->prepend_size + msg_pl->sg.size;
298 return sk_msg_clone(sk, msg_pl, msg_en, skip, len);
301 static struct tls_rec *tls_get_rec(struct sock *sk)
303 struct tls_context *tls_ctx = tls_get_ctx(sk);
304 struct tls_prot_info *prot = &tls_ctx->prot_info;
305 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
306 struct sk_msg *msg_pl, *msg_en;
310 mem_size = sizeof(struct tls_rec) + crypto_aead_reqsize(ctx->aead_send);
312 rec = kzalloc(mem_size, sk->sk_allocation);
316 msg_pl = &rec->msg_plaintext;
317 msg_en = &rec->msg_encrypted;
322 sg_init_table(rec->sg_aead_in, 2);
323 sg_set_buf(&rec->sg_aead_in[0], rec->aad_space, prot->aad_size);
324 sg_unmark_end(&rec->sg_aead_in[1]);
326 sg_init_table(rec->sg_aead_out, 2);
327 sg_set_buf(&rec->sg_aead_out[0], rec->aad_space, prot->aad_size);
328 sg_unmark_end(&rec->sg_aead_out[1]);
333 static void tls_free_rec(struct sock *sk, struct tls_rec *rec)
335 sk_msg_free(sk, &rec->msg_encrypted);
336 sk_msg_free(sk, &rec->msg_plaintext);
340 static void tls_free_open_rec(struct sock *sk)
342 struct tls_context *tls_ctx = tls_get_ctx(sk);
343 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
344 struct tls_rec *rec = ctx->open_rec;
347 tls_free_rec(sk, rec);
348 ctx->open_rec = NULL;
352 int tls_tx_records(struct sock *sk, int flags)
354 struct tls_context *tls_ctx = tls_get_ctx(sk);
355 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
356 struct tls_rec *rec, *tmp;
357 struct sk_msg *msg_en;
358 int tx_flags, rc = 0;
360 if (tls_is_partially_sent_record(tls_ctx)) {
361 rec = list_first_entry(&ctx->tx_list,
362 struct tls_rec, list);
365 tx_flags = rec->tx_flags;
369 rc = tls_push_partial_record(sk, tls_ctx, tx_flags);
373 /* Full record has been transmitted.
374 * Remove the head of tx_list
376 list_del(&rec->list);
377 sk_msg_free(sk, &rec->msg_plaintext);
381 /* Tx all ready records */
382 list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
383 if (READ_ONCE(rec->tx_ready)) {
385 tx_flags = rec->tx_flags;
389 msg_en = &rec->msg_encrypted;
390 rc = tls_push_sg(sk, tls_ctx,
391 &msg_en->sg.data[msg_en->sg.curr],
396 list_del(&rec->list);
397 sk_msg_free(sk, &rec->msg_plaintext);
405 if (rc < 0 && rc != -EAGAIN)
406 tls_err_abort(sk, EBADMSG);
411 static void tls_encrypt_done(struct crypto_async_request *req, int err)
413 struct aead_request *aead_req = (struct aead_request *)req;
414 struct sock *sk = req->data;
415 struct tls_context *tls_ctx = tls_get_ctx(sk);
416 struct tls_prot_info *prot = &tls_ctx->prot_info;
417 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
418 struct scatterlist *sge;
419 struct sk_msg *msg_en;
424 rec = container_of(aead_req, struct tls_rec, aead_req);
425 msg_en = &rec->msg_encrypted;
427 sge = sk_msg_elem(msg_en, msg_en->sg.curr);
428 sge->offset -= prot->prepend_size;
429 sge->length += prot->prepend_size;
431 /* Check if error is previously set on socket */
432 if (err || sk->sk_err) {
435 /* If err is already set on socket, return the same code */
437 ctx->async_wait.err = sk->sk_err;
439 ctx->async_wait.err = err;
440 tls_err_abort(sk, err);
445 struct tls_rec *first_rec;
447 /* Mark the record as ready for transmission */
448 smp_store_mb(rec->tx_ready, true);
450 /* If received record is at head of tx_list, schedule tx */
451 first_rec = list_first_entry(&ctx->tx_list,
452 struct tls_rec, list);
453 if (rec == first_rec)
457 pending = atomic_dec_return(&ctx->encrypt_pending);
459 if (!pending && READ_ONCE(ctx->async_notify))
460 complete(&ctx->async_wait.completion);
465 /* Schedule the transmission */
466 if (!test_and_set_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask))
467 schedule_delayed_work(&ctx->tx_work.work, 1);
470 static int tls_do_encryption(struct sock *sk,
471 struct tls_context *tls_ctx,
472 struct tls_sw_context_tx *ctx,
473 struct aead_request *aead_req,
474 size_t data_len, u32 start)
476 struct tls_prot_info *prot = &tls_ctx->prot_info;
477 struct tls_rec *rec = ctx->open_rec;
478 struct sk_msg *msg_en = &rec->msg_encrypted;
479 struct scatterlist *sge = sk_msg_elem(msg_en, start);
480 int rc, iv_offset = 0;
482 /* For CCM based ciphers, first byte of IV is a constant */
483 if (prot->cipher_type == TLS_CIPHER_AES_CCM_128) {
484 rec->iv_data[0] = TLS_AES_CCM_IV_B0_BYTE;
488 memcpy(&rec->iv_data[iv_offset], tls_ctx->tx.iv,
489 prot->iv_size + prot->salt_size);
491 xor_iv_with_seq(prot->version, rec->iv_data, tls_ctx->tx.rec_seq);
493 sge->offset += prot->prepend_size;
494 sge->length -= prot->prepend_size;
496 msg_en->sg.curr = start;
498 aead_request_set_tfm(aead_req, ctx->aead_send);
499 aead_request_set_ad(aead_req, prot->aad_size);
500 aead_request_set_crypt(aead_req, rec->sg_aead_in,
502 data_len, rec->iv_data);
504 aead_request_set_callback(aead_req, CRYPTO_TFM_REQ_MAY_BACKLOG,
505 tls_encrypt_done, sk);
507 /* Add the record in tx_list */
508 list_add_tail((struct list_head *)&rec->list, &ctx->tx_list);
509 atomic_inc(&ctx->encrypt_pending);
511 rc = crypto_aead_encrypt(aead_req);
512 if (!rc || rc != -EINPROGRESS) {
513 atomic_dec(&ctx->encrypt_pending);
514 sge->offset -= prot->prepend_size;
515 sge->length += prot->prepend_size;
519 WRITE_ONCE(rec->tx_ready, true);
520 } else if (rc != -EINPROGRESS) {
521 list_del(&rec->list);
525 /* Unhook the record from context if encryption is not failure */
526 ctx->open_rec = NULL;
527 tls_advance_record_sn(sk, &tls_ctx->tx, prot->version);
531 static int tls_split_open_record(struct sock *sk, struct tls_rec *from,
532 struct tls_rec **to, struct sk_msg *msg_opl,
533 struct sk_msg *msg_oen, u32 split_point,
534 u32 tx_overhead_size, u32 *orig_end)
536 u32 i, j, bytes = 0, apply = msg_opl->apply_bytes;
537 struct scatterlist *sge, *osge, *nsge;
538 u32 orig_size = msg_opl->sg.size;
539 struct scatterlist tmp = { };
540 struct sk_msg *msg_npl;
544 new = tls_get_rec(sk);
547 ret = sk_msg_alloc(sk, &new->msg_encrypted, msg_opl->sg.size +
548 tx_overhead_size, 0);
550 tls_free_rec(sk, new);
554 *orig_end = msg_opl->sg.end;
555 i = msg_opl->sg.start;
556 sge = sk_msg_elem(msg_opl, i);
557 while (apply && sge->length) {
558 if (sge->length > apply) {
559 u32 len = sge->length - apply;
561 get_page(sg_page(sge));
562 sg_set_page(&tmp, sg_page(sge), len,
563 sge->offset + apply);
568 apply -= sge->length;
569 bytes += sge->length;
572 sk_msg_iter_var_next(i);
573 if (i == msg_opl->sg.end)
575 sge = sk_msg_elem(msg_opl, i);
579 msg_opl->sg.curr = i;
580 msg_opl->sg.copybreak = 0;
581 msg_opl->apply_bytes = 0;
582 msg_opl->sg.size = bytes;
584 msg_npl = &new->msg_plaintext;
585 msg_npl->apply_bytes = apply;
586 msg_npl->sg.size = orig_size - bytes;
588 j = msg_npl->sg.start;
589 nsge = sk_msg_elem(msg_npl, j);
591 memcpy(nsge, &tmp, sizeof(*nsge));
592 sk_msg_iter_var_next(j);
593 nsge = sk_msg_elem(msg_npl, j);
596 osge = sk_msg_elem(msg_opl, i);
597 while (osge->length) {
598 memcpy(nsge, osge, sizeof(*nsge));
600 sk_msg_iter_var_next(i);
601 sk_msg_iter_var_next(j);
604 osge = sk_msg_elem(msg_opl, i);
605 nsge = sk_msg_elem(msg_npl, j);
609 msg_npl->sg.curr = j;
610 msg_npl->sg.copybreak = 0;
616 static void tls_merge_open_record(struct sock *sk, struct tls_rec *to,
617 struct tls_rec *from, u32 orig_end)
619 struct sk_msg *msg_npl = &from->msg_plaintext;
620 struct sk_msg *msg_opl = &to->msg_plaintext;
621 struct scatterlist *osge, *nsge;
625 sk_msg_iter_var_prev(i);
626 j = msg_npl->sg.start;
628 osge = sk_msg_elem(msg_opl, i);
629 nsge = sk_msg_elem(msg_npl, j);
631 if (sg_page(osge) == sg_page(nsge) &&
632 osge->offset + osge->length == nsge->offset) {
633 osge->length += nsge->length;
634 put_page(sg_page(nsge));
637 msg_opl->sg.end = orig_end;
638 msg_opl->sg.curr = orig_end;
639 msg_opl->sg.copybreak = 0;
640 msg_opl->apply_bytes = msg_opl->sg.size + msg_npl->sg.size;
641 msg_opl->sg.size += msg_npl->sg.size;
643 sk_msg_free(sk, &to->msg_encrypted);
644 sk_msg_xfer_full(&to->msg_encrypted, &from->msg_encrypted);
649 static int tls_push_record(struct sock *sk, int flags,
650 unsigned char record_type)
652 struct tls_context *tls_ctx = tls_get_ctx(sk);
653 struct tls_prot_info *prot = &tls_ctx->prot_info;
654 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
655 struct tls_rec *rec = ctx->open_rec, *tmp = NULL;
656 u32 i, split_point, uninitialized_var(orig_end);
657 struct sk_msg *msg_pl, *msg_en;
658 struct aead_request *req;
665 msg_pl = &rec->msg_plaintext;
666 msg_en = &rec->msg_encrypted;
668 split_point = msg_pl->apply_bytes;
669 split = split_point && split_point < msg_pl->sg.size;
671 rc = tls_split_open_record(sk, rec, &tmp, msg_pl, msg_en,
672 split_point, prot->overhead_size,
676 sk_msg_trim(sk, msg_en, msg_pl->sg.size +
677 prot->overhead_size);
680 rec->tx_flags = flags;
681 req = &rec->aead_req;
684 sk_msg_iter_var_prev(i);
686 rec->content_type = record_type;
687 if (prot->version == TLS_1_3_VERSION) {
688 /* Add content type to end of message. No padding added */
689 sg_set_buf(&rec->sg_content_type, &rec->content_type, 1);
690 sg_mark_end(&rec->sg_content_type);
691 sg_chain(msg_pl->sg.data, msg_pl->sg.end + 1,
692 &rec->sg_content_type);
694 sg_mark_end(sk_msg_elem(msg_pl, i));
697 i = msg_pl->sg.start;
698 sg_chain(rec->sg_aead_in, 2, rec->inplace_crypto ?
699 &msg_en->sg.data[i] : &msg_pl->sg.data[i]);
702 sk_msg_iter_var_prev(i);
703 sg_mark_end(sk_msg_elem(msg_en, i));
705 i = msg_en->sg.start;
706 sg_chain(rec->sg_aead_out, 2, &msg_en->sg.data[i]);
708 tls_make_aad(rec->aad_space, msg_pl->sg.size + prot->tail_size,
709 tls_ctx->tx.rec_seq, prot->rec_seq_size,
710 record_type, prot->version);
712 tls_fill_prepend(tls_ctx,
713 page_address(sg_page(&msg_en->sg.data[i])) +
714 msg_en->sg.data[i].offset,
715 msg_pl->sg.size + prot->tail_size,
716 record_type, prot->version);
718 tls_ctx->pending_open_record_frags = false;
720 rc = tls_do_encryption(sk, tls_ctx, ctx, req,
721 msg_pl->sg.size + prot->tail_size, i);
723 if (rc != -EINPROGRESS) {
724 tls_err_abort(sk, EBADMSG);
726 tls_ctx->pending_open_record_frags = true;
727 tls_merge_open_record(sk, rec, tmp, orig_end);
730 ctx->async_capable = 1;
733 msg_pl = &tmp->msg_plaintext;
734 msg_en = &tmp->msg_encrypted;
735 sk_msg_trim(sk, msg_en, msg_pl->sg.size + prot->overhead_size);
736 tls_ctx->pending_open_record_frags = true;
740 return tls_tx_records(sk, flags);
743 static int bpf_exec_tx_verdict(struct sk_msg *msg, struct sock *sk,
744 bool full_record, u8 record_type,
745 size_t *copied, int flags)
747 struct tls_context *tls_ctx = tls_get_ctx(sk);
748 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
749 struct sk_msg msg_redir = { };
750 struct sk_psock *psock;
751 struct sock *sk_redir;
757 policy = !(flags & MSG_SENDPAGE_NOPOLICY);
758 psock = sk_psock_get(sk);
759 if (!psock || !policy)
760 return tls_push_record(sk, flags, record_type);
762 enospc = sk_msg_full(msg);
763 if (psock->eval == __SK_NONE) {
764 delta = msg->sg.size;
765 psock->eval = sk_psock_msg_verdict(sk, psock, msg);
766 if (delta < msg->sg.size)
767 delta -= msg->sg.size;
771 if (msg->cork_bytes && msg->cork_bytes > msg->sg.size &&
772 !enospc && !full_record) {
778 if (msg->apply_bytes && msg->apply_bytes < send)
779 send = msg->apply_bytes;
781 switch (psock->eval) {
783 err = tls_push_record(sk, flags, record_type);
785 *copied -= sk_msg_free(sk, msg);
786 tls_free_open_rec(sk);
791 sk_redir = psock->sk_redir;
792 memcpy(&msg_redir, msg, sizeof(*msg));
793 if (msg->apply_bytes < send)
794 msg->apply_bytes = 0;
796 msg->apply_bytes -= send;
797 sk_msg_return_zero(sk, msg, send);
798 msg->sg.size -= send;
800 err = tcp_bpf_sendmsg_redir(sk_redir, &msg_redir, send, flags);
803 *copied -= sk_msg_free_nocharge(sk, &msg_redir);
806 if (msg->sg.size == 0)
807 tls_free_open_rec(sk);
811 sk_msg_free_partial(sk, msg, send);
812 if (msg->apply_bytes < send)
813 msg->apply_bytes = 0;
815 msg->apply_bytes -= send;
816 if (msg->sg.size == 0)
817 tls_free_open_rec(sk);
818 *copied -= (send + delta);
823 bool reset_eval = !ctx->open_rec;
827 msg = &rec->msg_plaintext;
828 if (!msg->apply_bytes)
832 psock->eval = __SK_NONE;
833 if (psock->sk_redir) {
834 sock_put(psock->sk_redir);
835 psock->sk_redir = NULL;
842 sk_psock_put(sk, psock);
846 static int tls_sw_push_pending_record(struct sock *sk, int flags)
848 struct tls_context *tls_ctx = tls_get_ctx(sk);
849 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
850 struct tls_rec *rec = ctx->open_rec;
851 struct sk_msg *msg_pl;
857 msg_pl = &rec->msg_plaintext;
858 copied = msg_pl->sg.size;
862 return bpf_exec_tx_verdict(msg_pl, sk, true, TLS_RECORD_TYPE_DATA,
866 int tls_sw_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
868 long timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
869 struct tls_context *tls_ctx = tls_get_ctx(sk);
870 struct tls_prot_info *prot = &tls_ctx->prot_info;
871 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
872 bool async_capable = ctx->async_capable;
873 unsigned char record_type = TLS_RECORD_TYPE_DATA;
874 bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
875 bool eor = !(msg->msg_flags & MSG_MORE);
876 size_t try_to_copy, copied = 0;
877 struct sk_msg *msg_pl, *msg_en;
887 if (msg->msg_flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL))
892 /* Wait till there is any pending write on socket */
893 if (unlikely(sk->sk_write_pending)) {
894 ret = wait_on_pending_writer(sk, &timeo);
899 if (unlikely(msg->msg_controllen)) {
900 ret = tls_proccess_cmsg(sk, msg, &record_type);
902 if (ret == -EINPROGRESS)
904 else if (ret != -EAGAIN)
909 while (msg_data_left(msg)) {
918 rec = ctx->open_rec = tls_get_rec(sk);
924 msg_pl = &rec->msg_plaintext;
925 msg_en = &rec->msg_encrypted;
927 orig_size = msg_pl->sg.size;
929 try_to_copy = msg_data_left(msg);
930 record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
931 if (try_to_copy >= record_room) {
932 try_to_copy = record_room;
936 required_size = msg_pl->sg.size + try_to_copy +
939 if (!sk_stream_memory_free(sk))
940 goto wait_for_sndbuf;
943 ret = tls_alloc_encrypted_msg(sk, required_size);
946 goto wait_for_memory;
948 /* Adjust try_to_copy according to the amount that was
949 * actually allocated. The difference is due
950 * to max sg elements limit
952 try_to_copy -= required_size - msg_en->sg.size;
956 if (!is_kvec && (full_record || eor) && !async_capable) {
957 u32 first = msg_pl->sg.end;
959 ret = sk_msg_zerocopy_from_iter(sk, &msg->msg_iter,
960 msg_pl, try_to_copy);
962 goto fallback_to_reg_send;
964 rec->inplace_crypto = 0;
967 copied += try_to_copy;
969 sk_msg_sg_copy_set(msg_pl, first);
970 ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
971 record_type, &copied,
974 if (ret == -EINPROGRESS)
976 else if (ret == -ENOMEM)
977 goto wait_for_memory;
978 else if (ret == -ENOSPC)
980 else if (ret != -EAGAIN)
985 copied -= try_to_copy;
986 sk_msg_sg_copy_clear(msg_pl, first);
987 iov_iter_revert(&msg->msg_iter,
988 msg_pl->sg.size - orig_size);
989 fallback_to_reg_send:
990 sk_msg_trim(sk, msg_pl, orig_size);
993 required_size = msg_pl->sg.size + try_to_copy;
995 ret = tls_clone_plaintext_msg(sk, required_size);
1000 /* Adjust try_to_copy according to the amount that was
1001 * actually allocated. The difference is due
1002 * to max sg elements limit
1004 try_to_copy -= required_size - msg_pl->sg.size;
1006 sk_msg_trim(sk, msg_en,
1007 msg_pl->sg.size + prot->overhead_size);
1011 ret = sk_msg_memcopy_from_iter(sk, &msg->msg_iter,
1012 msg_pl, try_to_copy);
1017 /* Open records defined only if successfully copied, otherwise
1018 * we would trim the sg but not reset the open record frags.
1020 tls_ctx->pending_open_record_frags = true;
1021 copied += try_to_copy;
1022 if (full_record || eor) {
1023 ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1024 record_type, &copied,
1027 if (ret == -EINPROGRESS)
1029 else if (ret == -ENOMEM)
1030 goto wait_for_memory;
1031 else if (ret != -EAGAIN) {
1042 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1044 ret = sk_stream_wait_memory(sk, &timeo);
1047 tls_trim_both_msgs(sk, orig_size);
1051 if (msg_en->sg.size < required_size)
1052 goto alloc_encrypted;
1057 } else if (num_zc) {
1058 /* Wait for pending encryptions to get completed */
1059 smp_store_mb(ctx->async_notify, true);
1061 if (atomic_read(&ctx->encrypt_pending))
1062 crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
1064 reinit_completion(&ctx->async_wait.completion);
1066 WRITE_ONCE(ctx->async_notify, false);
1068 if (ctx->async_wait.err) {
1069 ret = ctx->async_wait.err;
1074 /* Transmit if any encryptions have completed */
1075 if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
1076 cancel_delayed_work(&ctx->tx_work.work);
1077 tls_tx_records(sk, msg->msg_flags);
1081 ret = sk_stream_error(sk, msg->msg_flags, ret);
1084 return copied ? copied : ret;
1087 static int tls_sw_do_sendpage(struct sock *sk, struct page *page,
1088 int offset, size_t size, int flags)
1090 long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
1091 struct tls_context *tls_ctx = tls_get_ctx(sk);
1092 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
1093 struct tls_prot_info *prot = &tls_ctx->prot_info;
1094 unsigned char record_type = TLS_RECORD_TYPE_DATA;
1095 struct sk_msg *msg_pl;
1096 struct tls_rec *rec;
1104 eor = !(flags & (MSG_MORE | MSG_SENDPAGE_NOTLAST));
1105 sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
1107 /* Wait till there is any pending write on socket */
1108 if (unlikely(sk->sk_write_pending)) {
1109 ret = wait_on_pending_writer(sk, &timeo);
1114 /* Call the sk_stream functions to manage the sndbuf mem. */
1116 size_t copy, required_size;
1124 rec = ctx->open_rec;
1126 rec = ctx->open_rec = tls_get_rec(sk);
1132 msg_pl = &rec->msg_plaintext;
1134 full_record = false;
1135 record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
1138 if (copy >= record_room) {
1143 required_size = msg_pl->sg.size + copy + prot->overhead_size;
1145 if (!sk_stream_memory_free(sk))
1146 goto wait_for_sndbuf;
1148 ret = tls_alloc_encrypted_msg(sk, required_size);
1151 goto wait_for_memory;
1153 /* Adjust copy according to the amount that was
1154 * actually allocated. The difference is due
1155 * to max sg elements limit
1157 copy -= required_size - msg_pl->sg.size;
1161 sk_msg_page_add(msg_pl, page, copy, offset);
1162 sk_mem_charge(sk, copy);
1168 tls_ctx->pending_open_record_frags = true;
1169 if (full_record || eor || sk_msg_full(msg_pl)) {
1170 rec->inplace_crypto = 0;
1171 ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1172 record_type, &copied, flags);
1174 if (ret == -EINPROGRESS)
1176 else if (ret == -ENOMEM)
1177 goto wait_for_memory;
1178 else if (ret != -EAGAIN) {
1187 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1189 ret = sk_stream_wait_memory(sk, &timeo);
1191 tls_trim_both_msgs(sk, msg_pl->sg.size);
1199 /* Transmit if any encryptions have completed */
1200 if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
1201 cancel_delayed_work(&ctx->tx_work.work);
1202 tls_tx_records(sk, flags);
1206 ret = sk_stream_error(sk, flags, ret);
1207 return copied ? copied : ret;
1210 int tls_sw_sendpage(struct sock *sk, struct page *page,
1211 int offset, size_t size, int flags)
1215 if (flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
1216 MSG_SENDPAGE_NOTLAST | MSG_SENDPAGE_NOPOLICY))
1220 ret = tls_sw_do_sendpage(sk, page, offset, size, flags);
1225 static struct sk_buff *tls_wait_data(struct sock *sk, struct sk_psock *psock,
1226 int flags, long timeo, int *err)
1228 struct tls_context *tls_ctx = tls_get_ctx(sk);
1229 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1230 struct sk_buff *skb;
1231 DEFINE_WAIT_FUNC(wait, woken_wake_function);
1233 while (!(skb = ctx->recv_pkt) && sk_psock_queue_empty(psock)) {
1235 *err = sock_error(sk);
1239 if (sk->sk_shutdown & RCV_SHUTDOWN)
1242 if (sock_flag(sk, SOCK_DONE))
1245 if ((flags & MSG_DONTWAIT) || !timeo) {
1250 add_wait_queue(sk_sleep(sk), &wait);
1251 sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1252 sk_wait_event(sk, &timeo,
1253 ctx->recv_pkt != skb ||
1254 !sk_psock_queue_empty(psock),
1256 sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1257 remove_wait_queue(sk_sleep(sk), &wait);
1259 /* Handle signals */
1260 if (signal_pending(current)) {
1261 *err = sock_intr_errno(timeo);
1269 static int tls_setup_from_iter(struct sock *sk, struct iov_iter *from,
1270 int length, int *pages_used,
1271 unsigned int *size_used,
1272 struct scatterlist *to,
1275 int rc = 0, i = 0, num_elem = *pages_used, maxpages;
1276 struct page *pages[MAX_SKB_FRAGS];
1277 unsigned int size = *size_used;
1278 ssize_t copied, use;
1281 while (length > 0) {
1283 maxpages = to_max_pages - num_elem;
1284 if (maxpages == 0) {
1288 copied = iov_iter_get_pages(from, pages,
1296 iov_iter_advance(from, copied);
1301 use = min_t(int, copied, PAGE_SIZE - offset);
1303 sg_set_page(&to[num_elem],
1304 pages[i], use, offset);
1305 sg_unmark_end(&to[num_elem]);
1306 /* We do not uncharge memory from this API */
1315 /* Mark the end in the last sg entry if newly added */
1316 if (num_elem > *pages_used)
1317 sg_mark_end(&to[num_elem - 1]);
1320 iov_iter_revert(from, size - *size_used);
1322 *pages_used = num_elem;
1327 /* This function decrypts the input skb into either out_iov or in out_sg
1328 * or in skb buffers itself. The input parameter 'zc' indicates if
1329 * zero-copy mode needs to be tried or not. With zero-copy mode, either
1330 * out_iov or out_sg must be non-NULL. In case both out_iov and out_sg are
1331 * NULL, then the decryption happens inside skb buffers itself, i.e.
1332 * zero-copy gets disabled and 'zc' is updated.
1335 static int decrypt_internal(struct sock *sk, struct sk_buff *skb,
1336 struct iov_iter *out_iov,
1337 struct scatterlist *out_sg,
1338 int *chunk, bool *zc, bool async)
1340 struct tls_context *tls_ctx = tls_get_ctx(sk);
1341 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1342 struct tls_prot_info *prot = &tls_ctx->prot_info;
1343 struct strp_msg *rxm = strp_msg(skb);
1344 int n_sgin, n_sgout, nsg, mem_size, aead_size, err, pages = 0;
1345 struct aead_request *aead_req;
1346 struct sk_buff *unused;
1347 u8 *aad, *iv, *mem = NULL;
1348 struct scatterlist *sgin = NULL;
1349 struct scatterlist *sgout = NULL;
1350 const int data_len = rxm->full_len - prot->overhead_size +
1354 if (*zc && (out_iov || out_sg)) {
1356 n_sgout = iov_iter_npages(out_iov, INT_MAX) + 1;
1358 n_sgout = sg_nents(out_sg);
1359 n_sgin = skb_nsg(skb, rxm->offset + prot->prepend_size,
1360 rxm->full_len - prot->prepend_size);
1364 n_sgin = skb_cow_data(skb, 0, &unused);
1370 /* Increment to accommodate AAD */
1371 n_sgin = n_sgin + 1;
1373 nsg = n_sgin + n_sgout;
1375 aead_size = sizeof(*aead_req) + crypto_aead_reqsize(ctx->aead_recv);
1376 mem_size = aead_size + (nsg * sizeof(struct scatterlist));
1377 mem_size = mem_size + prot->aad_size;
1378 mem_size = mem_size + crypto_aead_ivsize(ctx->aead_recv);
1380 /* Allocate a single block of memory which contains
1381 * aead_req || sgin[] || sgout[] || aad || iv.
1382 * This order achieves correct alignment for aead_req, sgin, sgout.
1384 mem = kmalloc(mem_size, sk->sk_allocation);
1388 /* Segment the allocated memory */
1389 aead_req = (struct aead_request *)mem;
1390 sgin = (struct scatterlist *)(mem + aead_size);
1391 sgout = sgin + n_sgin;
1392 aad = (u8 *)(sgout + n_sgout);
1393 iv = aad + prot->aad_size;
1395 /* For CCM based ciphers, first byte of nonce+iv is always '2' */
1396 if (prot->cipher_type == TLS_CIPHER_AES_CCM_128) {
1402 err = skb_copy_bits(skb, rxm->offset + TLS_HEADER_SIZE,
1403 iv + iv_offset + prot->salt_size,
1409 if (prot->version == TLS_1_3_VERSION)
1410 memcpy(iv + iv_offset, tls_ctx->rx.iv,
1411 crypto_aead_ivsize(ctx->aead_recv));
1413 memcpy(iv + iv_offset, tls_ctx->rx.iv, prot->salt_size);
1415 xor_iv_with_seq(prot->version, iv, tls_ctx->rx.rec_seq);
1418 tls_make_aad(aad, rxm->full_len - prot->overhead_size +
1420 tls_ctx->rx.rec_seq, prot->rec_seq_size,
1421 ctx->control, prot->version);
1424 sg_init_table(sgin, n_sgin);
1425 sg_set_buf(&sgin[0], aad, prot->aad_size);
1426 err = skb_to_sgvec(skb, &sgin[1],
1427 rxm->offset + prot->prepend_size,
1428 rxm->full_len - prot->prepend_size);
1436 sg_init_table(sgout, n_sgout);
1437 sg_set_buf(&sgout[0], aad, prot->aad_size);
1440 err = tls_setup_from_iter(sk, out_iov, data_len,
1441 &pages, chunk, &sgout[1],
1444 goto fallback_to_reg_recv;
1445 } else if (out_sg) {
1446 memcpy(sgout, out_sg, n_sgout * sizeof(*sgout));
1448 goto fallback_to_reg_recv;
1451 fallback_to_reg_recv:
1458 /* Prepare and submit AEAD request */
1459 err = tls_do_decryption(sk, skb, sgin, sgout, iv,
1460 data_len, aead_req, async);
1461 if (err == -EINPROGRESS)
1464 /* Release the pages in case iov was mapped to pages */
1465 for (; pages > 0; pages--)
1466 put_page(sg_page(&sgout[pages]));
1472 static int decrypt_skb_update(struct sock *sk, struct sk_buff *skb,
1473 struct iov_iter *dest, int *chunk, bool *zc,
1476 struct tls_context *tls_ctx = tls_get_ctx(sk);
1477 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1478 struct tls_prot_info *prot = &tls_ctx->prot_info;
1479 int version = prot->version;
1480 struct strp_msg *rxm = strp_msg(skb);
1483 if (!ctx->decrypted) {
1484 #ifdef CONFIG_TLS_DEVICE
1485 err = tls_device_decrypted(sk, skb);
1489 /* Still not decrypted after tls_device */
1490 if (!ctx->decrypted) {
1491 err = decrypt_internal(sk, skb, dest, NULL, chunk, zc,
1494 if (err == -EINPROGRESS)
1495 tls_advance_record_sn(sk, &tls_ctx->rx,
1504 rxm->full_len -= padding_length(ctx, tls_ctx, skb);
1505 rxm->offset += prot->prepend_size;
1506 rxm->full_len -= prot->overhead_size;
1507 tls_advance_record_sn(sk, &tls_ctx->rx, version);
1508 ctx->decrypted = true;
1509 ctx->saved_data_ready(sk);
1517 int decrypt_skb(struct sock *sk, struct sk_buff *skb,
1518 struct scatterlist *sgout)
1523 return decrypt_internal(sk, skb, NULL, sgout, &chunk, &zc, false);
1526 static bool tls_sw_advance_skb(struct sock *sk, struct sk_buff *skb,
1529 struct tls_context *tls_ctx = tls_get_ctx(sk);
1530 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1533 struct strp_msg *rxm = strp_msg(skb);
1535 if (len < rxm->full_len) {
1537 rxm->full_len -= len;
1543 /* Finished with message */
1544 ctx->recv_pkt = NULL;
1545 __strp_unpause(&ctx->strp);
1550 /* This function traverses the rx_list in tls receive context to copies the
1551 * decrypted records into the buffer provided by caller zero copy is not
1552 * true. Further, the records are removed from the rx_list if it is not a peek
1553 * case and the record has been consumed completely.
1555 static int process_rx_list(struct tls_sw_context_rx *ctx,
1564 struct sk_buff *skb = skb_peek(&ctx->rx_list);
1567 struct tls_msg *tlm;
1570 /* Set the record type in 'control' if caller didn't pass it */
1573 ctrl = tlm->control;
1576 while (skip && skb) {
1577 struct strp_msg *rxm = strp_msg(skb);
1580 /* Cannot process a record of different type */
1581 if (ctrl != tlm->control)
1584 if (skip < rxm->full_len)
1587 skip = skip - rxm->full_len;
1588 skb = skb_peek_next(skb, &ctx->rx_list);
1591 while (len && skb) {
1592 struct sk_buff *next_skb;
1593 struct strp_msg *rxm = strp_msg(skb);
1594 int chunk = min_t(unsigned int, rxm->full_len - skip, len);
1598 /* Cannot process a record of different type */
1599 if (ctrl != tlm->control)
1602 /* Set record type if not already done. For a non-data record,
1603 * do not proceed if record type could not be copied.
1606 int cerr = put_cmsg(msg, SOL_TLS, TLS_GET_RECORD_TYPE,
1607 sizeof(ctrl), &ctrl);
1609 if (ctrl != TLS_RECORD_TYPE_DATA) {
1610 if (cerr || msg->msg_flags & MSG_CTRUNC)
1617 if (!zc || (rxm->full_len - skip) > len) {
1618 int err = skb_copy_datagram_msg(skb, rxm->offset + skip,
1625 copied = copied + chunk;
1627 /* Consume the data from record if it is non-peek case*/
1629 rxm->offset = rxm->offset + chunk;
1630 rxm->full_len = rxm->full_len - chunk;
1632 /* Return if there is unconsumed data in the record */
1633 if (rxm->full_len - skip)
1637 /* The remaining skip-bytes must lie in 1st record in rx_list.
1638 * So from the 2nd record, 'skip' should be 0.
1643 msg->msg_flags |= MSG_EOR;
1645 next_skb = skb_peek_next(skb, &ctx->rx_list);
1648 skb_unlink(skb, &ctx->rx_list);
1659 int tls_sw_recvmsg(struct sock *sk,
1666 struct tls_context *tls_ctx = tls_get_ctx(sk);
1667 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1668 struct tls_prot_info *prot = &tls_ctx->prot_info;
1669 struct sk_psock *psock;
1670 unsigned char control = 0;
1671 ssize_t decrypted = 0;
1672 struct strp_msg *rxm;
1673 struct tls_msg *tlm;
1674 struct sk_buff *skb;
1677 int target, err = 0;
1679 bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
1680 bool is_peek = flags & MSG_PEEK;
1685 if (unlikely(flags & MSG_ERRQUEUE))
1686 return sock_recv_errqueue(sk, msg, len, SOL_IP, IP_RECVERR);
1688 psock = sk_psock_get(sk);
1691 /* Process pending decrypted records. It must be non-zero-copy */
1692 err = process_rx_list(ctx, msg, &control, &cmsg, 0, len, false,
1695 tls_err_abort(sk, err);
1703 target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
1704 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1710 bool retain_skb = false;
1717 skb = tls_wait_data(sk, psock, flags, timeo, &err);
1720 int ret = __tcp_bpf_recvmsg(sk, psock,
1732 if (prot->version == TLS_1_3_VERSION)
1735 tlm->control = ctx->control;
1738 rxm = strp_msg(skb);
1740 to_decrypt = rxm->full_len - prot->overhead_size;
1742 if (to_decrypt <= len && !is_kvec && !is_peek &&
1743 ctx->control == TLS_RECORD_TYPE_DATA &&
1744 prot->version != TLS_1_3_VERSION)
1747 /* Do not use async mode if record is non-data */
1748 if (ctx->control == TLS_RECORD_TYPE_DATA)
1749 async_capable = ctx->async_capable;
1751 async_capable = false;
1753 err = decrypt_skb_update(sk, skb, &msg->msg_iter,
1754 &chunk, &zc, async_capable);
1755 if (err < 0 && err != -EINPROGRESS) {
1756 tls_err_abort(sk, EBADMSG);
1760 if (err == -EINPROGRESS) {
1763 } else if (prot->version == TLS_1_3_VERSION) {
1764 tlm->control = ctx->control;
1767 /* If the type of records being processed is not known yet,
1768 * set it to record type just dequeued. If it is already known,
1769 * but does not match the record type just dequeued, go to end.
1770 * We always get record type here since for tls1.2, record type
1771 * is known just after record is dequeued from stream parser.
1772 * For tls1.3, we disable async.
1776 control = tlm->control;
1777 else if (control != tlm->control)
1783 cerr = put_cmsg(msg, SOL_TLS, TLS_GET_RECORD_TYPE,
1784 sizeof(control), &control);
1786 if (control != TLS_RECORD_TYPE_DATA) {
1787 if (cerr || msg->msg_flags & MSG_CTRUNC) {
1795 goto pick_next_record;
1798 if (rxm->full_len > len) {
1802 chunk = rxm->full_len;
1805 err = skb_copy_datagram_msg(skb, rxm->offset,
1811 rxm->offset = rxm->offset + chunk;
1812 rxm->full_len = rxm->full_len - chunk;
1823 /* For async or peek case, queue the current skb */
1824 if (async || is_peek || retain_skb) {
1825 skb_queue_tail(&ctx->rx_list, skb);
1829 if (tls_sw_advance_skb(sk, skb, chunk)) {
1830 /* Return full control message to
1831 * userspace before trying to parse
1832 * another message type
1834 msg->msg_flags |= MSG_EOR;
1835 if (ctx->control != TLS_RECORD_TYPE_DATA)
1841 /* If we have a new message from strparser, continue now. */
1842 if (decrypted >= target && !ctx->recv_pkt)
1848 /* Wait for all previously submitted records to be decrypted */
1849 smp_store_mb(ctx->async_notify, true);
1850 if (atomic_read(&ctx->decrypt_pending)) {
1851 err = crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
1853 /* one of async decrypt failed */
1854 tls_err_abort(sk, err);
1860 reinit_completion(&ctx->async_wait.completion);
1862 WRITE_ONCE(ctx->async_notify, false);
1864 /* Drain records from the rx_list & copy if required */
1865 if (is_peek || is_kvec)
1866 err = process_rx_list(ctx, msg, &control, &cmsg, copied,
1867 decrypted, false, is_peek);
1869 err = process_rx_list(ctx, msg, &control, &cmsg, 0,
1870 decrypted, true, is_peek);
1872 tls_err_abort(sk, err);
1878 copied += decrypted;
1883 sk_psock_put(sk, psock);
1884 return copied ? : err;
1887 ssize_t tls_sw_splice_read(struct socket *sock, loff_t *ppos,
1888 struct pipe_inode_info *pipe,
1889 size_t len, unsigned int flags)
1891 struct tls_context *tls_ctx = tls_get_ctx(sock->sk);
1892 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1893 struct strp_msg *rxm = NULL;
1894 struct sock *sk = sock->sk;
1895 struct sk_buff *skb;
1904 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1906 skb = tls_wait_data(sk, NULL, flags, timeo, &err);
1908 goto splice_read_end;
1910 if (!ctx->decrypted) {
1911 err = decrypt_skb_update(sk, skb, NULL, &chunk, &zc, false);
1913 /* splice does not support reading control messages */
1914 if (ctx->control != TLS_RECORD_TYPE_DATA) {
1916 goto splice_read_end;
1920 tls_err_abort(sk, EBADMSG);
1921 goto splice_read_end;
1923 ctx->decrypted = true;
1925 rxm = strp_msg(skb);
1927 chunk = min_t(unsigned int, rxm->full_len, len);
1928 copied = skb_splice_bits(skb, sk, rxm->offset, pipe, chunk, flags);
1930 goto splice_read_end;
1932 if (likely(!(flags & MSG_PEEK)))
1933 tls_sw_advance_skb(sk, skb, copied);
1937 return copied ? : err;
1940 bool tls_sw_stream_read(const struct sock *sk)
1942 struct tls_context *tls_ctx = tls_get_ctx(sk);
1943 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1944 bool ingress_empty = true;
1945 struct sk_psock *psock;
1948 psock = sk_psock(sk);
1950 ingress_empty = list_empty(&psock->ingress_msg);
1953 return !ingress_empty || ctx->recv_pkt;
1956 static int tls_read_size(struct strparser *strp, struct sk_buff *skb)
1958 struct tls_context *tls_ctx = tls_get_ctx(strp->sk);
1959 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1960 struct tls_prot_info *prot = &tls_ctx->prot_info;
1961 char header[TLS_HEADER_SIZE + MAX_IV_SIZE];
1962 struct strp_msg *rxm = strp_msg(skb);
1963 size_t cipher_overhead;
1964 size_t data_len = 0;
1967 /* Verify that we have a full TLS header, or wait for more data */
1968 if (rxm->offset + prot->prepend_size > skb->len)
1971 /* Sanity-check size of on-stack buffer. */
1972 if (WARN_ON(prot->prepend_size > sizeof(header))) {
1977 /* Linearize header to local buffer */
1978 ret = skb_copy_bits(skb, rxm->offset, header, prot->prepend_size);
1983 ctx->control = header[0];
1985 data_len = ((header[4] & 0xFF) | (header[3] << 8));
1987 cipher_overhead = prot->tag_size;
1988 if (prot->version != TLS_1_3_VERSION)
1989 cipher_overhead += prot->iv_size;
1991 if (data_len > TLS_MAX_PAYLOAD_SIZE + cipher_overhead +
1996 if (data_len < cipher_overhead) {
2001 /* Note that both TLS1.3 and TLS1.2 use TLS_1_2 version here */
2002 if (header[1] != TLS_1_2_VERSION_MINOR ||
2003 header[2] != TLS_1_2_VERSION_MAJOR) {
2007 #ifdef CONFIG_TLS_DEVICE
2008 handle_device_resync(strp->sk, TCP_SKB_CB(skb)->seq + rxm->offset,
2009 *(u64*)tls_ctx->rx.rec_seq);
2011 return data_len + TLS_HEADER_SIZE;
2014 tls_err_abort(strp->sk, ret);
2019 static void tls_queue(struct strparser *strp, struct sk_buff *skb)
2021 struct tls_context *tls_ctx = tls_get_ctx(strp->sk);
2022 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2024 ctx->decrypted = false;
2026 ctx->recv_pkt = skb;
2029 ctx->saved_data_ready(strp->sk);
2032 static void tls_data_ready(struct sock *sk)
2034 struct tls_context *tls_ctx = tls_get_ctx(sk);
2035 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2036 struct sk_psock *psock;
2038 strp_data_ready(&ctx->strp);
2040 psock = sk_psock_get(sk);
2041 if (psock && !list_empty(&psock->ingress_msg)) {
2042 ctx->saved_data_ready(sk);
2043 sk_psock_put(sk, psock);
2047 void tls_sw_free_resources_tx(struct sock *sk)
2049 struct tls_context *tls_ctx = tls_get_ctx(sk);
2050 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2051 struct tls_rec *rec, *tmp;
2053 /* Wait for any pending async encryptions to complete */
2054 smp_store_mb(ctx->async_notify, true);
2055 if (atomic_read(&ctx->encrypt_pending))
2056 crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
2059 cancel_delayed_work_sync(&ctx->tx_work.work);
2062 /* Tx whatever records we can transmit and abandon the rest */
2063 tls_tx_records(sk, -1);
2065 /* Free up un-sent records in tx_list. First, free
2066 * the partially sent record if any at head of tx_list.
2068 if (tls_free_partial_record(sk, tls_ctx)) {
2069 rec = list_first_entry(&ctx->tx_list,
2070 struct tls_rec, list);
2071 list_del(&rec->list);
2072 sk_msg_free(sk, &rec->msg_plaintext);
2076 list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
2077 list_del(&rec->list);
2078 sk_msg_free(sk, &rec->msg_encrypted);
2079 sk_msg_free(sk, &rec->msg_plaintext);
2083 crypto_free_aead(ctx->aead_send);
2084 tls_free_open_rec(sk);
2089 void tls_sw_release_resources_rx(struct sock *sk)
2091 struct tls_context *tls_ctx = tls_get_ctx(sk);
2092 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2094 if (ctx->aead_recv) {
2095 kfree_skb(ctx->recv_pkt);
2096 ctx->recv_pkt = NULL;
2097 skb_queue_purge(&ctx->rx_list);
2098 crypto_free_aead(ctx->aead_recv);
2099 strp_stop(&ctx->strp);
2100 write_lock_bh(&sk->sk_callback_lock);
2101 sk->sk_data_ready = ctx->saved_data_ready;
2102 write_unlock_bh(&sk->sk_callback_lock);
2104 strp_done(&ctx->strp);
2109 void tls_sw_free_resources_rx(struct sock *sk)
2111 struct tls_context *tls_ctx = tls_get_ctx(sk);
2112 struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2114 tls_sw_release_resources_rx(sk);
2119 /* The work handler to transmitt the encrypted records in tx_list */
2120 static void tx_work_handler(struct work_struct *work)
2122 struct delayed_work *delayed_work = to_delayed_work(work);
2123 struct tx_work *tx_work = container_of(delayed_work,
2124 struct tx_work, work);
2125 struct sock *sk = tx_work->sk;
2126 struct tls_context *tls_ctx = tls_get_ctx(sk);
2127 struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2129 if (!test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask))
2133 tls_tx_records(sk, -1);
2137 void tls_sw_write_space(struct sock *sk, struct tls_context *ctx)
2139 struct tls_sw_context_tx *tx_ctx = tls_sw_ctx_tx(ctx);
2141 /* Schedule the transmission if tx list is ready */
2142 if (is_tx_ready(tx_ctx) && !sk->sk_write_pending) {
2143 /* Schedule the transmission */
2144 if (!test_and_set_bit(BIT_TX_SCHEDULED,
2145 &tx_ctx->tx_bitmask))
2146 schedule_delayed_work(&tx_ctx->tx_work.work, 0);
2150 int tls_set_sw_offload(struct sock *sk, struct tls_context *ctx, int tx)
2152 struct tls_context *tls_ctx = tls_get_ctx(sk);
2153 struct tls_prot_info *prot = &tls_ctx->prot_info;
2154 struct tls_crypto_info *crypto_info;
2155 struct tls12_crypto_info_aes_gcm_128 *gcm_128_info;
2156 struct tls12_crypto_info_aes_gcm_256 *gcm_256_info;
2157 struct tls12_crypto_info_aes_ccm_128 *ccm_128_info;
2158 struct tls_sw_context_tx *sw_ctx_tx = NULL;
2159 struct tls_sw_context_rx *sw_ctx_rx = NULL;
2160 struct cipher_context *cctx;
2161 struct crypto_aead **aead;
2162 struct strp_callbacks cb;
2163 u16 nonce_size, tag_size, iv_size, rec_seq_size, salt_size;
2164 struct crypto_tfm *tfm;
2165 char *iv, *rec_seq, *key, *salt, *cipher_name;
2175 if (!ctx->priv_ctx_tx) {
2176 sw_ctx_tx = kzalloc(sizeof(*sw_ctx_tx), GFP_KERNEL);
2181 ctx->priv_ctx_tx = sw_ctx_tx;
2184 (struct tls_sw_context_tx *)ctx->priv_ctx_tx;
2187 if (!ctx->priv_ctx_rx) {
2188 sw_ctx_rx = kzalloc(sizeof(*sw_ctx_rx), GFP_KERNEL);
2193 ctx->priv_ctx_rx = sw_ctx_rx;
2196 (struct tls_sw_context_rx *)ctx->priv_ctx_rx;
2201 crypto_init_wait(&sw_ctx_tx->async_wait);
2202 crypto_info = &ctx->crypto_send.info;
2204 aead = &sw_ctx_tx->aead_send;
2205 INIT_LIST_HEAD(&sw_ctx_tx->tx_list);
2206 INIT_DELAYED_WORK(&sw_ctx_tx->tx_work.work, tx_work_handler);
2207 sw_ctx_tx->tx_work.sk = sk;
2209 crypto_init_wait(&sw_ctx_rx->async_wait);
2210 crypto_info = &ctx->crypto_recv.info;
2212 skb_queue_head_init(&sw_ctx_rx->rx_list);
2213 aead = &sw_ctx_rx->aead_recv;
2216 switch (crypto_info->cipher_type) {
2217 case TLS_CIPHER_AES_GCM_128: {
2218 nonce_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
2219 tag_size = TLS_CIPHER_AES_GCM_128_TAG_SIZE;
2220 iv_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
2221 iv = ((struct tls12_crypto_info_aes_gcm_128 *)crypto_info)->iv;
2222 rec_seq_size = TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE;
2224 ((struct tls12_crypto_info_aes_gcm_128 *)crypto_info)->rec_seq;
2226 (struct tls12_crypto_info_aes_gcm_128 *)crypto_info;
2227 keysize = TLS_CIPHER_AES_GCM_128_KEY_SIZE;
2228 key = gcm_128_info->key;
2229 salt = gcm_128_info->salt;
2230 salt_size = TLS_CIPHER_AES_GCM_128_SALT_SIZE;
2231 cipher_name = "gcm(aes)";
2234 case TLS_CIPHER_AES_GCM_256: {
2235 nonce_size = TLS_CIPHER_AES_GCM_256_IV_SIZE;
2236 tag_size = TLS_CIPHER_AES_GCM_256_TAG_SIZE;
2237 iv_size = TLS_CIPHER_AES_GCM_256_IV_SIZE;
2238 iv = ((struct tls12_crypto_info_aes_gcm_256 *)crypto_info)->iv;
2239 rec_seq_size = TLS_CIPHER_AES_GCM_256_REC_SEQ_SIZE;
2241 ((struct tls12_crypto_info_aes_gcm_256 *)crypto_info)->rec_seq;
2243 (struct tls12_crypto_info_aes_gcm_256 *)crypto_info;
2244 keysize = TLS_CIPHER_AES_GCM_256_KEY_SIZE;
2245 key = gcm_256_info->key;
2246 salt = gcm_256_info->salt;
2247 salt_size = TLS_CIPHER_AES_GCM_256_SALT_SIZE;
2248 cipher_name = "gcm(aes)";
2251 case TLS_CIPHER_AES_CCM_128: {
2252 nonce_size = TLS_CIPHER_AES_CCM_128_IV_SIZE;
2253 tag_size = TLS_CIPHER_AES_CCM_128_TAG_SIZE;
2254 iv_size = TLS_CIPHER_AES_CCM_128_IV_SIZE;
2255 iv = ((struct tls12_crypto_info_aes_ccm_128 *)crypto_info)->iv;
2256 rec_seq_size = TLS_CIPHER_AES_CCM_128_REC_SEQ_SIZE;
2258 ((struct tls12_crypto_info_aes_ccm_128 *)crypto_info)->rec_seq;
2260 (struct tls12_crypto_info_aes_ccm_128 *)crypto_info;
2261 keysize = TLS_CIPHER_AES_CCM_128_KEY_SIZE;
2262 key = ccm_128_info->key;
2263 salt = ccm_128_info->salt;
2264 salt_size = TLS_CIPHER_AES_CCM_128_SALT_SIZE;
2265 cipher_name = "ccm(aes)";
2273 /* Sanity-check the IV size for stack allocations. */
2274 if (iv_size > MAX_IV_SIZE || nonce_size > MAX_IV_SIZE) {
2279 if (crypto_info->version == TLS_1_3_VERSION) {
2281 prot->aad_size = TLS_HEADER_SIZE;
2282 prot->tail_size = 1;
2284 prot->aad_size = TLS_AAD_SPACE_SIZE;
2285 prot->tail_size = 0;
2288 prot->version = crypto_info->version;
2289 prot->cipher_type = crypto_info->cipher_type;
2290 prot->prepend_size = TLS_HEADER_SIZE + nonce_size;
2291 prot->tag_size = tag_size;
2292 prot->overhead_size = prot->prepend_size +
2293 prot->tag_size + prot->tail_size;
2294 prot->iv_size = iv_size;
2295 prot->salt_size = salt_size;
2296 cctx->iv = kmalloc(iv_size + salt_size, GFP_KERNEL);
2301 /* Note: 128 & 256 bit salt are the same size */
2302 prot->rec_seq_size = rec_seq_size;
2303 memcpy(cctx->iv, salt, salt_size);
2304 memcpy(cctx->iv + salt_size, iv, iv_size);
2305 cctx->rec_seq = kmemdup(rec_seq, rec_seq_size, GFP_KERNEL);
2306 if (!cctx->rec_seq) {
2312 *aead = crypto_alloc_aead(cipher_name, 0, 0);
2313 if (IS_ERR(*aead)) {
2314 rc = PTR_ERR(*aead);
2320 ctx->push_pending_record = tls_sw_push_pending_record;
2322 rc = crypto_aead_setkey(*aead, key, keysize);
2327 rc = crypto_aead_setauthsize(*aead, prot->tag_size);
2332 tfm = crypto_aead_tfm(sw_ctx_rx->aead_recv);
2334 if (crypto_info->version == TLS_1_3_VERSION)
2335 sw_ctx_rx->async_capable = false;
2337 sw_ctx_rx->async_capable =
2338 tfm->__crt_alg->cra_flags & CRYPTO_ALG_ASYNC;
2340 /* Set up strparser */
2341 memset(&cb, 0, sizeof(cb));
2342 cb.rcv_msg = tls_queue;
2343 cb.parse_msg = tls_read_size;
2345 strp_init(&sw_ctx_rx->strp, sk, &cb);
2347 write_lock_bh(&sk->sk_callback_lock);
2348 sw_ctx_rx->saved_data_ready = sk->sk_data_ready;
2349 sk->sk_data_ready = tls_data_ready;
2350 write_unlock_bh(&sk->sk_callback_lock);
2352 strp_check_rcv(&sw_ctx_rx->strp);
2358 crypto_free_aead(*aead);
2361 kfree(cctx->rec_seq);
2362 cctx->rec_seq = NULL;
2368 kfree(ctx->priv_ctx_tx);
2369 ctx->priv_ctx_tx = NULL;
2371 kfree(ctx->priv_ctx_rx);
2372 ctx->priv_ctx_rx = NULL;