Netdev List
 help / color / mirror / Atom feed
From: Rishikesh Jethwani <rjethwani@purestorage.com>
To: netdev@vger.kernel.org
Cc: Rishikesh Jethwani <rjethwani@purestorage.com>,
	Andrew Lunn <andrew+netdev@lunn.ch>,
	"David S. Miller" <davem@davemloft.net>,
	Eric Dumazet <edumazet@kernel.org>,
	Jakub Kicinski <kuba@kernel.org>, Paolo Abeni <pabeni@redhat.com>,
	Shuah Khan <shuah@kernel.org>,
	John Fastabend <john.fastabend@gmail.com>,
	Sabrina Dubroca <sd@queasysnail.net>,
	linux-kselftest@vger.kernel.org
Subject: [PATCH net v3 9/9] selftests: net: verify that IP refuses to fragment TLS offload data
Date: Fri,  4 Dec 2026 16:53:56 -0700	[thread overview]
Message-ID: <20261204235642.36653-10-rjethwani@purestorage.com> (raw)
In-Reply-To: <20261204235642.36653-1-rjethwani@purestorage.com>

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


      parent reply	other threads:[~2026-12-04 23:56 UTC|newest]

Thread overview: 10+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
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 ` [PATCH net v3 3/9] tls: device: don't let the NIC encrypt fallback output again 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
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 ` [PATCH net v3 6/9] selftests: net: py: add a timeout argument to bkg() Rishikesh Jethwani
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 ` [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 [this message]

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261204235642.36653-10-rjethwani@purestorage.com \
    --to=rjethwani@purestorage.com \
    --cc=andrew+netdev@lunn.ch \
    --cc=davem@davemloft.net \
    --cc=edumazet@kernel.org \
    --cc=john.fastabend@gmail.com \
    --cc=kuba@kernel.org \
    --cc=linux-kselftest@vger.kernel.org \
    --cc=netdev@vger.kernel.org \
    --cc=pabeni@redhat.com \
    --cc=sd@queasysnail.net \
    --cc=shuah@kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox