From: Zhiling Zou 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") Cc: stable@vger.kernel.org Reported-by: Vega Link: https://bugtracker.nebusec.ai/f/13830 Assisted-by: LLM Signed-off-by: Zhiling Zou Signed-off-by: Steffen Klassert --- net/xfrm/xfrm_ipcomp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/net/xfrm/xfrm_ipcomp.c b/net/xfrm/xfrm_ipcomp.c index 671d48f8c937..c2cc88c8c360 100644 --- a/net/xfrm/xfrm_ipcomp.c +++ b/net/xfrm/xfrm_ipcomp.c @@ -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; -- 2.53.0 From: Guoshuai Yang 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)") Cc: stable@vger.kernel.org Signed-off-by: Guoshuai Yang Signed-off-by: Steffen Klassert --- include/net/esp.h | 51 +++++++++++++++++++++++++++++++++++++++++++++++ net/ipv4/esp4.c | 9 +++++++++ net/ipv6/esp6.c | 9 +++++++++ 3 files changed, 69 insertions(+) diff --git a/include/net/esp.h b/include/net/esp.h index 322950727dd0..83c75ef59482 100644 --- a/include/net/esp.h +++ b/include/net/esp.h @@ -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; diff --git a/net/ipv4/esp4.c b/net/ipv4/esp4.c index ae701561d9f1..111bea0bd260 100644 --- a/net/ipv4/esp4.c +++ b/net/ipv4/esp4.c @@ -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) diff --git a/net/ipv6/esp6.c b/net/ipv6/esp6.c index d654f0f44238..b287c807b018 100644 --- a/net/ipv6/esp6.c +++ b/net/ipv6/esp6.c @@ -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) -- 2.53.0 From: Cen Zhang 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) 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: ? 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 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") Signed-off-by: Cen Zhang Assisted-by: LLM Signed-off-by: Steffen Klassert --- net/xfrm/xfrm_state.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/net/xfrm/xfrm_state.c b/net/xfrm/xfrm_state.c index 0555e5d796ed..45a52771796b 100644 --- a/net/xfrm/xfrm_state.c +++ b/net/xfrm/xfrm_state.c @@ -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); -- 2.53.0 From: Kyle Zeng 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()") Signed-off-by: Kyle Zeng Signed-off-by: Steffen Klassert --- net/xfrm/xfrm_user.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/net/xfrm/xfrm_user.c b/net/xfrm/xfrm_user.c index a5fbe38839c4..f802899d3d13 100644 --- a/net/xfrm/xfrm_user.c +++ b/net/xfrm/xfrm_user.c @@ -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; -- 2.53.0 From: Cen Zhang 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: 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 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)") Signed-off-by: Cen Zhang Signed-off-by: Steffen Klassert --- net/xfrm/xfrm_policy.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/net/xfrm/xfrm_policy.c b/net/xfrm/xfrm_policy.c index cea6842e6454..39ca04432220 100644 --- a/net/xfrm/xfrm_policy.c +++ b/net/xfrm/xfrm_policy.c @@ -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 */ -- 2.53.0 From: Cen Zhang 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 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: 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 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)") Signed-off-by: Cen Zhang Signed-off-by: Steffen Klassert --- net/xfrm/xfrm_policy.c | 5 ++++- net/xfrm/xfrm_state.c | 6 +++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/net/xfrm/xfrm_policy.c b/net/xfrm/xfrm_policy.c index 39ca04432220..6edf60242a80 100644 --- a/net/xfrm/xfrm_policy.c +++ b/net/xfrm/xfrm_policy.c @@ -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; } diff --git a/net/xfrm/xfrm_state.c b/net/xfrm/xfrm_state.c index 45a52771796b..f4a4ddaeb9b3 100644 --- a/net/xfrm/xfrm_state.c +++ b/net/xfrm/xfrm_state.c @@ -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; } -- 2.53.0 From: Sewook Seo 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: stable@vger.kernel.org Cc: Maciej Żenczykowski Cc: Lorenzo Colitti Assisted-by: LLM Signed-off-by: Sewook Seo Signed-off-by: Steffen Klassert --- net/xfrm/xfrm_output.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/net/xfrm/xfrm_output.c b/net/xfrm/xfrm_output.c index f1f612cd7b43..60ffe9549c09 100644 --- a/net/xfrm/xfrm_output.c +++ b/net/xfrm/xfrm_output.c @@ -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)); -- 2.53.0 From: Yasuaki Torimaru 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") Signed-off-by: Yasuaki Torimaru Signed-off-by: Steffen Klassert --- net/xfrm/xfrm_user.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/net/xfrm/xfrm_user.c b/net/xfrm/xfrm_user.c index f802899d3d13..217f65faa2bd 100644 --- a/net/xfrm/xfrm_user.c +++ b/net/xfrm/xfrm_user.c @@ -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); -- 2.53.0 From: Cosmin Ratiu 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") Signed-off-by: Cosmin Ratiu Signed-off-by: Steffen Klassert --- net/xfrm/xfrm_replay.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/net/xfrm/xfrm_replay.c b/net/xfrm/xfrm_replay.c index 9394953247ab..37c0c299cb10 100644 --- a/net/xfrm/xfrm_replay.c +++ b/net/xfrm/xfrm_replay.c @@ -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; -- 2.53.0 From: Jérémy Jean 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") Cc: stable@vger.kernel.org Signed-off-by: Jérémy Jean Signed-off-by: Steffen Klassert --- net/xfrm/xfrm_policy.c | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/net/xfrm/xfrm_policy.c b/net/xfrm/xfrm_policy.c index 6edf60242a80..6baff3f797f8 100644 --- a/net/xfrm/xfrm_policy.c +++ b/net/xfrm/xfrm_policy.c @@ -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: -- 2.53.0 From: Jérémy Jean 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") Cc: stable@vger.kernel.org Signed-off-by: Jérémy Jean Signed-off-by: Steffen Klassert --- include/net/ipv6.h | 1 + net/ipv6/exthdrs_core.c | 25 +++++++++++++------------ net/xfrm/xfrm_policy.c | 19 ++++++++++++++++++- 3 files changed, 32 insertions(+), 13 deletions(-) diff --git a/include/net/ipv6.h b/include/net/ipv6.h index 3de07e738538..10785721b013 100644 --- a/include/net/ipv6.h +++ b/include/net/ipv6.h @@ -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 */ diff --git a/net/ipv6/exthdrs_core.c b/net/ipv6/exthdrs_core.c index 4a9748338cf4..f00c28ce2f1e 100644 --- a/net/ipv6/exthdrs_core.c +++ b/net/ipv6/exthdrs_core.c @@ -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 && diff --git a/net/xfrm/xfrm_policy.c b/net/xfrm/xfrm_policy.c index 6baff3f797f8..d2e938d4db9a 100644 --- a/net/xfrm/xfrm_policy.c +++ b/net/xfrm/xfrm_policy.c @@ -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; -- 2.53.0 From: "Baek Kyu, Kim" 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)") Signed-off-by: Baek Kyu, Kim Signed-off-by: Steffen Klassert --- net/xfrm/espintcp.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/net/xfrm/espintcp.c b/net/xfrm/espintcp.c index 4052ae5bbb2e..3e23900d6446 100644 --- a/net/xfrm/espintcp.c +++ b/net/xfrm/espintcp.c @@ -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) -- 2.53.0 From: Nguyen Ngoc Thang 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: syzbot+622de7e1f18a30fc404a@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=622de7e1f18a30fc404a Signed-off-by: Nguyen Ngoc Thang Signed-off-by: Steffen Klassert --- net/xfrm/xfrm_iptfs.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/net/xfrm/xfrm_iptfs.c b/net/xfrm/xfrm_iptfs.c index 0313a43aa8a9..3fff835497b9 100644 --- a/net/xfrm/xfrm_iptfs.c +++ b/net/xfrm/xfrm_iptfs.c @@ -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) -- 2.53.0 From: Zihan Xi 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") Cc: stable@vger.kernel.org Reported-by: Vega Signed-off-by: Zihan Xi Signed-off-by: Steffen Klassert --- net/xfrm/espintcp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/net/xfrm/espintcp.c b/net/xfrm/espintcp.c index 3e23900d6446..8412dc8eeed7 100644 --- a/net/xfrm/espintcp.c +++ b/net/xfrm/espintcp.c @@ -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 -- 2.53.0 From: Jamal Hadi Salim 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") Link: https://lore.kernel.org/netdev/DMZJS8O5A4YX.9T2P4DT0DAB7@gmail.com/ Cc: stable@vger.kernel.org Reviewed-by: Victor Nogueira Signed-off-by: Jamal Hadi Salim Reviewed-by: Eyal Birger Signed-off-by: Steffen Klassert --- 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(-) diff --git a/include/net/xfrm.h b/include/net/xfrm.h index 445223a8dc6f..1866e5a3b911 100644 --- a/include/net/xfrm.h +++ b/include/net/xfrm.h @@ -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 diff --git a/net/core/filter.c b/net/core/filter.c index d832d3332c6f..0dd2312521a9 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -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) { diff --git a/net/xfrm/xfrm_interface_bpf.c b/net/xfrm/xfrm_interface_bpf.c index 5ea15037ebd1..7afbdbd11145 100644 --- a/net/xfrm/xfrm_interface_bpf.c +++ b/net/xfrm/xfrm_interface_bpf.c @@ -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; } diff --git a/net/xfrm/xfrm_interface_core.c b/net/xfrm/xfrm_interface_core.c index 9835fbe63ccb..896180f8d171 100644 --- a/net/xfrm/xfrm_interface_core.c +++ b/net/xfrm/xfrm_interface_core.c @@ -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)) { -- 2.53.0 From: Andrii Tereshchenko 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: 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") Reported-by: Piyus Kedia Closes: https://lore.kernel.org/all/20261119142308.3272570-1-piyus@iiitd.ac.in/ Link: https://lore.kernel.org/all/20260908224855.1591147-1-kuba@kernel.org/ Cc: stable@vger.kernel.org Signed-off-by: Andrii Tereshchenko Reviewed-by: Fernando Fernandez Mancera Signed-off-by: Steffen Klassert --- net/xfrm/xfrm_iptfs.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/net/xfrm/xfrm_iptfs.c b/net/xfrm/xfrm_iptfs.c index 3fff835497b9..76272b0a1829 100644 --- a/net/xfrm/xfrm_iptfs.c +++ b/net/xfrm/xfrm_iptfs.c @@ -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; -- 2.53.0 From: Andrii Tereshchenko 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") Cc: stable@vger.kernel.org Signed-off-by: Andrii Tereshchenko Signed-off-by: Steffen Klassert --- include/net/xfrm.h | 2 +- net/xfrm/xfrm_compat.c | 18 ++++++++++++++---- net/xfrm/xfrm_state.c | 2 +- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/include/net/xfrm.h b/include/net/xfrm.h index 1866e5a3b911..5fbb73474e32 100644 --- a/include/net/xfrm.h +++ b/include/net/xfrm.h @@ -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; }; diff --git a/net/xfrm/xfrm_compat.c b/net/xfrm/xfrm_compat.c index 670e3512fc09..af5cb36d691e 100644 --- a/net/xfrm/xfrm_compat.c +++ b/net/xfrm/xfrm_compat.c @@ -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; } diff --git a/net/xfrm/xfrm_state.c b/net/xfrm/xfrm_state.c index f4a4ddaeb9b3..eb984ed11888 100644 --- a/net/xfrm/xfrm_state.c +++ b/net/xfrm/xfrm_state.c @@ -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); -- 2.53.0 From: Jianbo Liu 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") Signed-off-by: Jianbo Liu Reviewed-by: Carolina Jubran Signed-off-by: Steffen Klassert --- include/net/xfrm.h | 10 ++++------ net/xfrm/xfrm_state.c | 1 + 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/include/net/xfrm.h b/include/net/xfrm.h index 5fbb73474e32..cd37aa69c9ac 100644 --- a/include/net/xfrm.h +++ b/include/net/xfrm.h @@ -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; diff --git a/net/xfrm/xfrm_state.c b/net/xfrm/xfrm_state.c index eb984ed11888..9c101be250ee 100644 --- a/net/xfrm/xfrm_state.c +++ b/net/xfrm/xfrm_state.c @@ -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, -- 2.53.0 From: Jianbo Liu 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] [ 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] [ 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.") Link: https://lore.kernel.org/netdev/20260908224854.1591115-1-kuba@kernel.org/ Signed-off-by: Jianbo Liu Reviewed-by: Carolina Jubran Signed-off-by: Steffen Klassert --- net/xfrm/xfrm_device.c | 4 ++-- net/xfrm/xfrm_state.c | 51 ++++++++++++++++++++++++++++-------------- 2 files changed, 36 insertions(+), 19 deletions(-) diff --git a/net/xfrm/xfrm_device.c b/net/xfrm/xfrm_device.c index f153bf695b9d..3bbb970cd337 100644 --- a/net/xfrm/xfrm_device.c +++ b/net/xfrm/xfrm_device.c @@ -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) && diff --git a/net/xfrm/xfrm_state.c b/net/xfrm/xfrm_state.c index 9c101be250ee..6f98c5c1a823 100644 --- a/net/xfrm/xfrm_state.c +++ b/net/xfrm/xfrm_state.c @@ -790,20 +790,28 @@ EXPORT_SYMBOL_GPL(xfrm_dev_state_delete); void xfrm_dev_state_free(struct xfrm_state *x) { struct xfrm_dev_offload *xso = &x->xso; - struct net_device *dev = READ_ONCE(xso->dev); + struct net_device *dev; - if (dev && dev->xfrmdev_ops) { - spin_lock_bh(&xfrm_state_dev_gc_lock); - if (!hlist_unhashed(&x->dev_gclist)) - hlist_del(&x->dev_gclist); - spin_unlock_bh(&xfrm_state_dev_gc_lock); + if (!READ_ONCE(xso->dev)) + return; - if (dev->xfrmdev_ops->xdo_dev_state_free) - dev->xfrmdev_ops->xdo_dev_state_free(dev, x); - WRITE_ONCE(xso->dev, NULL); - xso->type = XFRM_DEV_OFFLOAD_UNSPECIFIED; - netdev_put(dev, &xso->dev_tracker); + spin_lock_bh(&x->lock); + spin_lock(&xfrm_state_dev_gc_lock); + dev = xso->dev; + if (!dev || !dev->xfrmdev_ops) { + spin_unlock(&xfrm_state_dev_gc_lock); + spin_unlock_bh(&x->lock); + return; } + if (!hlist_unhashed(&x->dev_gclist)) + hlist_del(&x->dev_gclist); + WRITE_ONCE(xso->dev, NULL); + spin_unlock(&xfrm_state_dev_gc_lock); + spin_unlock_bh(&x->lock); + + if (dev->xfrmdev_ops->xdo_dev_state_free) + dev->xfrmdev_ops->xdo_dev_state_free(dev, x); + netdev_put(dev, &xso->dev_tracker); } #endif @@ -974,6 +982,7 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali struct hlist_node *tmp; struct xfrm_dev_offload *xso; int i, err = 0, cnt = 0; + HLIST_HEAD(flush_list); spin_lock_bh(&net->xfrm.xfrm_state_lock); err = xfrm_dev_state_flush_secctx_check(net, dev, task_valid); @@ -1012,21 +1021,29 @@ int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_vali mutex_lock(&xfrm_state_gc_mutex); spin_lock_bh(&xfrm_state_dev_gc_lock); -restart_gc: hlist_for_each_entry_safe(x, tmp, &xfrm_state_dev_gc_list, dev_gclist) { xso = &x->xso; if (xso->dev == dev) { - spin_unlock_bh(&xfrm_state_dev_gc_lock); - xfrm_dev_state_free(x); - spin_lock_bh(&xfrm_state_dev_gc_lock); - goto restart_gc; + if (!refcount_inc_not_zero(&x->refcnt)) + continue; + hlist_del_init(&x->dev_gclist); + /* xfrm_dev_state_free() may consume dev_gclist. The + * reference prevents state GC from using gclist until + * this flush removes it and drops the reference. + */ + hlist_add_head(&x->gclist, &flush_list); } - } spin_unlock_bh(&xfrm_state_dev_gc_lock); mutex_unlock(&xfrm_state_gc_mutex); + hlist_for_each_entry_safe(x, tmp, &flush_list, gclist) { + hlist_del_init(&x->gclist); + xfrm_dev_state_free(x); + xfrm_state_put(x); + } + xfrm_flush_gc(); return err; -- 2.53.0 From: Jianbo Liu 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.") Signed-off-by: Jianbo Liu Reviewed-by: Carolina Jubran Signed-off-by: Steffen Klassert --- net/xfrm/xfrm_state.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/net/xfrm/xfrm_state.c b/net/xfrm/xfrm_state.c index 6f98c5c1a823..92c3631a43bf 100644 --- a/net/xfrm/xfrm_state.c +++ b/net/xfrm/xfrm_state.c @@ -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); -- 2.53.0 From: Jianbo Liu 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. Link: https://lore.kernel.org/netdev/aqfZNeR58HLm2x1o@secunet.com/ Signed-off-by: Jianbo Liu Reviewed-by: Carolina Jubran Signed-off-by: Steffen Klassert --- net/xfrm/xfrm_state.c | 5 ----- 1 file changed, 5 deletions(-) diff --git a/net/xfrm/xfrm_state.c b/net/xfrm/xfrm_state.c index 92c3631a43bf..d48c88f2df64 100644 --- a/net/xfrm/xfrm_state.c +++ b/net/xfrm/xfrm_state.c @@ -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(); -- 2.53.0 From: Jianbo Liu 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") Signed-off-by: Jianbo Liu Reviewed-by: Carolina Jubran Signed-off-by: Steffen Klassert --- include/net/xfrm.h | 12 ++++++ net/xfrm/xfrm_state.c | 87 +++++++++++++++++++++++++++++++++++++++---- net/xfrm/xfrm_user.c | 45 ++++++++++++++++++++-- 3 files changed, 133 insertions(+), 11 deletions(-) diff --git a/include/net/xfrm.h b/include/net/xfrm.h index cd37aa69c9ac..47aae21ea1cb 100644 --- a/include/net/xfrm.h +++ b/include/net/xfrm.h @@ -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); diff --git a/net/xfrm/xfrm_state.c b/net/xfrm/xfrm_state.c index d48c88f2df64..d7b00be32203 100644 --- a/net/xfrm/xfrm_state.c +++ b/net/xfrm/xfrm_state.c @@ -2405,15 +2405,28 @@ EXPORT_SYMBOL(xfrm_state_check_expire); void xfrm_state_update_stats(struct net *net) { + struct xfrm_state_walk_batch batch; + struct xfrm_state_walk walk; struct xfrm_state *x; - int i; + unsigned int i; + bool done; - spin_lock_bh(&net->xfrm.xfrm_state_lock); - for (i = 0; i <= net->xfrm.state_hmask; i++) { - hlist_for_each_entry(x, xfrm_state_deref_prot(net->xfrm.state_bydst, net) + i, bydst) - xfrm_dev_state_update_stats(x); - } - spin_unlock_bh(&net->xfrm.xfrm_state_lock); + xfrm_state_walk_init(&walk, 0, NULL); + do { + done = xfrm_state_walk_batch(net, &walk, &batch); + for (i = 0; i < batch.count; i++) { + x = batch.states[i]; + if (READ_ONCE(x->xso.dev)) { + spin_lock_bh(&x->lock); + if (x->km.state != XFRM_STATE_DEAD) + xfrm_dev_state_update_stats(x); + spin_unlock_bh(&x->lock); + } + xfrm_state_put(x); + } + cond_resched(); + } while (!done); + xfrm_state_walk_done(&walk, net); } struct xfrm_state * @@ -2837,6 +2850,66 @@ int xfrm_state_walk(struct net *net, struct xfrm_state_walk *walk, } EXPORT_SYMBOL(xfrm_state_walk); +bool xfrm_state_walk_batch(struct net *net, struct xfrm_state_walk *walk, + struct xfrm_state_walk_batch *batch) +{ + struct xfrm_state_walk *x; + struct xfrm_state *state; + unsigned int visited = 0; + bool done = true; + + batch->count = 0; + if (walk->seq != 0 && list_empty(&walk->all)) + return true; + + spin_lock_bh(&net->xfrm.xfrm_state_lock); + if (list_empty(&walk->all)) + x = list_first_entry(&net->xfrm.state_all, + struct xfrm_state_walk, all); + else + x = list_first_entry(&walk->all, struct xfrm_state_walk, all); + list_for_each_entry_from(x, &net->xfrm.state_all, all) { + /* Callers recheck state under x->lock before processing. */ + if (data_race(READ_ONCE(x->state)) == XFRM_STATE_DEAD) + continue; + if (visited++ == ARRAY_SIZE(batch->states)) { + list_move_tail(&walk->all, &x->all); + done = false; + goto out; + } + state = container_of(x, struct xfrm_state, km); + if (!xfrm_id_proto_match(state->id.proto, walk->proto)) + continue; + if (!__xfrm_state_filter_match(state, walk->filter)) + continue; + xfrm_state_hold(state); + batch->states[batch->count++] = state; + } + list_del_init(&walk->all); +out: + walk->seq = 1; + spin_unlock_bh(&net->xfrm.xfrm_state_lock); + return done; +} +EXPORT_SYMBOL(xfrm_state_walk_batch); + +bool xfrm_state_walk_rewind(struct xfrm_state_walk *walk, struct xfrm_state *x) +{ + struct net *net = xs_net(x); + bool linked; + + lockdep_assert_held(&x->lock); + + spin_lock(&net->xfrm.xfrm_state_lock); + linked = !hlist_unhashed(&x->bydst); + if (linked) + list_move_tail(&walk->all, &x->km.all); + spin_unlock(&net->xfrm.xfrm_state_lock); + + return linked; +} +EXPORT_SYMBOL(xfrm_state_walk_rewind); + void xfrm_state_walk_init(struct xfrm_state_walk *walk, u8 proto, struct xfrm_address_filter *filter) { diff --git a/net/xfrm/xfrm_user.c b/net/xfrm/xfrm_user.c index 217f65faa2bd..94f73349d22d 100644 --- a/net/xfrm/xfrm_user.c +++ b/net/xfrm/xfrm_user.c @@ -1181,8 +1181,6 @@ static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) memcpy(&p->id, &x->id, sizeof(p->id)); memcpy(&p->sel, &x->sel, sizeof(p->sel)); memcpy(&p->lft, &x->lft, sizeof(p->lft)); - if (x->xso.dev) - xfrm_dev_state_update_stats(x); memcpy(&p->curlft, &x->curlft, sizeof(p->curlft)); put_unaligned(x->stats.replay_window, &p->stats.replay_window); put_unaligned(x->stats.replay, &p->stats.replay); @@ -1566,11 +1564,34 @@ static int xfrm_dump_sa_done(struct netlink_callback *cb) return 0; } +static int refresh_and_dump_state(struct xfrm_state_walk *walk, + struct xfrm_state *x, + struct xfrm_dump_info *info) +{ + int err = 0; + + spin_lock_bh(&x->lock); + if (x->km.state != XFRM_STATE_DEAD) { + xfrm_dev_state_update_stats(x); + err = dump_one_state(x, 0, info); + if (err && !xfrm_state_walk_rewind(walk, x)) + err = 0; + } + spin_unlock_bh(&x->lock); + + return err; +} + static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1]; + struct xfrm_state_walk_batch batch; struct xfrm_dump_info info; + struct xfrm_state *x; + unsigned int i; + int err = 0; + bool done; BUILD_BUG_ON(sizeof(struct xfrm_state_walk) > sizeof(cb->args) - sizeof(cb->args[0])); @@ -1584,7 +1605,6 @@ static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb) struct nlattr *attrs[XFRMA_MAX+1]; struct xfrm_address_filter *filter = NULL; u8 proto = 0; - int err; err = nlmsg_parse_deprecated(cb->nlh, 0, attrs, XFRMA_MAX, xfrma_policy, cb->extack); @@ -1614,7 +1634,16 @@ static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb) cb->args[0] = 1; } - (void) xfrm_state_walk(net, walk, dump_one_state, &info); + do { + done = xfrm_state_walk_batch(net, walk, &batch); + for (i = 0; i < batch.count; i++) { + x = batch.states[i]; + if (!err) + err = refresh_and_dump_state(walk, x, &info); + xfrm_state_put(x); + } + cond_resched(); + } while (!done && !err); return skb->len; } @@ -1635,7 +1664,10 @@ static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb, info.nlmsg_seq = seq; info.nlmsg_flags = 0; + spin_lock_bh(&x->lock); + xfrm_dev_state_update_stats(x); err = dump_one_state(x, 0, &info); + spin_unlock_bh(&x->lock); if (err) { kfree_skb(skb); return ERR_PTR(err); @@ -3973,6 +4005,8 @@ static int build_expire(struct sk_buff *skb, struct xfrm_state *x, const struct struct nlmsghdr *nlh; int err; + xfrm_dev_state_update_stats(x); + nlh = nlmsg_put(skb, c->portid, 0, XFRM_MSG_EXPIRE, sizeof(*ue), 0); if (nlh == NULL) return -EMSGSIZE; @@ -4170,7 +4204,10 @@ static int xfrm_notify_sa(struct xfrm_state *x, const struct km_event *c) p = nla_data(attr); } + spin_lock_bh(&x->lock); + xfrm_dev_state_update_stats(x); err = copy_to_user_state_extra(x, p, skb); + spin_unlock_bh(&x->lock); if (err) goto out_free_skb; -- 2.53.0