Skip to contentSkip to conversation

pull request (net): ipsec 2026-12-01

PATCH New Steffen Klassert 2 participants 25 messages Dec 1

Subsystems (6)
lore
Share & tools
lore

Steffen Klassert

author maintainer
#0 lore raw

cover pull request (net): ipsec 2026-12-01

1) xfrm: ipcomp: account full fragment pages in truesize Charge the decompressed IPComp skb a page-rounded truesize, so the socket memory accounting matches the pages actually attached.

2) xfrm: esp: reset outer TCP GSO metadata on espintcp input Reset the GSO state inherited from the outer TCP stream on ESP-in-TCP input, so a decrypted packet isn't segmented with stale metadata and multi-segment records no longer crash.

3) xfrm: keep the mode module pinned until destroy_state returns Hold an extra module reference across the state destroy callback, so an rmmod racing the state GC can't free the module text while the callback is still running.

4) xfrm: serialize SA activation with state deletion Take the state lock for the final VOID-to-VALID transition, so a hard expiry can't delete the state in between and leave it in the per-CPU cache.

5) xfrm: keep old state references until migration deletion completes Delete the old states before dropping their lookup references, so a concurrent expiry can't free a state the migration still uses.

6) xfrm: hold migrated states through rollback
Keep a caller reference on the successor states and delete them before releasing it, so a failed migration can't touch a state that has already been reclaimed.

7) xfrm: check inner family via skb_dst for small_ipv6 DF clearing Take the inner address family from the dst instead of skb->protocol, so the outer DF bit is cleared for small IPv6 packets and the tunnel doesn't drop them.

8) xfrm: account XFRMA_MARK in xfrm_sa_len()
Count the mark attribute in the SA message length, so the netlink SA notifications are sized correctly.

9) xfrm: replay: Fix late packet handling with ESN crypto offload Drop packets far ahead of the replay window when the ICV check runs in hardware, so a late packet can't corrupt the offloaded ESN state.

10) xfrm: fix IPv6 first-fragment protocol decode
Let the flow dissector walk past an IPv6 fragment header, so the inbound policy lookup sees the real upper-layer protocol.

11) xfrm: fix selector matching for IPv6 atomic fragments Restore the port and protocol selector fields for atomic IPv6 fragments, so such packets can match a policy.

12) xfrm: espintcp: read the socket error queue for MSG_ERRQUEUE Read the error queue through the socket error path, so a queued timestamp is reported instead of being consumed as an IKE message.

13) xfrm: iptfs: force a dst reference before queueing an skb Take a dst reference while the packet is still under RCU, so the deferred IPTFS output doesn't use a dst that may already be gone.

14) xfrm: espintcp: select receive path by skb protocol Pick the receive path from the packet protocol instead of the socket family, so an IPv4 packet on a v4-mapped socket isn't parsed by the IPv6 path.

15) net: xfrm: interface: restore dst_orig on every xfrm interface Restore the original route in both arms of the interface xmit path, so a steered packet finds a policy and the metadata dst is left untouched.

16) xfrm: iptfs: make room before copying a continuation in reassembly Grow the skb head before copying a reassembly continuation, so a larger continuation doesn't overrun the buffer and panic.

17) xfrm/compat: pass on the translated length of a socket policy Pass the translated policy length to the 32-bit compat layer, so the last template isn't dropped and an ESP-required policy doesn't fall back to clear text.

18) xfrm: Give GC list nodes their own storage
Give the GC and hash list nodes separate storage, so adding a state to the GC list can't corrupt the hash linkage that RCU readers still follow.

19) xfrm: Serialize device state teardown
Let only one caller free the device state and hold a reference in the flush, so the state GC and a device flush can't free the same state.

20) xfrm: Wait for an RCU grace period before freeing device state Wait for an RCU grace period after collecting the device states, so the driver state isn't freed while readers are still using it.

21) Revert "xfrm: serialize state GC with device state flush" Revert the GC and flush mutex, since the reference handling and the single-free rule make it unnecessary and it can't cover the lookup path.

22) xfrm: Serialize offload stats updates with x->lock Serialize the offload stats refresh with the state lock, so the counters aren't updated twice and a dump doesn't copy them while they change.

Please pull or let me know if there are problems.

Thanks!

The following changes since commit 787268686c64be60023743b527645a907e38ccca:

ipmr, ip6mr: queue netlink route queries out of band (2026-11-03 22:30:55 +0100)

are available in the Git repository at:

git://git.kernel.org/pub/scm/linux/kernel/git/klassert/ipsec.git tags/ipsec-2026-12-01

for you to fetch changes up to bb65a0da99bf4861dce01149ba64e875e47ae5a3:

xfrm: Serialize offload stats updates with x->lock (2026-11-30 11:36:34 +0100)

----------------------------------------------------------------
ipsec-2026-12-01

----------------------------------------------------------------
Andrii Tereshchenko (2):
xfrm: iptfs: make room before copying a continuation in reassembly xfrm/compat: pass on the translated length of a socket policy

Baek Kyu, Kim (1):
xfrm: espintcp: read the socket error queue for MSG_ERRQUEUE

Cen Zhang (3):
xfrm: keep the mode module pinned until destroy_state returns
xfrm: keep old state references until migration deletion completes
xfrm: hold migrated states through rollback

Cosmin Ratiu (1):
xfrm: replay: Fix late packet handling with ESN crypto offload

Guoshuai Yang (1):
xfrm: esp: reset outer TCP GSO metadata on espintcp input

Jamal Hadi Salim (1):
net: xfrm: interface: restore dst_orig on every xfrm interface

Jianbo Liu (5):
xfrm: Give GC list nodes their own storage
xfrm: Serialize device state teardown
xfrm: Wait for an RCU grace period before freeing device state Revert "xfrm: serialize state GC with device state flush"
xfrm: Serialize offload stats updates with x->lock

Jérémy Jean (2):
xfrm: fix IPv6 first-fragment protocol decode
xfrm: fix selector matching for IPv6 atomic fragments

Kyle Zeng (1):
xfrm: serialize SA activation with state deletion

Nguyen Ngoc Thang (1):
xfrm: iptfs: force a dst reference before queueing an skb

Sewook Seo (1):
xfrm: check inner family via skb_dst for small_ipv6 DF clearing

Yasuaki Torimaru (1):
xfrm: account XFRMA_MARK in xfrm_sa_len()

Zhiling Zou (1):
xfrm: ipcomp: account full fragment pages in truesize

Zihan Xi (1):
xfrm: espintcp: select receive path by skb protocol

 include/net/esp.h              |  51 +++++++++++++
 include/net/ipv6.h             |   1 +
 include/net/xfrm.h             |  26 ++++---
 net/core/filter.c              |   8 --
 net/ipv4/esp4.c                |   9 +++
 net/ipv6/esp6.c                |   9 +++
 net/ipv6/exthdrs_core.c        |  25 ++++---
 net/xfrm/espintcp.c            |   5 +-
 net/xfrm/xfrm_compat.c         |  18 ++++-
 net/xfrm/xfrm_device.c         |   4 +-
 net/xfrm/xfrm_interface_bpf.c  |  19 ++---
 net/xfrm/xfrm_interface_core.c |  22 +++---
 net/xfrm/xfrm_ipcomp.c         |   2 +-
 net/xfrm/xfrm_iptfs.c          |  17 ++++-
 net/xfrm/xfrm_output.c         |   5 +-
 net/xfrm/xfrm_policy.c         |  61 +++++++++++----
 net/xfrm/xfrm_replay.c         |  14 +++-
 net/xfrm/xfrm_state.c          | 164 ++++++++++++++++++++++++++++++++---------
 net/xfrm/xfrm_user.c           |  50 +++++++++++--
 19 files changed, 395 insertions(+), 115 deletions(-)
author maintainer
#1 lore raw

PATCH 1/22 xfrm: ipcomp: account full fragment pages in truesize

From: Zhiling Zou <[email protected]>

ipcomp_post_acomp() allocates order-0 pages for decompressed skb fragments, but on input charges truesize by the decompressed byte count. When the output ends partway through a page, the unused tail of its final page is not accounted to the receiving socket. Repeated IPComp packets can therefore retain more memory than the socket receive-memory limits charge.

Round the decompressed length up to page size when charging input skb truesize, matching the pages attached to the skb. Leave output accounting unchanged.

Fixes 7d7e5a60c62e ("ipsec: ipcomp - Decompress into frags if necessary")
Assisted-by LLM
---
 net/xfrm/xfrm_ipcomp.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/xfrm/xfrm_ipcomp.c +1 -1
index 671d48f8c937..c2cc88c8c360 100644
@@ -67,7 +67,7 @@ static int ipcomp_post_acomp(struct sk_buff *skb, int err, int hlen)
 
 	/* Only update truesize on input. */
 	if (!hlen)
-		skb->truesize += dlen;
+		skb->truesize += PAGE_ALIGN(dlen);
 	skb->data_len = dlen;
 	skb->len += dlen;
 
Signature · 1 line
2.53.0
#2 lore raw

Re: [PATCH 01/22] xfrm: ipcomp: account full fragment pages in truesize

TL;DR: In ipcomp_post_acomp(), the truesize increase may unbalance the sender's sk_wmem_alloc for skbs arriving via veth and ESP GRO, possibly underflowing it or freeing the socket early; the patch…
Quoted 1 line

xfrm: ipcomp: account full fragment pages in truesize

TL;DR: In ipcomp_post_acomp(), the truesize increase may unbalance the sender's sk_wmem_alloc for skbs arriving via veth and ESP GRO, possibly underflowing it or freeing the socket early; the patch enlarges an existing mismatch.

Quoted 3 lines
net/xfrm/xfrm_ipcomp.c +0 -0

[ ... ]

net/xfrm/xfrm_ipcomp.c static int ipcomp_post_acomp(struct sk_buff *skb, int err, int hlen) · line 72

Quoted 8 lines
net/xfrm/xfrm_ipcomp.c +1 -1
@@ -67,7 +67,7 @@ static int ipcomp_post_acomp(struct sk_buff *skb, int err, int hlen)
 
 	/* Only update truesize on input. */
 	if (!hlen)
-		skb->truesize += dlen;
+		skb->truesize += PAGE_ALIGN(dlen);
 	skb->data_len = dlen;
 	skb->len += dlen;

Can this truesize write unbalance sk_wmem_alloc of the sending socket when the skb arrives through the ESP GRO path?

The input branch assumes the skb is not charged to any socket. On the ordinary xfrm4_rcv()/xfrm6_rcv() path the skb was already orphaned in ip_rcv_core()/ip6_rcv_core(), so that holds.

But a local UDP or raw sender's skb carries the sock_wfree destructor, and the following path keeps it:

veth_xmit()
veth_skb_is_eligible_for_gro() accepts skb->destructor == sock_wfree __dev_forward_skb() -> skb_scrub_packet() does not orphan
veth_xdp_rcv_skb()
skb_prepare_for_gro() only orphans when destructor != sock_wfree napi_gro_receive()

    inet_gro_receive() -> esp4_gro_receive() -> xfrm_input()
      ipcomp_input() -> ipcomp_decompress() -> ipcomp_input_done2()
        ipcomp_post_acomp(skb, err, 0)
          skb->truesize += PAGE_ALIGN(dlen);

The skb is still charged to the sender at that point. Later ip_rcv_core() calls skb_orphan(), and sock_wfree() subtracts the inflated skb->truesize from sk_wmem_alloc, which was only charged with the original value.

Each such packet over-subtracts PAGE_ALIGN(dlen) from the sender's sk_wmem_alloc, which can underflow the refcount or drop it to zero early and run __sk_free() while the socket is still in use.

The same hazard existed with the old "+= dlen", but this patch enlarges the mismatch by up to PAGE_SIZE - 1 per packet (about 64K on 64K-page kernels).

pskb_expand_head() guards this kind of change:

	if (!skb->sk || skb->destructor == sock_edemux)
		skb->truesize += size - osize;

Would gating the input adjustment the same way keep the receive-side fix without touching a sender's wmem charge?

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/46652847109

author maintainer
#3 lore raw

PATCH 2/22 xfrm: esp: reset outer TCP GSO metadata on espintcp input

In reply to Steffen Klassert

From: Guoshuai Yang <[email protected]>

When ESP packets are received over TCP (RFC 8229 espintcp), strparser slices individual length-prefixed ESP records from the outer TCP stream by cloning the incoming TCP skb(s) in __strp_recv().

If the outer TCP skb was GRO-coalesced before reaching strparser, its skb_shinfo carries the outer TCP stream's GSO metadata (gso_size, gso_segs, and gso_type). When an ESP record spans two outer TCP segments, strparser chains the spillover clone onto skb_shinfo(head)->frag_list.

Subsequently in esp_input() and esp6_input(), skb_cow_data() unshares the head skb via pskb_expand_head() (preserving the outer TCP gso_size and gso_type in the new private skb_shinfo) and calls skb_copy() on each cloned frag_list member, which copies the outer TCP GSO fields via skb_copy_header() onto a linear frag_list child skb allocated from slab with head_frag == 0.

Furthermore, on kernels with TCP fraglist GRO support, if an outer TCP GRO aggregate carrying SKB_GSO_FRAGLIST reaches the espintcp socket unsegmented (for example, when rx-gro-list is enabled on a device in an outer netns where tcp4/6_check_fraglist_gro() finds no local socket and the aggregate is forwarded across a NETIF_F_GSO_FRAGLIST-capable veth device into the netns hosting the espintcp socket) and is chained onto skb_shinfo(head)->frag_list by __strp_recv(), skb_cow_data() invokes skb_copy() / skb_copy_expand() on that frag_list member and hits WARN_ON_ONCE(skb_shinfo(skb)->gso_type & SKB_GSO_FRAGLIST), failing with -ENOMEM before decryption even begins. (On older stable trees without TCP fraglist GRO, the pre-pass is a no-op.)

After ESP decryption and header removal, the resulting single inner packet still has skb_is_gso(skb) == true with the stale outer TCP gso_size, while skb_headlen(head_skb) is now smaller than that gso_size due to stripping the outer framing and ESP header. When this packet passes through gro_cells_receive() (which flushes frag_list packets via GRO_NORMAL without resetting gso_size) and is forwarded, validate_xmit_skb() invokes tcp_gso_segment() -> skb_segment(). Because head_skb is shorter than the stale gso_size and SKB_GSO_DODGY is not set, skb_segment() attempts to map the slab-backed frag_list member as a scatter-gather page fragment where list_skb->head_frag == 0. On current mainline kernels, skb_segment() triggers DEBUG_NET_WARN_ON_ONCE(1) and fails with -EINVAL, causing validate_xmit_skb() to drop all multi-segment espintcp packets. On stable kernels prior to the removal of BUG_ON(!list_skb->head_frag) in skb_segment() (such as 6.12.94 where this trace was captured), it crashes the kernel:

  Internal error: Oops - undefined instruction: 0 [#1] SMP ARM
  PC is at skb_segment+0x574/0xd20
  LR is at skb_segment+0x884/0xd20
  Call trace:
   skb_segment from tcp_gso_segment
   tcp_gso_segment from inet_gso_segment
   inet_gso_segment from skb_mac_gso_segment
   skb_mac_gso_segment from __skb_gso_segment
   __skb_gso_segment from validate_xmit_skb
   validate_xmit_skb from __dev_queue_xmit
   __dev_queue_xmit from ip_finish_output2
   ip_finish_output2 from ip_output
   ip_output from ip_sublist_rcv_finish
   ip_sublist_rcv_finish from ip_sublist_rcv
   ip_list_rcv from __netif_receive_skb_list_core
   __netif_receive_skb_list_core from __netif_receive_skb_list
   __netif_receive_skb_list from gro_normal_list
   gro_normal_list from gro_cell_poll

Similarly, if a decrypted inner packet with a frag_list later takes the ip_do_fragment() frag_list fast path, each detached frag_list member is transmitted as a standalone IP fragment and would still carry the stale outer TCP GSO state when reaching validate_xmit_skb(). And even when an ESP record does not have a frag_list, leaving the stale outer TCP gso_size on the decrypted inner skb prevents dev_gro_receive() from initializing gso_size to the inner packet's skb_gro_len().

We cannot reset GSO state earlier in espintcp_rcv() / handle_esp() because the skb may still be a clone sharing skb_shinfo with the outer TCP skb held by strparser. Instead, in esp_input() and esp6_input():
1. Prior to skb_cow_data(), unshare/unclone and reset GSO metadata on any frag_list member carrying SKB_GSO_FRAGLIST (unsharing any shared predecessor frag_list members along the walk) so skb_copy() / skb_copy_expand() inside skb_cow_data() does not hit WARN_ON_ONCE() and drop the packet.
2. At skip_cow, where the head skb and all frag_list members are guaranteed to be uncloned with private skb_shinfo, call skb_gso_reset() on both the head skb and each skb_walk_frags() member.

Fixes e27cca96cd68 ("xfrm: add espintcp (RFC 8229)")
---
 include/net/esp.h | 51 +++++++++++++++++++++++++++++++++++++++++++++++
 net/ipv4/esp4.c   |  9 +++++++++
 net/ipv6/esp6.c   |  9 +++++++++
 3 files changed, 69 insertions(+)
include/net/esp.h +51 -0
index 322950727dd0..83c75ef59482 100644
@@ -28,6 +28,57 @@ static inline void esp_output_fill_trailer(u8 *tail, int tfclen, int plen, __u8
 	tail[plen - 1] = proto;
 }
 
+static inline int esp_reset_espintcp_fraglist_gso(struct sk_buff *skb)
+{
+	struct sk_buff **fragp;
+	struct sk_buff *frag;
+
+	skb_walk_frags(skb, frag) {
+		if (skb_shinfo(frag)->gso_type & SKB_GSO_FRAGLIST)
+			break;
+	}
+	if (!frag)
+		return 0;
+
+	if (skb_unclone(skb, GFP_ATOMIC))
+		return -ENOMEM;
+
+	for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
+	     fragp = &frag->next) {
+		if (skb_shared(frag)) {
+			struct sk_buff *nfrag;
+
+			nfrag = skb_clone(frag, GFP_ATOMIC);
+			if (!nfrag)
+				return -ENOMEM;
+
+			nfrag->next = frag->next;
+			consume_skb(frag);
+			frag = nfrag;
+			*fragp = frag;
+		}
+
+		if (!(skb_shinfo(frag)->gso_type & SKB_GSO_FRAGLIST))
+			continue;
+
+		if (skb_unclone(frag, GFP_ATOMIC))
+			return -ENOMEM;
+
+		skb_gso_reset(frag);
+	}
+
+	return 0;
+}
+
+static inline void esp_reset_espintcp_gso(struct sk_buff *skb)
+{
+	struct sk_buff *iter;
+
+	skb_gso_reset(skb);
+	skb_walk_frags(skb, iter)
+		skb_gso_reset(iter);
+}
+
 struct esp_info {
 	struct	ip_esp_hdr *esph;
 	__be64	seqno;
net/ipv4/esp4.c +9 -0
index ae701561d9f1..111bea0bd260 100644
@@ -893,6 +893,12 @@ static int esp_input(struct xfrm_state *x, struct sk_buff *skb)
 		}
 	}
 
+	if (x->encap && x->encap->encap_type == TCP_ENCAP_ESPINTCP) {
+		err = esp_reset_espintcp_fraglist_gso(skb);
+		if (err)
+			goto out;
+	}
+
 	err = skb_cow_data(skb, 0, &trailer);
 	if (err < 0)
 		goto out;
@@ -900,6 +906,9 @@ static int esp_input(struct xfrm_state *x, struct sk_buff *skb)
 	nfrags = err;
 
 skip_cow:
+	if (x->encap && x->encap->encap_type == TCP_ENCAP_ESPINTCP)
+		esp_reset_espintcp_gso(skb);
+
 	err = -ENOMEM;
 	tmp = esp_alloc_tmp(aead, nfrags, seqhilen);
 	if (!tmp)
net/ipv6/esp6.c +9 -0
index d654f0f44238..b287c807b018 100644
@@ -936,6 +936,12 @@ static int esp6_input(struct xfrm_state *x, struct sk_buff *skb)
 		}
 	}
 
+	if (x->encap && x->encap->encap_type == TCP_ENCAP_ESPINTCP) {
+		ret = esp_reset_espintcp_fraglist_gso(skb);
+		if (ret)
+			goto out;
+	}
+
 	nfrags = skb_cow_data(skb, 0, &trailer);
 	if (nfrags < 0) {
 		ret = -EINVAL;
@@ -943,6 +949,9 @@ static int esp6_input(struct xfrm_state *x, struct sk_buff *skb)
 	}
 
 skip_cow:
+	if (x->encap && x->encap->encap_type == TCP_ENCAP_ESPINTCP)
+		esp_reset_espintcp_gso(skb);
+
 	ret = -ENOMEM;
 	tmp = esp_alloc_tmp(aead, nfrags, seqhilen);
 	if (!tmp)
Signature · 1 line
2.53.0
author maintainer
#4 lore raw

PATCH 3/22 xfrm: keep the mode module pinned until destroy_state returns

In reply to Steffen Klassert

From: Cen Zhang <[email protected]>

An IPTFS state keeps its mode module referenced while mode_data exists. However, iptfs_destroy_state() drops that reference before returning to xfrm_state_gc_destroy(), which has no reference covering the callback's return path.

With CONFIG_XFRM_IPTFS=m and module unloading enabled, deleting the last IPTFS SA can overlap with ordinary module removal in this order:

XFRM GC worker rmmod xfrm_iptfs
iptfs_destroy_state()
free mode_data
module_put(owner)
<preempted>
delete_module()
xfrm_iptfs_fini()
unregister mode callbacks
free_module()
resume in freed module text

An unload started after the put can finish before the callback resumes. GC invokes the callback outside an RCU read-side critical section, after its grace period. The RCU waits in mode unregistration and module freeing therefore do not protect the callback. The GC mutex only serializes GC with device state flushes. Resuming the callback can cause an instruction-fetch fault in the freed module text.

The Oops below was observed on an earlier kernel with scheduling probes holding the worker in module_put() after the decrement until ordinary rmmod completed. The fixture created and deleted the SA over NETLINK_XFRM.

Take an additional reference to the already pinned owner before calling destroy_state(), and release it in XFRM core after the callback returns. Cache the owner before the call so releasing the extra reference does not need to access the callback table after the callback has finished.

Oops report as below:

    BUG: unable to handle page fault for address: ffffffffc0407455
    #PF: supervisor instruction fetch in kernel mode
    #PF: error_code(0x0010) - not-present page
    PGD 80a9067 P4D 80a9067 PUD 80ab067 PMD 0
    Oops: Oops: 0010 [#1] SMP KASAN NOPTI
    CPU: 3 UID: 0 PID: 53 Comm: kworker/3:1 Not tainted 7.2.0-rc5-pmb-xfrm-functional-v1+ #11 PREEMPT(lazy)
    Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    Workqueue: events xfrm_state_gc_task
    RIP: 0010:0xffffffffc0407455
    Code: Unable to access opcode bytes at 0xffffffffc040742b.
    RSP: 0018:ffff8881013e7aa0 EFLAGS: 00010282
    RAX: 0000000000000000 RBX: ffffffffc02199c0 RCX: ffffffff816fc84e
    RDX: ffff8881013c0000 RSI: 0000000000000000 RDI: ffffffff86338344
    RBP: ffff8881013e7ba8 R08: 0000000000000001 R09: 0000000000000001
    R10: ffffffff893e0257 R11: ffff8881013c0000 R12: ffff888107e9ec00
    R13: ffff888102b07980 R14: ffff888107412ec0 R15: ffff8881013e7ae0
    FS:  0000000000000000(0000) GS:ffff8881fd929000(0000) knlGS:0000000000000000
    CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
    CR2: ffffffffc040742b CR3: 00000000080a6006 CR4: 0000000000770ef0
    PKRU: 55555554
    Call Trace:
     <TASK>
     ? pmbd_gate_maybe+0x47/0x60
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_is_held_type+0x8f/0x100
     xfrm_state_gc_task+0x17e/0x790
     ? lock_acquire+0x17b/0x2f0
     ? __pfx_xfrm_state_gc_task+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_release+0xc8/0x280
     ? srso_alias_return_thunk+0x5/0xfbef5
     process_one_work+0x908/0x19c0
     ? __pfx_process_one_work+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_is_held_type+0x8f/0x100
     ? srso_alias_return_thunk+0x5/0xfbef5
     worker_thread+0x65c/0xe40
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __kthread_parkme+0x175/0x220
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_worker_thread+0x10/0x10
     kthread+0x34f/0x460
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_kthread+0x10/0x10
     ret_from_fork+0x659/0x940
     ? __pfx_ret_from_fork+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __switch_to+0x74f/0xf80
     ? __pfx_kthread+0x10/0x10
     ret_from_fork_asm+0x1a/0x30
     </TASK>
    Modules linked in: [last unloaded: xfrm_iptfs]
    CR2: ffffffffc0407455
    ---[ end trace 0000000000000000 ]---
    RIP: 0010:0xffffffffc0407455
    Code: Unable to access opcode bytes at 0xffffffffc040742b.
    RSP: 0018:ffff8881013e7aa0 EFLAGS: 00010282
    RAX: 0000000000000000 RBX: ffffffffc02199c0 RCX: ffffffff816fc84e
    RDX: ffff8881013c0000 RSI: 0000000000000000 RDI: ffffffff86338344
    RBP: ffff8881013e7ba8 R08: 0000000000000001 R09: 0000000000000001
    R10: ffffffff893e0257 R11: ffff8881013c0000 R12: ffff888107e9ec00
    R13: ffff888102b07980 R14: ffff888107412ec0 R15: ffff8881013e7ae0
    FS:  0000000000000000(0000) GS:ffff8881fd929000(0000) knlGS:0000000000000000
    CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
    CR2: ffffffffc040742b CR3: 00000000080a6006 CR4: 0000000000770ef0
    PKRU: 55555554
    Kernel panic - not syncing: Fatal exception
    Kernel Offset: disabled
Fixes 4b3faf610cc6 ("xfrm: iptfs: add new iptfs xfrm mode impl")
Assisted-by LLM
---
 net/xfrm/xfrm_state.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
net/xfrm/xfrm_state.c +7 -1
index 0555e5d796ed..45a52771796b 100644
@@ -596,8 +596,14 @@ EXPORT_SYMBOL(xfrm_state_free);
 static void xfrm_state_delete_tunnel(struct xfrm_state *x);
 static void xfrm_state_gc_destroy(struct xfrm_state *x)
 {
-	if (x->mode_cbs && x->mode_cbs->destroy_state)
+	if (x->mode_cbs && x->mode_cbs->destroy_state) {
+		struct module *owner = x->mode_cbs->owner;
+
+		/* The callback may drop the last module reference. */
+		__module_get(owner);
 		x->mode_cbs->destroy_state(x);
+		module_put(owner);
+	}
 	hrtimer_cancel(&x->mtimer);
 	timer_delete_sync(&x->rtimer);
 	kfree_sensitive(x->aead);
Signature · 1 line
2.53.0
author maintainer
#5 lore raw

PATCH 4/22 xfrm: serialize SA activation with state deletion

In reply to Steffen Klassert

From: Kyle Zeng <[email protected]>

xfrm_add_sa() publishes a newly constructed state and arms its lifetime timer before marking it VALID. The final VOID-to-VALID test and store are not serialized with state deletion. If hard expiry deletes the state between the test and the store, the store resurrects the unlinked state.

An input lookup which found the state before it was removed can then add it to the per-CPU cache after deletion has removed the cache entries. Once the remaining references are dropped, the cache points to freed memory.

Take x->lock around the conditional transition, with bottom halves disabled as in xfrm_state_delete(). This preserves DEAD if expiry won the race. The same protection covers UPDSA when it installs a replacement for an ACQ state.

Fixes cc01572e2fb0 ("xfrm: Add SA to hardware at the end of xfrm_state_construct()")
---
 net/xfrm/xfrm_user.c | 2 ++
 1 file changed, 2 insertions(+)
net/xfrm/xfrm_user.c +2 -0
index a5fbe38839c4..f802899d3d13 100644
@@ -1088,8 +1088,10 @@ static int xfrm_add_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
 		goto out;
 	}
 
+	spin_lock_bh(&x->lock);
 	if (x->km.state == XFRM_STATE_VOID)
 		x->km.state = XFRM_STATE_VALID;
+	spin_unlock_bh(&x->lock);
 
 	c.seq = nlh->nlmsg_seq;
 	c.portid = nlh->nlmsg_pid;
Signature · 1 line
2.53.0
author maintainer
#6 lore raw

PATCH 5/22 xfrm: keep old state references until migration deletion completes

In reply to Steffen Klassert

From: Cen Zhang <[email protected]>

xfrm_migrate() must retain the references returned by xfrm_migrate_state_find() until it finishes using the old states. The successful migration path instead calls xfrm_states_put() before xfrm_states_delete(), leaving the latter to use unreferenced pointers from x_cur[].

With CONFIG_XFRM_MIGRATE enabled, a privileged XFRM_MSG_MIGRATE or SADB_X_MIGRATE request can reach this path for an SA with a finite hard lifetime and no other users. If migration is preempted after the put, the old SA can expire and be reclaimed before deletion resumes:

Migration task Hard-expiry timer / GC worker
-------------- -----------------------------
xfrm_migrate_state_find()

    hold old SA in x_cur[]
  migrate state and policy
  xfrm_states_put(x_cur, ...)
    drop lookup reference
                                 xfrm_timer_handler()
                                   __xfrm_state_delete(old SA)
                                     drop SAD reference
                                 xfrm_state_gc_task()
                                   synchronize_rcu()
                                   free old SA
  xfrm_states_delete(x_cur, ...)
    xfrm_state_delete(old SA)
      spin_lock_bh(&x->lock) /* use after free */

The configuration mutex does not serialize migration with the timer or GC worker, and migration holds no RCU read lock across this interval. xfrm_state_delete() accesses the freed lock before it can check whether the state is already dead. Expiry before the migration put can open the same window, with that put dropping the last reference.

Delete the old states before putting their lookup references. Each state then remains allocated through the lock access and the dead-state check, including when expiry has already removed it from the SAD.

KASAN report as below:

    ==================================================================
    BUG: KASAN: slab-use-after-free in _raw_spin_lock_bh+0x38/0x50
    Read of size 1 at addr ffff88810967af48 by task python3/443

    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     kasan_report+0xe0/0x110
     __kasan_check_byte+0x36/0x50
     lock_acquire+0x113/0x2f0
     _raw_spin_lock_bh+0x38/0x50
     xfrm_state_delete+0x26/0x60
     xfrm_migrate+0xd26/0x1950
     xfrm_do_migrate+0x797/0xad0
     xfrm_user_rcv_msg+0x3b3/0xc20
     netlink_rcv_skb+0x133/0x390
     xfrm_netlink_rcv+0x76/0x90
     netlink_unicast+0x504/0x840
     netlink_sendmsg+0x7f7/0xcf0
     __sys_sendto+0x425/0x470
     __x64_sys_sendto+0xe5/0x1c0
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f
     </TASK>

    Allocated by task 424:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_slab_alloc+0x89/0x90
     kmem_cache_alloc_noprof+0x20b/0x5f0
     xfrm_state_alloc+0x28/0x5d0
     xfrm_add_sa+0xb81/0x5660
     xfrm_user_rcv_msg+0x3b3/0xc20
     netlink_rcv_skb+0x133/0x390
     xfrm_netlink_rcv+0x76/0x90
     netlink_unicast+0x504/0x840
     netlink_sendmsg+0x7f7/0xcf0
     ____sys_sendmsg+0x88b/0x9d0
     ___sys_sendmsg+0x125/0x1d0
     __sys_sendmsg+0x13e/0x1e0
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 66:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kmem_cache_free+0x242/0x580
     xfrm_state_gc_task+0x534/0x780
     process_one_work+0x908/0x19c0
     worker_thread+0x65c/0xe40
     kthread+0x34f/0x460
     ret_from_fork+0x659/0x940
     ret_from_fork_asm+0x1a/0x30

    The buggy address belongs to the object at ffff88810967aec0
     which belongs to the cache xfrm_state of size 936
    The buggy address is located 136 bytes inside of
     freed 936-byte region [ffff88810967aec0, ffff88810967b268)
    ==================================================================
Fixes 80c9abaabf42 ("[XFRM]: Extension for dynamic update of endpoint address(es)")
---
 net/xfrm/xfrm_policy.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/xfrm/xfrm_policy.c +1 -1
index cea6842e6454..39ca04432220 100644
@@ -4726,8 +4726,8 @@ int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
 
 	/* Stage 4 - delete old state(s) */
 	if (nx_cur) {
-		xfrm_states_put(x_cur, nx_cur);
 		xfrm_states_delete(x_cur, nx_cur);
+		xfrm_states_put(x_cur, nx_cur);
 	}
 
 	/* Stage 5 - announce */
Signature · 1 line
2.53.0
author maintainer
#7 lore raw

PATCH 6/22 xfrm: hold migrated states through rollback

In reply to Steffen Klassert

From: Cen Zhang <[email protected]>

xfrm_migrate() needs to keep each new state alive until it either commits or rolls back the migration. xfrm_state_migrate() publishes the successor using its initial reference as SAD ownership, then returns it without a caller reference. The pointer saved in x_new[] can therefore outlive the state.

A legacy migration can find an existing policy with no matching templates, install a successor and then fail xfrm_policy_migrate() with -ENODATA. If the successor inherits a finite hard lifetime and the migration task is delayed before rollback, expiry and GC can finish first:

Migration task Timer / GC
xfrm_state_migrate()
publish xc, arm mtimer
save xc in x_new[]
xfrm_policy_migrate()
return -ENODATA
<task delayed> xfrm_timer_handler(xc)
__xfrm_state_delete(xc) drop SAD reference
xfrm_state_gc_task()
synchronize_rcu() free xc
xfrm_states_delete(x_new)

    xfrm_state_delete(xc)
      spin_lock_bh(&xc->lock)

The control mutex does not serialize the timer or GC, and migration holds no RCU read lock across this interval. Rollback consequently accesses the freed state's lock. This also affects the PF_KEY migration entry, which uses the same helpers.

Take a caller reference before installing the successor, and release it on installation failure or after the transaction succeeds. On rollback, delete the successors before dropping their caller references. This keeps each allocation alive even if its timer has already removed it from the SAD.

The reported execution used trace probes and paused the netlink migration before the rollback lock access while the normal timer and GC ran. The userspace setup installed an SA with a five-second hard lifetime and a policy without templates using ordinary XFRM requests.

KASAN report as below:

    ==================================================================
    BUG: KASAN: slab-use-after-free in _raw_spin_lock_bh+0x38/0x50
    Read of size 1 at addr ffff8881076d6248 by task python3/417

    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     kasan_report+0xe0/0x110
     __kasan_check_byte+0x36/0x50
     lock_acquire+0x113/0x2f0
     _raw_spin_lock_bh+0x38/0x50
     xfrm_state_delete+0x26/0x60
     xfrm_migrate+0x11af/0x18a0
     xfrm_do_migrate+0x797/0xad0
     xfrm_user_rcv_msg+0x3b3/0xc20
     netlink_rcv_skb+0x133/0x390
     xfrm_netlink_rcv+0x76/0x90
     netlink_unicast+0x504/0x840
     netlink_sendmsg+0x7f7/0xcf0
     __sys_sendto+0x425/0x470
     __x64_sys_sendto+0xe5/0x1c0
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f
     </TASK>

    Allocated by task 417:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_slab_alloc+0x89/0x90
     kmem_cache_alloc_noprof+0x20b/0x5f0
     xfrm_state_alloc+0x28/0x5d0
     xfrm_state_migrate_create+0x55/0x2470
     xfrm_state_migrate+0x37/0x450
     xfrm_migrate+0x80b/0x18a0
     xfrm_do_migrate+0x797/0xad0
     xfrm_user_rcv_msg+0x3b3/0xc20
     netlink_rcv_skb+0x133/0x390
     xfrm_netlink_rcv+0x76/0x90
     netlink_unicast+0x504/0x840
     netlink_sendmsg+0x7f7/0xcf0
     __sys_sendto+0x425/0x470
     __x64_sys_sendto+0xe5/0x1c0
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 11:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kmem_cache_free+0x242/0x580
     xfrm_state_gc_task+0x533/0x730
     process_one_work+0x908/0x19c0
     worker_thread+0x65c/0xe40
     kthread+0x34f/0x460
     ret_from_fork+0x659/0x940
     ret_from_fork_asm+0x1a/0x30

    The buggy address belongs to the object at ffff8881076d61c0
     which belongs to the cache xfrm_state of size 936
    The buggy address is located 136 bytes inside of
     freed 936-byte region [ffff8881076d61c0, ffff8881076d6568)
    ==================================================================
Fixes 80c9abaabf42 ("[XFRM]: Extension for dynamic update of endpoint address(es)")
---
 net/xfrm/xfrm_policy.c | 5 ++++-
 net/xfrm/xfrm_state.c  | 6 +++++-
 2 files changed, 9 insertions(+), 2 deletions(-)
net/xfrm/xfrm_policy.c +4 -1
index 39ca04432220..6edf60242a80 100644
@@ -4733,6 +4733,7 @@ int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
 	/* Stage 5 - announce */
 	km_migrate(sel, dir, type, m, num_migrate, k, net, encap);
 
+	xfrm_states_put(x_new, nx_new);
 	xfrm_pol_put(pol);
 
 	return 0;
@@ -4744,8 +4745,10 @@ int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
 		xfrm_pol_put(pol);
 	if (nx_cur)
 		xfrm_states_put(x_cur, nx_cur);
-	if (nx_new)
+	if (nx_new) {
 		xfrm_states_delete(x_new, nx_new);
+		xfrm_states_put(x_new, nx_new);
+	}
 
 	return err;
 }
net/xfrm/xfrm_state.c +5 -1
index 45a52771796b..f4a4ddaeb9b3 100644
@@ -2244,8 +2244,12 @@ struct xfrm_state *xfrm_state_migrate(struct xfrm_state *x,
 
 	xfrm_migrate_sync(xc, x);
 
-	if (xfrm_state_migrate_install(x, xc, m, extack) < 0)
+	/* Hold a reference for the caller before publishing the state. */
+	xfrm_state_hold(xc);
+	if (xfrm_state_migrate_install(x, xc, m, extack) < 0) {
+		xfrm_state_put(xc);
 		return NULL;
+	}
 
 	return xc;
 }
Signature · 1 line
2.53.0
author maintainer
#8 lore raw

PATCH 7/22 xfrm: check inner family via skb_dst for small_ipv6 DF clearing

In reply to Steffen Klassert

From: Sewook Seo <[email protected]>

Commit 6821ad877034 ("xfrm: do not set IPv4 DF flag when encapsulating IPv6 frames <= 1280 bytes.") intended to clear the outer IPv4 DF bit in xfrm4_tunnel_encap_add() when encapsulating inner IPv6 frames of at most IPV6_MIN_MTU (1280) bytes, by checking skb->protocol == htons(ETH_P_IPV6).

However, its caller xfrm4_prepare_output() overwrites skb->protocol with htons(ETH_P_IP) before invoking xfrm4_tunnel_encap_add(), since commit 0c620e97b349 ("xfrm: remove output indirection from xfrm_mode"). As a result, small_ipv6 always evaluates to false, leaving IP_DF set on outer IPv4 tunnel packets even when encapsulating <= 1280-byte IPv6 frames.

This issue was observed on devices in production use over IPv6-in-IPv4 ESP-in-UDP tunnels where an intermediate IPv4 link has an MTU smaller than the encapsulated packet size (e.g. < 1362 bytes) and ICMPv4 Fragmentation Needed errors are either filtered or not actionable below IPV6_MIN_MTU, causing encapsulated <= 1280-byte IPv6 packets to be dropped instead of fragmented by the outer IPv4 router.

At the time xfrm4_tunnel_encap_add() runs, skb_dst(skb) has not been popped yet and still represents the inner packet destination entry, as already used a few lines below to set top_iph->protocol via xfrm_af2proto(skb_dst(skb)->ops->family), while skb->len still holds the unencapsulated inner packet length. Check dst->ops->family == AF_INET6 instead of skb->protocol so small_ipv6 works as intended.

Tested on User-Mode Linux (ARCH=um) with a four-namespace IPv6-over-IPv4 XFRM ESP tunnel reproducer across a 1300-byte MTU router link with ICMPv4 Fragmentation Needed filtered (verifying 1280-byte inner IPv6 frames fail before the fix and pass via outer IPv4 fragmentation with the fix, while larger frames still preserve outer IP_DF), and verified all tests pass in tools/testing/selftests/net/xfrm_state.sh.

Fixes 6821ad877034 ("xfrm: do not set IPv4 DF flag when encapsulating IPv6 frames <= 1280 bytes.")
Cc Maciej Żenczykowski <[email protected]>
Cc Lorenzo Colitti <[email protected]>
Assisted-by LLM
---
 net/xfrm/xfrm_output.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
net/xfrm/xfrm_output.c +4 -1
index f1f612cd7b43..60ffe9549c09 100644
@@ -275,11 +275,14 @@ static int xfrm4_beet_encap_add(struct xfrm_state *x, struct sk_buff *skb)
  */
 static int xfrm4_tunnel_encap_add(struct xfrm_state *x, struct sk_buff *skb)
 {
-	bool small_ipv6 = (skb->protocol == htons(ETH_P_IPV6)) && (skb->len <= IPV6_MIN_MTU);
 	struct dst_entry *dst = skb_dst(skb);
 	struct iphdr *top_iph;
+	bool small_ipv6;
 	int flags;
 
+	small_ipv6 = (dst->ops->family == AF_INET6) &&
+		     (skb->len <= IPV6_MIN_MTU);
+
 	if (!skb->inner_protocol) {
 		skb_set_inner_network_header(skb, skb_network_offset(skb));
 		skb_set_inner_transport_header(skb, skb_transport_offset(skb));
Signature · 1 line
2.53.0
author maintainer
#9 lore raw

PATCH 8/22 xfrm: account XFRMA_MARK in xfrm_sa_len()

In reply to Steffen Klassert

From: Yasuaki Torimaru <[email protected]>

xfrm_notify_sa() sizes its netlink message with xfrm_sa_len(), while copy_to_user_state_extra() appends XFRMA_MARK whenever the state carries a mark. xfrm_sa_len() does not count that attribute. Only the XFRM_MSG_DELSA path adds it to the length separately, so for a marked state the XFRM_MSG_NEWSA and XFRM_MSG_UPDSA messages are sized short by nla_total_size(sizeof(struct xfrm_mark)), 12 bytes. The other length calculations in this file already account for the mark; xfrm_sa_len() is the only one that does not.

Instrumenting xfrm_notify_sa() on an x86-64 KASAN build under qemu to print the accounted length while adding a marked state confirms the gap:
accounting the mark raises the computed length by exactly 12 bytes (348 -> 360), matching nla_total_size(sizeof(struct xfrm_mark)).

Whether the shortfall is reached depends on the skb allocation, which is rounded up: xfrm_notify_sa() fails with -EMSGSIZE only when that slack is exhausted. km_state_notify() discards the return value, so such a failure would be silent. This was not reproduced.

Count the mark in xfrm_sa_len() for every event and drop the now redundant addition in the DELSA path. The message content is unchanged; only the computed length changes.

Fixes 6f26b61e177e ("xfrm: Allow user space config of SAD mark")
---
 net/xfrm/xfrm_user.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
net/xfrm/xfrm_user.c +2 -1
index f802899d3d13..217f65faa2bd 100644
@@ -4083,6 +4083,8 @@ static inline unsigned int xfrm_sa_len(struct xfrm_state *x)
 		l += nla_total_size(sizeof(*x->encap));
 	if (x->tfcpad)
 		l += nla_total_size(sizeof(x->tfcpad));
+	if (x->mark.v | x->mark.m)
+		l += nla_total_size(sizeof(struct xfrm_mark));
 	if (x->replay_esn)
 		l += nla_total_size(xfrm_replay_state_esn_len(x->replay_esn));
 	else
@@ -4138,7 +4140,6 @@ static int xfrm_notify_sa(struct xfrm_state *x, const struct km_event *c)
 	if (c->event == XFRM_MSG_DELSA) {
 		len += nla_total_size(headlen);
 		headlen = sizeof(*id);
-		len += nla_total_size(sizeof(struct xfrm_mark));
 	}
 	len += NLMSG_ALIGN(headlen);
 
Signature · 1 line
2.53.0
author maintainer
#10 lore raw

PATCH 9/22 xfrm: replay: Fix late packet handling with ESN crypto offload

In reply to Steffen Klassert

From: Cosmin Ratiu <[email protected]>

xfrm_replay_seqhi() guesses seq_hi for a given ingress seq per RFC 4303 section A2.2. Packets with seq < bottom are interpreted as being ahead and the function returns the next seq_hi. xfrm_replay_check_esn() redoes the same computation and defers to the ICV check.

On SW crypto, such packets then fail the ICV check and are dropped, unless they're actual packets ~2^32 in the future (very unlikely).

But on crypto offload, the ICV check already happened in HW and isn't repeated. xfrm_replay_advance_esn() then increments replay_esn->seq_hi.

The problem becomes visible when the HW state is renewed (e.g. bond failover or mlx5 mid-sequence ESN state update). The newly offloaded SA carries the wrong seq_hi and completely breaks ingress since all future packets fail ICV.

This was verified on b2b ConnectX NICs, with an 'iperf3 -P 2' test over a pair of SAs over a bond device in active-backup mode. After ~10s of traffic at ~10 Gbps, replay_esn->seq_hi was ~2.5M due to the two streams sharing the ESN state.
Forcing a bond failover on both sides breaks traffic permanently.

Fix this by dropping packets up to 2^31 before the replay window for crypto offload, since the SW seq_hi guess cannot be validated. Packets up to 2^31 ahead are accepted as new, same as old code. A burst loss of more than 2^31 packets now stalls the SA (previously up to 2^32-wsize).

SW crypto is unaffected.

Fixes 50bd870a9e5c ("xfrm: Add ESN support for IPSec HW offload")
---
 net/xfrm/xfrm_replay.c | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
net/xfrm/xfrm_replay.c +13 -1
index 9394953247ab..37c0c299cb10 100644
@@ -451,6 +451,7 @@ static int xfrm_replay_overflow_esn(struct xfrm_state *x, struct sk_buff *skb)
 static int xfrm_replay_check_esn(struct xfrm_state *x,
 				 struct sk_buff *skb, __be32 net_seq)
 {
+	struct xfrm_offload *xo = xfrm_offload(skb);
 	unsigned int bitnr, nr;
 	u32 diff;
 	struct xfrm_replay_state_esn *replay_esn = x->replay_esn;
@@ -469,7 +470,18 @@ static int xfrm_replay_check_esn(struct xfrm_state *x,
 
 	diff = top - seq;
 
-	if (likely(top >= wsize - 1)) {
+	if (xo && (xo->flags & CRYPTO_DONE)) {
+		/* The ICV was already verified by HW with its own seq_hi,
+		 * so the seq_hi guessed by xfrm_replay_seqhi() can't
+		 * be validated in SW.
+		 *
+		 * Treat seq up to 2^31 ahead of top as new, everything else as
+		 * behind: in-window ones go through the bitmap, the rest get
+		 * dropped.
+		 */
+		if (likely(diff >= BIT(31)))
+			return 0;
+	} else if (likely(top >= wsize - 1)) {
 		/* A. same subspace */
 		if (likely(seq > top) || seq < bottom)
 			return 0;
Signature · 1 line
2.53.0
author maintainer
#11 lore raw

PATCH 10/22 xfrm: fix IPv6 first-fragment protocol decode

In reply to Steffen Klassert

From: Jérémy Jean <[email protected]>

Commit 7a0207094f1b ("xfrm: policy: replace session decode with flow dissector") replaced XFRM session decoding with the flow dissector. While the old IPv6 decoder kept walking past an IPv6 Fragment extension header, the flow dissector stops unless the caller sets FLOW_DISSECTOR_F_PARSE_1ST_FRAG. For an atomic fragment followed by extension headers, inbound policy lookup can therefore see the header after Fragment instead of the actual upper-layer protocol and miss protocol selectors.

Make the dissector continue through first IPv6 fragments. Keep the port, ICMPv6 and GRE selector fields zero for all fragments, as the old decoder did. This also keeps the result the same when a BPF flow dissector fills ports for a first fragment.

Fixes 7a0207094f1b ("xfrm: policy: replace session decode with flow dissector")
---
 net/xfrm/xfrm_policy.c | 35 ++++++++++++++++++++++-------------
 1 file changed, 22 insertions(+), 13 deletions(-)
net/xfrm/xfrm_policy.c +22 -13
index 6edf60242a80..6baff3f797f8 100644
@@ -3484,23 +3484,29 @@ decode_session6(const struct xfrm_flow_keys *flkeys, struct flowi *fl, bool reve
 	if (reverse) {
 		fl6->saddr = flkeys->addrs.ipv6.dst;
 		fl6->daddr = flkeys->addrs.ipv6.src;
-		fl6->fl6_sport = flkeys->ports.dst;
-		fl6->fl6_dport = flkeys->ports.src;
 	} else {
 		fl6->saddr = flkeys->addrs.ipv6.src;
 		fl6->daddr = flkeys->addrs.ipv6.dst;
-		fl6->fl6_sport = flkeys->ports.src;
-		fl6->fl6_dport = flkeys->ports.dst;
 	}
 
-	switch (flkeys->basic.ip_proto) {
-	case IPPROTO_GRE:
-		fl6->fl6_gre_key = flkeys->gre.keyid;
-		break;
-	case IPPROTO_ICMPV6:
-		fl6->fl6_icmp_type = flkeys->icmp.type;
-		fl6->fl6_icmp_code = flkeys->icmp.code;
-		break;
+	if (!(flkeys->control.flags & FLOW_DIS_IS_FRAGMENT)) {
+		if (reverse) {
+			fl6->fl6_sport = flkeys->ports.dst;
+			fl6->fl6_dport = flkeys->ports.src;
+		} else {
+			fl6->fl6_sport = flkeys->ports.src;
+			fl6->fl6_dport = flkeys->ports.dst;
+		}
+
+		switch (flkeys->basic.ip_proto) {
+		case IPPROTO_GRE:
+			fl6->fl6_gre_key = flkeys->gre.keyid;
+			break;
+		case IPPROTO_ICMPV6:
+			fl6->fl6_icmp_type = flkeys->icmp.type;
+			fl6->fl6_icmp_code = flkeys->icmp.code;
+			break;
+		}
 	}
 
 	fl6->flowi6_proto = flkeys->basic.ip_proto;
@@ -3511,10 +3517,13 @@ int __xfrm_decode_session(struct net *net, struct sk_buff *skb, struct flowi *fl
 			  unsigned int family, int reverse)
 {
 	struct xfrm_flow_keys flkeys;
+	unsigned int flags = FLOW_DISSECTOR_F_STOP_AT_ENCAP;
 
 	memset(&flkeys, 0, sizeof(flkeys));
+	if (family == AF_INET6)
+		flags |= FLOW_DISSECTOR_F_PARSE_1ST_FRAG;
 	__skb_flow_dissect(net, skb, &xfrm_session_dissector, &flkeys,
-			   NULL, 0, 0, 0, FLOW_DISSECTOR_F_STOP_AT_ENCAP);
+			   NULL, 0, 0, 0, flags);
 
 	switch (family) {
 	case AF_INET:
Signature · 1 line
2.53.0
author maintainer
#12 lore raw

PATCH 11/22 xfrm: fix selector matching for IPv6 atomic fragments

In reply to Steffen Klassert

From: Jérémy Jean <[email protected]>

IPv6 atomic fragments contain a complete packet, but XFRM leaves the port, ICMPv6 and GRE selector fields unset. Plaintext can then miss a matching policy.

Have ipv6_find_hdr() mark non-atomic Fragment headers. Restore the fields only when every Fragment header is atomic. Use its offset when the transport header is before skb->data. Read with skb_header_pointer() so decoding does not pull or reallocate the skb.

Fixes 7e3a42a12c4b ("xfrm6: handling fragment")
---
 include/net/ipv6.h      |  1 +
 net/ipv6/exthdrs_core.c | 25 +++++++++++++------------
 net/xfrm/xfrm_policy.c  | 19 ++++++++++++++++++-
 3 files changed, 32 insertions(+), 13 deletions(-)
include/net/ipv6.h +1 -0
index 3de07e738538..10785721b013 100644
@@ -1110,6 +1110,7 @@ enum {
 	IP6_FH_F_FRAG		= (1 << 0),
 	IP6_FH_F_AUTH		= (1 << 1),
 	IP6_FH_F_SKIP_RH	= (1 << 2),
+	IP6_FH_F_NON_ATOMIC	= (1 << 3),
 };
 
 /* find specified header and get offset to it */
net/ipv6/exthdrs_core.c +13 -12
index 4a9748338cf4..f00c28ce2f1e 100644
@@ -183,7 +183,8 @@ EXPORT_SYMBOL_GPL(ipv6_find_tlv);
  * isn't NULL.
  *
  * if flags is not NULL and it's a fragment, then the frag flag
- * IP6_FH_F_FRAG will be set. If it's an AH header, the
+ * IP6_FH_F_FRAG will be set. IP6_FH_F_NON_ATOMIC will be set for a
+ * non-atomic Fragment header. If it's an AH header, the
  * IP6_FH_F_AUTH flag is set and target < 0, then this function will
  * stop at the AH header. If IP6_FH_F_SKIP_RH flag was passed, then this
  * function will skip all those routing headers, where segements_left was 0.
@@ -191,23 +192,20 @@ EXPORT_SYMBOL_GPL(ipv6_find_tlv);
 int ipv6_find_hdr(const struct sk_buff *skb, unsigned int *offset,
 		  int target, unsigned short *fragoff, int *flags)
 {
-	unsigned int start = skb_network_offset(skb) + sizeof(struct ipv6hdr);
-	u8 nexthdr = ipv6_hdr(skb)->nexthdr;
+	unsigned int start = *offset ?: skb_network_offset(skb);
+	struct ipv6hdr _ip6, *ip6;
 	int exthdr_cnt = 0;
+	u8 nexthdr;
 	bool found;
 
 	if (fragoff)
 		*fragoff = 0;
 
-	if (*offset) {
-		struct ipv6hdr _ip6, *ip6;
-
-		ip6 = skb_header_pointer(skb, *offset, sizeof(_ip6), &_ip6);
-		if (!ip6 || (ip6->version != 6))
-			return -EBADMSG;
-		start = *offset + sizeof(struct ipv6hdr);
-		nexthdr = ip6->nexthdr;
-	}
+	ip6 = skb_header_pointer(skb, start, sizeof(_ip6), &_ip6);
+	if (!ip6 || (*offset && ip6->version != 6))
+		return -EBADMSG;
+	nexthdr = ip6->nexthdr;
+	start += sizeof(struct ipv6hdr);
 
 	do {
 		struct ipv6_opt_hdr _hdr, *hp;
@@ -254,6 +252,9 @@ int ipv6_find_hdr(const struct sk_buff *skb, unsigned int *offset,
 			if (!fp)
 				return -EBADMSG;
 
+			if (flags && (*fp & htons(IP6_OFFSET | IP6_MF)))
+				*flags |= IP6_FH_F_NON_ATOMIC;
+
 			_frag_off = ntohs(*fp) & ~0x7;
 			if (_frag_off) {
 				if (target < 0 &&
net/xfrm/xfrm_policy.c +18 -1
index 6baff3f797f8..d2e938d4db9a 100644
@@ -3530,9 +3530,26 @@ int __xfrm_decode_session(struct net *net, struct sk_buff *skb, struct flowi *fl
 		decode_session4(&flkeys, fl, reverse);
 		break;
 #if IS_ENABLED(CONFIG_IPV6)
-	case AF_INET6:
+	case AF_INET6: {
+		unsigned int offset = 0;
+		int thoff = flkeys.control.thoff;
+		int fh_flags = 0;
+
+		if ((flkeys.control.flags & FLOW_DIS_IS_FRAGMENT) &&
+		    ipv6_find_hdr(skb, &offset, -1, NULL, &fh_flags) >= 0 &&
+		    (fh_flags & IP6_FH_F_FRAG) &&
+		    !(fh_flags & IP6_FH_F_NON_ATOMIC)) {
+			if (offset > U16_MAX)
+				thoff = (int)offset;
+			flkeys.control.flags &= ~FLOW_DIS_IS_FRAGMENT;
+			flkeys.ports.ports = skb_flow_get_ports(skb,
+								thoff,
+								flkeys.basic.ip_proto,
+								NULL, 0);
+		}
 		decode_session6(&flkeys, fl, reverse);
 		break;
+	}
 #endif
 	default:
 		return -EAFNOSUPPORT;
Signature · 1 line
2.53.0
author maintainer
#13 lore raw

PATCH 12/22 xfrm: espintcp: read the socket error queue for MSG_ERRQUEUE

In reply to Steffen Klassert

From: "Baek Kyu, Kim" <[email protected]>

An ESP-in-TCP socket can have a TX timestamp queued and report POLLERR, but recvmsg(MSG_ERRQUEUE) returns EAGAIN because espintcp_recvmsg() reads the IKE queue instead. If an IKE message is pending, the same call consumes that message as though it were an error-queue result.

Handle MSG_ERRQUEUE through inet_recv_error() before reading the IKE queue. This exposes queued error metadata and leaves IKE messages for normal receive calls.

Fixes e27cca96cd68 ("xfrm: add espintcp (RFC 8229)")
---
 net/xfrm/espintcp.c | 3 +++
 1 file changed, 3 insertions(+)
net/xfrm/espintcp.c +3 -0
index 4052ae5bbb2e..3e23900d6446 100644
@@ -148,6 +148,9 @@ static int espintcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
 	int copied;
 	int off = 0;
 
+	if (unlikely(flags & MSG_ERRQUEUE))
+		return inet_recv_error(sk, msg, len);
+
 	skb = __skb_recv_datagram(sk, &ctx->ike_queue, flags, &off, &err);
 	if (!skb) {
 		if (err == -EAGAIN && sk->sk_shutdown & RCV_SHUTDOWN)
Signature · 1 line
2.53.0
author maintainer
#14 lore raw

PATCH 13/22 xfrm: iptfs: force a dst reference before queueing an skb

In reply to Steffen Klassert

From: Nguyen Ngoc Thang <[email protected]>

iptfs_output_collect() is the dst->output hook and runs under the caller's RCU read lock. It queues the skb and sends it later from the iptfs hrtimer. The skb may still carry a noref dst, e.g. one set by __ip_queue_xmit() via skb_dst_set_noref(). Once the RCU section ends, nothing keeps that dst alive.

When the timer fires, xfrm_output_one() calls skb_dst_force() outside any RCU section:

  WARNING: include/net/dst.h:326 at xfrm_output_resume+0x41d9/0x64e0
  Call Trace:
   xfrm_output_one net/xfrm/xfrm_output.c:549 [inline]
   xfrm_output_resume+0x41d9/0x64e0 net/xfrm/xfrm_output.c:597
   iptfs_output_queued net/xfrm/xfrm_iptfs.c:2325 [inline]
   iptfs_delay_timer+0x3803/0x4310 net/xfrm/xfrm_iptfs.c:2362
   __run_hrtimer kernel/time/hrtimer.c [inline]
   __hrtimer_run_queues+0x3bc/0xa10 kernel/time/hrtimer.c
   hrtimer_run_softirq+0x1e3/0x2e0 kernel/time/hrtimer.c:2153
   handle_softirqs+0x265/0x8d0 kernel/softirq.c:669

The warning also means the queued skb may point to a dst that has already been freed.

Take a reference with skb_dst_force() while still under RCU, as other deferred xmit paths do, and drop the skb if its dst is already gone.

Fixes 0e4fbf013fa5 ("xfrm: iptfs: add user packet (tunnel ingress) handling")
Reported-by [email protected]
---
 net/xfrm/xfrm_iptfs.c | 7 +++++++
 1 file changed, 7 insertions(+)
net/xfrm/xfrm_iptfs.c +7 -0
index 0313a43aa8a9..3fff835497b9 100644
@@ -1914,6 +1914,13 @@ static int iptfs_output_collect(struct net *net, struct sock *sk, struct sk_buff
 			continue;
 		}
 
+		/* The queued skb outlives our RCU section, so pin its dst. */
+		if (!skb_dst_force(skb)) {
+			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTERROR);
+			kfree_skb(skb);
+			continue;
+		}
+
 		/* Enqueue to send in tunnel */
 		ok = iptfs_enqueue(xtfs, skb);
 		if (!ok)
Signature · 1 line
2.53.0
#15 lore raw

Re: [PATCH 13/22] xfrm: iptfs: force a dst reference before queueing an skb

TL;DR: Commit message only: the claim that iptfs_output_collect() always runs under the caller's RCU read lock may be inaccurate, since the udp_sendmsg() path has no RCU lock. The code change itself…
Quoted 1 line

xfrm: iptfs: force a dst reference before queueing an skb

TL;DR: Commit message only: the claim that iptfs_output_collect() always runs under the caller's RCU read lock may be inaccurate, since the udp_sendmsg() path has no RCU lock. The code change itself looks fine.

Quoted 5 lines

iptfs_output_collect() is the dst->output hook and runs under the caller's RCU read lock. It queues the skb and sends it later from the iptfs hrtimer. The skb may still carry a noref dst, e.g. one set by __ip_queue_xmit() via skb_dst_set_noref(). Once the RCU section ends, nothing keeps that dst alive.

This isn't a bug, but is "runs under the caller's RCU read lock" accurate for every caller?

The udp_sendmsg() -> udp_send_skb() -> ip_send_skb() -> ip_local_out() -> dst_output() path reaches iptfs_output_collect() in process context without rcu_read_lock(), although the dst there is already refcounted so skb_dst_force() does nothing.

Would it be more precise to say that callers that attach a noref dst hold an RCU read lock?

Quoted 3 lines
net/xfrm/xfrm_iptfs.c +0 -0

[ ... ]

Quoted 4 lines
net/xfrm/xfrm_iptfs.c +0 -0
@@ -1914,6 +1914,13 @@ static int iptfs_output_collect(struct net *net, struct sock *sk, struct sk_buff
 			continue;
 		}
 

net/xfrm/xfrm_iptfs.c static int iptfs_output_collect(struct net *net, struct sock *sk, struct sk_buff · line 1926

Quoted 10 lines
net/xfrm/xfrm_iptfs.c +7 -0
+		/* The queued skb outlives our RCU section, so pin its dst. */
+		if (!skb_dst_force(skb)) {
+			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTERROR);
+			kfree_skb(skb);
+			continue;
+		}
+
 		/* Enqueue to send in tunnel */
 		ok = iptfs_enqueue(xtfs, skb);
 		if (!ok)

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/46652847109

author maintainer
#16 lore raw

PATCH 14/22 xfrm: espintcp: select receive path by skb protocol

In reply to Steffen Klassert

From: Zihan Xi <[email protected]>

An IPv6 socket can accept an IPv4 connection through a v4-mapped address. Such a socket still receives IPv4 skbs, but espintcp selected the XFRM receive path from the socket family.

Use the skb protocol when selecting the receive path so IPv4 packets are not passed to the IPv6 XFRM parser.

Fixes 26333c37fc28 ("xfrm: add IPv6 support for espintcp")
---
 net/xfrm/espintcp.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/xfrm/espintcp.c +1 -1
index 3e23900d6446..8412dc8eeed7 100644
@@ -48,7 +48,7 @@ static void handle_esp(struct sk_buff *skb, struct sock *sk)
 	}
 	local_bh_disable();
 #if IS_ENABLED(CONFIG_IPV6)
-	if (sk->sk_family == AF_INET6)
+	if (skb->protocol == htons(ETH_P_IPV6))
 		xfrm6_rcv_encap(skb, IPPROTO_ESP, 0, TCP_ENCAP_ESPINTCP);
 	else
 #endif
Signature · 1 line
2.53.0
author maintainer
#17 lore raw

PATCH 15/22 net: xfrm: interface: restore dst_orig on every xfrm interface

In reply to Steffen Klassert

From: Jamal Hadi Salim <[email protected]>

Found while auditing the xfrm metadata consumers of a steered packet. One of them is an xfrm interface, which restores the original route before the xfrm lookup; the swap warned on the metadata dst still installed in the skb, and only the collect_md arm restored the route at all.

The issue:
An xfrm interface takes the if_id and the underlying device either from its configuration or, in collect_md mode, from the xfrm metadata on the skb. When that metadata also carries the route the packet arrived through, xfrmi_xmit2() puts the route back on the skb, because the xfrm lookup takes the address family from it. skb_dst_set() expects the dst slot to be empty for a reference counted dst and warns when it is not, so the route landed over a metadata dst that was still there; a kernel built with CONFIG_DEBUG_NET=y panics on the first packet that takes this path when panic_on_warn is set.

Two more defects sit in the same place. An interface with a configured if_id never restores the route: it takes the metadata dst as it is, whose address family is AF_UNSPEC, so the lookup finds no policy and the packet is dropped as a link failure instead of being transformed. And the restore moved the route out of the metadata dst, which a clone of the skb shares, so the clone that reached the interface first left the original packet with nothing to restore.

The same slot overwrite is in the unstable helper a tc-bpf program uses to attach that metadata: bpf_skb_set_xfrm_info() records the route as dst_orig and installs a per-cpu metadata dst over it. The per-cpu dst is shared by every invocation of the program, so the restore cannot keep anything in it.

The Fix:
Restore dst_orig in both arms of xfrmi_xmit2(), taking a reference with dst_clone() so the metadata dst keeps its own, and empty the counted slot with skb_dst_drop() before the route is installed. The helper allocates a metadata dst per skb instead of a per-cpu one, so the route it records belongs to that skb and is released with it; the per-cpu allocation is no longer used and goes away.

Conditions to recreate the bug:
A tc-bpf program that records the route as dst_orig with bpf_skb_set_xfrm_info() is self-contained: the overwrite is in the helper, so the first packet that calls it panics inside bpf_skb_set_xfrm_info() on a CONFIG_DEBUG_NET=y build with panic_on_warn=1.

An interface with a configured if_id shows its own defect without any other patch: it drops the packet as a link failure without consulting the outbound policy. And a clone made after the metadata was attached consumes the route before the original packet arrives.

Fixes 94151f5aa966 ("xfrm: interface: Add unstable helpers for setting/getting XFRM metadata from TC-BPF")
---
 include/net/xfrm.h             |  2 --
 net/core/filter.c              |  8 --------
 net/xfrm/xfrm_interface_bpf.c  | 19 ++++++++-----------
 net/xfrm/xfrm_interface_core.c | 22 ++++++++++++----------
 4 files changed, 20 insertions(+), 31 deletions(-)
include/net/xfrm.h +0 -2
index 445223a8dc6f..1866e5a3b911 100644
@@ -2370,8 +2370,6 @@ static inline bool xfrm6_local_dontfrag(const struct sock *sk)
 #if (IS_BUILTIN(CONFIG_XFRM_INTERFACE) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) || \
     (IS_MODULE(CONFIG_XFRM_INTERFACE) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
 
-extern struct metadata_dst __percpu *xfrm_bpf_md_dst;
-
 int register_xfrm_interface_bpf(void);
 
 #else
net/core/filter.c +0 -8
index d832d3332c6f..0dd2312521a9 100644
@@ -6271,14 +6271,6 @@ static const struct bpf_func_proto bpf_bind_proto = {
 
 #ifdef CONFIG_XFRM
 
-#if (IS_BUILTIN(CONFIG_XFRM_INTERFACE) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) || \
-    (IS_MODULE(CONFIG_XFRM_INTERFACE) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
-
-struct metadata_dst __percpu *xfrm_bpf_md_dst;
-EXPORT_SYMBOL_GPL(xfrm_bpf_md_dst);
-
-#endif
-
 BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index,
 	   struct bpf_xfrm_state *, to, u32, size, u64, flags)
 {
net/xfrm/xfrm_interface_bpf.c +8 -11
index 5ea15037ebd1..7afbdbd11145 100644
@@ -68,16 +68,9 @@ __bpf_kfunc int bpf_skb_set_xfrm_info(struct __sk_buff *skb_ctx, const struct bp
 	if (unlikely(skb_metadata_dst(skb)))
 		return -EINVAL;
 
-	if (!xfrm_bpf_md_dst) {
-		struct metadata_dst __percpu *tmp;
-
-		tmp = metadata_dst_alloc_percpu(0, METADATA_XFRM, GFP_ATOMIC);
-		if (!tmp)
-			return -ENOMEM;
-		if (cmpxchg(&xfrm_bpf_md_dst, NULL, tmp))
-			metadata_dst_free_percpu(tmp);
-	}
-	md_dst = this_cpu_ptr(xfrm_bpf_md_dst);
+	md_dst = metadata_dst_alloc(0, METADATA_XFRM, GFP_ATOMIC);
+	if (unlikely(!md_dst))
+		return -ENOMEM;
 
 	info = &md_dst->u.xfrm_info;
 
@@ -86,7 +79,11 @@ __bpf_kfunc int bpf_skb_set_xfrm_info(struct __sk_buff *skb_ctx, const struct bp
 	skb_dst_force(skb);
 	info->dst_orig = skb_dst(skb);
 
-	dst_hold((struct dst_entry *)md_dst);
+	/* The metadata dst releases dst_orig when it is freed, so the
+	 * reference the skb held is stolen rather than dropped. The dst
+	 * allocated above is handed to the skb with its single reference.
+	 */
+	skb_dstref_steal(skb);
 	skb_dst_set(skb, (struct dst_entry *)md_dst);
 	return 0;
 }
net/xfrm/xfrm_interface_core.c +12 -10
index 9835fbe63ccb..896180f8d171 100644
@@ -423,6 +423,7 @@ static int xfrmi_rcv_cb(struct sk_buff *skb, int err)
 static int
 xfrmi_xmit2(struct sk_buff *skb, struct net_device *dev, struct flowi *fl)
 {
+	struct xfrm_md_info *md_info = skb_xfrm_md_info(skb);
 	struct xfrm_if *xi = netdev_priv(dev);
 	struct dst_entry *dst = skb_dst(skb);
 	unsigned int length = skb->len;
@@ -433,25 +434,26 @@ xfrmi_xmit2(struct sk_buff *skb, struct net_device *dev, struct flowi *fl)
 	int mtu;
 
 	if (xi->p.collect_md) {
-		struct xfrm_md_info *md_info = skb_xfrm_md_info(skb);
-
 		if (unlikely(!md_info))
 			return -EINVAL;
 
 		if_id = md_info->if_id;
 		fl->flowi_oif = md_info->link;
-		if (md_info->dst_orig) {
-			struct dst_entry *tmp_dst = dst;
-
-			dst = md_info->dst_orig;
-			skb_dst_set(skb, dst);
-			md_info->dst_orig = NULL;
-			dst_release(tmp_dst);
-		}
 	} else {
 		if_id = xi->p.if_id;
 	}
 
+	/* The metadata dst carries the route the packet is still to be
+	 * transformed for, and the lookup below takes the address family from
+	 * the dst it is given. Put that route back, taking our own reference:
+	 * the metadata dst keeps its own, as a clone of this skb shares it.
+	 */
+	if (md_info && md_info->dst_orig) {
+		dst = dst_clone(md_info->dst_orig);
+		skb_dst_drop(skb);
+		skb_dst_set(skb, dst);
+	}
+
 	dst_hold(dst);
 	dst = xfrm_lookup_with_ifid(xi->net, dst, fl, NULL, 0, if_id);
 	if (IS_ERR(dst)) {
Signature · 1 line
2.53.0
author maintainer
#18 lore raw

PATCH 16/22 xfrm: iptfs: make room before copying a continuation in reassembly

In reply to Steffen Klassert

From: Andrii Tereshchenko <[email protected]>

When iptfs_reassem_cont() cannot share a continuation as page frags, it linearizes the in-progress skb and copies the data in with skb_put(), without checking the tailroom. An skb started by iptfs_pskb_add_frags() has little room after linearizing, so a larger continuation panics the kernel in softirq:

skbuff: skb_over_panic: ... len:2884 put:1442 ... end:0x6c0 dev:eth1 kernel BUG at net/core/skbuff.c:215!

  Call Trace:
   <IRQ>
   skb_put.cold+0x1f/0x1f
   iptfs_reassem_cont+0x242/0x760
   iptfs_input_ordered+0x382/0x3e0
   iptfs_input+0x24d/0x630
   xfrm_input+0x12a5/0x29f0

After linearizing, grow the head if the rest of the inner packet does not fit, and abandon the reassembly if that fails.

Made with an AI coding assistant, reviewed by the submitter.

Fixes 5f2b6a909574 ("xfrm: iptfs: add skb-fragment sharing code")
Fixes 0b352f83cabf ("xfrm: iptfs: fix skb_put() panic on non-linear skb during reassembly")
---
 net/xfrm/xfrm_iptfs.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
net/xfrm/xfrm_iptfs.c +9 -1
index 3fff835497b9..76272b0a1829 100644
@@ -909,7 +909,15 @@ static u32 iptfs_reassem_cont(struct xfrm_iptfs_data *xtfs, u64 seq,
 	    iptfs_skb_can_add_frags(newskb, fragwalk, data, copylen)) {
 		iptfs_skb_add_frags(newskb, fragwalk, data, copylen);
 	} else {
-		if (skb_linearize(newskb)) {
+		/* A newskb started by iptfs_pskb_add_frags() has little
+		 * tailroom after linearizing. Make room for the rest of
+		 * the inner packet before copying.
+		 */
+		if (skb_linearize(newskb) ||
+		    (skb_tailroom(newskb) < ipremain &&
+		     pskb_expand_head(newskb, 0,
+				      ipremain - skb_tailroom(newskb),
+				      GFP_ATOMIC | __GFP_NOWARN))) {
 			XFRM_INC_STATS(xs_net(xtfs->x),
 				       LINUX_MIB_XFRMINBUFFERERROR);
 			goto abandon;
Signature · 1 line
2.53.0
author maintainer
#19 lore raw

PATCH 17/22 xfrm/compat: pass on the translated length of a socket policy

In reply to Steffen Klassert

From: Andrii Tereshchenko <[email protected]>

xfrm_user_policy() compiles a 32-bit task's translated socket policy with the untranslated length, 4 bytes short, so the policy loses its last template: an ESP-required socket policy then sends in clear text. Have the translator return the translated length.

Made with an AI coding assistant, reviewed by the submitter.

Fixes 96392ee5a13b ("xfrm/compat: Translate 32-bit user_policy from sockptr")
---
 include/net/xfrm.h     |  2 +-
 net/xfrm/xfrm_compat.c | 18 ++++++++++++++----
 net/xfrm/xfrm_state.c  |  2 +-
 3 files changed, 16 insertions(+), 6 deletions(-)
include/net/xfrm.h +1 -1
index 1866e5a3b911..5fbb73474e32 100644
@@ -2331,7 +2331,7 @@ struct xfrm_translator {
 			struct netlink_ext_ack *extack);
 
 	/* Translate 32-bit user_policy from sockptr */
-	int (*xlate_user_policy_sockptr)(u8 **pdata32, int optlen);
+	int (*xlate_user_policy_sockptr)(u8 **pdata32, int *optlen);
 
 	struct module *owner;
 };
net/xfrm/xfrm_compat.c +14 -4
index 670e3512fc09..af5cb36d691e 100644
@@ -642,16 +642,25 @@ static struct nlmsghdr *xfrm_user_rcv_msg_compat(const struct nlmsghdr *h32,
 	return h64;
 }
 
-static int xfrm_user_policy_compat(u8 **pdata32, int optlen)
+static int xfrm_user_policy_compat(u8 **pdata32, int *optlen)
 {
 	struct compat_xfrm_userpolicy_info *p = (void *)*pdata32;
 	u8 *src_templates, *dst_templates;
 	u8 *data64;
 
-	if (optlen < sizeof(*p))
+	/* The 64-bit layout only adds tail padding, and the templates
+	 * after it are the same in both layouts.
+	 */
+	BUILD_BUG_ON(sizeof(struct xfrm_userpolicy_info) -
+		     sizeof(struct compat_xfrm_userpolicy_info) != 4);
+	BUILD_BUG_ON(offsetof(struct xfrm_userpolicy_info, share) !=
+		     offsetof(struct compat_xfrm_userpolicy_info, share));
+	BUILD_BUG_ON(__alignof__(struct xfrm_user_tmpl) > 4);
+
+	if (*optlen < sizeof(*p))
 		return -EINVAL;
 
-	data64 = kmalloc_track_caller(optlen + 4, GFP_USER | __GFP_NOWARN);
+	data64 = kmalloc_track_caller(*optlen + 4, GFP_USER | __GFP_NOWARN);
 	if (!data64)
 		return -ENOMEM;
 
@@ -660,10 +669,11 @@ static int xfrm_user_policy_compat(u8 **pdata32, int optlen)
 
 	src_templates = *pdata32 + sizeof(*p);
 	dst_templates = data64 + sizeof(*p) + 4;
-	memcpy(dst_templates, src_templates, optlen - sizeof(*p));
+	memcpy(dst_templates, src_templates, *optlen - sizeof(*p));
 
 	kfree(*pdata32);
 	*pdata32 = data64;
+	*optlen += 4;
 	return 0;
 }
 
net/xfrm/xfrm_state.c +1 -1
index f4a4ddaeb9b3..eb984ed11888 100644
@@ -3115,7 +3115,7 @@ int xfrm_user_policy(struct sock *sk, int optname, sockptr_t optval, int optlen)
 			return -EOPNOTSUPP;
 		}
 
-		err = xtr->xlate_user_policy_sockptr(&data, optlen);
+		err = xtr->xlate_user_policy_sockptr(&data, &optlen);
 		xfrm_put_translator(xtr);
 		if (err) {
 			kfree(data);
Signature · 1 line
2.53.0
author maintainer
#20 lore raw

PATCH 18/22 xfrm: Give GC list nodes their own storage

In reply to Steffen Klassert

From: Jianbo Liu <[email protected]>

gclist currently shares storage with bydst, and dev_gclist shares storage with bysrc.

This is unsafe for bydst and bysrc, which can be traversed under RCU without holding xfrm_state_lock. __xfrm_state_delete() unlinks these nodes with hlist_del_init_rcu(), so a reader that started before the unlink may still be following their linkage after the state has been removed from the hash table.

Later, when the last reference is dropped, __xfrm_state_destroy() adds x->gclist to xfrm_state_gc_list. Since gclist and bydst currently share the same storage, adding the state to the GC list can overwrite the bydst linkage while an RCU reader is still using it. The same issue applies to dev_gclist and bysrc.

Give gclist, bydst, and bysrc separate storage so their hash-list linkage remains valid for outstanding RCU readers. Share dev_gclist with byseq instead. byseq has no RCU readers, only __xfrm_find_acq_byseq() under xfrm_state_lock, and the state is unlinked from byseq before dev_gclist is used. Sharing keeps the growth of struct xfrm_state at 16 bytes rather than 32.

Fixes d737a5805581 ("xfrm: state: don't use lock anymore unless acquire operation is needed")
---
 include/net/xfrm.h    | 10 ++++------
 net/xfrm/xfrm_state.c |  1 +
 2 files changed, 5 insertions(+), 6 deletions(-)
include/net/xfrm.h +4 -6
index 5fbb73474e32..cd37aa69c9ac 100644
@@ -189,16 +189,14 @@ enum xfrm_replay_mode {
 /* Full description of state of transformer. */
 struct xfrm_state {
 	possible_net_t		xs_net;
-	union {
-		struct hlist_node	gclist;
-		struct hlist_node	bydst;
-	};
+	struct hlist_node	bydst;
+	struct hlist_node	bysrc;
+	struct hlist_node	gclist;
 	union {
 		struct hlist_node	dev_gclist;
-		struct hlist_node	bysrc;
+		struct hlist_node	byseq;
 	};
 	struct hlist_node	byspi;
-	struct hlist_node	byseq;
 	struct hlist_node	state_cache;
 	struct hlist_node	state_cache_input;
 
net/xfrm/xfrm_state.c +1 -0
index eb984ed11888..9c101be250ee 100644
@@ -751,6 +751,7 @@ struct xfrm_state *xfrm_state_alloc(struct net *net)
 		INIT_HLIST_NODE(&x->state_cache);
 		INIT_HLIST_NODE(&x->bydst);
 		INIT_HLIST_NODE(&x->bysrc);
+		INIT_HLIST_NODE(&x->gclist);
 		INIT_HLIST_NODE(&x->byspi);
 		INIT_HLIST_NODE(&x->byseq);
 		hrtimer_setup(&x->mtimer, xfrm_timer_handler, CLOCK_BOOTTIME,
Signature · 1 line
2.53.0
author maintainer
#21 lore raw

PATCH 19/22 xfrm: Serialize device state teardown

In reply to Steffen Klassert

From: Jianbo Liu <[email protected]>

Commit 89fefad9f971 ("xfrm: serialize state GC with device state flush") stopped the state GC and xfrm_dev_state_flush() from freeing the same device state at once, but a third caller is not covered.

xfrm_state_find() frees a packet offload acquire state when km_query() fails. It runs under RCU and can't take the mutex. xfrm_dev_state_delete() first puts the state on xfrm_state_dev_gc_list with xso->dev still set, so a device flush can find it there and call xfrm_dev_state_free() too. Both callers see xso->dev set and both unlink the state, so the second hlist_del() hits a poisoned node.

Claim the device in xfrm_dev_state_free() by clearing xso->dev under x->lock and xfrm_state_dev_gc_lock, so only one caller unlinks the state, invokes xdo_dev_state_free() and drops the netdevice reference. x->lock also keeps xso->dev stable for the stats updates that hold it.

In the flush, take a state reference before removing a state from the device GC list, so it stays alive while the flush owns it. Skip a state with no reference left, the state GC frees it.

Keep xso->type unchanged after detaching the device, so lockless readers of xso->type do not see a packet offload state as a software state. Reject offloaded states with no device in xfrm_dev_offload_ok(): a packet offload state would otherwise pass the !dev check there, and xfrm_output() would send the packet with no ESP or use the NULL device in xfrm_dev_direct_output().

Found by the AI review of the commit above (see Link) and reproduced on ConnectX-7 with a packet offload policy that has no SA, an acquire listener that never reads, UDP senders hitting the policy and the device taken down in a loop:

[  167.689163] Oops: general protection fault, probably for non-canonical address 0xdead000000000122: 0000 [#1] SMP
[  167.690938] CPU: 11 UID: 0 PID: 2093 Comm: python3 Not tainted 7.4.0-rc1+ #10 PREEMPTLAZY
[  167.694337] RIP: 0010:xfrm_dev_state_free+0x41/0xe0
[  167.699068] RAX: dead000000000122 RBX: ff1100014f543800 RCX: ff11000103bbf800
[  167.700247] RDX: dead000000000100 RSI: 0000000000000001 RDI: ffffffff82da8c68
[  167.716897] Call Trace:
[  167.717405]  <TASK>
[  167.717863]  xfrm_state_find+0x19b0/0x1ab0
[  167.718629]  xfrm_resolve_and_create_bundle+0x17d/0x11e0
[  167.722070]  xfrm_lookup_with_ifid+0x1e7/0xb50
[  167.722872]  xfrm_lookup_route+0x1d/0xa0
[  167.723593]  udp_sendmsg+0x8da/0xc90
[  167.724273]  __sock_sendmsg+0x38/0x70
[  167.724988]  __sys_sendto+0x119/0x180
[  167.727954]  __x64_sys_sendto+0x20/0x30
[  167.728666]  do_syscall_64+0x72/0x3b0
[  167.729357]  entry_SYSCALL_64_after_hwframe+0x4b/0x53
[  167.741064]  </TASK>
[  167.752388] Kernel panic - not syncing: Fatal exception in interrupt

With this series the same test ran 400 cycles with no crash, and 150 cycles on a kernel with KASAN and lockdep.

Fixes 07b87f9eea0c ("xfrm: Fix unregister netdevice hang on hardware offload.")
---
 net/xfrm/xfrm_device.c |  4 ++--
 net/xfrm/xfrm_state.c  | 51 ++++++++++++++++++++++++++++--------------
 2 files changed, 36 insertions(+), 19 deletions(-)
net/xfrm/xfrm_device.c +2 -2
index f153bf695b9d..3bbb970cd337 100644
@@ -422,11 +422,11 @@ bool xfrm_dev_offload_ok(struct sk_buff *skb, struct xfrm_state *x)
 	int mtu;
 	struct dst_entry *dst = skb_dst(skb);
 	struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
-	struct net_device *dev = x->xso.dev;
+	struct net_device *dev = READ_ONCE(x->xso.dev);
 	bool check_tunnel_size;
 
 	if (!x->type_offload ||
-	    (x->xso.type == XFRM_DEV_OFFLOAD_UNSPECIFIED && x->encap))
+	    (x->xso.type == XFRM_DEV_OFFLOAD_UNSPECIFIED ? !!x->encap : !dev))
 		return false;
 
 	if ((!dev || dev == xfrm_dst_path(dst)->dev) &&
net/xfrm/xfrm_state.c +34 -17

81 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#22 lore raw

PATCH 20/22 xfrm: Wait for an RCU grace period before freeing device state

In reply to Steffen Klassert

From: Jianbo Liu <[email protected]>

xfrm_dev_state_flush() can call xdo_dev_state_free() immediately after xdo_dev_state_delete(), without waiting for pre-existing RCU readers of the driver's SA state to complete.

The normal state GC path waits for an RCU grace period before destroying the state, but the device flush path does not.

Remove the immediate xfrm_dev_state_free() following xfrm_state_delete(). The delete path queues the state on xfrm_state_dev_gc_list. The subsequent collection pass picks it up if a reference is left. If the flush dropped the last one, the state GC frees it after its own grace period and xfrm_flush_gc() waits for it.

Wait for one RCU grace period after collecting the states and before freeing them. This establishes the required xdo_dev_state_delete() -> synchronize_rcu() -> xdo_dev_state_free() ordering while using a single grace period for the whole flush.

Fixes 07b87f9eea0c ("xfrm: Fix unregister netdevice hang on hardware offload.")
---
 net/xfrm/xfrm_state.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
net/xfrm/xfrm_state.c +3 -1
index 6f98c5c1a823..92c3631a43bf 100644
@@ -1000,7 +1000,6 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali
 				spin_unlock_bh(&net->xfrm.xfrm_state_lock);
 
 				err = xfrm_state_delete(x);
-				xfrm_dev_state_free(x);
 
 				xfrm_audit_state_delete(x, err ? 0 : 1,
 							task_valid);
@@ -1038,6 +1037,9 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali
 	spin_unlock_bh(&xfrm_state_dev_gc_lock);
 	mutex_unlock(&xfrm_state_gc_mutex);
 
+	if (!hlist_empty(&flush_list))
+		synchronize_rcu();
+
 	hlist_for_each_entry_safe(x, tmp, &flush_list, gclist) {
 		hlist_del_init(&x->gclist);
 		xfrm_dev_state_free(x);
Signature · 1 line
2.53.0
author maintainer
#23 lore raw

PATCH 21/22 Revert "xfrm: serialize state GC with device state flush"

In reply to Steffen Klassert

From: Jianbo Liu <[email protected]>

This reverts commit 89fefad9f971bc637fb22373078144f2563c4be9.

The mutex kept the state GC from destroying a state while xfrm_dev_state_flush() was freeing its device state. It can't cover xfrm_state_find(), which frees device state under RCU.

The flush now holds a reference on each state it frees, and xfrm_dev_state_free() lets only one caller free the device state. Nothing is left for the mutex to protect, so remove it.

This needs "xfrm: Serialize device state teardown". Without that patch the flush frees the device state of a state it holds no reference on.

---
 net/xfrm/xfrm_state.c | 5 -----
 1 file changed, 5 deletions(-)
net/xfrm/xfrm_state.c +0 -5
index 92c3631a43bf..d48c88f2df64 100644
@@ -226,7 +226,6 @@ static struct xfrm_state_afinfo __rcu *xfrm_state_afinfo[NPROTO];
 
 static DEFINE_SPINLOCK(xfrm_state_gc_lock);
 static DEFINE_SPINLOCK(xfrm_state_dev_gc_lock);
-static DEFINE_MUTEX(xfrm_state_gc_mutex);
 
 int __xfrm_state_delete(struct xfrm_state *x);
 
@@ -639,10 +638,8 @@ static void xfrm_state_gc_task(struct work_struct *work)
 
 	synchronize_rcu();
 
-	mutex_lock(&xfrm_state_gc_mutex);
 	hlist_for_each_entry_safe(x, tmp, &gc_list, gclist)
 		xfrm_state_gc_destroy(x);
-	mutex_unlock(&xfrm_state_gc_mutex);
 }
 
 static enum hrtimer_restart xfrm_timer_handler(struct hrtimer *me)
@@ -1018,7 +1015,6 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali
 out:
 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
 
-	mutex_lock(&xfrm_state_gc_mutex);
 	spin_lock_bh(&xfrm_state_dev_gc_lock);
 	hlist_for_each_entry_safe(x, tmp, &xfrm_state_dev_gc_list, dev_gclist) {
 		xso = &x->xso;
@@ -1035,7 +1031,6 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali
 		}
 	}
 	spin_unlock_bh(&xfrm_state_dev_gc_lock);
-	mutex_unlock(&xfrm_state_gc_mutex);
 
 	if (!hlist_empty(&flush_list))
 		synchronize_rcu();
Signature · 1 line
2.53.0
author maintainer
#24 lore raw

PATCH 22/22 xfrm: Serialize offload stats updates with x->lock

In reply to Steffen Klassert

From: Jianbo Liu <[email protected]>

xfrm_dev_state_update_stats() calls into the driver, which adds to x->curlft and x->stats what the device counted since the last call. Callers use different locks, so two of them can refresh the same state at once and count the same packets twice, and a dump can copy the counters while another caller updates them.

Serialize all device stats refreshes with x->lock and assert it in xfrm_dev_state_update_stats(). Build the SA message of a netlink dump, get or notification under the same lock.

The SA dump and xfrm_state_update_stats() walk the states under xfrm_state_lock, where x->lock cannot be taken: the lock order is x->lock, then xfrm_state_lock. Add xfrm_state_walk_batch(), which takes references on at most 32 states per xfrm_state_lock hold, and handle each state under x->lock after the list lock is dropped. States rejected by the dump filter count against the 32, so a filter that matches few states cannot keep the list lock held over the whole list. xfrm_state_walk() cannot give this bound: it calls back only for states that pass the filter. Walk markers and states being deleted do not count, so a call always covers 32 states or reaches the end of the list.

Keep the refresh right before each state is copied, so every part of a multi-part dump still has current counters. When a state does not fit into the skb, put the walk marker back in front of it and drop the references, so no state stays referenced between two dump calls. If the state was unlinked meanwhile, skip it and go on.

copy_to_user_state() cannot take x->lock itself: build_expire() calls it with the lock held. Move the refresh out of it and let each caller refresh under x->lock. PF_KEY never refreshed and does not change.

Fixes c9fa320b00cf ("xfrm: copy_to_user_state fetch offloaded SA packets/bytes statistics")
Fixes f9f221c98fd8 ("xfrm: get global statistics from the offloaded device")
---
 include/net/xfrm.h    | 12 ++++++
 net/xfrm/xfrm_state.c | 87 +++++++++++++++++++++++++++++++++++++++----
 net/xfrm/xfrm_user.c  | 45 ++++++++++++++++++++--
 3 files changed, 133 insertions(+), 11 deletions(-)
include/net/xfrm.h +12 -0
index cd37aa69c9ac..47aae21ea1cb 100644
@@ -130,6 +130,13 @@ struct xfrm_state_walk {
 	struct xfrm_address_filter *filter;
 };
 
+#define XFRM_STATE_WALK_BATCH_SIZE	32
+
+struct xfrm_state_walk_batch {
+	struct xfrm_state	*states[XFRM_STATE_WALK_BATCH_SIZE];
+	unsigned int		count;
+};
+
 enum {
 	XFRM_DEV_OFFLOAD_IN = 1,
 	XFRM_DEV_OFFLOAD_OUT,
@@ -1716,6 +1723,9 @@ void xfrm_state_walk_init(struct xfrm_state_walk *walk, u8 proto,
 			  struct xfrm_address_filter *filter);
 int xfrm_state_walk(struct net *net, struct xfrm_state_walk *walk,
 		    int (*func)(struct xfrm_state *, int, void*), void *);
+bool xfrm_state_walk_batch(struct net *net, struct xfrm_state_walk *walk,
+			   struct xfrm_state_walk_batch *batch);
+bool xfrm_state_walk_rewind(struct xfrm_state_walk *walk, struct xfrm_state *x);
 void xfrm_state_walk_done(struct xfrm_state_walk *walk, struct net *net);
 struct xfrm_state *xfrm_state_alloc(struct net *net);
 void xfrm_state_free(struct xfrm_state *x);
@@ -1740,6 +1750,8 @@ static inline void xfrm_dev_state_update_stats(struct xfrm_state *x)
 	struct xfrm_dev_offload *xdo = &x->xso;
 	struct net_device *dev = READ_ONCE(xdo->dev);
 
+	lockdep_assert_held(&x->lock);
+
 	if (dev && dev->xfrmdev_ops &&
 	    dev->xfrmdev_ops->xdo_dev_state_update_stats)
 		dev->xfrmdev_ops->xdo_dev_state_update_stats(x);
net/xfrm/xfrm_state.c +80 -7

101 lines not on this page · raw message

net/xfrm/xfrm_user.c +41 -4

94 lines not on this page · raw message

Signature · 1 line
2.53.0