Skip to contentSkip to conversation

Namespace for namespace roots

RFC PATCH Superseded Jarkko Sakkinen 3 participants 33 messages Nov 17 – Nov 18

Subsystems (27)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover Namespace for namespace roots

OVERVIEW
========

The problem that root namespaces try to resolve is starting a container from a root mount tree that is pre-populated before any process is allowed to run, without inheriting any host mount-tree ancestors.

Work on this feature started originally in 2025 from David Howells' container object patch set [1], but I turned container objects into a namespace of namespace roots and built a new implementation around this premise.

In early 2026, the patch set was left to gather dust in my kernel tree [2]. Then, the other day I saw [3] as was shocked by its over the top complexity and thus, here we are.

Not doubling the number of container frameworks inside Linux kernel is at least a benefit over container object based solutions. Parallel plumbing is an inherent flaw of container objects, and it directly affects on development and maintenance cost of container runtimes.

Also, thanks to better scoped implementation surface, verifying rootns correctness is factors easier than with container objects, and even my early kselftest is meaningful. We know what and where we are testing, which is always great.

Finally, it is more compatible with pre-existing container tooling whereas container objects would have much higher cost.

[1] https://lore.kernel.org/all/155059610368.17079.2220554006494174417.stgit@warthog.procyon.org.uk/
[2] https://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd.git/log/?h=rootns
[3] https://lore.kernel.org/linux-fsdevel/[email protected]/

IMPLEMENTATION
==============

rootns_create() allocates a rootns object backed by a pollable anonymous inode fd, pinning dedicated empty mount (CLONE_EMPTY_MNTNS) and PID namespaces along with any optional namespaces selected in flags.

Before entry, a manager prepares the mount tree through the control fd:
FSCONFIG_SET_ROOTNS binds a newly opened fs_context to the target rootns, and move_mount(..., MOVE_MOUNT_T_ROOTNS_ROOT) installs "/" onto the nullfs root once and attaches relative submounts beneath it.

rootns_enter() forks a child directly into the rootns credentials, nsproxy, and root path without mutating the caller in place. The first entrant becomes PID 1; once it exits and zap_pid_ns_processes() reaps all members, poll() reports EPOLLHUP and rootns_wait() returns init's status and rusage. rootns_kill() walks pid_ns->idr under RCU to signal member thread groups.

Namespaces allocated by member tasks inherit the owning rootns ID in __ns_common_init() so intra-rootns clone(), unshare(), open_tree(), and setns() work while foreign setns() calls fail with -EPERM.

Cc Alexander Viro <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Ben Segall <[email protected]>
Cc Christian Brauner <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc David Howells <[email protected]>
Cc Davidlohr Bueso <[email protected]>
Cc Dietmar Eggemann <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Jan Kara <[email protected]>
Cc Jarkko Sakkinen <[email protected]>
Cc Jonathan Corbet <[email protected]>
Cc Juri Lelli <[email protected]>
Cc Kees Cook <[email protected]>
Cc K Prateek Nayak <[email protected]>
Cc "Liam R. Howlett" <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Manfred Spraul <[email protected]>
Cc Mel Gorman <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Neal Gompa <[email protected]>
Cc Paul Moore <[email protected]>
Cc Pavel Tikhomirov <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Serge Hallyn <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Valentin Schneider <[email protected]>
Cc Vincent Guittot <[email protected]>
Cc Vlastimil Babka <[email protected]>

Jarkko Sakkinen (13):
nsproxy: Pass nsproxy to create_new_namespaces()
rootns: Add core infrastructure for root namespaces
rootns: Track init lifecycle via copy_process() and pid_namespace
rootns: Add rootns_create() system call
rootns: Add rootns_wait() system call
rootns: Add rootns_kill() system call
rootns: Add rootns_enter() system call
fs: Support FSCONFIG_SET_ROOTNS in fsconfig()
fs: Support installing rootns mount trees via move_mount()
arch: Wire up rootns system calls
docs: Document root namespace uAPI
selftests/rootns: Add root namespace test suite
MAINTAINERS: Add entry for ROOT NAMESPACE

 Documentation/userspace-api/index.rst       |    1 +
 Documentation/userspace-api/rootns.rst      |   35 +
 MAINTAINERS                                 |   11 +
 arch/alpha/kernel/syscalls/syscall.tbl      |    4 +
 arch/arm/tools/syscall.tbl                  |    4 +
 arch/arm64/tools/syscall_32.tbl             |    4 +
 arch/m68k/kernel/syscalls/syscall.tbl       |    4 +
 arch/microblaze/kernel/syscalls/syscall.tbl |    4 +
 arch/mips/kernel/syscalls/syscall_n32.tbl   |    4 +
 arch/mips/kernel/syscalls/syscall_n64.tbl   |    4 +
 arch/mips/kernel/syscalls/syscall_o32.tbl   |    4 +
 arch/parisc/kernel/syscalls/syscall.tbl     |    4 +
 arch/powerpc/kernel/syscalls/syscall.tbl    |    4 +
 arch/s390/kernel/syscalls/syscall.tbl       |    4 +
 arch/sh/kernel/syscalls/syscall.tbl         |    4 +
 arch/sparc/kernel/syscalls/syscall.tbl      |    4 +
 arch/x86/entry/syscalls/syscall_32.tbl      |    4 +
 arch/x86/entry/syscalls/syscall_64.tbl      |    4 +
 arch/xtensa/kernel/syscalls/syscall.tbl     |    4 +
 fs/fsopen.c                                 |   74 +-
 fs/namespace.c                              |  176 ++-
 fs/proc/root.c                              |   13 +
 include/linux/compat.h                      |    4 +
 include/linux/cred.h                        |    4 +-
 include/linux/fs_context.h                  |    3 +
 include/linux/ns/ns_common_types.h          |    4 +
 include/linux/nsproxy.h                     |   27 +-
 include/linux/pid_namespace.h               |    4 +
 include/linux/rootns.h                      |   87 ++
 include/linux/sched/task.h                  |    4 +
 include/linux/syscalls.h                    |    5 +
 include/uapi/asm-generic/unistd.h           |   12 +-
 include/uapi/linux/mount.h                  |    4 +-
 include/uapi/linux/rootns.h                 |   38 +
 init/Kconfig                                |    9 +
 ipc/mqueue.c                                |   12 +
 kernel/Makefile                             |    2 +
 kernel/cred.c                               |   70 +-
 kernel/fork.c                               |   29 +-
 kernel/nscommon.c                           |    8 +
 kernel/nsproxy.c                            |   49 +-
 kernel/pid_namespace.c                      |    2 +
 kernel/rootns.c                             |  599 +++++++++
 kernel/sys_ni.c                             |    7 +
 scripts/syscall.tbl                         |    4 +
 tools/testing/selftests/Makefile            |    1 +
 tools/testing/selftests/rootns/.gitignore   |    2 +
 tools/testing/selftests/rootns/Makefile     |    5 +
 tools/testing/selftests/rootns/config       |    9 +
 tools/testing/selftests/rootns/smoke.c      | 1254 +++++++++++++++++++
 50 files changed, 2559 insertions(+), 73 deletions(-)
 create mode 100644 Documentation/userspace-api/rootns.rst
 create mode 100644 include/linux/rootns.h
 create mode 100644 include/uapi/linux/rootns.h
 create mode 100644 kernel/rootns.c
 create mode 100644 tools/testing/selftests/rootns/.gitignore
 create mode 100644 tools/testing/selftests/rootns/Makefile
 create mode 100644 tools/testing/selftests/rootns/config
 create mode 100644 tools/testing/selftests/rootns/smoke.c

--
2.47.3

#1 lore raw

RFC PATCH 1/13 nsproxy: Pass nsproxy to create_new_namespaces()

create_new_namespaces() takes a struct task_struct pointer even though it only reads tsk->nsproxy, preventing callers outside kernel/nsproxy.c from constructing a child nsproxy without mutating a task.

Expose create_new_namespaces() and pass the source struct nsproxy pointer directly so root namespace creation can allocate a detached namespace set from current->nsproxy.

---
 include/linux/nsproxy.h |  5 +++++
 kernel/nsproxy.c        | 32 ++++++++++++++++----------------
 2 files changed, 21 insertions(+), 16 deletions(-)
include/linux/nsproxy.h +5 -0
index dc2447f5f092..cacbbbe3f1ce 100644
@@ -12,6 +12,7 @@ struct ipc_namespace;
 struct pid_namespace;
 struct cgroup_namespace;
 struct fs_struct;
+struct user_namespace;
 
 /*
  * A structure to contain pointers to all per-process
@@ -92,6 +93,10 @@ static inline struct cred *nsset_cred(struct nsset *set)
  *
  */
 
+struct nsproxy *create_new_namespaces(u64 flags,
+				      struct nsproxy *ns,
+				      struct user_namespace *user_ns,
+				      struct fs_struct *new_fs);
 int copy_namespaces(u64 flags, struct task_struct *tsk);
 void switch_cred_namespaces(const struct cred *old, const struct cred *new);
 void exit_nsproxy_namespaces(struct task_struct *tsk);
kernel/nsproxy.c +16 -16
index 2dcf105e8ee2..8a3c6d4e94e2 100644
@@ -85,9 +85,10 @@ void deactivate_nsproxy(struct nsproxy *ns)
  * Return the newly created nsproxy.  Do not attach this to the task,
  * leave it to the caller to do proper locking and attach it to task.
  */
-static struct nsproxy *create_new_namespaces(u64 flags,
-	struct task_struct *tsk, struct user_namespace *user_ns,
-	struct fs_struct *new_fs)
+struct nsproxy *create_new_namespaces(u64 flags,
+				      struct nsproxy *ns,
+				      struct user_namespace *user_ns,
+				      struct fs_struct *new_fs)
 {
 	struct nsproxy *new_nsp;
 	int err;
@@ -96,52 +97,51 @@ static struct nsproxy *create_new_namespaces(u64 flags,
 	if (!new_nsp)
 		return ERR_PTR(-ENOMEM);
 
-	new_nsp->mnt_ns = copy_mnt_ns(flags, tsk->nsproxy->mnt_ns,
-				      user_ns, new_fs);
+	new_nsp->mnt_ns = copy_mnt_ns(flags, ns->mnt_ns, user_ns, new_fs);
 	if (IS_ERR(new_nsp->mnt_ns)) {
 		err = PTR_ERR(new_nsp->mnt_ns);
 		goto out_ns;
 	}
 
-	new_nsp->uts_ns = copy_utsname(flags, user_ns, tsk->nsproxy->uts_ns);
+	new_nsp->uts_ns = copy_utsname(flags, user_ns, ns->uts_ns);
 	if (IS_ERR(new_nsp->uts_ns)) {
 		err = PTR_ERR(new_nsp->uts_ns);
 		goto out_uts;
 	}
 
-	new_nsp->ipc_ns = copy_ipcs(flags, user_ns, tsk->nsproxy->ipc_ns);
+	new_nsp->ipc_ns = copy_ipcs(flags, user_ns, ns->ipc_ns);
 	if (IS_ERR(new_nsp->ipc_ns)) {
 		err = PTR_ERR(new_nsp->ipc_ns);
 		goto out_ipc;
 	}
 
 	new_nsp->pid_ns_for_children =
-		copy_pid_ns(flags, user_ns, tsk->nsproxy->pid_ns_for_children);
+		copy_pid_ns(flags, user_ns, ns->pid_ns_for_children);
 	if (IS_ERR(new_nsp->pid_ns_for_children)) {
 		err = PTR_ERR(new_nsp->pid_ns_for_children);
 		goto out_pid;
 	}
 
 	new_nsp->cgroup_ns = copy_cgroup_ns(flags, user_ns,
-					    tsk->nsproxy->cgroup_ns);
+					    ns->cgroup_ns);
 	if (IS_ERR(new_nsp->cgroup_ns)) {
 		err = PTR_ERR(new_nsp->cgroup_ns);
 		goto out_cgroup;
 	}
 
-	new_nsp->net_ns = copy_net_ns(flags, user_ns, tsk->nsproxy->net_ns);
+	new_nsp->net_ns = copy_net_ns(flags, user_ns, ns->net_ns);
 	if (IS_ERR(new_nsp->net_ns)) {
 		err = PTR_ERR(new_nsp->net_ns);
 		goto out_net;
 	}
 
 	new_nsp->time_ns_for_children = copy_time_ns(flags, user_ns,
-					tsk->nsproxy->time_ns_for_children);
+					ns->time_ns_for_children);
 	if (IS_ERR(new_nsp->time_ns_for_children)) {
 		err = PTR_ERR(new_nsp->time_ns_for_children);
 		goto out_time;
 	}
-	new_nsp->time_ns = get_time_ns(tsk->nsproxy->time_ns);
+	new_nsp->time_ns = get_time_ns(ns->time_ns);
 
 	return new_nsp;
 
@@ -192,7 +192,7 @@ int copy_namespaces(u64 flags, struct task_struct *tsk)
 		(CLONE_NEWIPC | CLONE_SYSVSEM))
 		return -EINVAL;
 
-	new_ns = create_new_namespaces(flags, tsk, user_ns, tsk->fs);
+	new_ns = create_new_namespaces(flags, tsk->nsproxy, user_ns, tsk->fs);
 	if (IS_ERR(new_ns))
 		return  PTR_ERR(new_ns);
 
@@ -231,7 +231,7 @@ int unshare_nsproxy_namespaces(unsigned long unshare_flags,
 		flags |= CLONE_EMPTY_MNTNS;
 	}
 
-	*new_nsp = create_new_namespaces(flags, current, user_ns,
+	*new_nsp = create_new_namespaces(flags, current->nsproxy, user_ns,
 					 new_fs ? new_fs : current->fs);
 	if (IS_ERR(*new_nsp)) {
 		err = PTR_ERR(*new_nsp);
@@ -289,7 +289,7 @@ int exec_task_namespaces(void)
 	if (tsk->nsproxy->time_ns_for_children == tsk->nsproxy->time_ns)
 		return 0;
 
-	new = create_new_namespaces(0, tsk, current_user_ns(), tsk->fs);
+	new = create_new_namespaces(0, tsk->nsproxy, current_user_ns(), tsk->fs);
 	if (IS_ERR(new))
 		return PTR_ERR(new);
 
@@ -356,7 +356,7 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)
 	struct task_struct *me = current;
 
 	nsset->flags = flags;
-	nsset->nsproxy = create_new_namespaces(0, me, current_user_ns(), me->fs);
+	nsset->nsproxy = create_new_namespaces(0, me->nsproxy, current_user_ns(), me->fs);
 	if (IS_ERR(nsset->nsproxy))
 		return PTR_ERR(nsset->nsproxy);
 
Signature · 1 line
2.47.3
#2 lore raw

Re: [RFC PATCH 01/13] nsproxy: Pass nsproxy to create_new_namespaces()

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

create_new_namespaces() takes a struct task_struct pointer even though it only reads tsk->nsproxy, preventing callers outside kernel/nsproxy.c from constructing a child nsproxy without mutating a task.

Expose create_new_namespaces() and pass the source struct nsproxy pointer directly so root namespace creation can allocate a detached namespace set from current->nsproxy.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw

RFC PATCH 2/13 rootns: Add core infrastructure for root namespaces

In reply to Jarkko Sakkinen

Linux namespaces can be created and entered individually, but userspace orchestrators lack a single kernel object that binds a namespace set, a root mount, and an init process behind a pollable file descriptor.

Add struct rootns, its lifecycle states, reference counting, uAPI creation flags, and anonymous inode file operations under CONFIG_ROOTNS. Drop active and passive namespace references on final release, send SIGKILL to the rootns init thread group on close when ROOTNS_KILL_ON_CLOSE is set, and report EPOLLHUP from poll() once the rootns reaches ROOTNS_DEAD.

---
 include/linux/nsproxy.h     |   3 +
 include/linux/rootns.h      |  66 ++++++++++++++++++++++
 include/uapi/linux/rootns.h |  38 +++++++++++++
 init/Kconfig                |   9 +++
 kernel/Makefile             |   2 +
 kernel/rootns.c             | 107 ++++++++++++++++++++++++++++++++++++
 6 files changed, 225 insertions(+)
 create mode 100644 include/linux/rootns.h
 create mode 100644 include/uapi/linux/rootns.h
 create mode 100644 kernel/rootns.c
include/linux/nsproxy.h +3 -0
index cacbbbe3f1ce..23cbeee6b1e4 100644
@@ -91,6 +91,9 @@ static inline struct cred *nsset_cred(struct nsset *set)
  *         * /
  *     task_unlock(task);
  *
+ *  4. Root namespace membership is carried by nsproxy and inherited by
+ *     namespaces derived from it.
+ *
  */
 
 struct nsproxy *create_new_namespaces(u64 flags,
include/linux/rootns.h new file +66 -0

66 lines not on this page · raw message

include/uapi/linux/rootns.h new file +38 -0
new file mode 100644
index 000000000000..bde89d183578
@@ -0,0 +1,38 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+/*
+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.
+ * Copyright (C) 2026 Opinsys Oy
+ */
+
+#ifndef _UAPI_LINUX_ROOTNS_H
+#define _UAPI_LINUX_ROOTNS_H
+
+/**
+ * enum rootns_flags - Flags for rootns_create()
+ * @ROOTNS_CGROUP: Create a fresh cgroup namespace instead of inheriting.
+ * @ROOTNS_UTS: Create a fresh UTS namespace instead of inheriting.
+ * @ROOTNS_IPC: Create a fresh IPC namespace instead of inheriting.
+ * @ROOTNS_USER: Create a fresh user namespace owned by the caller.
+ * @ROOTNS_NET: Create a fresh network namespace instead of inheriting.
+ * @ROOTNS_KILL_ON_CLOSE: Send %SIGKILL to rootns init on final fd release.
+ * @ROOTNS_CLOSE_ON_EXEC: Set %O_CLOEXEC on the returned control fd.
+ * @ROOTNS_ALL_NAMESPACES: Mask of all optional namespace selection flags.
+ * @ROOTNS_ALL_FLAGS: Mask of all valid flags accepted by rootns_create().
+ *
+ * Every root namespace unconditionally owns dedicated mount and PID
+ * namespaces. Optional namespace flags allocate fresh instances of the
+ * remaining namespaces instead of inheriting them from the caller.
+ */
+enum rootns_flags {
+	ROOTNS_CGROUP		= 0x00000001,
+	ROOTNS_UTS		= 0x00000002,
+	ROOTNS_IPC		= 0x00000004,
+	ROOTNS_USER		= 0x00000008,
+	ROOTNS_NET		= 0x00000010,
+	ROOTNS_KILL_ON_CLOSE	= 0x00000100,
+	ROOTNS_CLOSE_ON_EXEC	= 0x00000200,
+	ROOTNS_ALL_NAMESPACES	= 0x0000001f,
+	ROOTNS_ALL_FLAGS	= 0x0000031f,
+};
+
+#endif /* _UAPI_LINUX_ROOTNS_H */
init/Kconfig +9 -0
index 4013781e0a02..f1f3a6d1755c 100644
@@ -1280,6 +1280,15 @@ config NET_NS
 	  Allow user space to create what appear to be multiple instances
 	  of the network stack.
 
+config ROOTNS
+	bool "Root namespace"
+	depends on USER_NS && PID_NS && UTS_NS && IPC_NS && NET_NS && CGROUPS
+	help
+	  Allow user space to create and manage isolated root namespaces
+	  with their own mount tree, credentials, namespace set, and init
+	  process lifecycle via the rootns_create(), rootns_enter(),
+	  rootns_wait(), and rootns_kill() system calls.
+
 endif # NAMESPACES
 
 config CHECKPOINT_RESTORE
kernel/Makefile +2 -0
index 4ff92e24680c..7074d2664ce7 100644
@@ -152,6 +152,8 @@ KCOV_INSTRUMENT_kstack_erase.o := n
 
 obj-$(CONFIG_SCF_TORTURE_TEST) += scftorture.o
 
+obj-$(CONFIG_ROOTNS) += rootns.o
+
 $(obj)/configs.o: $(obj)/config_data.gz
 
 # .config is small, so it is compressed with gzip rather than the image compressor.
kernel/rootns.c new file +107 -0

107 lines not on this page · raw message

Signature · 1 line
2.47.3
#4 lore raw

Re: [RFC PATCH 02/13] rootns: Add core infrastructure for root namespaces

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

Linux namespaces can be created and entered individually, but userspace orchestrators lack a single kernel object that binds a namespace set, a root mount, and an init process behind a pollable file descriptor.

Add struct rootns, its lifecycle states, reference counting, uAPI creation flags, and anonymous inode file operations under CONFIG_ROOTNS. Drop active and passive namespace references on final release, send SIGKILL to the rootns init thread group on close when ROOTNS_KILL_ON_CLOSE is set, and report EPOLLHUP from poll() once the rootns reaches ROOTNS_DEAD.

Quoted 3 lines

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#5 lore raw

RFC PATCH 3/13 rootns: Track init lifecycle via copy_process() and pid_namespace

In reply to Jarkko Sakkinen

A root namespace needs to record its init thread group's PID when bootstrapped and capture its exit status and resource usage once all processes in the root namespace have terminated, without serializing normal fork() and exit() paths inside the container.

Represent the initial host context with a NULL nsproxy->rootns pointer, commit the bootstrap init PID and wake waiters in copy_rootns(), and invoke exit_rootns() from zap_pid_ns_processes() after the root namespace's PID namespace has killed and reaped all member tasks.

---
 include/linux/nsproxy.h       | 16 ++++++++++++++
 include/linux/pid_namespace.h |  4 ++++
 include/linux/rootns.h        | 12 +++++++++++
 kernel/fork.c                 |  2 ++
 kernel/nsproxy.c              |  4 ++++
 kernel/pid_namespace.c        |  2 ++
 kernel/rootns.c               | 40 +++++++++++++++++++++++++++++++++++
 7 files changed, 80 insertions(+)
include/linux/nsproxy.h +16 -0
index 23cbeee6b1e4..7d0b636387c6 100644
@@ -12,6 +12,7 @@ struct ipc_namespace;
 struct pid_namespace;
 struct cgroup_namespace;
 struct fs_struct;
+struct rootns;
 struct user_namespace;
 
 /*
@@ -40,9 +41,24 @@ struct nsproxy {
 	struct time_namespace *time_ns;
 	struct time_namespace *time_ns_for_children;
 	struct cgroup_namespace *cgroup_ns;
+#ifdef CONFIG_ROOTNS
+	struct rootns *rootns;
+#endif
 };
 extern struct nsproxy init_nsproxy;
 
+#ifdef CONFIG_ROOTNS
+static inline struct rootns *task_rootns(const struct task_struct *tsk)
+{
+	return tsk->nsproxy ? tsk->nsproxy->rootns : NULL;
+}
+#else
+static inline struct rootns *task_rootns(const struct task_struct *tsk)
+{
+	return NULL;
+}
+#endif
+
 /*
  * A structure to encompass all bits needed to install
  * a partial or complete new set of namespaces.
include/linux/pid_namespace.h +4 -0
index b20baaa7e62b..6fd959f4d0d4 100644
@@ -15,6 +15,7 @@
 #define MAX_PID_NS_LEVEL 32
 
 struct fs_pin;
+struct rootns;
 
 #if defined(CONFIG_SYSCTL) && defined(CONFIG_MEMFD_CREATE)
 /* modes for vm.memfd_noexec sysctl */
@@ -45,6 +46,9 @@ struct pid_namespace {
 	struct user_namespace *user_ns;
 	struct ucounts *ucounts;
 	int reboot;	/* group exit code if this pidns was rebooted */
+#ifdef CONFIG_ROOTNS
+	struct rootns *rootns;
+#endif
 	struct ns_common ns;
 	struct work_struct	work;
 } __randomize_layout;
include/linux/rootns.h +12 -0
index 8464c90863ac..b8437bf21830 100644
@@ -16,6 +16,7 @@ struct cred;
 struct file;
 struct nsproxy;
 struct pid;
+struct pid_namespace;
 struct task_struct;
 
 enum rootns_state {
@@ -47,6 +48,8 @@ struct rootns {
 struct rootns *get_rootns(struct rootns *c);
 void put_rootns(struct rootns *c);
 bool is_rootns_file(struct file *file);
+void copy_rootns(struct task_struct *tsk, struct rootns *rootns);
+void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk);
 #else
 static inline struct rootns *get_rootns(struct rootns *c)
 {
@@ -61,6 +64,15 @@ static inline bool is_rootns_file(struct file *file)
 {
 	return false;
 }
+
+static inline void copy_rootns(struct task_struct *tsk, struct rootns *rootns)
+{
+}
+
+static inline void exit_rootns(struct pid_namespace *pid_ns,
+			       struct task_struct *tsk)
+{
+}
 #endif /* CONFIG_ROOTNS */
 
 #endif /* _LINUX_ROOTNS_H */
kernel/fork.c +2 -0
index 5efceb8d58a7..99e22b3cd213 100644
@@ -83,6 +83,7 @@
 #include <linux/fs_struct.h>
 #include <linux/magic.h>
 #include <linux/perf_event.h>
+#include <linux/rootns.h>
 #include <linux/posix-timers.h>
 #include <linux/user-return-notifier.h>
 #include <linux/oom.h>
@@ -2565,6 +2566,7 @@ __latent_entropy struct task_struct *copy_process(
 			attach_pid(p, PIDTYPE_TGID);
 			attach_pid(p, PIDTYPE_PGID);
 			attach_pid(p, PIDTYPE_SID);
+			copy_rootns(p, NULL);
 			__this_cpu_inc(process_counts);
 		} else {
 			current->signal->nr_threads++;
kernel/nsproxy.c +4 -0
index 8a3c6d4e94e2..a76837b3ee33 100644
@@ -13,6 +13,7 @@
 #include <linux/export.h>
 #include <linux/nsproxy.h>
 #include <linux/ns/ns_common_types.h>
+#include <linux/rootns.h>
 #include <linux/init_task.h>
 #include <linux/mnt_namespace.h>
 #include <linux/utsname.h>
@@ -142,6 +143,9 @@ struct nsproxy *create_new_namespaces(u64 flags,
 		goto out_time;
 	}
 	new_nsp->time_ns = get_time_ns(ns->time_ns);
+#ifdef CONFIG_ROOTNS
+	new_nsp->rootns = ns->rootns;
+#endif
 
 	return new_nsp;
 
kernel/pid_namespace.c +2 -0
index 127a5fd23e70..081c27aa85bd 100644
@@ -24,6 +24,7 @@
 #include <linux/sched/signal.h>
 #include <linux/idr.h>
 #include <linux/nstree.h>
+#include <linux/rootns.h>
 #include <uapi/linux/wait.h>
 #include "pid_sysctl.h"
 
@@ -280,6 +281,7 @@ void zap_pid_ns_processes(struct pid_namespace *pid_ns)
 		current->signal->group_exit_code = pid_ns->reboot;
 
 	acct_exit_ns(pid_ns);
+	exit_rootns(pid_ns, me);
 	return;
 }
 
kernel/rootns.c +40 -0
index e75d918b93ec..e3b203322ae2 100644
@@ -16,6 +16,7 @@
 #include <linux/ns_common.h>
 #include <linux/nsfs.h>
 #include <linux/pid.h>
+#include <linux/pid_namespace.h>
 #include <linux/user_namespace.h>
 #include <linux/compat.h>
 #include <uapi/linux/rootns.h>
@@ -105,3 +106,42 @@ bool is_rootns_file(struct file *file)
 {
 	return file->f_op == &rootns_fops;
 }
+
+void copy_rootns(struct task_struct *tsk, struct rootns *c)
+{
+	if (likely(!c || READ_ONCE(c->state) != ROOTNS_FORKING))
+		return;
+
+	scoped_guard(spinlock, &c->lock) {
+		get_rootns(c);
+		WRITE_ONCE(c->init_pid, get_task_pid(tsk, PIDTYPE_TGID));
+		WRITE_ONCE(c->state, ROOTNS_RUNNING);
+	}
+	wake_up_all(&c->waitq);
+}
+
+void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk)
+{
+	struct rootns *c = pid_ns->rootns;
+	struct task_struct *leader;
+	struct rusage rusage;
+	int status;
+
+	if (!c)
+		return;
+
+	leader = tsk->group_leader;
+	status = (tsk->signal->flags & SIGNAL_GROUP_EXIT) ?
+		 tsk->signal->group_exit_code : leader->exit_code;
+	getrusage(leader, RUSAGE_BOTH, &rusage);
+
+	scoped_guard(spinlock, &c->lock) {
+		c->exit_code = status;
+		c->rusage = rusage;
+		WRITE_ONCE(c->state, ROOTNS_DEAD);
+	}
+
+	pid_ns->rootns = NULL;
+	wake_up_poll(&c->waitq, EPOLLHUP);
+	put_rootns(c);
+}
Signature · 1 line
2.47.3
#6 lore raw

Re: [RFC PATCH 03/13] rootns: Track init lifecycle via copy_process() and pid_namespace

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [High] rootns: UAF and refcount imbalance in exit_rootns() via unreferenced pid_ns->rootns - [High] rootns…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] rootns: UAF and refcount imbalance in exit_rootns() via unreferenced pid_ns->rootns
- [High] rootns: unreferenced pid_ns->rootns pointer in exit_rootns() causes UAF
- [Medium] rootns: copy_rootns() publishes init_pid before attach_pid(PIDTYPE_PID)
- [Medium] rootns: missing is_child_reaper() and locked state checks in copy_rootns()
--

commit 257575ec869d3f0e55e6c1a6f99ef3b0751d2a44
Author: Jarkko Sakkinen <[email protected]>

rootns: Track init lifecycle via copy_process() and pid_namespace

This commit adds rootns lifecycle tracking hooks to copy_process(), create_new_namespaces(), and zap_pid_ns_processes() to record the bootstrapped init task's PID and capture its exit status and resource usage when the PID namespace terminates.

Quoted 4 lines
kernel/fork.c +0 -0
index 5efceb8d58a78..99e22b3cd213e 100644

[ ... ]

kernel/fork.c __latent_entropy struct task_struct *copy_process( · line 2572

Quoted 8 lines
kernel/fork.c +1 -0
@@ -2565,6 +2566,7 @@ __latent_entropy struct task_struct *copy_process(
 			attach_pid(p, PIDTYPE_TGID);
 			attach_pid(p, PIDTYPE_PGID);
 			attach_pid(p, PIDTYPE_SID);
+			copy_rootns(p, NULL);
 			__this_cpu_inc(process_counts);
 		} else {
 			current->signal->nr_threads++;

[Severity: Medium]
Does calling copy_rootns() before attach_pid(p, PIDTYPE_PID) publish c->init_pid and ROOTNS_RUNNING before pid->tasks[PIDTYPE_PID] is populated?

CPU0 CPU1
copy_process()
attach_pid(p, PIDTYPE_TGID)
copy_rootns(p, c)

    spin_lock(&c->lock)
    c->init_pid = get_task_pid(p, ...)
    c->state = ROOTNS_RUNNING
    spin_unlock(&c->lock)
                                        __rootns_kill()
                                          spin_lock(&c->lock)
                                          pid = get_pid(c->init_pid)
                                          spin_unlock(&c->lock)
                                          kill_pid(pid, sig, priv)
                                            ...
                                              pid_task(pid, PIDTYPE_PID)
                                              --> NULL (-ESRCH)

attach_pid(p, PIDTYPE_PID)

__rootns_kill() does not take tasklist_lock, so if a signal is sent during this window (for example from rootns_release() when ROOTNS_KILL_ON_CLOSE is set), kill_pid() fails with -ESRCH and drops the signal, leaving the container init process running.

Quoted 4 lines
kernel/rootns.c +0 -0
index e75d918b93ec5..e3b203322ae23 100644

[ ... ]

Quoted 7 lines
kernel/rootns.c +3 -0
@@ -105,3 +106,42 @@ bool is_rootns_file(struct file *file)
 {
 	return file->f_op == &rootns_fops;
 }
+
+void copy_rootns(struct task_struct *tsk, struct rootns *c)
+{

kernel/rootns.c bool is_rootns_file(struct file *file) · line 121

Quoted 10 lines
kernel/rootns.c +10 -0
+	if (likely(!c || READ_ONCE(c->state) != ROOTNS_FORKING))
+		return;
+
+	scoped_guard(spinlock, &c->lock) {
+		get_rootns(c);
+		WRITE_ONCE(c->init_pid, get_task_pid(tsk, PIDTYPE_TGID));
+		WRITE_ONCE(c->state, ROOTNS_RUNNING);
+	}
+	wake_up_all(&c->waitq);
+}

[Severity: Medium]
Can copy_rootns() record a non-reaper task as c->init_pid or race with exit_rootns() to overwrite ROOTNS_DEAD back to ROOTNS_RUNNING?

In commit "rootns: Add rootns_create() system call", create_rootns() sets ns->pid_ns_for_children->rootns = c and marks the PID namespace active in pid_ns_tree before rootns_enter() is called. A host task with CAP_SYS_ADMIN can open that PID namespace via open_by_handle_at(), join it via setns(CLONE_NEWPID), and fork() PID 1 without bootstrapping c. Because copy_process() calls copy_rootns() for any thread_group_leader(p) rather than checking is_child_reaper(pid), a later rootns_enter() spawns PID 2 and commits it as c->init_pid.

Furthermore, copy_rootns() checks c->state == ROOTNS_FORKING outside c->lock without re-checking under the lock:

CPU0 CPU1
copy_rootns(tsk, c)
READ_ONCE(c->state) == ROOTNS_FORKING

                                        zap_pid_ns_processes(pid_ns)
                                          exit_rootns(pid_ns, me)
                                            spin_lock(&c->lock)
                                            c->state = ROOTNS_DEAD
                                            spin_unlock(&c->lock)
                                            put_rootns(c)

spin_lock(&c->lock)
get_rootns(c)
c->init_pid = ...
c->state = ROOTNS_RUNNING <-- overwrites ROOTNS_DEAD spin_unlock(&c->lock)

Checking is_child_reaper(pid) and re-checking c->state == ROOTNS_FORKING under c->lock would prevent both issues.

Quoted 16 lines
kernel/rootns.c +16 -0
+
+void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk)
+{
+	struct rootns *c = pid_ns->rootns;
+	struct task_struct *leader;
+	struct rusage rusage;
+	int status;
+
+	if (!c)
+		return;
+
+	leader = tsk->group_leader;
+	status = (tsk->signal->flags & SIGNAL_GROUP_EXIT) ?
+		 tsk->signal->group_exit_code : leader->exit_code;
+	getrusage(leader, RUSAGE_BOTH, &rusage);
+

kernel/rootns.c bool is_rootns_file(struct file *file) · line 147

Quoted 10 lines
kernel/rootns.c +10 -0
+	scoped_guard(spinlock, &c->lock) {
+		c->exit_code = status;
+		c->rusage = rusage;
+		WRITE_ONCE(c->state, ROOTNS_DEAD);
+	}
+
+	pid_ns->rootns = NULL;
+	wake_up_poll(&c->waitq, EPOLLHUP);
+	put_rootns(c);
+}

[Severity: High]
Can exit_rootns() drop an unheld reference on c when pid_ns was entered without copy_rootns()?

In commit "rootns: Add rootns_create() system call", create_rootns() sets ns->pid_ns_for_children->rootns = c without taking a reference on c; the matching get_rootns(c) only happens in copy_rootns() when bootstrapping in ROOTNS_FORKING state. If a privileged host process enters pid_ns via open_by_handle_at() and setns(CLONE_NEWPID) and forks a child reaper, copy_rootns() is called with c == NULL and never increments c->usage. When that child reaper exits, zap_pid_ns_processes() -> exit_rootns() sees pid_ns->rootns == c and calls put_rootns(c), dropping the open rootns file descriptor's own reference and freeing c while the file descriptor is still open.

[Severity: High]
Can exit_rootns() dereference a dangling pid_ns->rootns pointer after the rootns file descriptor has been closed?

Because create_rootns() stores an unreferenced c in pid_ns->rootns and put_rootns() frees c without clearing pid_ns->rootns, any reference that outlives the rootns file descriptor before rootns_enter() runs leaves pid_ns->rootns pointing to freed memory. If a process holds an nsfs file descriptor to pid_ns, closes the rootns file descriptor (freeing c), and then enters pid_ns via setns(CLONE_NEWPID), forks, and exits, zap_pid_ns_processes() -> exit_rootns() dereferences the freed c and double-frees it via put_rootns(c). Assigning pid_ns->rootns = get_rootns(c) in copy_rootns() when the bootstrap init task is attached would avoid storing an unreferenced pointer in create_rootns().

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#7 lore raw

RFC PATCH 4/13 rootns: Add rootns_create() system call

In reply to Jarkko Sakkinen

Setting up an isolated namespace environment from a multithreaded manager process currently requires helper processes to call unshare() and pass file descriptors back over sockets.

Add the rootns_create() system call to allocate a detached rootns instance with dedicated empty mount (CLONE_EMPTY_MNTNS) and PID namespaces and return its control file descriptor. Create fresh optional namespaces selected in flags while inheriting unset ones from the caller, and pin active references for the lifetime of the rootns. Leave the newly created rootns in ROOTNS_EMPTY until userspace installs a root mount.

---
 include/linux/syscalls.h |   1 +
 kernel/rootns.c          | 140 +++++++++++++++++++++++++++++++++++++++
 kernel/sys_ni.c          |   3 +
 3 files changed, 144 insertions(+)
include/linux/syscalls.h +1 -0
index 552d9710a0d5..272d54bddbe2 100644
@@ -1006,6 +1006,7 @@ asmlinkage long sys_lsm_get_self_attr(unsigned int attr, struct lsm_ctx __user *
 asmlinkage long sys_lsm_set_self_attr(unsigned int attr, struct lsm_ctx __user *ctx,
 				      u32 size, u32 flags);
 asmlinkage long sys_lsm_list_modules(u64 __user *ids, u32 __user *size, u32 flags);
+asmlinkage long sys_rootns_create(unsigned int flags);
 
 /*
  * Architecture-specific system calls
kernel/rootns.c +140 -0

143 lines not on this page · raw message

kernel/sys_ni.c +3 -0
index c8be0abaa407..4a6c4337cc74 100644
@@ -398,3 +398,6 @@ COND_SYSCALL(rseq_slice_yield);
 
 COND_SYSCALL(uretprobe);
 COND_SYSCALL(uprobe);
+
+/* kernel/rootns.c */
+COND_SYSCALL(rootns_create);
Signature · 1 line
2.47.3
#8 lore raw

Re: [RFC PATCH 04/13] rootns: Add rootns_create() system call

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] rootns: cred->user mismatch in create_rootns_creds() when ROOTNS_USER is set - [High] rootns: UAF…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] rootns: cred->user mismatch in create_rootns_creds() when ROOTNS_USER is set
- [High] rootns: UAF via unreferenced pid_ns_for_children->rootns in create_rootns()
--

commit b0275fb9f88bbbd1444c1c6937b46e36c52e8fe7
Author: Jarkko Sakkinen <[email protected]>

rootns: Add rootns_create() system call

This commit adds the rootns_create() system call to allocate a detached root namespace with dedicated mount and PID namespaces plus optional namespaces selected by flags, returning a control file descriptor.

Quoted 38 lines
kernel/rootns.c +30 -0
index e3b203322ae23..904d75ce9d909 100644
@@ -145,3 +145,143 @@ void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk)
 	wake_up_poll(&c->waitq, EPOLLHUP);
 	put_rootns(c);
 }
+
+/*
+ * Create credentials for a rootns. Drop keyrings from the new credential to
+ * avoid unnecessary pinning.
+ */
+static const struct cred *create_rootns_creds(unsigned int flags)
+{
+	struct cred *new;
+	int ret;
+
+	new = prepare_creds();
+	if (!new)
+		return ERR_PTR(-ENOMEM);
+
+#ifdef CONFIG_KEYS
+	key_put(new->thread_keyring);
+	new->thread_keyring = NULL;
+	key_put(new->process_keyring);
+	new->process_keyring = NULL;
+	key_put(new->session_keyring);
+	new->session_keyring = NULL;
+	key_put(new->request_key_auth);
+	new->request_key_auth = NULL;
+#endif
+	if (!(flags & ROOTNS_USER))
+		return new;
+
+	ret = create_user_ns(new);
+	if (ret < 0)
+		goto err;

kernel/rootns.c void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk) · line 187

Quoted 10 lines
kernel/rootns.c +10 -0
+	new->euid = new->user_ns->owner;
+	new->egid = new->user_ns->group;
+
+	new->uid = new->euid;
+	new->suid = new->euid;
+	new->fsuid = new->euid;
+	new->gid = new->egid;
+	new->sgid = new->egid;
+	new->fsgid = new->egid;
+	ret = set_cred_ucounts(new);

[Severity: High]
Does updating new->uid to new->euid without updating new->user leave new->user pointing to the caller's old real UID user_struct?

prepare_creds() clones new->user from current->cred->user. When the caller's real UID differs from its effective UID (for example, a manager process with real UID 0 that switched its effective UID via seteuid() before calling rootns_create(ROOTNS_USER)), tasks entering the rootns inherit new->user == INIT_USER while running as the unprivileged UID, bypassing RLIMIT_NPROC checks in copy_process() and misattributing per-user_struct resource accounting.

Updating new->user via alloc_uid(new->uid) and freeing the old reference with free_uid(), as set_user() does in kernel/sys.c, would keep new->user consistent with new->uid.

Quoted 14 lines
kernel/rootns.c +14 -0
+	if (ret < 0)
+		goto err;
+	return new;
+
+err:
+	abort_creds(new);
+	return ERR_PTR(ret);
+}
+
+/*
+ * Create a new rootns.
+ */
+static struct rootns *create_rootns(unsigned int flags)
+{

[ ... ]

kernel/rootns.c void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk) · line 249

Quoted 11 lines
kernel/rootns.c +11 -0
+	ns = create_new_namespaces(clone_flags, current->nsproxy, cred->user_ns,
+				   NULL);
+	if (IS_ERR(ns)) {
+		ret = PTR_ERR(ns);
+		goto err_put;
+	}
+
+	c->ns = ns;
+	ns->rootns = c;
+	ns->pid_ns_for_children->rootns = c;
+	nsproxy_ns_active_get(ns);

[Severity: High]
Can storing an uncounted pointer in ns->pid_ns_for_children->rootns before copy_rootns() runs lead to a use-after-free in exit_rootns()?

create_new_namespaces() adds ns->pid_ns_for_children to the namespace tree and nsproxy_ns_active_get() marks it active, while the reference on c that pairs with exit_rootns() -> put_rootns(c) is only taken later in copy_rootns() when c->state is ROOTNS_FORKING:

kernel/rootns.c:copy_rootns() {
    ...
	scoped_guard(spinlock, &c->lock) {
		get_rootns(c);
		WRITE_ONCE(c->init_pid, get_task_pid(tsk, PIDTYPE_TGID));
		WRITE_ONCE(c->state, ROOTNS_RUNNING);
	}
}

A process with CAP_SYS_ADMIN in init_user_ns and init_pid_ns can open the active PID namespace via open_by_handle_at(FD_NSFS_ROOT, ...), enter it with setns(), and fork a child that becomes child_reaper without going through ROOTNS_FORKING. If the rootns fd was already closed, put_rootns() frees c without clearing pid_ns->rootns, and when that child exits, zap_pid_ns_processes() -> exit_rootns() dereferences and frees c a second time. If the rootns fd is still open when the child exits, exit_rootns() drops the control fd's sole reference on c, freeing it while the fd still references it.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#9 lore raw

RFC PATCH 5/13 rootns: Add rootns_wait() system call

In reply to Jarkko Sakkinen

wait4() and waitid() only allow a parent or subreaper to collect exit status, so an external manager holding a rootns file descriptor cannot wait on a rootns init process forked by another process or observe exit status multiple times across observers.

Add the rootns_wait() system call and its compat entry point to wait on a rootns file descriptor until its init thread group exits and report the recorded wait status and rusage. Return the init TGID translated into the caller's active PID namespace, 0 for WNOHANG while still running, or -ECHILD when the PID is not visible to the caller.

---
 include/linux/compat.h   |   4 ++
 include/linux/syscalls.h |   2 +
 kernel/rootns.c          | 105 +++++++++++++++++++++++++++++++++++++++
 kernel/sys_ni.c          |   2 +
 4 files changed, 113 insertions(+)
include/linux/compat.h +4 -0
index ad37ca617e65..3a9ac9dbb24c 100644
@@ -779,6 +779,10 @@ asmlinkage long compat_sys_recvmmsg_time32(int fd, struct compat_mmsghdr __user
 asmlinkage long compat_sys_wait4(compat_pid_t pid,
 				 compat_uint_t __user *stat_addr, int options,
 				 struct compat_rusage __user *ru);
+asmlinkage long compat_sys_rootns_wait(int rootnsfd,
+				       compat_int_t __user *status,
+				       unsigned int options,
+				       struct compat_rusage __user *ru);
 asmlinkage long compat_sys_fanotify_mark(int, unsigned int, __u32, __u32,
 					    int, const char __user *);
 asmlinkage long compat_sys_open_by_handle_at(int mountdirfd,
include/linux/syscalls.h +2 -0
index 272d54bddbe2..60e9c4ff71e7 100644
@@ -1007,6 +1007,8 @@ asmlinkage long sys_lsm_set_self_attr(unsigned int attr, struct lsm_ctx __user *
 				      u32 size, u32 flags);
 asmlinkage long sys_lsm_list_modules(u64 __user *ids, u32 __user *size, u32 flags);
 asmlinkage long sys_rootns_create(unsigned int flags);
+asmlinkage long sys_rootns_wait(int rootnsfd, int __user *status,
+				unsigned int options, struct rusage __user *ru);
 
 /*
  * Architecture-specific system calls
kernel/rootns.c +105 -0

114 lines not on this page · raw message

kernel/sys_ni.c +2 -0
index 4a6c4337cc74..f9918d38107b 100644
@@ -401,3 +401,5 @@ COND_SYSCALL(uprobe);
 
 /* kernel/rootns.c */
 COND_SYSCALL(rootns_create);
+COND_SYSCALL(rootns_wait);
+COND_SYSCALL_COMPAT(rootns_wait);
Signature · 1 line
2.47.3
#10 lore raw

Re: [RFC PATCH 05/13] rootns: Add rootns_wait() system call

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

wait4() and waitid() only allow a parent or subreaper to collect exit status, so an external manager holding a rootns file descriptor cannot wait on a rootns init process forked by another process or observe exit status multiple times across observers.

Add the rootns_wait() system call and its compat entry point to wait on a rootns file descriptor until its init thread group exits and report the recorded wait status and rusage. Return the init TGID translated into the caller's active PID namespace, 0 for WNOHANG while still running, or -ECHILD when the PID is not visible to the caller.

Quoted 3 lines

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#11 lore raw

RFC PATCH 6/13 rootns: Add rootns_kill() system call

In reply to Jarkko Sakkinen

Signaling every process inside a container from userspace via /proc is racy against concurrent fork() calls.

Add the rootns_kill() system call to walk the root namespace's PID namespace IDR under RCU and deliver a validated signal once to each thread group, aggregating per-process delivery results.

---
 include/linux/syscalls.h |  1 +
 kernel/rootns.c          | 65 ++++++++++++++++++++++++++++++++++++++++
 kernel/sys_ni.c          |  1 +
 3 files changed, 67 insertions(+)
include/linux/syscalls.h +1 -0
index 60e9c4ff71e7..a854d248c8a3 100644
@@ -1009,6 +1009,7 @@ asmlinkage long sys_lsm_list_modules(u64 __user *ids, u32 __user *size, u32 flag
 asmlinkage long sys_rootns_create(unsigned int flags);
 asmlinkage long sys_rootns_wait(int rootnsfd, int __user *status,
 				unsigned int options, struct rusage __user *ru);
+asmlinkage long sys_rootns_kill(int rootnsfd, int sig);
 
 /*
  * Architecture-specific system calls
kernel/rootns.c +65 -0

74 lines not on this page · raw message

kernel/sys_ni.c +1 -0
index f9918d38107b..fba44c49ddbb 100644
@@ -403,3 +403,4 @@ COND_SYSCALL(uprobe);
 COND_SYSCALL(rootns_create);
 COND_SYSCALL(rootns_wait);
 COND_SYSCALL_COMPAT(rootns_wait);
+COND_SYSCALL(rootns_kill);
Signature · 1 line
2.47.3
#12 lore raw

Re: [RFC PATCH 06/13] rootns: Add rootns_kill() system call

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] rootns: fork() race in rootns_kill_members() missing tasklist_lock - [High] rootns: missing PID…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] rootns: fork() race in rootns_kill_members() missing tasklist_lock
- [High] rootns: missing PID namespace ancestry check in rootns_kill_members()
--

commit af3e55bb2ee92ebb14699cd9c72b34e3ddb26ffe
Author: Jarkko Sakkinen <[email protected]>

rootns: Add rootns_kill() system call

This commit adds the rootns_kill() system call to walk a root namespace's PID namespace IDR and send a signal to every member thread group.

Quoted 4 lines
kernel/rootns.c +0 -0
index 8a1254db69df7..f59b2fe9910de 100644

[ ... ]

kernel/rootns.c COMPAT_SYSCALL_DEFINE4(rootns_wait, int, rootnsfd, · line 397

Quoted 8 lines
kernel/rootns.c +4 -0
@@ -390,3 +391,67 @@ COMPAT_SYSCALL_DEFINE4(rootns_wait, int, rootnsfd,
 	return ret;
 }
 #endif
+
+static int rootns_kill_members(struct rootns *rootns, int sig)
+{
+	struct pid_namespace *pid_ns = rootns->ns->pid_ns_for_children;

[Severity: High]
Should rootns_kill_members() verify that the caller's active PID namespace is equal to or an ancestor of pid_ns before delivering signals?

Without an ancestry check, a caller holding rootnsfd in a sibling or descendant PID namespace can signal processes outside its PID namespace hierarchy. Because kill_pid() passes SEND_SIG_NOINFO to send_signal_locked():

kernel/signal.c:send_signal_locked() {
    ...
	if (info == SEND_SIG_NOINFO) {
		/* Force if sent from an ancestor pid namespace */
		force = !task_pid_nr_ns(current, task_active_pid_ns(t));
	}
    ...
}

when current has no PID in task_active_pid_ns(t), send_signal_locked() treats the signal as coming from an ancestor PID namespace and sets force = true, bypassing SIGNAL_UNKILLABLE and allowing SIGKILL or SIGSTOP to kill or stop the PID namespace init process.

Quoted 8 lines
kernel/rootns.c +8 -0
+	bool any_success = false;
+	bool any_other = false;
+	bool any_perm = false;
+	int other_err = 0;
+	struct pid *pid;
+	int nr;
+
+	if (READ_ONCE(rootns->state) != ROOTNS_RUNNING)

kernel/rootns.c COMPAT_SYSCALL_DEFINE4(rootns_wait, int, rootnsfd, · line 415

Quoted 10 lines
kernel/rootns.c +10 -0
+		return -ESRCH;
+
+	scoped_guard(rcu) {
+		idr_for_each_entry(&pid_ns->idr, pid, nr) {
+			int err;
+
+			if (!pid_task(pid, PIDTYPE_TGID))
+				continue;
+
+			err = kill_pid(pid, sig, 0);

[Severity: High]
Can a concurrent fork() still escape signals sent by rootns_kill_members()?

CPU0 CPU1
copy_process()
hlist_add_head(&delayed.node,

    &current->signal->multiprocess)
  ...
  pid = alloc_pid(...)
                                  rootns_kill_members()
                                    idr_for_each_entry(&pid_ns->idr, ...)
                                      /* parent: kill_pid() uses
                                       * PIDTYPE_TGID, so delayed.signal
                                       * is not updated */
                                      kill_pid(parent_pid, SIGTERM, 0)
                                      /* child: not attached yet */
                                      !pid_task(child_pid, PIDTYPE_TGID)
                                        -> continue
  write_lock_irq(&tasklist_lock)
  p->signal->shared_pending.signal =
    delayed.signal
  attach_pid(p, PIDTYPE_TGID)
  attach_pid(p, PIDTYPE_PID)
  write_unlock_irq(&tasklist_lock)
                                    /* child escapes SIGTERM */

__send_signal_locked() only records signals in t->signal->multiprocess for in-flight forks when type > PIDTYPE_TGID, whereas kill_pid() passes PIDTYPE_TGID. In addition, because pid_ns->idr is walked without holding read_lock(&tasklist_lock), a parent at a higher IDR entry can fork and attach a child at a lower, already-scanned IDR entry (via PID wrap-around or clone3() set_tid) before the scan reaches the parent, allowing the child to escape even SIGKILL, or rootns_kill_members() can observe pid_task(pid, PIDTYPE_TGID) before attach_pid(p, PIDTYPE_PID) completes and get -ESRCH from kill_pid().

Holding read_lock(&tasklist_lock) during the IDR walk and signaling via group_send_sig_info(sig, SEND_SIG_NOINFO, task, PIDTYPE_MAX), as zap_pid_ns_processes() and kill(-1, sig) do, would close these races.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
#13 lore raw

RFC PATCH 7/13 rootns: Add rootns_enter() system call

In reply to Jarkko Sakkinen

Multithreaded userspace daemons cannot call setns(CLONE_NEWUSER) or safely mutate process-wide filesystem state in place before spawning a child into a target namespace set.

Add the rootns_enter() system call to fork a child process directly into a rootns whose root mount has been installed. Transition the rootns from ROOTNS_READY through ROOTNS_FORKING to ROOTNS_RUNNING for the first process so it becomes PID 1, serialize concurrent entrants on waitq until bootstrap resolves, and admit subsequent callers into the running PID namespace until teardown begins.

Require CAP_SYS_ADMIN in the target user namespace, forbid credential or PR_SET_NO_NEW_PRIVS privilege escalation, and require an ancestor PID namespace so the caller receives a valid child PID. Inherit rootns provenance in __ns_common_init() so intra-rootns clone(), unshare(), open_tree(), and setns() work while foreign setns() calls fail with -EPERM.

---
 include/linux/cred.h               |   4 +-
 include/linux/ns/ns_common_types.h |   4 +
 include/linux/nsproxy.h            |   3 +-
 include/linux/rootns.h             |   9 ++
 include/linux/sched/task.h         |   4 +
 include/linux/syscalls.h           |   1 +
 kernel/cred.c                      |  70 ++++++++++----
 kernel/fork.c                      |  29 ++++--
 kernel/nscommon.c                  |   8 ++
 kernel/nsproxy.c                   |  15 ++-
 kernel/rootns.c                    | 142 +++++++++++++++++++++++++++++
 kernel/sys_ni.c                    |   1 +
 12 files changed, 260 insertions(+), 30 deletions(-)
include/linux/cred.h +3 -1
index 49c26af37349..9849366fd44b 100644
@@ -19,6 +19,7 @@
 
 struct cred;
 struct inode;
+struct rootns;
 
 extern struct task_struct init_task;
 
@@ -152,7 +153,8 @@ struct cred {
 
 extern void __put_cred(struct cred *);
 extern void exit_creds(struct task_struct *);
-extern int copy_creds(struct task_struct *, u64);
+int copy_creds(struct task_struct *tsk, u64 clone_flags,
+	       struct rootns *rootns);
 extern const struct cred *get_task_cred(struct task_struct *);
 extern struct cred *cred_alloc_blank(void);
 extern struct cred *prepare_creds(void);
include/linux/ns/ns_common_types.h +4 -0
index 47a5cfe2326a..3bfc8f24ea92 100644
@@ -105,6 +105,7 @@ extern const struct proc_ns_operations utsns_operations;
  * @stashed: cached dentry to be used by the vfs
  * @ops: namespace operations
  * @inum: namespace inode number (quickly recycled for non-initial namespaces)
+ * @rootns_id: rootns provenance tag, if the namespace was created by a rootns
  * @__ns_ref: main reference count (do not use directly)
  * @ns_tree: namespace tree nodes and active reference count
  */
@@ -118,6 +119,9 @@ struct ns_common {
 	unsigned int inum;
 #ifdef CONFIG_SECURITY
 	void *ns_security;
+#endif
+#ifdef CONFIG_ROOTNS
+	u64 rootns_id;
 #endif
 	struct ns_tree;
 	struct rcu_head ns_rcu;
include/linux/nsproxy.h +2 -1
index 7d0b636387c6..3724d6ba238c 100644
@@ -116,7 +116,8 @@ struct nsproxy *create_new_namespaces(u64 flags,
 				      struct nsproxy *ns,
 				      struct user_namespace *user_ns,
 				      struct fs_struct *new_fs);
-int copy_namespaces(u64 flags, struct task_struct *tsk);
+int copy_namespaces(u64 flags, struct task_struct *tsk,
+		    struct rootns *rootns);
 void switch_cred_namespaces(const struct cred *old, const struct cred *new);
 void exit_nsproxy_namespaces(struct task_struct *tsk);
 void get_cred_namespaces(struct task_struct *tsk);
include/linux/rootns.h +9 -0
index b8437bf21830..eab49d025c93 100644
@@ -14,6 +14,7 @@
 
 struct cred;
 struct file;
+struct ns_common;
 struct nsproxy;
 struct pid;
 struct pid_namespace;
@@ -32,6 +33,7 @@ enum rootns_state {
  */
 struct rootns {
 	refcount_t		usage;
+	u64			id;
 	int			exit_code;	/* The exit code of 'init' */
 	struct rusage		rusage;		/* Resource usage of 'init' */
 	const struct cred	*cred;		/* Creds for this rootns, including userns */
@@ -50,6 +52,7 @@ void put_rootns(struct rootns *c);
 bool is_rootns_file(struct file *file);
 void copy_rootns(struct task_struct *tsk, struct rootns *rootns);
 void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk);
+bool rootns_may_setns(struct rootns *rootns, struct ns_common *ns);
 #else
 static inline struct rootns *get_rootns(struct rootns *c)
 {
@@ -73,6 +76,12 @@ static inline void exit_rootns(struct pid_namespace *pid_ns,
 			       struct task_struct *tsk)
 {
 }
+
+static inline bool rootns_may_setns(struct rootns *rootns,
+				    struct ns_common *ns)
+{
+	return true;
+}
 #endif /* CONFIG_ROOTNS */
 
 #endif /* _LINUX_ROOTNS_H */
include/linux/sched/task.h +4 -0
index 90ed5bc3c7af..a3401e726a82 100644
@@ -16,6 +16,7 @@ struct task_struct;
 struct rusage;
 union thread_union;
 struct css_set;
+struct rootns;
 
 /* All the bits taken by the old clone syscall. */
 #define CLONE_LEGACY_FLAGS 0xffffffffULL
@@ -44,6 +45,9 @@ struct kernel_clone_args {
 	void *fn_arg;
 	struct cgroup *cgrp;
 	struct css_set *cset;
+#ifdef CONFIG_ROOTNS
+	struct rootns *rootns;
+#endif
 	unsigned int kill_seq;
 };
 
include/linux/syscalls.h +1 -0
index a854d248c8a3..f361dcc74a39 100644
@@ -1010,6 +1010,7 @@ asmlinkage long sys_rootns_create(unsigned int flags);
 asmlinkage long sys_rootns_wait(int rootnsfd, int __user *status,
 				unsigned int options, struct rusage __user *ru);
 asmlinkage long sys_rootns_kill(int rootnsfd, int sig);
+asmlinkage long sys_rootns_enter(int rootnsfd);
 
 /*
  * Architecture-specific system calls
kernel/cred.c +50 -20

117 lines not on this page · raw message

kernel/fork.c +23 -6
index 99e22b3cd213..5e23d36b7ac3 100644
@@ -1632,8 +1632,20 @@ enum copy_fs_flags_t {
 	COPY_FS_IDLE	= (1 << 1),
 };
 
+#ifdef CONFIG_ROOTNS
+static inline struct rootns *clone_args_rootns(const struct kernel_clone_args *args)
+{
+	return args->rootns;
+}
+#else
+static inline struct rootns *clone_args_rootns(const struct kernel_clone_args *args)
+{
+	return NULL;
+}
+#endif
+
 static int copy_fs(u64 clone_flags, struct task_struct *tsk,
-		   enum copy_fs_flags_t flags)
+		   enum copy_fs_flags_t flags, struct rootns *rootns)
 {
 	struct fs_struct *fs;
 
@@ -1649,7 +1661,7 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk,
 		if (current->nsproxy->mnt_ns != &init_mnt_ns)
 			return -EINVAL;
 		fs = userspace_init_fs;
-	} else if (flags & COPY_FS_IDLE) {
+	} else if (flags & COPY_FS_IDLE || rootns) {
 		fs = &init_fs;
 	} else {
 		fs = current->fs;
@@ -1671,6 +1683,10 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk,
 	tsk->real_fs = tsk->fs = copy_fs_struct(fs);
 	if (!tsk->fs)
 		return -ENOMEM;
+	if (rootns) {
+		set_fs_root(tsk->fs, &rootns->root);
+		set_fs_pwd(tsk->fs, &rootns->root);
+	}
 	return 0;
 }
 
@@ -2186,7 +2202,7 @@ __latent_entropy struct task_struct *copy_process(
 #ifdef CONFIG_PROVE_LOCKING
 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
 #endif
-	retval = copy_creds(p, clone_flags);
+	retval = copy_creds(p, clone_flags, clone_args_rootns(args));
 	if (retval < 0)
 		goto bad_fork_free;
 
@@ -2317,7 +2333,8 @@ __latent_entropy struct task_struct *copy_process(
 		goto bad_fork_cleanup_semundo;
 	retval = copy_fs(clone_flags, p,
 			 (args->umh ? COPY_FS_UMH : 0) |
-			 (args->idle ? COPY_FS_IDLE : 0));
+			 (args->idle ? COPY_FS_IDLE : 0),
+			 clone_args_rootns(args));
 	if (retval)
 		goto bad_fork_cleanup_semundo;
 	retval = copy_sighand(clone_flags, p);
@@ -2329,7 +2346,7 @@ __latent_entropy struct task_struct *copy_process(
 	retval = copy_mm(clone_flags, p);
 	if (retval)
 		goto bad_fork_cleanup_signal;
-	retval = copy_namespaces(clone_flags, p);
+	retval = copy_namespaces(clone_flags, p, clone_args_rootns(args));
 	if (retval)
 		goto bad_fork_cleanup_mm;
 	retval = copy_io(clone_flags, p);
@@ -2566,7 +2583,7 @@ __latent_entropy struct task_struct *copy_process(
 			attach_pid(p, PIDTYPE_TGID);
 			attach_pid(p, PIDTYPE_PGID);
 			attach_pid(p, PIDTYPE_SID);
-			copy_rootns(p, NULL);
+			copy_rootns(p, clone_args_rootns(args));
 			__this_cpu_inc(process_counts);
 		} else {
 			current->signal->nr_threads++;
kernel/nscommon.c +8 -0
index 4438c6b663f9..d7e857a417f7 100644
@@ -2,8 +2,10 @@
 /* Copyright (c) 2025 Christian Brauner <[email protected]> */
 
 #include <linux/ns_common.h>
+#include <linux/nsproxy.h>
 #include <linux/nstree.h>
 #include <linux/proc_ns.h>
+#include <linux/rootns.h>
 #include <linux/security.h>
 #include <linux/user_namespace.h>
 #include <linux/vfsdebug.h>
@@ -57,6 +59,9 @@ static void ns_debug(struct ns_common *ns, const struct proc_ns_operations *ops)
 int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_operations *ops,
 		     int inum, u64 ns_id)
 {
+#ifdef CONFIG_ROOTNS
+	struct rootns *rootns = task_rootns(current);
+#endif
 	int ret = 0;
 
 	refcount_set(&ns->__ns_ref, 1);
@@ -66,6 +71,9 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope
 #endif
 	ns->ops = ops;
 	ns->ns_type = ns_type;
+#ifdef CONFIG_ROOTNS
+	ns->rootns_id = rootns ? rootns->id : 0;
+#endif
 	ns_tree_node_init(&ns->ns_tree_node);
 	ns_tree_node_init(&ns->ns_unified_node);
 	ns_tree_node_init(&ns->ns_owner_node);
kernel/nsproxy.c +13 -2
index a76837b3ee33..0c6407757d89 100644
@@ -169,13 +169,21 @@ struct nsproxy *create_new_namespaces(u64 flags,
 /*
  * called from clone.  This now handles copy for nsproxy and all
  * namespaces therein.
+ *
+ * Namespaces derived from a rootns member inherit the same rootns domain.
  */
-int copy_namespaces(u64 flags, struct task_struct *tsk)
+int copy_namespaces(u64 flags, struct task_struct *tsk,
+		    struct rootns *rootns)
 {
 	struct nsproxy *old_ns = tsk->nsproxy;
 	struct user_namespace *user_ns = task_cred_xxx(tsk, user_ns);
 	struct nsproxy *new_ns;
 
+	if (rootns) {
+		get_nsproxy(rootns->ns);
+		tsk->nsproxy = rootns->ns;
+		return 0;
+	}
 	if (likely(!(flags & (CLONE_NS_ALL & ~CLONE_NEWUSER)))) {
 		if ((flags & CLONE_VM) ||
 		    likely(old_ns->time_ns_for_children == old_ns->time_ns)) {
@@ -196,7 +204,7 @@ int copy_namespaces(u64 flags, struct task_struct *tsk)
 		(CLONE_NEWIPC | CLONE_SYSVSEM))
 		return -EINVAL;
 
-	new_ns = create_new_namespaces(flags, tsk->nsproxy, user_ns, tsk->fs);
+	new_ns = create_new_namespaces(flags, old_ns, user_ns, tsk->fs);
 	if (IS_ERR(new_ns))
 		return  PTR_ERR(new_ns);
 
@@ -391,6 +399,9 @@ static inline int validate_ns(struct nsset *nsset, struct ns_common *ns)
 {
 	int ret;
 
+	if (!rootns_may_setns(task_rootns(current), ns))
+		return -EPERM;
+
 	ret = security_namespace_install(nsset, ns);
 	if (ret)
 		return ret;
kernel/rootns.c +142 -0

177 lines not on this page · raw message

kernel/sys_ni.c +1 -0
index fba44c49ddbb..3fd6376ddbe7 100644
@@ -404,3 +404,4 @@ COND_SYSCALL(rootns_create);
 COND_SYSCALL(rootns_wait);
 COND_SYSCALL_COMPAT(rootns_wait);
 COND_SYSCALL(rootns_kill);
+COND_SYSCALL(rootns_enter);
Signature · 1 line
2.47.3
#14 lore raw

Re: [RFC PATCH 07/13] rootns: Add rootns_enter() system call

Quoted 12 lines · Jarkko Sakkinen

Multithreaded userspace daemons cannot call setns(CLONE_NEWUSER) or safely mutate process-wide filesystem state in place before spawning a child into a target namespace set.

Add the rootns_enter() system call to fork a child process directly into a rootns whose root mount has been installed. Transition the rootns from ROOTNS_READY through ROOTNS_FORKING to ROOTNS_RUNNING for the first process so it becomes PID 1, serialize concurrent entrants on waitq until bootstrap resolves, and admit subsequent callers into the running PID namespace until teardown begins.

Quoted 2 lines

Require CAP_SYS_ADMIN in the target user namespace, forbid credential or PR_SET_NO_NEW_PRIVS privilege escalation

Why are you disallowing this if no_new_privs?

This isn't necessarily a showstopper, but fork() is really quite slow in many cases. It would be nice to have a more spawn-like API available. I assume it's possible to open a file in the target's mountns by some sane API even without entering that mountns, as a side effect of how the fsopen / move_mount mechanism works.

--Andy

#15 lore raw

Re: [RFC PATCH 07/13] rootns: Add rootns_enter() system call

Quoted 13 lines · Andy Lutomirski
Quoted 12 lines · Jarkko Sakkinen

Multithreaded userspace daemons cannot call setns(CLONE_NEWUSER) or safely mutate process-wide filesystem state in place before spawning a child into a target namespace set.

Add the rootns_enter() system call to fork a child process directly into a rootns whose root mount has been installed. Transition the rootns from ROOTNS_READY through ROOTNS_FORKING to ROOTNS_RUNNING for the first process so it becomes PID 1, serialize concurrent entrants on waitq until bootstrap resolves, and admit subsequent callers into the running PID namespace until teardown begins.

Quoted 4 lines
Quoted 2 lines

Require CAP_SYS_ADMIN in the target user namespace, forbid credential or PR_SET_NO_NEW_PRIVS privilege escalation

Why are you disallowing this if no_new_privs?

For no any good reason at all apparently: no_new_privs is inherited by the child and only restricts privilege gain across execve(), whereas user_namespace transitions are allowed under it.

So yeah, it's a spurious check, and thus I'll drop it.

Quoted 5 lines

This isn't necessarily a showstopper, but fork() is really quite slow in many cases. It would be nice to have a more spawn-like API available. I assume it's possible to open a file in the target's mountns by some sane API even without entering that mountns, as a side effect of how the fsopen / move_mount mechanism works.

If the caller retains the O_PATH fd returned by fsmount() for "/", it is able to open files inside the target mount tree via openat2(..., RESOLVE_IN_ROOT) w/o entering the mount namespace, and pass the resulting fd to execveat().

For avoiding full fork(), there are (at least) two options:

1. A rootns flag in clone3() (e.g., CLONE_INTO_ROOTNS) and a rootns fd in struct clone_args (disallowing incompatible CLONE_NEW*, CLONE_FS, CLONE_THREAD, ...), and callers can pair it with CLONE_VM | CLONE_VFORK.
2. A flags parameter in rootns_enter() (e.g., ROOTNS_ENTER_VFORK), which would map directly to CLONE_VM | CLONE_VFORK.

Quoted 2 lines

--Andy

Br, Jarkko

#16 lore raw

Re: [RFC PATCH 07/13] rootns: Add rootns_enter() system call

Quoted 38 lines · Jarkko Sakkinen
Quoted 13 lines · Andy Lutomirski
Quoted 12 lines · Jarkko Sakkinen

Multithreaded userspace daemons cannot call setns(CLONE_NEWUSER) or safely mutate process-wide filesystem state in place before spawning a child into a target namespace set.

Add the rootns_enter() system call to fork a child process directly into a rootns whose root mount has been installed. Transition the rootns from ROOTNS_READY through ROOTNS_FORKING to ROOTNS_RUNNING for the first process so it becomes PID 1, serialize concurrent entrants on waitq until bootstrap resolves, and admit subsequent callers into the running PID namespace until teardown begins.

Quoted 4 lines
Quoted 2 lines

Require CAP_SYS_ADMIN in the target user namespace, forbid credential or PR_SET_NO_NEW_PRIVS privilege escalation

Why are you disallowing this if no_new_privs?

For no any good reason at all apparently: no_new_privs is inherited by the child and only restricts privilege gain across execve(), whereas user_namespace transitions are allowed under it.

So yeah, it's a spurious check, and thus I'll drop it.

Quoted 5 lines

This isn't necessarily a showstopper, but fork() is really quite slow in many cases. It would be nice to have a more spawn-like API available. I assume it's possible to open a file in the target's mountns by some sane API even without entering that mountns, as a side effect of how the fsopen / move_mount mechanism works.

If the caller retains the O_PATH fd returned by fsmount() for "/", it is able to open files inside the target mount tree via openat2(..., RESOLVE_IN_ROOT) w/o entering the mount namespace, and pass the resulting fd to execveat().

Quoted 7 lines

For avoiding full fork(), there are (at least) two options:

1. A rootns flag in clone3() (e.g., CLONE_INTO_ROOTNS) and a rootns fd in struct clone_args (disallowing incompatible CLONE_NEW*, CLONE_FS, CLONE_THREAD, ...), and callers can pair it with CLONE_VM | CLONE_VFORK.
2. A flags parameter in rootns_enter() (e.g., ROOTNS_ENTER_VFORK), which would map directly to CLONE_VM | CLONE_VFORK.

There's also been some work on using a pidfd-like object to build and spawn a subprocess. Supporting that would make sense, but I don't know to what extent these projects should block each other.

Signature · 2 lines
Andy Lutomirski
AMA Capital Management, LLC
#17 lore raw

Re: [RFC PATCH 07/13] rootns: Add rootns_enter() system call

In reply to Jarkko Sakkinen
Thank you for your contribution! Sashiko AI review found 7 potential issues to consider: - [Critical] cred: privilege escalation and NNP bypass in may_enter_rootns_creds() - [High] cred: missing…

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider:
- [Critical] cred: privilege escalation and NNP bypass in may_enter_rootns_creds()
- [High] cred: missing dumpability reset in copy_creds() on rootns entry
- [High] rootns: refcount underflow and UAF of rootns via setns() on pid_ns
- [High] rootns: sys_rootns_enter() calls kernel_clone() without arch fork wrappers
- [Medium] nsproxy: missing timens_commit() in copy_namespaces() on rootns entry
- [Medium] fork: stale rootns->root used in copy_fs() after pivot_root()
- [Medium] rootns: rootns_may_setns() rejects setns() to inherited rootns namespaces
--

commit 2b3b027946b3cddbb69540b1d520fd1496bf137c
Author: Jarkko Sakkinen <[email protected]>

rootns: Add rootns_enter() system call

This commit introduces the rootns_enter() system call to fork a child process directly into a configured rootns, along with credential checks and namespace provenance tracking for setns().

Quoted 4 lines
kernel/cred.c +0 -0
index d01df40a9a386..97d334db7758a 100644

[ ... ]

Quoted 12 lines
kernel/cred.c +8 -0
@@ -251,6 +255,25 @@ struct cred *prepare_exec_creds(void)
 	return new;
 }
 
+static bool cred_cap_issubset(const struct cred *set,
+			      const struct cred *subset);
+
+static bool may_enter_rootns_creds(const struct cred *old,
+				   const struct cred *target)
+{
+	if (cred_cap_issubset(old, target) &&
+	    uid_eq(old->euid, target->euid) &&

kernel/cred.c struct cred *prepare_exec_creds(void) · line 275

Quoted 10 lines
kernel/cred.c +10 -0
+	    gid_eq(old->egid, target->egid))
+		return true;
+
+	if (task_no_new_privs(current) || old->user_ns == target->user_ns)
+		return false;
+
+	return ns_capable(target->user_ns->parent, CAP_SYS_ADMIN) &&
+	       ns_capable(target->user_ns->parent, CAP_SETUID) &&
+	       ns_capable(target->user_ns->parent, CAP_SETGID);
+}

[Severity: Critical]
Can a process bypass PR_SET_NO_NEW_PRIVS, regain dropped credentials, or escape an LSM domain through may_enter_rootns_creds()?

When may_enter_rootns_creds() succeeds, copy_creds() replaces the child's entire struct cred with dup_creds(rootns->cred). The early return runs before the task_no_new_privs(current) check and only compares euid, egid, and cred_cap_issubset(old, target). For a ROOTNS_USER namespace where old->euid is target->user_ns->owner, cred_cap_issubset() returns true even if old dropped capabilities or set PR_SET_NO_NEW_PRIVS, letting the child gain full capabilities in target->user_ns.

Even in the same user namespace, the early return does not check real, saved, or fs UIDs/GIDs, group_info, cap_effective, cap_bset, securebits, or the LSM security blob. A process that creates a rootns and later drops real/saved UIDs, clears supplementary groups, drops bounding set bits, or restricts itself with Landlock can call rootns_enter() to spawn a child with the original unrestricted rootns->cred.

In the second branch, CAP_SETUID and CAP_SETGID are checked only against target->user_ns->parent without checking old->user_ns or verifying that target's UIDs, GIDs, and supplementary groups are mapped into target->user_ns->parent. Conversely, when old->user_ns == target->user_ns, a caller holding CAP_SYS_ADMIN, CAP_SETUID, and CAP_SETGID in old->user_ns is rejected if its euid or egid differs from target.

Quoted 14 lines
kernel/cred.c +2 -1
@@ -260,7 +283,8 @@ struct cred *prepare_exec_creds(void)
  * The new process gets the current process's subjective credentials as its
  * objective and subjective credentials
  */
-int copy_creds(struct task_struct *p, u64 clone_flags)
+int copy_creds(struct task_struct *p, u64 clone_flags,
+	       struct rootns *rootns)
 {
 	struct cred *new;
 	int ret;
@@ -283,7 +307,13 @@ int copy_creds(struct task_struct *p, u64 clone_flags)
 		return 0;
 	}
 

kernel/cred.c int copy_creds(struct task_struct *p, u64 clone_flags) · line 318

Quoted 10 lines
kernel/cred.c +7 -1
-	new = prepare_creds();
+	if (rootns) {
+		if (!may_enter_rootns_creds(current_cred(), rootns->cred))
+			return -EPERM;
+		new = dup_creds(rootns->cred);
+	} else {
+		new = prepare_creds();
+	}
 	if (!new)
 		return -ENOMEM;

[Severity: High]
Does switching credentials to rootns->cred in copy_creds() leave p->exec_state->dumpable set to TASK_DUMPABLE_OWNER?

In copy_process(), copy_exec_state() copies current->exec_state->dumpable into p->exec_state before copy_creds() runs. Unlike commit_creds(), copy_creds() does not reset dumpable to suid_dumpable when UIDs, GIDs, or capabilities change. When a privileged daemon calls rootns_enter() to fork into a rootns owned by an unprivileged user, processes inside the target user namespace pass task_still_dumpable() and can ptrace the child before execve(), reading the daemon's duplicated memory or stealing its open file descriptors via pidfd_getfd().

Quoted 4 lines
kernel/fork.c +0 -0
index 99e22b3cd213e..5e23d36b7ac3e 100644

[ ... ]

kernel/fork.c static int copy_fs(u64 clone_flags, struct task_struct *tsk, · line 1691

Quoted 10 lines
kernel/fork.c +4 -0
@@ -1671,6 +1683,10 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk,
 	tsk->real_fs = tsk->fs = copy_fs_struct(fs);
 	if (!tsk->fs)
 		return -ENOMEM;
+	if (rootns) {
+		set_fs_root(tsk->fs, &rootns->root);
+		set_fs_pwd(tsk->fs, &rootns->root);
+	}
 	return 0;
 }

[Severity: Medium]
If a process inside a running rootns changes the root mount with pivot_root() or overmounts "/", will subsequent rootns_enter() calls get a stale root path here?

rootns->root holds the initial mount installed by MOVE_MOUNT_T_ROOTNS_ROOT and is not updated by pivot_root(). Setting tsk->fs root and pwd to &rootns->root gives newly entering tasks the old root mount instead of the current root of rootns->ns->mnt_ns.

Quoted 14 lines
kernel/nsproxy.c +4 -1
index a76837b3ee332..0c6407757d896 100644
@@ -169,13 +169,21 @@ struct nsproxy *create_new_namespaces(u64 flags,
 /*
  * called from clone.  This now handles copy for nsproxy and all
  * namespaces therein.
+ *
+ * Namespaces derived from a rootns member inherit the same rootns domain.
  */
-int copy_namespaces(u64 flags, struct task_struct *tsk)
+int copy_namespaces(u64 flags, struct task_struct *tsk,
+		    struct rootns *rootns)

kernel/nsproxy.c struct nsproxy *create_new_namespaces(u64 flags, · line 186

Quoted 10 lines
kernel/nsproxy.c +5 -0
 {
 	struct nsproxy *old_ns = tsk->nsproxy;
 	struct user_namespace *user_ns = task_cred_xxx(tsk, user_ns);
 	struct nsproxy *new_ns;
 
+	if (rootns) {
+		get_nsproxy(rootns->ns);
+		tsk->nsproxy = rootns->ns;
+		return 0;
+	}

[Severity: Medium]
Does returning early here without calling timens_commit() leave the child with the parent's VDSO vvar mappings when entering a rootns in a different time namespace?

copy_mm() runs before copy_namespaces() and duplicates the caller's vvar PTEs into tsk->mm. When old_ns->time_ns differs from rootns->ns->time_ns, skipping timens_commit() leaves the old vvar mappings in place until execve(), so vDSO clock_gettime() in the child reads the wrong time namespace offsets.

Quoted 4 lines
kernel/rootns.c +0 -0
index f59b2fe9910de..e286c1e753b71 100644

[ ... ]

Quoted 19 lines
kernel/rootns.c +19 -0
+static atomic64_t rootns_id = ATOMIC64_INIT(0);
+
+static void rootns_tag_namespaces(struct rootns *c, const struct nsproxy *old)
+{
+	struct nsproxy *ns = c->ns;
+
+	if (c->cred->user_ns != current_user_ns())
+		c->cred->user_ns->ns.rootns_id = c->id;
+	from_mnt_ns(ns->mnt_ns)->rootns_id = c->id;
+	ns->pid_ns_for_children->ns.rootns_id = c->id;
+	if (ns->uts_ns != old->uts_ns)
+		ns->uts_ns->ns.rootns_id = c->id;
+	if (ns->ipc_ns != old->ipc_ns)
+		ns->ipc_ns->ns.rootns_id = c->id;
+	if (ns->cgroup_ns != old->cgroup_ns)
+		ns->cgroup_ns->ns.rootns_id = c->id;
+	if (ns->net_ns != old->net_ns)
+		ns->net_ns->ns.rootns_id = c->id;
+}

kernel/rootns.c line 83

Quoted 10 lines
kernel/rootns.c +10 -0
+
+bool rootns_may_setns(struct rootns *rootns, struct ns_common *ns)
+{
+	if (!ns)
+		return false;
+	if (!rootns || is_current_namespace(ns))
+		return true;
+
+	return ns->rootns_id == rootns->id;
+}

[Severity: Medium]
Does rootns_may_setns() reject intra-rootns setns() back to a namespace that the rootns inherited at creation time?

rootns_tag_namespaces() only sets c->id on newly created namespaces, so any namespace inherited from the creator (such as time_ns, or UTS, IPC, cgroup, net, or user namespaces omitted from rootns_create() flags) keeps its previous rootns_id. If a task inside the rootns unshares one of those namespace types, is_current_namespace(ns) becomes false for the rootns's initial namespace and ns->rootns_id != rootns->id, causing setns() back to PID 1's namespace to fail with -EPERM.

kernel/rootns.c static struct rootns *create_rootns(unsigned int flags) · line 314

Quoted 8 lines
kernel/rootns.c +1 -0
@@ -249,6 +308,7 @@ static struct rootns *create_rootns(unsigned int flags)
 	c->ns = ns;
 	ns->rootns = c;
 	ns->pid_ns_for_children->rootns = c;
+	rootns_tag_namespaces(c, current->nsproxy);
 	nsproxy_ns_active_get(ns);
 
 	return c;

[Severity: High]
Can an external task joining ns->pid_ns_for_children via setns() trigger a refcount underflow and use-after-free on struct rootns?

create_rootns() sets ns->pid_ns_for_children->rootns = c without taking a reference on c, and marks ns->pid_ns_for_children active in the namespace tree via nsproxy_ns_active_get(ns). The reference on c that pairs with exit_rootns()'s put_rootns(c) is only acquired in copy_rootns() when PID 1 is forked through sys_rootns_enter() in state ROOTNS_FORKING:

kernel/rootns.c:copy_rootns() {
	if (likely(!c || READ_ONCE(c->state) != ROOTNS_FORKING))
		return;

	scoped_guard(spinlock, &c->lock) {
		get_rootns(c);

...
}

Because rootns_may_setns() returns true when task_rootns(current) is NULL, a process outside any rootns can open ns->pid_ns_for_children from nsfs, call setns(fd, CLONE_NEWPID), and fork() PID 1 with args->rootns == NULL. copy_rootns() then skips get_rootns(c), but when that child exits, zap_pid_ns_processes() -> exit_rootns() still calls put_rootns(c), dropping the rootns fd's reference and freeing c while the fd is still open (or dereferencing a dangling pid_ns->rootns if the fd was already closed, since put_rootns() does not clear pid_ns->rootns).

Quoted 1 line
kernel/rootns.c +0 -0
@@ -455,3 +515,85 @@ SYSCALL_DEFINE2(rootns_kill, int, rootnsfd, int, sig)

[ ... ]

Quoted 2 lines
kernel/rootns.c +2 -0
+SYSCALL_DEFINE1(rootns_enter, int, rootnsfd)
+{

[ ... ]

kernel/rootns.c SYSCALL_DEFINE2(rootns_kill, int, rootnsfd, int, sig) · line 586

Quoted 2 lines
kernel/rootns.c +2 -0
+	args.rootns = rootns;
+	ret = kernel_clone(&args);

[Severity: High]
Is calling kernel_clone() directly from a regular C syscall safe on architectures that require fork/clone entry wrappers?

On alpha, m68k, parisc, mips, arc, nios2, and openrisc, fork and clone syscalls enter through assembly wrappers that allocate a switch_stack or save callee-saved registers before calling C code, which copy_thread() then reads from the stack. On sparc, the wrapper must flush register windows via synchronize_user_stack(), and copy_thread() checks whether UREG_G1 is __NR_clone3 to return 0 in the child instead of the parent's PID. Calling kernel_clone() from sys_rootns_enter() bypasses those paths and corrupts the child's register state or return value on those architectures.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
#18 lore raw

RFC PATCH 8/13 fs: Support FSCONFIG_SET_ROOTNS in fsconfig()

In reply to Jarkko Sakkinen

fsopen() initializes a filesystem context from current's user, network, PID, and IPC namespaces, preventing an external manager from creating proc, mqueue, or userns-owned superblocks bound to an unentered root namespace.

Add FSCONFIG_SET_ROOTNS so callers holding CAP_SYS_ADMIN in the target rootns user namespace can bind a newly opened fs_context to that rootns once before offering parameters. Update fc->net_ns, switch fc->user_ns for non-global FS_USERNS_MOUNT or FS_USERNS_DELEGATABLE filesystems whose mounter fsuid/fsgid map into the rootns user namespace, and pass the rootns to ->set_rootns() for proc and mqueue.

---
 fs/fsopen.c                | 74 +++++++++++++++++++++++++++++++++++---
 fs/proc/root.c             | 13 +++++++
 include/linux/fs_context.h |  3 ++
 include/uapi/linux/mount.h |  1 +
 ipc/mqueue.c               | 12 +++++++
 5 files changed, 99 insertions(+), 4 deletions(-)
fs/fsopen.c +70 -4
index 70024870fefa..98d407fd249b 100644
@@ -13,9 +13,14 @@
 #include <linux/security.h>
 #include <linux/anon_inodes.h>
 #include <linux/namei.h>
+#include <linux/capability.h>
+#include <linux/nsproxy.h>
+#include <linux/rootns.h>
+#include <linux/user_namespace.h>
 #include <linux/file.h>
 #include <uapi/linux/mount.h>
 #include <linux/audit.h>
+#include <net/net_namespace.h>
 #include "internal.h"
 #include "mount.h"
 
@@ -41,6 +46,48 @@ static inline const char *fetch_message_locked(struct fc_log *log, size_t len,
 	return p;
 }
 
+/**
+ * DOC: FSCONFIG_SET_ROOTNS
+ *
+ * ``fsconfig(fsfd, FSCONFIG_SET_ROOTNS, NULL, NULL, rootnsfd)`` binds a newly
+ * opened filesystem context to @rootnsfd once before any parameters are
+ * supplied (subsequent calls fail with ``-EBUSY``).
+ *
+ * The caller must hold ``CAP_SYS_ADMIN`` in the target ``rootns`` user
+ * namespace. ``fc->net_ns`` is switched to the ``rootns`` network namespace,
+ * ``fc->user_ns`` is delegated for non-global ``FS_USERNS_MOUNT`` or
+ * ``FS_USERNS_DELEGATABLE`` filesystems when the mounter ``fsuid``/``fsgid``
+ * map into the target user namespace, and ``proc`` and ``mqueue`` contexts
+ * bind to the target ``rootns`` PID and IPC namespaces.
+ */
+static int fsconfig_set_rootns(struct fs_context *fc, struct fs_parameter *param)
+{
+	struct user_namespace *user_ns;
+	struct rootns *c;
+
+	if (!is_rootns_file(param->file))
+		return -EINVAL;
+
+	c = param->file->private_data;
+	user_ns = c->cred->user_ns;
+	if (!ns_capable(user_ns, CAP_SYS_ADMIN))
+		return -EPERM;
+
+	put_net(fc->net_ns);
+	fc->net_ns = get_net(c->ns->net_ns);
+	if (!fc->global &&
+	    (fc->fs_type->fs_flags & (FS_USERNS_MOUNT | FS_USERNS_DELEGATABLE)) &&
+	    kuid_has_mapping(user_ns, fc->cred->fsuid) &&
+	    kgid_has_mapping(user_ns, fc->cred->fsgid)) {
+		put_user_ns(fc->user_ns);
+		fc->user_ns = get_user_ns(user_ns);
+	}
+	if (fc->ops->set_rootns)
+		fc->ops->set_rootns(fc, c);
+	fc->phase = FS_CONTEXT_CREATE_PARAMS;
+	return 0;
+}
+
 /*
  * Allow the user to read back any error, warning or informational messages.
  * Only one message is returned for each read(2) call.
@@ -147,7 +194,7 @@ SYSCALL_DEFINE2(fsopen, const char __user *, _fs_name, unsigned int, flags)
 	if (IS_ERR(fc))
 		return PTR_ERR(fc);
 
-	fc->phase = FS_CONTEXT_CREATE_PARAMS;
+	fc->phase = FS_CONTEXT_CREATE_NS;
 
 	ret = fscontext_alloc_log(fc);
 	if (ret < 0)
@@ -222,7 +269,8 @@ static int vfs_cmd_create(struct fs_context *fc, bool exclusive)
 	struct super_block *sb;
 	int ret;
 
-	if (fc->phase != FS_CONTEXT_CREATE_PARAMS)
+	if (fc->phase != FS_CONTEXT_CREATE_NS &&
+	    fc->phase != FS_CONTEXT_CREATE_PARAMS)
 		return -EBUSY;
 
 	if (!mount_capable(fc))
@@ -298,9 +346,16 @@ static int vfs_fsconfig_locked(struct fs_context *fc, int cmd,
 		return vfs_cmd_create(fc, true);
 	case FSCONFIG_CMD_RECONFIGURE:
 		return vfs_cmd_reconfigure(fc);
+	case FSCONFIG_SET_ROOTNS:
+		if (fc->phase != FS_CONTEXT_CREATE_NS)
+			return -EBUSY;
+		return fsconfig_set_rootns(fc, param);
+
 	default:
-		if (fc->phase != FS_CONTEXT_CREATE_PARAMS &&
-		    fc->phase != FS_CONTEXT_RECONF_PARAMS)
+		if (fc->phase == FS_CONTEXT_CREATE_NS)
+			fc->phase = FS_CONTEXT_CREATE_PARAMS;
+		else if (fc->phase != FS_CONTEXT_CREATE_PARAMS &&
+			 fc->phase != FS_CONTEXT_RECONF_PARAMS)
 			return -EBUSY;
 
 		return vfs_parse_fs_param(fc, param);
@@ -390,6 +445,10 @@ SYSCALL_DEFINE5(fsconfig,
 		if (!_key || _value || aux < 0)
 			return -EINVAL;
 		break;
+	case FSCONFIG_SET_ROOTNS:
+		if (_key || _value || aux < 0)
+			return -EINVAL;
+		break;
 	case FSCONFIG_CMD_CREATE:
 	case FSCONFIG_CMD_CREATE_EXCL:
 	case FSCONFIG_CMD_RECONFIGURE:
@@ -457,6 +516,12 @@ SYSCALL_DEFINE5(fsconfig,
 			goto out_key;
 		param.dirfd = aux;
 		break;
+	case FSCONFIG_SET_ROOTNS:
+		ret = -EBADF;
+		param.file = fget(aux);
+		if (!param.file)
+			goto out_key;
+		break;
 	default:
 		break;
 	}
@@ -482,6 +547,7 @@ SYSCALL_DEFINE5(fsconfig,
 			putname(param.name);
 		break;
 	case FSCONFIG_SET_FD:
+	case FSCONFIG_SET_ROOTNS:
 		if (param.file)
 			fput(param.file);
 		break;
fs/proc/root.c +13 -0
index 7fbbe92bf73a..5976029ad3f8 100644
@@ -15,6 +15,8 @@
 #include <linux/sched/stat.h>
 #include <linux/module.h>
 #include <linux/bitops.h>
+#include <linux/nsproxy.h>
+#include <linux/rootns.h>
 #include <linux/user_namespace.h>
 #include <linux/fs_context.h>
 #include <linux/mount.h>
@@ -323,6 +325,16 @@ static int proc_get_tree(struct fs_context *fc)
 	return get_tree_nodev(fc, proc_fill_super);
 }
 
+static void proc_set_rootns(struct fs_context *fc, struct rootns *rootns)
+{
+	struct proc_fs_context *ctx = fc->fs_private;
+
+	put_pid_ns(ctx->pid_ns);
+	ctx->pid_ns = get_pid_ns(rootns->ns->pid_ns_for_children);
+	put_user_ns(fc->user_ns);
+	fc->user_ns = get_user_ns(ctx->pid_ns->user_ns);
+}
+
 static void proc_fs_context_free(struct fs_context *fc)
 {
 	struct proc_fs_context *ctx = fc->fs_private;
@@ -334,6 +346,7 @@ static void proc_fs_context_free(struct fs_context *fc)
 static const struct fs_context_operations proc_fs_context_ops = {
 	.free		= proc_fs_context_free,
 	.parse_param	= proc_parse_param,
+	.set_rootns	= proc_set_rootns,
 	.get_tree	= proc_get_tree,
 	.reconfigure	= proc_reconfigure,
 };
include/linux/fs_context.h +3 -0
index d1727dffecc5..cb978273c8bc 100644
@@ -21,6 +21,7 @@ struct file_system_type;
 struct mnt_namespace;
 struct net;
 struct pid_namespace;
+struct rootns;
 struct super_block;
 struct user_namespace;
 struct vfsmount;
@@ -36,6 +37,7 @@ enum fs_context_purpose {
  * Userspace usage phase for fsopen/fspick.
  */
 enum fs_context_phase {
+	FS_CONTEXT_CREATE_NS,		/* Set namespaces for sb creation */
 	FS_CONTEXT_CREATE_PARAMS,	/* Loading params for sb creation */
 	FS_CONTEXT_CREATING,		/* A superblock is being created */
 	FS_CONTEXT_AWAITING_MOUNT,	/* Superblock created, awaiting fsmount() */
@@ -117,6 +119,7 @@ struct fs_context_operations {
 	int (*dup)(struct fs_context *fc, struct fs_context *src_fc);
 	int (*parse_param)(struct fs_context *fc, struct fs_parameter *param);
 	int (*parse_monolithic)(struct fs_context *fc, void *data);
+	void (*set_rootns)(struct fs_context *fc, struct rootns *rootns);
 	int (*get_tree)(struct fs_context *fc);
 	int (*reconfigure)(struct fs_context *fc);
 };
include/uapi/linux/mount.h +1 -0
index ac865edac517..cb55cfcfc92e 100644
@@ -105,6 +105,7 @@ enum fsconfig_command {
 	FSCONFIG_CMD_CREATE	= 6,	/* Create new or reuse existing superblock */
 	FSCONFIG_CMD_RECONFIGURE = 7,	/* Invoke superblock reconfiguration */
 	FSCONFIG_CMD_CREATE_EXCL = 8,	/* Create new superblock, fail if reusing existing superblock */
+	FSCONFIG_SET_ROOTNS	= 9,	/* Set a rootns, supplied by fd */
 };
 
 /*
ipc/mqueue.c +12 -0
index 322c3dd98c44..a85ca188d370 100644
@@ -32,6 +32,7 @@
 #include <linux/mutex.h>
 #include <linux/nsproxy.h>
 #include <linux/pid.h>
+#include <linux/rootns.h>
 #include <linux/ipc_namespace.h>
 #include <linux/user_namespace.h>
 #include <linux/slab.h>
@@ -400,6 +401,16 @@ static struct inode *mqueue_get_inode(struct super_block *sb,
 	return ERR_PTR(ret);
 }
 
+static void mqueue_set_rootns(struct fs_context *fc, struct rootns *rootns)
+{
+	struct mqueue_fs_context *ctx = fc->fs_private;
+
+	put_ipc_ns(ctx->ipc_ns);
+	ctx->ipc_ns = get_ipc_ns(rootns->ns->ipc_ns);
+	put_user_ns(fc->user_ns);
+	fc->user_ns = get_user_ns(ctx->ipc_ns->user_ns);
+}
+
 static int mqueue_fill_super(struct super_block *sb, struct fs_context *fc)
 {
 	struct inode *inode;
@@ -1613,6 +1624,7 @@ static const struct super_operations mqueue_super_ops = {
 
 static const struct fs_context_operations mqueue_fs_context_ops = {
 	.free		= mqueue_fs_context_free,
+	.set_rootns	= mqueue_set_rootns,
 	.get_tree	= mqueue_get_tree,
 };
 
Signature · 1 line
2.47.3
#19 lore raw

Re: [RFC PATCH 08/13] fs: Support FSCONFIG_SET_ROOTNS in fsconfig()

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Critical] fs: fsconfig_set_rootns() replaces fc->net_ns after init_fs_context() runs - [High] fs: proc…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Critical] fs: fsconfig_set_rootns() replaces fc->net_ns after init_fs_context() runs
- [High] fs: proc: missing pidns_is_ancestor() check in proc_set_rootns()
- [High] fs: broken fc->user_ns delegation in fsconfig_set_rootns() --

commit c40a472d45a1ca48a5976af47a79bdbf753d63b0
Author: Jarkko Sakkinen <[email protected]>

fs: Support FSCONFIG_SET_ROOTNS in fsconfig()

This commit adds the FSCONFIG_SET_ROOTNS command to fsconfig() so a newly opened filesystem context can be bound to a target rootns file descriptor before parameters are parsed.

Quoted 4 lines
fs/fsopen.c +0 -0
index 70024870fefa2..98d407fd249bc 100644

[ ... ]

Quoted 5 lines
fs/fsopen.c +5 -0
+static int fsconfig_set_rootns(struct fs_context *fc, struct fs_parameter *param)
+{
+	struct user_namespace *user_ns;
+	struct rootns *c;
+

fs/fsopen.c static inline const char *fetch_message_locked(struct fc_log *log, size_t len, · line 77

Quoted 10 lines
fs/fsopen.c +10 -0
+	if (!is_rootns_file(param->file))
+		return -EINVAL;
+
+	c = param->file->private_data;
+	user_ns = c->cred->user_ns;
+	if (!ns_capable(user_ns, CAP_SYS_ADMIN))
+		return -EPERM;
+
+	put_net(fc->net_ns);
+	fc->net_ns = get_net(c->ns->net_ns);

[Severity: Critical]
Can replacing and dropping fc->net_ns here after fc->fs_type->init_fs_context() has already run during fsopen() cause a use-after-free on ctx->net in kAFS?

alloc_fs_context() invokes init_fs_context() during fsopen(), where afs_init_fs_context() caches an unreferenced net_generic pointer from the initial fc->net_ns:

fs/afs/super.c:afs_init_fs_context() {
	...
	ctx->net = afs_net(fc->net_ns);

	/* Default to the workstation cell. */
	cell = afs_find_cell(ctx->net, NULL, 0, afs_cell_trace_use_fc);
	if (IS_ERR(cell))
		cell = NULL;
	ctx->cell = cell;
	...
}

When fsconfig_set_rootns() calls put_net(fc->net_ns), an unprivileged caller in a user and network namespace can let that initial network namespace exit so cleanup_net() frees struct net and its pernet struct afs_net, and then call fsconfig(fsfd, FSCONFIG_SET_STRING, "source", "#cell:vol", 0) to trigger a use-after-free in afs_parse_source() -> afs_lookup_cell(ctx->net, ...).

In addition, nfsd_init_fs_context() and rpc_init_fs_context() set fc->user_ns from fc->net_ns->user_ns during fsopen(), so switching fc->net_ns afterwards leaves fc->user_ns bound to the fsopen() caller's user namespace and bypasses the sget_fc() non-initial user_ns check. nfs_init_fs_context() also evaluates fc->net_ns != &init_net during fsopen() when setting NFS_MOUNT_NETUNREACH_FATAL, which becomes stale once fc->net_ns changes.

fs/fsopen.c static inline const char *fetch_message_locked(struct fc_log *log, size_t len, · line 89

Quoted 12 lines
fs/fsopen.c +12 -0
+	if (!fc->global &&
+	    (fc->fs_type->fs_flags & (FS_USERNS_MOUNT | FS_USERNS_DELEGATABLE)) &&
+	    kuid_has_mapping(user_ns, fc->cred->fsuid) &&
+	    kgid_has_mapping(user_ns, fc->cred->fsgid)) {
+		put_user_ns(fc->user_ns);
+		fc->user_ns = get_user_ns(user_ns);
+	}
+	if (fc->ops->set_rootns)
+		fc->ops->set_rootns(fc, c);
+	fc->phase = FS_CONTEXT_CREATE_PARAMS;
+	return 0;
+}

[Severity: High]
Does gating the fc->user_ns update on kuid_has_mapping() and kgid_has_mapping() silently skip user namespace delegation for an unentered ROOTNS_USER rootns?

When rootns_create() creates a rootns with ROOTNS_USER, create_user_ns() initializes user_ns->uid_map and user_ns->gid_map with zero extents, and sys_rootns_enter() rejects entering the rootns with -ENOENT while its state is ROOTNS_EMPTY before "/" is mounted. Because no ID mappings can exist yet in that unentered user namespace (or when a host manager's fsuid/fsgid lies outside the container's subordinate ID range), kuid_has_mapping() and kgid_has_mapping() return false and fsconfig_set_rootns() returns 0 without updating fc->user_ns, causing privileged managers to create init_user_ns-owned superblocks and unprivileged callers to fail mount_capable(fc) with -EPERM.

Meanwhile, mqueue_set_rootns() unconditionally sets fc->user_ns to ctx->ipc_ns->user_ns even when current_fsuid() and current_fsgid() are unmapped there, leaving the root inode created by mqueue_fill_super() -> mqueue_get_inode() with unmapped i_uid and i_gid. Conversely, when ID mappings do exist and fc->user_ns is switched to a target user_ns that differs from current_user_ns(), FS_USERNS_MOUNT filesystems such as overlayfs (ovl_fill_super() and ovl_parse_param()) and binfmt_misc (bm_fill_super()) explicitly check fc->user_ns != current_user_ns() and fail with -EINVAL.

[ ... ]

Quoted 4 lines
fs/proc/root.c +0 -0
index 7fbbe92bf73a7..5976029ad3f80 100644

[ ... ]

fs/proc/root.c static int proc_get_tree(struct fs_context *fc) · line 336

Quoted 9 lines
fs/proc/root.c +9 -0
+static void proc_set_rootns(struct fs_context *fc, struct rootns *rootns)
+{
+	struct proc_fs_context *ctx = fc->fs_private;
+
+	put_pid_ns(ctx->pid_ns);
+	ctx->pid_ns = get_pid_ns(rootns->ns->pid_ns_for_children);
+	put_user_ns(fc->user_ns);
+	fc->user_ns = get_user_ns(ctx->pid_ns->user_ns);
+}

[Severity: High]
Does proc_set_rootns() allow a task in a child or sibling PID namespace to mount procfs for a non-descendant PID namespace by omitting a pidns_is_ancestor() check?

proc_parse_pidns_param(), pidns_install(), and sys_rootns_enter() all require pidns_is_ancestor(target, task_active_pid_ns(current)) so a process confined to a sub-PID namespace cannot access or mount procfs for an ancestor or sibling PID namespace. Because fsconfig_set_rootns() only checks ns_capable(user_ns, CAP_SYS_ADMIN) and proc_set_rootns() unconditionally binds ctx->pid_ns to rootns->ns->pid_ns_for_children, a process in a child PID namespace within the same user namespace that receives a rootnsfd can mount procfs for that outer or sibling PID namespace.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
#20 lore raw

RFC PATCH 9/13 fs: Support installing rootns mount trees via move_mount()

In reply to Jarkko Sakkinen

A newly created rootns starts with an empty nullfs-rooted mount namespace, and move_mount() only resolves target paths against the caller's own filesystem view.

Add MOVE_MOUNT_T_ROOTNS_ROOT to populate a rootns mount tree through its file descriptor before or after entry. Installing "/" attaches a detached anonymous mount tree onto the nullfs root of the rootns mount namespace once and transitions the rootns to ROOTNS_READY; relative target paths attach anonymous mounts underneath the installed rootns root while verifying the destination mount namespace.

Allocate fsmount() anonymous namespaces in fc->user_ns, check target user namespace CAP_SYS_ADMIN for MOVE_MOUNT_T_ROOTNS_ROOT instead of caller may_mount(), and lock moved mount trees when crossing user namespace boundaries.

---
 fs/namespace.c             | 176 ++++++++++++++++++++++++++++++++-----
 include/uapi/linux/mount.h |   3 +-
 2 files changed, 155 insertions(+), 24 deletions(-)
fs/namespace.c +153 -23
index aecd05ac0170..5376d0230899 100644
@@ -34,6 +34,7 @@
 #include <linux/mnt_idmapping.h>
 #include <linux/pidfs.h>
 #include <linux/nstree.h>
+#include <linux/rootns.h>
 
 #include "pnode.h"
 #include "internal.h"
@@ -2564,6 +2565,8 @@ int count_mounts(struct mnt_namespace *ns, struct mount *mnt)
 enum mnt_tree_flags_t {
 	MNT_TREE_BENEATH = BIT(0),
 	MNT_TREE_PROPAGATION = BIT(1),
+	MNT_TREE_ROOTNS = BIT(2),
+	MNT_TREE_ROOTNS_INIT = BIT(3),
 };
 
 /**
@@ -3781,6 +3784,7 @@ static int do_move_mount(const struct path *old_path,
 	struct mount *old = real_mount(old_path->mnt);
 	int err;
 	bool beneath = flags & MNT_TREE_BENEATH;
+	bool lock_tree;
 
 	if (!path_mounted(old_path))
 		return -EINVAL;
@@ -3792,7 +3796,13 @@ static int do_move_mount(const struct path *old_path,
 	if (IS_ERR(mp.parent))
 		return PTR_ERR(mp.parent);
 
-	if (check_mnt(old)) {
+	if (flags & MNT_TREE_ROOTNS) {
+		if (!anon_ns_root(old) || old->mnt_ns == mp.parent->mnt_ns)
+			return -EINVAL;
+		if ((flags & MNT_TREE_ROOTNS_INIT) &&
+		    mp.parent != real_mount(new_path->mnt))
+			return -EBUSY;
+	} else if (check_mnt(old)) {
 		/* if the source is in our namespace... */
 		/* ... it should be detachable from parent */
 		if (!mnt_has_parent(old) || IS_MNT_LOCKED(old))
@@ -3845,7 +3855,16 @@ static int do_move_mount(const struct path *old_path,
 	if (mount_is_ancestor(old, mp.parent))
 		return -ELOOP;
 
-	return attach_recursive_mnt(old, &mp);
+	lock_tree = (flags & MNT_TREE_ROOTNS) &&
+		    old->mnt_ns->user_ns != mp.parent->mnt_ns->user_ns;
+	err = attach_recursive_mnt(old, &mp);
+	if (!err && lock_tree) {
+		scoped_guard(mount_writer) {
+			lock_mnt_tree(old);
+			old->mnt.mnt_flags |= MNT_LOCKED;
+		}
+	}
+	return err;
 }
 
 static int do_move_mount_old(const struct path *path, const char *old_name)
@@ -4699,7 +4718,7 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 		return FD_ADD((flags & FSMOUNT_CLOEXEC) ? O_CLOEXEC : 0,
 			      open_new_namespace(&new_path, MOUNT_COPY_NEW));
 
-	ns = alloc_mnt_ns(current->nsproxy->mnt_ns->user_ns, true);
+	ns = alloc_mnt_ns(fc->user_ns, true);
 	if (IS_ERR(ns))
 		return PTR_ERR(ns);
 	mnt = real_mount(new_path.mnt);
@@ -4739,6 +4758,127 @@ static inline int vfs_move_mount(const struct path *from_path,
 	return do_move_mount(from_path, to_path, mflags);
 }
 
+static int lookup_move_mount_from(int from_dfd,
+				  const char __user *from_pathname,
+				  unsigned int flags, struct path *from_path)
+{
+	unsigned int uflags = 0;
+	unsigned int lflags = 0;
+
+	if (flags & MOVE_MOUNT_F_EMPTY_PATH)
+		uflags = AT_EMPTY_PATH;
+
+	CLASS(filename_maybe_null, from_name)(from_pathname, uflags);
+	if (!from_name && from_dfd >= 0) {
+		CLASS(fd_raw, f_from)(from_dfd);
+		if (fd_empty(f_from))
+			return -EBADF;
+
+		*from_path = fd_file(f_from)->f_path;
+		path_get(from_path);
+		return 0;
+	}
+
+	if (flags & MOVE_MOUNT_F_SYMLINKS)
+		lflags |= LOOKUP_FOLLOW;
+	if (flags & MOVE_MOUNT_F_AUTOMOUNTS)
+		lflags |= LOOKUP_AUTOMOUNT;
+	return filename_lookup(from_dfd, from_name, lflags, from_path, NULL);
+}
+
+/**
+ * DOC: MOVE_MOUNT_T_ROOTNS_ROOT
+ *
+ * ``MOVE_MOUNT_T_ROOTNS_ROOT`` installs detached anonymous mount trees into a
+ * target ``rootns`` control fd supplied as ``to_dfd``:
+ *
+ * 1. ``to_pathname`` of ``"/"`` attaches the initial root mount onto the
+ *    ``nullfs`` root of the ``rootns`` mount namespace at most once and
+ *    transitions the ``rootns`` to ``ROOTNS_READY``.
+ * 2. Relative ``to_pathname`` values resolve beneath the installed ``rootns``
+ *    root inside the ``rootns`` mount namespace.
+ * 3. Capability is checked against ``CAP_SYS_ADMIN`` in the target ``rootns``
+ *    user namespace, and source trees crossing user namespace boundaries are
+ *    locked with ``MNT_LOCKED`` and locked mount flags.
+ */
+static int move_mount_rootns(int from_dfd, const char __user *from_pathname,
+			     int to_dfd, const char __user *to_pathname,
+			     unsigned int flags, enum mnt_tree_flags_t mflags)
+{
+	struct path from_path __free(path_put) = {};
+	struct path to_path __free(path_put) = {};
+	struct mnt_namespace *rootns_mnt_ns;
+	unsigned int lflags;
+	struct rootns *rootns;
+	bool is_root;
+	int ret;
+
+	CLASS(filename_maybe_null, to_name)(to_pathname, AT_EMPTY_PATH);
+	if (IS_ERR(to_name))
+		return PTR_ERR(to_name);
+	if (!to_name)
+		return -EINVAL;
+
+	CLASS(fd, f_rootns)(to_dfd);
+	if (fd_empty(f_rootns))
+		return -EBADF;
+	if (!is_rootns_file(fd_file(f_rootns)))
+		return -EINVAL;
+
+	rootns = fd_file(f_rootns)->private_data;
+	if (!ns_capable(rootns->cred->user_ns, CAP_SYS_ADMIN))
+		return -EPERM;
+
+	rootns_mnt_ns = rootns->ns->mnt_ns;
+	is_root = to_name->name[0] == '/' && to_name->name[1] == '\0';
+	if (is_root) {
+		if (flags & MOVE_MOUNT_BENEATH)
+			return -EINVAL;
+		if (READ_ONCE(rootns->state) != ROOTNS_EMPTY)
+			return -EBUSY;
+
+		to_path.mnt = mntget(&rootns_mnt_ns->root->mnt);
+		to_path.dentry = dget(rootns_mnt_ns->root->mnt.mnt_root);
+		mflags |= MNT_TREE_ROOTNS_INIT;
+	} else {
+		if (to_name->name[0] == '/')
+			return -EINVAL;
+
+		scoped_guard(spinlock, &rootns->lock) {
+			if (rootns->state == ROOTNS_EMPTY)
+				return -ENOENT;
+		}
+
+		lflags = 0;
+		if (flags & MOVE_MOUNT_T_SYMLINKS)
+			lflags |= LOOKUP_FOLLOW;
+		if (flags & MOVE_MOUNT_T_AUTOMOUNTS)
+			lflags |= LOOKUP_AUTOMOUNT;
+		ret = filename_lookup(AT_FDCWD, to_name, lflags, &to_path,
+				      &rootns->root);
+		if (ret)
+			return ret;
+		if (real_mount(to_path.mnt)->mnt_ns != rootns_mnt_ns)
+			return -EINVAL;
+	}
+
+	ret = lookup_move_mount_from(from_dfd, from_pathname, flags,
+				     &from_path);
+	if (ret)
+		return ret;
+
+	ret = vfs_move_mount(&from_path, &to_path, mflags | MNT_TREE_ROOTNS);
+	if (!ret && is_root) {
+		scoped_guard(spinlock, &rootns->lock) {
+			path_get(&from_path);
+			rootns->root = from_path;
+			WRITE_ONCE(rootns->state, ROOTNS_READY);
+		}
+	}
+
+	return ret;
+}
+
 /*
  * Move a mount from one place to another.  In combination with
  * fsopen()/fsmount() this is used to install a new mount and in combination
@@ -4758,7 +4898,7 @@ SYSCALL_DEFINE5(move_mount,
 	enum mnt_tree_flags_t mflags = 0;
 	int ret = 0;
 
-	if (!may_mount())
+	if (!(flags & MOVE_MOUNT_T_ROOTNS_ROOT) && !may_mount())
 		return -EPERM;
 
 	if (flags & ~MOVE_MOUNT__MASK)
@@ -4771,6 +4911,13 @@ SYSCALL_DEFINE5(move_mount,
 	if (flags & MOVE_MOUNT_SET_GROUP)	mflags |= MNT_TREE_PROPAGATION;
 	if (flags & MOVE_MOUNT_BENEATH)		mflags |= MNT_TREE_BENEATH;
 
+	if (unlikely(flags & MOVE_MOUNT_T_ROOTNS_ROOT)) {
+		if (flags & (MOVE_MOUNT_T_EMPTY_PATH | MOVE_MOUNT_SET_GROUP))
+			return -EINVAL;
+		return move_mount_rootns(from_dfd, from_pathname,
+					 to_dfd, to_pathname, flags, mflags);
+	}
+
 	uflags = 0;
 	if (flags & MOVE_MOUNT_T_EMPTY_PATH)
 		uflags = AT_EMPTY_PATH;
@@ -4794,25 +4941,8 @@ SYSCALL_DEFINE5(move_mount,
 			return ret;
 	}
 
-	uflags = 0;
-	if (flags & MOVE_MOUNT_F_EMPTY_PATH)
-		uflags = AT_EMPTY_PATH;
-
-	CLASS(filename_maybe_null,from_name)(from_pathname, uflags);
-	if (!from_name && from_dfd >= 0) {
-		CLASS(fd_raw, f_from)(from_dfd);
-		if (fd_empty(f_from))
-			return -EBADF;
-
-		return vfs_move_mount(&fd_file(f_from)->f_path, &to_path, mflags);
-	}
-
-	lflags = 0;
-	if (flags & MOVE_MOUNT_F_SYMLINKS)
-		lflags |= LOOKUP_FOLLOW;
-	if (flags & MOVE_MOUNT_F_AUTOMOUNTS)
-		lflags |= LOOKUP_AUTOMOUNT;
-	ret = filename_lookup(from_dfd, from_name, lflags, &from_path, NULL);
+	ret = lookup_move_mount_from(from_dfd, from_pathname, flags,
+				     &from_path);
 	if (ret)
 		return ret;
 
include/uapi/linux/mount.h +2 -1
index cb55cfcfc92e..7224a43af51d 100644
@@ -75,9 +75,10 @@
 #define MOVE_MOUNT_T_SYMLINKS		0x00000010 /* Follow symlinks on to path */
 #define MOVE_MOUNT_T_AUTOMOUNTS		0x00000020 /* Follow automounts on to path */
 #define MOVE_MOUNT_T_EMPTY_PATH		0x00000040 /* Empty to path permitted */
+#define MOVE_MOUNT_T_ROOTNS_ROOT	0x00000080 /* Set as rootns root */
 #define MOVE_MOUNT_SET_GROUP		0x00000100 /* Set sharing group instead */
 #define MOVE_MOUNT_BENEATH		0x00000200 /* Mount beneath top mount */
-#define MOVE_MOUNT__MASK		0x00000377
+#define MOVE_MOUNT__MASK		0x000003f7
 
 /*
  * fsopen() flags.
Signature · 1 line
2.47.3
#21 lore raw

Re: [RFC PATCH 09/13] fs: Support installing rootns mount trees via move_mount()

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider: - [High] fs: do_move_mount() calls lock_mnt_tree() after attach_recursive_mnt() - [High] fs: relative target…

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider:
- [High] fs: do_move_mount() calls lock_mnt_tree() after attach_recursive_mnt()
- [High] fs: relative target paths in move_mount_rootns() bypass is_root checks
- [High] fs: TOCTOU race on rootns->state in move_mount_rootns() corrupts state
- [High] fs: fsmount() alloc_mnt_ns(fc->user_ns) bypasses submount MNT_LOCKED
- [High] fs: check_for_nsfs_mounts() checks caller mnt_ns instead of rootns target
--

commit b8cf56b982aa2378115c847c099e10376c22e6b8
Author: Jarkko Sakkinen <[email protected]>

fs: Support installing rootns mount trees via move_mount()

This commit adds MOVE_MOUNT_T_ROOTNS_ROOT to move_mount() to allow installing detached anonymous mount trees into a target rootns via its control file descriptor, and allocates fsmount() anonymous mount namespaces in fc->user_ns.

Quoted 4 lines
fs/namespace.c +0 -0
index aecd05ac01705..5376d0230899a 100644

[ ... ]

Quoted 12 lines
fs/namespace.c +7 -1
@@ -3792,7 +3796,13 @@ static int do_move_mount(const struct path *old_path,
 	if (IS_ERR(mp.parent))
 		return PTR_ERR(mp.parent);
 
-	if (check_mnt(old)) {
+	if (flags & MNT_TREE_ROOTNS) {
+		if (!anon_ns_root(old) || old->mnt_ns == mp.parent->mnt_ns)
+			return -EINVAL;
+		if ((flags & MNT_TREE_ROOTNS_INIT) &&
+		    mp.parent != real_mount(new_path->mnt))
+			return -EBUSY;
+	} else if (check_mnt(old)) {

[ ... ]

fs/namespace.c static int do_move_mount(const struct path *old_path, · line 3856

Quoted 3 lines
fs/namespace.c +0 -0
@@ -3845,7 +3855,16 @@ static int do_move_mount(const struct path *old_path,
 	if (mount_is_ancestor(old, mp.parent))
 		return -ELOOP;

[Severity: High]
Just above this line, do_move_mount() calls check_for_nsfs_mounts(old), which checks mnt_ns_loop():

fs/namespace.c:mnt_ns_loop() {
    ...
	return current->nsproxy->mnt_ns->ns.ns_id >= mnt_ns->ns.ns_id;
}

When MNT_TREE_ROOTNS is set, the destination mount namespace is mp.parent->mnt_ns rather than current->nsproxy->mnt_ns. Can a caller in an older mount namespace clone an nsfs mount of rootns_mnt_ns with open_tree(OPEN_TREE_CLONE) and attach it into rootns_mnt_ns via MOVE_MOUNT_T_ROOTNS_ROOT? Because current->nsproxy->mnt_ns->ns.ns_id is smaller than rootns_mnt_ns->ns.ns_id, mnt_ns_loop() returns false, creating an unbreakable reference cycle between rootns_mnt_ns and its nsfs inode that permanently leaks the mount namespace and all mounts inside it.

fs/namespace.c static int do_move_mount(const struct path *old_path, · line 3868

Quoted 12 lines
fs/namespace.c +10 -1
-	return attach_recursive_mnt(old, &mp);
+	lock_tree = (flags & MNT_TREE_ROOTNS) &&
+		    old->mnt_ns->user_ns != mp.parent->mnt_ns->user_ns;
+	err = attach_recursive_mnt(old, &mp);
+	if (!err && lock_tree) {
+		scoped_guard(mount_writer) {
+			lock_mnt_tree(old);
+			old->mnt.mnt_flags |= MNT_LOCKED;
+		}
+	}
+	return err;
 }

[Severity: High]
Does calling lock_mnt_tree(old) after attach_recursive_mnt(old, &mp) happen too late?

Inside attach_recursive_mnt(), when an existing mount q is present at the destination (for example with MOVE_MOUNT_BENEATH or overmounting), q is reparented onto topmost_overmount(old) via mnt_change_mountpoint() and has MNT_LOCKED cleared on it so it remains unmountable. Running lock_mnt_tree(old) afterwards walks into q and all of its descendants (since p != old), setting MNT_LOCKED and MNT_LOCK_* on preexisting mounts in the target rootns and preventing q from being unmounted.

In addition, if mp.parent is a shared mount, propagate_mnt() clones old before lock_mnt_tree(old) runs. Because attach_recursive_mnt() sets user_ns = ns->user_ns (the target rootns user_ns rather than old->mnt_ns->user_ns), child->mnt_parent->mnt_ns->user_ns != user_ns is false for peer and slave mounts in the target user_ns, leaving all propagated copies unlocked without MNT_LOCKED or MNT_LOCK_* flags. Finally, attach_recursive_mnt() commits old and drops mount_lock before mount_writer is re-acquired here, briefly exposing the unlocked tree in rootns_mnt_ns.

fs/namespace.c SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags, · line 4724

Quoted 9 lines
fs/namespace.c +1 -1
@@ -4699,7 +4718,7 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 		return FD_ADD((flags & FSMOUNT_CLOEXEC) ? O_CLOEXEC : 0,
 			      open_new_namespace(&new_path, MOUNT_COPY_NEW));
 
-	ns = alloc_mnt_ns(current->nsproxy->mnt_ns->user_ns, true);
+	ns = alloc_mnt_ns(fc->user_ns, true);
 	if (IS_ERR(ns))
 		return PTR_ERR(ns);
 	mnt = real_mount(new_path.mnt);

[Severity: High]
Can allocating the anonymous mount namespace in fc->user_ns leave host submounts unlocked when a multi-mount tree is installed into an unprivileged rootns?

When a process in init_user_ns configures a context with FSCONFIG_SET_ROOTNS for a ROOTNS_USER rootns (user_ns_B), fc->user_ns is user_ns_B, so fsmount() creates a root mount M_root with M_root->mnt_ns->user_ns == user_ns_B. If the caller then attaches a host submount M_sub from init_user_ns (such as a read-only bind mount or a masking mount) onto M_root via move_mount(), attach_recursive_mnt() moves M_sub into M_root->mnt_ns and calls lock_mnt_tree(M_sub):

fs/namespace.c:lock_mnt_tree() {
    ...
		if (list_empty(&p->mnt_expire) && p != mnt)
			flags |= MNT_LOCKED;
    ...
}

That only sets MNT_LOCKED on descendants p != M_sub, leaving M_sub itself without MNT_LOCKED. When M_root is subsequently installed into the rootns via MOVE_MOUNT_T_ROOTNS_ROOT, old->mnt_ns->user_ns == mp.parent->mnt_ns->user_ns (both are user_ns_B), so lock_tree is false and lock_mnt_tree(M_root) is never called. Tasks in user_ns_B can then unmount M_sub and expose the underlying directory.

Conversely, if the caller attaches a submount that was also created with FSCONFIG_SET_ROOTNS onto M_root, attach_recursive_mnt() sets user_ns to current->nsproxy->mnt_ns->user_ns (because is_anon_ns(M_root->mnt_ns) is true) and spuriously locks the submount; and if an anonymous mount with old->mnt_ns->user_ns != mp.parent->mnt_ns->user_ns is attached via normal move_mount() without MOVE_MOUNT_T_ROOTNS_ROOT, neither do_move_mount() nor attach_recursive_mnt() locks the tree.

[ ... ]

Quoted 4 lines
fs/namespace.c +4 -0
+static int move_mount_rootns(int from_dfd, const char __user *from_pathname,
+			     int to_dfd, const char __user *to_pathname,
+			     unsigned int flags, enum mnt_tree_flags_t mflags)
+{

[ ... ]

Quoted 22 lines
fs/namespace.c +22 -0
+	rootns_mnt_ns = rootns->ns->mnt_ns;
+	is_root = to_name->name[0] == '/' && to_name->name[1] == '\0';
+	if (is_root) {
+		if (flags & MOVE_MOUNT_BENEATH)
+			return -EINVAL;
+		if (READ_ONCE(rootns->state) != ROOTNS_EMPTY)
+			return -EBUSY;
+
+		to_path.mnt = mntget(&rootns_mnt_ns->root->mnt);
+		to_path.dentry = dget(rootns_mnt_ns->root->mnt.mnt_root);
+		mflags |= MNT_TREE_ROOTNS_INIT;
+	} else {
+		if (to_name->name[0] == '/')
+			return -EINVAL;
+
+		scoped_guard(spinlock, &rootns->lock) {
+			if (rootns->state == ROOTNS_EMPTY)
+				return -ENOENT;
+		}
+
+		lflags = 0;
+		if (flags & MOVE_MOUNT_T_SYMLINKS)

fs/namespace.c static inline int vfs_move_mount(const struct path *from_path, · line 4863

Quoted 10 lines
fs/namespace.c +10 -0
+			lflags |= LOOKUP_FOLLOW;
+		if (flags & MOVE_MOUNT_T_AUTOMOUNTS)
+			lflags |= LOOKUP_AUTOMOUNT;
+		ret = filename_lookup(AT_FDCWD, to_name, lflags, &to_path,
+				      &rootns->root);
+		if (ret)
+			return ret;
+		if (real_mount(to_path.mnt)->mnt_ns != rootns_mnt_ns)
+			return -EINVAL;
+	}

[Severity: High]
Can relative target paths such as ".", "subdir/..", or relative symlinks to "/" bypass the is_root checks here?

Because is_root only tests for the literal string "/", passing "." enters the else branch, where filename_lookup(..., &rootns->root) resolves to_path to rootns->root itself:

1. With MOVE_MOUNT_BENEATH, this bypasses the MOVE_MOUNT_BENEATH check in the is_root branch, mounts from_path beneath rootns->root directly onto the nullfs root, and clears MNT_LOCKED on rootns->root in attach_recursive_mnt(), allowing an unprivileged rootns owner to unmount a cross-userns locked root mount.

2. Without MOVE_MOUNT_BENEATH, vfs_move_mount() runs without MNT_TREE_ROOTNS_INIT and overmounts rootns->root without updating rootns->root (and similarly on initial "/" installation if from_path already has overmounts on its root dentry, rootns->root = from_path stores the bottom mount rather than topmost_overmount()), leaving subsequent rootns_enter() tasks and relative lookups trapped in the shadowed lower mount.

Quoted 7 lines
fs/namespace.c +7 -0
+
+	ret = lookup_move_mount_from(from_dfd, from_pathname, flags,
+				     &from_path);
+	if (ret)
+		return ret;
+
+	ret = vfs_move_mount(&from_path, &to_path, mflags | MNT_TREE_ROOTNS);

fs/namespace.c static inline int vfs_move_mount(const struct path *from_path, · line 4880

Quoted 10 lines
fs/namespace.c +10 -0
+	if (!ret && is_root) {
+		scoped_guard(spinlock, &rootns->lock) {
+			path_get(&from_path);
+			rootns->root = from_path;
+			WRITE_ONCE(rootns->state, ROOTNS_READY);
+		}
+	}
+
+	return ret;
+}

[Severity: High]
Can a race on rootns->state when is_root is true overwrite rootns->root and reset a running or dead rootns back to ROOTNS_READY?

CPU0 CPU1
move_mount_rootns(..., "/") move_mount_rootns(..., "/")
READ_ONCE(rootns->state)

    == ROOTNS_EMPTY
                                        READ_ONCE(rootns->state)
                                          == ROOTNS_EMPTY
                                        lookup_move_mount_from()

vfs_move_mount() -> attaches M1
rootns->root = M1
rootns->state = ROOTNS_READY
rootns_enter()
rootns->state = ROOTNS_RUNNING
umount2("/", MNT_DETACH)

    (detaches M1 from nullfs)
                                        vfs_move_mount()
                                          mp.parent == new_path->mnt
                                          attaches M2 onto nullfs
                                        rootns->root = M2
                                        rootns->state = ROOTNS_READY  <-- resets state

Because do_move_mount() with MNT_TREE_ROOTNS_INIT only checks whether rootns_mnt_ns->root currently has an overmount (mp.parent != real_mount(new_path->mnt)), detaching M1 allows CPU1 to succeed. CPU1 then overwrites rootns->root without calling path_put() on M1 (and while concurrent readers in filename_lookup() or copy_fs() may be reading rootns->root without rootns->lock), and resets rootns->state to ROOTNS_READY. A subsequent rootns_enter() will then bootstrap a second init process in copy_rootns(), overwriting c->init_pid without put_pid() and taking a second get_rootns(c) reference that exit_rootns() never drops.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
#22 lore raw

RFC PATCH 10/13 arch: Wire up rootns system calls

In reply to Jarkko Sakkinen

Now that the core root namespace lifecycle and VFS mount-tree installation are in place, expose rootns_create() (473), rootns_wait() (474), rootns_kill() (475), and rootns_enter() (476) across all architecture system call tables and asm-generic unistd.h.

---
 arch/alpha/kernel/syscalls/syscall.tbl      |  4 ++++
 arch/arm/tools/syscall.tbl                  |  4 ++++
 arch/arm64/tools/syscall_32.tbl             |  4 ++++
 arch/m68k/kernel/syscalls/syscall.tbl       |  4 ++++
 arch/microblaze/kernel/syscalls/syscall.tbl |  4 ++++
 arch/mips/kernel/syscalls/syscall_n32.tbl   |  4 ++++
 arch/mips/kernel/syscalls/syscall_n64.tbl   |  4 ++++
 arch/mips/kernel/syscalls/syscall_o32.tbl   |  4 ++++
 arch/parisc/kernel/syscalls/syscall.tbl     |  4 ++++
 arch/powerpc/kernel/syscalls/syscall.tbl    |  4 ++++
 arch/s390/kernel/syscalls/syscall.tbl       |  4 ++++
 arch/sh/kernel/syscalls/syscall.tbl         |  4 ++++
 arch/sparc/kernel/syscalls/syscall.tbl      |  4 ++++
 arch/x86/entry/syscalls/syscall_32.tbl      |  4 ++++
 arch/x86/entry/syscalls/syscall_64.tbl      |  4 ++++
 arch/xtensa/kernel/syscalls/syscall.tbl     |  4 ++++
 include/uapi/asm-generic/unistd.h           | 12 +++++++++++-
 scripts/syscall.tbl                         |  4 ++++
 18 files changed, 79 insertions(+), 1 deletion(-)
arch/alpha/kernel/syscalls/syscall.tbl +4 -0
index 52e3538cc7df..a945b15abe6d 100644
@@ -512,3 +512,7 @@
 580	common	listns				sys_listns
 581	common	rseq_slice_yield		sys_rseq_slice_yield
 582	common	fchroot				sys_fchroot
+583	common	rootns_create			sys_rootns_create
+584	common	rootns_wait			sys_rootns_wait
+585	common	rootns_kill			sys_rootns_kill
+586	common	rootns_enter			sys_rootns_enter
arch/arm/tools/syscall.tbl +4 -0
index 55717ed32c27..a6df8f688a03 100644
@@ -487,3 +487,7 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
+476	common	rootns_enter			sys_rootns_enter
arch/arm64/tools/syscall_32.tbl +4 -0
index df2d1d82fb3c..0fee3f3a6f18 100644
@@ -484,3 +484,7 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait		compat_sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
+476	common	rootns_enter			sys_rootns_enter
arch/m68k/kernel/syscalls/syscall.tbl +4 -0
index ba7a4d8903d0..db99316451d5 100644
@@ -472,3 +472,7 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
+476	common	rootns_enter			sys_rootns_enter
arch/microblaze/kernel/syscalls/syscall.tbl +4 -0
index 76d7cbe2a133..fdd26eb61173 100644
@@ -478,3 +478,7 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
+476	common	rootns_enter			sys_rootns_enter
arch/mips/kernel/syscalls/syscall_n32.tbl +4 -0
index 9ae88e4eac61..3a81da7abd44 100644
@@ -411,3 +411,7 @@
 470	n32	listns				sys_listns
 471	n32	rseq_slice_yield		sys_rseq_slice_yield
 472	n32	fchroot				sys_fchroot
+473	n32	rootns_create			sys_rootns_create
+474	n32	rootns_wait			compat_sys_rootns_wait
+475	n32	rootns_kill			sys_rootns_kill
+476	n32	rootns_enter			sys_rootns_enter
arch/mips/kernel/syscalls/syscall_n64.tbl +4 -0
index 83dc93a0712f..2c38f050d14e 100644
@@ -387,3 +387,7 @@
 470	n64	listns				sys_listns
 471	n64	rseq_slice_yield		sys_rseq_slice_yield
 472	n64	fchroot				sys_fchroot
+473	n64	rootns_create			sys_rootns_create
+474	n64	rootns_wait			sys_rootns_wait
+475	n64	rootns_kill			sys_rootns_kill
+476	n64	rootns_enter			sys_rootns_enter
arch/mips/kernel/syscalls/syscall_o32.tbl +4 -0
index 9c62429c9b7b..3f0344992c20 100644
@@ -460,3 +460,7 @@
 470	o32	listns				sys_listns
 471	o32	rseq_slice_yield		sys_rseq_slice_yield
 472	o32	fchroot				sys_fchroot
+473	o32	rootns_create			sys_rootns_create
+474	o32	rootns_wait			sys_rootns_wait			compat_sys_rootns_wait
+475	o32	rootns_kill			sys_rootns_kill
+476	o32	rootns_enter			sys_rootns_enter
arch/parisc/kernel/syscalls/syscall.tbl +4 -0
index 88adc4016cce..1f3d051a9c56 100644
@@ -471,3 +471,7 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait			compat_sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
+476	common	rootns_enter			sys_rootns_enter
arch/powerpc/kernel/syscalls/syscall.tbl +4 -0
index cfbb70039ff0..610ceedd1a14 100644
@@ -563,3 +563,7 @@
 470	common	listns				sys_listns
 471	nospu	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait			compat_sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
+476	common	rootns_enter			sys_rootns_enter
arch/s390/kernel/syscalls/syscall.tbl +4 -0
index 1b45e68a217b..e9c7021a07e1 100644
@@ -399,3 +399,7 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
+476	common	rootns_enter			sys_rootns_enter
arch/sh/kernel/syscalls/syscall.tbl +4 -0
index ace068dff0de..c122ee2d7cd2 100644
@@ -476,3 +476,7 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
+476	common	rootns_enter			sys_rootns_enter
arch/sparc/kernel/syscalls/syscall.tbl +4 -0
index 5b9fe0e8140f..e7cfd43d616a 100644
@@ -518,3 +518,7 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait			compat_sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
+476	common	rootns_enter			sys_rootns_enter
arch/x86/entry/syscalls/syscall_32.tbl +4 -0
index 2c172ef48dfd..c444d59d0267 100644
@@ -478,3 +478,7 @@
 470	i386	listns			sys_listns
 471	i386	rseq_slice_yield	sys_rseq_slice_yield
 472	i386	fchroot			sys_fchroot
+473	i386	rootns_create		sys_rootns_create
+474	i386	rootns_wait		sys_rootns_wait		compat_sys_rootns_wait
+475	i386	rootns_kill		sys_rootns_kill
+476	i386	rootns_enter		sys_rootns_enter
arch/x86/entry/syscalls/syscall_64.tbl +4 -0
index d5b6045b0090..f331f1ddc330 100644
@@ -397,6 +397,10 @@
 470	common	listns			sys_listns
 471	common	rseq_slice_yield	sys_rseq_slice_yield
 472	common	fchroot			sys_fchroot
+473	common	rootns_create		sys_rootns_create
+474	common	rootns_wait		sys_rootns_wait
+475	common	rootns_kill		sys_rootns_kill
+476	common	rootns_enter		sys_rootns_enter
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
arch/xtensa/kernel/syscalls/syscall.tbl +4 -0
index d354bb231796..7482743ea9b4 100644
@@ -443,3 +443,7 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
+476	common	rootns_enter			sys_rootns_enter
include/uapi/asm-generic/unistd.h +11 -1
index 5b7e77a7c736..2595346d3aac 100644
@@ -867,8 +867,18 @@ __SYSCALL(__NR_rseq_slice_yield, sys_rseq_slice_yield)
 #define __NR_fchroot 472
 __SYSCALL(__NR_fchroot, sys_fchroot)
 
+/* kernel/rootns.c */
+#define __NR_rootns_create 473
+__SYSCALL(__NR_rootns_create, sys_rootns_create)
+#define __NR_rootns_wait 474
+__SC_COMP(__NR_rootns_wait, sys_rootns_wait, compat_sys_rootns_wait)
+#define __NR_rootns_kill 475
+__SYSCALL(__NR_rootns_kill, sys_rootns_kill)
+#define __NR_rootns_enter 476
+__SYSCALL(__NR_rootns_enter, sys_rootns_enter)
+
 #undef __NR_syscalls
-#define __NR_syscalls 473
+#define __NR_syscalls 477
 
 /*
  * 32 bit systems traditionally used different
scripts/syscall.tbl +4 -0
index 0ab531605120..f0e6d70b5260 100644
@@ -413,3 +413,7 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait			compat_sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
+476	common	rootns_enter			sys_rootns_enter
Signature · 1 line
2.47.3
#23 lore raw

Re: [RFC PATCH 10/13] arch: Wire up rootns system calls

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] arch: missing fork wrappers and copy_thread() handling for rootns_enter() - [Medium] powerpc…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] arch: missing fork wrappers and copy_thread() handling for rootns_enter()
- [Medium] powerpc: syscalls: mark rootns syscalls as nospu instead of common
--

commit 6e1db5e1442ac6454b78c4391c7f17751ffafb5b
Author: Jarkko Sakkinen <[email protected]>

arch: Wire up rootns system calls

This commit wires up the rootns_create(), rootns_wait(), rootns_kill(), and rootns_enter() system calls across the architecture syscall tables and asm-generic/unistd.h.

arch/alpha/kernel/syscalls/syscall.tbl line 518

Quoted 12 lines
arch/alpha/kernel/syscalls/syscall.tbl +4 -0
index 52e3538cc7df4..a945b15abe6dd 100644
@@ -512,3 +512,7 @@
 580	common	listns				sys_listns
 581	common	rseq_slice_yield		sys_rseq_slice_yield
 582	common	fchroot				sys_fchroot
+583	common	rootns_create			sys_rootns_create
+584	common	rootns_wait			sys_rootns_wait
+585	common	rootns_kill			sys_rootns_kill
+586	common	rootns_enter			sys_rootns_enter

[Severity: High]
Does wiring rootns_enter directly to sys_rootns_enter corrupt the child process's user registers and leak kernel stack contents on architectures that require a fork-like entry wrapper?

sys_rootns_enter() calls kernel_clone() -> copy_process() -> copy_thread(). On Alpha, normal syscall entry (entSys) pops struct switch_stack before calling the C handler, whereas fork, vfork, clone, and clone3 use fork_like wrappers (alpha_clone3, etc.) to push struct switch_stack and call __save_fpu(). Without that wrapper, copy_thread() copies ((struct switch_stack *)regs) - 1, which holds sys_rootns_enter()'s C stack frame, into childstack and restores kernel stack words into the child's r9-r15 registers in ret_from_fork.

The same issue affects the other architectures in this patch whose normal syscall entry does not save callee-saved registers or register windows before copy_thread():
- m68k needs a SAVE_SWITCH_STACK wrapper like __sys_clone3 so copy_thread() does not populate the child's switch_stack (d6-d7, a3-a6) from the C frame.
- MIPS (o32, n32, n64) needs save_static_function() so s0-s8 are saved into struct pt_regs before copy_thread().
- PA-RISC needs a fork_like wrapper like sys_clone3_wrapper to save r3-r18 and cr27 into task->thread.regs.
- SPARC (32-bit and 64-bit) needs an assembly wrapper like __sys_clone3 / sparc_clone3 to flush register windows and call synchronize_user_stack(), and copy_thread() in process_32.c and process_64.c needs to check for __NR_rootns_enter alongside __NR_clone3 so it does not apply SunOS fork() return conventions (which set the child's %o0 to current->pid instead of 0 and clobber %o1).
- ARC, Nios II, and OpenRISC (via include/uapi/asm-generic/unistd.h and scripts/syscall.tbl) likewise require their callee-saved register / switch_stack wrappers before calling sys_rootns_enter().

[ ... ]

arch/powerpc/kernel/syscalls/syscall.tbl line 569

Quoted 12 lines
arch/powerpc/kernel/syscalls/syscall.tbl +4 -0
index cfbb70039ff00..610ceedd1a14c 100644
@@ -563,3 +563,7 @@
 470	common	listns				sys_listns
 471	nospu	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait			compat_sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
+476	common	rootns_enter			sys_rootns_enter

[Severity: Medium]
Should the rootns syscalls, especially rootns_enter, be marked nospu instead of common on PowerPC?

Entries marked common are included in spu_syscall_table[] and can be invoked by a Cell SPU program via spu_process_callback() -> spu_sys_callback() while the host PowerPC thread is inside spufs_run_spu(). Process creation and wait syscalls (fork, vfork, clone, clone3, waitid) are marked nospu so an SPU context cannot clone the host PPE thread from inside sys_spu_run().

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
#24 lore raw

RFC PATCH 11/13 docs: Document root namespace uAPI

In reply to Jarkko Sakkinen

Userspace container managers need a clear specification of rootns state transitions, mount-tree construction, credential rules, and namespace isolation guarantees.

Add Documentation/userspace-api/rootns.rst to include the kernel-doc sections and system call reference from kernel/rootns.c, include/uapi/linux/rootns.h, fs/fsopen.c, and fs/namespace.c.

---
 Documentation/userspace-api/index.rst  |  1 +
 Documentation/userspace-api/rootns.rst | 35 ++++++++++++++++++++++++++
 2 files changed, 36 insertions(+)
 create mode 100644 Documentation/userspace-api/rootns.rst
Documentation/userspace-api/index.rst +1 -0
index a68b1bea57a8..56d0ac4eb087 100644
@@ -17,6 +17,7 @@ System calls
    :maxdepth: 1
 
    unshare
+   rootns
    futex2
    ebpf/index
    ioctl/index
Documentation/userspace-api/rootns.rst new file +35 -0
new file mode 100644
index 000000000000..66c6dbc0e937
@@ -0,0 +1,35 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+===================
+Root namespace uAPI
+===================
+
+Overview
+========
+
+.. kernel-doc:: kernel/rootns.c
+   :doc: Overview
+
+Flags
+=====
+
+.. kernel-doc:: include/uapi/linux/rootns.h
+
+System calls
+============
+
+.. kernel-doc:: kernel/rootns.c
+   :identifiers: sys_rootns_create sys_rootns_enter sys_rootns_wait
+                 sys_rootns_kill
+
+Filesystem configuration
+========================
+
+.. kernel-doc:: fs/fsopen.c
+   :doc: FSCONFIG_SET_ROOTNS
+
+Mount tree installation
+=======================
+
+.. kernel-doc:: fs/namespace.c
+   :doc: MOVE_MOUNT_T_ROOTNS_ROOT
Signature · 1 line
2.47.3
#25 lore raw

Re: [RFC PATCH 11/13] docs: Document root namespace uAPI

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

Userspace container managers need a clear specification of rootns state transitions, mount-tree construction, credential rules, and namespace isolation guarantees.

Add Documentation/userspace-api/rootns.rst to include the kernel-doc sections and system call reference from kernel/rootns.c, include/uapi/linux/rootns.h, fs/fsopen.c, and fs/namespace.c.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
#26 lore raw

RFC PATCH 12/13 selftests/rootns: Add root namespace test suite

In reply to Jarkko Sakkinen

Verify the root namespace uAPI and security invariants across privileged, unprivileged, and edge-case scenarios.

Add a kselftest harness suite under tools/testing/selftests/rootns exercising rootns creation, init and concurrent bootstrap lifecycle, poll(EPOLLHUP) and WNOHANG/rusage reporting, FSCONFIG_SET_ROOTNS and mount-tree installation, pivot_root() and OPEN_TREE_NAMESPACE inside a rootns, and entry and setns() permission enforcement.

---
 tools/testing/selftests/Makefile          |    1 +
 tools/testing/selftests/rootns/.gitignore |    2 +
 tools/testing/selftests/rootns/Makefile   |    5 +
 tools/testing/selftests/rootns/config     |    9 +
 tools/testing/selftests/rootns/smoke.c    | 1254 +++++++++++++++++++++
 5 files changed, 1271 insertions(+)
 create mode 100644 tools/testing/selftests/rootns/.gitignore
 create mode 100644 tools/testing/selftests/rootns/Makefile
 create mode 100644 tools/testing/selftests/rootns/config
 create mode 100644 tools/testing/selftests/rootns/smoke.c
tools/testing/selftests/Makefile +1 -0
index 07c3719f8b04..7c44f93e57a4 100644
@@ -117,6 +117,7 @@ TARGETS += rdma
 TARGETS += resctrl
 TARGETS += riscv
 TARGETS += rlimits
+TARGETS += rootns
 TARGETS += rseq
 TARGETS += rtc
 TARGETS += rust
tools/testing/selftests/rootns/.gitignore new file +2 -0
new file mode 100644
index 000000000000..9a018c20d310
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0-only
+/smoke
tools/testing/selftests/rootns/Makefile new file +5 -0
new file mode 100644
index 000000000000..79162fba3c2b
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+
+CFLAGS += -Wall -Wextra -O2 -g $(KHDR_INCLUDES)
+TEST_GEN_PROGS := smoke
+include ../lib.mk
tools/testing/selftests/rootns/config new file +9 -0
new file mode 100644
index 000000000000..715b0a1cf6a8
@@ -0,0 +1,9 @@
+CONFIG_CGROUPS=y
+CONFIG_IPC_NS=y
+CONFIG_NET_NS=y
+CONFIG_PID_NS=y
+CONFIG_PROC_FS=y
+CONFIG_ROOTNS=y
+CONFIG_TMPFS=y
+CONFIG_USER_NS=y
+CONFIG_UTS_NS=y
tools/testing/selftests/rootns/smoke.c new file +1254 -0

1,254 lines not on this page · raw message

Signature · 1 line
2.47.3
#27 lore raw

Re: [RFC PATCH 12/13] selftests/rootns: Add root namespace test suite

Thank you for your contribution! Sashiko AI review found 9 potential issues to consider: - [Medium] selftests/rootns: setns tests fail to open /proc/self/ns/mnt and hang - [Medium] selftests/rootns…

Thank you for your contribution! Sashiko AI review found 9 potential issues to consider:
- [Medium] selftests/rootns: setns tests fail to open /proc/self/ns/mnt and hang
- [Medium] selftests/rootns: nested_ns fails with EPERM in unmapped user namespace
- [Medium] selftests/rootns: enter_perms fails under PR_SET_NO_NEW_PRIVS as owner
- [Medium] selftests/rootns: PID 1 exit race with sibling tasks in enter_concurrent
- [Medium] selftests/rootns: missing SKIP() in fixture setup and silent child skips
- [Medium] selftests/rootns: enter_unpriv_user_mntns() fails to restore dumpability
- [Medium] selftests/rootns: fsconfig test fails with EPERM at sys_fsopen() for sysfs
- [Low] selftests/rootns: fallback syscall definitions omit MIPS ABI offsets
- [Low] selftests/rootns: fd leak in create_rootns_as_uid() when waitpid() fails
--

commit 180af99245923a2ffc15ed3bd6aa532d0e868807
Author: Jarkko Sakkinen <[email protected]>

selftests/rootns: Add root namespace test suite

This commit adds a kselftest harness suite under tools/testing/selftests/rootns to test root namespace creation, lifecycle, mount configuration, and permission checks.

Quoted 5 lines
tools/testing/selftests/rootns/smoke.c new file +0 -0
new file mode 100644
index 0000000000000..fdb6a74822204

[ ... ]

tools/testing/selftests/rootns/smoke.c line 49

Quoted 13 lines
tools/testing/selftests/rootns/smoke.c new file +13 -0
+#ifndef __NR_rootns_create
+#ifdef __alpha__
+#define __NR_rootns_create 583
+#define __NR_rootns_wait 584
+#define __NR_rootns_kill 585
+#define __NR_rootns_enter 586
+#else
+#define __NR_rootns_create 473
+#define __NR_rootns_wait 474
+#define __NR_rootns_kill 475
+#define __NR_rootns_enter 476
+#endif
+#endif

[Severity: Low]
On mips, syscall numbers in syscall_*.tbl are offset by the ABI base (4000 for o32, 5000 for n64, and 6000 for n32). Should the fallback definitions account for _MIPS_SIM so builds without updated system headers do not invoke unrelated syscalls?

[ ... ]

Quoted 2 lines
tools/testing/selftests/rootns/smoke.c new file +2 -0
+static int create_rootns_as_uid(uid_t uid, unsigned int flags, int *cfd)
+{

[ ... ]

Quoted 4 lines
tools/testing/selftests/rootns/smoke.c new file +4 -0
+	if (!err) {
+		*cfd = recv_fd(sv[0]);
+		if (*cfd < 0)
+			err = errno;

tools/testing/selftests/rootns/smoke.c line 364

Quoted 10 lines
tools/testing/selftests/rootns/smoke.c new file +10 -0
+	}
+	close(sv[0]);
+
+	if (waitpid(pid, &status, 0) != pid && !err)
+		err = errno;
+	if (!err && (!WIFEXITED(status) || WEXITSTATUS(status)))
+		err = ECHILD;
+
+	return err ? -err : 0;
+}

[Severity: Low]
Does create_rootns_as_uid() leak *cfd if recv_fd() succeeds and waitpid() or the child exit status check then sets err?

[ ... ]

tools/testing/selftests/rootns/smoke.c line 480

Quoted 10 lines
tools/testing/selftests/rootns/smoke.c new file +10 -0
+FIXTURE(rootns) {
+	int cfd;
+};
+
+FIXTURE_SETUP(rootns) {
+	self->cfd = create_test_rootns(false, ROOTNS_ALL_NAMESPACES |
+					ROOTNS_KILL_ON_CLOSE |
+					ROOTNS_CLOSE_ON_EXEC);
+	ASSERT_GE(self->cfd, 0);
+}

[Severity: Medium]
Does FIXTURE_SETUP(rootns) fail all 16 tests instead of skipping when CONFIG_ROOTNS is disabled (ENOSYS) or when the test runs without root privileges (EPERM from sys_fsopen("tmpfs", 0) in mount_root())?

Because rootns is added unconditionally to TARGETS in tools/testing/selftests/Makefile while CONFIG_ROOTNS defaults to n, missing kernel support or privileges should call SKIP(return, ...) with a reason string. Conversely, the child helpers in mount_perms and fsconfig call _exit(0) when unprivileged user namespaces or sysfs are unavailable, which reports a silent pass instead of a skip with a reason.

[ ... ]

Quoted 20 lines
tools/testing/selftests/rootns/smoke.c new file +20 -0
+TEST_F(rootns, nested_ns) {
+	pid_t pid;
+	int nsfd;
+
+	nsfd = open("/proc/self/ns/mnt", O_RDONLY | O_CLOEXEC);
+	ASSERT_GE(nsfd, 0);
+
+	pid = sys_rootns_enter(self->cfd);
+	ASSERT_GE(pid, 0);
+	if (pid == 0) {
+		close(self->cfd);
+
+		if (unshare(CLONE_NEWNS))
+			_exit(1);
+		if (clone_with_flags(CLONE_NEWNS))
+			_exit(2);
+		if (unshare(CLONE_NEWUSER))
+			_exit(3);
+		if (clone_with_flags(CLONE_NEWUSER))
+			_exit(4);

tools/testing/selftests/rootns/smoke.c line 670

Quoted 10 lines
tools/testing/selftests/rootns/smoke.c new file +10 -0
+		if (setns(nsfd, CLONE_NEWNS) != -1 || errno != EPERM)
+			_exit(5);
+
+		close(nsfd);
+		_exit(0);
+	}
+
+	close(nsfd);
+	ASSERT_EQ(reap_child_exit_code(pid), 0);
+}

[Severity: Medium]
Will unshare(CLONE_NEWUSER) and clone_with_flags(CLONE_NEWUSER) always fail with EPERM here?

FIXTURE_SETUP(rootns) creates self->cfd with ROOTNS_ALL_NAMESPACES (which includes ROOTNS_USER), allocating a new user namespace with no UID or GID mappings. When the child enters self->cfd and calls unshare(CLONE_NEWUSER), create_user_ns() checks kuid_has_mapping() and kgid_has_mapping() in the parent user namespace (self->cfd->cred->user_ns) and returns -EPERM, causing the child to exit with status 3. In addition, unshare(CLONE_NEWUSER) places the child into another unmapped user namespace before clone_with_flags(CLONE_NEWUSER) runs, so the second user namespace creation also fails with EPERM unless UID and GID mappings are written first.

Quoted 16 lines
tools/testing/selftests/rootns/smoke.c new file +16 -0
+
+TEST_F(rootns, setns_same) {
+	ssize_t nwritten;
+	pid_t pid1;
+	pid_t pid2;
+	char ch;
+	int nsfd;
+	int sv[2];
+
+	ASSERT_EQ(socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0, sv), 0);
+
+	pid1 = sys_rootns_enter(self->cfd);
+	ASSERT_GE(pid1, 0);
+	if (pid1 == 0) {
+		int ret;
+

tools/testing/selftests/rootns/smoke.c line 696

Quoted 10 lines
tools/testing/selftests/rootns/smoke.c new file +10 -0
+		close(self->cfd);
+		close(sv[0]);
+		ret = send_unshared_mntns_and_wait(sv[1]);
+		close(sv[1]);
+		_exit(ret);
+	}
+	close(sv[1]);
+
+	nsfd = recv_fd(sv[0]);
+	ASSERT_GE(nsfd, 0);

[Severity: Medium]
Does recv_fd(sv[0]) hang in both setns_same and setns_foreign after send_unshared_mntns_and_wait() fails with ENOENT?

Both self->cfd (in FIXTURE_SETUP) and beta_cfd (in setns_foreign) are created via create_test_rootns(false, ...), which mounts an empty tmpfs at /proc instead of procfs:

tools/testing/selftests/rootns/smoke.c:mount_proc() {
	const char *fstype = need_proc ? "proc" : "tmpfs";
}

When pid1 (or beta_pid) enters the rootns and runs send_unshared_mntns_and_wait(), open("/proc/self/ns/mnt", ...) fails with ENOENT and the child exits without calling send_fd(). Because sv is an AF_UNIX SOCK_DGRAM socketpair, closing sv[1] on child exit does not wake a blocking recvmsg() on sv[0], so the parent blocks in recv_fd(sv[0]) until the test harness times out.

[ ... ]

Quoted 17 lines
tools/testing/selftests/rootns/smoke.c new file +17 -0
+static int enter_unpriv_user_mntns(uid_t drop_uid)
+{
+	char map[32];
+	uid_t uid;
+	gid_t gid;
+	int fd;
+	int len;
+
+	if (geteuid() == 0 &&
+	    (setresgid(drop_uid, drop_uid, drop_uid) < 0 ||
+	     setresuid(drop_uid, drop_uid, drop_uid) < 0))
+		return -errno;
+
+	uid = geteuid();
+	gid = getegid();
+	if (unshare(CLONE_NEWUSER | CLONE_NEWNS) < 0)
+		return -errno;

tools/testing/selftests/rootns/smoke.c line 948

Quoted 10 lines
tools/testing/selftests/rootns/smoke.c new file +10 -0
+
+	fd = open("/proc/self/setgroups", O_WRONLY | O_CLOEXEC);
+	if (fd >= 0) {
+		(void)write(fd, "deny\n", 5);
+		close(fd);
+	}
+
+	fd = open("/proc/self/uid_map", O_WRONLY | O_CLOEXEC);
+	if (fd < 0)
+		return -errno;

[Severity: Medium]
When the test runs as root, does enter_unpriv_user_mntns() always fail with -EACCES when opening /proc/self/uid_map?

Dropping privileges with setresgid() and setresuid() clears task dumpability in commit_creds(), which makes /proc/self/uid_map owned by GLOBAL_ROOT_UID. After unshare(CLONE_NEWUSER), GLOBAL_ROOT_UID is unmapped in the new user namespace, so open("/proc/self/uid_map", O_WRONLY | O_CLOEXEC) fails with EACCES unless prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) is called after setresuid(). Because both mount_perms and fsconfig treat -EACCES from enter_unpriv_user_mntns() as _exit(0), both tests silently skip their unprivileged checks when run as root.

[ ... ]

Quoted 18 lines
tools/testing/selftests/rootns/smoke.c new file +18 -0
+TEST_F(rootns, enter_perms) {
+	pid_t pid;
+	int cfd;
+
+	cfd = sys_rootns_create(ROOTNS_ALL_NAMESPACES |
+			    ROOTNS_KILL_ON_CLOSE |
+			    ROOTNS_CLOSE_ON_EXEC);
+	ASSERT_GE(cfd, 0);
+
+	ASSERT_EQ(sys_rootns_enter(cfd), -1);
+	ASSERT_EQ(errno, ENOENT);
+
+	ASSERT_EQ(mount_root(cfd), 0);
+
+	pid = fork();
+	ASSERT_GE(pid, 0);
+	if (pid == 0) {
+		if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0)

tools/testing/selftests/rootns/smoke.c line 1115

Quoted 10 lines
tools/testing/selftests/rootns/smoke.c new file +10 -0
+			_exit(1);
+		if (sys_rootns_enter(cfd) != -1 || errno != EPERM)
+			_exit(2);
+		close(cfd);
+		_exit(0);
+	}
+
+	ASSERT_EQ(reap_child_exit_code(pid), 0);
+	close(cfd);
+}

[Severity: Medium]
Does sys_rootns_enter(cfd) succeed here instead of failing with EPERM?

The child inherits the same credentials that created cfd, so in may_enter_rootns_creds(old, target), cred_cap_issubset(old, target), uid_eq(old->euid, target->euid), and gid_eq(old->egid, target->egid) all hold (as old->user_ns == target->user_ns->parent and old->euid == target->user_ns->owner). may_enter_rootns_creds() returns true before checking task_no_new_privs(current), causing the child to fork into the rootns and exit with status 2.

Quoted 2 lines
tools/testing/selftests/rootns/smoke.c new file +2 -0
+
+TEST_F(rootns, fsconfig) {

[ ... ]

Quoted 26 lines
tools/testing/selftests/rootns/smoke.c new file +26 -0
+	pid = fork();
+	ASSERT_GE(pid, 0);
+	if (pid == 0) {
+		int ucfd;
+		int ret;
+		int sfd;
+
+		ret = enter_unpriv_user_mntns(1000);
+		if (ret == -EPERM || ret == -EACCES || ret == -EINVAL ||
+		    ret == -ENOSPC)
+			_exit(0);
+		if (ret < 0)
+			_exit(1);
+
+		ucfd = sys_rootns_create(ROOTNS_USER | ROOTNS_CLOSE_ON_EXEC);
+		if (ucfd < 0) {
+			if (errno == EPERM || errno == EACCES ||
+			    errno == EINVAL || errno == ENOSPC)
+				_exit(0);
+			_exit(2);
+		}
+
+		sfd = sys_fsopen("sysfs", 0);
+		if (sfd < 0) {
+			if (errno == ENODEV) {
+				close(ucfd);

tools/testing/selftests/rootns/smoke.c line 1170

Quoted 10 lines
tools/testing/selftests/rootns/smoke.c new file +10 -0
+				_exit(0);
+			}
+			_exit(3);
+		}
+
+		if (sys_fsconfig(sfd, FSCONFIG_SET_ROOTNS, NULL, NULL, ucfd) < 0)
+			_exit(4);
+		if (sys_fsconfig(sfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0) != -1 ||
+		    errno != EPERM)
+			_exit(5);

[Severity: Medium]
When enter_unpriv_user_mntns() succeeds, doesn't sys_fsopen("sysfs", 0) fail with EPERM and exit with code 3 before reaching sys_fsconfig()?

enter_unpriv_user_mntns() unshares CLONE_NEWUSER | CLONE_NEWNS without CLONE_NEWNET, so current->nsproxy->net_ns still belongs to the parent user namespace. sysfs_init_fs_context() checks kobj_ns_current_may_mount(KOBJ_NS_TYPE_NET), which requires CAP_SYS_ADMIN in net_ns->user_ns and fails during fsopen("sysfs", 0) with EPERM.

Quoted 10 lines
tools/testing/selftests/rootns/smoke.c new file +10 -0
+
+		close(sfd);
+		close(ucfd);
+		_exit(0);
+	}
+
+	ASSERT_EQ(reap_child_exit_code(pid), 0);
+}
+
+TEST_F(rootns, enter_concurrent) {

[ ... ]

Quoted 20 lines
tools/testing/selftests/rootns/smoke.c new file +20 -0
+			ent_pid = sys_rootns_enter(self->cfd);
+			if (ent_pid < 0)
+				_exit(1);
+			if (ent_pid == 0) {
+				unsigned char my_pid = (unsigned char)getpid();
+
+				if (write(ready_pipe[1], &my_pid, 1) != 1)
+					_exit(2);
+				close(ready_pipe[1]);
+				(void)read(hold_pipe[0], &ch, 1);
+				close(hold_pipe[0]);
+				_exit(0);
+			}
+
+			close(ready_pipe[1]);
+			close(hold_pipe[0]);
+			close(self->cfd);
+			_exit(reap_child_exit_code(ent_pid) == 0 ? 0 : 3);
+		}
+	}

[ ... ]

tools/testing/selftests/rootns/smoke.c line 1247

Quoted 7 lines
tools/testing/selftests/rootns/smoke.c new file +7 -0
+	close(ready_pipe[0]);
+	close(hold_pipe[1]);
+
+	ASSERT_EQ(seen_mask, 0x1eU);
+
+	for (i = 0; i < 4; i++)
+		ASSERT_EQ(reap_child_exit_code(workers[i]), 0);

[Severity: Medium]
Can PID 1 inside the rootns exit before PIDs 2..4 when hold_pipe[1] is closed, killing its siblings with SIGKILL and failing the test?

CPU0 (rootns PID 1) CPU1 (rootns PID 2 / worker)
read(hold_pipe[0]) -> EOF
_exit(0)
zap_pid_ns_processes()
group_send_sig_info(SIGKILL)
killed by SIGKILL reap_child_exit_code(ent_pid)
!WIFEXITED(status) -> returns -2 worker calls _exit(3) <-- test fails

Closing hold_pipe[1] wakes PID 1 and PIDs 2..4 at the same time, and PID 1 was queued first on hold_pipe[0]. If PID 1 reaches zap_pid_ns_processes() before a sibling finishes _exit(0), the sibling is terminated by SIGKILL and reap_child_exit_code() fails because !WIFEXITED(status).

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
#28 lore raw

RFC PATCH 13/13 MAINTAINERS: Add entry for ROOT NAMESPACE

In reply to Jarkko Sakkinen

Record maintainership and mailing list routing for the root namespace subsystem across its uAPI headers, core implementation, documentation, and selftests.

---
 MAINTAINERS | 11 +++++++++++
 1 file changed, 11 insertions(+)
MAINTAINERS +11 -0
index 7e7753a54125..1019266bc077 100644
@@ -24534,6 +24534,17 @@ F:	include/linux/mfd/rohm-bd96802.h
 F:	include/linux/mfd/rohm-generic.h
 F:	include/linux/mfd/rohm-shared.h
 
+ROOT NAMESPACE
+M:	David Howells <[email protected]>
+M:	Jarkko Sakkinen <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	Documentation/userspace-api/rootns.rst
+F:	include/linux/rootns.h
+F:	include/uapi/linux/rootns.h
+F:	kernel/rootns.c
+F:	tools/testing/selftests/rootns/
+
 ROTATION DRIVER FOR ALLWINNER A83T
 M:	Jernej Skrabec <[email protected]>
 L:	[email protected]
Signature · 1 line
2.47.3
#29 lore raw
In reply to Jarkko Sakkinen

Possibly also:

Cc John Johansen <[email protected]>

The cc list was generated via:

	./scripts/get_maintainer.pl --nogit --nogit-fallback --norolestats 00[0-9][1-9]*.patch |  awk '{print "Cc: " $0}' | sort

Br, Jarkko

Quoted 175 lines · Jarkko Sakkinen

OVERVIEW
========

The problem that root namespaces try to resolve is starting a container from a root mount tree that is pre-populated before any process is allowed to run, without inheriting any host mount-tree ancestors.

Work on this feature started originally in 2025 from David Howells' container object patch set [1], but I turned container objects into a namespace of namespace roots and built a new implementation around this premise.

In early 2026, the patch set was left to gather dust in my kernel tree [2]. Then, the other day I saw [3] as was shocked by its over the top complexity and thus, here we are.

Not doubling the number of container frameworks inside Linux kernel is at least a benefit over container object based solutions. Parallel plumbing is an inherent flaw of container objects, and it directly affects on development and maintenance cost of container runtimes.

Also, thanks to better scoped implementation surface, verifying rootns correctness is factors easier than with container objects, and even my early kselftest is meaningful. We know what and where we are testing, which is always great.

Finally, it is more compatible with pre-existing container tooling whereas container objects would have much higher cost.

[1] https://lore.kernel.org/all/155059610368.17079.2220554006494174417.stgit@warthog.procyon.org.uk/
[2] https://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd.git/log/?h=rootns
[3] https://lore.kernel.org/linux-fsdevel/[email protected]/

IMPLEMENTATION
==============

rootns_create() allocates a rootns object backed by a pollable anonymous inode fd, pinning dedicated empty mount (CLONE_EMPTY_MNTNS) and PID namespaces along with any optional namespaces selected in flags.

Before entry, a manager prepares the mount tree through the control fd:
FSCONFIG_SET_ROOTNS binds a newly opened fs_context to the target rootns, and move_mount(..., MOVE_MOUNT_T_ROOTNS_ROOT) installs "/" onto the nullfs root once and attaches relative submounts beneath it.

rootns_enter() forks a child directly into the rootns credentials, nsproxy, and root path without mutating the caller in place. The first entrant becomes PID 1; once it exits and zap_pid_ns_processes() reaps all members, poll() reports EPOLLHUP and rootns_wait() returns init's status and rusage. rootns_kill() walks pid_ns->idr under RCU to signal member thread groups.

Namespaces allocated by member tasks inherit the owning rootns ID in __ns_common_init() so intra-rootns clone(), unshare(), open_tree(), and setns() work while foreign setns() calls fail with -EPERM.

Cc Alexander Viro <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Ben Segall <[email protected]>
Cc Christian Brauner <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc David Howells <[email protected]>
Cc Davidlohr Bueso <[email protected]>
Cc Dietmar Eggemann <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Jan Kara <[email protected]>
Cc Jarkko Sakkinen <[email protected]>
Cc Jonathan Corbet <[email protected]>
Cc Juri Lelli <[email protected]>
Cc Kees Cook <[email protected]>
Cc K Prateek Nayak <[email protected]>
Cc "Liam R. Howlett" <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Manfred Spraul <[email protected]>
Cc Mel Gorman <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Neal Gompa <[email protected]>
Cc Paul Moore <[email protected]>
Cc Pavel Tikhomirov <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Serge Hallyn <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Valentin Schneider <[email protected]>
Cc Vincent Guittot <[email protected]>
Cc Vlastimil Babka <[email protected]>

Jarkko Sakkinen (13):
nsproxy: Pass nsproxy to create_new_namespaces()
rootns: Add core infrastructure for root namespaces
rootns: Track init lifecycle via copy_process() and pid_namespace
rootns: Add rootns_create() system call
rootns: Add rootns_wait() system call
rootns: Add rootns_kill() system call
rootns: Add rootns_enter() system call
fs: Support FSCONFIG_SET_ROOTNS in fsconfig()
fs: Support installing rootns mount trees via move_mount()
arch: Wire up rootns system calls
docs: Document root namespace uAPI
selftests/rootns: Add root namespace test suite
MAINTAINERS: Add entry for ROOT NAMESPACE

 Documentation/userspace-api/index.rst       |    1 +
 Documentation/userspace-api/rootns.rst      |   35 +
 MAINTAINERS                                 |   11 +
 arch/alpha/kernel/syscalls/syscall.tbl      |    4 +
 arch/arm/tools/syscall.tbl                  |    4 +
 arch/arm64/tools/syscall_32.tbl             |    4 +
 arch/m68k/kernel/syscalls/syscall.tbl       |    4 +
 arch/microblaze/kernel/syscalls/syscall.tbl |    4 +
 arch/mips/kernel/syscalls/syscall_n32.tbl   |    4 +
 arch/mips/kernel/syscalls/syscall_n64.tbl   |    4 +
 arch/mips/kernel/syscalls/syscall_o32.tbl   |    4 +
 arch/parisc/kernel/syscalls/syscall.tbl     |    4 +
 arch/powerpc/kernel/syscalls/syscall.tbl    |    4 +
 arch/s390/kernel/syscalls/syscall.tbl       |    4 +
 arch/sh/kernel/syscalls/syscall.tbl         |    4 +
 arch/sparc/kernel/syscalls/syscall.tbl      |    4 +
 arch/x86/entry/syscalls/syscall_32.tbl      |    4 +
 arch/x86/entry/syscalls/syscall_64.tbl      |    4 +
 arch/xtensa/kernel/syscalls/syscall.tbl     |    4 +
 fs/fsopen.c                                 |   74 +-
 fs/namespace.c                              |  176 ++-
 fs/proc/root.c                              |   13 +
 include/linux/compat.h                      |    4 +
 include/linux/cred.h                        |    4 +-
 include/linux/fs_context.h                  |    3 +
 include/linux/ns/ns_common_types.h          |    4 +
 include/linux/nsproxy.h                     |   27 +-
 include/linux/pid_namespace.h               |    4 +
 include/linux/rootns.h                      |   87 ++
 include/linux/sched/task.h                  |    4 +
 include/linux/syscalls.h                    |    5 +
 include/uapi/asm-generic/unistd.h           |   12 +-
 include/uapi/linux/mount.h                  |    4 +-
 include/uapi/linux/rootns.h                 |   38 +
 init/Kconfig                                |    9 +
 ipc/mqueue.c                                |   12 +
 kernel/Makefile                             |    2 +
 kernel/cred.c                               |   70 +-
 kernel/fork.c                               |   29 +-
 kernel/nscommon.c                           |    8 +
 kernel/nsproxy.c                            |   49 +-
 kernel/pid_namespace.c                      |    2 +
 kernel/rootns.c                             |  599 +++++++++
 kernel/sys_ni.c                             |    7 +
 scripts/syscall.tbl                         |    4 +
 tools/testing/selftests/Makefile            |    1 +
 tools/testing/selftests/rootns/.gitignore   |    2 +
 tools/testing/selftests/rootns/Makefile     |    5 +
 tools/testing/selftests/rootns/config       |    9 +
 tools/testing/selftests/rootns/smoke.c      | 1254 +++++++++++++++++++
 50 files changed, 2559 insertions(+), 73 deletions(-)
 create mode 100644 Documentation/userspace-api/rootns.rst
 create mode 100644 include/linux/rootns.h
 create mode 100644 include/uapi/linux/rootns.h
 create mode 100644 kernel/rootns.c
 create mode 100644 tools/testing/selftests/rootns/.gitignore
 create mode 100644 tools/testing/selftests/rootns/Makefile
 create mode 100644 tools/testing/selftests/rootns/config
 create mode 100644 tools/testing/selftests/rootns/smoke.c

--
2.47.3

#30 lore raw
In reply to Jarkko Sakkinen
Quoted 46 lines · Jarkko Sakkinen

OVERVIEW
========

The problem that root namespaces try to resolve is starting a container from a root mount tree that is pre-populated before any process is allowed to run, without inheriting any host mount-tree ancestors.

Work on this feature started originally in 2025 from David Howells' container object patch set [1], but I turned container objects into a namespace of namespace roots and built a new implementation around this premise.

In early 2026, the patch set was left to gather dust in my kernel tree [2]. Then, the other day I saw [3] as was shocked by its over the top complexity and thus, here we are.

Not doubling the number of container frameworks inside Linux kernel is at least a benefit over container object based solutions. Parallel plumbing is an inherent flaw of container objects, and it directly affects on development and maintenance cost of container runtimes.

Also, thanks to better scoped implementation surface, verifying rootns correctness is factors easier than with container objects, and even my early kselftest is meaningful. We know what and where we are testing, which is always great.

Finally, it is more compatible with pre-existing container tooling whereas container objects would have much higher cost.

[1] https://lore.kernel.org/all/155059610368.17079.2220554006494174417.stgit@warthog.procyon.org.uk/
[2] https://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd.git/log/?h=rootns
[3] https://lore.kernel.org/linux-fsdevel/[email protected]/

IMPLEMENTATION
==============

rootns_create() allocates a rootns object backed by a pollable anonymous inode fd, pinning dedicated empty mount (CLONE_EMPTY_MNTNS) and PID namespaces along with any optional namespaces selected in flags.

Before entry, a manager prepares the mount tree through the control fd:
FSCONFIG_SET_ROOTNS binds a newly opened fs_context to the target rootns, and move_mount(..., MOVE_MOUNT_T_ROOTNS_ROOT) installs "/" onto the nullfs root once and attaches relative submounts beneath it.

Quoted 6 lines

rootns_enter() forks a child directly into the rootns credentials, nsproxy, and root path without mutating the caller in place. The first entrant becomes PID 1; once it exits and zap_pid_ns_processes() reaps all members, poll() reports EPOLLHUP and rootns_wait() returns init's status and rusage. rootns_kill() walks pid_ns->idr under RCU to signal member thread groups.

Can you clarify what this new API actually does? I've read this three times, and the best understanding I've come up with is that you've designed a way to create a group of namespaces identified by an fd and you're adding an API to configure and enter them cleanly. Which sounds very sensible. But I'm completely confused as to why a namespace needs to be owned by a "rootns" or why that ownership affects even newly created sub-namespaces.

--Andy

Signature · 2 lines
Andy Lutomirski
AMA Capital Management, LLC
#31 lore raw
Quoted 7 lines · Andy Lutomirski

Can you clarify what this new API actually does? I've read this three times, and the best understanding I've come up with is that you've designed a way to create a group of namespaces identified by an fd and you're adding an API to configure and enter them cleanly. Which sounds very sensible. But I'm completely confused as to why a namespace needs to be owned by a "rootns" or why that ownership affects even newly created sub-namespaces.

I think this would postulate the patch set:

1. A subset of detached namespaces.
2. A dedicated PID namespace for spawning into, signaling members, and polling/waiting on init exit.
3. Initially an empty mount mount namespace that must be populated before going live.

I had to do some head scratching for the second question as I've worked seriously on this already some time ago but I think it was as follows.

If recall it correctly, rootns ownership tracking was meant to stop processes inside a rootns from calling setns() into host or other namespaces of the other containers.

However, user_namespace already enforces namespace ownership for setns(), and adding a separate rootns check prevents legitimately entering a shared external namespace (such as a pre-created netns).

I will drop the rootns ownership tracking.

Quoted 5 lines

--Andy

Signature · 2 lines
Andy Lutomirski
AMA Capital Management, LLC

Br, Jarkko

#32 lore raw
Quoted 24 lines · Jarkko Sakkinen
Quoted 7 lines · Andy Lutomirski

Can you clarify what this new API actually does? I've read this three times, and the best understanding I've come up with is that you've designed a way to create a group of namespaces identified by an fd and you're adding an API to configure and enter them cleanly. Which sounds very sensible. But I'm completely confused as to why a namespace needs to be owned by a "rootns" or why that ownership affects even newly created sub-namespaces.

I think this would postulate the patch set:

1. A subset of detached namespaces.
2. A dedicated PID namespace for spawning into, signaling members, and polling/waiting on init exit.
3. Initially an empty mount mount namespace that must be populated before going live.

I had to do some head scratching for the second question as I've worked seriously on this already some time ago but I think it was as follows.

If recall it correctly, rootns ownership tracking was meant to stop processes inside a rootns from calling setns() into host or other namespaces of the other containers.

Quoted 5 lines

However, user_namespace already enforces namespace ownership for setns(), and adding a separate rootns check prevents legitimately entering a shared external namespace (such as a pre-created netns).

I will drop the rootns ownership tracking.

While the patch set itself is manually coded, I got inspired by LLM agents back then. It was quite clear that in the near future OCI runtimes should try to minimize the live configuration surface.

Another force was that whatever the solution ever can be it should be made migration friendly for OCI runtimes. This led to the conclusion that we need yet another namespace instead of a fully parallel framework.

Br, Jarkko