Skip to contentSkip to conversation

tls: device: keep tls_sw_fallback() from encrypting its own output

PATCH In review Rishikesh Jethwani 4 participants 8 messages Nov 19 – Nov 24

Subsystems (5)
lore
Share & tools
lore
#0 lore raw

PATCH v2 1/3 tls: device: keep tls_sw_fallback() from encrypting its own output

With a bond, each skb is validated at both the master and the slave. tls_validate_xmit_skb() skips the master, but tls_validate_xmit_skb_sw(), installed by tls_device_down(), runs tls_sw_fallback() both times. The second pass re-encrypts the ciphertext with the same rcd_sn and IV, cancelling the keystream and putting plaintext on the wire; for a complete record it also computes a valid tag, so the peer accepts it.

Offload plaintext always has the decrypted bit set (tls_push_data() and tls_device_write_space() send with MSG_SENDPAGE_DECRYPTED). Have tls_sw_fallback() pass through skbs without it, and clear the bit in complete_skb() so its output is not encrypted again.

This needs commit fc6d80eb5044 ("tcp: prevent collapsing skbs across boundary in rtx queue"): otherwise a retransmit collapse can merge offloaded data into a pre-offload skb with decrypted = 0, which would now be sent in plaintext rather than dropped.

Tested over a single-slave mlx5 bond, bouncing the slave under an open TLS 1.2 AES-GCM-128 socket.

Fixes c55dcdd435aa ("net/tls: Fix use-after-free after the TLS device goes down and up")
Cc <[email protected]> # 5.13.x: fc6d80eb5044: tcp: prevent collapsing skbs across boundary in rtx queue
---
 net/tls/tls_device_fallback.c | 7 +++++++
 1 file changed, 7 insertions(+)
net/tls/tls_device_fallback.c +7 -0
index b547027cc879..57d8f6b50e4d 100644
@@ -192,6 +192,9 @@ static void complete_skb(struct sk_buff *nskb, struct sk_buff *skb, int headln)
 	skb->destructor = NULL;
 	skb->sk = NULL;
 
+	/* nskb is encrypted now */
+	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;
 
+	/* Already encrypted, e.g. by the bond master */
+	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.
Signature · 1 line
2.50.1
#1 lore raw

PATCH v2 2/3 selftests: net: py: add a bkg() timeout and kill the child when it expires

bkg() waits a fixed 20s for its command on exit and, on timeout, raises with the child still running, outliving the devices and namespaces the test tears down. Add a timeout argument for that wait, and kill the child when it expires before raising TimeoutExpired as before.

---
 tools/testing/selftests/net/lib/py/utils.py | 28 ++++++++++++++++++---
 1 file changed, 24 insertions(+), 4 deletions(-)
tools/testing/selftests/net/lib/py/utils.py +24 -4
index 1727bc418073..7a3fc39db334 100644
@@ -104,13 +104,32 @@ class cmd:
     def _process_terminate(self, terminate, timeout):
         if terminate:
             self.proc.terminate()
-        stdout, stderr = self.proc.communicate(timeout=timeout)
+        timed_out = None
+        try:
+            stdout, stderr = self.proc.communicate(timeout=timeout)
+        except subprocess.TimeoutExpired as exc:
+            # terminate() is only a request, and bkg() with exit_wait or
+            # ksft_wait never sends one, so kill rather than leave the child
+            # running. That does not stop a command run over ssh on the
+            # remote; it needs a bound of its own.
+            self.proc.kill()
+            try:
+                stdout, stderr = self.proc.communicate(timeout=1)
+            except subprocess.TimeoutExpired:
+                # A grandchild (shell=True, ssh) still holds the pipes.
+                self.proc.wait()
+                stdout, stderr = b"", b""
+            timed_out = exc
+
         self.stdout = stdout.decode("utf-8")
         self.stderr = stderr.decode("utf-8")
         self.proc.stdout.close()
         self.proc.stderr.close()
         self.ret = self.proc.returncode
 
+        if timed_out:
+            raise timed_out
+
         return stdout, stderr
 
     def process(self, terminate=True, fail=None, expect_fail=False, timeout=20):
@@ -179,11 +198,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)
+                         ksft_wait=ksft_wait, timeout=timeout)
+        self.timeout = timeout
         self.terminate = not exit_wait and not ksft_wait
         self._exit_wait = exit_wait
         self.check_fail = fail
@@ -203,7 +223,7 @@ class bkg(cmd):
         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)
+                            expect_fail=self.expect_fail, timeout=self.timeout)
 
 
 GLOBAL_DEFER_QUEUE = []
Signature · 1 line
2.50.1
#2 lore raw

Re: [PATCH net v2 2/3] selftests: net: py: add a bkg() timeout and kill the child when it expires

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 2 · Low: 3

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] In tools/testing/selftests/net/lib/py/utils.py, cmd._process_terminate() handles a communicate() timeout by calling…
- [Medium] In cmd._process_terminate(), when the second communicate(timeout=1) times out after self.proc.kill(), the code…
- [Low] The commit message describes a bkg()-only change, but the modified helper cmd._process_terminate() is shared.
- [Low] The new comment in cmd._process_terminate() says "bkg() with exit_wait or ksft_wait never sends one [terminate()]".
- [Low] The new comments in cmd._process_terminate() describe which backends leave processes behind after kill().

--

selftests: net: py: add a bkg() timeout and kill the child when it expires

This adds a timeout argument to bkg() for its exit-time wait. It also changes cmd._process_terminate() so that, when communicate() times out, the child gets SIGKILL before TimeoutExpired is re-raised. The goal is to stop a timed-out background command from outliving the devices and namespaces the test tears down.

Quoted 5 lines
tools/testing/selftests/net/lib/py/utils.py +0 -0
index 1727bc4180733..7a3fc39db3348 100644

tools/testing/selftests/net/lib/py/utils.py class cmd: · line 112

Quoted 10 lines
tools/testing/selftests/net/lib/py/utils.py +6 -1
@@ -104,13 +104,32 @@ class cmd:
     def _process_terminate(self, terminate, timeout):
         if terminate:
             self.proc.terminate()
-        stdout, stderr = self.proc.communicate(timeout=timeout)
+        timed_out = None
+        try:
+            stdout, stderr = self.proc.communicate(timeout=timeout)
+        except subprocess.TimeoutExpired as exc:
+            # terminate() is only a request, and bkg() with exit_wait or
+            # ksft_wait never sends one, so kill rather than leave the child

[Severity: Low]
Is this comment accurate for exit_wait? When the with-body raises and the child is still running, bkg.__exit__() in this same file does send terminate for an exit_wait bkg():

if self.proc.poll() is None:
terminate = terminate or (self._exit_wait and ex_type is not None)

Callers can also call process(terminate=True) on an exit_wait bkg() directly. The next patch in the series does this in run_tls_test() with pending.process(terminate=True, ...).

The statement seems to hold only for ksft_wait, and for exit_wait when no exception is in flight.

tools/testing/selftests/net/lib/py/utils.py class cmd: · line 115

Quoted 3 lines
tools/testing/selftests/net/lib/py/utils.py +3 -0
+            # running. That does not stop a command run over ssh on the
+            # remote; it needs a bound of its own.
+            self.proc.kill()

[Severity: Medium]
Does this kill() reach the process that is actually doing the work? Popen.kill() sends SIGKILL only to the direct child pid. cmd.__init__() creates the Popen without start_new_session or a process group, so the whole tree can't be killed with os.killpg().

In several setups the workload is not the direct child:

remote_ssh.py Remote.cmd():

    return subprocess.Popen(["ssh", "-q", self.name, comm],

Here only the local ssh client is killed, and the remote command keeps running.

remote_netns.py Remote.cmd():

    return subprocess.Popen(["ip", "netns", "exec", self.name, "bash", "-c", comm],

With compound commands (pipelines, ;, &&, or loops such as the for loop in rss_flow_label.py), bash forks children that survive SIGKILL to bash. The same is true of bkg(shell=True) with a compound command.

In these cases the inner except branch below reaps the dead direct child, drops the output and re-raises. The workload is still alive when the caller's defer/teardown runs. Isn't that the same ordering problem the commit message says this patch fixes?

The code comment mentions the ssh case, but the commit message doesn't mention any limitation. Would a complete local fix need start_new_session plus os.killpg()?

tools/testing/selftests/net/lib/py/utils.py class cmd: · line 119

Quoted 4 lines
tools/testing/selftests/net/lib/py/utils.py +4 -0
+            try:
+                stdout, stderr = self.proc.communicate(timeout=1)
+            except subprocess.TimeoutExpired:
+                # A grandchild (shell=True, ssh) still holds the pipes.

[Severity: Low]
Should this comment, and the ssh comment above it, also mention the remote_netns backend? remote_netns.py Remote.cmd() wraps every remote command in ip netns exec <ns> bash -c comm. The forked parts of compound commands can survive kill(), keep the pipes open, and take this same path while the workload keeps running inside the namespace.

tools/testing/selftests/net/lib/py/utils.py class cmd: · line 120

Quoted 1 line
tools/testing/selftests/net/lib/py/utils.py +1 -0
+                self.proc.wait()

[Severity: Medium]
Can this wait() block forever? It has no timeout. The comment assumes that only a grandchild can still hold the pipes here, but the direct child may still be alive too.

SIGKILL doesn't act on a task in uninterruptible sleep until the task leaves that state. Two examples: an ip command blocked in mutex_lock(&rtnl_mutex) while RTNL is held indefinitely, or ip link del stuck in the msleep() loop of netdev_wait_allrefs_any() because of a leaked netdev refcount.

In that case the child still holds its own stdout/stderr, so communicate(timeout=1) times out. wait() then blocks for as long as the task stays in D state.

Before this patch, _process_terminate() always returned or raised TimeoutExpired within timeout. Now the harness hangs instead of reporting a failure. ksft_run can't record the failure, run defer() cleanup, or move on to later cases.

The helper is shared, so this affects foreground cmd() as well as bkg(). Would a bounded wait be safer here?

tools/testing/selftests/net/lib/py/utils.py class cmd: · line 132

Quoted 12 lines
tools/testing/selftests/net/lib/py/utils.py +6 -0
+                stdout, stderr = b"", b""
+            timed_out = exc
+
         self.stdout = stdout.decode("utf-8")
         self.stderr = stderr.decode("utf-8")
         self.proc.stdout.close()
         self.proc.stderr.close()
         self.ret = self.proc.returncode
 
+        if timed_out:
+            raise timed_out
+

[Severity: Low]
The commit message describes a change to bkg() only, but _process_terminate() is shared. Foreground cmd() reaches it through cmd.__init__() when background is False:

if not background:
self.process(terminate=False, fail=fail, expect_fail=expect_fail,
timeout=timeout)

The ksft_ready init-failure path also calls it directly with timeout=1.

With this patch, any foreground cmd() that hits its timeout now gets SIGKILL, and ret/stdout/stderr are filled in before TimeoutExpired is re-raised. Before, the child was left running and those fields stayed None.

No in-tree caller seems to rely on the old behaviour. Could the commit message mention this change?

[ ... ]

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261119191341.4089157-1-rjethwani%40purestorage.com
#3 lore raw

PATCH v2 3/3 selftests: net: add TLS offload over bond tests

In reply to Rishikesh Jethwani

Run the kTLS HW offload echo test over a single-slave balance-xor bond with xmit_hash_policy layer3+4, which maps each socket to a fixed slave and so lets it offload, without needing an LACP partner. The bond takes over the NIC's MAC and addresses, so the peer sees no change.

test_tls_offload_bond checks that the slave did the offload.

test_tls_offload_bond_bounce takes the slave down while the client is paused halfway, moving the socket to the TX SW fallback, which over a bond runs at both master and slave and must encrypt only once. "idle" brings the slave back before the client resumes; "inflight" keeps it down until after, so the first record on resume goes out on retransmit.

Enslaving or bouncing the slave makes the NIC retrain for seconds, so the cases wait for carrier and peer reachability before starting the helpers. The helper gains -P to pause the client via ksft_ready() and ksft_wait(), and -T to widen its timeouts to cover the retraining.

Tested on a pair of mlx5 hosts: the bond cases pass, and both bounce cases report an echo mismatch without the fix.

---
 tools/testing/selftests/drivers/net/hw/config |   1 +
 .../selftests/drivers/net/hw/tls_hw_offload.c |  57 ++++-
 .../drivers/net/hw/tls_hw_offload.py          | 203 +++++++++++++++++-
 3 files changed, 247 insertions(+), 14 deletions(-)
tools/testing/selftests/drivers/net/hw/config +1 -0
index 081155bf7847..ee658188670a 100644
@@ -1,3 +1,4 @@
+CONFIG_BONDING=y
 CONFIG_BPF_SYSCALL=y
 CONFIG_FAIL_FUNCTION=y
 CONFIG_FAULT_INJECTION=y
tools/testing/selftests/drivers/net/hw/tls_hw_offload.c +48 -9

125 lines not on this page · raw message

tools/testing/selftests/drivers/net/hw/tls_hw_offload.py +198 -5

273 lines not on this page · raw message

Signature · 1 line
2.50.1
#4 lore raw

Re: [PATCH net v2 3/3] selftests: net: add TLS offload over bond tests

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 2 · Low: 2

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] In tools/testing/selftests/drivers/net/hw/tls_hw_offload.py, bounce_idle() (lines 458-462) runs ip link set dev <slave> down,…
- [Medium] test_tls_offload_bond_bounce takes the slave NIC administratively down and up (bounce_idle()/bounce_inflight() at…
- [Low] The -T help line in print_usage() (tools/testing/selftests/drivers/net/hw/tls_hw_offload.c:769) reads…
- [Low] selftests: net: setup_bond() runs before IPv4 check in bond offload tests

--

selftests: net: add TLS offload over bond tests

This adds kTLS HW offload tests that run the echo test over a single-slave balance-xor bond. It also adds tests that bounce the slave under an open offloaded socket, in idle and inflight variants. The C helper gains -P to pause the client halfway and -T to widen its I/O timeouts and SIGALRM lifetime.

Quoted 4 lines
tools/testing/selftests/drivers/net/hw/tls_hw_offload.c +0 -0
index 5b3887f32b689..0be321866a978 100644

[ ... ]

tools/testing/selftests/drivers/net/hw/tls_hw_offload.c static void print_usage(const char *prog) · line 770

Quoted 7 lines
tools/testing/selftests/drivers/net/hw/tls_hw_offload.c +3 -0
@@ -751,6 +765,9 @@ 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 and lifetime bound (default: %d)\n",
+	       IO_TIMEOUT_S);

[Severity: Low]
This isn't a bug, but does this help text match what -T does?

Without -T, the SIGALRM lifetime is HELPER_TIMEOUT_S (15), not 8. With -T N, main() sets:

	helper_timeout_s = 2 * io_timeout_s + 15;

and passes that to alarm(). So <sec> sets the send/recv timeout, and the lifetime bound is derived from it rather than equal to it.

[ ... ]

Quoted 4 lines
tools/testing/selftests/drivers/net/hw/tls_hw_offload.py +0 -0
index e720ce6547610..345d5fd9a5e95 100755

[ ... ]

Quoted 1 line
tools/testing/selftests/drivers/net/hw/tls_hw_offload.py +0 -0
@@ -305,6 +358,145 @@ def test_tls_offload_record_type(cfg, record_type):

[ ... ]

Quoted 2 lines
tools/testing/selftests/drivers/net/hw/tls_hw_offload.py +2 -0
+    ip(f"link add {BOND_IFNAME} address {mac} mtu {mtu} type bond "
+       "mode balance-xor xmit_hash_policy layer3+4 miimon 100")

[ ... ]

Quoted 5 lines
tools/testing/selftests/drivers/net/hw/tls_hw_offload.py +5 -0
+    wait_carrier(cfg.ifname)
+    wait_carrier(BOND_IFNAME)
+
+    for peer in filter(None, cfg.remote_addr_v.values()):
+        wait_reachable(BOND_IFNAME, peer)

[ ... ]

tools/testing/selftests/drivers/net/hw/tls_hw_offload.py def test_tls_offload_record_type(cfg, record_type): · line 462

Quoted 5 lines
tools/testing/selftests/drivers/net/hw/tls_hw_offload.py +5 -0
+def bounce_idle(cfg):
+    """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_carrier(BOND_IFNAME)

[Severity: Medium]
Can wait_carrier(BOND_IFNAME) return here before the slave is actually back?

For a slave going down or up, bond_slave_netdev_event() only refreshes the slave array. It does not change the master's carrier:

drivers/net/bonding/bond_main.c:bond_slave_netdev_event() {
    ...
	case NETDEV_DOWN:
		...
		if (bond_mode_can_use_xmit_hash(bond))
			bond_update_slave_arr(bond, NULL);
		break;
    ...
}

For a running balance-xor bond, bond_set_carrier() is only reached through bond_mii_monitor()->bond_miimon_commit(). That runs every 100ms here (miimon 100), and it is deferred again whenever rtnl_trylock() fails while the ip commands hold RTNL.

So /sys/class/net/tlsbond0/carrier can still read the 1 from before the bounce. In that case the wait returns at once, while the NIC is still retraining.

The resumed records would then reach a slave with no carrier and go out on retransmit. That is the inflight scenario, so the idle variant may not reliably cover the "slave back before the client resumes" case.

setup_bond() waits on wait_carrier(cfg.ifname), then on the bond carrier, then on wait_reachable() for each peer. Should bounce_idle() use the same sequence?

[ ... ]

Quoted 6 lines

+@ksft_variants([

tools/testing/selftests/drivers/net/hw/tls_hw_offload.py +5 -0
+    KsftNamedVariant("idle", bounce_idle),
+    KsftNamedVariant("inflight", bounce_inflight),
+])
+@ksft_disruptive
+def test_tls_offload_bond_bounce(cfg, bounce):

[ ... ]

tools/testing/selftests/drivers/net/hw/tls_hw_offload.py def test_tls_offload_record_type(cfg, record_type): · line 497

Quoted 3 lines
tools/testing/selftests/drivers/net/hw/tls_hw_offload.py +3 -0
+    require_tls_setup(cfg)
+    setup_bond(cfg)
+    run_tls_test(cfg, pause=bounce)

[Severity: Low]
Does setup_bond() run too early for an IPv6-only environment?

run_tls_test() is called here with the default ipver="4", and it only checks cfg.require_ipver(ipver) after setup_bond() has returned.

On a NetDrvEpEnv with only IPv6 addresses, setup_bond() still does all of its work first. It moves the global addresses to tlsbond0, takes cfg.ifname down, enslaves it, and waits for carrier and for ping reachability of the IPv6 peer.

Only then does run_tls_test() raise KsftSkipEx. The deferred cleanup then deletes the bond, and restore_nic() brings the NIC up again, which flaps the link a second time.

test_tls_offload_bond_bounce() has the same ordering. So each of the four bond variants retrains the NIC twice only to report a skip.

Would it make sense to call cfg.require_ipver("4") before setup_bond() in both tests? Alternatively, setup_bond() could take the ipver the case is going to run with.

[Severity: Medium]
Could the NIC packet count check fail in both bounce variants on drivers that keep their TLS stats in per-queue state?

The slave is taken down and up between the nic_before and nic_after snapshots in run_tls_test(), which runs the driver's ndo_stop/ndo_open. check_hw_crypto() then requires:

got = stat_diff(nic_before, nic_after, key) ksft_ge(got, 1,
comment=f"DUT {direction}: NIC reported no TLS "
f"offload packets ({key}={got})")

On funeth, which the HW_NIC_COUNTERS comment lists, fun_get_ethtool_stats() builds tx_tls_encrypted_packets by summing the live fp->txqs[i]->stats.

funeth_close()->fun_down() with FUN_QSTATE_DESTROYED frees the TX queues in fun_free_rings(). funeth_open() then allocates new zeroed queues through kzalloc_node() in fun_txq_create_sw(). The counter therefore restarts at 0 after the bounce.

NETDEV_DOWN also moves the socket to the TX SW fallback through tls_device_down(), so nothing goes through the HW path after resume. nic_before is also around 0, because setup_bond() has just recreated the queues.

As a result, got ends up 0, and the case reports "NIC reported no TLS offload packets" even with a correct kernel fix.

tx_tls_ctx (fp->tx_tls_add) survives close/open, so only the packet count check seems to be affected. The bounce cases were only tested on mlx5, which keeps its counters across close/open.

Should the bounce cases relax or skip the packet count check?

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261119191341.4089157-1-rjethwani%40purestorage.com
#5 lore raw
In reply to Rishikesh Jethwani
This is an automated message. This series looks like a fix, but its commit messages seem to be missing some information:

Hi!

This is an automated message. This series looks like a fix, but its commit messages seem to be missing some information:

- How the issue was discovered, e.g. hit in production, hit during development, syzbot report, manual code inspection, LLM or static analysis tool scan.

Please do not repost the series just to address the above. Instead, reply to this email with the missing information, so that reviewers can take it into account.

*IMPORTANT*: If you do repost (for other reasons) - please include the relevant info in the cover letter or commit messages.

Signature · 2 lines
The evaluation is done by an LLM so it may be wrong, if you think
that is the case please reply and explain.
#6 lore raw
In reply to Rishikesh Jethwani
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.

Critical: 0 · High: 1 · Medium: 0 · Low: 1

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [High] The patch makes skb->decrypted the marker for 'still needs TLS encryption': tls_sw_fallback() now skips skbs with…
- [Low] The new early return in tls_sw_fallback() (net/tls/tls_device_fallback.c:377-379, '/* Already encrypted, e.g. by…

--

tls: device: keep tls_sw_fallback() from encrypting its own output

This patch makes tls_sw_fallback() pass through skbs that do not have the decrypted bit set, and clears that bit on the output of complete_skb(). The aim is to keep a second software fallback pass (for example at the bond master and then again at the slave) from re-encrypting ciphertext with the same rcd_sn and IV.

net/tls/tls_device_fallback.c static void complete_skb(struct sk_buff *nskb, struct sk_buff *skb, int headln) · line 197

Quoted 11 lines
net/tls/tls_device_fallback.c +3 -0
index b547027cc879f..57d8f6b50e4dd 100644
@@ -192,6 +192,9 @@ static void complete_skb(struct sk_buff *nskb, struct sk_buff *skb, int headln)
 	skb->destructor = NULL;
 	skb->sk = NULL;
 
+	/* nskb is encrypted now */
+	nskb->decrypted = 0;
+

[Severity: High]
Does this also cover the hardware offload path?

complete_skb() keeps nskb->sk = sk. The driver side check for hardware encryption does not look at skb->decrypted:

include/net/tls.h:tls_is_skb_tx_device_offloaded() {
	...
	return sk && sk_fullsock(sk) &&
	       (smp_load_acquire(&sk->sk_validate_xmit_skb) ==
	       &tls_validate_xmit_skb);
}

So drivers still treat software fallback ciphertext as offloaded.

Take a TLS_HW socket offloaded on mlx5 eth0 whose route later moves to vlan@eth0:

vlan@eth0:
tls_validate_xmit_skb()

    dev != netdev, not a bond master
    tls_sw_fallback()->complete_skb()    /* ciphertext, decrypted = 0 */

vlan_dev_hard_start_xmit()
dev_queue_xmit(eth0)

eth0:
tls_validate_xmit_skb()

    dev == netdev, skb returned unchanged
  mlx5e_accel_tx_begin()
    tls_is_skb_tx_device_offloaded() returns true
    mlx5e_ktls_handle_tx_skb()
      state->tls_tisn = priv_tx->tisn;   /* in-order seq */

In that case, would the NIC encrypt the software ciphertext a second time with the same record keystream and put plaintext on the wire?

mlx5e_ktls_handle_tx_skb() only checks skb->decrypted in the MLX5E_KTLS_SYNC_SKIP_NO_DATA branch. nfp_net_tls_tx() also decides only through tls_is_skb_tx_device_offloaded(), and it attaches ntls->fw_handle when ntls->next_seq == seq.

This path existed before this patch. However, the commit message says the bit is cleared "so its output is not encrypted again", and that doesn't seem to hold for the hardware path.

Should tls_is_skb_tx_device_offloaded() also require skb_is_decrypted(skb) so that it follows the same rule?

[ ... ]

net/tls/tls_device_fallback.c static struct sk_buff *tls_sw_fallback(struct sock *sk, struct sk_buff *skb) · line 380

Quoted 8 lines
net/tls/tls_device_fallback.c +4 -0
@@ -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;
 
+	/* Already encrypted, e.g. by the bond master */
+	if (!skb_is_decrypted(skb))
+		return skb;
+

[Severity: Low]
This isn't a bug, but is this comment accurate for every skb that takes this return?

Data written before setsockopt(TLS_TX) also has decrypted = 0, because tcp_sendmsg_locked() does:

	skb->decrypted = !!(flags & MSG_SENDPAGE_DECRYPTED);

Only tls_push_data() and tls_device_write_space() pass that flag, so that data was never encrypted by kTLS.

Also, the existing bypass further down in tls_sw_fallback() no longer seems reachable for the packets it describes:

	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);
		goto put_sg;
	}

Three things make it unreachable for those packets:

- Only decrypted = 1 skbs reach fill_sg_in() now.
- Those skbs are created after the start marker set in tls_set_device_offload().
- tcp_skb_can_collapse() refuses merges across a decrypted mismatch.

Should the new comment also mention pre-offload plaintext? And should the start marker bypass, along with the matching start marker handling in fill_sg_in(), be updated or removed?

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261119191341.4089157-1-rjethwani%40purestorage.com
#7 lore raw
Quoted 127 lines · On Mon, Nov 23, 2026 at 12:39 PM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.

Critical: 0 · High: 1 · Medium: 0 · Low: 1

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [High] The patch makes skb->decrypted the marker for 'still needs TLS encryption': tls_sw_fallback() now skips skbs with…
- [Low] The new early return in tls_sw_fallback() (net/tls/tls_device_fallback.c:377-379, '/* Already encrypted, e.g. by…

--

tls: device: keep tls_sw_fallback() from encrypting its own output

This patch makes tls_sw_fallback() pass through skbs that do not have the decrypted bit set, and clears that bit on the output of complete_skb(). The aim is to keep a second software fallback pass (for example at the bond master and then again at the slave) from re-encrypting ciphertext with the same rcd_sn and IV.

net/tls/tls_device_fallback.c static void complete_skb(struct sk_buff *nskb, struct sk_buff *skb, int headln) · line 197

Quoted 11 lines
net/tls/tls_device_fallback.c +3 -0
index b547027cc879f..57d8f6b50e4dd 100644
@@ -192,6 +192,9 @@ static void complete_skb(struct sk_buff *nskb, struct sk_buff *skb, int headln)
      skb->destructor = NULL;
      skb->sk = NULL;
 
+     /* nskb is encrypted now */
+     nskb->decrypted = 0;
+

[Severity: High]
Does this also cover the hardware offload path?

complete_skb() keeps nskb->sk = sk. The driver side check for hardware encryption does not look at skb->decrypted:

include/net/tls.h:tls_is_skb_tx_device_offloaded() {
        ...
        return sk && sk_fullsock(sk) &&
               (smp_load_acquire(&sk->sk_validate_xmit_skb) ==
               &tls_validate_xmit_skb);
}

So drivers still treat software fallback ciphertext as offloaded.

Take a TLS_HW socket offloaded on mlx5 eth0 whose route later moves to vlan@eth0:

vlan@eth0:
tls_validate_xmit_skb()

    dev != netdev, not a bond master
    tls_sw_fallback()->complete_skb()    /* ciphertext, decrypted = 0 */

vlan_dev_hard_start_xmit()
dev_queue_xmit(eth0)

eth0:
tls_validate_xmit_skb()

    dev == netdev, skb returned unchanged
  mlx5e_accel_tx_begin()
    tls_is_skb_tx_device_offloaded() returns true
    mlx5e_ktls_handle_tx_skb()
      state->tls_tisn = priv_tx->tisn;   /* in-order seq */

In that case, would the NIC encrypt the software ciphertext a second time with the same record keystream and put plaintext on the wire?

mlx5e_ktls_handle_tx_skb() only checks skb->decrypted in the MLX5E_KTLS_SYNC_SKIP_NO_DATA branch. nfp_net_tls_tx() also decides only through tls_is_skb_tx_device_offloaded(), and it attaches ntls->fw_handle when ntls->next_seq == seq.

This path existed before this patch. However, the commit message says the bit is cleared "so its output is not encrypted again", and that doesn't seem to hold for the hardware path.

Should tls_is_skb_tx_device_offloaded() also require skb_is_decrypted(skb) so that it follows the same rule?

[ ... ]

net/tls/tls_device_fallback.c static struct sk_buff *tls_sw_fallback(struct sock *sk, struct sk_buff *skb) · line 380

Quoted 8 lines
net/tls/tls_device_fallback.c +4 -0
@@ -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;
 
+     /* Already encrypted, e.g. by the bond master */
+     if (!skb_is_decrypted(skb))
+             return skb;
+

[Severity: Low]
This isn't a bug, but is this comment accurate for every skb that takes this return?

Data written before setsockopt(TLS_TX) also has decrypted = 0, because tcp_sendmsg_locked() does:

        skb->decrypted = !!(flags & MSG_SENDPAGE_DECRYPTED);

Only tls_push_data() and tls_device_write_space() pass that flag, so that data was never encrypted by kTLS.

Also, the existing bypass further down in tls_sw_fallback() no longer seems reachable for the packets it describes:

        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);
                goto put_sg;
        }

Three things make it unreachable for those packets:

- Only decrypted = 1 skbs reach fill_sg_in() now.
- Those skbs are created after the start marker set in tls_set_device_offload().
- tcp_skb_can_collapse() refuses merges across a decrypted mismatch.

Quoted 6 lines

Should the new comment also mention pre-offload plaintext? And should the start marker bypass, along with the matching start marker handling in fill_sg_in(), be updated or removed?

--
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261119191341.4089157-1-rjethwani%40purestorage.com

pw-bot: cr