* [PATCH net v3 1/9] net: don't fragment skbs that still need device crypto
2026-12-04 23:53 [PATCH net v3 0/9] tls: device: don't put offload plaintext on the wire Rishikesh Jethwani
@ 2026-12-04 23:53 ` Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 2/9] tls: device: keep tls_sw_fallback() from encrypting its own output Rishikesh Jethwani
` (7 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Rishikesh Jethwani @ 2026-12-04 23:53 UTC (permalink / raw)
To: netdev
Cc: Rishikesh Jethwani, stable, David Ahern, Ido Schimmel,
David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
Willem de Bruijn, Simon Horman, Ilya Lesokhin, Aviad Yehezkel,
Boris Pismenny, Daniel Zahka
IP fragmentation runs before TX validation. Fragments can lose
skb->decrypted, allowing PSP traffic to bypass encapsulation. Copying
the bit would not make kTLS work either: only the first fragment has
the TCP header needed for encryption.
Reject marked skbs before IPv4 or IPv6 builds fragments. In IPv6,
keep the existing Packet Too Big checks ahead of the new guard.
Found by manual inspection. On two mlx5 hosts with TLS 1.2 AES-GCM-128,
IPv4 FragCreates increased by 50 on the NIC and 26 on a macvlan
without the fix, and by zero on both with it. The IPv6 test still got
Packet Too Big. PSP and the remaining IPv6 paths were inspected only.
Fixes: e8f69799810c ("net/tls: Add generic NIC offload infrastructure")
Fixes: 659a2899a57d ("tcp: add datapath logic for PSP with inline key exchange")
Cc: stable@vger.kernel.org
Signed-off-by: Rishikesh Jethwani <rjethwani@purestorage.com>
---
net/ipv4/ip_output.c | 8 ++++++++
net/ipv6/ip6_output.c | 9 +++++++++
2 files changed, 17 insertions(+)
diff --git a/net/ipv4/ip_output.c b/net/ipv4/ip_output.c
index d42d776af273..36ae3d08742a 100644
--- a/net/ipv4/ip_output.c
+++ b/net/ipv4/ip_output.c
@@ -770,6 +770,14 @@ int ip_do_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
struct ip_frag_state state;
int err = 0;
+ /* Still needs kTLS encryption or PSP encapsulation, which neither
+ * tls_sw_fallback() nor the NIC can apply to fragments.
+ */
+ if (unlikely(skb_is_decrypted(skb))) {
+ err = -EMSGSIZE;
+ goto fail;
+ }
+
/* for offloaded checksums cleanup checksum before fragmentation */
if (skb->ip_summed == CHECKSUM_PARTIAL) {
err = ip_check_csum_start(skb);
diff --git a/net/ipv6/ip6_output.c b/net/ipv6/ip6_output.c
index 5887e537f662..637a3d23c4c2 100644
--- a/net/ipv6/ip6_output.c
+++ b/net/ipv6/ip6_output.c
@@ -937,6 +937,15 @@ int ip6_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
}
if (mtu < hlen + sizeof(struct frag_hdr) + 8)
goto fail_toobig;
+
+ /* Still needs kTLS encryption or PSP encapsulation, which neither
+ * tls_sw_fallback() nor the NIC can apply to fragments. Checked only
+ * now, so that an oversized skb still gets its Packet Too Big above.
+ */
+ if (unlikely(skb_is_decrypted(skb))) {
+ err = -EMSGSIZE;
+ goto fail;
+ }
mtu -= hlen + sizeof(struct frag_hdr);
frag_id = ipv6_select_ident(net, &ipv6_hdr(skb)->daddr,
--
2.50.1
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH net v3 2/9] tls: device: keep tls_sw_fallback() from encrypting its own output
2026-12-04 23:53 [PATCH net v3 0/9] tls: device: don't put offload plaintext on the wire Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 1/9] net: don't fragment skbs that still need device crypto Rishikesh Jethwani
@ 2026-12-04 23:53 ` Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 3/9] tls: device: don't let the NIC encrypt fallback output again Rishikesh Jethwani
` (6 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Rishikesh Jethwani @ 2026-12-04 23:53 UTC (permalink / raw)
To: netdev
Cc: Rishikesh Jethwani, stable, John Fastabend, Jakub Kicinski,
Sabrina Dubroca, David S. Miller, Eric Dumazet, Paolo Abeni,
Willem de Bruijn, Simon Horman, Alice Mikityanska, Tariq Toukan
After the TLS device goes down, TX validation can run the software
fallback at both the bond and its slave. The second pass encrypts
ciphertext with the same keystream and can expose plaintext.
Pass unmarked skbs through tls_sw_fallback() and clear skb->decrypted
on its output. Backport the preceding fragmentation fix first:
otherwise fragments of offload plaintext can also arrive unmarked.
Found by manual inspection. On two mlx5 hosts with TLS 1.2 AES-GCM-128,
both the idle and in-flight bond bounce tests returned a mismatched
echo without the fix and passed with it.
Fixes: c55dcdd435aa ("net/tls: Fix use-after-free after the TLS device goes down and up")
Cc: <stable@vger.kernel.org> # 5.10.x: fc6d80eb5044: tcp: prevent collapsing skbs across boundary in rtx queue
Signed-off-by: Rishikesh Jethwani <rjethwani@purestorage.com>
---
net/tls/tls_device_fallback.c | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/net/tls/tls_device_fallback.c b/net/tls/tls_device_fallback.c
index b547027cc879..42afbe7e60b5 100644
--- a/net/tls/tls_device_fallback.c
+++ b/net/tls/tls_device_fallback.c
@@ -192,6 +192,9 @@ static void complete_skb(struct sk_buff *nskb, struct sk_buff *skb, int headln)
skb->destructor = NULL;
skb->sk = NULL;
+ /* Ciphertext now: don't encrypt it again */
+ nskb->decrypted = 0;
+
update_chksum(nskb, headln);
/* sock_efree means skb must gone through skb_orphan_partial() */
@@ -371,6 +374,10 @@ static struct sk_buff *tls_sw_fallback(struct sock *sk, struct sk_buff *skb)
s32 sync_size = 0;
u64 rcd_sn;
+ /* Pre-offload data or tls_sw_fallback() output */
+ if (!skb_is_decrypted(skb))
+ return skb;
+
/* worst case is:
* MAX_SKB_FRAGS in tls_record_info
* MAX_SKB_FRAGS + 1 in SKB head and frags.
--
2.50.1
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH net v3 3/9] tls: device: don't let the NIC encrypt fallback output again
2026-12-04 23:53 [PATCH net v3 0/9] tls: device: don't put offload plaintext on the wire Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 1/9] net: don't fragment skbs that still need device crypto Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 2/9] tls: device: keep tls_sw_fallback() from encrypting its own output Rishikesh Jethwani
@ 2026-12-04 23:53 ` Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 4/9] tls: device: remove the dead start marker bypass in TX fallback Rishikesh Jethwani
` (5 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Rishikesh Jethwani @ 2026-12-04 23:53 UTC (permalink / raw)
To: netdev
Cc: Rishikesh Jethwani, stable, John Fastabend, Jakub Kicinski,
Sabrina Dubroca, David S. Miller, Eric Dumazet, Paolo Abeni,
Willem de Bruijn, Simon Horman, Ilya Lesokhin, Aviad Yehezkel,
Boris Pismenny
Software fallback output still belongs to the offloaded socket. A
driver that checks only the socket can therefore encrypt ciphertext
again, exposing plaintext.
Require skb_is_decrypted() in tls_is_skb_tx_device_offloaded().
Fallback output then takes the ordinary TX path, as does data queued
before TLS_TX was enabled. Backport the first three fixes together,
in order.
Found by manual inspection. On two mlx5 hosts with TLS 1.2 AES-GCM-128,
the macvlan reroute test returned a mismatched echo without the fix
and passed with it. The other drivers were checked by inspection only.
Fixes: e8f69799810c ("net/tls: Add generic NIC offload infrastructure")
Cc: stable@vger.kernel.org
Signed-off-by: Rishikesh Jethwani <rjethwani@purestorage.com>
---
include/net/tls.h | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/include/net/tls.h b/include/net/tls.h
index 0b001b8ab1c3..9998b5582091 100644
--- a/include/net/tls.h
+++ b/include/net/tls.h
@@ -365,7 +365,8 @@ static inline bool tls_is_skb_tx_device_offloaded(const struct sk_buff *skb)
return sk && sk_fullsock(sk) &&
(smp_load_acquire(&sk->sk_validate_xmit_skb) ==
- &tls_validate_xmit_skb);
+ &tls_validate_xmit_skb) &&
+ skb_is_decrypted(skb);
#else
return false;
#endif
--
2.50.1
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH net v3 4/9] tls: device: remove the dead start marker bypass in TX fallback
2026-12-04 23:53 [PATCH net v3 0/9] tls: device: don't put offload plaintext on the wire Rishikesh Jethwani
` (2 preceding siblings ...)
2026-12-04 23:53 ` [PATCH net v3 3/9] tls: device: don't let the NIC encrypt fallback output again Rishikesh Jethwani
@ 2026-12-04 23:53 ` Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 5/9] selftests: net: py: reap commands that fail to report ready Rishikesh Jethwani
` (4 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Rishikesh Jethwani @ 2026-12-04 23:53 UTC (permalink / raw)
To: netdev
Cc: Rishikesh Jethwani, John Fastabend, Jakub Kicinski,
Sabrina Dubroca, David S. Miller, Eric Dumazet, Paolo Abeni,
Willem de Bruijn, Simon Horman
Pre-offload skbs now bypass tls_sw_fallback() before record lookup,
and TCP does not merge them with marked data across the start marker.
Remove the unreachable bypass and its special case in fill_sg_in().
Keep the marker itself: record lookup and ACK cleanup still count it.
No functional change.
Signed-off-by: Rishikesh Jethwani <rjethwani@purestorage.com>
---
net/tls/tls_device_fallback.c | 11 ++---------
1 file changed, 2 insertions(+), 9 deletions(-)
diff --git a/net/tls/tls_device_fallback.c b/net/tls/tls_device_fallback.c
index 42afbe7e60b5..da875fdf5b54 100644
--- a/net/tls/tls_device_fallback.c
+++ b/net/tls/tls_device_fallback.c
@@ -237,8 +237,6 @@ static int fill_sg_in(struct scatterlist *sg_in,
*sync_size = tcp_seq - tls_record_start_seq(record);
if (*sync_size < 0) {
- int is_start_marker = tls_record_is_start_marker(record);
-
spin_unlock_irqrestore(&ctx->lock, flags);
/* This should only occur if the relevant record was
* already acked. In that case it should be ok
@@ -250,8 +248,6 @@ static int fill_sg_in(struct scatterlist *sg_in,
* on TCP to retransmit a packet that doesn't contain
* already acked payload.
*/
- if (!is_start_marker)
- *sync_size = 0;
return -EINVAL;
}
@@ -394,12 +390,9 @@ static struct sk_buff *tls_sw_fallback(struct sock *sk, struct sk_buff *skb)
sg_init_table(sg_in, sg_in_max_elements);
sg_init_table(sg_out, ARRAY_SIZE(sg_out));
- if (fill_sg_in(sg_in, skb, ctx, &rcd_sn, &sync_size, &resync_sgs)) {
- /* bypass packets before kernel TLS socket option was set */
- if (sync_size < 0 && payload_len <= -sync_size)
- nskb = skb_get(skb);
+ /* Its record was acked and freed: drop it */
+ if (fill_sg_in(sg_in, skb, ctx, &rcd_sn, &sync_size, &resync_sgs))
goto put_sg;
- }
nskb = tls_enc_skb(tls_ctx, sg_out, sg_in, skb, sync_size, rcd_sn);
--
2.50.1
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH net v3 5/9] selftests: net: py: reap commands that fail to report ready
2026-12-04 23:53 [PATCH net v3 0/9] tls: device: don't put offload plaintext on the wire Rishikesh Jethwani
` (3 preceding siblings ...)
2026-12-04 23:53 ` [PATCH net v3 4/9] tls: device: remove the dead start marker bypass in TX fallback Rishikesh Jethwani
@ 2026-12-04 23:53 ` Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 6/9] selftests: net: py: add a timeout argument to bkg() Rishikesh Jethwani
` (3 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Rishikesh Jethwani @ 2026-12-04 23:53 UTC (permalink / raw)
To: netdev
Cc: Rishikesh Jethwani, David S. Miller, Eric Dumazet, Jakub Kicinski,
Paolo Abeni, Willem de Bruijn, Simon Horman, Shuah Khan,
Stanislav Fomichev, Joe Damato, linux-kselftest
A readiness timeout leaves the command running with its pipes open.
Killing only the command can also leave a wrapper's workers behind.
Give readiness-enabled commands their own process group. Kill the
group on timeout; on readiness EOF, allow one second after SIGTERM
before escalating. Drain output, but bound the wait: a worker can
keep a pipe open after its parent exits. Keep the wait FD open until
teardown is complete so EOF does not resume a paused helper.
Clean up the group on interruption without masking the original
exception. Use poll() so readiness also works above FD_SETSIZE.
Found while developing the TLS bond tests. Tested locally with
TERM-ignoring workers, inherited pipes, large output, high-numbered
FDs and Ctrl-C during readiness and teardown.
Fixes: 71477137994f ("selftests: drv-net: add a way to wait for a local process")
Signed-off-by: Rishikesh Jethwani <rjethwani@purestorage.com>
---
tools/testing/selftests/net/lib/py/utils.py | 246 ++++++++++++++++++--
1 file changed, 231 insertions(+), 15 deletions(-)
diff --git a/tools/testing/selftests/net/lib/py/utils.py b/tools/testing/selftests/net/lib/py/utils.py
index 1727bc418073..9edfc4f88621 100644
--- a/tools/testing/selftests/net/lib/py/utils.py
+++ b/tools/testing/selftests/net/lib/py/utils.py
@@ -1,9 +1,12 @@
# SPDX-License-Identifier: GPL-2.0
+import contextlib
import json as _json
+import math
import os
import re
import select
+import signal
import socket
import subprocess
import time
@@ -27,9 +30,28 @@ class CmdExitZeroFailure(CmdExitFailure):
""" Command succeeded (returned zero exit code), but expected failure. """
+def _poll_timeout_ms(timeout):
+ """Convert a timeout in seconds to poll()'s milliseconds.
+
+ None waits forever. poll() takes a negative timeout as forever too,
+ where select() raised, and overflows past INT_MAX milliseconds: refuse
+ both. Also lets cmd() check a timeout before spawning its command.
+ """
+ if timeout is None:
+ return None
+ if (not 0 <= timeout or not math.isfinite(timeout) or
+ math.ceil(timeout * 1000) > 2**31 - 1):
+ raise ValueError(f"timeout must be between 0 and "
+ f"{(2**31 - 1) / 1000}s, not {timeout}")
+ return timeout * 1000
+
+
def fd_read_timeout(fd, timeout):
- rlist, _, _ = select.select([fd], [], [], timeout)
- if rlist:
+ timeout_ms = _poll_timeout_ms(timeout)
+ # poll(), not select(): select() rejects FDs >= FD_SETSIZE.
+ poller = select.poll()
+ poller.register(fd, select.POLLIN)
+ if poller.poll(timeout_ms):
return os.read(fd, 1024)
raise TimeoutError("Timeout waiting for fd read")
@@ -58,6 +80,7 @@ class cmd:
self.stderr = None
self.ret = None
self.ksft_term_fd = None
+ self._own_pgrp = False
self.host = host
self.comm = comm
@@ -74,6 +97,8 @@ class cmd:
# Similarly term_fd tells child it's time to exit.
pass_fds = []
env = os.environ.copy()
+ # Before spawning: fd_read_timeout() would refuse it only after.
+ _poll_timeout_ms(ksft_wait)
if ksft_wait is not None:
wait_fd, self.ksft_term_fd = os.pipe()
pass_fds.append(wait_fd)
@@ -84,26 +109,207 @@ class cmd:
pass_fds.append(ready_fd)
env["KSFT_READY_FD"] = str(ready_fd)
+ # A command that reports ready leads its own process group, so
+ # that _reap_unready() and _kill_leftovers() can stop what it
+ # started too. Terminal signals then no longer reach it: on
+ # Ctrl-C, KeyboardInterrupt here leads to the same cleanup.
+ self._own_pgrp = ksft_ready is not None
self.proc = subprocess.Popen(comm, shell=shell, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, pass_fds=pass_fds,
- env=env)
+ env=env,
+ start_new_session=self._own_pgrp)
if ksft_wait is not None:
os.close(wait_fd)
if ksft_ready is not None:
os.close(ready_fd)
- msg = fd_read_timeout(rfd, ksft_wait)
- os.close(rfd)
+ timed_out = False
+ try:
+ msg = fd_read_timeout(rfd, ksft_wait)
+ except TimeoutError:
+ msg = None
+ timed_out = True
+ except BaseException:
+ # Interrupted: stop the command, then let the
+ # interruption, not any cleanup failure, propagate.
+ self._cleanup_quietly(self._reap_unready, kill=True)
+ raise
+ finally:
+ os.close(rfd)
if not msg:
- terminate = self.proc.poll() is None
- self._process_terminate(terminate=terminate, timeout=1)
+ self._reap_unready(kill=timed_out)
raise CmdInitFailure("Did not receive ready message", self)
if not background:
self.process(terminate=False, fail=fail, expect_fail=expect_fail,
timeout=timeout)
+ def _drain_until_exit(self, bufs, timeout):
+ """Read the command's output into bufs until it exits.
+
+ Reading keeps a command that writes while shutting down from
+ blocking on a full pipe. Returns False if the command is still
+ running after timeout seconds.
+ """
+ fds = {self.proc.stdout.fileno(): bufs[0],
+ self.proc.stderr.fileno(): bufs[1]}
+ poller = select.poll()
+ for fd in fds:
+ poller.register(fd, select.POLLIN)
+ deadline = time.monotonic() + timeout
+ while self.proc.poll() is None:
+ left = deadline - time.monotonic()
+ if left <= 0:
+ return False
+ if not fds:
+ # Both pipes are at EOF: nothing left to drain.
+ try:
+ self.proc.wait(timeout=left)
+ except subprocess.TimeoutExpired:
+ return False
+ break
+ # Poll the exit status at least every 100ms: descendants can
+ # keep the pipes open, and quiet, after the command exits.
+ for fd, _ in poller.poll(min(left, 0.1) * 1000):
+ data = os.read(fd, 65536)
+ if data:
+ fds[fd].append(data)
+ else:
+ poller.unregister(fd)
+ del fds[fd]
+ return True
+
+ def _cleanup_quietly(self, func, *args, **kwargs):
+ """Run a cleanup step while an exception is propagating.
+
+ Report a failure instead of raising it, which would replace that
+ exception. A second interruption still propagates.
+ """
+ try:
+ func(*args, **kwargs)
+ except Exception as e:
+ print(f"# Warning: cleanup of {self.comm!r} failed: "
+ f"{type(e).__name__}: {e}")
+
+ @contextlib.contextmanager
+ def _killed_on_interrupt(self):
+ """Guard a wait for the command to exit.
+
+ If the wait ends in an exception, KeyboardInterrupt say, SIGKILL
+ the process group the command leads: terminal signals do not reach
+ it, so it and what it started would run on. The exception stays
+ the one raised.
+ """
+ try:
+ yield
+ except BaseException:
+ self._cleanup_quietly(self._kill_leftovers)
+ raise
+
+ def _kill_leftovers(self):
+ """SIGKILL what is left of the process group the command leads."""
+ if not self._own_pgrp:
+ return
+ self._kill_group(signal.SIGKILL)
+ if self.proc.returncode is None:
+ try:
+ self.proc.wait(timeout=1)
+ except subprocess.TimeoutExpired:
+ pass
+ self.proc.stdout.close()
+ self.proc.stderr.close()
+ # Only now: EOF on the ksft_wait pipe lets a command go on.
+ if self.ksft_term_fd:
+ os.close(self.ksft_term_fd)
+ self.ksft_term_fd = None
+
+ def _kill_group(self, sig):
+ """Signal the process group the command leads.
+
+ The group outlives the command while any of its descendants are
+ left in it, so this reaches them after the command is reaped too.
+ """
+ try:
+ os.killpg(self.proc.pid, sig)
+ except ProcessLookupError:
+ pass
+
+ def _reap_unready(self, kill):
+ """Stop and reap a local command that did not report ready.
+
+ A command that closed the ready FD gets SIGTERM, as before, and a
+ grace period to exit, with its output drained meanwhile. One that
+ never answered gets SIGKILL, since it may ignore SIGTERM, as does
+ one still running after the grace period. The signals go to the
+ command's whole process group, and whatever is left of the group
+ once the command is gone gets SIGKILL, so that a wrapper's workers
+ do not outlive it. Wait for the command itself rather than for EOF
+ on its output: a shell's descendants can keep its stdout/stderr
+ pipes open after it exits, so take only the output that is there.
+
+ Close the ksft_wait pipe only once all that is done: ksft_wait()
+ takes EOF on it as leave to go on, so closing it first lets a
+ command that is still running resume.
+ """
+ out, err = [], []
+ with self._killed_on_interrupt():
+ if self.proc.poll() is None:
+ self._kill_group(signal.SIGKILL if kill else signal.SIGTERM)
+ self._drain_until_exit((out, err), timeout=1)
+ self._collect_reaped(out, err)
+
+ def _reap_cancelled(self, terminate, timeout):
+ """Stop and reap a local command whose bkg() was cancelled.
+
+ Ask the command to exit as a normal exit would, through the
+ ksft_wait pipe or with SIGTERM to its group, and wait for it, not
+ for EOF: what it started may hold its pipes open. Then SIGKILL the
+ rest of its group, as _reap_unready() does.
+ """
+ if self.ksft_term_fd:
+ try:
+ os.write(self.ksft_term_fd, b"1")
+ except BrokenPipeError:
+ pass
+ out, err = [], []
+ with self._killed_on_interrupt():
+ if self.proc.poll() is None:
+ if terminate:
+ self._kill_group(signal.SIGTERM)
+ self._drain_until_exit((out, err), timeout=timeout)
+ self._collect_reaped(out, err)
+
+ def _collect_reaped(self, out, err):
+ """SIGKILL the command's group, reap it and keep its output.
+
+ out and err hold output drained so far.
+ """
+ self._kill_group(signal.SIGKILL)
+ # A command stuck in the kernel does not die even then: give up
+ # on it rather than hang, leaving ret unset.
+ try:
+ self.proc.wait(timeout=1)
+ except subprocess.TimeoutExpired:
+ pass
+ try:
+ stdout, stderr = self.proc.communicate(timeout=1)
+ except subprocess.TimeoutExpired as e:
+ stdout, stderr = e.stdout or b"", e.stderr or b""
+ stdout = b"".join(out) + stdout
+ stderr = b"".join(err) + stderr
+ self.stdout = stdout.decode("utf-8", "replace")
+ self.stderr = stderr.decode("utf-8", "replace")
+ self.proc.stdout.close()
+ self.proc.stderr.close()
+ self.ret = self.proc.returncode
+ if self.ksft_term_fd:
+ os.close(self.ksft_term_fd)
+ self.ksft_term_fd = None
+
def _process_terminate(self, terminate, timeout):
if terminate:
- self.proc.terminate()
+ if self._own_pgrp:
+ self._kill_group(signal.SIGTERM)
+ else:
+ self.proc.terminate()
stdout, stderr = self.proc.communicate(timeout=timeout)
self.stdout = stdout.decode("utf-8")
self.stderr = stderr.decode("utf-8")
@@ -117,11 +323,11 @@ class cmd:
if fail is None:
fail = not terminate
- if self.ksft_term_fd:
- os.write(self.ksft_term_fd, b"1")
-
- stdout, stderr = self._process_terminate(terminate=terminate,
- timeout=timeout)
+ with self._killed_on_interrupt():
+ if self.ksft_term_fd:
+ os.write(self.ksft_term_fd, b"1")
+ stdout, stderr = self._process_terminate(terminate=terminate,
+ timeout=timeout)
# Fail on unexpected test failure if fail.
# Fail on unexpected test success if expect_fail.
@@ -202,8 +408,18 @@ class bkg(cmd):
# since forcing termination silences failures with fail=None
if self.proc.poll() is None:
terminate = terminate or (self._exit_wait and ex_type is not None)
- return self.process(terminate=terminate, fail=self.check_fail,
- expect_fail=self.expect_fail)
+ if ex_type is None:
+ return self.process(terminate=terminate, fail=self.check_fail,
+ expect_fail=self.expect_fail)
+ # Cancelled, e.g. by Ctrl-C: stop the command and what it started,
+ # without replacing the exception in flight.
+ if self._own_pgrp:
+ self._cleanup_quietly(self._reap_cancelled, terminate, 20)
+ else:
+ self._cleanup_quietly(self.process, terminate=terminate,
+ fail=self.check_fail,
+ expect_fail=self.expect_fail)
+ return None
GLOBAL_DEFER_QUEUE = []
--
2.50.1
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH net v3 6/9] selftests: net: py: add a timeout argument to bkg()
2026-12-04 23:53 [PATCH net v3 0/9] tls: device: don't put offload plaintext on the wire Rishikesh Jethwani
` (4 preceding siblings ...)
2026-12-04 23:53 ` [PATCH net v3 5/9] selftests: net: py: reap commands that fail to report ready Rishikesh Jethwani
@ 2026-12-04 23:53 ` Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 7/9] selftests: net: add TLS offload over bond tests Rishikesh Jethwani
` (2 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Rishikesh Jethwani @ 2026-12-04 23:53 UTC (permalink / raw)
To: netdev
Cc: Rishikesh Jethwani, David S. Miller, Eric Dumazet, Jakub Kicinski,
Paolo Abeni, Willem de Bruijn, Simon Horman, Shuah Khan,
linux-kselftest
Let callers override the 20-second context-exit timeout for
long-running commands. None waits indefinitely on normal exit, but
gives a readiness-enabled command one second to exit on cancellation.
An explicit zero still means no grace period.
Signed-off-by: Rishikesh Jethwani <rjethwani@purestorage.com>
---
tools/testing/selftests/net/lib/py/utils.py | 18 +++++++++++++-----
1 file changed, 13 insertions(+), 5 deletions(-)
diff --git a/tools/testing/selftests/net/lib/py/utils.py b/tools/testing/selftests/net/lib/py/utils.py
index 9edfc4f88621..1db7a21db642 100644
--- a/tools/testing/selftests/net/lib/py/utils.py
+++ b/tools/testing/selftests/net/lib/py/utils.py
@@ -274,7 +274,11 @@ class cmd:
if self.proc.poll() is None:
if terminate:
self._kill_group(signal.SIGTERM)
- self._drain_until_exit((out, err), timeout=timeout)
+ # None waits forever elsewhere; cleanup must end. Not
+ # "timeout or 1", which would change an explicit 0.
+ self._drain_until_exit((out, err),
+ timeout=1 if timeout is None
+ else timeout)
self._collect_reaped(out, err)
def _collect_reaped(self, out, err):
@@ -385,11 +389,12 @@ class bkg(cmd):
"""
def __init__(self, comm, shell=None, fail=None, expect_fail=None,
ns=None, host=None, exit_wait=False, ksft_ready=None,
- ksft_wait=None):
+ ksft_wait=None, timeout=20):
super().__init__(comm, background=True,
shell=shell, fail=fail, expect_fail=expect_fail,
ns=ns, host=host, ksft_ready=ksft_ready,
ksft_wait=ksft_wait)
+ self.timeout = timeout
self.terminate = not exit_wait and not ksft_wait
self._exit_wait = exit_wait
self.check_fail = fail
@@ -410,15 +415,18 @@ class bkg(cmd):
terminate = terminate or (self._exit_wait and ex_type is not None)
if ex_type is None:
return self.process(terminate=terminate, fail=self.check_fail,
- expect_fail=self.expect_fail)
+ expect_fail=self.expect_fail,
+ timeout=self.timeout)
# Cancelled, e.g. by Ctrl-C: stop the command and what it started,
# without replacing the exception in flight.
if self._own_pgrp:
- self._cleanup_quietly(self._reap_cancelled, terminate, 20)
+ self._cleanup_quietly(self._reap_cancelled, terminate,
+ self.timeout)
else:
self._cleanup_quietly(self.process, terminate=terminate,
fail=self.check_fail,
- expect_fail=self.expect_fail)
+ expect_fail=self.expect_fail,
+ timeout=self.timeout)
return None
--
2.50.1
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH net v3 7/9] selftests: net: add TLS offload over bond tests
2026-12-04 23:53 [PATCH net v3 0/9] tls: device: don't put offload plaintext on the wire Rishikesh Jethwani
` (5 preceding siblings ...)
2026-12-04 23:53 ` [PATCH net v3 6/9] selftests: net: py: add a timeout argument to bkg() Rishikesh Jethwani
@ 2026-12-04 23:53 ` Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 8/9] selftests: net: test TLS fallback after rerouting to an upper device Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 9/9] selftests: net: verify that IP refuses to fragment TLS offload data Rishikesh Jethwani
8 siblings, 0 replies; 10+ messages in thread
From: Rishikesh Jethwani @ 2026-12-04 23:53 UTC (permalink / raw)
To: netdev
Cc: Rishikesh Jethwani, Andrew Lunn, David S. Miller, Eric Dumazet,
Jakub Kicinski, Paolo Abeni, Shuah Khan, John Fastabend,
Sabrina Dubroca, linux-kselftest
Run the kTLS echo test over a single-slave balance-xor bond with
layer3+4 hashing. First verify that the slave offloads TLS. Then take
the slave down midway through an echo to exercise TX software fallback.
Cover two cases: bring the slave back before the client resumes, or
resume the client with the slave down and wait for a retransmission
timeout before bringing it back. Without the fix, the fallback
encrypts the same data at both the bond and the slave, and the echoed
data differs from what the client sent in both cases.
Skip configurations the test cannot safely restore. On cleanup,
restore the NIC's addresses and verify that its original routes are back
Both bounce cases fail without "tls: device: keep tls_sw_fallback()
from encrypting its own output".
Signed-off-by: Rishikesh Jethwani <rjethwani@purestorage.com>
---
tools/testing/selftests/drivers/net/hw/config | 1 +
.../selftests/drivers/net/hw/tls_hw_offload.c | 57 +-
.../drivers/net/hw/tls_hw_offload.py | 499 +++++++++++++++++-
3 files changed, 543 insertions(+), 14 deletions(-)
diff --git a/tools/testing/selftests/drivers/net/hw/config b/tools/testing/selftests/drivers/net/hw/config
index 081155bf7847..ee658188670a 100644
--- a/tools/testing/selftests/drivers/net/hw/config
+++ b/tools/testing/selftests/drivers/net/hw/config
@@ -1,3 +1,4 @@
+CONFIG_BONDING=y
CONFIG_BPF_SYSCALL=y
CONFIG_FAIL_FUNCTION=y
CONFIG_FAULT_INJECTION=y
diff --git a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c
index 5b3887f32b68..9c1c546d36cf 100644
--- a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c
+++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c
@@ -24,6 +24,8 @@
#include <netdb.h>
#include <linux/tls.h>
+#include "../../../net/lib/ksft.h"
+
#ifndef SOL_TLS
#define SOL_TLS 282
#endif
@@ -82,13 +84,19 @@ static int random_size_max;
*/
static int verbose;
-/* Upper bound on a helper's lifetime, enforced by SIGALRM. The harness
- * waits for both helpers with the default 20s cmd()/bkg() timeout and
- * cannot signal the one on the remote, so each must exit on its own first.
- * A normal run takes a few seconds; the socket timeouts catch most stalls
- * sooner and with a better error.
+/* -P: pause the client halfway until the harness releases it. */
+static int pause_mid;
+
+/* Upper bound on a helper's lifetime, enforced by SIGALRM. On a timeout
+ * the harness can only kill the ssh client of the remote helper, not the
+ * helper itself, so each must exit on its own first. A normal run takes a
+ * few seconds; the socket timeouts catch most stalls sooner and with a
+ * better error. -T raises both, keeping the lifetime above the I/O timeout.
*/
#define HELPER_TIMEOUT_S 15
+#define IO_TIMEOUT_S 8
+static int io_timeout_s = IO_TIMEOUT_S;
+static int helper_timeout_s = HELPER_TIMEOUT_S;
static const char *cipher_name(int cipher)
{
@@ -152,7 +160,7 @@ static void configure_echo_socket(int fd, int payload)
*/
static void set_io_timeouts(int fd)
{
- struct timeval tv = { .tv_sec = 8, .tv_usec = 0 };
+ struct timeval tv = { .tv_sec = io_timeout_s, .tv_usec = 0 };
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
@@ -388,6 +396,13 @@ static int do_client(void)
printf("Sent %zd bytes (iteration %d)\n", n, i);
if (client_recv_echo(csk, buf, echo_buf, n) < 0)
goto out;
+
+ if (pause_mid && i == num_iterations / 2) {
+ printf("Pausing after iteration %d\n", i);
+ ksft_ready();
+ ksft_wait();
+ printf("Resumed\n");
+ }
}
test_result = 0;
@@ -751,6 +766,10 @@ static void print_usage(const char *prog)
printf(" -c <cipher> Cipher: 128 or 256 (default: 128)\n");
printf(" -n <N> Send/echo iterations (default: 100)\n");
printf(" -t <type> Record type test: 21=alert, 22=handshake\n");
+ printf(" -P Pause halfway (client): ksft_ready(), ksft_wait()\n");
+ printf(" -T <sec> Send/recv timeout (default: %d); lifetime bound\n"
+ " becomes 2 * <sec> + 15 (default: %d)\n",
+ IO_TIMEOUT_S, HELPER_TIMEOUT_S);
printf(" -V Verbose: log every iteration\n");
printf(" -h Show this help message\n");
printf("\nExample:\n");
@@ -779,7 +798,6 @@ int main(int argc, char *argv[])
* is not lost in the stdio buffer.
*/
setvbuf(stdout, NULL, _IOLBF, 0);
- alarm(HELPER_TIMEOUT_S);
if (argc < 2 ||
(strcmp(argv[1], "server") && strcmp(argv[1], "client"))) {
@@ -789,7 +807,7 @@ int main(int argc, char *argv[])
is_server = !strcmp(argv[1], "server");
optind = 2; /* skip subcommand */
- while ((opt = getopt(argc, argv, "s:p:b:r:c:v:n:t:V46h")) != -1) {
+ while ((opt = getopt(argc, argv, "s:p:b:r:c:v:n:t:T:PV46h")) != -1) {
switch (opt) {
case 's':
server_ip = optarg;
@@ -797,6 +815,17 @@ int main(int argc, char *argv[])
case 'V':
verbose = 1;
break;
+ case 'P':
+ pause_mid = 1;
+ break;
+ case 'T':
+ io_timeout_s = atoi(optarg);
+ if (io_timeout_s < 1 || io_timeout_s > 120) {
+ printf("ERROR: -T out of range 1..120\n");
+ return 1;
+ }
+ helper_timeout_s = 2 * io_timeout_s + 15;
+ break;
case '4':
if (force_family == AF_INET6) {
printf("ERROR: -4 and -6 are exclusive\n");
@@ -865,6 +894,11 @@ int main(int argc, char *argv[])
return 1;
}
+ if (pause_mid && (test_record_type || num_iterations < 2)) {
+ printf("ERROR: -P needs echo mode and -n >= 2\n");
+ return 1;
+ }
+
if (test_record_type && random_size_max) {
printf("ERROR: -t cannot be combined with -r\n");
return 1;
@@ -879,6 +913,10 @@ int main(int argc, char *argv[])
printf("warning: -r is ignored in server mode\n");
random_size_max = 0;
}
+ if (pause_mid) {
+ printf("warning: -P is ignored in server mode\n");
+ pause_mid = 0;
+ }
} else {
if (!server_ip) {
printf("ERROR: Client requires -s <ip> option\n");
@@ -886,6 +924,9 @@ int main(int argc, char *argv[])
}
}
+ /* After option parsing, so -T applies */
+ alarm(helper_timeout_s);
+
printf("TLS Version: %s\n", version_name(tls_version));
printf("Cipher: %s\n", cipher_name(cipher_type));
printf("Address family: %s\n",
diff --git a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
index e720ce654761..7d90f1c2024a 100755
--- a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
+++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
@@ -3,15 +3,27 @@
"""Test kTLS hardware offload using a C helper binary."""
+import ipaddress
+import json
+import os
+import socket
+import struct
+import sys
+import tempfile
+import time
from collections import defaultdict
from lib.py import (
CmdExitFailure,
+ KsftFailEx,
KsftNamedVariant,
KsftSkipEx,
NetDrvEpEnv,
bkg,
cmd,
+ defer,
+ ip,
+ ksft_disruptive,
ksft_eq,
ksft_exit,
ksft_ge,
@@ -19,9 +31,18 @@ from lib.py import (
ksft_run,
ksft_variants,
rand_port,
+ wait_file,
wait_port_listen,
)
+BOND_IFNAME = "tlsbond0"
+
+# -T for -P cases, long enough for a bounced NIC to retrain.
+PAUSE_IO_TIMEOUT_S = 45
+# bounce_inflight(): outage once the client has sent, and wait for that.
+INFLIGHT_OUTAGE_S = 2
+INFLIGHT_SEND_WAIT_S = 10
+
# `ethtool -S` counters on the DUT NIC, from the minimum set every TLS
# offload driver should report (Documentation/networking/tls-offload.rst,
# "Statistics"). Drivers expose varying subsets: mlx5 has all four, nfp
@@ -198,7 +219,7 @@ def verify_tls_counters(stats_before, stats_after, is_dut, hw_directions=()):
def run_tls_test(cfg, cipher="128", tls_version="1.2",
buffer_size=None, random_max=None, ipver="4",
- record_type=None):
+ record_type=None, pause=None):
"""Run the TLS offload test.
The DUT runs the TLS client and the remote runs the echo server.
@@ -213,6 +234,10 @@ def run_tls_test(cfg, cipher="128", tls_version="1.2",
kTLS because TLS is pairwise, but verify_tls_counters() requires HW
offload only in enabled DUT directions. The peer and the DUT's other
direction may use SW kTLS.
+
+ pause: if set, the client stops halfway, pause(cfg, port) runs, and
+ the client resumes once it returns. pause() may return a bkg()
+ handle for work that outlives it, reaped after the echo.
"""
require_tls_setup(cfg)
@@ -228,8 +253,13 @@ def run_tls_test(cfg, cipher="128", tls_version="1.2",
port = rand_port()
send_size = random_max or buffer_size
+ io_opt = f"-T {PAUSE_IO_TIMEOUT_S}"
+ budget = {"timeout": 2 * PAUSE_IO_TIMEOUT_S + 30} if pause else {}
+
server_parts = [f"{cfg.bin_remote} server -p {port} -c {cipher}",
f"-v {tls_version}", f"-{ipver}"]
+ if pause:
+ server_parts.append(io_opt)
if send_size:
server_parts.append(f"-b {send_size}")
if record_type:
@@ -244,26 +274,48 @@ def run_tls_test(cfg, cipher="128", tls_version="1.2",
client_parts.append(f"-b {buffer_size}")
if record_type:
client_parts.append(f"-t {record_type}")
+ if pause:
+ client_parts += ["-P", io_opt]
client_cmd = " ".join(client_parts)
stats_before_local = read_tls_stats()
stats_before_remote = read_tls_stats(host=cfg.remote)
nic_before = read_nic_stats(cfg)
+ nic_paused = None
# The remote server runs under bkg(), whose stdout pipe is only drained
# once it exits, so the helper keeps its per-connection output small
# (see the note on verbose in tls_hw_offload.c); do not pass -V.
#
- # Both helpers exit on their own within HELPER_TIMEOUT_S (see
+ # Both helpers exit on their own within their SIGALRM lifetime (see
# tls_hw_offload.c), so nothing outlives the variant even on failure.
- with bkg(server_cmd, host=cfg.remote, exit_wait=True):
+ with bkg(server_cmd, host=cfg.remote, exit_wait=True, **budget):
wait_port_listen(port, host=cfg.remote)
- cmd(client_cmd)
+ if pause:
+ # bkg() returns once the client pauses; leaving resumes it.
+ pending = None
+ reap_timeout = INFLIGHT_SEND_WAIT_S + INFLIGHT_OUTAGE_S + 10
+ try:
+ with bkg(client_cmd, ksft_wait=30, **budget):
+ # pause() may take the socket off the NIC.
+ cfg.wait_hw_stats_settle()
+ nic_paused = read_nic_stats(cfg)
+ pending = pause(cfg, port)
+ except BaseException:
+ if pending:
+ pending.process(terminate=True, fail=False,
+ timeout=reap_timeout)
+ raise
+ if pending:
+ pending.process(terminate=False, fail=True,
+ timeout=reap_timeout)
+ else:
+ cmd(client_cmd)
cfg.wait_hw_stats_settle()
stats_after_local = read_tls_stats()
stats_after_remote = read_tls_stats(host=cfg.remote)
- nic_after = read_nic_stats(cfg)
+ nic_after = nic_paused if pause else read_nic_stats(cfg)
verify_tls_counters(stats_before_local, stats_after_local, is_dut=True,
hw_directions=hw_directions)
@@ -305,6 +357,439 @@ def test_tls_offload_record_type(cfg, record_type):
run_tls_test(cfg, record_type=record_type)
+def wait_carrier(ifname, deadline=30):
+ """Wait for carrier, which can take a NIC well over wait_file()'s
+ default 5s after a flap.
+ """
+ wait_file(f"/sys/class/net/{ifname}/carrier",
+ lambda x: x.strip() == "1", deadline=deadline)
+
+
+def wait_reachable(ifname, peer, deadline=30):
+ """Wait until the peer answers through ifname.
+
+ The peer can lag carrier after a flap; fail here rather than with an
+ opaque connect() error in the helper.
+ """
+ family = "-6" if ":" in peer else "-4"
+ end = time.monotonic() + deadline
+ while cmd(f"ping {family} -c1 -W1 -I {ifname} {peer}",
+ fail=False).ret != 0:
+ if time.monotonic() > end:
+ raise KsftFailEx(f"{peer} unreachable through {ifname}")
+ time.sleep(0.5)
+
+
+def save_nic(ifname):
+ """Dump the NIC's global addresses and its routes in all tables.
+
+ Skip the IPv6 local table, which the restored addresses and addrconf
+ recreate: require_restorable() refuses NICs with other routes there,
+ and restore_nic() checks that they came back.
+ """
+ saved = tempfile.TemporaryDirectory()
+ cmd(f"ip addr save dev {ifname} scope global > {saved.name}/addr",
+ shell=True)
+ cmd(f"ip -4 route save dev {ifname} table all > {saved.name}/route4",
+ shell=True)
+ tables = {r.get("table", "main") for r in
+ ip(f"-6 route show dev {ifname} table all", json=True)}
+ for table in sorted(tables - {"local"}):
+ cmd(f"ip -6 route save dev {ifname} table {table} "
+ f"> {saved.name}/route6-{table}", shell=True)
+ return saved
+
+
+# Route attributes that change on their own: flags follow the carrier
+# (linkdown), and expires counts down.
+ROUTE_VOLATILE = ("flags", "expires")
+
+
+def route_keys(ifname):
+ """The NIC's routes as save_nic() dumps them, for comparison."""
+ keys = set()
+ for family in ("-4", "-6"):
+ for r in ip(f"{family} route show dev {ifname} table all",
+ json=True):
+ if family == "-6" and r.get("table") == "local":
+ continue
+ attrs = {k: v for k, v in r.items() if k not in ROUTE_VOLATILE}
+ keys.add((family, json.dumps(attrs, sort_keys=True)))
+ return keys
+
+
+def local6_routes(ifname):
+ """The NIC's IPv6 local table routes, with the attributes that identify
+ them: all but empty flags. Unlike in route_keys(), an expiry or a flag
+ counts: addrconf's routes have neither, so such a route would not come
+ back as it was. -d, as iproute2 omits "proto boot" otherwise.
+ """
+ return [{k: v for k, v in r.items() if k != "flags" or v}
+ for r in ip(f"-d -6 route show dev {ifname} table local",
+ json=True)]
+
+
+def local6_keys(ifname):
+ """local6_routes() in comparable form."""
+ return {json.dumps(r, sort_keys=True) for r in local6_routes(ifname)}
+
+
+def wait_local6(ifname, local6, deadline=10):
+ """Fail unless the IPv6 local routes saved by setup_bond() come back.
+
+ addrconf adds an address's route only once its DAD completes.
+ """
+ end = time.monotonic() + deadline
+ while True:
+ missing = local6 - local6_keys(ifname)
+ if not missing:
+ return
+ if time.monotonic() > end:
+ raise KsftFailEx(f"{len(missing)} IPv6 local routes of {ifname} "
+ f"missing after restore: "
+ + "; ".join(sorted(missing)))
+ time.sleep(0.5)
+
+
+def check_routes(ifname, routes, when):
+ """Fail if any of the routes saved by setup_bond() is missing."""
+ missing = routes - route_keys(ifname)
+ if missing:
+ link = ip(f"link show dev {ifname}", json=True)[0]
+ raise KsftFailEx(f"{len(missing)} routes of {ifname} missing "
+ f"{when} (flags {link['flags']}, operstate "
+ f"{link['operstate']}): "
+ + "; ".join(f"{family} {attrs}"
+ for family, attrs in sorted(missing)))
+
+
+def count_routes(ifname):
+ """Number of IPv4 and IPv6 routes on ifname, in all tables."""
+ return sum(len(ip(f"{family} route show dev {ifname} table all",
+ json=True))
+ for family in ("-4", "-6"))
+
+
+def restore_routes(ifname, dumps):
+ """Replay route dumps until all of them apply.
+
+ "ip route restore" stops at the first failing route, e.g. one whose
+ gateway's route comes later, so replay while each round adds routes.
+ """
+ routes = count_routes(ifname)
+ while True:
+ failed = [dump for dump in dumps
+ if cmd(f"ip route restore < {dump}", shell=True,
+ fail=False).ret]
+ if not failed:
+ return
+ prev, routes = routes, count_routes(ifname)
+ if routes == prev:
+ raise KsftFailEx(f"Could not restore the routes of {ifname} "
+ f"from {failed}")
+
+
+def restore_nic(cfg, saved, routes, local6):
+ """Bring the NIC back up as a standalone link with its configuration.
+
+ Check the routes after the replay and again after carrier, to tell a
+ failed replay from routes the kernel removed later, and the IPv6
+ local routes, which addrconf recreates, once there is carrier.
+ """
+ try:
+ ip(f"link set dev {cfg.ifname} up")
+ cmd(f"ip addr restore < {saved.name}/addr", shell=True)
+ restore_routes(cfg.ifname,
+ [f"{saved.name}/{dump}"
+ for dump in sorted(os.listdir(saved.name))
+ if dump.startswith("route")])
+ finally:
+ saved.cleanup()
+ check_routes(cfg.ifname, routes, "after the replay")
+ # Best effort: the next case waits for carrier itself.
+ try:
+ wait_carrier(cfg.ifname, deadline=10)
+ except TimeoutError:
+ ksft_pr(f"NOTE: {cfg.ifname} still without carrier, "
+ f"leaving it to the next case to wait for, and not "
+ f"checking its IPv6 local routes, which need DAD")
+ else:
+ wait_local6(cfg.ifname, local6)
+ check_routes(cfg.ifname, routes, "after waiting for carrier")
+
+
+def eui64_link_local(mac):
+ """The link-local address addrconf derives from mac (addr_gen_mode 0)."""
+ b = bytes.fromhex(mac.replace(":", ""))
+ iid = bytes([b[0] ^ 2]) + b[1:3] + b"\xff\xfe" + b[3:6]
+ return ipaddress.IPv6Address(b"\xfe\x80" + bytes(6) + iid)
+
+
+def normalize_local6(route):
+ """route with its destination as an IPv6 network, so that a host
+ address printed without /128 compares equal. Anything else, such as
+ "default", is left as printed.
+ """
+ try:
+ dst = str(ipaddress.IPv6Network(route["dst"]))
+ except ValueError:
+ return route
+ return {**route, "dst": dst}
+
+
+def require_ipv6_recreated(ifname):
+ """Skip unless the NIC's IPv6 addresses and local routes come back.
+
+ Taking the NIC down removes its IPv6 addresses and its IPv6 local
+ table, which save_nic() leaves out. Only the global addresses are
+ restored; addrconf adds the EUI-64 link-local address again in
+ addr_gen_mode 0, as the MAC is unchanged. Of the local table, allow
+ only the routes those recreate, as wait_local6() expects them back,
+ compared whole: any other route, or one of those with an attribute
+ addrconf does not set (another metric, a metrics entry, ...), would
+ be lost, so skip. This includes anycast routes and NICs without IPv6
+ addresses, whose local table can still hold routes.
+ """
+ link = ip(f"addr show dev {ifname}", json=True)[0]
+ v6 = [a for a in link["addr_info"] if a["family"] == "inet6"]
+ auto_ll = None
+ mode = f"/proc/sys/net/ipv6/conf/{ifname}/addr_gen_mode"
+ if os.path.exists(mode):
+ with open(mode, encoding="ascii") as f:
+ if f.read().strip() == "0":
+ auto_ll = eui64_link_local(link["address"])
+ kept = set()
+ for a in v6:
+ addr = ipaddress.IPv6Address(a["local"])
+ if a.get("scope") != "global" and addr != auto_ll:
+ raise KsftSkipEx(f"IPv6 address {addr} on {ifname} would be "
+ f"lost: taking {ifname} down removes it, and "
+ f"only global addresses are restored")
+ kept.add(addr)
+ # The routes addrconf adds, as local6_routes() shows them.
+ common = {"protocol": "kernel", "scope": "global", "pref": "medium"}
+ allowed = [{**common, "type": "local", "dst": f"{addr}/128",
+ "metric": 0} for addr in kept]
+ allowed.append({**common, "type": "multicast", "dst": "ff00::/8",
+ "metric": 256})
+ for r in local6_routes(ifname):
+ if normalize_local6(r) in allowed:
+ continue
+ raise KsftSkipEx(f"IPv6 local table route of {ifname} would not "
+ f"come back after taking {ifname} down: "
+ f"{json.dumps(r, sort_keys=True)}")
+
+
+def require_restorable(ifname, addrs):
+ """Skip if moving the NIC into the bond would lose state that
+ restore_nic() does not put back.
+
+ Flushing the addresses deletes IPv4 routes, and strips the source of
+ IPv6 routes, that prefer one of them as source, also through other
+ devices. Taking the NIC down deletes multipath routes through it,
+ which save_nic()'s per-device dumps miss, flushes its permanent and
+ proxy neighbour entries, and removes its IPv6 addresses (see
+ require_ipv6_recreated()).
+ """
+ locals_ = {a["local"] for a in addrs}
+ for family in ("-4", "-6"):
+ # Unfiltered: "dev" filtering can leave out multipath routes.
+ for r in ip(f"{family} route show table all", json=True):
+ hops = [h.get("dev") for h in r.get("nexthops", [])]
+ if ifname in hops:
+ raise KsftSkipEx(f"Multipath route {r['dst']} has a "
+ f"nexthop through {ifname}, which taking "
+ f"it down would delete")
+ # A multipath route has no "dev".
+ if r.get("prefsrc") in locals_ and r.get("dev") != ifname:
+ raise KsftSkipEx(f"Route {r['dst']} via "
+ f"{r.get('dev', 'multipath')} prefers "
+ f"{r['prefsrc']} as source, which moving "
+ f"{ifname}'s addresses would remove")
+ require_ipv6_recreated(ifname)
+ if ip(f"neigh show dev {ifname} nud permanent", json=True) or \
+ ip(f"neigh show proxy dev {ifname}", json=True):
+ raise KsftSkipEx(f"{ifname} has permanent or proxy neighbour "
+ f"entries, which taking it down would delete")
+
+
+def require_connected_peers(cfg, addrs):
+ """Skip unless every peer is on-link through a prefix of addrs.
+
+ Only the addresses move to the bond, bringing their prefix routes
+ with them: a peer reached through a gateway, or through any route
+ other than those, would be unreachable through the bond.
+ """
+ nets = [ipaddress.ip_network(f"{a['local']}/{a['prefixlen']}",
+ strict=False) for a in addrs]
+ for peer in filter(None, cfg.remote_addr_v.values()):
+ family = "-6" if ":" in peer else "-4"
+ route = ip(f"{family} route get {peer}", json=True)[0]
+ if (route.get("dev") != cfg.ifname or "gateway" in route or
+ not any(ipaddress.ip_address(peer) in net for net in nets)):
+ raise KsftSkipEx(f"{peer} is not on-link through a prefix of "
+ f"{cfg.ifname}'s global addresses, so it would "
+ f"be unreachable through {BOND_IFNAME}")
+
+
+def setup_bond(cfg):
+ """Enslave the DUT NIC to a single-slave bond for the rest of the case.
+
+ kTLS offload over a bond needs layer3+4 hashing (bond_sk_get_lower_dev());
+ balance-xor needs no LACP partner. The NIC's global addresses move to
+ the bond and cleanup restores them and its routes.
+ """
+ # Reuse the NIC's MAC so the peer's neighbour entries stay valid.
+ link = ip(f"link show dev {cfg.ifname}", json=True)[0]
+ if "master" in link:
+ raise KsftSkipEx(f"{cfg.ifname} is already enslaved to "
+ f"{link['master']}")
+ if ip(f"nexthop show dev {cfg.ifname}", json=True):
+ raise KsftSkipEx(f"{cfg.ifname} has nexthop objects, which taking "
+ f"it down would delete")
+ mtu, mac = link["mtu"], link["address"]
+ addrs = [a for a in
+ ip(f"addr show dev {cfg.ifname}", json=True)[0]["addr_info"]
+ if a.get("scope") == "global"]
+ if not addrs:
+ raise KsftSkipEx(f"No global address on {cfg.ifname} to move to "
+ f"{BOND_IFNAME}")
+ require_restorable(cfg.ifname, addrs)
+ require_connected_peers(cfg, addrs)
+
+ routes = route_keys(cfg.ifname)
+ local6 = local6_keys(cfg.ifname)
+ saved = save_nic(cfg.ifname)
+ ip(f"link add {BOND_IFNAME} address {mac} mtu {mtu} type bond "
+ "mode balance-xor xmit_hash_policy layer3+4 miimon 100")
+ # defer() runs LIFO: delete the bond (releasing the NIC) first.
+ defer(restore_nic, cfg, saved, routes, local6)
+ defer(ip, f"link del {BOND_IFNAME}")
+
+ # Deleting a primary IPv4 address can take its secondaries with it.
+ ip(f"addr flush dev {cfg.ifname} scope global")
+ ip(f"link set dev {cfg.ifname} down")
+ ip(f"link set dev {cfg.ifname} master {BOND_IFNAME}")
+ ip(f"link set dev {BOND_IFNAME} up")
+ for addr in addrs:
+ nodad = " nodad" if addr["family"] == "inet6" else ""
+ ip(f"addr replace {addr['local']}/{addr['prefixlen']} "
+ f"dev {BOND_IFNAME}{nodad}")
+ wait_bond_ready(cfg)
+
+
+def wait_bond_ready(cfg):
+ """Wait until the bond carries traffic through its slave again.
+
+ The bond's carrier lags the slave's by a miimon round: check both.
+ """
+ wait_carrier(cfg.ifname)
+ wait_carrier(BOND_IFNAME)
+
+ for peer in filter(None, cfg.remote_addr_v.values()):
+ wait_reachable(BOND_IFNAME, peer)
+
+
+@ksft_disruptive
+def test_tls_offload_bond(cfg):
+ """kTLS offload to the slave NIC through a bond, with no bounce."""
+ require_tls_setup(cfg)
+ cfg.require_ipver("4")
+ setup_bond(cfg)
+ run_tls_test(cfg)
+
+
+def bounce_idle(cfg, _port):
+ """Bounce the slave while the socket is idle, then resume the echo."""
+ ip(f"link set dev {cfg.ifname} down")
+ ip(f"link set dev {cfg.ifname} up")
+ wait_bond_ready(cfg)
+
+
+# Background link-up for bounce_inflight(). Reads icsk_retransmits from
+# /proc/net/tcp, as ss needs CONFIG_INET_DIAG for it.
+INFLIGHT_LINK_UP = """
+import subprocess, sys, time
+proc_rem, base, ifname, wait_s, outage_s = sys.argv[1:]
+
+def client_retransmits():
+ with open("/proc/net/tcp") as f:
+ return [int(c[6], 16) for c in (l.split() for l in f.readlines()[1:])
+ if c[2] == proc_rem and c[3] == "01"]
+
+found = []
+# Bring the slave back however polling ends.
+try:
+ end = time.monotonic() + float(wait_s)
+ while time.monotonic() < end:
+ found = client_retransmits()
+ if len(found) == 1 and found[0] > int(base):
+ time.sleep(float(outage_s))
+ break
+ time.sleep(0.1)
+finally:
+ up = subprocess.run(["ip", "link", "set", "dev", ifname, "up"])
+if up.returncode:
+ sys.exit(up.returncode)
+if len(found) != 1 or found[0] <= int(base):
+ sys.exit(f"no client retransmission timeout during the outage "
+ f"(client sockets' retransmits: {found}, was {base})")
+"""
+
+
+def client_proc_rem(cfg, port):
+ """The test client's remote address as /proc/net/tcp prints it."""
+ addr = struct.unpack("=I", socket.inet_aton(cfg.remote_addr_v["4"]))[0]
+ return f"{addr:08X}:{port:04X}"
+
+
+def client_retransmits(cfg, port):
+ """The test client's icsk_retransmits."""
+ rem = client_proc_rem(cfg, port)
+ with open("/proc/net/tcp", encoding="ascii") as f:
+ found = [int(c[6], 16) for c in (l.split() for l in f.readlines()[1:])
+ if c[2] == rem and c[3] == "01"]
+ if len(found) != 1:
+ raise KsftFailEx(f"Expected one client socket to port {port}, "
+ f"found {len(found)}")
+ return found[0]
+
+
+def bounce_inflight(cfg, port):
+ """Send the resumed echo into a bond that has no usable slave.
+
+ The client resumes only after this returns, so the link-up runs in the
+ background, once the client's socket has had a retransmission timeout.
+ Returns it for run_tls_test() to reap; it fails if there was none.
+ """
+ base = client_retransmits(cfg, port)
+ ip(f"link set dev {cfg.ifname} down")
+ return bkg([sys.executable, "-c", INFLIGHT_LINK_UP,
+ client_proc_rem(cfg, port), str(base), cfg.ifname,
+ str(INFLIGHT_SEND_WAIT_S), str(INFLIGHT_OUTAGE_S)],
+ exit_wait=True)
+
+
+@ksft_variants([
+ KsftNamedVariant("idle", bounce_idle),
+ KsftNamedVariant("inflight", bounce_inflight),
+])
+@ksft_disruptive
+def test_tls_offload_bond_bounce(cfg, bounce):
+ """Bounce the bond slave under an open offloaded socket.
+
+ NETDEV_DOWN moves the socket to the TX SW fallback, which then runs
+ at both bond master and slave and must encrypt only once; encrypting
+ twice puts plaintext on the wire and the echo mismatches.
+ """
+ require_tls_setup(cfg)
+ if 'Tx' not in cfg.tls_hw_directions:
+ raise KsftSkipEx("Bond bounce requires DUT TLS TX offload")
+ cfg.require_ipver("4")
+ setup_bond(cfg)
+ run_tls_test(cfg, pause=bounce)
+
+
def main() -> None:
"""Set up the DUT/peer environment and run the offload test suites."""
with NetDrvEpEnv(__file__, nsim_test=False) as cfg:
@@ -312,8 +797,10 @@ def main() -> None:
cfg.bin_remote = None
cfg.tls_skip_reason = None
+ # Flap the NIC last, so a slow retrain cannot fail later cases.
ksft_run([test_tls_offload, test_tls_offload_sizes,
- test_tls_offload_record_type], args=(cfg, ))
+ test_tls_offload_record_type, test_tls_offload_bond,
+ test_tls_offload_bond_bounce], args=(cfg, ))
ksft_exit()
--
2.50.1
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH net v3 8/9] selftests: net: test TLS fallback after rerouting to an upper device
2026-12-04 23:53 [PATCH net v3 0/9] tls: device: don't put offload plaintext on the wire Rishikesh Jethwani
` (6 preceding siblings ...)
2026-12-04 23:53 ` [PATCH net v3 7/9] selftests: net: add TLS offload over bond tests Rishikesh Jethwani
@ 2026-12-04 23:53 ` Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 9/9] selftests: net: verify that IP refuses to fragment TLS offload data Rishikesh Jethwani
8 siblings, 0 replies; 10+ messages in thread
From: Rishikesh Jethwani @ 2026-12-04 23:53 UTC (permalink / raw)
To: netdev
Cc: Rishikesh Jethwani, Andrew Lunn, David S. Miller, Eric Dumazet,
Jakub Kicinski, Paolo Abeni, Shuah Khan, John Fastabend,
Sabrina Dubroca, linux-kselftest
Move an established offloaded connection to a macvlan on the same
NIC. Unlike a bond bounce, this leaves the NIC up and the socket
offloaded: the NIC must transmit the fallback's ciphertext unchanged.
Check that the resumed echo traverses the macvlan and matches the
original data. Without "tls: device: don't let the NIC encrypt
fallback output again", the echo mismatches.
Signed-off-by: Rishikesh Jethwani <rjethwani@purestorage.com>
---
tools/testing/selftests/drivers/net/hw/config | 1 +
.../drivers/net/hw/tls_hw_offload.py | 84 +++++++++++++++++++
2 files changed, 85 insertions(+)
diff --git a/tools/testing/selftests/drivers/net/hw/config b/tools/testing/selftests/drivers/net/hw/config
index ee658188670a..dab194fb27ee 100644
--- a/tools/testing/selftests/drivers/net/hw/config
+++ b/tools/testing/selftests/drivers/net/hw/config
@@ -14,6 +14,7 @@ CONFIG_IPV6=y
CONFIG_IPV6_GRE=y
CONFIG_IPV6_SIT=y
CONFIG_IPV6_TUNNEL=y
+CONFIG_MACVLAN=m
CONFIG_NET_CLS_ACT=y
CONFIG_NET_CLS_BPF=y
CONFIG_NET_DEVMEM=y
diff --git a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
index 7d90f1c2024a..e1382cee8dd1 100755
--- a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
+++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
@@ -36,6 +36,10 @@ from lib.py import (
)
BOND_IFNAME = "tlsbond0"
+MACVLAN_IFNAME = "tlsmv0"
+
+# Second half of the helper's default echo (-n 100, -b 16384).
+RESUMED_ECHO_BYTES = 50 * 16384
# -T for -P cases, long enough for a bounced NIC to retrain.
PAUSE_IO_TIMEOUT_S = 45
@@ -790,6 +794,85 @@ def test_tls_offload_bond_bounce(cfg, bounce):
run_tls_test(cfg, pause=bounce)
+def read_tx_bytes(ifname):
+ """TX bytes of a local interface."""
+ link = ip(f"-s link show dev {ifname}", json=True)[0]
+ return link["stats64"]["tx"]["bytes"]
+
+
+def sysctl_set(name, value):
+ """Set a sysctl for the rest of the case, restoring it on cleanup."""
+ old = cmd(f"sysctl -n {name}").stdout.strip()
+ cmd(f"sysctl -qw {name}={value}")
+ defer(cmd, f"sysctl -qw {name}={old}")
+
+
+def require_onlink_peer(cfg):
+ """Skip unless reroute_macvlan()'s direct /32 can take over the
+ connection's route without changing its next hop.
+
+ The macvlan is unnumbered and ARPs for the peer itself: a peer behind
+ a gateway would need the gateway, which also could not be made to
+ forget the macvlan's MAC on cleanup. An existing /32 to the peer would
+ clash with the one added, and a route from a table other than main
+ would win over it.
+ """
+ peer, local = cfg.remote_addr_v["4"], cfg.addr_v["4"]
+ route = ip(f"-d route get {peer} from {local}", json=True)[0]
+ if route.get("dev") != cfg.ifname or "gateway" in route:
+ raise KsftSkipEx(f"{peer} is not on-link through {cfg.ifname}")
+ if route.get("table", "main") != "main":
+ raise KsftSkipEx(f"{peer} is routed by table {route['table']}, "
+ f"not main")
+ if ip(f"route show table main exact {peer}/32", json=True):
+ raise KsftSkipEx(f"A host route to {peer} already exists")
+
+
+def setup_macvlan(cfg):
+ """Add a macvlan upper on the DUT NIC for the rest of the case.
+
+ The peer may answer on either MAC, so set loose rp_filter on both.
+ """
+ ip(f"link add {MACVLAN_IFNAME} link {cfg.ifname} type macvlan "
+ "mode bridge")
+ # Runs after the delete: make the peer drop the macvlan's MAC.
+ defer(ip, f"neigh flush to {cfg.addr_v['4']}", host=cfg.remote)
+ defer(ip, f"link del {MACVLAN_IFNAME}")
+ sysctl_set(f"net.ipv4.conf.{cfg.ifname}.rp_filter", 2)
+ sysctl_set(f"net.ipv4.conf.{MACVLAN_IFNAME}.rp_filter", 2)
+ ip(f"link set dev {MACVLAN_IFNAME} up")
+ wait_carrier(MACVLAN_IFNAME)
+
+
+def reroute_macvlan(cfg, _port):
+ """Move the paused connection's route to the macvlan upper."""
+ peer = cfg.remote_addr_v["4"]
+ # The macvlan is unnumbered, so pin the source address.
+ ip(f"route add {peer}/32 dev {MACVLAN_IFNAME} src {cfg.addr_v['4']}")
+ defer(ip, f"route del {peer}/32 dev {MACVLAN_IFNAME}")
+ wait_reachable(MACVLAN_IFNAME, peer)
+
+
+@ksft_disruptive
+def test_tls_offload_upper_reroute(cfg):
+ """Move an offloaded socket's route to an upper device of its NIC.
+
+ The NIC must not encrypt the SW fallback's output again.
+ """
+ require_tls_setup(cfg)
+ if 'Tx' not in cfg.tls_hw_directions:
+ raise KsftSkipEx("Upper device reroute requires DUT TLS TX offload")
+ cfg.require_ipver("4")
+ require_onlink_peer(cfg)
+ setup_macvlan(cfg)
+ before = read_tx_bytes(MACVLAN_IFNAME)
+ run_tls_test(cfg, pause=reroute_macvlan)
+ sent = read_tx_bytes(MACVLAN_IFNAME) - before
+ ksft_ge(sent, RESUMED_ECHO_BYTES,
+ comment=f"resumed echo did not go through {MACVLAN_IFNAME} "
+ f"({sent} bytes)")
+
+
def main() -> None:
"""Set up the DUT/peer environment and run the offload test suites."""
with NetDrvEpEnv(__file__, nsim_test=False) as cfg:
@@ -800,6 +883,7 @@ def main() -> None:
# Flap the NIC last, so a slow retrain cannot fail later cases.
ksft_run([test_tls_offload, test_tls_offload_sizes,
test_tls_offload_record_type, test_tls_offload_bond,
+ test_tls_offload_upper_reroute,
test_tls_offload_bond_bounce], args=(cfg, ))
ksft_exit()
--
2.50.1
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH net v3 9/9] selftests: net: verify that IP refuses to fragment TLS offload data
2026-12-04 23:53 [PATCH net v3 0/9] tls: device: don't put offload plaintext on the wire Rishikesh Jethwani
` (7 preceding siblings ...)
2026-12-04 23:53 ` [PATCH net v3 8/9] selftests: net: test TLS fallback after rerouting to an upper device Rishikesh Jethwani
@ 2026-12-04 23:53 ` Rishikesh Jethwani
8 siblings, 0 replies; 10+ messages in thread
From: Rishikesh Jethwani @ 2026-12-04 23:53 UTC (permalink / raw)
To: netdev
Cc: Rishikesh Jethwani, Andrew Lunn, David S. Miller, Eric Dumazet,
Jakub Kicinski, Paolo Abeni, Shuah Khan, John Fastabend,
Sabrina Dubroca, linux-kselftest
Pause an offloaded echo and reroute it onto a path whose MTU is below
the established connection's segment size. Cover both the NIC and a
macvlan upper. Clear DF on the client socket rather than changing the
namespace default.
A stalled echo alone does not prove IP refused fragmentation. Verify
that TX offload was active, ip_do_fragment() returned -EMSGSIZE for
the marked skbs, and no fragment reached output or device egress.
Require the client to time out after resuming and the peer to receive
no bytes beyond the pre-pause echo, with no TLS decryption error.
Signed-off-by: Rishikesh Jethwani <rjethwani@purestorage.com>
---
tools/testing/selftests/drivers/net/hw/config | 13 +
.../selftests/drivers/net/hw/tls_hw_offload.c | 28 +-
.../drivers/net/hw/tls_hw_offload.py | 258 +++++++++++++++++-
3 files changed, 297 insertions(+), 2 deletions(-)
diff --git a/tools/testing/selftests/drivers/net/hw/config b/tools/testing/selftests/drivers/net/hw/config
index dab194fb27ee..d36de1f3b2de 100644
--- a/tools/testing/selftests/drivers/net/hw/config
+++ b/tools/testing/selftests/drivers/net/hw/config
@@ -1,12 +1,18 @@
CONFIG_BONDING=y
+CONFIG_BPF_EVENTS=y
+CONFIG_BPF_JIT=y
CONFIG_BPF_SYSCALL=y
+CONFIG_DEBUG_INFO_BTF=y
+CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT=y
CONFIG_FAIL_FUNCTION=y
CONFIG_FAULT_INJECTION=y
CONFIG_FAULT_INJECTION_DEBUG_FS=y
CONFIG_FUNCTION_ERROR_INJECTION=y
+CONFIG_FUNCTION_TRACER=y
CONFIG_HUGETLBFS=y
CONFIG_INET6_ESP=y
CONFIG_INET6_ESP_OFFLOAD=y
+CONFIG_INET_DIAG=y
CONFIG_INET_ESP=y
CONFIG_INET_ESP_OFFLOAD=y
CONFIG_IO_URING=y
@@ -14,6 +20,8 @@ CONFIG_IPV6=y
CONFIG_IPV6_GRE=y
CONFIG_IPV6_SIT=y
CONFIG_IPV6_TUNNEL=y
+CONFIG_IP_ADVANCED_ROUTER=y
+CONFIG_IP_MULTIPLE_TABLES=y
CONFIG_MACVLAN=m
CONFIG_NET_CLS_ACT=y
CONFIG_NET_CLS_BPF=y
@@ -23,6 +31,11 @@ CONFIG_NET_IPGRE_DEMUX=y
CONFIG_NET_IPIP=y
CONFIG_NETKIT=y
CONFIG_NET_SCH_INGRESS=y
+CONFIG_NETFILTER=y
+CONFIG_NETFILTER_EGRESS=y
+CONFIG_NF_TABLES=m
+CONFIG_NF_TABLES_IPV4=y
+CONFIG_NF_TABLES_NETDEV=y
CONFIG_SYNC_FILE=y
CONFIG_TLS=y
CONFIG_TLS_DEVICE=y
diff --git a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c
index 9c1c546d36cf..73cb7a8a7b0f 100644
--- a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c
+++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c
@@ -87,6 +87,9 @@ static int verbose;
/* -P: pause the client halfway until the harness releases it. */
static int pause_mid;
+/* -D: let IP fragment the client's packets (IP_PMTUDISC_DONT). */
+static int pmtudisc_dont;
+
/* Upper bound on a helper's lifetime, enforced by SIGALRM. On a timeout
* the harness can only kill the ssh client of the remote helper, not the
* helper itself, so each must exit on its own first. A normal run takes a
@@ -254,6 +257,19 @@ static int install_tls_key(int fd, int direction, int cipher)
* family and %zone scope IDs in link-local addresses). Returns the fd on
* success, -1 on error (with the fd already closed).
*/
+static int set_pmtudisc_dont(int fd, int family)
+{
+ int val;
+
+ if (family == AF_INET6) {
+ val = IPV6_PMTUDISC_DONT;
+ return setsockopt(fd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &val,
+ sizeof(val));
+ }
+ val = IP_PMTUDISC_DONT;
+ return setsockopt(fd, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val));
+}
+
static int client_connect_tls(void)
{
struct addrinfo hints = {0}, *res, *rp;
@@ -281,6 +297,12 @@ static int client_connect_tls(void)
err = errno;
continue;
}
+ if (pmtudisc_dont && set_pmtudisc_dont(csk, rp->ai_family) < 0) {
+ err = errno;
+ close(csk);
+ csk = -1;
+ continue;
+ }
if (connect(csk, rp->ai_addr, rp->ai_addrlen) == 0)
break;
err = errno;
@@ -767,6 +789,7 @@ static void print_usage(const char *prog)
printf(" -n <N> Send/echo iterations (default: 100)\n");
printf(" -t <type> Record type test: 21=alert, 22=handshake\n");
printf(" -P Pause halfway (client): ksft_ready(), ksft_wait()\n");
+ printf(" -D Clear DF, letting IP fragment (client)\n");
printf(" -T <sec> Send/recv timeout (default: %d); lifetime bound\n"
" becomes 2 * <sec> + 15 (default: %d)\n",
IO_TIMEOUT_S, HELPER_TIMEOUT_S);
@@ -807,7 +830,7 @@ int main(int argc, char *argv[])
is_server = !strcmp(argv[1], "server");
optind = 2; /* skip subcommand */
- while ((opt = getopt(argc, argv, "s:p:b:r:c:v:n:t:T:PV46h")) != -1) {
+ while ((opt = getopt(argc, argv, "s:p:b:r:c:v:n:t:T:DPV46h")) != -1) {
switch (opt) {
case 's':
server_ip = optarg;
@@ -818,6 +841,9 @@ int main(int argc, char *argv[])
case 'P':
pause_mid = 1;
break;
+ case 'D':
+ pmtudisc_dont = 1;
+ break;
case 'T':
io_timeout_s = atoi(optarg);
if (io_timeout_s < 1 || io_timeout_s > 120) {
diff --git a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
index e1382cee8dd1..a937ec979a7b 100755
--- a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
+++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
@@ -3,9 +3,13 @@
"""Test kTLS hardware offload using a C helper binary."""
+import errno
import ipaddress
import json
import os
+import re
+import select
+import signal
import socket
import struct
import sys
@@ -27,6 +31,8 @@ from lib.py import (
ksft_eq,
ksft_exit,
ksft_ge,
+ ksft_in,
+ ksft_not_in,
ksft_pr,
ksft_run,
ksft_variants,
@@ -38,9 +44,24 @@ from lib.py import (
BOND_IFNAME = "tlsbond0"
MACVLAN_IFNAME = "tlsmv0"
-# Second half of the helper's default echo (-n 100, -b 16384).
+# Each half of the helper's default echo (-n 100, -b 16384): -P pauses
+# after the first, and the second is the resumed echo.
+PAUSED_ECHO_BYTES = 50 * 16384
RESUMED_ECHO_BYTES = 50 * 16384
+# Fragmentation cases (see frag_reroute()).
+FRAG_NFT_TABLE = "tlsfrag"
+FRAG_NFT_EGRESS_TABLE = "tlsfrag_egress"
+FRAG_MARK = 0x544c
+FRAG_RT_TABLE = 0x544c
+# Rerouted path's MTU, lowered to the connection's MSS (frag_reroute()).
+FRAG_MTU = 1000
+# The server's recv timeout outlasts the client's lifetime, so the
+# client stalls on its own timeout rather than seeing EOF.
+FRAG_CLIENT_LIFETIME_S = 15
+FRAG_SERVER_IO_TIMEOUT_S = 2 * FRAG_CLIENT_LIFETIME_S
+FRAG_SERVER_LIFETIME_S = 2 * FRAG_SERVER_IO_TIMEOUT_S + 15
+
# -T for -P cases, long enough for a bounced NIC to retrain.
PAUSE_IO_TIMEOUT_S = 45
# bounce_inflight(): outage once the client has sent, and wait for that.
@@ -873,6 +894,240 @@ def test_tls_offload_upper_reroute(cfg):
f"({sent} bytes)")
+def client_mss(peer, port):
+ """The MSS the test client's established socket sizes segments by.
+
+ -O prints one line per socket. Not finding exactly one is a test
+ failure; ss not reporting the MSS of the one found is a skip.
+ """
+ out = cmd(f"ss -tinHO state established dst {peer} "
+ f"dport = :{port}").stdout
+ socks = [line for line in out.splitlines() if line.strip()]
+ if len(socks) != 1:
+ raise KsftFailEx(f"Expected one client socket to port {port}, "
+ f"found {len(socks)}: {out.strip()!r}")
+ # Not advmss: or rcvmss:.
+ found = re.search(r"\bmss:(\d+)", socks[0])
+ if not found:
+ raise KsftSkipEx(f"ss reports no mss: for the client socket: "
+ f"{socks[0].strip()!r}")
+ return int(found.group(1))
+
+
+def frag_reroute(cfg, port, dev):
+ """Reroute the connection onto a small-MTU route without TCP noticing.
+
+ TCP keeps sizing segments for the socket's route, but the route chain
+ re-runs the lookup (ip_route_me_harder()) after marking the skb, so
+ each segment leaves through the policy route and exceeds its MTU. A
+ full segment is the MSS plus at least 40 bytes of headers, so an MTU
+ of at most the MSS is below it whatever the path the connection
+ started on.
+ """
+ peer = cfg.remote_addr_v["4"]
+ mtu = min(FRAG_MTU, client_mss(peer, port))
+ if mtu < 68:
+ raise KsftSkipEx(f"MSS {mtu} leaves no IPv4 MTU below the segments")
+ ip(f"route add {peer}/32 dev {dev} mtu {mtu} table {FRAG_RT_TABLE}")
+ defer(ip, f"route del {peer}/32 dev {dev} table {FRAG_RT_TABLE}")
+ # "create" fails if the table exists, so never delete one we do not own.
+ cmd(f"nft create table ip {FRAG_NFT_TABLE}")
+ defer(cmd, f"nft delete table ip {FRAG_NFT_TABLE}")
+ cmd(f"nft add chain ip {FRAG_NFT_TABLE} out "
+ "{ type route hook output priority mangle ; }")
+ cmd(f"nft add rule ip {FRAG_NFT_TABLE} out ip daddr {peer} "
+ f"tcp dport {port} meta mark set {FRAG_MARK}")
+
+
+def frag_count_egress(dev):
+ """Count the rerouted flow's IPv4 fragments that reach dev.
+
+ Egress runs before validate_xmit_skb(), so this also counts fragments
+ that tls_sw_fallback() or the driver would drop.
+ """
+ table = f"netdev {FRAG_NFT_EGRESS_TABLE}"
+ cmd(f"nft create table {table}")
+ defer(cmd, f"nft delete table {table}")
+ cmd(f"nft add counter {table} frags")
+ cmd(f"nft add chain {table} out "
+ f"{{ type filter hook egress device {dev} priority 0 ; }}")
+ cmd(f"nft add rule {table} out meta mark {FRAG_MARK} "
+ "ip frag-off & 0x3fff != 0 counter name frags")
+
+
+def read_nft_counter(family, table, name):
+ """Packet count of a named nftables counter."""
+ out = json.loads(cmd(f"nft --json list counter {family} {table} "
+ f"{name}").stdout)
+ return next(obj["counter"]["packets"] for obj in out["nftables"]
+ if "counter" in obj)
+
+
+# @ret: ip_do_fragment() return values for rerouted segments. @frags:
+# their fragments handed to ip_finish_output2(). Without the fix, a
+# fragment can fail in output() and never reach the egress counter, so
+# count both. The skb is not dereferenced on return, where it may be
+# freed. frag_off is read bytewise to avoid a byte swap.
+FRAG_BPFTRACE = f"""
+fentry:ip_do_fragment
+/args.skb->mark == {FRAG_MARK}/
+{{
+ @in[(uint64)args.skb] = 1;
+}}
+fexit:ip_do_fragment
+/@in[(uint64)args.skb]/
+{{
+ @ret[retval] = count();
+ delete(@in[(uint64)args.skb]);
+}}
+fentry:ip_finish_output2
+/args.skb->mark == {FRAG_MARK}/
+{{
+ $frag_off = args.skb->head + args.skb->network_header + 6;
+ if ((*(uint8 *)$frag_off & 0x3f) || *(uint8 *)($frag_off + 1)) {{
+ @frags = count();
+ }}
+}}
+"""
+
+
+def wait_bpftrace_attached(trace, timeout=30):
+ """Wait until bpftrace reports its probes attached, on either pipe."""
+ fds = [trace.proc.stdout.fileno(), trace.proc.stderr.fileno()]
+ deadline = time.monotonic() + timeout
+ seen = b""
+ while b"attached_probes" not in seen and b"Attaching " not in seen:
+ left = deadline - time.monotonic()
+ rlist = select.select(fds, [], [], left)[0] if left > 0 else []
+ if not rlist:
+ raise KsftFailEx(f"bpftrace did not attach: {seen!r}")
+ for fd in rlist:
+ data = os.read(fd, 4096)
+ if not data:
+ raise KsftFailEx(f"bpftrace exited: {seen!r}")
+ seen += data
+
+
+def bpftrace_maps(stdout):
+ """Maps from bpftrace's JSON output, by name without the "@"."""
+ maps = {}
+ for line in stdout.splitlines():
+ try:
+ obj = json.loads(line)
+ except ValueError:
+ continue
+ if obj.get("type") == "map":
+ for name, value in obj["data"].items():
+ maps[name.lstrip("@")] = value
+ return maps
+
+
+def frag_route_dev(cfg, upper):
+ """Return the device for the small-MTU route, setting it up if needed."""
+ if not upper:
+ return cfg.ifname
+ setup_macvlan(cfg)
+ return MACVLAN_IFNAME
+
+
+@ksft_variants([
+ KsftNamedVariant("same_dev", False),
+ KsftNamedVariant("upper", True),
+])
+@ksft_disruptive
+def test_tls_offload_frag(cfg, upper):
+ """IP must not fragment kTLS offload plaintext.
+
+ Every rerouted segment must be refused by ip_do_fragment(), and the
+ connection must stall rather than deliver or corrupt data: the server
+ must have received nothing beyond the bytes echoed before the pause.
+ Segments under the MTU, such as a record's tail, can still leave, but
+ out of order behind a refused one. MTU probing is off, as it would
+ shrink the MSS and end the stall.
+ """
+ require_tls_setup(cfg)
+ if 'Tx' not in cfg.tls_hw_directions:
+ raise KsftSkipEx("Fragmentation test requires DUT TLS TX offload")
+ cfg.require_ipver("4")
+ cfg.require_cmd("nft")
+ cfg.require_cmd("bpftrace")
+ cfg.require_cmd("ss")
+ if not os.path.exists("/sys/kernel/btf/vmlinux"):
+ raise KsftSkipEx("Fragmentation test requires CONFIG_DEBUG_INFO_BTF")
+
+ peer = cfg.remote_addr_v["4"]
+ dev = frag_route_dev(cfg, upper)
+ sysctl_set("net.ipv4.tcp_mtu_probing", 0)
+ # frag_reroute() fills the table; until then, lookups fall through it.
+ ip(f"rule add fwmark {FRAG_MARK} lookup {FRAG_RT_TABLE}")
+ defer(ip, f"rule del fwmark {FRAG_MARK} lookup {FRAG_RT_TABLE}")
+ frag_count_egress(dev)
+
+ port = rand_port()
+ server_cmd = (f"{cfg.bin_remote} server -p {port} -c 128 -v 1.2 -4 "
+ f"-T {FRAG_SERVER_IO_TIMEOUT_S}")
+ client_cmd = (f"{cfg.bin_local} client -s {peer} -p {port} -c 128 "
+ "-v 1.2 -4 -P -D")
+
+ tls_before = read_tls_stats()
+ peer_before = read_tls_stats(host=cfg.remote)
+ # Both helpers stall and time out, so check their outcome below.
+ with bkg(["bpftrace", "-f", "json", "-e", FRAG_BPFTRACE],
+ fail=False) as trace:
+ wait_bpftrace_attached(trace)
+ with bkg(server_cmd, host=cfg.remote, exit_wait=True, fail=False,
+ timeout=FRAG_SERVER_LIFETIME_S + 15) as server:
+ wait_port_listen(port, host=cfg.remote)
+ with bkg(client_cmd, ksft_wait=30, fail=False,
+ timeout=FRAG_CLIENT_LIFETIME_S + 15) as client:
+ frag_reroute(cfg, port, dev)
+ tls_after = read_tls_stats()
+ peer_after = read_tls_stats(host=cfg.remote)
+
+ dev_tx = stat_diff(tls_before, tls_after, 'TlsTxDevice')
+ ksft_ge(dev_tx, 1,
+ comment=f"HW TX offload not engaged (TlsTxDevice={dev_tx})")
+
+ maps = bpftrace_maps(trace.stdout)
+ rets = maps.get("ret", {})
+ refused = rets.get(str(-errno.EMSGSIZE), 0)
+ ksft_ge(refused, 1,
+ comment=f"no rerouted segment was refused by ip_do_fragment() "
+ f"(returns: {rets})")
+ ksft_eq(sum(rets.values()), refused,
+ comment=f"ip_do_fragment() returned other than -EMSGSIZE for "
+ f"rerouted segments (returns: {rets})")
+ built = maps.get("frags", 0)
+ ksft_eq(built, 0,
+ comment=f"ip_do_fragment() passed {built} fragments of rerouted "
+ f"segments to ip_finish_output2()")
+
+ ksft_in("Resumed", client.stdout,
+ comment="client never resumed after the reroute")
+ ksft_not_in("mismatch", client.stdout,
+ comment="client got a corrupted echo")
+ stalled = (client.ret == -signal.SIGALRM or
+ "Resource temporarily unavailable" in client.stdout)
+ ksft_eq(stalled, True,
+ comment=f"client did not stall (exit {client.ret}): "
+ f"{client.stdout.strip()}")
+ decrypt_err = stat_diff(peer_before, peer_after, 'TlsDecryptError')
+ ksft_eq(decrypt_err, 0,
+ comment=f"peer failed to decrypt (TlsDecryptError={decrypt_err})")
+ # The server reports its total once its recv times out.
+ received = re.search(r"Total received: (\d+) bytes", server.stdout)
+ ksft_eq(received is not None, True,
+ comment=f"server did not report its total: "
+ f"{server.stdout.strip()}")
+ ksft_eq(int(received.group(1)) if received else None, PAUSED_ECHO_BYTES,
+ comment="server received data sent after the reroute")
+
+ frags = read_nft_counter("netdev", FRAG_NFT_EGRESS_TABLE, "frags")
+ ksft_eq(frags, 0,
+ comment=f"offload plaintext was fragmented "
+ f"({frags} fragments reached {dev})")
+
+
def main() -> None:
"""Set up the DUT/peer environment and run the offload test suites."""
with NetDrvEpEnv(__file__, nsim_test=False) as cfg:
@@ -884,6 +1139,7 @@ def main() -> None:
ksft_run([test_tls_offload, test_tls_offload_sizes,
test_tls_offload_record_type, test_tls_offload_bond,
test_tls_offload_upper_reroute,
+ test_tls_offload_frag,
test_tls_offload_bond_bounce], args=(cfg, ))
ksft_exit()
--
2.50.1
^ permalink raw reply related [flat|nested] 10+ messages in thread