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>
37 #include <sys/domainset.h>
41 #include <sys/mutex.h>
42 #include <sys/rmlock.h>
44 #include <sys/protosw.h>
45 #include <sys/refcount.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/sysctl.h>
50 #include <sys/taskqueue.h>
51 #include <sys/kthread.h>
53 #include <sys/vmmeter.h>
54 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
55 #include <machine/pcb.h>
57 #include <machine/vmparam.h>
59 #include <net/if_var.h>
61 #include <net/netisr.h>
62 #include <net/rss_config.h>
64 #include <net/route.h>
65 #include <net/route/nhop.h>
66 #if defined(INET) || defined(INET6)
67 #include <netinet/in.h>
68 #include <netinet/in_pcb.h>
70 #include <netinet/tcp_var.h>
72 #include <netinet/tcp_offload.h>
74 #include <opencrypto/xform.h>
75 #include <vm/uma_dbg.h>
77 #include <vm/vm_pageout.h>
78 #include <vm/vm_page.h>
82 STAILQ_HEAD(, mbuf) m_head;
83 STAILQ_HEAD(, socket) so_head;
85 } __aligned(CACHE_LINE_SIZE);
87 struct ktls_domain_info {
92 struct ktls_domain_info ktls_domains[MAXMEMDOM];
93 static struct ktls_wq *ktls_wq;
94 static struct proc *ktls_proc;
95 LIST_HEAD(, ktls_crypto_backend) ktls_backends;
96 static struct rmlock ktls_backends_lock;
97 static uma_zone_t ktls_session_zone;
98 static uint16_t ktls_cpuid_lookup[MAXCPU];
100 SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
101 "Kernel TLS offload");
102 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
103 "Kernel TLS offload stats");
105 static int ktls_allow_unload;
106 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, allow_unload, CTLFLAG_RDTUN,
107 &ktls_allow_unload, 0, "Allow software crypto modules to unload");
110 static int ktls_bind_threads = 1;
112 static int ktls_bind_threads;
114 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
115 &ktls_bind_threads, 0,
116 "Bind crypto threads to cores (1) or cores and domains (2) at boot");
118 static u_int ktls_maxlen = 16384;
119 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RWTUN,
120 &ktls_maxlen, 0, "Maximum TLS record size");
122 static int ktls_number_threads;
123 SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
124 &ktls_number_threads, 0,
125 "Number of TLS threads in thread-pool");
127 static bool ktls_offload_enable;
128 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RWTUN,
129 &ktls_offload_enable, 0,
130 "Enable support for kernel TLS offload");
132 static bool ktls_cbc_enable = true;
133 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RWTUN,
135 "Enable Support of AES-CBC crypto for kernel TLS");
137 static COUNTER_U64_DEFINE_EARLY(ktls_tasks_active);
138 SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
139 &ktls_tasks_active, "Number of active tasks");
141 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_tx_queued);
142 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_tx_inqueue, CTLFLAG_RD,
144 "Number of TLS records in queue to tasks for SW encryption");
146 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_rx_queued);
147 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_rx_inqueue, CTLFLAG_RD,
149 "Number of TLS sockets in queue to tasks for SW decryption");
151 static COUNTER_U64_DEFINE_EARLY(ktls_offload_total);
152 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
153 CTLFLAG_RD, &ktls_offload_total,
154 "Total successful TLS setups (parameters set)");
156 static COUNTER_U64_DEFINE_EARLY(ktls_offload_enable_calls);
157 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
158 CTLFLAG_RD, &ktls_offload_enable_calls,
159 "Total number of TLS enable calls made");
161 static COUNTER_U64_DEFINE_EARLY(ktls_offload_active);
162 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
163 &ktls_offload_active, "Total Active TLS sessions");
165 static COUNTER_U64_DEFINE_EARLY(ktls_offload_corrupted_records);
166 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, corrupted_records, CTLFLAG_RD,
167 &ktls_offload_corrupted_records, "Total corrupted TLS records received");
169 static COUNTER_U64_DEFINE_EARLY(ktls_offload_failed_crypto);
170 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
171 &ktls_offload_failed_crypto, "Total TLS crypto failures");
173 static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_ifnet);
174 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
175 &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
177 static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_sw);
178 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
179 &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
181 static COUNTER_U64_DEFINE_EARLY(ktls_switch_failed);
182 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
183 &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
185 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
186 "Software TLS session stats");
187 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
188 "Hardware (ifnet) TLS session stats");
190 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
191 "TOE TLS session stats");
194 static COUNTER_U64_DEFINE_EARLY(ktls_sw_cbc);
195 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
196 "Active number of software TLS sessions using AES-CBC");
198 static COUNTER_U64_DEFINE_EARLY(ktls_sw_gcm);
199 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
200 "Active number of software TLS sessions using AES-GCM");
202 static COUNTER_U64_DEFINE_EARLY(ktls_sw_chacha20);
203 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, chacha20, CTLFLAG_RD,
205 "Active number of software TLS sessions using Chacha20-Poly1305");
207 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_cbc);
208 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
210 "Active number of ifnet TLS sessions using AES-CBC");
212 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_gcm);
213 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
215 "Active number of ifnet TLS sessions using AES-GCM");
217 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_chacha20);
218 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, chacha20, CTLFLAG_RD,
219 &ktls_ifnet_chacha20,
220 "Active number of ifnet TLS sessions using Chacha20-Poly1305");
222 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset);
223 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
224 &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
226 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_dropped);
227 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
228 &ktls_ifnet_reset_dropped,
229 "TLS sessions dropped after failing to update ifnet send tag");
231 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_failed);
232 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
233 &ktls_ifnet_reset_failed,
234 "TLS sessions that failed to allocate a new ifnet send tag");
236 static int ktls_ifnet_permitted;
237 SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
238 &ktls_ifnet_permitted, 1,
239 "Whether to permit hardware (ifnet) TLS sessions");
242 static COUNTER_U64_DEFINE_EARLY(ktls_toe_cbc);
243 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
245 "Active number of TOE TLS sessions using AES-CBC");
247 static COUNTER_U64_DEFINE_EARLY(ktls_toe_gcm);
248 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
250 "Active number of TOE TLS sessions using AES-GCM");
252 static counter_u64_t ktls_toe_chacha20;
253 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, chacha20, CTLFLAG_RD,
255 "Active number of TOE TLS sessions using Chacha20-Poly1305");
258 static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
260 static void ktls_cleanup(struct ktls_session *tls);
261 #if defined(INET) || defined(INET6)
262 static void ktls_reset_send_tag(void *context, int pending);
264 static void ktls_work_thread(void *ctx);
267 ktls_crypto_backend_register(struct ktls_crypto_backend *be)
269 struct ktls_crypto_backend *curr_be, *tmp;
271 if (be->api_version != KTLS_API_VERSION) {
272 printf("KTLS: API version mismatch (%d vs %d) for %s\n",
273 be->api_version, KTLS_API_VERSION,
278 rm_wlock(&ktls_backends_lock);
279 printf("KTLS: Registering crypto method %s with prio %d\n",
281 if (LIST_EMPTY(&ktls_backends)) {
282 LIST_INSERT_HEAD(&ktls_backends, be, next);
284 LIST_FOREACH_SAFE(curr_be, &ktls_backends, next, tmp) {
285 if (curr_be->prio < be->prio) {
286 LIST_INSERT_BEFORE(curr_be, be, next);
289 if (LIST_NEXT(curr_be, next) == NULL) {
290 LIST_INSERT_AFTER(curr_be, be, next);
295 rm_wunlock(&ktls_backends_lock);
300 ktls_crypto_backend_deregister(struct ktls_crypto_backend *be)
302 struct ktls_crypto_backend *tmp;
305 * Don't error if the backend isn't registered. This permits
306 * MOD_UNLOAD handlers to use this function unconditionally.
308 rm_wlock(&ktls_backends_lock);
309 LIST_FOREACH(tmp, &ktls_backends, next) {
314 rm_wunlock(&ktls_backends_lock);
318 if (!ktls_allow_unload) {
319 rm_wunlock(&ktls_backends_lock);
321 "KTLS: Deregistering crypto method %s is not supported\n",
327 rm_wunlock(&ktls_backends_lock);
331 LIST_REMOVE(be, next);
332 rm_wunlock(&ktls_backends_lock);
336 #if defined(INET) || defined(INET6)
338 ktls_get_cpu(struct socket *so)
342 struct ktls_domain_info *di;
348 cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
349 if (cpuid != NETISR_CPUID_NONE)
353 * Just use the flowid to shard connections in a repeatable
354 * fashion. Note that some crypto backends rely on the
355 * serialization provided by having the same connection use
359 if (ktls_bind_threads > 1 && inp->inp_numa_domain != M_NODOM) {
360 di = &ktls_domains[inp->inp_numa_domain];
361 cpuid = di->cpu[inp->inp_flowid % di->count];
364 cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
370 ktls_init(void *dummy __unused)
375 int count, domain, error, i;
377 rm_init(&ktls_backends_lock, "ktls backends");
378 LIST_INIT(&ktls_backends);
380 ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
383 ktls_session_zone = uma_zcreate("ktls_session",
384 sizeof(struct ktls_session),
385 NULL, NULL, NULL, NULL,
389 * Initialize the workqueues to run the TLS work. We create a
390 * work queue for each CPU.
393 STAILQ_INIT(&ktls_wq[i].m_head);
394 STAILQ_INIT(&ktls_wq[i].so_head);
395 mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
396 error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
397 &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
399 panic("Can't add KTLS thread %d error %d", i, error);
402 * Bind threads to cores. If ktls_bind_threads is >
403 * 1, then we bind to the NUMA domain.
405 if (ktls_bind_threads) {
406 if (ktls_bind_threads > 1) {
408 domain = pc->pc_domain;
409 CPU_COPY(&cpuset_domain[domain], &mask);
410 count = ktls_domains[domain].count;
411 ktls_domains[domain].cpu[count] = i;
412 ktls_domains[domain].count++;
416 error = cpuset_setthread(td->td_tid, &mask);
419 "Unable to bind KTLS thread for CPU %d error %d",
422 ktls_cpuid_lookup[ktls_number_threads] = i;
423 ktls_number_threads++;
427 * If we somehow have an empty domain, fall back to choosing
428 * among all KTLS threads.
430 if (ktls_bind_threads > 1) {
431 for (i = 0; i < vm_ndomains; i++) {
432 if (ktls_domains[i].count == 0) {
433 ktls_bind_threads = 1;
440 printf("KTLS: Initialized %d threads\n", ktls_number_threads);
442 SYSINIT(ktls, SI_SUB_SMP + 1, SI_ORDER_ANY, ktls_init, NULL);
444 #if defined(INET) || defined(INET6)
446 ktls_create_session(struct socket *so, struct tls_enable *en,
447 struct ktls_session **tlsp)
449 struct ktls_session *tls;
452 /* Only TLS 1.0 - 1.3 are supported. */
453 if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
455 if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
456 en->tls_vminor > TLS_MINOR_VER_THREE)
459 if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
461 if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
463 if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
466 /* All supported algorithms require a cipher key. */
467 if (en->cipher_key_len == 0)
470 /* No flags are currently supported. */
474 /* Common checks for supported algorithms. */
475 switch (en->cipher_algorithm) {
476 case CRYPTO_AES_NIST_GCM_16:
478 * auth_algorithm isn't used, but permit GMAC values
481 switch (en->auth_algorithm) {
483 #ifdef COMPAT_FREEBSD12
484 /* XXX: Really 13.0-current COMPAT. */
485 case CRYPTO_AES_128_NIST_GMAC:
486 case CRYPTO_AES_192_NIST_GMAC:
487 case CRYPTO_AES_256_NIST_GMAC:
493 if (en->auth_key_len != 0)
495 if ((en->tls_vminor == TLS_MINOR_VER_TWO &&
496 en->iv_len != TLS_AEAD_GCM_LEN) ||
497 (en->tls_vminor == TLS_MINOR_VER_THREE &&
498 en->iv_len != TLS_1_3_GCM_IV_LEN))
502 switch (en->auth_algorithm) {
503 case CRYPTO_SHA1_HMAC:
505 * TLS 1.0 requires an implicit IV. TLS 1.1+
506 * all use explicit IVs.
508 if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
509 if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
515 case CRYPTO_SHA2_256_HMAC:
516 case CRYPTO_SHA2_384_HMAC:
517 /* Ignore any supplied IV. */
523 if (en->auth_key_len == 0)
526 case CRYPTO_CHACHA20_POLY1305:
527 if (en->auth_algorithm != 0 || en->auth_key_len != 0)
529 if (en->tls_vminor != TLS_MINOR_VER_TWO &&
530 en->tls_vminor != TLS_MINOR_VER_THREE)
532 if (en->iv_len != TLS_CHACHA20_IV_LEN)
539 tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
541 counter_u64_add(ktls_offload_active, 1);
543 refcount_init(&tls->refcount, 1);
544 TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
546 tls->wq_index = ktls_get_cpu(so);
548 tls->params.cipher_algorithm = en->cipher_algorithm;
549 tls->params.auth_algorithm = en->auth_algorithm;
550 tls->params.tls_vmajor = en->tls_vmajor;
551 tls->params.tls_vminor = en->tls_vminor;
552 tls->params.flags = en->flags;
553 tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
555 /* Set the header and trailer lengths. */
556 tls->params.tls_hlen = sizeof(struct tls_record_layer);
557 switch (en->cipher_algorithm) {
558 case CRYPTO_AES_NIST_GCM_16:
560 * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
561 * nonce. TLS 1.3 uses a 12 byte implicit IV.
563 if (en->tls_vminor < TLS_MINOR_VER_THREE)
564 tls->params.tls_hlen += sizeof(uint64_t);
565 tls->params.tls_tlen = AES_GMAC_HASH_LEN;
566 tls->params.tls_bs = 1;
569 switch (en->auth_algorithm) {
570 case CRYPTO_SHA1_HMAC:
571 if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
572 /* Implicit IV, no nonce. */
574 tls->params.tls_hlen += AES_BLOCK_LEN;
576 tls->params.tls_tlen = AES_BLOCK_LEN +
579 case CRYPTO_SHA2_256_HMAC:
580 tls->params.tls_hlen += AES_BLOCK_LEN;
581 tls->params.tls_tlen = AES_BLOCK_LEN +
584 case CRYPTO_SHA2_384_HMAC:
585 tls->params.tls_hlen += AES_BLOCK_LEN;
586 tls->params.tls_tlen = AES_BLOCK_LEN +
590 panic("invalid hmac");
592 tls->params.tls_bs = AES_BLOCK_LEN;
594 case CRYPTO_CHACHA20_POLY1305:
596 * Chacha20 uses a 12 byte implicit IV.
598 tls->params.tls_tlen = POLY1305_HASH_LEN;
599 tls->params.tls_bs = 1;
602 panic("invalid cipher");
606 * TLS 1.3 includes optional padding which we do not support,
607 * and also puts the "real" record type at the end of the
610 if (en->tls_vminor == TLS_MINOR_VER_THREE)
611 tls->params.tls_tlen += sizeof(uint8_t);
613 KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
614 ("TLS header length too long: %d", tls->params.tls_hlen));
615 KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
616 ("TLS trailer length too long: %d", tls->params.tls_tlen));
618 if (en->auth_key_len != 0) {
619 tls->params.auth_key_len = en->auth_key_len;
620 tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
622 error = copyin(en->auth_key, tls->params.auth_key,
628 tls->params.cipher_key_len = en->cipher_key_len;
629 tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
630 error = copyin(en->cipher_key, tls->params.cipher_key,
636 * This holds the implicit portion of the nonce for AEAD
637 * ciphers and the initial implicit IV for TLS 1.0. The
638 * explicit portions of the IV are generated in ktls_frame().
640 if (en->iv_len != 0) {
641 tls->params.iv_len = en->iv_len;
642 error = copyin(en->iv, tls->params.iv, en->iv_len);
647 * For TLS 1.2 with GCM, generate an 8-byte nonce as a
648 * counter to generate unique explicit IVs.
650 * Store this counter in the last 8 bytes of the IV
651 * array so that it is 8-byte aligned.
653 if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
654 en->tls_vminor == TLS_MINOR_VER_TWO)
655 arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
666 static struct ktls_session *
667 ktls_clone_session(struct ktls_session *tls)
669 struct ktls_session *tls_new;
671 tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
673 counter_u64_add(ktls_offload_active, 1);
675 refcount_init(&tls_new->refcount, 1);
676 TASK_INIT(&tls_new->reset_tag_task, 0, ktls_reset_send_tag, tls_new);
678 /* Copy fields from existing session. */
679 tls_new->params = tls->params;
680 tls_new->wq_index = tls->wq_index;
682 /* Deep copy keys. */
683 if (tls_new->params.auth_key != NULL) {
684 tls_new->params.auth_key = malloc(tls->params.auth_key_len,
686 memcpy(tls_new->params.auth_key, tls->params.auth_key,
687 tls->params.auth_key_len);
690 tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
692 memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
693 tls->params.cipher_key_len);
700 ktls_cleanup(struct ktls_session *tls)
703 counter_u64_add(ktls_offload_active, -1);
705 case TCP_TLS_MODE_SW:
706 MPASS(tls->be != NULL);
707 switch (tls->params.cipher_algorithm) {
709 counter_u64_add(ktls_sw_cbc, -1);
711 case CRYPTO_AES_NIST_GCM_16:
712 counter_u64_add(ktls_sw_gcm, -1);
714 case CRYPTO_CHACHA20_POLY1305:
715 counter_u64_add(ktls_sw_chacha20, -1);
720 case TCP_TLS_MODE_IFNET:
721 switch (tls->params.cipher_algorithm) {
723 counter_u64_add(ktls_ifnet_cbc, -1);
725 case CRYPTO_AES_NIST_GCM_16:
726 counter_u64_add(ktls_ifnet_gcm, -1);
728 case CRYPTO_CHACHA20_POLY1305:
729 counter_u64_add(ktls_ifnet_chacha20, -1);
732 if (tls->snd_tag != NULL)
733 m_snd_tag_rele(tls->snd_tag);
736 case TCP_TLS_MODE_TOE:
737 switch (tls->params.cipher_algorithm) {
739 counter_u64_add(ktls_toe_cbc, -1);
741 case CRYPTO_AES_NIST_GCM_16:
742 counter_u64_add(ktls_toe_gcm, -1);
744 case CRYPTO_CHACHA20_POLY1305:
745 counter_u64_add(ktls_toe_chacha20, -1);
751 if (tls->params.auth_key != NULL) {
752 zfree(tls->params.auth_key, M_KTLS);
753 tls->params.auth_key = NULL;
754 tls->params.auth_key_len = 0;
756 if (tls->params.cipher_key != NULL) {
757 zfree(tls->params.cipher_key, M_KTLS);
758 tls->params.cipher_key = NULL;
759 tls->params.cipher_key_len = 0;
761 explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
764 #if defined(INET) || defined(INET6)
768 ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
776 if (inp->inp_flags2 & INP_FREED) {
780 if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
784 if (inp->inp_socket == NULL) {
789 if (!(tp->t_flags & TF_TOE)) {
794 error = tcp_offload_alloc_tls_session(tp, tls, direction);
797 tls->mode = TCP_TLS_MODE_TOE;
798 switch (tls->params.cipher_algorithm) {
800 counter_u64_add(ktls_toe_cbc, 1);
802 case CRYPTO_AES_NIST_GCM_16:
803 counter_u64_add(ktls_toe_gcm, 1);
805 case CRYPTO_CHACHA20_POLY1305:
806 counter_u64_add(ktls_toe_chacha20, 1);
815 * Common code used when first enabling ifnet TLS on a connection or
816 * when allocating a new ifnet TLS session due to a routing change.
817 * This function allocates a new TLS send tag on whatever interface
818 * the connection is currently routed over.
821 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
822 struct m_snd_tag **mstp)
824 union if_snd_tag_alloc_params params;
826 struct nhop_object *nh;
831 if (inp->inp_flags2 & INP_FREED) {
835 if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
839 if (inp->inp_socket == NULL) {
846 * Check administrative controls on ifnet TLS to determine if
847 * ifnet TLS should be denied.
849 * - Always permit 'force' requests.
850 * - ktls_ifnet_permitted == 0: always deny.
852 if (!force && ktls_ifnet_permitted == 0) {
858 * XXX: Use the cached route in the inpcb to find the
859 * interface. This should perhaps instead use
860 * rtalloc1_fib(dst, 0, 0, fibnum). Since KTLS is only
861 * enabled after a connection has completed key negotiation in
862 * userland, the cached route will be present in practice.
864 nh = inp->inp_route.ro_nh;
873 * Allocate a TLS + ratelimit tag if the connection has an
874 * existing pacing rate.
876 if (tp->t_pacing_rate != -1 &&
877 (ifp->if_capenable & IFCAP_TXTLS_RTLMT) != 0) {
878 params.hdr.type = IF_SND_TAG_TYPE_TLS_RATE_LIMIT;
879 params.tls_rate_limit.inp = inp;
880 params.tls_rate_limit.tls = tls;
881 params.tls_rate_limit.max_rate = tp->t_pacing_rate;
883 params.hdr.type = IF_SND_TAG_TYPE_TLS;
884 params.tls.inp = inp;
885 params.tls.tls = tls;
887 params.hdr.flowid = inp->inp_flowid;
888 params.hdr.flowtype = inp->inp_flowtype;
889 params.hdr.numa_domain = inp->inp_numa_domain;
892 if ((ifp->if_capenable & IFCAP_MEXTPG) == 0) {
896 if (inp->inp_vflag & INP_IPV6) {
897 if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
902 if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
907 error = m_snd_tag_alloc(ifp, ¶ms, mstp);
914 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
916 struct m_snd_tag *mst;
919 error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
921 tls->mode = TCP_TLS_MODE_IFNET;
923 switch (tls->params.cipher_algorithm) {
925 counter_u64_add(ktls_ifnet_cbc, 1);
927 case CRYPTO_AES_NIST_GCM_16:
928 counter_u64_add(ktls_ifnet_gcm, 1);
930 case CRYPTO_CHACHA20_POLY1305:
931 counter_u64_add(ktls_ifnet_chacha20, 1);
939 ktls_try_sw(struct socket *so, struct ktls_session *tls, int direction)
941 struct rm_priotracker prio;
942 struct ktls_crypto_backend *be;
945 * Choose the best software crypto backend. Backends are
946 * stored in sorted priority order (larget value == most
947 * important at the head of the list), so this just stops on
948 * the first backend that claims the session by returning
951 if (ktls_allow_unload)
952 rm_rlock(&ktls_backends_lock, &prio);
953 LIST_FOREACH(be, &ktls_backends, next) {
954 if (be->try(so, tls, direction) == 0)
956 KASSERT(tls->cipher == NULL,
957 ("ktls backend leaked a cipher pointer"));
960 if (ktls_allow_unload)
964 if (ktls_allow_unload)
965 rm_runlock(&ktls_backends_lock, &prio);
968 tls->mode = TCP_TLS_MODE_SW;
969 switch (tls->params.cipher_algorithm) {
971 counter_u64_add(ktls_sw_cbc, 1);
973 case CRYPTO_AES_NIST_GCM_16:
974 counter_u64_add(ktls_sw_gcm, 1);
976 case CRYPTO_CHACHA20_POLY1305:
977 counter_u64_add(ktls_sw_chacha20, 1);
984 * KTLS RX stores data in the socket buffer as a list of TLS records,
985 * where each record is stored as a control message containg the TLS
986 * header followed by data mbufs containing the decrypted data. This
987 * is different from KTLS TX which always uses an mb_ext_pgs mbuf for
988 * both encrypted and decrypted data. TLS records decrypted by a NIC
989 * should be queued to the socket buffer as records, but encrypted
990 * data which needs to be decrypted by software arrives as a stream of
991 * regular mbufs which need to be converted. In addition, there may
992 * already be pending encrypted data in the socket buffer when KTLS RX
995 * To manage not-yet-decrypted data for KTLS RX, the following scheme
998 * - A single chain of NOTREADY mbufs is hung off of sb_mtls.
1000 * - ktls_check_rx checks this chain of mbufs reading the TLS header
1001 * from the first mbuf. Once all of the data for that TLS record is
1002 * queued, the socket is queued to a worker thread.
1004 * - The worker thread calls ktls_decrypt to decrypt TLS records in
1005 * the TLS chain. Each TLS record is detached from the TLS chain,
1006 * decrypted, and inserted into the regular socket buffer chain as
1007 * record starting with a control message holding the TLS header and
1008 * a chain of mbufs holding the encrypted data.
1012 sb_mark_notready(struct sockbuf *sb)
1019 sb->sb_mbtail = NULL;
1020 sb->sb_lastrecord = NULL;
1021 for (; m != NULL; m = m->m_next) {
1022 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt != NULL",
1024 KASSERT((m->m_flags & M_NOTAVAIL) == 0, ("%s: mbuf not avail",
1026 KASSERT(sb->sb_acc >= m->m_len, ("%s: sb_acc < m->m_len",
1028 m->m_flags |= M_NOTREADY;
1029 sb->sb_acc -= m->m_len;
1030 sb->sb_tlscc += m->m_len;
1031 sb->sb_mtlstail = m;
1033 KASSERT(sb->sb_acc == 0 && sb->sb_tlscc == sb->sb_ccc,
1034 ("%s: acc %u tlscc %u ccc %u", __func__, sb->sb_acc, sb->sb_tlscc,
1039 ktls_enable_rx(struct socket *so, struct tls_enable *en)
1041 struct ktls_session *tls;
1044 if (!ktls_offload_enable)
1046 if (SOLISTENING(so))
1049 counter_u64_add(ktls_offload_enable_calls, 1);
1052 * This should always be true since only the TCP socket option
1053 * invokes this function.
1055 if (so->so_proto->pr_protocol != IPPROTO_TCP)
1059 * XXX: Don't overwrite existing sessions. We should permit
1060 * this to support rekeying in the future.
1062 if (so->so_rcv.sb_tls_info != NULL)
1065 if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1068 /* TLS 1.3 is not yet supported. */
1069 if (en->tls_vmajor == TLS_MAJOR_VER_ONE &&
1070 en->tls_vminor == TLS_MINOR_VER_THREE)
1073 error = ktls_create_session(so, en, &tls);
1078 error = ktls_try_toe(so, tls, KTLS_RX);
1081 error = ktls_try_sw(so, tls, KTLS_RX);
1088 /* Mark the socket as using TLS offload. */
1089 SOCKBUF_LOCK(&so->so_rcv);
1090 so->so_rcv.sb_tls_seqno = be64dec(en->rec_seq);
1091 so->so_rcv.sb_tls_info = tls;
1092 so->so_rcv.sb_flags |= SB_TLS_RX;
1094 /* Mark existing data as not ready until it can be decrypted. */
1095 if (tls->mode != TCP_TLS_MODE_TOE) {
1096 sb_mark_notready(&so->so_rcv);
1097 ktls_check_rx(&so->so_rcv);
1099 SOCKBUF_UNLOCK(&so->so_rcv);
1101 counter_u64_add(ktls_offload_total, 1);
1107 ktls_enable_tx(struct socket *so, struct tls_enable *en)
1109 struct ktls_session *tls;
1113 if (!ktls_offload_enable)
1115 if (SOLISTENING(so))
1118 counter_u64_add(ktls_offload_enable_calls, 1);
1121 * This should always be true since only the TCP socket option
1122 * invokes this function.
1124 if (so->so_proto->pr_protocol != IPPROTO_TCP)
1128 * XXX: Don't overwrite existing sessions. We should permit
1129 * this to support rekeying in the future.
1131 if (so->so_snd.sb_tls_info != NULL)
1134 if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1137 /* TLS requires ext pgs */
1138 if (mb_use_ext_pgs == 0)
1141 error = ktls_create_session(so, en, &tls);
1145 /* Prefer TOE -> ifnet TLS -> software TLS. */
1147 error = ktls_try_toe(so, tls, KTLS_TX);
1150 error = ktls_try_ifnet(so, tls, false);
1152 error = ktls_try_sw(so, tls, KTLS_TX);
1159 error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1166 * Write lock the INP when setting sb_tls_info so that
1167 * routines in tcp_ratelimit.c can read sb_tls_info while
1168 * holding the INP lock.
1172 SOCKBUF_LOCK(&so->so_snd);
1173 so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1174 so->so_snd.sb_tls_info = tls;
1175 if (tls->mode != TCP_TLS_MODE_SW)
1176 so->so_snd.sb_flags |= SB_TLS_IFNET;
1177 SOCKBUF_UNLOCK(&so->so_snd);
1179 SOCK_IO_SEND_UNLOCK(so);
1181 counter_u64_add(ktls_offload_total, 1);
1187 ktls_get_rx_mode(struct socket *so)
1189 struct ktls_session *tls;
1193 if (SOLISTENING(so))
1196 INP_WLOCK_ASSERT(inp);
1197 SOCKBUF_LOCK(&so->so_rcv);
1198 tls = so->so_rcv.sb_tls_info;
1200 mode = TCP_TLS_MODE_NONE;
1203 SOCKBUF_UNLOCK(&so->so_rcv);
1208 ktls_get_tx_mode(struct socket *so)
1210 struct ktls_session *tls;
1214 if (SOLISTENING(so))
1217 INP_WLOCK_ASSERT(inp);
1218 SOCKBUF_LOCK(&so->so_snd);
1219 tls = so->so_snd.sb_tls_info;
1221 mode = TCP_TLS_MODE_NONE;
1224 SOCKBUF_UNLOCK(&so->so_snd);
1229 * Switch between SW and ifnet TLS sessions as requested.
1232 ktls_set_tx_mode(struct socket *so, int mode)
1234 struct ktls_session *tls, *tls_new;
1238 if (SOLISTENING(so))
1241 case TCP_TLS_MODE_SW:
1242 case TCP_TLS_MODE_IFNET:
1249 INP_WLOCK_ASSERT(inp);
1250 SOCKBUF_LOCK(&so->so_snd);
1251 tls = so->so_snd.sb_tls_info;
1253 SOCKBUF_UNLOCK(&so->so_snd);
1257 if (tls->mode == mode) {
1258 SOCKBUF_UNLOCK(&so->so_snd);
1262 tls = ktls_hold(tls);
1263 SOCKBUF_UNLOCK(&so->so_snd);
1266 tls_new = ktls_clone_session(tls);
1268 if (mode == TCP_TLS_MODE_IFNET)
1269 error = ktls_try_ifnet(so, tls_new, true);
1271 error = ktls_try_sw(so, tls_new, KTLS_TX);
1273 counter_u64_add(ktls_switch_failed, 1);
1280 error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1282 counter_u64_add(ktls_switch_failed, 1);
1290 * If we raced with another session change, keep the existing
1293 if (tls != so->so_snd.sb_tls_info) {
1294 counter_u64_add(ktls_switch_failed, 1);
1295 SOCK_IO_SEND_UNLOCK(so);
1302 SOCKBUF_LOCK(&so->so_snd);
1303 so->so_snd.sb_tls_info = tls_new;
1304 if (tls_new->mode != TCP_TLS_MODE_SW)
1305 so->so_snd.sb_flags |= SB_TLS_IFNET;
1306 SOCKBUF_UNLOCK(&so->so_snd);
1307 SOCK_IO_SEND_UNLOCK(so);
1310 * Drop two references on 'tls'. The first is for the
1311 * ktls_hold() above. The second drops the reference from the
1314 KASSERT(tls->refcount >= 2, ("too few references on old session"));
1318 if (mode == TCP_TLS_MODE_IFNET)
1319 counter_u64_add(ktls_switch_to_ifnet, 1);
1321 counter_u64_add(ktls_switch_to_sw, 1);
1328 * Try to allocate a new TLS send tag. This task is scheduled when
1329 * ip_output detects a route change while trying to transmit a packet
1330 * holding a TLS record. If a new tag is allocated, replace the tag
1331 * in the TLS session. Subsequent packets on the connection will use
1332 * the new tag. If a new tag cannot be allocated, drop the
1336 ktls_reset_send_tag(void *context, int pending)
1338 struct epoch_tracker et;
1339 struct ktls_session *tls;
1340 struct m_snd_tag *old, *new;
1345 MPASS(pending == 1);
1351 * Free the old tag first before allocating a new one.
1352 * ip[6]_output_send() will treat a NULL send tag the same as
1353 * an ifp mismatch and drop packets until a new tag is
1356 * Write-lock the INP when changing tls->snd_tag since
1357 * ip[6]_output_send() holds a read-lock when reading the
1362 tls->snd_tag = NULL;
1365 m_snd_tag_rele(old);
1367 error = ktls_alloc_snd_tag(inp, tls, true, &new);
1372 mtx_pool_lock(mtxpool_sleep, tls);
1373 tls->reset_pending = false;
1374 mtx_pool_unlock(mtxpool_sleep, tls);
1375 if (!in_pcbrele_wlocked(inp))
1378 counter_u64_add(ktls_ifnet_reset, 1);
1381 * XXX: Should we kick tcp_output explicitly now that
1382 * the send tag is fixed or just rely on timers?
1385 NET_EPOCH_ENTER(et);
1387 if (!in_pcbrele_wlocked(inp)) {
1388 if (!(inp->inp_flags & INP_TIMEWAIT) &&
1389 !(inp->inp_flags & INP_DROPPED)) {
1390 tp = intotcpcb(inp);
1391 CURVNET_SET(tp->t_vnet);
1392 tp = tcp_drop(tp, ECONNABORTED);
1396 counter_u64_add(ktls_ifnet_reset_dropped, 1);
1402 counter_u64_add(ktls_ifnet_reset_failed, 1);
1405 * Leave reset_pending true to avoid future tasks while
1406 * the socket goes away.
1414 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1420 INP_LOCK_ASSERT(inp);
1423 * See if we should schedule a task to update the send tag for
1426 mtx_pool_lock(mtxpool_sleep, tls);
1427 if (!tls->reset_pending) {
1428 (void) ktls_hold(tls);
1431 tls->reset_pending = true;
1432 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1434 mtx_pool_unlock(mtxpool_sleep, tls);
1440 ktls_modify_txrtlmt(struct ktls_session *tls, uint64_t max_pacing_rate)
1442 union if_snd_tag_modify_params params = {
1443 .rate_limit.max_rate = max_pacing_rate,
1444 .rate_limit.flags = M_NOWAIT,
1446 struct m_snd_tag *mst;
1450 /* Can't get to the inp, but it should be locked. */
1451 /* INP_LOCK_ASSERT(inp); */
1453 MPASS(tls->mode == TCP_TLS_MODE_IFNET);
1455 if (tls->snd_tag == NULL) {
1457 * Resetting send tag, ignore this change. The
1458 * pending reset may or may not see this updated rate
1459 * in the tcpcb. If it doesn't, we will just lose
1465 MPASS(tls->snd_tag != NULL);
1466 MPASS(tls->snd_tag->type == IF_SND_TAG_TYPE_TLS_RATE_LIMIT);
1470 return (ifp->if_snd_tag_modify(mst, ¶ms));
1476 ktls_destroy(struct ktls_session *tls)
1478 struct rm_priotracker prio;
1481 if (tls->be != NULL && ktls_allow_unload) {
1482 rm_rlock(&ktls_backends_lock, &prio);
1483 tls->be->use_count--;
1484 rm_runlock(&ktls_backends_lock, &prio);
1486 uma_zfree(ktls_session_zone, tls);
1490 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1493 for (; m != NULL; m = m->m_next) {
1494 KASSERT((m->m_flags & M_EXTPG) != 0,
1495 ("ktls_seq: mapped mbuf %p", m));
1497 m->m_epg_seqno = sb->sb_tls_seqno;
1503 * Add TLS framing (headers and trailers) to a chain of mbufs. Each
1504 * mbuf in the chain must be an unmapped mbuf. The payload of the
1505 * mbuf must be populated with the payload of each TLS record.
1507 * The record_type argument specifies the TLS record type used when
1508 * populating the TLS header.
1510 * The enq_count argument on return is set to the number of pages of
1511 * payload data for this entire chain that need to be encrypted via SW
1512 * encryption. The returned value should be passed to ktls_enqueue
1513 * when scheduling encryption of this chain of mbufs. To handle the
1514 * special case of empty fragments for TLS 1.0 sessions, an empty
1515 * fragment counts as one page.
1518 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1519 uint8_t record_type)
1521 struct tls_record_layer *tlshdr;
1527 maxlen = tls->params.max_frame_len;
1529 for (m = top; m != NULL; m = m->m_next) {
1531 * All mbufs in the chain should be TLS records whose
1532 * payload does not exceed the maximum frame length.
1534 * Empty TLS records are permitted when using CBC.
1536 KASSERT(m->m_len <= maxlen &&
1537 (tls->params.cipher_algorithm == CRYPTO_AES_CBC ?
1538 m->m_len >= 0 : m->m_len > 0),
1539 ("ktls_frame: m %p len %d\n", m, m->m_len));
1542 * TLS frames require unmapped mbufs to store session
1545 KASSERT((m->m_flags & M_EXTPG) != 0,
1546 ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1550 /* Save a reference to the session. */
1551 m->m_epg_tls = ktls_hold(tls);
1553 m->m_epg_hdrlen = tls->params.tls_hlen;
1554 m->m_epg_trllen = tls->params.tls_tlen;
1555 if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1559 * AES-CBC pads messages to a multiple of the
1560 * block size. Note that the padding is
1561 * applied after the digest and the encryption
1562 * is done on the "plaintext || mac || padding".
1563 * At least one byte of padding is always
1566 * Compute the final trailer length assuming
1567 * at most one block of padding.
1568 * tls->params.sb_tls_tlen is the maximum
1569 * possible trailer length (padding + digest).
1570 * delta holds the number of excess padding
1571 * bytes if the maximum were used. Those
1572 * extra bytes are removed.
1574 bs = tls->params.tls_bs;
1575 delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
1576 m->m_epg_trllen -= delta;
1578 m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
1580 /* Populate the TLS header. */
1581 tlshdr = (void *)m->m_epg_hdr;
1582 tlshdr->tls_vmajor = tls->params.tls_vmajor;
1585 * TLS 1.3 masquarades as TLS 1.2 with a record type
1586 * of TLS_RLTYPE_APP.
1588 if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
1589 tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
1590 tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
1591 tlshdr->tls_type = TLS_RLTYPE_APP;
1592 /* save the real record type for later */
1593 m->m_epg_record_type = record_type;
1594 m->m_epg_trail[0] = record_type;
1596 tlshdr->tls_vminor = tls->params.tls_vminor;
1597 tlshdr->tls_type = record_type;
1599 tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1602 * Store nonces / explicit IVs after the end of the
1605 * For GCM with TLS 1.2, an 8 byte nonce is copied
1606 * from the end of the IV. The nonce is then
1607 * incremented for use by the next record.
1609 * For CBC, a random nonce is inserted for TLS 1.1+.
1611 if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
1612 tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
1613 noncep = (uint64_t *)(tls->params.iv + 8);
1614 be64enc(tlshdr + 1, *noncep);
1616 } else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
1617 tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
1618 arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
1621 * When using SW encryption, mark the mbuf not ready.
1622 * It will be marked ready via sbready() after the
1623 * record has been encrypted.
1625 * When using ifnet TLS, unencrypted TLS records are
1626 * sent down the stack to the NIC.
1628 if (tls->mode == TCP_TLS_MODE_SW) {
1629 m->m_flags |= M_NOTREADY;
1630 if (__predict_false(tls_len == 0)) {
1631 /* TLS 1.0 empty fragment. */
1634 m->m_epg_nrdy = m->m_epg_npgs;
1635 *enq_cnt += m->m_epg_nrdy;
1641 ktls_check_rx(struct sockbuf *sb)
1643 struct tls_record_layer hdr;
1648 SOCKBUF_LOCK_ASSERT(sb);
1649 KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
1651 so = __containerof(sb, struct socket, so_rcv);
1653 if (sb->sb_flags & SB_TLS_RX_RUNNING)
1656 /* Is there enough queued for a TLS header? */
1657 if (sb->sb_tlscc < sizeof(hdr)) {
1658 if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc != 0)
1659 so->so_error = EMSGSIZE;
1663 m_copydata(sb->sb_mtls, 0, sizeof(hdr), (void *)&hdr);
1665 /* Is the entire record queued? */
1666 if (sb->sb_tlscc < sizeof(hdr) + ntohs(hdr.tls_length)) {
1667 if ((sb->sb_state & SBS_CANTRCVMORE) != 0)
1668 so->so_error = EMSGSIZE;
1672 sb->sb_flags |= SB_TLS_RX_RUNNING;
1675 wq = &ktls_wq[so->so_rcv.sb_tls_info->wq_index];
1677 STAILQ_INSERT_TAIL(&wq->so_head, so, so_ktls_rx_list);
1678 running = wq->running;
1679 mtx_unlock(&wq->mtx);
1682 counter_u64_add(ktls_cnt_rx_queued, 1);
1685 static struct mbuf *
1686 ktls_detach_record(struct sockbuf *sb, int len)
1688 struct mbuf *m, *n, *top;
1691 SOCKBUF_LOCK_ASSERT(sb);
1692 MPASS(len <= sb->sb_tlscc);
1695 * If TLS chain is the exact size of the record,
1696 * just grab the whole record.
1699 if (sb->sb_tlscc == len) {
1701 sb->sb_mtlstail = NULL;
1706 * While it would be nice to use m_split() here, we need
1707 * to know exactly what m_split() allocates to update the
1708 * accounting, so do it inline instead.
1711 for (m = top; remain > m->m_len; m = m->m_next)
1714 /* Easy case: don't have to split 'm'. */
1715 if (remain == m->m_len) {
1716 sb->sb_mtls = m->m_next;
1717 if (sb->sb_mtls == NULL)
1718 sb->sb_mtlstail = NULL;
1724 * Need to allocate an mbuf to hold the remainder of 'm'. Try
1725 * with M_NOWAIT first.
1727 n = m_get(M_NOWAIT, MT_DATA);
1730 * Use M_WAITOK with socket buffer unlocked. If
1731 * 'sb_mtls' changes while the lock is dropped, return
1732 * NULL to force the caller to retry.
1736 n = m_get(M_WAITOK, MT_DATA);
1739 if (sb->sb_mtls != top) {
1744 n->m_flags |= M_NOTREADY;
1746 /* Store remainder in 'n'. */
1747 n->m_len = m->m_len - remain;
1748 if (m->m_flags & M_EXT) {
1749 n->m_data = m->m_data + remain;
1752 bcopy(mtod(m, caddr_t) + remain, mtod(n, caddr_t), n->m_len);
1755 /* Trim 'm' and update accounting. */
1756 m->m_len -= n->m_len;
1757 sb->sb_tlscc -= n->m_len;
1758 sb->sb_ccc -= n->m_len;
1760 /* Account for 'n'. */
1761 sballoc_ktls_rx(sb, n);
1763 /* Insert 'n' into the TLS chain. */
1765 n->m_next = m->m_next;
1766 if (sb->sb_mtlstail == m)
1767 sb->sb_mtlstail = n;
1769 /* Detach the record from the TLS chain. */
1773 MPASS(m_length(top, NULL) == len);
1774 for (m = top; m != NULL; m = m->m_next)
1775 sbfree_ktls_rx(sb, m);
1776 sb->sb_tlsdcc = len;
1783 ktls_decrypt(struct socket *so)
1785 char tls_header[MBUF_PEXT_HDR_LEN];
1786 struct ktls_session *tls;
1788 struct tls_record_layer *hdr;
1789 struct tls_get_record tgr;
1790 struct mbuf *control, *data, *m;
1792 int error, remain, tls_len, trail_len;
1794 hdr = (struct tls_record_layer *)tls_header;
1797 KASSERT(sb->sb_flags & SB_TLS_RX_RUNNING,
1798 ("%s: socket %p not running", __func__, so));
1800 tls = sb->sb_tls_info;
1804 /* Is there enough queued for a TLS header? */
1805 if (sb->sb_tlscc < tls->params.tls_hlen)
1808 m_copydata(sb->sb_mtls, 0, tls->params.tls_hlen, tls_header);
1809 tls_len = sizeof(*hdr) + ntohs(hdr->tls_length);
1811 if (hdr->tls_vmajor != tls->params.tls_vmajor ||
1812 hdr->tls_vminor != tls->params.tls_vminor)
1814 else if (tls_len < tls->params.tls_hlen || tls_len >
1815 tls->params.tls_hlen + TLS_MAX_MSG_SIZE_V10_2 +
1816 tls->params.tls_tlen)
1820 if (__predict_false(error != 0)) {
1822 * We have a corrupted record and are likely
1823 * out of sync. The connection isn't
1824 * recoverable at this point, so abort it.
1827 counter_u64_add(ktls_offload_corrupted_records, 1);
1829 CURVNET_SET(so->so_vnet);
1830 so->so_proto->pr_usrreqs->pru_abort(so);
1831 so->so_error = error;
1836 /* Is the entire record queued? */
1837 if (sb->sb_tlscc < tls_len)
1841 * Split out the portion of the mbuf chain containing
1844 data = ktls_detach_record(sb, tls_len);
1847 MPASS(sb->sb_tlsdcc == tls_len);
1849 seqno = sb->sb_tls_seqno;
1854 error = tls->sw_decrypt(tls, hdr, data, seqno, &trail_len);
1856 counter_u64_add(ktls_offload_failed_crypto, 1);
1859 if (sb->sb_tlsdcc == 0) {
1861 * sbcut/drop/flush discarded these
1869 * Drop this TLS record's data, but keep
1870 * decrypting subsequent records.
1872 sb->sb_ccc -= tls_len;
1875 CURVNET_SET(so->so_vnet);
1876 so->so_error = EBADMSG;
1877 sorwakeup_locked(so);
1886 /* Allocate the control mbuf. */
1887 tgr.tls_type = hdr->tls_type;
1888 tgr.tls_vmajor = hdr->tls_vmajor;
1889 tgr.tls_vminor = hdr->tls_vminor;
1890 tgr.tls_length = htobe16(tls_len - tls->params.tls_hlen -
1892 control = sbcreatecontrol_how(&tgr, sizeof(tgr),
1893 TLS_GET_RECORD, IPPROTO_TCP, M_WAITOK);
1896 if (sb->sb_tlsdcc == 0) {
1897 /* sbcut/drop/flush discarded these mbufs. */
1898 MPASS(sb->sb_tlscc == 0);
1905 * Clear the 'dcc' accounting in preparation for
1906 * adding the decrypted record.
1908 sb->sb_ccc -= tls_len;
1912 /* If there is no payload, drop all of the data. */
1913 if (tgr.tls_length == htobe16(0)) {
1918 remain = tls->params.tls_hlen;
1919 while (remain > 0) {
1920 if (data->m_len > remain) {
1921 data->m_data += remain;
1922 data->m_len -= remain;
1925 remain -= data->m_len;
1926 data = m_free(data);
1929 /* Trim trailer and clear M_NOTREADY. */
1930 remain = be16toh(tgr.tls_length);
1932 for (m = data; remain > m->m_len; m = m->m_next) {
1933 m->m_flags &= ~M_NOTREADY;
1939 m->m_flags &= ~M_NOTREADY;
1941 /* Set EOR on the final mbuf. */
1942 m->m_flags |= M_EOR;
1945 sbappendcontrol_locked(sb, data, control, 0);
1948 sb->sb_flags &= ~SB_TLS_RX_RUNNING;
1950 if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc > 0)
1951 so->so_error = EMSGSIZE;
1953 sorwakeup_locked(so);
1956 SOCKBUF_UNLOCK_ASSERT(sb);
1958 CURVNET_SET(so->so_vnet);
1965 ktls_enqueue_to_free(struct mbuf *m)
1970 /* Mark it for freeing. */
1971 m->m_epg_flags |= EPG_FLAG_2FREE;
1972 wq = &ktls_wq[m->m_epg_tls->wq_index];
1974 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
1975 running = wq->running;
1976 mtx_unlock(&wq->mtx);
1982 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
1987 KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
1988 (M_EXTPG | M_NOTREADY)),
1989 ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
1990 KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
1992 KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
1994 m->m_epg_enc_cnt = page_count;
1997 * Save a pointer to the socket. The caller is responsible
1998 * for taking an additional reference via soref().
2002 wq = &ktls_wq[m->m_epg_tls->wq_index];
2004 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2005 running = wq->running;
2006 mtx_unlock(&wq->mtx);
2009 counter_u64_add(ktls_cnt_tx_queued, 1);
2012 static __noinline void
2013 ktls_encrypt(struct mbuf *top)
2015 struct ktls_session *tls;
2018 vm_paddr_t parray[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
2019 struct iovec src_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
2020 struct iovec dst_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
2022 int error, i, len, npages, off, total_pages;
2026 tls = top->m_epg_tls;
2027 KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
2028 KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
2030 top->m_epg_so = NULL;
2032 total_pages = top->m_epg_enc_cnt;
2036 * Encrypt the TLS records in the chain of mbufs starting with
2037 * 'top'. 'total_pages' gives us a total count of pages and is
2038 * used to know when we have finished encrypting the TLS
2039 * records originally queued with 'top'.
2041 * NB: These mbufs are queued in the socket buffer and
2042 * 'm_next' is traversing the mbufs in the socket buffer. The
2043 * socket buffer lock is not held while traversing this chain.
2044 * Since the mbufs are all marked M_NOTREADY their 'm_next'
2045 * pointers should be stable. However, the 'm_next' of the
2046 * last mbuf encrypted is not necessarily NULL. It can point
2047 * to other mbufs appended while 'top' was on the TLS work
2050 * Each mbuf holds an entire TLS record.
2053 for (m = top; npages != total_pages; m = m->m_next) {
2054 KASSERT(m->m_epg_tls == tls,
2055 ("different TLS sessions in a single mbuf chain: %p vs %p",
2056 tls, m->m_epg_tls));
2057 KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
2058 (M_EXTPG | M_NOTREADY),
2059 ("%p not unready & nomap mbuf (top = %p)\n", m, top));
2060 KASSERT(npages + m->m_epg_npgs <= total_pages,
2061 ("page count mismatch: top %p, total_pages %d, m %p", top,
2065 * Generate source and destination ivoecs to pass to
2066 * the SW encryption backend. For writable mbufs, the
2067 * destination iovec is a copy of the source and
2068 * encryption is done in place. For file-backed mbufs
2069 * (from sendfile), anonymous wired pages are
2070 * allocated and assigned to the destination iovec.
2072 is_anon = (m->m_epg_flags & EPG_FLAG_ANON) != 0;
2074 off = m->m_epg_1st_off;
2075 for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
2076 len = m_epg_pagelen(m, i, off);
2077 src_iov[i].iov_len = len;
2078 src_iov[i].iov_base =
2079 (char *)(void *)PHYS_TO_DMAP(m->m_epg_pa[i]) +
2083 dst_iov[i].iov_base = src_iov[i].iov_base;
2084 dst_iov[i].iov_len = src_iov[i].iov_len;
2088 pg = vm_page_alloc_noobj(VM_ALLOC_NODUMP |
2094 parray[i] = VM_PAGE_TO_PHYS(pg);
2095 dst_iov[i].iov_base =
2096 (char *)(void *)PHYS_TO_DMAP(parray[i]) + off;
2097 dst_iov[i].iov_len = len;
2100 npages += m->m_epg_nrdy;
2102 error = (*tls->sw_encrypt)(tls,
2103 (const struct tls_record_layer *)m->m_epg_hdr,
2104 m->m_epg_trail, src_iov, dst_iov, i, m->m_epg_seqno,
2105 m->m_epg_record_type);
2107 counter_u64_add(ktls_offload_failed_crypto, 1);
2112 * For file-backed mbufs, release the file-backed
2113 * pages and replace them in the ext_pgs array with
2114 * the anonymous wired pages allocated above.
2117 /* Free the old pages. */
2118 m->m_ext.ext_free(m);
2120 /* Replace them with the new pages. */
2121 for (i = 0; i < m->m_epg_npgs; i++)
2122 m->m_epg_pa[i] = parray[i];
2124 /* Use the basic free routine. */
2125 m->m_ext.ext_free = mb_free_mext_pgs;
2127 /* Pages are now writable. */
2128 m->m_epg_flags |= EPG_FLAG_ANON;
2132 * Drop a reference to the session now that it is no
2133 * longer needed. Existing code depends on encrypted
2134 * records having no associated session vs
2135 * yet-to-be-encrypted records having an associated
2138 m->m_epg_tls = NULL;
2142 CURVNET_SET(so->so_vnet);
2144 (void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
2146 so->so_proto->pr_usrreqs->pru_abort(so);
2148 mb_free_notready(top, total_pages);
2157 ktls_work_thread(void *ctx)
2159 struct ktls_wq *wq = ctx;
2161 struct socket *so, *son;
2162 STAILQ_HEAD(, mbuf) local_m_head;
2163 STAILQ_HEAD(, socket) local_so_head;
2165 if (ktls_bind_threads > 1) {
2166 curthread->td_domain.dr_policy =
2167 DOMAINSET_PREF(PCPU_GET(domain));
2169 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
2174 while (STAILQ_EMPTY(&wq->m_head) &&
2175 STAILQ_EMPTY(&wq->so_head)) {
2176 wq->running = false;
2177 mtx_sleep(wq, &wq->mtx, 0, "-", 0);
2181 STAILQ_INIT(&local_m_head);
2182 STAILQ_CONCAT(&local_m_head, &wq->m_head);
2183 STAILQ_INIT(&local_so_head);
2184 STAILQ_CONCAT(&local_so_head, &wq->so_head);
2185 mtx_unlock(&wq->mtx);
2187 STAILQ_FOREACH_SAFE(m, &local_m_head, m_epg_stailq, n) {
2188 if (m->m_epg_flags & EPG_FLAG_2FREE) {
2189 ktls_free(m->m_epg_tls);
2193 counter_u64_add(ktls_cnt_tx_queued, -1);
2197 STAILQ_FOREACH_SAFE(so, &local_so_head, so_ktls_rx_list, son) {
2199 counter_u64_add(ktls_cnt_rx_queued, -1);