2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2014-2019 Netflix Inc.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
32 #include "opt_inet6.h"
35 #include <sys/param.h>
36 #include <sys/kernel.h>
40 #include <sys/mutex.h>
41 #include <sys/rmlock.h>
43 #include <sys/protosw.h>
44 #include <sys/refcount.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>
52 #include <sys/vmmeter.h>
53 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
54 #include <machine/pcb.h>
56 #include <machine/vmparam.h>
58 #include <net/if_var.h>
60 #include <net/netisr.h>
62 #include <net/rss_config.h>
64 #if defined(INET) || defined(INET6)
65 #include <netinet/in.h>
66 #include <netinet/in_pcb.h>
68 #include <netinet/tcp_var.h>
70 #include <netinet/tcp_offload.h>
72 #include <opencrypto/xform.h>
73 #include <vm/uma_dbg.h>
75 #include <vm/vm_pageout.h>
76 #include <vm/vm_page.h>
80 STAILQ_HEAD(, mbuf_ext_pgs) head;
82 } __aligned(CACHE_LINE_SIZE);
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];
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");
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");
101 static int ktls_bind_threads = 1;
103 static int ktls_bind_threads;
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");
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");
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");
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");
123 static bool ktls_cbc_enable = true;
124 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RW,
126 "Enable Support of AES-CBC crypto for kernel TLS");
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");
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");
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)");
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");
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");
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");
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");
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");
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");
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");
171 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
172 "TOE TLS session stats");
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");
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");
183 static counter_u64_t ktls_ifnet_cbc;
184 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
186 "Active number of ifnet TLS sessions using AES-CBC");
188 static counter_u64_t ktls_ifnet_gcm;
189 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
191 "Active number of ifnet TLS sessions using AES-GCM");
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");
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");
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");
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");
213 static counter_u64_t ktls_toe_cbc;
214 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
216 "Active number of TOE TLS sessions using AES-CBC");
218 static counter_u64_t ktls_toe_gcm;
219 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
221 "Active number of TOE TLS sessions using AES-GCM");
224 static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
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);
230 static void ktls_work_thread(void *ctx);
233 ktls_crypto_backend_register(struct ktls_crypto_backend *be)
235 struct ktls_crypto_backend *curr_be, *tmp;
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,
244 rm_wlock(&ktls_backends_lock);
245 printf("KTLS: Registering crypto method %s with prio %d\n",
247 if (LIST_EMPTY(&ktls_backends)) {
248 LIST_INSERT_HEAD(&ktls_backends, be, next);
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);
255 if (LIST_NEXT(curr_be, next) == NULL) {
256 LIST_INSERT_AFTER(curr_be, be, next);
261 rm_wunlock(&ktls_backends_lock);
266 ktls_crypto_backend_deregister(struct ktls_crypto_backend *be)
268 struct ktls_crypto_backend *tmp;
271 * Don't error if the backend isn't registered. This permits
272 * MOD_UNLOAD handlers to use this function unconditionally.
274 rm_wlock(&ktls_backends_lock);
275 LIST_FOREACH(tmp, &ktls_backends, next) {
280 rm_wunlock(&ktls_backends_lock);
284 if (!ktls_allow_unload) {
285 rm_wunlock(&ktls_backends_lock);
287 "KTLS: Deregistering crypto method %s is not supported\n",
293 rm_wunlock(&ktls_backends_lock);
297 LIST_REMOVE(be, next);
298 rm_wunlock(&ktls_backends_lock);
302 #if defined(INET) || defined(INET6)
304 ktls_get_cpu(struct socket *so)
311 cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
312 if (cpuid != NETISR_CPUID_NONE)
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
321 cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
327 ktls_init(void *dummy __unused)
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);
351 ktls_toe_cbc = counter_u64_alloc(M_WAITOK);
352 ktls_toe_gcm = counter_u64_alloc(M_WAITOK);
355 rm_init(&ktls_backends_lock, "ktls backends");
356 LIST_INIT(&ktls_backends);
358 ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
361 ktls_session_zone = uma_zcreate("ktls_session",
362 sizeof(struct ktls_session),
363 NULL, NULL, NULL, NULL,
367 * Initialize the workqueues to run the TLS work. We create a
368 * work queue for each CPU.
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);
376 panic("Can't add KTLS thread %d error %d", i, error);
379 * Bind threads to cores. If ktls_bind_threads is >
380 * 1, then we bind to the NUMA domain.
382 if (ktls_bind_threads) {
383 if (ktls_bind_threads > 1) {
385 CPU_COPY(&cpuset_domain[pc->pc_domain], &mask);
389 error = cpuset_setthread(td->td_tid, &mask);
392 "Unable to bind KTLS thread for CPU %d error %d",
395 ktls_cpuid_lookup[ktls_number_threads] = i;
396 ktls_number_threads++;
398 printf("KTLS: Initialized %d threads\n", ktls_number_threads);
400 SYSINIT(ktls, SI_SUB_SMP + 1, SI_ORDER_ANY, ktls_init, NULL);
402 #if defined(INET) || defined(INET6)
404 ktls_create_session(struct socket *so, struct tls_enable *en,
405 struct ktls_session **tlsp)
407 struct ktls_session *tls;
410 /* Only TLS 1.0 - 1.3 are supported. */
411 if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
413 if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
414 en->tls_vminor > TLS_MINOR_VER_THREE)
417 if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
419 if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
421 if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
424 /* All supported algorithms require a cipher key. */
425 if (en->cipher_key_len == 0)
428 /* No flags are currently supported. */
432 /* Common checks for supported algorithms. */
433 switch (en->cipher_algorithm) {
434 case CRYPTO_AES_NIST_GCM_16:
436 * auth_algorithm isn't used, but permit GMAC values
439 switch (en->auth_algorithm) {
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:
451 if (en->auth_key_len != 0)
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))
460 switch (en->auth_algorithm) {
461 case CRYPTO_SHA1_HMAC:
463 * TLS 1.0 requires an implicit IV. TLS 1.1+
464 * all use explicit IVs.
466 if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
467 if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
473 case CRYPTO_SHA2_256_HMAC:
474 case CRYPTO_SHA2_384_HMAC:
475 /* Ignore any supplied IV. */
481 if (en->auth_key_len == 0)
488 tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
490 counter_u64_add(ktls_offload_active, 1);
492 refcount_init(&tls->refcount, 1);
493 TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
495 tls->wq_index = ktls_get_cpu(so);
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);
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:
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.
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;
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.
521 if (en->tls_vminor == TLS_MINOR_VER_THREE)
522 tls->params.tls_tlen += sizeof(uint8_t);
524 tls->params.tls_bs = 1;
527 switch (en->auth_algorithm) {
528 case CRYPTO_SHA1_HMAC:
529 if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
530 /* Implicit IV, no nonce. */
532 tls->params.tls_hlen += AES_BLOCK_LEN;
534 tls->params.tls_tlen = AES_BLOCK_LEN +
537 case CRYPTO_SHA2_256_HMAC:
538 tls->params.tls_hlen += AES_BLOCK_LEN;
539 tls->params.tls_tlen = AES_BLOCK_LEN +
542 case CRYPTO_SHA2_384_HMAC:
543 tls->params.tls_hlen += AES_BLOCK_LEN;
544 tls->params.tls_tlen = AES_BLOCK_LEN +
548 panic("invalid hmac");
550 tls->params.tls_bs = AES_BLOCK_LEN;
553 panic("invalid cipher");
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));
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,
565 error = copyin(en->auth_key, tls->params.auth_key,
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,
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().
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);
590 * For TLS 1.2, generate an 8-byte nonce as a counter
591 * to generate unique explicit IVs.
593 * Store this counter in the last 8 bytes of the IV
594 * array so that it is 8-byte aligned.
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);
609 static struct ktls_session *
610 ktls_clone_session(struct ktls_session *tls)
612 struct ktls_session *tls_new;
614 tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
616 counter_u64_add(ktls_offload_active, 1);
618 refcount_init(&tls_new->refcount, 1);
620 /* Copy fields from existing session. */
621 tls_new->params = tls->params;
622 tls_new->wq_index = tls->wq_index;
624 /* Deep copy keys. */
625 if (tls_new->params.auth_key != NULL) {
626 tls_new->params.auth_key = malloc(tls->params.auth_key_len,
628 memcpy(tls_new->params.auth_key, tls->params.auth_key,
629 tls->params.auth_key_len);
632 tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
634 memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
635 tls->params.cipher_key_len);
642 ktls_cleanup(struct ktls_session *tls)
645 counter_u64_add(ktls_offload_active, -1);
647 case TCP_TLS_MODE_SW:
648 MPASS(tls->be != NULL);
649 switch (tls->params.cipher_algorithm) {
651 counter_u64_add(ktls_sw_cbc, -1);
653 case CRYPTO_AES_NIST_GCM_16:
654 counter_u64_add(ktls_sw_gcm, -1);
659 case TCP_TLS_MODE_IFNET:
660 switch (tls->params.cipher_algorithm) {
662 counter_u64_add(ktls_ifnet_cbc, -1);
664 case CRYPTO_AES_NIST_GCM_16:
665 counter_u64_add(ktls_ifnet_gcm, -1);
668 m_snd_tag_rele(tls->snd_tag);
671 case TCP_TLS_MODE_TOE:
672 switch (tls->params.cipher_algorithm) {
674 counter_u64_add(ktls_toe_cbc, -1);
676 case CRYPTO_AES_NIST_GCM_16:
677 counter_u64_add(ktls_toe_gcm, -1);
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;
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;
696 explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
699 #if defined(INET) || defined(INET6)
703 ktls_try_toe(struct socket *so, struct ktls_session *tls)
711 if (inp->inp_flags2 & INP_FREED) {
715 if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
719 if (inp->inp_socket == NULL) {
724 if (tp->tod == NULL) {
729 error = tcp_offload_alloc_tls_session(tp, tls);
732 tls->mode = TCP_TLS_MODE_TOE;
733 switch (tls->params.cipher_algorithm) {
735 counter_u64_add(ktls_toe_cbc, 1);
737 case CRYPTO_AES_NIST_GCM_16:
738 counter_u64_add(ktls_toe_gcm, 1);
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.
753 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
754 struct m_snd_tag **mstp)
756 union if_snd_tag_alloc_params params;
758 struct nhop_object *nh;
763 if (inp->inp_flags2 & INP_FREED) {
767 if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
771 if (inp->inp_socket == NULL) {
778 * Check administrative controls on ifnet TLS to determine if
779 * ifnet TLS should be denied.
781 * - Always permit 'force' requests.
782 * - ktls_ifnet_permitted == 0: always deny.
784 if (!force && ktls_ifnet_permitted == 0) {
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.
796 nh = inp->inp_route.ro_nh;
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;
812 if (ifp->if_snd_tag_alloc == NULL) {
816 if ((ifp->if_capenable & IFCAP_NOMAP) == 0) {
820 if (inp->inp_vflag & INP_IPV6) {
821 if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
826 if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
831 error = ifp->if_snd_tag_alloc(ifp, ¶ms, mstp);
838 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
840 struct m_snd_tag *mst;
843 error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
845 tls->mode = TCP_TLS_MODE_IFNET;
847 switch (tls->params.cipher_algorithm) {
849 counter_u64_add(ktls_ifnet_cbc, 1);
851 case CRYPTO_AES_NIST_GCM_16:
852 counter_u64_add(ktls_ifnet_gcm, 1);
860 ktls_try_sw(struct socket *so, struct ktls_session *tls)
862 struct rm_priotracker prio;
863 struct ktls_crypto_backend *be;
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
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)
877 KASSERT(tls->cipher == NULL,
878 ("ktls backend leaked a cipher pointer"));
881 if (ktls_allow_unload)
885 if (ktls_allow_unload)
886 rm_runlock(&ktls_backends_lock, &prio);
889 tls->mode = TCP_TLS_MODE_SW;
890 switch (tls->params.cipher_algorithm) {
892 counter_u64_add(ktls_sw_cbc, 1);
894 case CRYPTO_AES_NIST_GCM_16:
895 counter_u64_add(ktls_sw_gcm, 1);
902 ktls_enable_tx(struct socket *so, struct tls_enable *en)
904 struct ktls_session *tls;
907 if (!ktls_offload_enable)
910 counter_u64_add(ktls_offload_enable_calls, 1);
913 * This should always be true since only the TCP socket option
914 * invokes this function.
916 if (so->so_proto->pr_protocol != IPPROTO_TCP)
920 * XXX: Don't overwrite existing sessions. We should permit
921 * this to support rekeying in the future.
923 if (so->so_snd.sb_tls_info != NULL)
926 if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
929 /* TLS requires ext pgs */
930 if (mb_use_ext_pgs == 0)
933 error = ktls_create_session(so, en, &tls);
937 /* Prefer TOE -> ifnet TLS -> software TLS. */
939 error = ktls_try_toe(so, tls);
942 error = ktls_try_ifnet(so, tls, false);
944 error = ktls_try_sw(so, tls);
951 error = sblock(&so->so_snd, SBL_WAIT);
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);
964 counter_u64_add(ktls_offload_total, 1);
970 ktls_get_tx_mode(struct socket *so)
972 struct ktls_session *tls;
977 INP_WLOCK_ASSERT(inp);
978 SOCKBUF_LOCK(&so->so_snd);
979 tls = so->so_snd.sb_tls_info;
981 mode = TCP_TLS_MODE_NONE;
984 SOCKBUF_UNLOCK(&so->so_snd);
989 * Switch between SW and ifnet TLS sessions as requested.
992 ktls_set_tx_mode(struct socket *so, int mode)
994 struct ktls_session *tls, *tls_new;
999 case TCP_TLS_MODE_SW:
1000 case TCP_TLS_MODE_IFNET:
1007 INP_WLOCK_ASSERT(inp);
1008 SOCKBUF_LOCK(&so->so_snd);
1009 tls = so->so_snd.sb_tls_info;
1011 SOCKBUF_UNLOCK(&so->so_snd);
1015 if (tls->mode == mode) {
1016 SOCKBUF_UNLOCK(&so->so_snd);
1020 tls = ktls_hold(tls);
1021 SOCKBUF_UNLOCK(&so->so_snd);
1024 tls_new = ktls_clone_session(tls);
1026 if (mode == TCP_TLS_MODE_IFNET)
1027 error = ktls_try_ifnet(so, tls_new, true);
1029 error = ktls_try_sw(so, tls_new);
1031 counter_u64_add(ktls_switch_failed, 1);
1038 error = sblock(&so->so_snd, SBL_WAIT);
1040 counter_u64_add(ktls_switch_failed, 1);
1048 * If we raced with another session change, keep the existing
1051 if (tls != so->so_snd.sb_tls_info) {
1052 counter_u64_add(ktls_switch_failed, 1);
1053 sbunlock(&so->so_snd);
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);
1068 * Drop two references on 'tls'. The first is for the
1069 * ktls_hold() above. The second drops the reference from the
1072 KASSERT(tls->refcount >= 2, ("too few references on old session"));
1076 if (mode == TCP_TLS_MODE_IFNET)
1077 counter_u64_add(ktls_switch_to_ifnet, 1);
1079 counter_u64_add(ktls_switch_to_sw, 1);
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
1094 ktls_reset_send_tag(void *context, int pending)
1096 struct epoch_tracker et;
1097 struct ktls_session *tls;
1098 struct m_snd_tag *old, *new;
1103 MPASS(pending == 1);
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
1114 * Write-lock the INP when changing tls->snd_tag since
1115 * ip[6]_output_send() holds a read-lock when reading the
1120 tls->snd_tag = NULL;
1123 m_snd_tag_rele(old);
1125 error = ktls_alloc_snd_tag(inp, tls, true, &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))
1136 counter_u64_add(ktls_ifnet_reset, 1);
1139 * XXX: Should we kick tcp_output explicitly now that
1140 * the send tag is fixed or just rely on timers?
1143 NET_EPOCH_ENTER(et);
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);
1154 counter_u64_add(ktls_ifnet_reset_dropped, 1);
1160 counter_u64_add(ktls_ifnet_reset_failed, 1);
1163 * Leave reset_pending true to avoid future tasks while
1164 * the socket goes away.
1172 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1178 INP_LOCK_ASSERT(inp);
1181 * See if we should schedule a task to update the send tag for
1184 mtx_pool_lock(mtxpool_sleep, tls);
1185 if (!tls->reset_pending) {
1186 (void) ktls_hold(tls);
1189 tls->reset_pending = true;
1190 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1192 mtx_pool_unlock(mtxpool_sleep, tls);
1198 ktls_destroy(struct ktls_session *tls)
1200 struct rm_priotracker prio;
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);
1208 uma_zfree(ktls_session_zone, tls);
1212 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1214 struct mbuf_ext_pgs *pgs;
1216 for (; m != NULL; m = m->m_next) {
1217 KASSERT((m->m_flags & M_NOMAP) != 0,
1218 ("ktls_seq: mapped mbuf %p", m));
1220 pgs = &m->m_ext_pgs;
1221 pgs->seqno = sb->sb_tls_seqno;
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.
1231 * The record_type argument specifies the TLS record type used when
1232 * populating the TLS header.
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.
1240 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1241 uint8_t record_type)
1243 struct tls_record_layer *tlshdr;
1245 struct mbuf_ext_pgs *pgs;
1250 maxlen = tls->params.max_frame_len;
1252 for (m = top; m != NULL; m = m->m_next) {
1254 * All mbufs in the chain should be non-empty TLS
1255 * records whose payload does not exceed the maximum
1258 KASSERT(m->m_len <= maxlen && m->m_len > 0,
1259 ("ktls_frame: m %p len %d\n", m, m->m_len));
1261 * TLS frames require unmapped mbufs to store session
1264 KASSERT((m->m_flags & M_NOMAP) != 0,
1265 ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1268 pgs = &m->m_ext_pgs;
1270 /* Save a reference to the session. */
1271 pgs->tls = ktls_hold(tls);
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) {
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
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.
1294 bs = tls->params.tls_bs;
1295 delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
1296 pgs->trail_len -= delta;
1298 m->m_len += pgs->hdr_len + pgs->trail_len;
1300 /* Populate the TLS header. */
1301 tlshdr = (void *)pgs->m_epg_hdr;
1302 tlshdr->tls_vmajor = tls->params.tls_vmajor;
1305 * TLS 1.3 masquarades as TLS 1.2 with a record type
1306 * of TLS_RLTYPE_APP.
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;
1316 tlshdr->tls_vminor = tls->params.tls_vminor;
1317 tlshdr->tls_type = record_type;
1319 tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1322 * Store nonces / explicit IVs after the end of the
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.
1329 * For CBC, a random nonce is inserted for TLS 1.1+.
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);
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);
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.
1345 * When using ifnet TLS, unencrypted TLS records are
1346 * sent down the stack to the NIC.
1348 if (tls->mode == TCP_TLS_MODE_SW) {
1349 m->m_flags |= M_NOTREADY;
1350 pgs->nrdy = pgs->npgs;
1351 *enq_cnt += pgs->npgs;
1357 ktls_enqueue_to_free(struct mbuf_ext_pgs *pgs)
1362 /* Mark it for freeing. */
1364 wq = &ktls_wq[pgs->tls->wq_index];
1366 STAILQ_INSERT_TAIL(&wq->head, pgs, stailq);
1367 running = wq->running;
1368 mtx_unlock(&wq->mtx);
1374 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
1376 struct mbuf_ext_pgs *pgs;
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"));
1385 pgs = &m->m_ext_pgs;
1387 KASSERT(pgs->tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
1389 pgs->enc_cnt = page_count;
1393 * Save a pointer to the socket. The caller is responsible
1394 * for taking an additional reference via soref().
1398 wq = &ktls_wq[pgs->tls->wq_index];
1400 STAILQ_INSERT_TAIL(&wq->head, pgs, stailq);
1401 running = wq->running;
1402 mtx_unlock(&wq->mtx);
1405 counter_u64_add(ktls_cnt_on, 1);
1408 static __noinline void
1409 ktls_encrypt(struct mbuf_ext_pgs *pgs)
1411 struct ktls_session *tls;
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)];
1418 int error, i, len, npages, off, total_pages;
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));
1430 total_pages = pgs->enc_cnt;
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'.
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
1448 * Each mbuf holds an entire TLS record.
1451 for (m = top; npages != total_pages; m = m->m_next) {
1452 pgs = &m->m_ext_pgs;
1454 KASSERT(pgs->tls == tls,
1455 ("different TLS sessions in a single mbuf chain: %p vs %p",
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,
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.
1472 is_anon = (pgs->flags & MBUF_PEXT_FLAG_ANON) != 0;
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]) +
1483 dst_iov[i].iov_base = src_iov[i].iov_base;
1484 dst_iov[i].iov_len = src_iov[i].iov_len;
1488 pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
1489 VM_ALLOC_NOOBJ | VM_ALLOC_NODUMP | VM_ALLOC_WIRED);
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;
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,
1507 counter_u64_add(ktls_offload_failed_crypto, 1);
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.
1517 /* Free the old pages. */
1518 m->m_ext.ext_free(m);
1520 /* Replace them with the new pages. */
1521 for (i = 0; i < pgs->npgs; i++)
1522 pgs->m_epg_pa[i] = parray[i];
1524 /* Use the basic free routine. */
1525 m->m_ext.ext_free = mb_free_mext_pgs;
1527 /* Pages are now writable. */
1528 pgs->flags |= MBUF_PEXT_FLAG_ANON;
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
1542 CURVNET_SET(so->so_vnet);
1544 (void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
1546 so->so_proto->pr_usrreqs->pru_abort(so);
1548 mb_free_notready(top, total_pages);
1557 ktls_work_thread(void *ctx)
1559 struct ktls_wq *wq = ctx;
1560 struct mbuf_ext_pgs *p, *n;
1561 struct ktls_session *tls;
1563 STAILQ_HEAD(, mbuf_ext_pgs) local_head;
1565 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
1570 while (STAILQ_EMPTY(&wq->head)) {
1571 wq->running = false;
1572 mtx_sleep(wq, &wq->mtx, 0, "-", 0);
1576 STAILQ_INIT(&local_head);
1577 STAILQ_CONCAT(&local_head, &wq->head);
1578 mtx_unlock(&wq->mtx);
1580 STAILQ_FOREACH_SAFE(p, &local_head, stailq, n) {
1581 if (p->mbuf != NULL) {
1583 counter_u64_add(ktls_cnt_on, -1);
1587 m = __containerof(p, struct mbuf, m_ext_pgs);
1588 uma_zfree(zone_mbuf, m);