~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/net/tls/tls_sw.c

Version: ~ [ linux-5.12-rc1 ] ~ [ linux-5.11.2 ] ~ [ linux-5.10.19 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.101 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.177 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.222 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.258 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.258 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.18.140 ] ~ [ linux-3.16.85 ] ~ [ linux-3.14.79 ] ~ [ linux-3.12.74 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 /*
  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
  8  *
  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:
 14  *
 15  *     Redistribution and use in source and binary forms, with or
 16  *     without modification, are permitted provided that the following
 17  *     conditions are met:
 18  *
 19  *      - Redistributions of source code must retain the above
 20  *        copyright notice, this list of conditions and the following
 21  *        disclaimer.
 22  *
 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.
 27  *
 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
 35  * SOFTWARE.
 36  */
 37 
 38 #include <linux/sched/signal.h>
 39 #include <linux/module.h>
 40 #include <crypto/aead.h>
 41 
 42 #include <net/strparser.h>
 43 #include <net/tls.h>
 44 
 45 #define MAX_IV_SIZE     TLS_CIPHER_AES_GCM_128_IV_SIZE
 46 
 47 static int __skb_nsg(struct sk_buff *skb, int offset, int len,
 48                      unsigned int recursion_level)
 49 {
 50         int start = skb_headlen(skb);
 51         int i, chunk = start - offset;
 52         struct sk_buff *frag_iter;
 53         int elt = 0;
 54 
 55         if (unlikely(recursion_level >= 24))
 56                 return -EMSGSIZE;
 57 
 58         if (chunk > 0) {
 59                 if (chunk > len)
 60                         chunk = len;
 61                 elt++;
 62                 len -= chunk;
 63                 if (len == 0)
 64                         return elt;
 65                 offset += chunk;
 66         }
 67 
 68         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
 69                 int end;
 70 
 71                 WARN_ON(start > offset + len);
 72 
 73                 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
 74                 chunk = end - offset;
 75                 if (chunk > 0) {
 76                         if (chunk > len)
 77                                 chunk = len;
 78                         elt++;
 79                         len -= chunk;
 80                         if (len == 0)
 81                                 return elt;
 82                         offset += chunk;
 83                 }
 84                 start = end;
 85         }
 86 
 87         if (unlikely(skb_has_frag_list(skb))) {
 88                 skb_walk_frags(skb, frag_iter) {
 89                         int end, ret;
 90 
 91                         WARN_ON(start > offset + len);
 92 
 93                         end = start + frag_iter->len;
 94                         chunk = end - offset;
 95                         if (chunk > 0) {
 96                                 if (chunk > len)
 97                                         chunk = len;
 98                                 ret = __skb_nsg(frag_iter, offset - start, chunk,
 99                                                 recursion_level + 1);
100                                 if (unlikely(ret < 0))
101                                         return ret;
102                                 elt += ret;
103                                 len -= chunk;
104                                 if (len == 0)
105                                         return elt;
106                                 offset += chunk;
107                         }
108                         start = end;
109                 }
110         }
111         BUG_ON(len);
112         return elt;
113 }
114 
115 /* Return the number of scatterlist elements required to completely map the
116  * skb, or -EMSGSIZE if the recursion depth is exceeded.
117  */
118 static int skb_nsg(struct sk_buff *skb, int offset, int len)
119 {
120         return __skb_nsg(skb, offset, len, 0);
121 }
122 
123 static void tls_decrypt_done(struct crypto_async_request *req, int err)
124 {
125         struct aead_request *aead_req = (struct aead_request *)req;
126         struct scatterlist *sgout = aead_req->dst;
127         struct tls_sw_context_rx *ctx;
128         struct tls_context *tls_ctx;
129         struct scatterlist *sg;
130         struct sk_buff *skb;
131         unsigned int pages;
132         int pending;
133 
134         skb = (struct sk_buff *)req->data;
135         tls_ctx = tls_get_ctx(skb->sk);
136         ctx = tls_sw_ctx_rx(tls_ctx);
137         pending = atomic_dec_return(&ctx->decrypt_pending);
138 
139         /* Propagate if there was an err */
140         if (err) {
141                 ctx->async_wait.err = err;
142                 tls_err_abort(skb->sk, err);
143         }
144 
145         /* After using skb->sk to propagate sk through crypto async callback
146          * we need to NULL it again.
147          */
148         skb->sk = NULL;
149 
150         /* Release the skb, pages and memory allocated for crypto req */
151         kfree_skb(skb);
152 
153         /* Skip the first S/G entry as it points to AAD */
154         for_each_sg(sg_next(sgout), sg, UINT_MAX, pages) {
155                 if (!sg)
156                         break;
157                 put_page(sg_page(sg));
158         }
159 
160         kfree(aead_req);
161 
162         if (!pending && READ_ONCE(ctx->async_notify))
163                 complete(&ctx->async_wait.completion);
164 }
165 
166 static int tls_do_decryption(struct sock *sk,
167                              struct sk_buff *skb,
168                              struct scatterlist *sgin,
169                              struct scatterlist *sgout,
170                              char *iv_recv,
171                              size_t data_len,
172                              struct aead_request *aead_req,
173                              bool async)
174 {
175         struct tls_context *tls_ctx = tls_get_ctx(sk);
176         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
177         int ret;
178 
179         aead_request_set_tfm(aead_req, ctx->aead_recv);
180         aead_request_set_ad(aead_req, TLS_AAD_SPACE_SIZE);
181         aead_request_set_crypt(aead_req, sgin, sgout,
182                                data_len + tls_ctx->rx.tag_size,
183                                (u8 *)iv_recv);
184 
185         if (async) {
186                 /* Using skb->sk to push sk through to crypto async callback
187                  * handler. This allows propagating errors up to the socket
188                  * if needed. It _must_ be cleared in the async handler
189                  * before kfree_skb is called. We _know_ skb->sk is NULL
190                  * because it is a clone from strparser.
191                  */
192                 skb->sk = sk;
193                 aead_request_set_callback(aead_req,
194                                           CRYPTO_TFM_REQ_MAY_BACKLOG,
195                                           tls_decrypt_done, skb);
196                 atomic_inc(&ctx->decrypt_pending);
197         } else {
198                 aead_request_set_callback(aead_req,
199                                           CRYPTO_TFM_REQ_MAY_BACKLOG,
200                                           crypto_req_done, &ctx->async_wait);
201         }
202 
203         ret = crypto_aead_decrypt(aead_req);
204         if (ret == -EINPROGRESS) {
205                 if (async)
206                         return ret;
207 
208                 ret = crypto_wait_req(ret, &ctx->async_wait);
209         }
210 
211         if (async)
212                 atomic_dec(&ctx->decrypt_pending);
213 
214         return ret;
215 }
216 
217 static void tls_trim_both_msgs(struct sock *sk, int target_size)
218 {
219         struct tls_context *tls_ctx = tls_get_ctx(sk);
220         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
221         struct tls_rec *rec = ctx->open_rec;
222 
223         sk_msg_trim(sk, &rec->msg_plaintext, target_size);
224         if (target_size > 0)
225                 target_size += tls_ctx->tx.overhead_size;
226         sk_msg_trim(sk, &rec->msg_encrypted, target_size);
227 }
228 
229 static int tls_alloc_encrypted_msg(struct sock *sk, int len)
230 {
231         struct tls_context *tls_ctx = tls_get_ctx(sk);
232         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
233         struct tls_rec *rec = ctx->open_rec;
234         struct sk_msg *msg_en = &rec->msg_encrypted;
235 
236         return sk_msg_alloc(sk, msg_en, len, 0);
237 }
238 
239 static int tls_clone_plaintext_msg(struct sock *sk, int required)
240 {
241         struct tls_context *tls_ctx = tls_get_ctx(sk);
242         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
243         struct tls_rec *rec = ctx->open_rec;
244         struct sk_msg *msg_pl = &rec->msg_plaintext;
245         struct sk_msg *msg_en = &rec->msg_encrypted;
246         int skip, len;
247 
248         /* We add page references worth len bytes from encrypted sg
249          * at the end of plaintext sg. It is guaranteed that msg_en
250          * has enough required room (ensured by caller).
251          */
252         len = required - msg_pl->sg.size;
253 
254         /* Skip initial bytes in msg_en's data to be able to use
255          * same offset of both plain and encrypted data.
256          */
257         skip = tls_ctx->tx.prepend_size + msg_pl->sg.size;
258 
259         return sk_msg_clone(sk, msg_pl, msg_en, skip, len);
260 }
261 
262 static struct tls_rec *tls_get_rec(struct sock *sk)
263 {
264         struct tls_context *tls_ctx = tls_get_ctx(sk);
265         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
266         struct sk_msg *msg_pl, *msg_en;
267         struct tls_rec *rec;
268         int mem_size;
269 
270         mem_size = sizeof(struct tls_rec) + crypto_aead_reqsize(ctx->aead_send);
271 
272         rec = kzalloc(mem_size, sk->sk_allocation);
273         if (!rec)
274                 return NULL;
275 
276         msg_pl = &rec->msg_plaintext;
277         msg_en = &rec->msg_encrypted;
278 
279         sk_msg_init(msg_pl);
280         sk_msg_init(msg_en);
281 
282         sg_init_table(rec->sg_aead_in, 2);
283         sg_set_buf(&rec->sg_aead_in[0], rec->aad_space,
284                    sizeof(rec->aad_space));
285         sg_unmark_end(&rec->sg_aead_in[1]);
286 
287         sg_init_table(rec->sg_aead_out, 2);
288         sg_set_buf(&rec->sg_aead_out[0], rec->aad_space,
289                    sizeof(rec->aad_space));
290         sg_unmark_end(&rec->sg_aead_out[1]);
291 
292         return rec;
293 }
294 
295 static void tls_free_rec(struct sock *sk, struct tls_rec *rec)
296 {
297         sk_msg_free(sk, &rec->msg_encrypted);
298         sk_msg_free(sk, &rec->msg_plaintext);
299         kfree(rec);
300 }
301 
302 static void tls_free_open_rec(struct sock *sk)
303 {
304         struct tls_context *tls_ctx = tls_get_ctx(sk);
305         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
306         struct tls_rec *rec = ctx->open_rec;
307 
308         if (rec) {
309                 tls_free_rec(sk, rec);
310                 ctx->open_rec = NULL;
311         }
312 }
313 
314 int tls_tx_records(struct sock *sk, int flags)
315 {
316         struct tls_context *tls_ctx = tls_get_ctx(sk);
317         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
318         struct tls_rec *rec, *tmp;
319         struct sk_msg *msg_en;
320         int tx_flags, rc = 0;
321 
322         if (tls_is_partially_sent_record(tls_ctx)) {
323                 rec = list_first_entry(&ctx->tx_list,
324                                        struct tls_rec, list);
325 
326                 if (flags == -1)
327                         tx_flags = rec->tx_flags;
328                 else
329                         tx_flags = flags;
330 
331                 rc = tls_push_partial_record(sk, tls_ctx, tx_flags);
332                 if (rc)
333                         goto tx_err;
334 
335                 /* Full record has been transmitted.
336                  * Remove the head of tx_list
337                  */
338                 list_del(&rec->list);
339                 sk_msg_free(sk, &rec->msg_plaintext);
340                 kfree(rec);
341         }
342 
343         /* Tx all ready records */
344         list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
345                 if (READ_ONCE(rec->tx_ready)) {
346                         if (flags == -1)
347                                 tx_flags = rec->tx_flags;
348                         else
349                                 tx_flags = flags;
350 
351                         msg_en = &rec->msg_encrypted;
352                         rc = tls_push_sg(sk, tls_ctx,
353                                          &msg_en->sg.data[msg_en->sg.curr],
354                                          0, tx_flags);
355                         if (rc)
356                                 goto tx_err;
357 
358                         list_del(&rec->list);
359                         sk_msg_free(sk, &rec->msg_plaintext);
360                         kfree(rec);
361                 } else {
362                         break;
363                 }
364         }
365 
366 tx_err:
367         if (rc < 0 && rc != -EAGAIN)
368                 tls_err_abort(sk, EBADMSG);
369 
370         return rc;
371 }
372 
373 static void tls_encrypt_done(struct crypto_async_request *req, int err)
374 {
375         struct aead_request *aead_req = (struct aead_request *)req;
376         struct sock *sk = req->data;
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 scatterlist *sge;
380         struct sk_msg *msg_en;
381         struct tls_rec *rec;
382         bool ready = false;
383         int pending;
384 
385         rec = container_of(aead_req, struct tls_rec, aead_req);
386         msg_en = &rec->msg_encrypted;
387 
388         sge = sk_msg_elem(msg_en, msg_en->sg.curr);
389         sge->offset -= tls_ctx->tx.prepend_size;
390         sge->length += tls_ctx->tx.prepend_size;
391 
392         /* Check if error is previously set on socket */
393         if (err || sk->sk_err) {
394                 rec = NULL;
395 
396                 /* If err is already set on socket, return the same code */
397                 if (sk->sk_err) {
398                         ctx->async_wait.err = sk->sk_err;
399                 } else {
400                         ctx->async_wait.err = err;
401                         tls_err_abort(sk, err);
402                 }
403         }
404 
405         if (rec) {
406                 struct tls_rec *first_rec;
407 
408                 /* Mark the record as ready for transmission */
409                 smp_store_mb(rec->tx_ready, true);
410 
411                 /* If received record is at head of tx_list, schedule tx */
412                 first_rec = list_first_entry(&ctx->tx_list,
413                                              struct tls_rec, list);
414                 if (rec == first_rec)
415                         ready = true;
416         }
417 
418         pending = atomic_dec_return(&ctx->encrypt_pending);
419 
420         if (!pending && READ_ONCE(ctx->async_notify))
421                 complete(&ctx->async_wait.completion);
422 
423         if (!ready)
424                 return;
425 
426         /* Schedule the transmission */
427         if (!test_and_set_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask))
428                 schedule_delayed_work(&ctx->tx_work.work, 1);
429 }
430 
431 static int tls_do_encryption(struct sock *sk,
432                              struct tls_context *tls_ctx,
433                              struct tls_sw_context_tx *ctx,
434                              struct aead_request *aead_req,
435                              size_t data_len, u32 start)
436 {
437         struct tls_rec *rec = ctx->open_rec;
438         struct sk_msg *msg_en = &rec->msg_encrypted;
439         struct scatterlist *sge = sk_msg_elem(msg_en, start);
440         int rc;
441 
442         memcpy(rec->iv_data, tls_ctx->tx.iv, sizeof(rec->iv_data));
443 
444         sge->offset += tls_ctx->tx.prepend_size;
445         sge->length -= tls_ctx->tx.prepend_size;
446 
447         msg_en->sg.curr = start;
448 
449         aead_request_set_tfm(aead_req, ctx->aead_send);
450         aead_request_set_ad(aead_req, TLS_AAD_SPACE_SIZE);
451         aead_request_set_crypt(aead_req, rec->sg_aead_in,
452                                rec->sg_aead_out,
453                                data_len, rec->iv_data);
454 
455         aead_request_set_callback(aead_req, CRYPTO_TFM_REQ_MAY_BACKLOG,
456                                   tls_encrypt_done, sk);
457 
458         /* Add the record in tx_list */
459         list_add_tail((struct list_head *)&rec->list, &ctx->tx_list);
460         atomic_inc(&ctx->encrypt_pending);
461 
462         rc = crypto_aead_encrypt(aead_req);
463         if (!rc || rc != -EINPROGRESS) {
464                 atomic_dec(&ctx->encrypt_pending);
465                 sge->offset -= tls_ctx->tx.prepend_size;
466                 sge->length += tls_ctx->tx.prepend_size;
467         }
468 
469         if (!rc) {
470                 WRITE_ONCE(rec->tx_ready, true);
471         } else if (rc != -EINPROGRESS) {
472                 list_del(&rec->list);
473                 return rc;
474         }
475 
476         /* Unhook the record from context if encryption is not failure */
477         ctx->open_rec = NULL;
478         tls_advance_record_sn(sk, &tls_ctx->tx);
479         return rc;
480 }
481 
482 static int tls_split_open_record(struct sock *sk, struct tls_rec *from,
483                                  struct tls_rec **to, struct sk_msg *msg_opl,
484                                  struct sk_msg *msg_oen, u32 split_point,
485                                  u32 tx_overhead_size, u32 *orig_end)
486 {
487         u32 i, j, bytes = 0, apply = msg_opl->apply_bytes;
488         struct scatterlist *sge, *osge, *nsge;
489         u32 orig_size = msg_opl->sg.size;
490         struct scatterlist tmp = { };
491         struct sk_msg *msg_npl;
492         struct tls_rec *new;
493         int ret;
494 
495         new = tls_get_rec(sk);
496         if (!new)
497                 return -ENOMEM;
498         ret = sk_msg_alloc(sk, &new->msg_encrypted, msg_opl->sg.size +
499                            tx_overhead_size, 0);
500         if (ret < 0) {
501                 tls_free_rec(sk, new);
502                 return ret;
503         }
504 
505         *orig_end = msg_opl->sg.end;
506         i = msg_opl->sg.start;
507         sge = sk_msg_elem(msg_opl, i);
508         while (apply && sge->length) {
509                 if (sge->length > apply) {
510                         u32 len = sge->length - apply;
511 
512                         get_page(sg_page(sge));
513                         sg_set_page(&tmp, sg_page(sge), len,
514                                     sge->offset + apply);
515                         sge->length = apply;
516                         bytes += apply;
517                         apply = 0;
518                 } else {
519                         apply -= sge->length;
520                         bytes += sge->length;
521                 }
522 
523                 sk_msg_iter_var_next(i);
524                 if (i == msg_opl->sg.end)
525                         break;
526                 sge = sk_msg_elem(msg_opl, i);
527         }
528 
529         msg_opl->sg.end = i;
530         msg_opl->sg.curr = i;
531         msg_opl->sg.copybreak = 0;
532         msg_opl->apply_bytes = 0;
533         msg_opl->sg.size = bytes;
534 
535         msg_npl = &new->msg_plaintext;
536         msg_npl->apply_bytes = apply;
537         msg_npl->sg.size = orig_size - bytes;
538 
539         j = msg_npl->sg.start;
540         nsge = sk_msg_elem(msg_npl, j);
541         if (tmp.length) {
542                 memcpy(nsge, &tmp, sizeof(*nsge));
543                 sk_msg_iter_var_next(j);
544                 nsge = sk_msg_elem(msg_npl, j);
545         }
546 
547         osge = sk_msg_elem(msg_opl, i);
548         while (osge->length) {
549                 memcpy(nsge, osge, sizeof(*nsge));
550                 sg_unmark_end(nsge);
551                 sk_msg_iter_var_next(i);
552                 sk_msg_iter_var_next(j);
553                 if (i == *orig_end)
554                         break;
555                 osge = sk_msg_elem(msg_opl, i);
556                 nsge = sk_msg_elem(msg_npl, j);
557         }
558 
559         msg_npl->sg.end = j;
560         msg_npl->sg.curr = j;
561         msg_npl->sg.copybreak = 0;
562 
563         *to = new;
564         return 0;
565 }
566 
567 static void tls_merge_open_record(struct sock *sk, struct tls_rec *to,
568                                   struct tls_rec *from, u32 orig_end)
569 {
570         struct sk_msg *msg_npl = &from->msg_plaintext;
571         struct sk_msg *msg_opl = &to->msg_plaintext;
572         struct scatterlist *osge, *nsge;
573         u32 i, j;
574 
575         i = msg_opl->sg.end;
576         sk_msg_iter_var_prev(i);
577         j = msg_npl->sg.start;
578 
579         osge = sk_msg_elem(msg_opl, i);
580         nsge = sk_msg_elem(msg_npl, j);
581 
582         if (sg_page(osge) == sg_page(nsge) &&
583             osge->offset + osge->length == nsge->offset) {
584                 osge->length += nsge->length;
585                 put_page(sg_page(nsge));
586         }
587 
588         msg_opl->sg.end = orig_end;
589         msg_opl->sg.curr = orig_end;
590         msg_opl->sg.copybreak = 0;
591         msg_opl->apply_bytes = msg_opl->sg.size + msg_npl->sg.size;
592         msg_opl->sg.size += msg_npl->sg.size;
593 
594         sk_msg_free(sk, &to->msg_encrypted);
595         sk_msg_xfer_full(&to->msg_encrypted, &from->msg_encrypted);
596 
597         kfree(from);
598 }
599 
600 static int tls_push_record(struct sock *sk, int flags,
601                            unsigned char record_type)
602 {
603         struct tls_context *tls_ctx = tls_get_ctx(sk);
604         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
605         struct tls_rec *rec = ctx->open_rec, *tmp = NULL;
606         u32 i, split_point, uninitialized_var(orig_end);
607         struct sk_msg *msg_pl, *msg_en;
608         struct aead_request *req;
609         bool split;
610         int rc;
611 
612         if (!rec)
613                 return 0;
614 
615         msg_pl = &rec->msg_plaintext;
616         msg_en = &rec->msg_encrypted;
617 
618         split_point = msg_pl->apply_bytes;
619         split = split_point && split_point < msg_pl->sg.size;
620         if (split) {
621                 rc = tls_split_open_record(sk, rec, &tmp, msg_pl, msg_en,
622                                            split_point, tls_ctx->tx.overhead_size,
623                                            &orig_end);
624                 if (rc < 0)
625                         return rc;
626                 sk_msg_trim(sk, msg_en, msg_pl->sg.size +
627                             tls_ctx->tx.overhead_size);
628         }
629 
630         rec->tx_flags = flags;
631         req = &rec->aead_req;
632 
633         i = msg_pl->sg.end;
634         sk_msg_iter_var_prev(i);
635         sg_mark_end(sk_msg_elem(msg_pl, i));
636 
637         i = msg_pl->sg.start;
638         sg_chain(rec->sg_aead_in, 2, rec->inplace_crypto ?
639                  &msg_en->sg.data[i] : &msg_pl->sg.data[i]);
640 
641         i = msg_en->sg.end;
642         sk_msg_iter_var_prev(i);
643         sg_mark_end(sk_msg_elem(msg_en, i));
644 
645         i = msg_en->sg.start;
646         sg_chain(rec->sg_aead_out, 2, &msg_en->sg.data[i]);
647 
648         tls_make_aad(rec->aad_space, msg_pl->sg.size,
649                      tls_ctx->tx.rec_seq, tls_ctx->tx.rec_seq_size,
650                      record_type);
651 
652         tls_fill_prepend(tls_ctx,
653                          page_address(sg_page(&msg_en->sg.data[i])) +
654                          msg_en->sg.data[i].offset, msg_pl->sg.size,
655                          record_type);
656 
657         tls_ctx->pending_open_record_frags = false;
658 
659         rc = tls_do_encryption(sk, tls_ctx, ctx, req, msg_pl->sg.size, i);
660         if (rc < 0) {
661                 if (rc != -EINPROGRESS) {
662                         tls_err_abort(sk, EBADMSG);
663                         if (split) {
664                                 tls_ctx->pending_open_record_frags = true;
665                                 tls_merge_open_record(sk, rec, tmp, orig_end);
666                         }
667                 }
668                 return rc;
669         } else if (split) {
670                 msg_pl = &tmp->msg_plaintext;
671                 msg_en = &tmp->msg_encrypted;
672                 sk_msg_trim(sk, msg_en, msg_pl->sg.size +
673                             tls_ctx->tx.overhead_size);
674                 tls_ctx->pending_open_record_frags = true;
675                 ctx->open_rec = tmp;
676         }
677 
678         return tls_tx_records(sk, flags);
679 }
680 
681 static int bpf_exec_tx_verdict(struct sk_msg *msg, struct sock *sk,
682                                bool full_record, u8 record_type,
683                                size_t *copied, int flags)
684 {
685         struct tls_context *tls_ctx = tls_get_ctx(sk);
686         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
687         struct sk_msg msg_redir = { };
688         struct sk_psock *psock;
689         struct sock *sk_redir;
690         struct tls_rec *rec;
691         int err = 0, send;
692         bool enospc;
693 
694         psock = sk_psock_get(sk);
695         if (!psock)
696                 return tls_push_record(sk, flags, record_type);
697 more_data:
698         enospc = sk_msg_full(msg);
699         if (psock->eval == __SK_NONE)
700                 psock->eval = sk_psock_msg_verdict(sk, psock, msg);
701         if (msg->cork_bytes && msg->cork_bytes > msg->sg.size &&
702             !enospc && !full_record) {
703                 err = -ENOSPC;
704                 goto out_err;
705         }
706         msg->cork_bytes = 0;
707         send = msg->sg.size;
708         if (msg->apply_bytes && msg->apply_bytes < send)
709                 send = msg->apply_bytes;
710 
711         switch (psock->eval) {
712         case __SK_PASS:
713                 err = tls_push_record(sk, flags, record_type);
714                 if (err < 0) {
715                         *copied -= sk_msg_free(sk, msg);
716                         tls_free_open_rec(sk);
717                         goto out_err;
718                 }
719                 break;
720         case __SK_REDIRECT:
721                 sk_redir = psock->sk_redir;
722                 memcpy(&msg_redir, msg, sizeof(*msg));
723                 if (msg->apply_bytes < send)
724                         msg->apply_bytes = 0;
725                 else
726                         msg->apply_bytes -= send;
727                 sk_msg_return_zero(sk, msg, send);
728                 msg->sg.size -= send;
729                 release_sock(sk);
730                 err = tcp_bpf_sendmsg_redir(sk_redir, &msg_redir, send, flags);
731                 lock_sock(sk);
732                 if (err < 0) {
733                         *copied -= sk_msg_free_nocharge(sk, &msg_redir);
734                         msg->sg.size = 0;
735                 }
736                 if (msg->sg.size == 0)
737                         tls_free_open_rec(sk);
738                 break;
739         case __SK_DROP:
740         default:
741                 sk_msg_free_partial(sk, msg, send);
742                 if (msg->apply_bytes < send)
743                         msg->apply_bytes = 0;
744                 else
745                         msg->apply_bytes -= send;
746                 if (msg->sg.size == 0)
747                         tls_free_open_rec(sk);
748                 *copied -= send;
749                 err = -EACCES;
750         }
751 
752         if (likely(!err)) {
753                 bool reset_eval = !ctx->open_rec;
754 
755                 rec = ctx->open_rec;
756                 if (rec) {
757                         msg = &rec->msg_plaintext;
758                         if (!msg->apply_bytes)
759                                 reset_eval = true;
760                 }
761                 if (reset_eval) {
762                         psock->eval = __SK_NONE;
763                         if (psock->sk_redir) {
764                                 sock_put(psock->sk_redir);
765                                 psock->sk_redir = NULL;
766                         }
767                 }
768                 if (rec)
769                         goto more_data;
770         }
771  out_err:
772         sk_psock_put(sk, psock);
773         return err;
774 }
775 
776 static int tls_sw_push_pending_record(struct sock *sk, int flags)
777 {
778         struct tls_context *tls_ctx = tls_get_ctx(sk);
779         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
780         struct tls_rec *rec = ctx->open_rec;
781         struct sk_msg *msg_pl;
782         size_t copied;
783 
784         if (!rec)
785                 return 0;
786 
787         msg_pl = &rec->msg_plaintext;
788         copied = msg_pl->sg.size;
789         if (!copied)
790                 return 0;
791 
792         return bpf_exec_tx_verdict(msg_pl, sk, true, TLS_RECORD_TYPE_DATA,
793                                    &copied, flags);
794 }
795 
796 int tls_sw_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
797 {
798         long timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
799         struct tls_context *tls_ctx = tls_get_ctx(sk);
800         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
801         struct crypto_tfm *tfm = crypto_aead_tfm(ctx->aead_send);
802         bool async_capable = tfm->__crt_alg->cra_flags & CRYPTO_ALG_ASYNC;
803         unsigned char record_type = TLS_RECORD_TYPE_DATA;
804         bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
805         bool eor = !(msg->msg_flags & MSG_MORE);
806         size_t try_to_copy, copied = 0;
807         struct sk_msg *msg_pl, *msg_en;
808         struct tls_rec *rec;
809         int required_size;
810         int num_async = 0;
811         bool full_record;
812         int record_room;
813         int num_zc = 0;
814         int orig_size;
815         int ret = 0;
816 
817         if (msg->msg_flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL))
818                 return -ENOTSUPP;
819 
820         lock_sock(sk);
821 
822         /* Wait till there is any pending write on socket */
823         if (unlikely(sk->sk_write_pending)) {
824                 ret = wait_on_pending_writer(sk, &timeo);
825                 if (unlikely(ret))
826                         goto send_end;
827         }
828 
829         if (unlikely(msg->msg_controllen)) {
830                 ret = tls_proccess_cmsg(sk, msg, &record_type);
831                 if (ret) {
832                         if (ret == -EINPROGRESS)
833                                 num_async++;
834                         else if (ret != -EAGAIN)
835                                 goto send_end;
836                 }
837         }
838 
839         while (msg_data_left(msg)) {
840                 if (sk->sk_err) {
841                         ret = -sk->sk_err;
842                         goto send_end;
843                 }
844 
845                 if (ctx->open_rec)
846                         rec = ctx->open_rec;
847                 else
848                         rec = ctx->open_rec = tls_get_rec(sk);
849                 if (!rec) {
850                         ret = -ENOMEM;
851                         goto send_end;
852                 }
853 
854                 msg_pl = &rec->msg_plaintext;
855                 msg_en = &rec->msg_encrypted;
856 
857                 orig_size = msg_pl->sg.size;
858                 full_record = false;
859                 try_to_copy = msg_data_left(msg);
860                 record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
861                 if (try_to_copy >= record_room) {
862                         try_to_copy = record_room;
863                         full_record = true;
864                 }
865 
866                 required_size = msg_pl->sg.size + try_to_copy +
867                                 tls_ctx->tx.overhead_size;
868 
869                 if (!sk_stream_memory_free(sk))
870                         goto wait_for_sndbuf;
871 
872 alloc_encrypted:
873                 ret = tls_alloc_encrypted_msg(sk, required_size);
874                 if (ret) {
875                         if (ret != -ENOSPC)
876                                 goto wait_for_memory;
877 
878                         /* Adjust try_to_copy according to the amount that was
879                          * actually allocated. The difference is due
880                          * to max sg elements limit
881                          */
882                         try_to_copy -= required_size - msg_en->sg.size;
883                         full_record = true;
884                 }
885 
886                 if (!is_kvec && (full_record || eor) && !async_capable) {
887                         u32 first = msg_pl->sg.end;
888 
889                         ret = sk_msg_zerocopy_from_iter(sk, &msg->msg_iter,
890                                                         msg_pl, try_to_copy);
891                         if (ret)
892                                 goto fallback_to_reg_send;
893 
894                         rec->inplace_crypto = 0;
895 
896                         num_zc++;
897                         copied += try_to_copy;
898 
899                         sk_msg_sg_copy_set(msg_pl, first);
900                         ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
901                                                   record_type, &copied,
902                                                   msg->msg_flags);
903                         if (ret) {
904                                 if (ret == -EINPROGRESS)
905                                         num_async++;
906                                 else if (ret == -ENOMEM)
907                                         goto wait_for_memory;
908                                 else if (ret == -ENOSPC)
909                                         goto rollback_iter;
910                                 else if (ret != -EAGAIN)
911                                         goto send_end;
912                         }
913                         continue;
914 rollback_iter:
915                         copied -= try_to_copy;
916                         sk_msg_sg_copy_clear(msg_pl, first);
917                         iov_iter_revert(&msg->msg_iter,
918                                         msg_pl->sg.size - orig_size);
919 fallback_to_reg_send:
920                         sk_msg_trim(sk, msg_pl, orig_size);
921                 }
922 
923                 required_size = msg_pl->sg.size + try_to_copy;
924 
925                 ret = tls_clone_plaintext_msg(sk, required_size);
926                 if (ret) {
927                         if (ret != -ENOSPC)
928                                 goto send_end;
929 
930                         /* Adjust try_to_copy according to the amount that was
931                          * actually allocated. The difference is due
932                          * to max sg elements limit
933                          */
934                         try_to_copy -= required_size - msg_pl->sg.size;
935                         full_record = true;
936                         sk_msg_trim(sk, msg_en, msg_pl->sg.size +
937                                     tls_ctx->tx.overhead_size);
938                 }
939 
940                 if (try_to_copy) {
941                         ret = sk_msg_memcopy_from_iter(sk, &msg->msg_iter,
942                                                        msg_pl, try_to_copy);
943                         if (ret < 0)
944                                 goto trim_sgl;
945                 }
946 
947                 /* Open records defined only if successfully copied, otherwise
948                  * we would trim the sg but not reset the open record frags.
949                  */
950                 tls_ctx->pending_open_record_frags = true;
951                 copied += try_to_copy;
952                 if (full_record || eor) {
953                         ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
954                                                   record_type, &copied,
955                                                   msg->msg_flags);
956                         if (ret) {
957                                 if (ret == -EINPROGRESS)
958                                         num_async++;
959                                 else if (ret == -ENOMEM)
960                                         goto wait_for_memory;
961                                 else if (ret != -EAGAIN) {
962                                         if (ret == -ENOSPC)
963                                                 ret = 0;
964                                         goto send_end;
965                                 }
966                         }
967                 }
968 
969                 continue;
970 
971 wait_for_sndbuf:
972                 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
973 wait_for_memory:
974                 ret = sk_stream_wait_memory(sk, &timeo);
975                 if (ret) {
976 trim_sgl:
977                         tls_trim_both_msgs(sk, orig_size);
978                         goto send_end;
979                 }
980 
981                 if (msg_en->sg.size < required_size)
982                         goto alloc_encrypted;
983         }
984 
985         if (!num_async) {
986                 goto send_end;
987         } else if (num_zc) {
988                 /* Wait for pending encryptions to get completed */
989                 smp_store_mb(ctx->async_notify, true);
990 
991                 if (atomic_read(&ctx->encrypt_pending))
992                         crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
993                 else
994                         reinit_completion(&ctx->async_wait.completion);
995 
996                 WRITE_ONCE(ctx->async_notify, false);
997 
998                 if (ctx->async_wait.err) {
999                         ret = ctx->async_wait.err;
1000                         copied = 0;
1001                 }
1002         }
1003 
1004         /* Transmit if any encryptions have completed */
1005         if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
1006                 cancel_delayed_work(&ctx->tx_work.work);
1007                 tls_tx_records(sk, msg->msg_flags);
1008         }
1009 
1010 send_end:
1011         ret = sk_stream_error(sk, msg->msg_flags, ret);
1012 
1013         release_sock(sk);
1014         return copied ? copied : ret;
1015 }
1016 
1017 int tls_sw_sendpage(struct sock *sk, struct page *page,
1018                     int offset, size_t size, int flags)
1019 {
1020         long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
1021         struct tls_context *tls_ctx = tls_get_ctx(sk);
1022         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
1023         unsigned char record_type = TLS_RECORD_TYPE_DATA;
1024         struct sk_msg *msg_pl;
1025         struct tls_rec *rec;
1026         int num_async = 0;
1027         size_t copied = 0;
1028         bool full_record;
1029         int record_room;
1030         int ret = 0;
1031         bool eor;
1032 
1033         if (flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
1034                       MSG_SENDPAGE_NOTLAST))
1035                 return -ENOTSUPP;
1036 
1037         /* No MSG_EOR from splice, only look at MSG_MORE */
1038         eor = !(flags & (MSG_MORE | MSG_SENDPAGE_NOTLAST));
1039 
1040         lock_sock(sk);
1041 
1042         sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
1043 
1044         /* Wait till there is any pending write on socket */
1045         if (unlikely(sk->sk_write_pending)) {
1046                 ret = wait_on_pending_writer(sk, &timeo);
1047                 if (unlikely(ret))
1048                         goto sendpage_end;
1049         }
1050 
1051         /* Call the sk_stream functions to manage the sndbuf mem. */
1052         while (size > 0) {
1053                 size_t copy, required_size;
1054 
1055                 if (sk->sk_err) {
1056                         ret = -sk->sk_err;
1057                         goto sendpage_end;
1058                 }
1059 
1060                 if (ctx->open_rec)
1061                         rec = ctx->open_rec;
1062                 else
1063                         rec = ctx->open_rec = tls_get_rec(sk);
1064                 if (!rec) {
1065                         ret = -ENOMEM;
1066                         goto sendpage_end;
1067                 }
1068 
1069                 msg_pl = &rec->msg_plaintext;
1070 
1071                 full_record = false;
1072                 record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
1073                 copied = 0;
1074                 copy = size;
1075                 if (copy >= record_room) {
1076                         copy = record_room;
1077                         full_record = true;
1078                 }
1079 
1080                 required_size = msg_pl->sg.size + copy +
1081                                 tls_ctx->tx.overhead_size;
1082 
1083                 if (!sk_stream_memory_free(sk))
1084                         goto wait_for_sndbuf;
1085 alloc_payload:
1086                 ret = tls_alloc_encrypted_msg(sk, required_size);
1087                 if (ret) {
1088                         if (ret != -ENOSPC)
1089                                 goto wait_for_memory;
1090 
1091                         /* Adjust copy according to the amount that was
1092                          * actually allocated. The difference is due
1093                          * to max sg elements limit
1094                          */
1095                         copy -= required_size - msg_pl->sg.size;
1096                         full_record = true;
1097                 }
1098 
1099                 sk_msg_page_add(msg_pl, page, copy, offset);
1100                 sk_mem_charge(sk, copy);
1101 
1102                 offset += copy;
1103                 size -= copy;
1104                 copied += copy;
1105 
1106                 tls_ctx->pending_open_record_frags = true;
1107                 if (full_record || eor || sk_msg_full(msg_pl)) {
1108                         rec->inplace_crypto = 0;
1109                         ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1110                                                   record_type, &copied, flags);
1111                         if (ret) {
1112                                 if (ret == -EINPROGRESS)
1113                                         num_async++;
1114                                 else if (ret == -ENOMEM)
1115                                         goto wait_for_memory;
1116                                 else if (ret != -EAGAIN) {
1117                                         if (ret == -ENOSPC)
1118                                                 ret = 0;
1119                                         goto sendpage_end;
1120                                 }
1121                         }
1122                 }
1123                 continue;
1124 wait_for_sndbuf:
1125                 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1126 wait_for_memory:
1127                 ret = sk_stream_wait_memory(sk, &timeo);
1128                 if (ret) {
1129                         tls_trim_both_msgs(sk, msg_pl->sg.size);
1130                         goto sendpage_end;
1131                 }
1132 
1133                 goto alloc_payload;
1134         }
1135 
1136         if (num_async) {
1137                 /* Transmit if any encryptions have completed */
1138                 if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
1139                         cancel_delayed_work(&ctx->tx_work.work);
1140                         tls_tx_records(sk, flags);
1141                 }
1142         }
1143 sendpage_end:
1144         ret = sk_stream_error(sk, flags, ret);
1145         release_sock(sk);
1146         return copied ? copied : ret;
1147 }
1148 
1149 static struct sk_buff *tls_wait_data(struct sock *sk, struct sk_psock *psock,
1150                                      int flags, long timeo, int *err)
1151 {
1152         struct tls_context *tls_ctx = tls_get_ctx(sk);
1153         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1154         struct sk_buff *skb;
1155         DEFINE_WAIT_FUNC(wait, woken_wake_function);
1156 
1157         while (!(skb = ctx->recv_pkt) && sk_psock_queue_empty(psock)) {
1158                 if (sk->sk_err) {
1159                         *err = sock_error(sk);
1160                         return NULL;
1161                 }
1162 
1163                 if (sk->sk_shutdown & RCV_SHUTDOWN)
1164                         return NULL;
1165 
1166                 if (sock_flag(sk, SOCK_DONE))
1167                         return NULL;
1168 
1169                 if ((flags & MSG_DONTWAIT) || !timeo) {
1170                         *err = -EAGAIN;
1171                         return NULL;
1172                 }
1173 
1174                 add_wait_queue(sk_sleep(sk), &wait);
1175                 sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1176                 sk_wait_event(sk, &timeo,
1177                               ctx->recv_pkt != skb ||
1178                               !sk_psock_queue_empty(psock),
1179                               &wait);
1180                 sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1181                 remove_wait_queue(sk_sleep(sk), &wait);
1182 
1183                 /* Handle signals */
1184                 if (signal_pending(current)) {
1185                         *err = sock_intr_errno(timeo);
1186                         return NULL;
1187                 }
1188         }
1189 
1190         return skb;
1191 }
1192 
1193 static int tls_setup_from_iter(struct sock *sk, struct iov_iter *from,
1194                                int length, int *pages_used,
1195                                unsigned int *size_used,
1196                                struct scatterlist *to,
1197                                int to_max_pages)
1198 {
1199         int rc = 0, i = 0, num_elem = *pages_used, maxpages;
1200         struct page *pages[MAX_SKB_FRAGS];
1201         unsigned int size = *size_used;
1202         ssize_t copied, use;
1203         size_t offset;
1204 
1205         while (length > 0) {
1206                 i = 0;
1207                 maxpages = to_max_pages - num_elem;
1208                 if (maxpages == 0) {
1209                         rc = -EFAULT;
1210                         goto out;
1211                 }
1212                 copied = iov_iter_get_pages(from, pages,
1213                                             length,
1214                                             maxpages, &offset);
1215                 if (copied <= 0) {
1216                         rc = -EFAULT;
1217                         goto out;
1218                 }
1219 
1220                 iov_iter_advance(from, copied);
1221 
1222                 length -= copied;
1223                 size += copied;
1224                 while (copied) {
1225                         use = min_t(int, copied, PAGE_SIZE - offset);
1226 
1227                         sg_set_page(&to[num_elem],
1228                                     pages[i], use, offset);
1229                         sg_unmark_end(&to[num_elem]);
1230                         /* We do not uncharge memory from this API */
1231 
1232                         offset = 0;
1233                         copied -= use;
1234 
1235                         i++;
1236                         num_elem++;
1237                 }
1238         }
1239         /* Mark the end in the last sg entry if newly added */
1240         if (num_elem > *pages_used)
1241                 sg_mark_end(&to[num_elem - 1]);
1242 out:
1243         if (rc)
1244                 iov_iter_revert(from, size - *size_used);
1245         *size_used = size;
1246         *pages_used = num_elem;
1247 
1248         return rc;
1249 }
1250 
1251 /* This function decrypts the input skb into either out_iov or in out_sg
1252  * or in skb buffers itself. The input parameter 'zc' indicates if
1253  * zero-copy mode needs to be tried or not. With zero-copy mode, either
1254  * out_iov or out_sg must be non-NULL. In case both out_iov and out_sg are
1255  * NULL, then the decryption happens inside skb buffers itself, i.e.
1256  * zero-copy gets disabled and 'zc' is updated.
1257  */
1258 
1259 static int decrypt_internal(struct sock *sk, struct sk_buff *skb,
1260                             struct iov_iter *out_iov,
1261                             struct scatterlist *out_sg,
1262                             int *chunk, bool *zc)
1263 {
1264         struct tls_context *tls_ctx = tls_get_ctx(sk);
1265         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1266         struct strp_msg *rxm = strp_msg(skb);
1267         int n_sgin, n_sgout, nsg, mem_size, aead_size, err, pages = 0;
1268         struct aead_request *aead_req;
1269         struct sk_buff *unused;
1270         u8 *aad, *iv, *mem = NULL;
1271         struct scatterlist *sgin = NULL;
1272         struct scatterlist *sgout = NULL;
1273         const int data_len = rxm->full_len - tls_ctx->rx.overhead_size;
1274 
1275         if (*zc && (out_iov || out_sg)) {
1276                 if (out_iov)
1277                         n_sgout = iov_iter_npages(out_iov, INT_MAX) + 1;
1278                 else
1279                         n_sgout = sg_nents(out_sg);
1280                 n_sgin = skb_nsg(skb, rxm->offset + tls_ctx->rx.prepend_size,
1281                                  rxm->full_len - tls_ctx->rx.prepend_size);
1282         } else {
1283                 n_sgout = 0;
1284                 *zc = false;
1285                 n_sgin = skb_cow_data(skb, 0, &unused);
1286         }
1287 
1288         if (n_sgin < 1)
1289                 return -EBADMSG;
1290 
1291         /* Increment to accommodate AAD */
1292         n_sgin = n_sgin + 1;
1293 
1294         nsg = n_sgin + n_sgout;
1295 
1296         aead_size = sizeof(*aead_req) + crypto_aead_reqsize(ctx->aead_recv);
1297         mem_size = aead_size + (nsg * sizeof(struct scatterlist));
1298         mem_size = mem_size + TLS_AAD_SPACE_SIZE;
1299         mem_size = mem_size + crypto_aead_ivsize(ctx->aead_recv);
1300 
1301         /* Allocate a single block of memory which contains
1302          * aead_req || sgin[] || sgout[] || aad || iv.
1303          * This order achieves correct alignment for aead_req, sgin, sgout.
1304          */
1305         mem = kmalloc(mem_size, sk->sk_allocation);
1306         if (!mem)
1307                 return -ENOMEM;
1308 
1309         /* Segment the allocated memory */
1310         aead_req = (struct aead_request *)mem;
1311         sgin = (struct scatterlist *)(mem + aead_size);
1312         sgout = sgin + n_sgin;
1313         aad = (u8 *)(sgout + n_sgout);
1314         iv = aad + TLS_AAD_SPACE_SIZE;
1315 
1316         /* Prepare IV */
1317         err = skb_copy_bits(skb, rxm->offset + TLS_HEADER_SIZE,
1318                             iv + TLS_CIPHER_AES_GCM_128_SALT_SIZE,
1319                             tls_ctx->rx.iv_size);
1320         if (err < 0) {
1321                 kfree(mem);
1322                 return err;
1323         }
1324         memcpy(iv, tls_ctx->rx.iv, TLS_CIPHER_AES_GCM_128_SALT_SIZE);
1325 
1326         /* Prepare AAD */
1327         tls_make_aad(aad, rxm->full_len - tls_ctx->rx.overhead_size,
1328                      tls_ctx->rx.rec_seq, tls_ctx->rx.rec_seq_size,
1329                      ctx->control);
1330 
1331         /* Prepare sgin */
1332         sg_init_table(sgin, n_sgin);
1333         sg_set_buf(&sgin[0], aad, TLS_AAD_SPACE_SIZE);
1334         err = skb_to_sgvec(skb, &sgin[1],
1335                            rxm->offset + tls_ctx->rx.prepend_size,
1336                            rxm->full_len - tls_ctx->rx.prepend_size);
1337         if (err < 0) {
1338                 kfree(mem);
1339                 return err;
1340         }
1341 
1342         if (n_sgout) {
1343                 if (out_iov) {
1344                         sg_init_table(sgout, n_sgout);
1345                         sg_set_buf(&sgout[0], aad, TLS_AAD_SPACE_SIZE);
1346 
1347                         *chunk = 0;
1348                         err = tls_setup_from_iter(sk, out_iov, data_len,
1349                                                   &pages, chunk, &sgout[1],
1350                                                   (n_sgout - 1));
1351                         if (err < 0)
1352                                 goto fallback_to_reg_recv;
1353                 } else if (out_sg) {
1354                         memcpy(sgout, out_sg, n_sgout * sizeof(*sgout));
1355                 } else {
1356                         goto fallback_to_reg_recv;
1357                 }
1358         } else {
1359 fallback_to_reg_recv:
1360                 sgout = sgin;
1361                 pages = 0;
1362                 *chunk = 0;
1363                 *zc = false;
1364         }
1365 
1366         /* Prepare and submit AEAD request */
1367         err = tls_do_decryption(sk, skb, sgin, sgout, iv,
1368                                 data_len, aead_req, *zc);
1369         if (err == -EINPROGRESS)
1370                 return err;
1371 
1372         /* Release the pages in case iov was mapped to pages */
1373         for (; pages > 0; pages--)
1374                 put_page(sg_page(&sgout[pages]));
1375 
1376         kfree(mem);
1377         return err;
1378 }
1379 
1380 static int decrypt_skb_update(struct sock *sk, struct sk_buff *skb,
1381                               struct iov_iter *dest, int *chunk, bool *zc)
1382 {
1383         struct tls_context *tls_ctx = tls_get_ctx(sk);
1384         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1385         struct strp_msg *rxm = strp_msg(skb);
1386         int err = 0;
1387 
1388 #ifdef CONFIG_TLS_DEVICE
1389         err = tls_device_decrypted(sk, skb);
1390         if (err < 0)
1391                 return err;
1392 #endif
1393         if (!ctx->decrypted) {
1394                 err = decrypt_internal(sk, skb, dest, NULL, chunk, zc);
1395                 if (err < 0) {
1396                         if (err == -EINPROGRESS)
1397                                 tls_advance_record_sn(sk, &tls_ctx->rx);
1398 
1399                         return err;
1400                 }
1401         } else {
1402                 *zc = false;
1403         }
1404 
1405         rxm->offset += tls_ctx->rx.prepend_size;
1406         rxm->full_len -= tls_ctx->rx.overhead_size;
1407         tls_advance_record_sn(sk, &tls_ctx->rx);
1408         ctx->decrypted = true;
1409         ctx->saved_data_ready(sk);
1410 
1411         return err;
1412 }
1413 
1414 int decrypt_skb(struct sock *sk, struct sk_buff *skb,
1415                 struct scatterlist *sgout)
1416 {
1417         bool zc = true;
1418         int chunk;
1419 
1420         return decrypt_internal(sk, skb, NULL, sgout, &chunk, &zc);
1421 }
1422 
1423 static bool tls_sw_advance_skb(struct sock *sk, struct sk_buff *skb,
1424                                unsigned int len)
1425 {
1426         struct tls_context *tls_ctx = tls_get_ctx(sk);
1427         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1428 
1429         if (skb) {
1430                 struct strp_msg *rxm = strp_msg(skb);
1431 
1432                 if (len < rxm->full_len) {
1433                         rxm->offset += len;
1434                         rxm->full_len -= len;
1435                         return false;
1436                 }
1437                 kfree_skb(skb);
1438         }
1439 
1440         /* Finished with message */
1441         ctx->recv_pkt = NULL;
1442         __strp_unpause(&ctx->strp);
1443 
1444         return true;
1445 }
1446 
1447 int tls_sw_recvmsg(struct sock *sk,
1448                    struct msghdr *msg,
1449                    size_t len,
1450                    int nonblock,
1451                    int flags,
1452                    int *addr_len)
1453 {
1454         struct tls_context *tls_ctx = tls_get_ctx(sk);
1455         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1456         struct sk_psock *psock;
1457         unsigned char control;
1458         struct strp_msg *rxm;
1459         struct sk_buff *skb;
1460         ssize_t copied = 0;
1461         bool cmsg = false;
1462         int target, err = 0;
1463         long timeo;
1464         bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
1465         int num_async = 0;
1466 
1467         flags |= nonblock;
1468 
1469         if (unlikely(flags & MSG_ERRQUEUE))
1470                 return sock_recv_errqueue(sk, msg, len, SOL_IP, IP_RECVERR);
1471 
1472         psock = sk_psock_get(sk);
1473         lock_sock(sk);
1474 
1475         target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
1476         timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1477         do {
1478                 bool zc = false;
1479                 bool async = false;
1480                 int chunk = 0;
1481 
1482                 skb = tls_wait_data(sk, psock, flags, timeo, &err);
1483                 if (!skb) {
1484                         if (psock) {
1485                                 int ret = __tcp_bpf_recvmsg(sk, psock,
1486                                                             msg, len, flags);
1487 
1488                                 if (ret > 0) {
1489                                         copied += ret;
1490                                         len -= ret;
1491                                         continue;
1492                                 }
1493                         }
1494                         goto recv_end;
1495                 }
1496 
1497                 rxm = strp_msg(skb);
1498 
1499                 if (!cmsg) {
1500                         int cerr;
1501 
1502                         cerr = put_cmsg(msg, SOL_TLS, TLS_GET_RECORD_TYPE,
1503                                         sizeof(ctx->control), &ctx->control);
1504                         cmsg = true;
1505                         control = ctx->control;
1506                         if (ctx->control != TLS_RECORD_TYPE_DATA) {
1507                                 if (cerr || msg->msg_flags & MSG_CTRUNC) {
1508                                         err = -EIO;
1509                                         goto recv_end;
1510                                 }
1511                         }
1512                 } else if (control != ctx->control) {
1513                         goto recv_end;
1514                 }
1515 
1516                 if (!ctx->decrypted) {
1517                         int to_copy = rxm->full_len - tls_ctx->rx.overhead_size;
1518 
1519                         if (!is_kvec && to_copy <= len &&
1520                             likely(!(flags & MSG_PEEK)))
1521                                 zc = true;
1522 
1523                         err = decrypt_skb_update(sk, skb, &msg->msg_iter,
1524                                                  &chunk, &zc);
1525                         if (err < 0 && err != -EINPROGRESS) {
1526                                 tls_err_abort(sk, EBADMSG);
1527                                 goto recv_end;
1528                         }
1529 
1530                         if (err == -EINPROGRESS) {
1531                                 async = true;
1532                                 num_async++;
1533                                 goto pick_next_record;
1534                         }
1535 
1536                         ctx->decrypted = true;
1537                 }
1538 
1539                 if (!zc) {
1540                         chunk = min_t(unsigned int, rxm->full_len, len);
1541 
1542                         err = skb_copy_datagram_msg(skb, rxm->offset, msg,
1543                                                     chunk);
1544                         if (err < 0)
1545                                 goto recv_end;
1546                 }
1547 
1548 pick_next_record:
1549                 copied += chunk;
1550                 len -= chunk;
1551                 if (likely(!(flags & MSG_PEEK))) {
1552                         u8 control = ctx->control;
1553 
1554                         /* For async, drop current skb reference */
1555                         if (async)
1556                                 skb = NULL;
1557 
1558                         if (tls_sw_advance_skb(sk, skb, chunk)) {
1559                                 /* Return full control message to
1560                                  * userspace before trying to parse
1561                                  * another message type
1562                                  */
1563                                 msg->msg_flags |= MSG_EOR;
1564                                 if (control != TLS_RECORD_TYPE_DATA)
1565                                         goto recv_end;
1566                         } else {
1567                                 break;
1568                         }
1569                 } else {
1570                         /* MSG_PEEK right now cannot look beyond current skb
1571                          * from strparser, meaning we cannot advance skb here
1572                          * and thus unpause strparser since we'd loose original
1573                          * one.
1574                          */
1575                         break;
1576                 }
1577 
1578                 /* If we have a new message from strparser, continue now. */
1579                 if (copied >= target && !ctx->recv_pkt)
1580                         break;
1581         } while (len);
1582 
1583 recv_end:
1584         if (num_async) {
1585                 /* Wait for all previously submitted records to be decrypted */
1586                 smp_store_mb(ctx->async_notify, true);
1587                 if (atomic_read(&ctx->decrypt_pending)) {
1588                         err = crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
1589                         if (err) {
1590                                 /* one of async decrypt failed */
1591                                 tls_err_abort(sk, err);
1592                                 copied = 0;
1593                         }
1594                 } else {
1595                         reinit_completion(&ctx->async_wait.completion);
1596                 }
1597                 WRITE_ONCE(ctx->async_notify, false);
1598         }
1599 
1600         release_sock(sk);
1601         if (psock)
1602                 sk_psock_put(sk, psock);
1603         return copied ? : err;
1604 }
1605 
1606 ssize_t tls_sw_splice_read(struct socket *sock,  loff_t *ppos,
1607                            struct pipe_inode_info *pipe,
1608                            size_t len, unsigned int flags)
1609 {
1610         struct tls_context *tls_ctx = tls_get_ctx(sock->sk);
1611         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1612         struct strp_msg *rxm = NULL;
1613         struct sock *sk = sock->sk;
1614         struct sk_buff *skb;
1615         ssize_t copied = 0;
1616         int err = 0;
1617         long timeo;
1618         int chunk;
1619         bool zc = false;
1620 
1621         lock_sock(sk);
1622 
1623         timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1624 
1625         skb = tls_wait_data(sk, NULL, flags, timeo, &err);
1626         if (!skb)
1627                 goto splice_read_end;
1628 
1629         /* splice does not support reading control messages */
1630         if (ctx->control != TLS_RECORD_TYPE_DATA) {
1631                 err = -ENOTSUPP;
1632                 goto splice_read_end;
1633         }
1634 
1635         if (!ctx->decrypted) {
1636                 err = decrypt_skb_update(sk, skb, NULL, &chunk, &zc);
1637 
1638                 if (err < 0) {
1639                         tls_err_abort(sk, EBADMSG);
1640                         goto splice_read_end;
1641                 }
1642                 ctx->decrypted = true;
1643         }
1644         rxm = strp_msg(skb);
1645 
1646         chunk = min_t(unsigned int, rxm->full_len, len);
1647         copied = skb_splice_bits(skb, sk, rxm->offset, pipe, chunk, flags);
1648         if (copied < 0)
1649                 goto splice_read_end;
1650 
1651         if (likely(!(flags & MSG_PEEK)))
1652                 tls_sw_advance_skb(sk, skb, copied);
1653 
1654 splice_read_end:
1655         release_sock(sk);
1656         return copied ? : err;
1657 }
1658 
1659 bool tls_sw_stream_read(const struct sock *sk)
1660 {
1661         struct tls_context *tls_ctx = tls_get_ctx(sk);
1662         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1663         bool ingress_empty = true;
1664         struct sk_psock *psock;
1665 
1666         rcu_read_lock();
1667         psock = sk_psock(sk);
1668         if (psock)
1669                 ingress_empty = list_empty(&psock->ingress_msg);
1670         rcu_read_unlock();
1671 
1672         return !ingress_empty || ctx->recv_pkt;
1673 }
1674 
1675 static int tls_read_size(struct strparser *strp, struct sk_buff *skb)
1676 {
1677         struct tls_context *tls_ctx = tls_get_ctx(strp->sk);
1678         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1679         char header[TLS_HEADER_SIZE + MAX_IV_SIZE];
1680         struct strp_msg *rxm = strp_msg(skb);
1681         size_t cipher_overhead;
1682         size_t data_len = 0;
1683         int ret;
1684 
1685         /* Verify that we have a full TLS header, or wait for more data */
1686         if (rxm->offset + tls_ctx->rx.prepend_size > skb->len)
1687                 return 0;
1688 
1689         /* Sanity-check size of on-stack buffer. */
1690         if (WARN_ON(tls_ctx->rx.prepend_size > sizeof(header))) {
1691                 ret = -EINVAL;
1692                 goto read_failure;
1693         }
1694 
1695         /* Linearize header to local buffer */
1696         ret = skb_copy_bits(skb, rxm->offset, header, tls_ctx->rx.prepend_size);
1697 
1698         if (ret < 0)
1699                 goto read_failure;
1700 
1701         ctx->control = header[0];
1702 
1703         data_len = ((header[4] & 0xFF) | (header[3] << 8));
1704 
1705         cipher_overhead = tls_ctx->rx.tag_size + tls_ctx->rx.iv_size;
1706 
1707         if (data_len > TLS_MAX_PAYLOAD_SIZE + cipher_overhead) {
1708                 ret = -EMSGSIZE;
1709                 goto read_failure;
1710         }
1711         if (data_len < cipher_overhead) {
1712                 ret = -EBADMSG;
1713                 goto read_failure;
1714         }
1715 
1716         if (header[1] != TLS_VERSION_MINOR(tls_ctx->crypto_recv.info.version) ||
1717             header[2] != TLS_VERSION_MAJOR(tls_ctx->crypto_recv.info.version)) {
1718                 ret = -EINVAL;
1719                 goto read_failure;
1720         }
1721 
1722 #ifdef CONFIG_TLS_DEVICE
1723         handle_device_resync(strp->sk, TCP_SKB_CB(skb)->seq + rxm->offset,
1724                              *(u64*)tls_ctx->rx.rec_seq);
1725 #endif
1726         return data_len + TLS_HEADER_SIZE;
1727 
1728 read_failure:
1729         tls_err_abort(strp->sk, ret);
1730 
1731         return ret;
1732 }
1733 
1734 static void tls_queue(struct strparser *strp, struct sk_buff *skb)
1735 {
1736         struct tls_context *tls_ctx = tls_get_ctx(strp->sk);
1737         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1738 
1739         ctx->decrypted = false;
1740 
1741         ctx->recv_pkt = skb;
1742         strp_pause(strp);
1743 
1744         ctx->saved_data_ready(strp->sk);
1745 }
1746 
1747 static void tls_data_ready(struct sock *sk)
1748 {
1749         struct tls_context *tls_ctx = tls_get_ctx(sk);
1750         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1751         struct sk_psock *psock;
1752 
1753         strp_data_ready(&ctx->strp);
1754 
1755         psock = sk_psock_get(sk);
1756         if (psock && !list_empty(&psock->ingress_msg)) {
1757                 ctx->saved_data_ready(sk);
1758                 sk_psock_put(sk, psock);
1759         }
1760 }
1761 
1762 void tls_sw_free_resources_tx(struct sock *sk)
1763 {
1764         struct tls_context *tls_ctx = tls_get_ctx(sk);
1765         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
1766         struct tls_rec *rec, *tmp;
1767 
1768         /* Wait for any pending async encryptions to complete */
1769         smp_store_mb(ctx->async_notify, true);
1770         if (atomic_read(&ctx->encrypt_pending))
1771                 crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
1772 
1773         release_sock(sk);
1774         cancel_delayed_work_sync(&ctx->tx_work.work);
1775         lock_sock(sk);
1776 
1777         /* Tx whatever records we can transmit and abandon the rest */
1778         tls_tx_records(sk, -1);
1779 
1780         /* Free up un-sent records in tx_list. First, free
1781          * the partially sent record if any at head of tx_list.
1782          */
1783         if (tls_ctx->partially_sent_record) {
1784                 struct scatterlist *sg = tls_ctx->partially_sent_record;
1785 
1786                 while (1) {
1787                         put_page(sg_page(sg));
1788                         sk_mem_uncharge(sk, sg->length);
1789 
1790                         if (sg_is_last(sg))
1791                                 break;
1792                         sg++;
1793                 }
1794 
1795                 tls_ctx->partially_sent_record = NULL;
1796 
1797                 rec = list_first_entry(&ctx->tx_list,
1798                                        struct tls_rec, list);
1799                 list_del(&rec->list);
1800                 sk_msg_free(sk, &rec->msg_plaintext);
1801                 kfree(rec);
1802         }
1803 
1804         list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
1805                 list_del(&rec->list);
1806                 sk_msg_free(sk, &rec->msg_encrypted);
1807                 sk_msg_free(sk, &rec->msg_plaintext);
1808                 kfree(rec);
1809         }
1810 
1811         crypto_free_aead(ctx->aead_send);
1812         tls_free_open_rec(sk);
1813 
1814         kfree(ctx);
1815 }
1816 
1817 void tls_sw_release_resources_rx(struct sock *sk)
1818 {
1819         struct tls_context *tls_ctx = tls_get_ctx(sk);
1820         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1821 
1822         if (ctx->aead_recv) {
1823                 kfree_skb(ctx->recv_pkt);
1824                 ctx->recv_pkt = NULL;
1825                 crypto_free_aead(ctx->aead_recv);
1826                 strp_stop(&ctx->strp);
1827                 write_lock_bh(&sk->sk_callback_lock);
1828                 sk->sk_data_ready = ctx->saved_data_ready;
1829                 write_unlock_bh(&sk->sk_callback_lock);
1830                 release_sock(sk);
1831                 strp_done(&ctx->strp);
1832                 lock_sock(sk);
1833         }
1834 }
1835 
1836 void tls_sw_free_resources_rx(struct sock *sk)
1837 {
1838         struct tls_context *tls_ctx = tls_get_ctx(sk);
1839         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1840 
1841         tls_sw_release_resources_rx(sk);
1842 
1843         kfree(ctx);
1844 }
1845 
1846 /* The work handler to transmitt the encrypted records in tx_list */
1847 static void tx_work_handler(struct work_struct *work)
1848 {
1849         struct delayed_work *delayed_work = to_delayed_work(work);
1850         struct tx_work *tx_work = container_of(delayed_work,
1851                                                struct tx_work, work);
1852         struct sock *sk = tx_work->sk;
1853         struct tls_context *tls_ctx = tls_get_ctx(sk);
1854         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
1855 
1856         if (!test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask))
1857                 return;
1858 
1859         lock_sock(sk);
1860         tls_tx_records(sk, -1);
1861         release_sock(sk);
1862 }
1863 
1864 int tls_set_sw_offload(struct sock *sk, struct tls_context *ctx, int tx)
1865 {
1866         struct tls_crypto_info *crypto_info;
1867         struct tls12_crypto_info_aes_gcm_128 *gcm_128_info;
1868         struct tls_sw_context_tx *sw_ctx_tx = NULL;
1869         struct tls_sw_context_rx *sw_ctx_rx = NULL;
1870         struct cipher_context *cctx;
1871         struct crypto_aead **aead;
1872         struct strp_callbacks cb;
1873         u16 nonce_size, tag_size, iv_size, rec_seq_size;
1874         char *iv, *rec_seq;
1875         int rc = 0;
1876 
1877         if (!ctx) {
1878                 rc = -EINVAL;
1879                 goto out;
1880         }
1881 
1882         if (tx) {
1883                 if (!ctx->priv_ctx_tx) {
1884                         sw_ctx_tx = kzalloc(sizeof(*sw_ctx_tx), GFP_KERNEL);
1885                         if (!sw_ctx_tx) {
1886                                 rc = -ENOMEM;
1887                                 goto out;
1888                         }
1889                         ctx->priv_ctx_tx = sw_ctx_tx;
1890                 } else {
1891                         sw_ctx_tx =
1892                                 (struct tls_sw_context_tx *)ctx->priv_ctx_tx;
1893                 }
1894         } else {
1895                 if (!ctx->priv_ctx_rx) {
1896                         sw_ctx_rx = kzalloc(sizeof(*sw_ctx_rx), GFP_KERNEL);
1897                         if (!sw_ctx_rx) {
1898                                 rc = -ENOMEM;
1899                                 goto out;
1900                         }
1901                         ctx->priv_ctx_rx = sw_ctx_rx;
1902                 } else {
1903                         sw_ctx_rx =
1904                                 (struct tls_sw_context_rx *)ctx->priv_ctx_rx;
1905                 }
1906         }
1907 
1908         if (tx) {
1909                 crypto_init_wait(&sw_ctx_tx->async_wait);
1910                 crypto_info = &ctx->crypto_send.info;
1911                 cctx = &ctx->tx;
1912                 aead = &sw_ctx_tx->aead_send;
1913                 INIT_LIST_HEAD(&sw_ctx_tx->tx_list);
1914                 INIT_DELAYED_WORK(&sw_ctx_tx->tx_work.work, tx_work_handler);
1915                 sw_ctx_tx->tx_work.sk = sk;
1916         } else {
1917                 crypto_init_wait(&sw_ctx_rx->async_wait);
1918                 crypto_info = &ctx->crypto_recv.info;
1919                 cctx = &ctx->rx;
1920                 aead = &sw_ctx_rx->aead_recv;
1921         }
1922 
1923         switch (crypto_info->cipher_type) {
1924         case TLS_CIPHER_AES_GCM_128: {
1925                 nonce_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
1926                 tag_size = TLS_CIPHER_AES_GCM_128_TAG_SIZE;
1927                 iv_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
1928                 iv = ((struct tls12_crypto_info_aes_gcm_128 *)crypto_info)->iv;
1929                 rec_seq_size = TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE;
1930                 rec_seq =
1931                  ((struct tls12_crypto_info_aes_gcm_128 *)crypto_info)->rec_seq;
1932                 gcm_128_info =
1933                         (struct tls12_crypto_info_aes_gcm_128 *)crypto_info;
1934                 break;
1935         }
1936         default:
1937                 rc = -EINVAL;
1938                 goto free_priv;
1939         }
1940 
1941         /* Sanity-check the IV size for stack allocations. */
1942         if (iv_size > MAX_IV_SIZE || nonce_size > MAX_IV_SIZE) {
1943                 rc = -EINVAL;
1944                 goto free_priv;
1945         }
1946 
1947         cctx->prepend_size = TLS_HEADER_SIZE + nonce_size;
1948         cctx->tag_size = tag_size;
1949         cctx->overhead_size = cctx->prepend_size + cctx->tag_size;
1950         cctx->iv_size = iv_size;
1951         cctx->iv = kmalloc(iv_size + TLS_CIPHER_AES_GCM_128_SALT_SIZE,
1952                            GFP_KERNEL);
1953         if (!cctx->iv) {
1954                 rc = -ENOMEM;
1955                 goto free_priv;
1956         }
1957         memcpy(cctx->iv, gcm_128_info->salt, TLS_CIPHER_AES_GCM_128_SALT_SIZE);
1958         memcpy(cctx->iv + TLS_CIPHER_AES_GCM_128_SALT_SIZE, iv, iv_size);
1959         cctx->rec_seq_size = rec_seq_size;
1960         cctx->rec_seq = kmemdup(rec_seq, rec_seq_size, GFP_KERNEL);
1961         if (!cctx->rec_seq) {
1962                 rc = -ENOMEM;
1963                 goto free_iv;
1964         }
1965 
1966         if (!*aead) {
1967                 *aead = crypto_alloc_aead("gcm(aes)", 0, 0);
1968                 if (IS_ERR(*aead)) {
1969                         rc = PTR_ERR(*aead);
1970                         *aead = NULL;
1971                         goto free_rec_seq;
1972                 }
1973         }
1974 
1975         ctx->push_pending_record = tls_sw_push_pending_record;
1976 
1977         rc = crypto_aead_setkey(*aead, gcm_128_info->key,
1978                                 TLS_CIPHER_AES_GCM_128_KEY_SIZE);
1979         if (rc)
1980                 goto free_aead;
1981 
1982         rc = crypto_aead_setauthsize(*aead, cctx->tag_size);
1983         if (rc)
1984                 goto free_aead;
1985 
1986         if (sw_ctx_rx) {
1987                 /* Set up strparser */
1988                 memset(&cb, 0, sizeof(cb));
1989                 cb.rcv_msg = tls_queue;
1990                 cb.parse_msg = tls_read_size;
1991 
1992                 strp_init(&sw_ctx_rx->strp, sk, &cb);
1993 
1994                 write_lock_bh(&sk->sk_callback_lock);
1995                 sw_ctx_rx->saved_data_ready = sk->sk_data_ready;
1996                 sk->sk_data_ready = tls_data_ready;
1997                 write_unlock_bh(&sk->sk_callback_lock);
1998 
1999                 strp_check_rcv(&sw_ctx_rx->strp);
2000         }
2001 
2002         goto out;
2003 
2004 free_aead:
2005         crypto_free_aead(*aead);
2006         *aead = NULL;
2007 free_rec_seq:
2008         kfree(cctx->rec_seq);
2009         cctx->rec_seq = NULL;
2010 free_iv:
2011         kfree(cctx->iv);
2012         cctx->iv = NULL;
2013 free_priv:
2014         if (tx) {
2015                 kfree(ctx->priv_ctx_tx);
2016                 ctx->priv_ctx_tx = NULL;
2017         } else {
2018                 kfree(ctx->priv_ctx_rx);
2019                 ctx->priv_ctx_rx = NULL;
2020         }
2021 out:
2022         return rc;
2023 }
2024 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp