Netdev List
 help / color / mirror / Atom feed
* [BUG] xfrm: a socket policy cloned for a TCP child leaks when cloning the second policy fails
@ 2026-11-19  3:04 Kyuwon Cho
  2026-11-23  3:38 ` netdev-bot+sashiko
  0 siblings, 1 reply; 2+ messages in thread
From: Kyuwon Cho @ 2026-11-19  3:04 UTC (permalink / raw)
  To: Steffen Klassert, Herbert Xu
  Cc: Eric Dumazet, Kuniyuki Iwashima, David S. Miller, Jakub Kicinski,
	Paolo Abeni, Simon Horman, Alexei Starovoitov, Josef Bacik,
	netdev, ipsec, linux-kernel

[-- Attachment #1: Type: text/plain, Size: 3644 bytes --]

Hi Steffen, Herbert,

While testing v7.4-rc3 with an LLM-guided test generator that we are
developing as a research prototype, we found that a TCP listener with
socket policies in both directions leaks one xfrm policy when cloning
its second policy for a new child fails. The leaked policy stays on
net->xfrm.policy_all, and the network namespace teardown warns:

  WARNING: net/xfrm/xfrm_policy.c:4303 at xfrm_policy_fini+0x24c/0x300, CPU#0: kworker/u8:4/88
  RIP: 0010:xfrm_policy_fini (net/xfrm/xfrm_policy.c:4303)
  Call Trace:
   <TASK>
   xfrm_net_exit (net/xfrm/xfrm_policy.c:4372)
   ops_undo_list (net/core/net_namespace.c:200 net/core/net_namespace.c:253)
   cleanup_net (net/core/net_namespace.c:713)
   process_one_work (kernel/workqueue.c:3495)
   worker_thread (kernel/workqueue.c:3578 kernel/workqueue.c:3659)
   kthread (kernel/kthread.c:436)
   ret_from_fork (arch/x86/kernel/process.c:158)
   ret_from_fork_asm (arch/x86/entry/entry_64.S:245)
   </TASK>

__xfrm_sk_clone_policy() clones the parent's policies into the new
socket one direction at a time and stops at the first failure:

	for (i = 0; i < 2; i++) {
		p = rcu_dereference(osk->sk_policy[i]);
		if (p) {
			np = clone_policy(p, i);
			if (unlikely(!np)) {
				ret = -ENOMEM;
				break;
			}
			rcu_assign_pointer(sk->sk_policy[i], np);
		}
	}

When clone_policy() fails for sk_policy[1], sk_policy[0] already holds
a new policy that is linked on net->xfrm.policy_all. sk_clone() then
takes its "free" path, which treats the socket as a raw copy of the
parent:

	if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) {
		...
		goto free;
	}
	...
free:
	/* It is still raw copy of parent, so invalidate
	 * destructor and make plain sk_free()
	 */
	newsk->sk_destruct = NULL;

Socket policies are only freed by xfrm_sk_free_policy() from
inet_csk_destroy_sock() and sk_common_release(), so nothing frees the
clone of sk_policy[0]. xfrm_policy_flush() skips socket policies, and
xfrm_policy_fini() finds it when the namespace goes away. The leak
needs one allocation failure during the handshake, in softirq context.

Josef and Alexei's "[PATCH net] net: free the policies if a socket's
clone fails late" (2026-10-17) frees the policies when
bpf_sk_storage_clone() fails, and its message explains why the "free"
label cannot do that for every user: after a failed filter charge,
sk_policy[] still holds the parent's pointers. A partial clone leaves
the same mix, a new sk_policy[0] next to the parent's sk_policy[1], so
it is not covered there.

The reproducer runs as root. In a new network namespace per iteration,
it sets IP_XFRM_POLICY in both directions on a loopback TCP listener
and completes one handshake while failslab fails one slab allocation
(probability 5%, at most one failure). On an x86_64 QEMU guest with 2
vCPUs and KASAN (gcc 13.3), the warning shows up in every run.
IP_XFRM_POLICY itself only needs CAP_NET_ADMIN in the user namespace
that owns the network namespace.

The loop and its early exit come from d188ba86dd07 ("xfrm: add rcu
protection to sk->sk_policy[]").

Checked against v7.4-rc3 (aebb72744764); xfrm_policy.c and sock.c are
the same in net (2a324a58a084).

A patch is attached (git format-patch against v7.4-rc3; it applies to
the ipsec tree):

  0001-xfrm-free-the-policies-already-cloned-when-a-socket-.patch

It deletes the policies that __xfrm_sk_clone_policy() already cloned
before it returns the error. It was written with LLM assistance; we
reviewed and tested it. With it, the reproducer no longer triggers the
report.

The reproducer (repro.c), the kernel config and the patch are attached.

Thanks,
Kyuwon Cho

[-- Attachment #2: repro.c --]
[-- Type: text/plain, Size: 2767 bytes --]

// WARNING in xfrm_policy_fini: a socket policy cloned for an accepted TCP child is leaked when cloning the
// listener's second policy fails.
// Each iteration, in a new network namespace, sets an IP_XFRM_POLICY in both directions on a TCP listener and
// completes one loopback handshake while failslab fails one slab allocation (5% per allocation, at most one).
// When the failed allocation is clone_policy() for sk_policy[1], __xfrm_sk_clone_policy() returns -ENOMEM with
// the clone of sk_policy[0] already in the child; sk_clone() frees the child without it, the policy stays on
// net->xfrm.policy_all, and the namespace teardown warns.
// Runs as root (failslab through debugfs).
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <fcntl.h>
#include <linux/xfrm.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sched.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>

#ifndef IP_XFRM_POLICY
#define IP_XFRM_POLICY 17
#endif

static void failslab(const char *knob, const char *val)
{
	char path[96];
	int fd;

	snprintf(path, sizeof(path), "/sys/kernel/debug/failslab/%s", knob);
	fd = open(path, O_WRONLY);
	if (fd < 0 || write(fd, val, strlen(val)) < 0)
		perror(path);
	close(fd);
}

static void one_handshake(int port)
{
	struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(port),
				 .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
	struct ifreq ifr = { .ifr_name = "lo", .ifr_flags = IFF_UP };
	int ls, c, s;

	unshare(CLONE_NEWNET);
	s = socket(AF_INET, SOCK_DGRAM, 0);
	ioctl(s, SIOCSIFFLAGS, &ifr);
	close(s);

	ls = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
	bind(ls, (struct sockaddr *)&a, sizeof(a));
	listen(ls, 16);
	for (int dir = 0; dir < 2; dir++) {
		struct xfrm_userpolicy_info pi = { .sel.family = AF_INET, .dir = dir, .action = XFRM_POLICY_ALLOW,
			.lft = { XFRM_INF, XFRM_INF, XFRM_INF, XFRM_INF } };

		if (setsockopt(ls, SOL_IP, IP_XFRM_POLICY, &pi, sizeof(pi)))
			perror("IP_XFRM_POLICY");
	}

	failslab("times", "1");		/* fail at most one allocation from here */
	c = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
	connect(c, (struct sockaddr *)&a, sizeof(a));
	s = accept(ls, NULL, NULL);
	failslab("times", "0");
	close(s);
	close(c);
	close(ls);
}

int main(void)
{
	mount("debugfs", "/sys/kernel/debug", "debugfs", 0, NULL);
	failslab("ignore-gfp-wait", "0");
	failslab("task-filter", "0");
	failslab("interval", "1");
	failslab("probability", "5");
	for (int k = 1; k <= 120; k++) {
		pid_t pid = fork();

		if (!pid) {
			one_handshake(20000 + k);
			_exit(0);
		}
		waitpid(pid, NULL, 0);
	}
	sleep(40);			/* the namespaces are torn down asynchronously */
	printf("done\n");
	return 0;
}

[-- Attachment #3: config.gz --]
[-- Type: application/gzip, Size: 38966 bytes --]

[-- Attachment #4: 0001-xfrm-free-the-policies-already-cloned-when-a-socket-.patch --]
[-- Type: text/plain, Size: 1722 bytes --]

>From 84f048c2bd57b87dcf83233cf59c4ba1fee855b1 Mon Sep 17 00:00:00 2001
From: Kyuwon Cho <kyuwoncho18@gmail.com>
Date: Thu, 19 Nov 2026 11:36:52 +0900
Subject: [PATCH ipsec] xfrm: free the policies already cloned when a socket
 clone fails

__xfrm_sk_clone_policy() clones the parent's socket policies one
direction at a time and returns -ENOMEM at the first failure. If the
policy for the second direction cannot be cloned, the clone of the
first one is already linked on net->xfrm.policy_all. sk_clone() then
frees the new socket as a raw copy of the parent, without
xfrm_sk_free_policy(), and the policy is leaked until the network
namespace goes away:

  WARNING: net/xfrm/xfrm_policy.c:4303 at xfrm_policy_fini+0x24c/0x300
  Call Trace:
   xfrm_net_exit (net/xfrm/xfrm_policy.c:4372)
   ops_undo_list (net/core/net_namespace.c:253)
   cleanup_net (net/core/net_namespace.c:713)

Delete the policies cloned so far before returning the error.

Fixes: d188ba86dd07 ("xfrm: add rcu protection to sk->sk_policy[]")
Signed-off-by: Kyuwon Cho <kyuwoncho18@gmail.com>
---
 net/xfrm/xfrm_policy.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/net/xfrm/xfrm_policy.c b/net/xfrm/xfrm_policy.c
index cea6842e6454..c6d5c7582af7 100644
--- a/net/xfrm/xfrm_policy.c
+++ b/net/xfrm/xfrm_policy.c
@@ -2460,6 +2460,13 @@ int __xfrm_sk_clone_policy(struct sock *sk, const struct sock *osk)
 			rcu_assign_pointer(sk->sk_policy[i], np);
 		}
 	}
+	while (unlikely(ret) && i--) {
+		np = rcu_dereference(sk->sk_policy[i]);
+		if (rcu_access_pointer(osk->sk_policy[i])) {
+			RCU_INIT_POINTER(sk->sk_policy[i], NULL);
+			xfrm_policy_delete(np, XFRM_POLICY_MAX + i);
+		}
+	}
 	rcu_read_unlock();
 	return ret;
 }
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 2+ messages in thread

* Re: [BUG] xfrm: a socket policy cloned for a TCP child leaks when cloning the second policy fails
  2026-11-19  3:04 [BUG] xfrm: a socket policy cloned for a TCP child leaks when cloning the second policy fails Kyuwon Cho
@ 2026-11-23  3:38 ` netdev-bot+sashiko
  0 siblings, 0 replies; 2+ messages in thread
From: netdev-bot+sashiko @ 2026-11-23  3:38 UTC (permalink / raw)
  To: kyuwoncho18
  Cc: steffen.klassert, herbert, edumazet, kuniyu, davem, kuba, pabeni,
	horms, ast, josef, netdev, ipsec, linux-kernel

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

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

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

- [High] The new rollback loop in __xfrm_sk_clone_policy()
  (net/xfrm/xfrm_policy.c:2463-2469) checks the parent's slot,…
- [Low] The commit message is the raw MIME bug-report email, not a
  changelog.
- [Low] The commit message says a partial clone 'leaves the same mix, a
  new sk_policy[0] next to the parent's sk_policy[1]'.

--

xfrm: a socket policy cloned for a TCP child leaks when cloning the second policy fails

This patch adds a rollback loop to __xfrm_sk_clone_policy(). When a later
clone_policy() call fails, the loop deletes the policies already cloned into
the child socket. The goal is to stop a socket policy leaking on
net->xfrm.policy_all, which triggers a warning in xfrm_policy_fini() when the
network namespace is torn down.

> --===============7878978291613295449==
> Content-Type: text/plain; charset="us-ascii"
> Content-Transfer-Encoding: 7bit
>
> Hi Steffen, Herbert,

[Severity: Low]
This isn't a bug, but the commit message is the raw MIME bug report, not
a changelog. It contains:

- MIME boundary lines and Content-Type headers
- the cover letter greeting and sign-off
- the full repro.c
- a base64 gzip of the kernel config
- an mbox-escaped ">>From 84f048c2..." line before the actual patch
  description

The commit subject is the bug report subject. The patch's own subject,
"xfrm: free the policies already cloned when a socket clone fails", only
appears inside the attachment.

Could this be resent as an inline patch with its own subject and
description? The reproducer and config could go below the --- line, or be
linked.

[ ... ]

> Socket policies are only freed by xfrm_sk_free_policy() from
> inet_csk_destroy_sock() and sk_common_release(), so nothing frees the
> clone of sk_policy[0].

[Severity: Low]
This list leaves out mptcp (net/mptcp/protocol.c) and tcp_v4_send_reset().
tcp_v4_send_reset() already frees partial clones itself:

net/ipv4/tcp_ipv4.c:tcp_v4_send_reset() {
    ...
		xfrm_sk_clone_policy(ctl_sk, sk);
    ...
	xfrm_sk_free_policy(ctl_sk);
    ...
}

With this patch, partial clones for that caller are also freed inside the
callee. Should the changelog mention that?

[ ... ]

> A partial clone leaves
> the same mix, a new sk_policy[0] next to the parent's sk_policy[1], so
> it is not covered there.

Is this accurate? xfrm_sk_clone_policy() clears the child's slots before
it calls __xfrm_sk_clone_policy():

include/net/xfrm.h:xfrm_sk_clone_policy() {
	if (!sk_fullsock(osk))
		return 0;
	sk->sk_policy[0] = NULL;
	sk->sk_policy[1] = NULL;
	...
}

So after a failure at i == 1, the child holds its own clone in slot 0 and
NULL in slot 1, not the parent's pointer.

The parent's pointers survive in newsk only on the !is_charged path in
sk_clone(). On that path xfrm_sk_clone_policy() is never called, because of
short-circuit evaluation:

	if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) {

> diff --git a/net/xfrm/xfrm_policy.c b/net/xfrm/xfrm_policy.c
> index cea6842e6454d..c6d5c7582af73 100644
> --- a/net/xfrm/xfrm_policy.c
> +++ b/net/xfrm/xfrm_policy.c
> @@ -2460,6 +2460,13 @@ int __xfrm_sk_clone_policy(struct sock *sk, const struct sock *osk)
>  			rcu_assign_pointer(sk->sk_policy[i], np);
>  		}
>  	}
> +	while (unlikely(ret) && i--) {
> +		np = rcu_dereference(sk->sk_policy[i]);
> +		if (rcu_access_pointer(osk->sk_policy[i])) {
> +			RCU_INIT_POINTER(sk->sk_policy[i], NULL);
> +			xfrm_policy_delete(np, XFRM_POLICY_MAX + i);
> +		}
> +	}

[Severity: High]
Should this test np instead of reading osk->sk_policy[i] a second time?

The parent slot is read once in the clone loop with
rcu_dereference(osk->sk_policy[i]) and again here. Nothing keeps the two
reads equal.

The listener is not locked on this path. tcp_v4_rcv()->tcp_check_req()
runs on the listener without bh_lock_sock(), and tcp_v4_send_reset() clones
from sk into ctl_sk. Meanwhile, setsockopt(IP_XFRM_POLICY) can change the
parent slots through do_ip_setsockopt()->xfrm_user_policy()->
xfrm_sk_policy_insert(), which only holds net->xfrm.xfrm_policy_lock.

Could this pass NULL to xfrm_policy_delete()? Suppose the listener has only
sk_policy[1] set:

clone loop, i == 0:  osk->sk_policy[0] == NULL, child slot 0 stays NULL
clone loop, i == 1:  clone_policy() fails, ret = -ENOMEM
                     concurrent setsockopt installs a dir 0 policy
cleanup, i == 0:     np == NULL, osk->sk_policy[0] != NULL
                     xfrm_policy_delete(NULL, XFRM_POLICY_MAX)

xfrm_policy_delete() dereferences pol straight away:

	struct net *net = xp_net(pol);

	spin_lock_bh(&net->xfrm.xfrm_policy_lock);

On the sk_clone() path, this would oops in softirq context.

The opposite ordering seems to leave the original leak in place. Suppose
both parent slots are set: slot 0 is cloned and linked on
net->xfrm.policy_all, and the slot 1 clone fails. A concurrent setsockopt
with a NULL optval and optlen of 0 then clears both parent slots in
xfrm_user_policy():

	if (sockptr_is_null(optval) && !optlen) {
		xfrm_sk_policy_insert(sk, XFRM_POLICY_IN, NULL);
		xfrm_sk_policy_insert(sk, XFRM_POLICY_OUT, NULL);

The cleanup sees osk->sk_policy[0] == NULL and skips the real clone.
sk_clone() then takes its free path, and the xfrm_policy_fini() warning can
still fire.

xfrm_sk_clone_policy() already sets the child slots to NULL before cloning.
Would checking "if (np)" on the child pointer avoid both cases?

>  	rcu_read_unlock();
>  	return ret;
>  }

-- 
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/179505710269.3511679.8893709762919027206%40gmail.com

^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2026-11-23  3:39 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-19  3:04 [BUG] xfrm: a socket policy cloned for a TCP child leaks when cloning the second policy fails Kyuwon Cho
2026-11-23  3:38 ` netdev-bot+sashiko

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox