Re: [PATCH] cgroup: prevent use-after-free during namespace root replacement

From: Tejun Heo

Date: Wed Sep 23 2026 - 19:59:44 EST


Hello, Jeremy.

On Wed, Sep 23, 2026 at 08:49:36PM +0000, Jeremy Jean wrote:
> copy_cgroup_ns() pins the creator's css_set, but cgroup_post_fork()
> replaces root_cset and releases the namespace's reference to that css_set
> after the child is visible to pid and pidfd lookups. A task joining the
> new namespace can race with this replacement and access the original
> css_set or its cgroup after they are freed.
...
> Keep the initial root pinned until namespace destruction, taking a
> separate reference to the final root only when the roots differ.

The underlying problem is that the swap is observable at all. Pinning the
initial css_set keeps whatever a reader loaded alive, but then a namespace
created with CLONE_INTO_CGROUP holds a css_set that isn't its root, and
through it the parent's cgroups, for its whole lifetime, and readers like
current_cgns_cgroup_dfl() keep assuming root_cset never changes.

Can we instead make root_cset final before anything can reach the
namespace? At cgroup_can_fork(), kargs->cset is already what the child
will be attached to (cgroup_threadgroup_rwsem is held through
cgroup_post_fork()), the child isn't hashed and the pidfd isn't installed,
so the only way in is the ns tree. Something like:

- copy_cgroup_ns() skips ns_tree_add() on the fork path.
- cgroup_can_fork() updates root_cset from kargs->cset and then calls
ns_tree_add().
- cgroup_post_fork() drops the swap.
- free_cgroup_ns() calls ns_tree_remove() only if the namespace made it
into the tree.

Once visible, root_cset never changes and none of the readers need to
change. Kernels before the ns tree only expose the namespace through the
pid hash and the pidfd, so the backport would only need to move the
update.

Thanks.

--
tejun