]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_ktls.c
Convert route caching to nexthop caching.
[FreeBSD/FreeBSD.git] / sys / kern / uipc_ktls.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2014-2019 Netflix Inc.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 #include "opt_rss.h"
34
35 #include <sys/param.h>
36 #include <sys/kernel.h>
37 #include <sys/ktls.h>
38 #include <sys/lock.h>
39 #include <sys/mbuf.h>
40 #include <sys/mutex.h>
41 #include <sys/rmlock.h>
42 #include <sys/proc.h>
43 #include <sys/protosw.h>
44 #include <sys/refcount.h>
45 #include <sys/smp.h>
46 #include <sys/socket.h>
47 #include <sys/socketvar.h>
48 #include <sys/sysctl.h>
49 #include <sys/taskqueue.h>
50 #include <sys/kthread.h>
51 #include <sys/uio.h>
52 #include <sys/vmmeter.h>
53 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
54 #include <machine/pcb.h>
55 #endif
56 #include <machine/vmparam.h>
57 #include <net/if.h>
58 #include <net/if_var.h>
59 #ifdef RSS
60 #include <net/netisr.h>
61 #include <net/nhop.h>
62 #include <net/rss_config.h>
63 #endif
64 #if defined(INET) || defined(INET6)
65 #include <netinet/in.h>
66 #include <netinet/in_pcb.h>
67 #endif
68 #include <netinet/tcp_var.h>
69 #ifdef TCP_OFFLOAD
70 #include <netinet/tcp_offload.h>
71 #endif
72 #include <opencrypto/xform.h>
73 #include <vm/uma_dbg.h>
74 #include <vm/vm.h>
75 #include <vm/vm_pageout.h>
76 #include <vm/vm_page.h>
77
78 struct ktls_wq {
79         struct mtx      mtx;
80         STAILQ_HEAD(, mbuf_ext_pgs) head;
81         bool            running;
82 } __aligned(CACHE_LINE_SIZE);
83
84 static struct ktls_wq *ktls_wq;
85 static struct proc *ktls_proc;
86 LIST_HEAD(, ktls_crypto_backend) ktls_backends;
87 static struct rmlock ktls_backends_lock;
88 static uma_zone_t ktls_session_zone;
89 static uint16_t ktls_cpuid_lookup[MAXCPU];
90
91 SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
92     "Kernel TLS offload");
93 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
94     "Kernel TLS offload stats");
95
96 static int ktls_allow_unload;
97 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, allow_unload, CTLFLAG_RDTUN,
98     &ktls_allow_unload, 0, "Allow software crypto modules to unload");
99
100 #ifdef RSS
101 static int ktls_bind_threads = 1;
102 #else
103 static int ktls_bind_threads;
104 #endif
105 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
106     &ktls_bind_threads, 0,
107     "Bind crypto threads to cores or domains at boot");
108
109 static u_int ktls_maxlen = 16384;
110 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RWTUN,
111     &ktls_maxlen, 0, "Maximum TLS record size");
112
113 static int ktls_number_threads;
114 SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
115     &ktls_number_threads, 0,
116     "Number of TLS threads in thread-pool");
117
118 static bool ktls_offload_enable;
119 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RW,
120     &ktls_offload_enable, 0,
121     "Enable support for kernel TLS offload");
122
123 static bool ktls_cbc_enable = true;
124 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RW,
125     &ktls_cbc_enable, 1,
126     "Enable Support of AES-CBC crypto for kernel TLS");
127
128 static counter_u64_t ktls_tasks_active;
129 SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
130     &ktls_tasks_active, "Number of active tasks");
131
132 static counter_u64_t ktls_cnt_on;
133 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, so_inqueue, CTLFLAG_RD,
134     &ktls_cnt_on, "Number of TLS records in queue to tasks for SW crypto");
135
136 static counter_u64_t ktls_offload_total;
137 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
138     CTLFLAG_RD, &ktls_offload_total,
139     "Total successful TLS setups (parameters set)");
140
141 static counter_u64_t ktls_offload_enable_calls;
142 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
143     CTLFLAG_RD, &ktls_offload_enable_calls,
144     "Total number of TLS enable calls made");
145
146 static counter_u64_t ktls_offload_active;
147 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
148     &ktls_offload_active, "Total Active TLS sessions");
149
150 static counter_u64_t ktls_offload_failed_crypto;
151 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
152     &ktls_offload_failed_crypto, "Total TLS crypto failures");
153
154 static counter_u64_t ktls_switch_to_ifnet;
155 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
156     &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
157
158 static counter_u64_t ktls_switch_to_sw;
159 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
160     &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
161
162 static counter_u64_t ktls_switch_failed;
163 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
164     &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
165
166 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
167     "Software TLS session stats");
168 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
169     "Hardware (ifnet) TLS session stats");
170 #ifdef TCP_OFFLOAD
171 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
172     "TOE TLS session stats");
173 #endif
174
175 static counter_u64_t ktls_sw_cbc;
176 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
177     "Active number of software TLS sessions using AES-CBC");
178
179 static counter_u64_t ktls_sw_gcm;
180 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
181     "Active number of software TLS sessions using AES-GCM");
182
183 static counter_u64_t ktls_ifnet_cbc;
184 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
185     &ktls_ifnet_cbc,
186     "Active number of ifnet TLS sessions using AES-CBC");
187
188 static counter_u64_t ktls_ifnet_gcm;
189 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
190     &ktls_ifnet_gcm,
191     "Active number of ifnet TLS sessions using AES-GCM");
192
193 static counter_u64_t ktls_ifnet_reset;
194 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
195     &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
196
197 static counter_u64_t ktls_ifnet_reset_dropped;
198 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
199     &ktls_ifnet_reset_dropped,
200     "TLS sessions dropped after failing to update ifnet send tag");
201
202 static counter_u64_t ktls_ifnet_reset_failed;
203 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
204     &ktls_ifnet_reset_failed,
205     "TLS sessions that failed to allocate a new ifnet send tag");
206
207 static int ktls_ifnet_permitted;
208 SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
209     &ktls_ifnet_permitted, 1,
210     "Whether to permit hardware (ifnet) TLS sessions");
211
212 #ifdef TCP_OFFLOAD
213 static counter_u64_t ktls_toe_cbc;
214 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
215     &ktls_toe_cbc,
216     "Active number of TOE TLS sessions using AES-CBC");
217
218 static counter_u64_t ktls_toe_gcm;
219 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
220     &ktls_toe_gcm,
221     "Active number of TOE TLS sessions using AES-GCM");
222 #endif
223
224 static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
225
226 static void ktls_cleanup(struct ktls_session *tls);
227 #if defined(INET) || defined(INET6)
228 static void ktls_reset_send_tag(void *context, int pending);
229 #endif
230 static void ktls_work_thread(void *ctx);
231
232 int
233 ktls_crypto_backend_register(struct ktls_crypto_backend *be)
234 {
235         struct ktls_crypto_backend *curr_be, *tmp;
236
237         if (be->api_version != KTLS_API_VERSION) {
238                 printf("KTLS: API version mismatch (%d vs %d) for %s\n",
239                     be->api_version, KTLS_API_VERSION,
240                     be->name);
241                 return (EINVAL);
242         }
243
244         rm_wlock(&ktls_backends_lock);
245         printf("KTLS: Registering crypto method %s with prio %d\n",
246                be->name, be->prio);
247         if (LIST_EMPTY(&ktls_backends)) {
248                 LIST_INSERT_HEAD(&ktls_backends, be, next);
249         } else {
250                 LIST_FOREACH_SAFE(curr_be, &ktls_backends, next, tmp) {
251                         if (curr_be->prio < be->prio) {
252                                 LIST_INSERT_BEFORE(curr_be, be, next);
253                                 break;
254                         }
255                         if (LIST_NEXT(curr_be, next) == NULL) {
256                                 LIST_INSERT_AFTER(curr_be, be, next);
257                                 break;
258                         }
259                 }
260         }
261         rm_wunlock(&ktls_backends_lock);
262         return (0);
263 }
264
265 int
266 ktls_crypto_backend_deregister(struct ktls_crypto_backend *be)
267 {
268         struct ktls_crypto_backend *tmp;
269
270         /*
271          * Don't error if the backend isn't registered.  This permits
272          * MOD_UNLOAD handlers to use this function unconditionally.
273          */
274         rm_wlock(&ktls_backends_lock);
275         LIST_FOREACH(tmp, &ktls_backends, next) {
276                 if (tmp == be)
277                         break;
278         }
279         if (tmp == NULL) {
280                 rm_wunlock(&ktls_backends_lock);
281                 return (0);
282         }
283
284         if (!ktls_allow_unload) {
285                 rm_wunlock(&ktls_backends_lock);
286                 printf(
287                     "KTLS: Deregistering crypto method %s is not supported\n",
288                     be->name);
289                 return (EBUSY);
290         }
291
292         if (be->use_count) {
293                 rm_wunlock(&ktls_backends_lock);
294                 return (EBUSY);
295         }
296
297         LIST_REMOVE(be, next);
298         rm_wunlock(&ktls_backends_lock);
299         return (0);
300 }
301
302 #if defined(INET) || defined(INET6)
303 static u_int
304 ktls_get_cpu(struct socket *so)
305 {
306         struct inpcb *inp;
307         u_int cpuid;
308
309         inp = sotoinpcb(so);
310 #ifdef RSS
311         cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
312         if (cpuid != NETISR_CPUID_NONE)
313                 return (cpuid);
314 #endif
315         /*
316          * Just use the flowid to shard connections in a repeatable
317          * fashion.  Note that some crypto backends rely on the
318          * serialization provided by having the same connection use
319          * the same queue.
320          */
321         cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
322         return (cpuid);
323 }
324 #endif
325
326 static void
327 ktls_init(void *dummy __unused)
328 {
329         struct thread *td;
330         struct pcpu *pc;
331         cpuset_t mask;
332         int error, i;
333
334         ktls_tasks_active = counter_u64_alloc(M_WAITOK);
335         ktls_cnt_on = counter_u64_alloc(M_WAITOK);
336         ktls_offload_total = counter_u64_alloc(M_WAITOK);
337         ktls_offload_enable_calls = counter_u64_alloc(M_WAITOK);
338         ktls_offload_active = counter_u64_alloc(M_WAITOK);
339         ktls_offload_failed_crypto = counter_u64_alloc(M_WAITOK);
340         ktls_switch_to_ifnet = counter_u64_alloc(M_WAITOK);
341         ktls_switch_to_sw = counter_u64_alloc(M_WAITOK);
342         ktls_switch_failed = counter_u64_alloc(M_WAITOK);
343         ktls_sw_cbc = counter_u64_alloc(M_WAITOK);
344         ktls_sw_gcm = counter_u64_alloc(M_WAITOK);
345         ktls_ifnet_cbc = counter_u64_alloc(M_WAITOK);
346         ktls_ifnet_gcm = counter_u64_alloc(M_WAITOK);
347         ktls_ifnet_reset = counter_u64_alloc(M_WAITOK);
348         ktls_ifnet_reset_dropped = counter_u64_alloc(M_WAITOK);
349         ktls_ifnet_reset_failed = counter_u64_alloc(M_WAITOK);
350 #ifdef TCP_OFFLOAD
351         ktls_toe_cbc = counter_u64_alloc(M_WAITOK);
352         ktls_toe_gcm = counter_u64_alloc(M_WAITOK);
353 #endif
354
355         rm_init(&ktls_backends_lock, "ktls backends");
356         LIST_INIT(&ktls_backends);
357
358         ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
359             M_WAITOK | M_ZERO);
360
361         ktls_session_zone = uma_zcreate("ktls_session",
362             sizeof(struct ktls_session),
363             NULL, NULL, NULL, NULL,
364             UMA_ALIGN_CACHE, 0);
365
366         /*
367          * Initialize the workqueues to run the TLS work.  We create a
368          * work queue for each CPU.
369          */
370         CPU_FOREACH(i) {
371                 STAILQ_INIT(&ktls_wq[i].head);
372                 mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
373                 error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
374                     &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
375                 if (error)
376                         panic("Can't add KTLS thread %d error %d", i, error);
377
378                 /*
379                  * Bind threads to cores.  If ktls_bind_threads is >
380                  * 1, then we bind to the NUMA domain.
381                  */
382                 if (ktls_bind_threads) {
383                         if (ktls_bind_threads > 1) {
384                                 pc = pcpu_find(i);
385                                 CPU_COPY(&cpuset_domain[pc->pc_domain], &mask);
386                         } else {
387                                 CPU_SETOF(i, &mask);
388                         }
389                         error = cpuset_setthread(td->td_tid, &mask);
390                         if (error)
391                                 panic(
392                             "Unable to bind KTLS thread for CPU %d error %d",
393                                      i, error);
394                 }
395                 ktls_cpuid_lookup[ktls_number_threads] = i;
396                 ktls_number_threads++;
397         }
398         printf("KTLS: Initialized %d threads\n", ktls_number_threads);
399 }
400 SYSINIT(ktls, SI_SUB_SMP + 1, SI_ORDER_ANY, ktls_init, NULL);
401
402 #if defined(INET) || defined(INET6)
403 static int
404 ktls_create_session(struct socket *so, struct tls_enable *en,
405     struct ktls_session **tlsp)
406 {
407         struct ktls_session *tls;
408         int error;
409
410         /* Only TLS 1.0 - 1.3 are supported. */
411         if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
412                 return (EINVAL);
413         if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
414             en->tls_vminor > TLS_MINOR_VER_THREE)
415                 return (EINVAL);
416
417         if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
418                 return (EINVAL);
419         if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
420                 return (EINVAL);
421         if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
422                 return (EINVAL);
423
424         /* All supported algorithms require a cipher key. */
425         if (en->cipher_key_len == 0)
426                 return (EINVAL);
427
428         /* No flags are currently supported. */
429         if (en->flags != 0)
430                 return (EINVAL);
431
432         /* Common checks for supported algorithms. */
433         switch (en->cipher_algorithm) {
434         case CRYPTO_AES_NIST_GCM_16:
435                 /*
436                  * auth_algorithm isn't used, but permit GMAC values
437                  * for compatibility.
438                  */
439                 switch (en->auth_algorithm) {
440                 case 0:
441 #ifdef COMPAT_FREEBSD12
442                 /* XXX: Really 13.0-current COMPAT. */
443                 case CRYPTO_AES_128_NIST_GMAC:
444                 case CRYPTO_AES_192_NIST_GMAC:
445                 case CRYPTO_AES_256_NIST_GMAC:
446 #endif
447                         break;
448                 default:
449                         return (EINVAL);
450                 }
451                 if (en->auth_key_len != 0)
452                         return (EINVAL);
453                 if ((en->tls_vminor == TLS_MINOR_VER_TWO &&
454                         en->iv_len != TLS_AEAD_GCM_LEN) ||
455                     (en->tls_vminor == TLS_MINOR_VER_THREE &&
456                         en->iv_len != TLS_1_3_GCM_IV_LEN))
457                         return (EINVAL);
458                 break;
459         case CRYPTO_AES_CBC:
460                 switch (en->auth_algorithm) {
461                 case CRYPTO_SHA1_HMAC:
462                         /*
463                          * TLS 1.0 requires an implicit IV.  TLS 1.1+
464                          * all use explicit IVs.
465                          */
466                         if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
467                                 if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
468                                         return (EINVAL);
469                                 break;
470                         }
471
472                         /* FALLTHROUGH */
473                 case CRYPTO_SHA2_256_HMAC:
474                 case CRYPTO_SHA2_384_HMAC:
475                         /* Ignore any supplied IV. */
476                         en->iv_len = 0;
477                         break;
478                 default:
479                         return (EINVAL);
480                 }
481                 if (en->auth_key_len == 0)
482                         return (EINVAL);
483                 break;
484         default:
485                 return (EINVAL);
486         }
487
488         tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
489
490         counter_u64_add(ktls_offload_active, 1);
491
492         refcount_init(&tls->refcount, 1);
493         TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
494
495         tls->wq_index = ktls_get_cpu(so);
496
497         tls->params.cipher_algorithm = en->cipher_algorithm;
498         tls->params.auth_algorithm = en->auth_algorithm;
499         tls->params.tls_vmajor = en->tls_vmajor;
500         tls->params.tls_vminor = en->tls_vminor;
501         tls->params.flags = en->flags;
502         tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
503
504         /* Set the header and trailer lengths. */
505         tls->params.tls_hlen = sizeof(struct tls_record_layer);
506         switch (en->cipher_algorithm) {
507         case CRYPTO_AES_NIST_GCM_16:
508                 /*
509                  * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
510                  * nonce.  TLS 1.3 uses a 12 byte implicit IV.
511                  */
512                 if (en->tls_vminor < TLS_MINOR_VER_THREE)
513                         tls->params.tls_hlen += sizeof(uint64_t);
514                 tls->params.tls_tlen = AES_GMAC_HASH_LEN;
515
516                 /*
517                  * TLS 1.3 includes optional padding which we
518                  * do not support, and also puts the "real" record
519                  * type at the end of the encrypted data.
520                  */
521                 if (en->tls_vminor == TLS_MINOR_VER_THREE)
522                         tls->params.tls_tlen += sizeof(uint8_t);
523
524                 tls->params.tls_bs = 1;
525                 break;
526         case CRYPTO_AES_CBC:
527                 switch (en->auth_algorithm) {
528                 case CRYPTO_SHA1_HMAC:
529                         if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
530                                 /* Implicit IV, no nonce. */
531                         } else {
532                                 tls->params.tls_hlen += AES_BLOCK_LEN;
533                         }
534                         tls->params.tls_tlen = AES_BLOCK_LEN +
535                             SHA1_HASH_LEN;
536                         break;
537                 case CRYPTO_SHA2_256_HMAC:
538                         tls->params.tls_hlen += AES_BLOCK_LEN;
539                         tls->params.tls_tlen = AES_BLOCK_LEN +
540                             SHA2_256_HASH_LEN;
541                         break;
542                 case CRYPTO_SHA2_384_HMAC:
543                         tls->params.tls_hlen += AES_BLOCK_LEN;
544                         tls->params.tls_tlen = AES_BLOCK_LEN +
545                             SHA2_384_HASH_LEN;
546                         break;
547                 default:
548                         panic("invalid hmac");
549                 }
550                 tls->params.tls_bs = AES_BLOCK_LEN;
551                 break;
552         default:
553                 panic("invalid cipher");
554         }
555
556         KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
557             ("TLS header length too long: %d", tls->params.tls_hlen));
558         KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
559             ("TLS trailer length too long: %d", tls->params.tls_tlen));
560
561         if (en->auth_key_len != 0) {
562                 tls->params.auth_key_len = en->auth_key_len;
563                 tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
564                     M_WAITOK);
565                 error = copyin(en->auth_key, tls->params.auth_key,
566                     en->auth_key_len);
567                 if (error)
568                         goto out;
569         }
570
571         tls->params.cipher_key_len = en->cipher_key_len;
572         tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
573         error = copyin(en->cipher_key, tls->params.cipher_key,
574             en->cipher_key_len);
575         if (error)
576                 goto out;
577
578         /*
579          * This holds the implicit portion of the nonce for GCM and
580          * the initial implicit IV for TLS 1.0.  The explicit portions
581          * of the IV are generated in ktls_frame().
582          */
583         if (en->iv_len != 0) {
584                 tls->params.iv_len = en->iv_len;
585                 error = copyin(en->iv, tls->params.iv, en->iv_len);
586                 if (error)
587                         goto out;
588
589                 /*
590                  * For TLS 1.2, generate an 8-byte nonce as a counter
591                  * to generate unique explicit IVs.
592                  *
593                  * Store this counter in the last 8 bytes of the IV
594                  * array so that it is 8-byte aligned.
595                  */
596                 if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
597                     en->tls_vminor == TLS_MINOR_VER_TWO)
598                         arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
599         }
600
601         *tlsp = tls;
602         return (0);
603
604 out:
605         ktls_cleanup(tls);
606         return (error);
607 }
608
609 static struct ktls_session *
610 ktls_clone_session(struct ktls_session *tls)
611 {
612         struct ktls_session *tls_new;
613
614         tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
615
616         counter_u64_add(ktls_offload_active, 1);
617
618         refcount_init(&tls_new->refcount, 1);
619
620         /* Copy fields from existing session. */
621         tls_new->params = tls->params;
622         tls_new->wq_index = tls->wq_index;
623
624         /* Deep copy keys. */
625         if (tls_new->params.auth_key != NULL) {
626                 tls_new->params.auth_key = malloc(tls->params.auth_key_len,
627                     M_KTLS, M_WAITOK);
628                 memcpy(tls_new->params.auth_key, tls->params.auth_key,
629                     tls->params.auth_key_len);
630         }
631
632         tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
633             M_WAITOK);
634         memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
635             tls->params.cipher_key_len);
636
637         return (tls_new);
638 }
639 #endif
640
641 static void
642 ktls_cleanup(struct ktls_session *tls)
643 {
644
645         counter_u64_add(ktls_offload_active, -1);
646         switch (tls->mode) {
647         case TCP_TLS_MODE_SW:
648                 MPASS(tls->be != NULL);
649                 switch (tls->params.cipher_algorithm) {
650                 case CRYPTO_AES_CBC:
651                         counter_u64_add(ktls_sw_cbc, -1);
652                         break;
653                 case CRYPTO_AES_NIST_GCM_16:
654                         counter_u64_add(ktls_sw_gcm, -1);
655                         break;
656                 }
657                 tls->free(tls);
658                 break;
659         case TCP_TLS_MODE_IFNET:
660                 switch (tls->params.cipher_algorithm) {
661                 case CRYPTO_AES_CBC:
662                         counter_u64_add(ktls_ifnet_cbc, -1);
663                         break;
664                 case CRYPTO_AES_NIST_GCM_16:
665                         counter_u64_add(ktls_ifnet_gcm, -1);
666                         break;
667                 }
668                 m_snd_tag_rele(tls->snd_tag);
669                 break;
670 #ifdef TCP_OFFLOAD
671         case TCP_TLS_MODE_TOE:
672                 switch (tls->params.cipher_algorithm) {
673                 case CRYPTO_AES_CBC:
674                         counter_u64_add(ktls_toe_cbc, -1);
675                         break;
676                 case CRYPTO_AES_NIST_GCM_16:
677                         counter_u64_add(ktls_toe_gcm, -1);
678                         break;
679                 }
680                 break;
681 #endif
682         }
683         if (tls->params.auth_key != NULL) {
684                 explicit_bzero(tls->params.auth_key, tls->params.auth_key_len);
685                 free(tls->params.auth_key, M_KTLS);
686                 tls->params.auth_key = NULL;
687                 tls->params.auth_key_len = 0;
688         }
689         if (tls->params.cipher_key != NULL) {
690                 explicit_bzero(tls->params.cipher_key,
691                     tls->params.cipher_key_len);
692                 free(tls->params.cipher_key, M_KTLS);
693                 tls->params.cipher_key = NULL;
694                 tls->params.cipher_key_len = 0;
695         }
696         explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
697 }
698
699 #if defined(INET) || defined(INET6)
700
701 #ifdef TCP_OFFLOAD
702 static int
703 ktls_try_toe(struct socket *so, struct ktls_session *tls)
704 {
705         struct inpcb *inp;
706         struct tcpcb *tp;
707         int error;
708
709         inp = so->so_pcb;
710         INP_WLOCK(inp);
711         if (inp->inp_flags2 & INP_FREED) {
712                 INP_WUNLOCK(inp);
713                 return (ECONNRESET);
714         }
715         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
716                 INP_WUNLOCK(inp);
717                 return (ECONNRESET);
718         }
719         if (inp->inp_socket == NULL) {
720                 INP_WUNLOCK(inp);
721                 return (ECONNRESET);
722         }
723         tp = intotcpcb(inp);
724         if (tp->tod == NULL) {
725                 INP_WUNLOCK(inp);
726                 return (EOPNOTSUPP);
727         }
728
729         error = tcp_offload_alloc_tls_session(tp, tls);
730         INP_WUNLOCK(inp);
731         if (error == 0) {
732                 tls->mode = TCP_TLS_MODE_TOE;
733                 switch (tls->params.cipher_algorithm) {
734                 case CRYPTO_AES_CBC:
735                         counter_u64_add(ktls_toe_cbc, 1);
736                         break;
737                 case CRYPTO_AES_NIST_GCM_16:
738                         counter_u64_add(ktls_toe_gcm, 1);
739                         break;
740                 }
741         }
742         return (error);
743 }
744 #endif
745
746 /*
747  * Common code used when first enabling ifnet TLS on a connection or
748  * when allocating a new ifnet TLS session due to a routing change.
749  * This function allocates a new TLS send tag on whatever interface
750  * the connection is currently routed over.
751  */
752 static int
753 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
754     struct m_snd_tag **mstp)
755 {
756         union if_snd_tag_alloc_params params;
757         struct ifnet *ifp;
758         struct nhop_object *nh;
759         struct tcpcb *tp;
760         int error;
761
762         INP_RLOCK(inp);
763         if (inp->inp_flags2 & INP_FREED) {
764                 INP_RUNLOCK(inp);
765                 return (ECONNRESET);
766         }
767         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
768                 INP_RUNLOCK(inp);
769                 return (ECONNRESET);
770         }
771         if (inp->inp_socket == NULL) {
772                 INP_RUNLOCK(inp);
773                 return (ECONNRESET);
774         }
775         tp = intotcpcb(inp);
776
777         /*
778          * Check administrative controls on ifnet TLS to determine if
779          * ifnet TLS should be denied.
780          *
781          * - Always permit 'force' requests.
782          * - ktls_ifnet_permitted == 0: always deny.
783          */
784         if (!force && ktls_ifnet_permitted == 0) {
785                 INP_RUNLOCK(inp);
786                 return (ENXIO);
787         }
788
789         /*
790          * XXX: Use the cached route in the inpcb to find the
791          * interface.  This should perhaps instead use
792          * rtalloc1_fib(dst, 0, 0, fibnum).  Since KTLS is only
793          * enabled after a connection has completed key negotiation in
794          * userland, the cached route will be present in practice.
795          */
796         nh = inp->inp_route.ro_nh;
797         if (nh == NULL) {
798                 INP_RUNLOCK(inp);
799                 return (ENXIO);
800         }
801         ifp = nh->nh_ifp;
802         if_ref(ifp);
803
804         params.hdr.type = IF_SND_TAG_TYPE_TLS;
805         params.hdr.flowid = inp->inp_flowid;
806         params.hdr.flowtype = inp->inp_flowtype;
807         params.hdr.numa_domain = inp->inp_numa_domain;
808         params.tls.inp = inp;
809         params.tls.tls = tls;
810         INP_RUNLOCK(inp);
811
812         if (ifp->if_snd_tag_alloc == NULL) {
813                 error = EOPNOTSUPP;
814                 goto out;
815         }
816         if ((ifp->if_capenable & IFCAP_NOMAP) == 0) {   
817                 error = EOPNOTSUPP;
818                 goto out;
819         }
820         if (inp->inp_vflag & INP_IPV6) {
821                 if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
822                         error = EOPNOTSUPP;
823                         goto out;
824                 }
825         } else {
826                 if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
827                         error = EOPNOTSUPP;
828                         goto out;
829                 }
830         }
831         error = ifp->if_snd_tag_alloc(ifp, &params, mstp);
832 out:
833         if_rele(ifp);
834         return (error);
835 }
836
837 static int
838 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
839 {
840         struct m_snd_tag *mst;
841         int error;
842
843         error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
844         if (error == 0) {
845                 tls->mode = TCP_TLS_MODE_IFNET;
846                 tls->snd_tag = mst;
847                 switch (tls->params.cipher_algorithm) {
848                 case CRYPTO_AES_CBC:
849                         counter_u64_add(ktls_ifnet_cbc, 1);
850                         break;
851                 case CRYPTO_AES_NIST_GCM_16:
852                         counter_u64_add(ktls_ifnet_gcm, 1);
853                         break;
854                 }
855         }
856         return (error);
857 }
858
859 static int
860 ktls_try_sw(struct socket *so, struct ktls_session *tls)
861 {
862         struct rm_priotracker prio;
863         struct ktls_crypto_backend *be;
864
865         /*
866          * Choose the best software crypto backend.  Backends are
867          * stored in sorted priority order (larget value == most
868          * important at the head of the list), so this just stops on
869          * the first backend that claims the session by returning
870          * success.
871          */
872         if (ktls_allow_unload)
873                 rm_rlock(&ktls_backends_lock, &prio);
874         LIST_FOREACH(be, &ktls_backends, next) {
875                 if (be->try(so, tls) == 0)
876                         break;
877                 KASSERT(tls->cipher == NULL,
878                     ("ktls backend leaked a cipher pointer"));
879         }
880         if (be != NULL) {
881                 if (ktls_allow_unload)
882                         be->use_count++;
883                 tls->be = be;
884         }
885         if (ktls_allow_unload)
886                 rm_runlock(&ktls_backends_lock, &prio);
887         if (be == NULL)
888                 return (EOPNOTSUPP);
889         tls->mode = TCP_TLS_MODE_SW;
890         switch (tls->params.cipher_algorithm) {
891         case CRYPTO_AES_CBC:
892                 counter_u64_add(ktls_sw_cbc, 1);
893                 break;
894         case CRYPTO_AES_NIST_GCM_16:
895                 counter_u64_add(ktls_sw_gcm, 1);
896                 break;
897         }
898         return (0);
899 }
900
901 int
902 ktls_enable_tx(struct socket *so, struct tls_enable *en)
903 {
904         struct ktls_session *tls;
905         int error;
906
907         if (!ktls_offload_enable)
908                 return (ENOTSUP);
909
910         counter_u64_add(ktls_offload_enable_calls, 1);
911
912         /*
913          * This should always be true since only the TCP socket option
914          * invokes this function.
915          */
916         if (so->so_proto->pr_protocol != IPPROTO_TCP)
917                 return (EINVAL);
918
919         /*
920          * XXX: Don't overwrite existing sessions.  We should permit
921          * this to support rekeying in the future.
922          */
923         if (so->so_snd.sb_tls_info != NULL)
924                 return (EALREADY);
925
926         if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
927                 return (ENOTSUP);
928
929         /* TLS requires ext pgs */
930         if (mb_use_ext_pgs == 0)
931                 return (ENXIO);
932
933         error = ktls_create_session(so, en, &tls);
934         if (error)
935                 return (error);
936
937         /* Prefer TOE -> ifnet TLS -> software TLS. */
938 #ifdef TCP_OFFLOAD
939         error = ktls_try_toe(so, tls);
940         if (error)
941 #endif
942                 error = ktls_try_ifnet(so, tls, false);
943         if (error)
944                 error = ktls_try_sw(so, tls);
945
946         if (error) {
947                 ktls_cleanup(tls);
948                 return (error);
949         }
950
951         error = sblock(&so->so_snd, SBL_WAIT);
952         if (error) {
953                 ktls_cleanup(tls);
954                 return (error);
955         }
956
957         SOCKBUF_LOCK(&so->so_snd);
958         so->so_snd.sb_tls_info = tls;
959         if (tls->mode != TCP_TLS_MODE_SW)
960                 so->so_snd.sb_flags |= SB_TLS_IFNET;
961         SOCKBUF_UNLOCK(&so->so_snd);
962         sbunlock(&so->so_snd);
963
964         counter_u64_add(ktls_offload_total, 1);
965
966         return (0);
967 }
968
969 int
970 ktls_get_tx_mode(struct socket *so)
971 {
972         struct ktls_session *tls;
973         struct inpcb *inp;
974         int mode;
975
976         inp = so->so_pcb;
977         INP_WLOCK_ASSERT(inp);
978         SOCKBUF_LOCK(&so->so_snd);
979         tls = so->so_snd.sb_tls_info;
980         if (tls == NULL)
981                 mode = TCP_TLS_MODE_NONE;
982         else
983                 mode = tls->mode;
984         SOCKBUF_UNLOCK(&so->so_snd);
985         return (mode);
986 }
987
988 /*
989  * Switch between SW and ifnet TLS sessions as requested.
990  */
991 int
992 ktls_set_tx_mode(struct socket *so, int mode)
993 {
994         struct ktls_session *tls, *tls_new;
995         struct inpcb *inp;
996         int error;
997
998         switch (mode) {
999         case TCP_TLS_MODE_SW:
1000         case TCP_TLS_MODE_IFNET:
1001                 break;
1002         default:
1003                 return (EINVAL);
1004         }
1005
1006         inp = so->so_pcb;
1007         INP_WLOCK_ASSERT(inp);
1008         SOCKBUF_LOCK(&so->so_snd);
1009         tls = so->so_snd.sb_tls_info;
1010         if (tls == NULL) {
1011                 SOCKBUF_UNLOCK(&so->so_snd);
1012                 return (0);
1013         }
1014
1015         if (tls->mode == mode) {
1016                 SOCKBUF_UNLOCK(&so->so_snd);
1017                 return (0);
1018         }
1019
1020         tls = ktls_hold(tls);
1021         SOCKBUF_UNLOCK(&so->so_snd);
1022         INP_WUNLOCK(inp);
1023
1024         tls_new = ktls_clone_session(tls);
1025
1026         if (mode == TCP_TLS_MODE_IFNET)
1027                 error = ktls_try_ifnet(so, tls_new, true);
1028         else
1029                 error = ktls_try_sw(so, tls_new);
1030         if (error) {
1031                 counter_u64_add(ktls_switch_failed, 1);
1032                 ktls_free(tls_new);
1033                 ktls_free(tls);
1034                 INP_WLOCK(inp);
1035                 return (error);
1036         }
1037
1038         error = sblock(&so->so_snd, SBL_WAIT);
1039         if (error) {
1040                 counter_u64_add(ktls_switch_failed, 1);
1041                 ktls_free(tls_new);
1042                 ktls_free(tls);
1043                 INP_WLOCK(inp);
1044                 return (error);
1045         }
1046
1047         /*
1048          * If we raced with another session change, keep the existing
1049          * session.
1050          */
1051         if (tls != so->so_snd.sb_tls_info) {
1052                 counter_u64_add(ktls_switch_failed, 1);
1053                 sbunlock(&so->so_snd);
1054                 ktls_free(tls_new);
1055                 ktls_free(tls);
1056                 INP_WLOCK(inp);
1057                 return (EBUSY);
1058         }
1059
1060         SOCKBUF_LOCK(&so->so_snd);
1061         so->so_snd.sb_tls_info = tls_new;
1062         if (tls_new->mode != TCP_TLS_MODE_SW)
1063                 so->so_snd.sb_flags |= SB_TLS_IFNET;
1064         SOCKBUF_UNLOCK(&so->so_snd);
1065         sbunlock(&so->so_snd);
1066
1067         /*
1068          * Drop two references on 'tls'.  The first is for the
1069          * ktls_hold() above.  The second drops the reference from the
1070          * socket buffer.
1071          */
1072         KASSERT(tls->refcount >= 2, ("too few references on old session"));
1073         ktls_free(tls);
1074         ktls_free(tls);
1075
1076         if (mode == TCP_TLS_MODE_IFNET)
1077                 counter_u64_add(ktls_switch_to_ifnet, 1);
1078         else
1079                 counter_u64_add(ktls_switch_to_sw, 1);
1080
1081         INP_WLOCK(inp);
1082         return (0);
1083 }
1084
1085 /*
1086  * Try to allocate a new TLS send tag.  This task is scheduled when
1087  * ip_output detects a route change while trying to transmit a packet
1088  * holding a TLS record.  If a new tag is allocated, replace the tag
1089  * in the TLS session.  Subsequent packets on the connection will use
1090  * the new tag.  If a new tag cannot be allocated, drop the
1091  * connection.
1092  */
1093 static void
1094 ktls_reset_send_tag(void *context, int pending)
1095 {
1096         struct epoch_tracker et;
1097         struct ktls_session *tls;
1098         struct m_snd_tag *old, *new;
1099         struct inpcb *inp;
1100         struct tcpcb *tp;
1101         int error;
1102
1103         MPASS(pending == 1);
1104
1105         tls = context;
1106         inp = tls->inp;
1107
1108         /*
1109          * Free the old tag first before allocating a new one.
1110          * ip[6]_output_send() will treat a NULL send tag the same as
1111          * an ifp mismatch and drop packets until a new tag is
1112          * allocated.
1113          *
1114          * Write-lock the INP when changing tls->snd_tag since
1115          * ip[6]_output_send() holds a read-lock when reading the
1116          * pointer.
1117          */
1118         INP_WLOCK(inp);
1119         old = tls->snd_tag;
1120         tls->snd_tag = NULL;
1121         INP_WUNLOCK(inp);
1122         if (old != NULL)
1123                 m_snd_tag_rele(old);
1124
1125         error = ktls_alloc_snd_tag(inp, tls, true, &new);
1126
1127         if (error == 0) {
1128                 INP_WLOCK(inp);
1129                 tls->snd_tag = new;
1130                 mtx_pool_lock(mtxpool_sleep, tls);
1131                 tls->reset_pending = false;
1132                 mtx_pool_unlock(mtxpool_sleep, tls);
1133                 if (!in_pcbrele_wlocked(inp))
1134                         INP_WUNLOCK(inp);
1135
1136                 counter_u64_add(ktls_ifnet_reset, 1);
1137
1138                 /*
1139                  * XXX: Should we kick tcp_output explicitly now that
1140                  * the send tag is fixed or just rely on timers?
1141                  */
1142         } else {
1143                 NET_EPOCH_ENTER(et);
1144                 INP_WLOCK(inp);
1145                 if (!in_pcbrele_wlocked(inp)) {
1146                         if (!(inp->inp_flags & INP_TIMEWAIT) &&
1147                             !(inp->inp_flags & INP_DROPPED)) {
1148                                 tp = intotcpcb(inp);
1149                                 CURVNET_SET(tp->t_vnet);
1150                                 tp = tcp_drop(tp, ECONNABORTED);
1151                                 CURVNET_RESTORE();
1152                                 if (tp != NULL)
1153                                         INP_WUNLOCK(inp);
1154                                 counter_u64_add(ktls_ifnet_reset_dropped, 1);
1155                         } else
1156                                 INP_WUNLOCK(inp);
1157                 }
1158                 NET_EPOCH_EXIT(et);
1159
1160                 counter_u64_add(ktls_ifnet_reset_failed, 1);
1161
1162                 /*
1163                  * Leave reset_pending true to avoid future tasks while
1164                  * the socket goes away.
1165                  */
1166         }
1167
1168         ktls_free(tls);
1169 }
1170
1171 int
1172 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1173 {
1174
1175         if (inp == NULL)
1176                 return (ENOBUFS);
1177
1178         INP_LOCK_ASSERT(inp);
1179
1180         /*
1181          * See if we should schedule a task to update the send tag for
1182          * this session.
1183          */
1184         mtx_pool_lock(mtxpool_sleep, tls);
1185         if (!tls->reset_pending) {
1186                 (void) ktls_hold(tls);
1187                 in_pcbref(inp);
1188                 tls->inp = inp;
1189                 tls->reset_pending = true;
1190                 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1191         }
1192         mtx_pool_unlock(mtxpool_sleep, tls);
1193         return (ENOBUFS);
1194 }
1195 #endif
1196
1197 void
1198 ktls_destroy(struct ktls_session *tls)
1199 {
1200         struct rm_priotracker prio;
1201
1202         ktls_cleanup(tls);
1203         if (tls->be != NULL && ktls_allow_unload) {
1204                 rm_rlock(&ktls_backends_lock, &prio);
1205                 tls->be->use_count--;
1206                 rm_runlock(&ktls_backends_lock, &prio);
1207         }
1208         uma_zfree(ktls_session_zone, tls);
1209 }
1210
1211 void
1212 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1213 {
1214         struct mbuf_ext_pgs *pgs;
1215
1216         for (; m != NULL; m = m->m_next) {
1217                 KASSERT((m->m_flags & M_NOMAP) != 0,
1218                     ("ktls_seq: mapped mbuf %p", m));
1219
1220                 pgs = &m->m_ext_pgs;
1221                 pgs->seqno = sb->sb_tls_seqno;
1222                 sb->sb_tls_seqno++;
1223         }
1224 }
1225
1226 /*
1227  * Add TLS framing (headers and trailers) to a chain of mbufs.  Each
1228  * mbuf in the chain must be an unmapped mbuf.  The payload of the
1229  * mbuf must be populated with the payload of each TLS record.
1230  *
1231  * The record_type argument specifies the TLS record type used when
1232  * populating the TLS header.
1233  *
1234  * The enq_count argument on return is set to the number of pages of
1235  * payload data for this entire chain that need to be encrypted via SW
1236  * encryption.  The returned value should be passed to ktls_enqueue
1237  * when scheduling encryption of this chain of mbufs.
1238  */
1239 void
1240 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1241     uint8_t record_type)
1242 {
1243         struct tls_record_layer *tlshdr;
1244         struct mbuf *m;
1245         struct mbuf_ext_pgs *pgs;
1246         uint64_t *noncep;
1247         uint16_t tls_len;
1248         int maxlen;
1249
1250         maxlen = tls->params.max_frame_len;
1251         *enq_cnt = 0;
1252         for (m = top; m != NULL; m = m->m_next) {
1253                 /*
1254                  * All mbufs in the chain should be non-empty TLS
1255                  * records whose payload does not exceed the maximum
1256                  * frame length.
1257                  */
1258                 KASSERT(m->m_len <= maxlen && m->m_len > 0,
1259                     ("ktls_frame: m %p len %d\n", m, m->m_len));
1260                 /*
1261                  * TLS frames require unmapped mbufs to store session
1262                  * info.
1263                  */
1264                 KASSERT((m->m_flags & M_NOMAP) != 0,
1265                     ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1266
1267                 tls_len = m->m_len;
1268                 pgs = &m->m_ext_pgs;
1269
1270                 /* Save a reference to the session. */
1271                 pgs->tls = ktls_hold(tls);
1272
1273                 pgs->hdr_len = tls->params.tls_hlen;
1274                 pgs->trail_len = tls->params.tls_tlen;
1275                 if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1276                         int bs, delta;
1277
1278                         /*
1279                          * AES-CBC pads messages to a multiple of the
1280                          * block size.  Note that the padding is
1281                          * applied after the digest and the encryption
1282                          * is done on the "plaintext || mac || padding".
1283                          * At least one byte of padding is always
1284                          * present.
1285                          *
1286                          * Compute the final trailer length assuming
1287                          * at most one block of padding.
1288                          * tls->params.sb_tls_tlen is the maximum
1289                          * possible trailer length (padding + digest).
1290                          * delta holds the number of excess padding
1291                          * bytes if the maximum were used.  Those
1292                          * extra bytes are removed.
1293                          */
1294                         bs = tls->params.tls_bs;
1295                         delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
1296                         pgs->trail_len -= delta;
1297                 }
1298                 m->m_len += pgs->hdr_len + pgs->trail_len;
1299
1300                 /* Populate the TLS header. */
1301                 tlshdr = (void *)pgs->m_epg_hdr;
1302                 tlshdr->tls_vmajor = tls->params.tls_vmajor;
1303
1304                 /*
1305                  * TLS 1.3 masquarades as TLS 1.2 with a record type
1306                  * of TLS_RLTYPE_APP.
1307                  */
1308                 if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
1309                     tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
1310                         tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
1311                         tlshdr->tls_type = TLS_RLTYPE_APP;
1312                         /* save the real record type for later */
1313                         pgs->record_type = record_type;
1314                         pgs->m_epg_trail[0] = record_type;
1315                 } else {
1316                         tlshdr->tls_vminor = tls->params.tls_vminor;
1317                         tlshdr->tls_type = record_type;
1318                 }
1319                 tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1320
1321                 /*
1322                  * Store nonces / explicit IVs after the end of the
1323                  * TLS header.
1324                  *
1325                  * For GCM with TLS 1.2, an 8 byte nonce is copied
1326                  * from the end of the IV.  The nonce is then
1327                  * incremented for use by the next record.
1328                  *
1329                  * For CBC, a random nonce is inserted for TLS 1.1+.
1330                  */
1331                 if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
1332                     tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
1333                         noncep = (uint64_t *)(tls->params.iv + 8);
1334                         be64enc(tlshdr + 1, *noncep);
1335                         (*noncep)++;
1336                 } else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
1337                     tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
1338                         arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
1339
1340                 /*
1341                  * When using SW encryption, mark the mbuf not ready.
1342                  * It will be marked ready via sbready() after the
1343                  * record has been encrypted.
1344                  *
1345                  * When using ifnet TLS, unencrypted TLS records are
1346                  * sent down the stack to the NIC.
1347                  */
1348                 if (tls->mode == TCP_TLS_MODE_SW) {
1349                         m->m_flags |= M_NOTREADY;
1350                         pgs->nrdy = pgs->npgs;
1351                         *enq_cnt += pgs->npgs;
1352                 }
1353         }
1354 }
1355
1356 void
1357 ktls_enqueue_to_free(struct mbuf_ext_pgs *pgs)
1358 {
1359         struct ktls_wq *wq;
1360         bool running;
1361
1362         /* Mark it for freeing. */
1363         pgs->mbuf = NULL;
1364         wq = &ktls_wq[pgs->tls->wq_index];
1365         mtx_lock(&wq->mtx);
1366         STAILQ_INSERT_TAIL(&wq->head, pgs, stailq);
1367         running = wq->running;
1368         mtx_unlock(&wq->mtx);
1369         if (!running)
1370                 wakeup(wq);
1371 }
1372
1373 void
1374 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
1375 {
1376         struct mbuf_ext_pgs *pgs;
1377         struct ktls_wq *wq;
1378         bool running;
1379
1380         KASSERT(((m->m_flags & (M_NOMAP | M_NOTREADY)) ==
1381             (M_NOMAP | M_NOTREADY)),
1382             ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
1383         KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
1384
1385         pgs = &m->m_ext_pgs;
1386
1387         KASSERT(pgs->tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
1388
1389         pgs->enc_cnt = page_count;
1390         pgs->mbuf = m;
1391
1392         /*
1393          * Save a pointer to the socket.  The caller is responsible
1394          * for taking an additional reference via soref().
1395          */
1396         pgs->so = so;
1397
1398         wq = &ktls_wq[pgs->tls->wq_index];
1399         mtx_lock(&wq->mtx);
1400         STAILQ_INSERT_TAIL(&wq->head, pgs, stailq);
1401         running = wq->running;
1402         mtx_unlock(&wq->mtx);
1403         if (!running)
1404                 wakeup(wq);
1405         counter_u64_add(ktls_cnt_on, 1);
1406 }
1407
1408 static __noinline void
1409 ktls_encrypt(struct mbuf_ext_pgs *pgs)
1410 {
1411         struct ktls_session *tls;
1412         struct socket *so;
1413         struct mbuf *m, *top;
1414         vm_paddr_t parray[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1415         struct iovec src_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1416         struct iovec dst_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1417         vm_page_t pg;
1418         int error, i, len, npages, off, total_pages;
1419         bool is_anon;
1420
1421         so = pgs->so;
1422         tls = pgs->tls;
1423         top = pgs->mbuf;
1424         KASSERT(tls != NULL, ("tls = NULL, top = %p, pgs = %p\n", top, pgs));
1425         KASSERT(so != NULL, ("so = NULL, top = %p, pgs = %p\n", top, pgs));
1426 #ifdef INVARIANTS
1427         pgs->so = NULL;
1428         pgs->mbuf = NULL;
1429 #endif
1430         total_pages = pgs->enc_cnt;
1431         npages = 0;
1432
1433         /*
1434          * Encrypt the TLS records in the chain of mbufs starting with
1435          * 'top'.  'total_pages' gives us a total count of pages and is
1436          * used to know when we have finished encrypting the TLS
1437          * records originally queued with 'top'.
1438          *
1439          * NB: These mbufs are queued in the socket buffer and
1440          * 'm_next' is traversing the mbufs in the socket buffer.  The
1441          * socket buffer lock is not held while traversing this chain.
1442          * Since the mbufs are all marked M_NOTREADY their 'm_next'
1443          * pointers should be stable.  However, the 'm_next' of the
1444          * last mbuf encrypted is not necessarily NULL.  It can point
1445          * to other mbufs appended while 'top' was on the TLS work
1446          * queue.
1447          *
1448          * Each mbuf holds an entire TLS record.
1449          */
1450         error = 0;
1451         for (m = top; npages != total_pages; m = m->m_next) {
1452                 pgs = &m->m_ext_pgs;
1453
1454                 KASSERT(pgs->tls == tls,
1455                     ("different TLS sessions in a single mbuf chain: %p vs %p",
1456                     tls, pgs->tls));
1457                 KASSERT((m->m_flags & (M_NOMAP | M_NOTREADY)) ==
1458                     (M_NOMAP | M_NOTREADY),
1459                     ("%p not unready & nomap mbuf (top = %p)\n", m, top));
1460                 KASSERT(npages + pgs->npgs <= total_pages,
1461                     ("page count mismatch: top %p, total_pages %d, m %p", top,
1462                     total_pages, m));
1463
1464                 /*
1465                  * Generate source and destination ivoecs to pass to
1466                  * the SW encryption backend.  For writable mbufs, the
1467                  * destination iovec is a copy of the source and
1468                  * encryption is done in place.  For file-backed mbufs
1469                  * (from sendfile), anonymous wired pages are
1470                  * allocated and assigned to the destination iovec.
1471                  */
1472                 is_anon = (pgs->flags & MBUF_PEXT_FLAG_ANON) != 0;
1473
1474                 off = pgs->first_pg_off;
1475                 for (i = 0; i < pgs->npgs; i++, off = 0) {
1476                         len = mbuf_ext_pg_len(pgs, i, off);
1477                         src_iov[i].iov_len = len;
1478                         src_iov[i].iov_base =
1479                             (char *)(void *)PHYS_TO_DMAP(pgs->m_epg_pa[i]) +
1480                                 off;
1481
1482                         if (is_anon) {
1483                                 dst_iov[i].iov_base = src_iov[i].iov_base;
1484                                 dst_iov[i].iov_len = src_iov[i].iov_len;
1485                                 continue;
1486                         }
1487 retry_page:
1488                         pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
1489                             VM_ALLOC_NOOBJ | VM_ALLOC_NODUMP | VM_ALLOC_WIRED);
1490                         if (pg == NULL) {
1491                                 vm_wait(NULL);
1492                                 goto retry_page;
1493                         }
1494                         parray[i] = VM_PAGE_TO_PHYS(pg);
1495                         dst_iov[i].iov_base =
1496                             (char *)(void *)PHYS_TO_DMAP(parray[i]) + off;
1497                         dst_iov[i].iov_len = len;
1498                 }
1499
1500                 npages += i;
1501
1502                 error = (*tls->sw_encrypt)(tls,
1503                     (const struct tls_record_layer *)pgs->m_epg_hdr,
1504                     pgs->m_epg_trail, src_iov, dst_iov, i, pgs->seqno,
1505                     pgs->record_type);
1506                 if (error) {
1507                         counter_u64_add(ktls_offload_failed_crypto, 1);
1508                         break;
1509                 }
1510
1511                 /*
1512                  * For file-backed mbufs, release the file-backed
1513                  * pages and replace them in the ext_pgs array with
1514                  * the anonymous wired pages allocated above.
1515                  */
1516                 if (!is_anon) {
1517                         /* Free the old pages. */
1518                         m->m_ext.ext_free(m);
1519
1520                         /* Replace them with the new pages. */
1521                         for (i = 0; i < pgs->npgs; i++)
1522                                 pgs->m_epg_pa[i] = parray[i];
1523
1524                         /* Use the basic free routine. */
1525                         m->m_ext.ext_free = mb_free_mext_pgs;
1526
1527                         /* Pages are now writable. */
1528                         pgs->flags |= MBUF_PEXT_FLAG_ANON;
1529                 }
1530
1531                 /*
1532                  * Drop a reference to the session now that it is no
1533                  * longer needed.  Existing code depends on encrypted
1534                  * records having no associated session vs
1535                  * yet-to-be-encrypted records having an associated
1536                  * session.
1537                  */
1538                 pgs->tls = NULL;
1539                 ktls_free(tls);
1540         }
1541
1542         CURVNET_SET(so->so_vnet);
1543         if (error == 0) {
1544                 (void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
1545         } else {
1546                 so->so_proto->pr_usrreqs->pru_abort(so);
1547                 so->so_error = EIO;
1548                 mb_free_notready(top, total_pages);
1549         }
1550
1551         SOCK_LOCK(so);
1552         sorele(so);
1553         CURVNET_RESTORE();
1554 }
1555
1556 static void
1557 ktls_work_thread(void *ctx)
1558 {
1559         struct ktls_wq *wq = ctx;
1560         struct mbuf_ext_pgs *p, *n;
1561         struct ktls_session *tls;
1562         struct mbuf *m;
1563         STAILQ_HEAD(, mbuf_ext_pgs) local_head;
1564
1565 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
1566         fpu_kern_thread(0);
1567 #endif
1568         for (;;) {
1569                 mtx_lock(&wq->mtx);
1570                 while (STAILQ_EMPTY(&wq->head)) {
1571                         wq->running = false;
1572                         mtx_sleep(wq, &wq->mtx, 0, "-", 0);
1573                         wq->running = true;
1574                 }
1575
1576                 STAILQ_INIT(&local_head);
1577                 STAILQ_CONCAT(&local_head, &wq->head);
1578                 mtx_unlock(&wq->mtx);
1579
1580                 STAILQ_FOREACH_SAFE(p, &local_head, stailq, n) {
1581                         if (p->mbuf != NULL) {
1582                                 ktls_encrypt(p);
1583                                 counter_u64_add(ktls_cnt_on, -1);
1584                         } else {
1585                                 tls = p->tls;
1586                                 ktls_free(tls);
1587                                 m = __containerof(p, struct mbuf, m_ext_pgs);
1588                                 uma_zfree(zone_mbuf, m);
1589                         }
1590                 }
1591         }
1592 }