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/netisr.h>
59 #include <net/rss_config.h>
61 #if defined(INET) || defined(INET6)
62 #include <netinet/in.h>
63 #include <netinet/in_pcb.h>
65 #include <netinet/tcp_var.h>
67 #include <netinet/tcp_offload.h>
69 #include <opencrypto/xform.h>
70 #include <vm/uma_dbg.h>
72 #include <vm/vm_pageout.h>
73 #include <vm/vm_page.h>
77 STAILQ_HEAD(, mbuf_ext_pgs) head;
79 } __aligned(CACHE_LINE_SIZE);
81 static struct ktls_wq *ktls_wq;
82 static struct proc *ktls_proc;
83 LIST_HEAD(, ktls_crypto_backend) ktls_backends;
84 static struct rmlock ktls_backends_lock;
85 static uma_zone_t ktls_session_zone;
86 static uint16_t ktls_cpuid_lookup[MAXCPU];
88 SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW, 0,
89 "Kernel TLS offload");
90 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW, 0,
91 "Kernel TLS offload stats");
93 static int ktls_allow_unload;
94 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, allow_unload, CTLFLAG_RDTUN,
95 &ktls_allow_unload, 0, "Allow software crypto modules to unload");
98 static int ktls_bind_threads = 1;
100 static int ktls_bind_threads;
102 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
103 &ktls_bind_threads, 0,
104 "Bind crypto threads to cores or domains at boot");
106 static u_int ktls_maxlen = 16384;
107 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RWTUN,
108 &ktls_maxlen, 0, "Maximum TLS record size");
110 static int ktls_number_threads;
111 SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
112 &ktls_number_threads, 0,
113 "Number of TLS threads in thread-pool");
115 static bool ktls_offload_enable;
116 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RW,
117 &ktls_offload_enable, 0,
118 "Enable support for kernel TLS offload");
120 static bool ktls_cbc_enable = true;
121 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RW,
123 "Enable Support of AES-CBC crypto for kernel TLS");
125 static counter_u64_t ktls_tasks_active;
126 SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
127 &ktls_tasks_active, "Number of active tasks");
129 static counter_u64_t ktls_cnt_on;
130 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, so_inqueue, CTLFLAG_RD,
131 &ktls_cnt_on, "Number of TLS records in queue to tasks for SW crypto");
133 static counter_u64_t ktls_offload_total;
134 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
135 CTLFLAG_RD, &ktls_offload_total,
136 "Total successful TLS setups (parameters set)");
138 static counter_u64_t ktls_offload_enable_calls;
139 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
140 CTLFLAG_RD, &ktls_offload_enable_calls,
141 "Total number of TLS enable calls made");
143 static counter_u64_t ktls_offload_active;
144 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
145 &ktls_offload_active, "Total Active TLS sessions");
147 static counter_u64_t ktls_offload_failed_crypto;
148 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
149 &ktls_offload_failed_crypto, "Total TLS crypto failures");
151 static counter_u64_t ktls_switch_to_ifnet;
152 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
153 &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
155 static counter_u64_t ktls_switch_to_sw;
156 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
157 &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
159 static counter_u64_t ktls_switch_failed;
160 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
161 &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
163 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD, 0,
164 "Software TLS session stats");
165 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD, 0,
166 "Hardware (ifnet) TLS session stats");
168 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD, 0,
169 "TOE TLS session stats");
172 static counter_u64_t ktls_sw_cbc;
173 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
174 "Active number of software TLS sessions using AES-CBC");
176 static counter_u64_t ktls_sw_gcm;
177 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
178 "Active number of software TLS sessions using AES-GCM");
180 static counter_u64_t ktls_ifnet_cbc;
181 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
183 "Active number of ifnet TLS sessions using AES-CBC");
185 static counter_u64_t ktls_ifnet_gcm;
186 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
188 "Active number of ifnet TLS sessions using AES-GCM");
190 static counter_u64_t ktls_ifnet_reset;
191 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
192 &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
194 static counter_u64_t ktls_ifnet_reset_dropped;
195 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
196 &ktls_ifnet_reset_dropped,
197 "TLS sessions dropped after failing to update ifnet send tag");
199 static counter_u64_t ktls_ifnet_reset_failed;
200 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
201 &ktls_ifnet_reset_failed,
202 "TLS sessions that failed to allocate a new ifnet send tag");
204 static int ktls_ifnet_permitted;
205 SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
206 &ktls_ifnet_permitted, 1,
207 "Whether to permit hardware (ifnet) TLS sessions");
210 static counter_u64_t ktls_toe_cbc;
211 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
213 "Active number of TOE TLS sessions using AES-CBC");
215 static counter_u64_t ktls_toe_gcm;
216 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
218 "Active number of TOE TLS sessions using AES-GCM");
221 static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
223 static void ktls_cleanup(struct ktls_session *tls);
224 #if defined(INET) || defined(INET6)
225 static void ktls_reset_send_tag(void *context, int pending);
227 static void ktls_work_thread(void *ctx);
230 ktls_crypto_backend_register(struct ktls_crypto_backend *be)
232 struct ktls_crypto_backend *curr_be, *tmp;
234 if (be->api_version != KTLS_API_VERSION) {
235 printf("KTLS: API version mismatch (%d vs %d) for %s\n",
236 be->api_version, KTLS_API_VERSION,
241 rm_wlock(&ktls_backends_lock);
242 printf("KTLS: Registering crypto method %s with prio %d\n",
244 if (LIST_EMPTY(&ktls_backends)) {
245 LIST_INSERT_HEAD(&ktls_backends, be, next);
247 LIST_FOREACH_SAFE(curr_be, &ktls_backends, next, tmp) {
248 if (curr_be->prio < be->prio) {
249 LIST_INSERT_BEFORE(curr_be, be, next);
252 if (LIST_NEXT(curr_be, next) == NULL) {
253 LIST_INSERT_AFTER(curr_be, be, next);
258 rm_wunlock(&ktls_backends_lock);
263 ktls_crypto_backend_deregister(struct ktls_crypto_backend *be)
265 struct ktls_crypto_backend *tmp;
268 * Don't error if the backend isn't registered. This permits
269 * MOD_UNLOAD handlers to use this function unconditionally.
271 rm_wlock(&ktls_backends_lock);
272 LIST_FOREACH(tmp, &ktls_backends, next) {
277 rm_wunlock(&ktls_backends_lock);
281 if (!ktls_allow_unload) {
282 rm_wunlock(&ktls_backends_lock);
284 "KTLS: Deregistering crypto method %s is not supported\n",
290 rm_wunlock(&ktls_backends_lock);
294 LIST_REMOVE(be, next);
295 rm_wunlock(&ktls_backends_lock);
299 #if defined(INET) || defined(INET6)
301 ktls_get_cpu(struct socket *so)
308 cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
309 if (cpuid != NETISR_CPUID_NONE)
313 * Just use the flowid to shard connections in a repeatable
314 * fashion. Note that some crypto backends rely on the
315 * serialization provided by having the same connection use
318 cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
324 ktls_init(void *dummy __unused)
331 ktls_tasks_active = counter_u64_alloc(M_WAITOK);
332 ktls_cnt_on = counter_u64_alloc(M_WAITOK);
333 ktls_offload_total = counter_u64_alloc(M_WAITOK);
334 ktls_offload_enable_calls = counter_u64_alloc(M_WAITOK);
335 ktls_offload_active = counter_u64_alloc(M_WAITOK);
336 ktls_offload_failed_crypto = counter_u64_alloc(M_WAITOK);
337 ktls_switch_to_ifnet = counter_u64_alloc(M_WAITOK);
338 ktls_switch_to_sw = counter_u64_alloc(M_WAITOK);
339 ktls_switch_failed = counter_u64_alloc(M_WAITOK);
340 ktls_sw_cbc = counter_u64_alloc(M_WAITOK);
341 ktls_sw_gcm = counter_u64_alloc(M_WAITOK);
342 ktls_ifnet_cbc = counter_u64_alloc(M_WAITOK);
343 ktls_ifnet_gcm = counter_u64_alloc(M_WAITOK);
344 ktls_ifnet_reset = counter_u64_alloc(M_WAITOK);
345 ktls_ifnet_reset_dropped = counter_u64_alloc(M_WAITOK);
346 ktls_ifnet_reset_failed = counter_u64_alloc(M_WAITOK);
348 ktls_toe_cbc = counter_u64_alloc(M_WAITOK);
349 ktls_toe_gcm = counter_u64_alloc(M_WAITOK);
352 rm_init(&ktls_backends_lock, "ktls backends");
353 LIST_INIT(&ktls_backends);
355 ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
358 ktls_session_zone = uma_zcreate("ktls_session",
359 sizeof(struct ktls_session),
361 trash_ctor, trash_dtor, trash_init, trash_fini,
363 NULL, NULL, NULL, NULL,
368 * Initialize the workqueues to run the TLS work. We create a
369 * work queue for each CPU.
372 STAILQ_INIT(&ktls_wq[i].head);
373 mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
374 error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
375 &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
377 panic("Can't add KTLS thread %d error %d", i, error);
380 * Bind threads to cores. If ktls_bind_threads is >
381 * 1, then we bind to the NUMA domain.
383 if (ktls_bind_threads) {
384 if (ktls_bind_threads > 1) {
386 CPU_COPY(&cpuset_domain[pc->pc_domain], &mask);
390 error = cpuset_setthread(td->td_tid, &mask);
393 "Unable to bind KTLS thread for CPU %d error %d",
396 ktls_cpuid_lookup[ktls_number_threads] = i;
397 ktls_number_threads++;
399 printf("KTLS: Initialized %d threads\n", ktls_number_threads);
401 SYSINIT(ktls, SI_SUB_SMP + 1, SI_ORDER_ANY, ktls_init, NULL);
403 #if defined(INET) || defined(INET6)
405 ktls_create_session(struct socket *so, struct tls_enable *en,
406 struct ktls_session **tlsp)
408 struct ktls_session *tls;
411 /* Only TLS 1.0 - 1.3 are supported. */
412 if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
414 if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
415 en->tls_vminor > TLS_MINOR_VER_THREE)
418 if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
420 if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
422 if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
425 /* All supported algorithms require a cipher key. */
426 if (en->cipher_key_len == 0)
429 /* No flags are currently supported. */
433 /* Common checks for supported algorithms. */
434 switch (en->cipher_algorithm) {
435 case CRYPTO_AES_NIST_GCM_16:
437 * auth_algorithm isn't used, but permit GMAC values
440 switch (en->auth_algorithm) {
442 case CRYPTO_AES_128_NIST_GMAC:
443 case CRYPTO_AES_192_NIST_GMAC:
444 case CRYPTO_AES_256_NIST_GMAC:
449 if (en->auth_key_len != 0)
451 if ((en->tls_vminor == TLS_MINOR_VER_TWO &&
452 en->iv_len != TLS_AEAD_GCM_LEN) ||
453 (en->tls_vminor == TLS_MINOR_VER_THREE &&
454 en->iv_len != TLS_1_3_GCM_IV_LEN))
458 switch (en->auth_algorithm) {
459 case CRYPTO_SHA1_HMAC:
461 * TLS 1.0 requires an implicit IV. TLS 1.1+
462 * all use explicit IVs.
464 if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
465 if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
471 case CRYPTO_SHA2_256_HMAC:
472 case CRYPTO_SHA2_384_HMAC:
473 /* Ignore any supplied IV. */
479 if (en->auth_key_len == 0)
486 tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
488 counter_u64_add(ktls_offload_active, 1);
490 refcount_init(&tls->refcount, 1);
491 TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
493 tls->wq_index = ktls_get_cpu(so);
495 tls->params.cipher_algorithm = en->cipher_algorithm;
496 tls->params.auth_algorithm = en->auth_algorithm;
497 tls->params.tls_vmajor = en->tls_vmajor;
498 tls->params.tls_vminor = en->tls_vminor;
499 tls->params.flags = en->flags;
500 tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
502 /* Set the header and trailer lengths. */
503 tls->params.tls_hlen = sizeof(struct tls_record_layer);
504 switch (en->cipher_algorithm) {
505 case CRYPTO_AES_NIST_GCM_16:
507 * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
508 * nonce. TLS 1.3 uses a 12 byte implicit IV.
510 if (en->tls_vminor < TLS_MINOR_VER_THREE)
511 tls->params.tls_hlen += sizeof(uint64_t);
512 tls->params.tls_tlen = AES_GMAC_HASH_LEN;
515 * TLS 1.3 includes optional padding which we
516 * do not support, and also puts the "real" record
517 * type at the end of the encrypted data.
519 if (en->tls_vminor == TLS_MINOR_VER_THREE)
520 tls->params.tls_tlen += sizeof(uint8_t);
522 tls->params.tls_bs = 1;
525 switch (en->auth_algorithm) {
526 case CRYPTO_SHA1_HMAC:
527 if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
528 /* Implicit IV, no nonce. */
530 tls->params.tls_hlen += AES_BLOCK_LEN;
532 tls->params.tls_tlen = AES_BLOCK_LEN +
535 case CRYPTO_SHA2_256_HMAC:
536 tls->params.tls_hlen += AES_BLOCK_LEN;
537 tls->params.tls_tlen = AES_BLOCK_LEN +
540 case CRYPTO_SHA2_384_HMAC:
541 tls->params.tls_hlen += AES_BLOCK_LEN;
542 tls->params.tls_tlen = AES_BLOCK_LEN +
546 panic("invalid hmac");
548 tls->params.tls_bs = AES_BLOCK_LEN;
551 panic("invalid cipher");
554 KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
555 ("TLS header length too long: %d", tls->params.tls_hlen));
556 KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
557 ("TLS trailer length too long: %d", tls->params.tls_tlen));
559 if (en->auth_key_len != 0) {
560 tls->params.auth_key_len = en->auth_key_len;
561 tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
563 error = copyin(en->auth_key, tls->params.auth_key,
569 tls->params.cipher_key_len = en->cipher_key_len;
570 tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
571 error = copyin(en->cipher_key, tls->params.cipher_key,
577 * This holds the implicit portion of the nonce for GCM and
578 * the initial implicit IV for TLS 1.0. The explicit portions
579 * of the IV are generated in ktls_frame().
581 if (en->iv_len != 0) {
582 tls->params.iv_len = en->iv_len;
583 error = copyin(en->iv, tls->params.iv, en->iv_len);
588 * For TLS 1.2, generate an 8-byte nonce as a counter
589 * to generate unique explicit IVs.
591 * Store this counter in the last 8 bytes of the IV
592 * array so that it is 8-byte aligned.
594 if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
595 en->tls_vminor == TLS_MINOR_VER_TWO)
596 arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
607 static struct ktls_session *
608 ktls_clone_session(struct ktls_session *tls)
610 struct ktls_session *tls_new;
612 tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
614 counter_u64_add(ktls_offload_active, 1);
616 refcount_init(&tls_new->refcount, 1);
618 /* Copy fields from existing session. */
619 tls_new->params = tls->params;
620 tls_new->wq_index = tls->wq_index;
622 /* Deep copy keys. */
623 if (tls_new->params.auth_key != NULL) {
624 tls_new->params.auth_key = malloc(tls->params.auth_key_len,
626 memcpy(tls_new->params.auth_key, tls->params.auth_key,
627 tls->params.auth_key_len);
630 tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
632 memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
633 tls->params.cipher_key_len);
640 ktls_cleanup(struct ktls_session *tls)
643 counter_u64_add(ktls_offload_active, -1);
645 case TCP_TLS_MODE_SW:
646 MPASS(tls->be != NULL);
647 switch (tls->params.cipher_algorithm) {
649 counter_u64_add(ktls_sw_cbc, -1);
651 case CRYPTO_AES_NIST_GCM_16:
652 counter_u64_add(ktls_sw_gcm, -1);
657 case TCP_TLS_MODE_IFNET:
658 switch (tls->params.cipher_algorithm) {
660 counter_u64_add(ktls_ifnet_cbc, -1);
662 case CRYPTO_AES_NIST_GCM_16:
663 counter_u64_add(ktls_ifnet_gcm, -1);
666 m_snd_tag_rele(tls->snd_tag);
669 case TCP_TLS_MODE_TOE:
670 switch (tls->params.cipher_algorithm) {
672 counter_u64_add(ktls_toe_cbc, -1);
674 case CRYPTO_AES_NIST_GCM_16:
675 counter_u64_add(ktls_toe_gcm, -1);
681 if (tls->params.auth_key != NULL) {
682 explicit_bzero(tls->params.auth_key, tls->params.auth_key_len);
683 free(tls->params.auth_key, M_KTLS);
684 tls->params.auth_key = NULL;
685 tls->params.auth_key_len = 0;
687 if (tls->params.cipher_key != NULL) {
688 explicit_bzero(tls->params.cipher_key,
689 tls->params.cipher_key_len);
690 free(tls->params.cipher_key, M_KTLS);
691 tls->params.cipher_key = NULL;
692 tls->params.cipher_key_len = 0;
694 explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
697 #if defined(INET) || defined(INET6)
701 ktls_try_toe(struct socket *so, struct ktls_session *tls)
709 if (inp->inp_flags2 & INP_FREED) {
713 if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
717 if (inp->inp_socket == NULL) {
722 if (tp->tod == NULL) {
727 error = tcp_offload_alloc_tls_session(tp, tls);
730 tls->mode = TCP_TLS_MODE_TOE;
731 switch (tls->params.cipher_algorithm) {
733 counter_u64_add(ktls_toe_cbc, 1);
735 case CRYPTO_AES_NIST_GCM_16:
736 counter_u64_add(ktls_toe_gcm, 1);
745 * Common code used when first enabling ifnet TLS on a connection or
746 * when allocating a new ifnet TLS session due to a routing change.
747 * This function allocates a new TLS send tag on whatever interface
748 * the connection is currently routed over.
751 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
752 struct m_snd_tag **mstp)
754 union if_snd_tag_alloc_params params;
761 if (inp->inp_flags2 & INP_FREED) {
765 if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
769 if (inp->inp_socket == NULL) {
776 * Check administrative controls on ifnet TLS to determine if
777 * ifnet TLS should be denied.
779 * - Always permit 'force' requests.
780 * - ktls_ifnet_permitted == 0: always deny.
782 if (!force && ktls_ifnet_permitted == 0) {
788 * XXX: Use the cached route in the inpcb to find the
789 * interface. This should perhaps instead use
790 * rtalloc1_fib(dst, 0, 0, fibnum). Since KTLS is only
791 * enabled after a connection has completed key negotiation in
792 * userland, the cached route will be present in practice.
794 rt = inp->inp_route.ro_rt;
795 if (rt == NULL || rt->rt_ifp == NULL) {
802 params.hdr.type = IF_SND_TAG_TYPE_TLS;
803 params.hdr.flowid = inp->inp_flowid;
804 params.hdr.flowtype = inp->inp_flowtype;
805 params.tls.inp = inp;
806 params.tls.tls = tls;
809 if (ifp->if_snd_tag_alloc == NULL) {
813 if ((ifp->if_capenable & IFCAP_NOMAP) == 0) {
817 if (inp->inp_vflag & INP_IPV6) {
818 if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
823 if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
828 error = ifp->if_snd_tag_alloc(ifp, ¶ms, mstp);
835 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
837 struct m_snd_tag *mst;
840 error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
842 tls->mode = TCP_TLS_MODE_IFNET;
844 switch (tls->params.cipher_algorithm) {
846 counter_u64_add(ktls_ifnet_cbc, 1);
848 case CRYPTO_AES_NIST_GCM_16:
849 counter_u64_add(ktls_ifnet_gcm, 1);
857 ktls_try_sw(struct socket *so, struct ktls_session *tls)
859 struct rm_priotracker prio;
860 struct ktls_crypto_backend *be;
863 * Choose the best software crypto backend. Backends are
864 * stored in sorted priority order (larget value == most
865 * important at the head of the list), so this just stops on
866 * the first backend that claims the session by returning
869 if (ktls_allow_unload)
870 rm_rlock(&ktls_backends_lock, &prio);
871 LIST_FOREACH(be, &ktls_backends, next) {
872 if (be->try(so, tls) == 0)
874 KASSERT(tls->cipher == NULL,
875 ("ktls backend leaked a cipher pointer"));
878 if (ktls_allow_unload)
882 if (ktls_allow_unload)
883 rm_runlock(&ktls_backends_lock, &prio);
886 tls->mode = TCP_TLS_MODE_SW;
887 switch (tls->params.cipher_algorithm) {
889 counter_u64_add(ktls_sw_cbc, 1);
891 case CRYPTO_AES_NIST_GCM_16:
892 counter_u64_add(ktls_sw_gcm, 1);
899 ktls_enable_tx(struct socket *so, struct tls_enable *en)
901 struct ktls_session *tls;
904 if (!ktls_offload_enable)
907 counter_u64_add(ktls_offload_enable_calls, 1);
910 * This should always be true since only the TCP socket option
911 * invokes this function.
913 if (so->so_proto->pr_protocol != IPPROTO_TCP)
917 * XXX: Don't overwrite existing sessions. We should permit
918 * this to support rekeying in the future.
920 if (so->so_snd.sb_tls_info != NULL)
923 if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
926 /* TLS requires ext pgs */
927 if (mb_use_ext_pgs == 0)
930 error = ktls_create_session(so, en, &tls);
934 /* Prefer TOE -> ifnet TLS -> software TLS. */
936 error = ktls_try_toe(so, tls);
939 error = ktls_try_ifnet(so, tls, false);
941 error = ktls_try_sw(so, tls);
948 error = sblock(&so->so_snd, SBL_WAIT);
954 SOCKBUF_LOCK(&so->so_snd);
955 so->so_snd.sb_tls_info = tls;
956 if (tls->mode != TCP_TLS_MODE_SW)
957 so->so_snd.sb_flags |= SB_TLS_IFNET;
958 SOCKBUF_UNLOCK(&so->so_snd);
959 sbunlock(&so->so_snd);
961 counter_u64_add(ktls_offload_total, 1);
967 ktls_get_tx_mode(struct socket *so)
969 struct ktls_session *tls;
974 INP_WLOCK_ASSERT(inp);
975 SOCKBUF_LOCK(&so->so_snd);
976 tls = so->so_snd.sb_tls_info;
978 mode = TCP_TLS_MODE_NONE;
981 SOCKBUF_UNLOCK(&so->so_snd);
986 * Switch between SW and ifnet TLS sessions as requested.
989 ktls_set_tx_mode(struct socket *so, int mode)
991 struct ktls_session *tls, *tls_new;
996 case TCP_TLS_MODE_SW:
997 case TCP_TLS_MODE_IFNET:
1004 INP_WLOCK_ASSERT(inp);
1005 SOCKBUF_LOCK(&so->so_snd);
1006 tls = so->so_snd.sb_tls_info;
1008 SOCKBUF_UNLOCK(&so->so_snd);
1012 if (tls->mode == mode) {
1013 SOCKBUF_UNLOCK(&so->so_snd);
1017 tls = ktls_hold(tls);
1018 SOCKBUF_UNLOCK(&so->so_snd);
1021 tls_new = ktls_clone_session(tls);
1023 if (mode == TCP_TLS_MODE_IFNET)
1024 error = ktls_try_ifnet(so, tls_new, true);
1026 error = ktls_try_sw(so, tls_new);
1028 counter_u64_add(ktls_switch_failed, 1);
1035 error = sblock(&so->so_snd, SBL_WAIT);
1037 counter_u64_add(ktls_switch_failed, 1);
1045 * If we raced with another session change, keep the existing
1048 if (tls != so->so_snd.sb_tls_info) {
1049 counter_u64_add(ktls_switch_failed, 1);
1050 sbunlock(&so->so_snd);
1057 SOCKBUF_LOCK(&so->so_snd);
1058 so->so_snd.sb_tls_info = tls_new;
1059 if (tls_new->mode != TCP_TLS_MODE_SW)
1060 so->so_snd.sb_flags |= SB_TLS_IFNET;
1061 SOCKBUF_UNLOCK(&so->so_snd);
1062 sbunlock(&so->so_snd);
1065 * Drop two references on 'tls'. The first is for the
1066 * ktls_hold() above. The second drops the reference from the
1069 KASSERT(tls->refcount >= 2, ("too few references on old session"));
1073 if (mode == TCP_TLS_MODE_IFNET)
1074 counter_u64_add(ktls_switch_to_ifnet, 1);
1076 counter_u64_add(ktls_switch_to_sw, 1);
1083 * Try to allocate a new TLS send tag. This task is scheduled when
1084 * ip_output detects a route change while trying to transmit a packet
1085 * holding a TLS record. If a new tag is allocated, replace the tag
1086 * in the TLS session. Subsequent packets on the connection will use
1087 * the new tag. If a new tag cannot be allocated, drop the
1091 ktls_reset_send_tag(void *context, int pending)
1093 struct epoch_tracker et;
1094 struct ktls_session *tls;
1095 struct m_snd_tag *old, *new;
1100 MPASS(pending == 1);
1106 * Free the old tag first before allocating a new one.
1107 * ip[6]_output_send() will treat a NULL send tag the same as
1108 * an ifp mismatch and drop packets until a new tag is
1111 * Write-lock the INP when changing tls->snd_tag since
1112 * ip[6]_output_send() holds a read-lock when reading the
1117 tls->snd_tag = NULL;
1120 m_snd_tag_rele(old);
1122 error = ktls_alloc_snd_tag(inp, tls, true, &new);
1127 mtx_pool_lock(mtxpool_sleep, tls);
1128 tls->reset_pending = false;
1129 mtx_pool_unlock(mtxpool_sleep, tls);
1130 if (!in_pcbrele_wlocked(inp))
1133 counter_u64_add(ktls_ifnet_reset, 1);
1136 * XXX: Should we kick tcp_output explicitly now that
1137 * the send tag is fixed or just rely on timers?
1140 NET_EPOCH_ENTER(et);
1142 if (!in_pcbrele_wlocked(inp)) {
1143 if (!(inp->inp_flags & INP_TIMEWAIT) &&
1144 !(inp->inp_flags & INP_DROPPED)) {
1145 tp = intotcpcb(inp);
1146 tp = tcp_drop(tp, ECONNABORTED);
1149 counter_u64_add(ktls_ifnet_reset_dropped, 1);
1155 counter_u64_add(ktls_ifnet_reset_failed, 1);
1158 * Leave reset_pending true to avoid future tasks while
1159 * the socket goes away.
1167 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1173 INP_LOCK_ASSERT(inp);
1176 * See if we should schedule a task to update the send tag for
1179 mtx_pool_lock(mtxpool_sleep, tls);
1180 if (!tls->reset_pending) {
1181 (void) ktls_hold(tls);
1184 tls->reset_pending = true;
1185 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1187 mtx_pool_unlock(mtxpool_sleep, tls);
1193 ktls_destroy(struct ktls_session *tls)
1195 struct rm_priotracker prio;
1198 if (tls->be != NULL && ktls_allow_unload) {
1199 rm_rlock(&ktls_backends_lock, &prio);
1200 tls->be->use_count--;
1201 rm_runlock(&ktls_backends_lock, &prio);
1203 uma_zfree(ktls_session_zone, tls);
1207 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1209 struct mbuf_ext_pgs *pgs;
1211 for (; m != NULL; m = m->m_next) {
1212 KASSERT((m->m_flags & M_NOMAP) != 0,
1213 ("ktls_seq: mapped mbuf %p", m));
1215 pgs = m->m_ext.ext_pgs;
1216 pgs->seqno = sb->sb_tls_seqno;
1222 * Add TLS framing (headers and trailers) to a chain of mbufs. Each
1223 * mbuf in the chain must be an unmapped mbuf. The payload of the
1224 * mbuf must be populated with the payload of each TLS record.
1226 * The record_type argument specifies the TLS record type used when
1227 * populating the TLS header.
1229 * The enq_count argument on return is set to the number of pages of
1230 * payload data for this entire chain that need to be encrypted via SW
1231 * encryption. The returned value should be passed to ktls_enqueue
1232 * when scheduling encryption of this chain of mbufs.
1235 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1236 uint8_t record_type)
1238 struct tls_record_layer *tlshdr;
1240 struct mbuf_ext_pgs *pgs;
1245 maxlen = tls->params.max_frame_len;
1247 for (m = top; m != NULL; m = m->m_next) {
1249 * All mbufs in the chain should be non-empty TLS
1250 * records whose payload does not exceed the maximum
1253 if (m->m_len > maxlen || m->m_len == 0)
1258 * TLS frames require unmapped mbufs to store session
1261 KASSERT((m->m_flags & M_NOMAP) != 0,
1262 ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1264 pgs = m->m_ext.ext_pgs;
1266 /* Save a reference to the session. */
1267 pgs->tls = ktls_hold(tls);
1269 pgs->hdr_len = tls->params.tls_hlen;
1270 pgs->trail_len = tls->params.tls_tlen;
1271 if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1275 * AES-CBC pads messages to a multiple of the
1276 * block size. Note that the padding is
1277 * applied after the digest and the encryption
1278 * is done on the "plaintext || mac || padding".
1279 * At least one byte of padding is always
1282 * Compute the final trailer length assuming
1283 * at most one block of padding.
1284 * tls->params.sb_tls_tlen is the maximum
1285 * possible trailer length (padding + digest).
1286 * delta holds the number of excess padding
1287 * bytes if the maximum were used. Those
1288 * extra bytes are removed.
1290 bs = tls->params.tls_bs;
1291 delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
1292 pgs->trail_len -= delta;
1294 m->m_len += pgs->hdr_len + pgs->trail_len;
1296 /* Populate the TLS header. */
1297 tlshdr = (void *)pgs->hdr;
1298 tlshdr->tls_vmajor = tls->params.tls_vmajor;
1301 * TLS 1.3 masquarades as TLS 1.2 with a record type
1302 * of TLS_RLTYPE_APP.
1304 if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
1305 tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
1306 tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
1307 tlshdr->tls_type = TLS_RLTYPE_APP;
1308 /* save the real record type for later */
1309 pgs->record_type = record_type;
1311 tlshdr->tls_vminor = tls->params.tls_vminor;
1312 tlshdr->tls_type = record_type;
1314 tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1317 * Store nonces / explicit IVs after the end of the
1320 * For GCM with TLS 1.2, an 8 byte nonce is copied
1321 * from the end of the IV. The nonce is then
1322 * incremented for use by the next record.
1324 * For CBC, a random nonce is inserted for TLS 1.1+.
1326 if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
1327 tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
1328 noncep = (uint64_t *)(tls->params.iv + 8);
1329 be64enc(tlshdr + 1, *noncep);
1331 } else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
1332 tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
1333 arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
1336 * When using SW encryption, mark the mbuf not ready.
1337 * It will be marked ready via sbready() after the
1338 * record has been encrypted.
1340 * When using ifnet TLS, unencrypted TLS records are
1341 * sent down the stack to the NIC.
1343 if (tls->mode == TCP_TLS_MODE_SW) {
1344 m->m_flags |= M_NOTREADY;
1345 pgs->nrdy = pgs->npgs;
1346 *enq_cnt += pgs->npgs;
1353 ktls_enqueue_to_free(struct mbuf_ext_pgs *pgs)
1358 /* Mark it for freeing. */
1360 wq = &ktls_wq[pgs->tls->wq_index];
1362 STAILQ_INSERT_TAIL(&wq->head, pgs, stailq);
1363 running = wq->running;
1364 mtx_unlock(&wq->mtx);
1370 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
1372 struct mbuf_ext_pgs *pgs;
1376 KASSERT(((m->m_flags & (M_NOMAP | M_NOTREADY)) ==
1377 (M_NOMAP | M_NOTREADY)),
1378 ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
1379 KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
1381 pgs = m->m_ext.ext_pgs;
1383 KASSERT(pgs->tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
1385 pgs->enc_cnt = page_count;
1389 * Save a pointer to the socket. The caller is responsible
1390 * for taking an additional reference via soref().
1394 wq = &ktls_wq[pgs->tls->wq_index];
1396 STAILQ_INSERT_TAIL(&wq->head, pgs, stailq);
1397 running = wq->running;
1398 mtx_unlock(&wq->mtx);
1401 counter_u64_add(ktls_cnt_on, 1);
1404 static __noinline void
1405 ktls_encrypt(struct mbuf_ext_pgs *pgs)
1407 struct ktls_session *tls;
1409 struct mbuf *m, *top;
1410 vm_paddr_t parray[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1411 struct iovec src_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1412 struct iovec dst_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1414 int error, i, len, npages, off, total_pages;
1420 KASSERT(tls != NULL, ("tls = NULL, top = %p, pgs = %p\n", top, pgs));
1421 KASSERT(so != NULL, ("so = NULL, top = %p, pgs = %p\n", top, pgs));
1426 total_pages = pgs->enc_cnt;
1430 * Encrypt the TLS records in the chain of mbufs starting with
1431 * 'top'. 'total_pages' gives us a total count of pages and is
1432 * used to know when we have finished encrypting the TLS
1433 * records originally queued with 'top'.
1435 * NB: These mbufs are queued in the socket buffer and
1436 * 'm_next' is traversing the mbufs in the socket buffer. The
1437 * socket buffer lock is not held while traversing this chain.
1438 * Since the mbufs are all marked M_NOTREADY their 'm_next'
1439 * pointers should be stable. However, the 'm_next' of the
1440 * last mbuf encrypted is not necessarily NULL. It can point
1441 * to other mbufs appended while 'top' was on the TLS work
1444 * Each mbuf holds an entire TLS record.
1447 for (m = top; npages != total_pages; m = m->m_next) {
1448 pgs = m->m_ext.ext_pgs;
1450 KASSERT(pgs->tls == tls,
1451 ("different TLS sessions in a single mbuf chain: %p vs %p",
1453 KASSERT((m->m_flags & (M_NOMAP | M_NOTREADY)) ==
1454 (M_NOMAP | M_NOTREADY),
1455 ("%p not unready & nomap mbuf (top = %p)\n", m, top));
1456 KASSERT(npages + pgs->npgs <= total_pages,
1457 ("page count mismatch: top %p, total_pages %d, m %p", top,
1461 * Generate source and destination ivoecs to pass to
1462 * the SW encryption backend. For writable mbufs, the
1463 * destination iovec is a copy of the source and
1464 * encryption is done in place. For file-backed mbufs
1465 * (from sendfile), anonymous wired pages are
1466 * allocated and assigned to the destination iovec.
1468 is_anon = (pgs->flags & MBUF_PEXT_FLAG_ANON) != 0;
1470 off = pgs->first_pg_off;
1471 for (i = 0; i < pgs->npgs; i++, off = 0) {
1472 len = mbuf_ext_pg_len(pgs, i, off);
1473 src_iov[i].iov_len = len;
1474 src_iov[i].iov_base =
1475 (char *)(void *)PHYS_TO_DMAP(pgs->pa[i]) + off;
1478 dst_iov[i].iov_base = src_iov[i].iov_base;
1479 dst_iov[i].iov_len = src_iov[i].iov_len;
1483 pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
1484 VM_ALLOC_NOOBJ | VM_ALLOC_NODUMP | VM_ALLOC_WIRED);
1489 parray[i] = VM_PAGE_TO_PHYS(pg);
1490 dst_iov[i].iov_base =
1491 (char *)(void *)PHYS_TO_DMAP(parray[i]) + off;
1492 dst_iov[i].iov_len = len;
1497 error = (*tls->sw_encrypt)(tls,
1498 (const struct tls_record_layer *)pgs->hdr,
1499 pgs->trail, src_iov, dst_iov, i, pgs->seqno,
1502 counter_u64_add(ktls_offload_failed_crypto, 1);
1507 * For file-backed mbufs, release the file-backed
1508 * pages and replace them in the ext_pgs array with
1509 * the anonymous wired pages allocated above.
1512 /* Free the old pages. */
1513 m->m_ext.ext_free(m);
1515 /* Replace them with the new pages. */
1516 for (i = 0; i < pgs->npgs; i++)
1517 pgs->pa[i] = parray[i];
1519 /* Use the basic free routine. */
1520 m->m_ext.ext_free = mb_free_mext_pgs;
1522 /* Pages are now writable. */
1523 pgs->flags |= MBUF_PEXT_FLAG_ANON;
1527 * Drop a reference to the session now that it is no
1528 * longer needed. Existing code depends on encrypted
1529 * records having no associated session vs
1530 * yet-to-be-encrypted records having an associated
1537 CURVNET_SET(so->so_vnet);
1539 (void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
1541 so->so_proto->pr_usrreqs->pru_abort(so);
1543 mb_free_notready(top, total_pages);
1552 ktls_work_thread(void *ctx)
1554 struct ktls_wq *wq = ctx;
1555 struct mbuf_ext_pgs *p, *n;
1556 struct ktls_session *tls;
1557 STAILQ_HEAD(, mbuf_ext_pgs) local_head;
1559 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
1564 while (STAILQ_EMPTY(&wq->head)) {
1565 wq->running = false;
1566 mtx_sleep(wq, &wq->mtx, 0, "-", 0);
1570 STAILQ_INIT(&local_head);
1571 STAILQ_CONCAT(&local_head, &wq->head);
1572 mtx_unlock(&wq->mtx);
1574 STAILQ_FOREACH_SAFE(p, &local_head, stailq, n) {
1575 if (p->mbuf != NULL) {
1577 counter_u64_add(ktls_cnt_on, -1);
1581 uma_zfree(zone_extpgs, p);