Skip to contentSkip to conversation

Namespace for namespace roots

RFC PATCH In review Jarkko Sakkinen 3 participants 29 messages Nov 19 – Nov 20

Subsystems (30)
lore
Share & tools
lore
#0 lore raw

v4 cover Namespace for namespace roots

OVERVIEW
========

A root namespace (rootns) is a kernel object backed by a file descriptor that binds together:

1. A full set of detached namespaces owned by a fresh user namespace.
2. A dedicated PID namespace for spawning processes into, signaling members, and polling or waiting on PID 1 exit.
3. An initially empty mount namespace (CLONE_EMPTY_MNTNS) populated directly in its target user namespace before going live, without inheriting host mounts or cloning staged trees, while still allowing new mounts to be attached at runtime.

Work on this feature started in 2025 from David Howells' container object patch set [1], which I turned into a namespace for namespace roots and rebuilt around that premise.

While the patch set is manually written, the original motivation came from isolating LLM agents. Running untrusted agent workloads made it clear that OCI runtimes need to minimize their live configuration surface.

Assembling mounts, credentials, and namespaces inside helper processes with a half-configured container is what I see as the main challenge, and the existential debate around namespaces and container objects is an unfocused discussion topic.

[1] https://lore.kernel.org/all/155059610368.17079.2220554006494174417.stgit@warthog.procyon.org.uk/

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

rootns() allocates a rootns instance backed by a pollable anonymous inode fd, creating a fresh owning user namespace and a full set of detached namespaces: empty mount (CLONE_EMPTY_MNTNS), PID, UTS, IPC, network, cgroup, and time. ioctl(rootnsfd, ROOTNS_GET_NSFD, nstype) returns nsfs file descriptors for individual member namespaces when standalone namespace operations are needed.

Superblocks are configured directly in the target user namespace via fsopen(), FSCONFIG_SET_ROOTNS, and fsmount(), allowing unprivileged callers to assemble FS_USERNS_MOUNT filesystems without holding CAP_SYS_ADMIN in their own user namespace or entering the target user namespace first. move_mount(..., MOVE_MOUNT_T_MNTNS) operates on any non-anonymous mount namespace fd: on an empty mount namespace it installs "/" onto the nullfs root once, and it attaches relative submounts both before entry and into live mount namespaces.

Once "/" is installed, processes are spawned into the rootns via clone3() with CLONE_INTO_ROOTNS and struct clone_args.rootns, without mutating the caller in place. Pairing CLONE_INTO_ROOTNS with CLONE_VFORK and opening the target binary via openat2(..., RESOLVE_IN_ROOT) on the retained "/" mount fd allows spawning with execveat() directly into the target root.

The first entrant becomes PID 1; once it exits and zap_pid_ns_processes() reaps all members, poll() reports EPOLLHUP and ioctl(rootnsfd, ROOTNS_WAIT, &args) returns init's exit status. ioctl(rootnsfd, ROOTNS_KILL, sig) walks pid_ns->idr under tasklist_lock to signal member thread groups, and dedicated LSM hooks mediate rootns allocation, teardown, process entry, and signal delivery.

CHANGES
=======

v4:
- A single syscall API (and shenanigans e.g., in fsconfig).
- I use a similar API model as I used in SGX driver, as like enclaves, containers are "closures". Instead of /dev/sgx_enclave like device file, anon inode is used.
- Consolidate rootns_create(), rootns_wait(), and rootns_kill() into a single rootns() system call plus ROOTNS_WAIT and ROOTNS_KILL ioctls, dropping rusage from ROOTNS_WAIT.
- LSM: lbs_rootns security blob management and security_rootns_alloc(), security_rootns_free(), security_rootns_clone(), and security_rootns_kill() LSM hooks wired into bpf_lsm.
- Disallow CLONE_VM with CLONE_INTO_ROOTNS across time namespaces, require CAP_SYS_CHROOT, preserve caller umask, reset dumpability on user namespace transitions, and fix ROOTNS_WAIT, FSCONFIG_SET_ROOTNS, fsmount(), and MOVE_MOUNT_T_MNTNS locking and permission checks (Sashiko).
- Rewrite selftests/rootns in Python. I used similar structure as I've used in selftests/tpm2. This "along the lines" mimics Cells style container manager. Rootns is a quite typical no policy solution and Cells is a managed solution, and they are at the far ends, which can also be witnessed from the patch set sizes.

The question really is where we want to draw the borderline. I'm neither favoring nor supporting any possible solution because I don't know. I'm just saying where they live as a software stack.
- Update documentation and architecture syscall tables for rootns().

v3:
- The patch set size increased predominantly because the coverage of kselftest had to widened to cover the introduced changes.
- Replace MOVE_MOUNT_T_ROOTNS_ROOT with MOVE_MOUNT_T_MNTNS targeting mnt_ns nsfs fds, and add ioctl(ROOTNS_GET_NSFD) to open member namespace fds (Andy Lutomirski).
- Allow unprivileged fsopen(), FSCONFIG_SET_ROOTNS, and fsmount() to configure and mount FS_USERNS_MOUNT filesystems directly in the target user namespace without entering it first (Andy Lutomirski).
- Fix locking, refcounting, credential/dumpability/timens setup, pivot_root() lookup, and cross-userns mount checks across copy_rootns(), CLONE_INTO_ROOTNS, rootns_kill(), FSCONFIG_SET_ROOTNS, and move_mount() (Sashiko).
- Mark PowerPC rootns syscalls nospu (Sashiko).
- Update documentation and kselftests.

v2:
- Drop rootns provenance tracking (rootns_id and rootns_may_setns()) and rely on user_namespace ownership for setns() isolation (Andy Lutomirski).
- Replace the rootns_enter() system call with clone3(CLONE_INTO_ROOTNS) and struct clone_args.rootns (CLONE_ARGS_SIZE_VER3), allowing CLONE_VM | CLONE_VFORK and compatible per-child clone3() flags (Andy Lutomirski).
- Drop the spurious task_no_new_privs() check in may_enter_rootns_creds() (Andy Lutomirski).
- Update documentation, Kconfig, syscall tables, and kselftests for CLONE_INTO_ROOTNS.

VERSIONS
========

v3: https://lore.kernel.org/linux-fsdevel/[email protected]/
v2: https://lore.kernel.org/linux-fsdevel/[email protected]/
v1: https://lore.kernel.org/linux-fsdevel/[email protected]/

Cc Albert Ou <[email protected]>
Cc Alexander Gordeev <[email protected]>
Cc Alexander Viro <[email protected]>
Cc Alexandre Ghiti <[email protected]>
Cc Andreas Larsson <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Andy Lutomirski <[email protected]>
Cc Andy Lutomirski <[email protected]>
Cc Anna-Maria Behnsen <[email protected]>
Cc Arnd Bergmann <[email protected]>
Cc Ben Segall <[email protected]>
Cc Borislav Petkov <[email protected]>
Cc Casey Schaufler <[email protected]>
Cc Catalin Marinas <[email protected]>
Cc Christian Borntraeger <[email protected]>
Cc Christian Brauner <[email protected]>
Cc "Christophe Leroy (CS GROUP)" <[email protected]>
Cc Chris Zankel <[email protected]>
Cc Dave Hansen <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc David Howells <[email protected]>
Cc Davidlohr Bueso <[email protected]>
Cc "David S. Miller" <[email protected]>
Cc Dietmar Eggemann <[email protected]>
Cc Frederic Weisbecker <[email protected]>
Cc Geert Uytterhoeven <[email protected]>
Cc Hallgrimur H. Gunnarsson <[email protected]>
Cc Heiko Carstens <[email protected]>
Cc Helge Deller <[email protected]>
Cc "H. Peter Anvin" <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc "James E.J. Bottomley" <[email protected]>
Cc Jan Kara <[email protected]>
Cc Jarkko Sakkinen <[email protected]>
Cc John Johansen <[email protected]>
Cc John Paul Adrian Glaubitz <[email protected]>
Cc Jonathan Corbet <[email protected]>
Cc Josef Bacik <[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 Madhavan Srinivasan <[email protected]>
Cc Magnus Lindholm <[email protected]>
Cc Manfred Spraul <[email protected]>
Cc Mark Rutland <[email protected]>
Cc Matt Turner <[email protected]>
Cc Max Filippov <[email protected]>
Cc Mel Gorman <[email protected]>
Cc Michael Ellerman <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Michal Simek <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Neal Gompa <[email protected]>
Cc Nicholas Piggin <[email protected]>
Cc Palmer Dabbelt <[email protected]>
Cc Paul Moore <[email protected]>
Cc Paul Walmsley <[email protected]>
Cc Pavel Tikhomirov <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Richard Henderson <[email protected]>
Cc Rich Felker <[email protected]>
Cc "Ritesh Harjani (IBM)" <[email protected]>
Cc Russell King <[email protected]>
Cc Serge Hallyn <[email protected]>
Cc Shrikanth Hegde <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Sven Schnelle <[email protected]>
Cc Thomas Bogendoerfer <[email protected]>
Cc Thomas Gleixner <[email protected]>
Cc Valentin Schneider <[email protected]>
Cc Vasily Gorbik <[email protected]>
Cc Vincent Guittot <[email protected]>
Cc Vincenzo Frascino <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Will Deacon <[email protected]>
Cc Yoshinori Sato <[email protected]>
Cc Zygmunt Krynicki <[email protected]>

Jarkko Sakkinen (14):
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() system call
rootns: Add ROOTNS_WAIT ioctl
rootns: Add ROOTNS_KILL ioctl
fork: Support CLONE_INTO_ROOTNS in clone3()
fs: Support FSCONFIG_SET_ROOTNS in fsconfig()
fs: Support MOVE_MOUNT_T_MNTNS in move_mount()
security: Add rootns LSM hooks
arch: Wire up rootns() system call
docs: Document root namespace uAPI
selftests/rootns: Add root namespace test suite
MAINTAINERS: Add entry for ROOT NAMESPACE

 Documentation/userspace-api/index.rst         |    1 +
 .../userspace-api/ioctl/ioctl-number.rst      |    1 +
 Documentation/userspace-api/rootns.rst        |   56 +
 MAINTAINERS                                   |   11 +
 arch/alpha/kernel/syscalls/syscall.tbl        |    1 +
 arch/arm/tools/syscall.tbl                    |    1 +
 arch/arm64/tools/syscall_32.tbl               |    1 +
 arch/m68k/kernel/syscalls/syscall.tbl         |    1 +
 arch/microblaze/kernel/syscalls/syscall.tbl   |    1 +
 arch/mips/kernel/syscalls/syscall_n32.tbl     |    1 +
 arch/mips/kernel/syscalls/syscall_n64.tbl     |    1 +
 arch/mips/kernel/syscalls/syscall_o32.tbl     |    1 +
 arch/parisc/kernel/syscalls/syscall.tbl       |    1 +
 arch/powerpc/kernel/syscalls/syscall.tbl      |    1 +
 arch/s390/kernel/syscalls/syscall.tbl         |    1 +
 arch/sh/kernel/syscalls/syscall.tbl           |    1 +
 arch/sparc/kernel/syscalls/syscall.tbl        |    1 +
 arch/x86/entry/syscalls/syscall_32.tbl        |    1 +
 arch/x86/entry/syscalls/syscall_64.tbl        |    1 +
 arch/xtensa/kernel/syscalls/syscall.tbl       |    1 +
 fs/devpts/inode.c                             |    2 +
 fs/filesystems.c                              |   15 +
 fs/fs_context.c                               |   21 +-
 fs/fsopen.c                                   |  139 +-
 fs/internal.h                                 |    6 +
 fs/namespace.c                                |  272 +++-
 fs/nsfs.c                                     |   64 +
 fs/proc/root.c                                |   18 +
 include/linux/cred.h                          |    4 +-
 include/linux/fs_context.h                    |    6 +
 include/linux/lsm_hook_defs.h                 |    7 +
 include/linux/lsm_hooks.h                     |    3 +
 include/linux/mnt_namespace.h                 |    2 +
 include/linux/nsfs.h                          |    2 +
 include/linux/nsproxy.h                       |    9 +-
 include/linux/pid_namespace.h                 |    4 +
 include/linux/rootns.h                        |   92 ++
 include/linux/sched/task.h                    |    8 +
 include/linux/security.h                      |   30 +
 include/linux/syscalls.h                      |    1 +
 include/linux/time_namespace.h                |   13 +
 include/linux/user_namespace.h                |    7 +
 include/uapi/asm-generic/unistd.h             |    6 +-
 include/uapi/linux/mount.h                    |    4 +-
 include/uapi/linux/rootns.h                   |   83 ++
 include/uapi/linux/sched.h                    |    5 +
 init/Kconfig                                  |    9 +
 ipc/mqueue.c                                  |   13 +
 kernel/Makefile                               |    2 +
 kernel/bpf/bpf_lsm.c                          |   10 +
 kernel/cred.c                                 |   32 +-
 kernel/fork.c                                 |   95 +-
 kernel/nsproxy.c                              |   41 +-
 kernel/pid_namespace.c                        |    2 +
 kernel/rootns.c                               |  581 +++++++++
 kernel/sys_ni.c                               |    3 +
 kernel/user_namespace.c                       |   12 +-
 scripts/syscall.tbl                           |    1 +
 security/lsm_init.c                           |    6 +
 security/security.c                           |   86 ++
 tools/testing/selftests/Makefile              |    1 +
 tools/testing/selftests/rootns/Makefile       |    5 +
 tools/testing/selftests/rootns/config         |   10 +
 .../testing/selftests/rootns/rootns_cells.py  | 1076 +++++++++++++++
 tools/testing/selftests/rootns/rootns_test.py | 1161 +++++++++++++++++
 tools/testing/selftests/rootns/test_smoke.sh  |   11 +
 66 files changed, 3977 insertions(+), 88 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/Makefile
 create mode 100644 tools/testing/selftests/rootns/config
 create mode 100755 tools/testing/selftests/rootns/rootns_cells.py
 create mode 100755 tools/testing/selftests/rootns/rootns_test.py
 create mode 100755 tools/testing/selftests/rootns/test_smoke.sh

--
2.47.3

#1 lore raw

RFC PATCH v4 1/14 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

RFC PATCH v4 2/14 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 full detached namespace set and an init process behind a pollable file descriptor.

Add struct rootns, its lifecycle states, reference counting, uAPI creation flags, ROOTNS_GET_NSFD ioctl, 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, report EPOLLHUP from poll() once the rootns reaches ROOTNS_DEAD, and allow holders with CAP_SYS_ADMIN in the rootns user namespace to open member nsfs fds.

---
 fs/nsfs.c                   |  64 +++++++++++++
 include/linux/nsfs.h        |   2 +
 include/linux/rootns.h      |  60 ++++++++++++
 include/uapi/linux/rootns.h |  44 +++++++++
 init/Kconfig                |   9 ++
 kernel/Makefile             |   2 +
 kernel/rootns.c             | 185 ++++++++++++++++++++++++++++++++++++
 7 files changed, 366 insertions(+)
 create mode 100644 include/linux/rootns.h
 create mode 100644 include/uapi/linux/rootns.h
 create mode 100644 kernel/rootns.c
fs/nsfs.c +64 -0
index 8179d69da038..1de51cd47508 100644
@@ -711,3 +711,67 @@ void nsproxy_ns_active_put(struct nsproxy *ns)
 	ns_ref_active_put(ns->time_ns);
 	ns_ref_active_put(ns->time_ns_for_children);
 }
+
+int nsproxy_open_namespace(struct nsproxy *nsp, struct user_namespace *user_ns,
+			   unsigned long nstype)
+{
+	struct ns_common *ns = NULL;
+
+	switch (nstype) {
+	case CLONE_NEWNS:
+		if (ns_ref_get(nsp->mnt_ns))
+			ns = to_ns_common(nsp->mnt_ns);
+		break;
+#ifdef CONFIG_CGROUPS
+	case CLONE_NEWCGROUP:
+		if (ns_ref_get(nsp->cgroup_ns))
+			ns = to_ns_common(nsp->cgroup_ns);
+		break;
+#endif
+#ifdef CONFIG_UTS_NS
+	case CLONE_NEWUTS:
+		if (ns_ref_get(nsp->uts_ns))
+			ns = to_ns_common(nsp->uts_ns);
+		break;
+#endif
+#ifdef CONFIG_IPC_NS
+	case CLONE_NEWIPC:
+		if (ns_ref_get(nsp->ipc_ns))
+			ns = to_ns_common(nsp->ipc_ns);
+		break;
+#endif
+#ifdef CONFIG_USER_NS
+	case CLONE_NEWUSER:
+		if (ns_ref_get(user_ns))
+			ns = to_ns_common(user_ns);
+		break;
+#endif
+#ifdef CONFIG_PID_NS
+	case CLONE_NEWPID:
+		if (ns_ref_get(nsp->pid_ns_for_children))
+			ns = to_ns_common(nsp->pid_ns_for_children);
+		break;
+#endif
+#ifdef CONFIG_NET_NS
+	case CLONE_NEWNET:
+		if (ns_ref_get(nsp->net_ns))
+			ns = to_ns_common(nsp->net_ns);
+		break;
+#endif
+	case CLONE_NEWTIME:
+#ifdef CONFIG_TIME_NS
+		if (ns_ref_get(nsp->time_ns))
+			ns = to_ns_common(nsp->time_ns);
+		break;
+#else
+		return -EOPNOTSUPP;
+#endif
+	default:
+		return -EINVAL;
+	}
+
+	if (!ns)
+		return -ESRCH;
+
+	return open_namespace(ns);
+}
include/linux/nsfs.h +2 -0
index 731b67fc2fec..bfba790ee1a7 100644
@@ -39,5 +39,7 @@ void nsfs_init(void);
 
 void nsproxy_ns_active_get(struct nsproxy *ns);
 void nsproxy_ns_active_put(struct nsproxy *ns);
+int nsproxy_open_namespace(struct nsproxy *nsp, struct user_namespace *user_ns,
+			   unsigned long nstype);
 
 #endif /* _LINUX_NSFS_H */
include/linux/rootns.h new file +60 -0

60 lines not on this page · raw message

include/uapi/linux/rootns.h new file +44 -0

44 lines not on this page · raw message

init/Kconfig +9 -0
index c8a7cfa60a6e..ed93dd11e6ac 100644
@@ -1281,6 +1281,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, user namespace, namespace set, and init
+	  process lifecycle via rootns(), rootns ioctls, and clone3() with
+	  CLONE_INTO_ROOTNS.
+
 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 +185 -0

185 lines not on this page · raw message

Signature · 1 line
2.47.3
#3 lore raw

RFC PATCH v4 3/14 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 once all processes in the root namespace have terminated, without serializing normal fork() and exit() paths inside the container.

Commit the bootstrap child reaper, bind pid_ns->rootns, and wake waiters in copy_rootns() after attach_pid(PIDTYPE_PID), 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/pid_namespace.h |  4 ++++
 include/linux/rootns.h        | 15 ++++++++++++++
 kernel/fork.c                 |  3 +++
 kernel/pid_namespace.c        |  2 ++
 kernel/rootns.c               | 38 +++++++++++++++++++++++++++++++++++
 5 files changed, 62 insertions(+)
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 +15 -0
index 3f59415efadb..0557ce75195d 100644
@@ -13,6 +13,8 @@
 struct file;
 struct nsproxy;
 struct pid;
+struct pid_namespace;
+struct task_struct;
 struct user_namespace;
 
 enum rootns_state {
@@ -41,6 +43,9 @@ 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 pid *pid,
+		 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)
 {
@@ -55,6 +60,16 @@ static inline bool is_rootns_file(struct file *file)
 {
 	return false;
 }
+
+static inline void copy_rootns(struct task_struct *tsk, struct pid *pid,
+			       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 +3 -0
index 5efceb8d58a7..08fc28ad1eed 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>
@@ -2576,6 +2577,8 @@ __latent_entropy struct task_struct *copy_process(
 					  &p->signal->thread_head);
 		}
 		attach_pid(p, PIDTYPE_PID);
+		if (thread_group_leader(p))
+			copy_rootns(p, pid, NULL);
 		nr_threads++;
 	}
 	total_forks++;
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 +38 -0
index 3bbf7677080e..bde7cf4baebe 100644
@@ -183,3 +183,41 @@ bool is_rootns_file(struct file *file)
 {
 	return file->f_op == &rootns_fops;
 }
+
+void copy_rootns(struct task_struct *tsk, struct pid *pid, struct rootns *c)
+{
+	if (likely(!c || !is_child_reaper(pid)))
+		return;
+
+	scoped_guard(spinlock, &c->lock) {
+		if (c->state != ROOTNS_FORKING)
+			return;
+		ns_of_pid(pid)->rootns = get_rootns(c);
+		WRITE_ONCE(c->init_pid, get_pid(pid));
+		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;
+	int status;
+
+	if (!c)
+		return;
+
+	leader = tsk->group_leader;
+	status = (tsk->signal->flags & SIGNAL_GROUP_EXIT) ?
+		 tsk->signal->group_exit_code : leader->exit_code;
+
+	scoped_guard(spinlock, &c->lock) {
+		c->exit_code = status;
+		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
#4 lore raw

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

Quoted 131 lines · Jarkko Sakkinen

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

Commit the bootstrap child reaper, bind pid_ns->rootns, and wake waiters
in copy_rootns() after attach_pid(PIDTYPE_PID), 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/pid_namespace.h |  4 ++++ include/linux/rootns.h        | 15 ++++++++++++++ kernel/fork.c                 |  3 +++ kernel/pid_namespace.c        |  2 ++ kernel/rootns.c               | 38
+++++++++++++++++++++++++++++++++++

 5 files changed, 62 insertions(+)
include/linux/pid_namespace.h +0 -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 */

include/linux/pid_namespace.h +0 -0
@@ -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 */

include/linux/pid_namespace.h +3 -0
+#ifdef CONFIG_ROOTNS
+	struct rootns *rootns;
+#endif

  struct ns_common ns;
  struct work_struct work;
 } __randomize_layout;

include/linux/rootns.h +2 -0
index 3f59415efadb..0557ce75195d 100644
@@ -13,6 +13,8 @@
  struct file;
  struct nsproxy;
  struct pid;
+struct pid_namespace;
+struct task_struct;
  struct user_namespace;


 enum rootns_state {

include/linux/rootns.h +3 -0
@@ -41,6 +43,9 @@ 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 pid *pid,
+		 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)

 {

include/linux/rootns.h +10 -0
@@ -55,6 +60,16 @@ static inline bool is_rootns_file(struct file
 *file)
  {
  	return false;
  }
+
+static inline void copy_rootns(struct task_struct *tsk, struct pid
 *pid,
+			       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 +3 -0
index 5efceb8d58a7..08fc28ad1eed 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>
@@ -2576,6 +2577,8 @@ __latent_entropy struct task_struct
 *copy_process(
  					  &p->signal->thread_head);
  		}
  		attach_pid(p, PIDTYPE_PID);
+		if (thread_group_leader(p))
+			copy_rootns(p, pid, NULL);
  		nr_threads++;
  	}

  total_forks++;

kernel/pid_namespace.c +1 -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"

kernel/pid_namespace.c +0 -0
@@ -280,6 +281,7 @@ void zap_pid_ns_processes(struct pid_namespace
 *pid_ns)
  		current->signal->group_exit_code = pid_ns->reboot;
Quoted 1 line

Dear Jarkko,

kernel/pid_namespace.c void zap_pid_ns_processes(struct pid_namespace *pid_ns) · line 284

Quoted 2 lines

  acct_exit_ns(pid_ns);

kernel/pid_namespace.c +1 -0
+	exit_rootns(pid_ns, me);

We have a very similar mechanism around pidfd's to track exit information for a task. As far as I can see we already have (struct rootns *)->init_pid reference, so we can get exit information for free (look for PIDFD_INFO_EXIT).

Kind regards,
Alex

Quoted 51 lines

  return;
 }

kernel/rootns.c +2 -0
index 3bbf7677080e..bde7cf4baebe 100644
@@ -183,3 +183,41 @@ bool is_rootns_file(struct file *file)
  {
  	return file->f_op == &rootns_fops;
  }
+
+void copy_rootns(struct task_struct *tsk, struct pid *pid, struct

rootns *c)

kernel/rootns.c +15 -0
+{
+	if (likely(!c || !is_child_reaper(pid)))
+		return;
+
+	scoped_guard(spinlock, &c->lock) {
+		if (c->state != ROOTNS_FORKING)
+			return;
+		ns_of_pid(pid)->rootns = get_rootns(c);
+		WRITE_ONCE(c->init_pid, get_pid(pid));
+		WRITE_ONCE(c->state, ROOTNS_RUNNING);
+	}
+	wake_up_all(&c->waitq);
+}
+
+void exit_rootns(struct pid_namespace *pid_ns, struct task_struct

*tsk)

kernel/rootns.c +21 -0
+{
+	struct rootns *c = pid_ns->rootns;
+	struct task_struct *leader;
+	int status;
+
+	if (!c)
+		return;
+
+	leader = tsk->group_leader;
+	status = (tsk->signal->flags & SIGNAL_GROUP_EXIT) ?
+		 tsk->signal->group_exit_code : leader->exit_code;
+
+	scoped_guard(spinlock, &c->lock) {
+		c->exit_code = status;
+		WRITE_ONCE(c->state, ROOTNS_DEAD);
+	}
+
+	pid_ns->rootns = NULL;
+	wake_up_poll(&c->waitq, EPOLLHUP);
+	put_rootns(c);
+}
#5 lore raw

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

Quoted 9 lines · Alexander Mikhalitsyn

Dear Jarkko,

kernel/pid_namespace.c void zap_pid_ns_processes(struct pid_namespace *pid_ns) · line 284

Quoted 2 lines

  acct_exit_ns(pid_ns);

kernel/pid_namespace.c +1 -0
+	exit_rootns(pid_ns, me);

We have a very similar mechanism around pidfd's to track exit information for a task. As far as I can see we already have (struct rootns *)->init_pid reference, so we can get exit information for free (look for PIDFD_INFO_EXIT).

Thanks for mentioning. I'll see if I can leverage it.

If something like this is found, it is partly due long history of this code i.e., not planned/opionated choice :-)

Quoted 3 lines

Kind regards,
Alex

Br, Jarkko

#6 lore raw

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

Quoted 11 lines · Jarkko Sakkinen
Quoted 9 lines · Alexander Mikhalitsyn

Dear Jarkko,

kernel/pid_namespace.c void zap_pid_ns_processes(struct pid_namespace *pid_ns) · line 284

Quoted 2 lines

  acct_exit_ns(pid_ns);

kernel/pid_namespace.c +1 -0
+	exit_rootns(pid_ns, me);

We have a very similar mechanism around pidfd's to track exit information for a task. As far as I can see we already have (struct rootns *)->init_pid reference, so we can get exit information for free (look for PIDFD_INFO_EXIT).

Quoted 4 lines

Thanks for mentioning. I'll see if I can leverage it.

If something like this is found, it is partly due long history of this code i.e., not planned/opionated choice :-)

This non-doable or incompatible at least. I'm not sure if that would have gain. I think this goes to acceptable redundancy. Or at least, currently think this way.

Br, Jarkko

#7 lore raw

RFC PATCH v4 4/14 rootns: Add rootns() 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() system call to allocate a detached rootns instance owning a fresh user namespace alongside dedicated empty mount (CLONE_EMPTY_MNTNS), PID, UTS, IPC, network, cgroup, and time namespaces, and return its control file descriptor. Finalize the nsproxy time namespace and pin active references for the lifetime of the rootns.

---
 include/linux/syscalls.h       |   1 +
 include/linux/time_namespace.h |  13 ++++
 kernel/rootns.c                | 106 +++++++++++++++++++++++++++++++++
 kernel/sys_ni.c                |   3 +
 4 files changed, 123 insertions(+)
include/linux/syscalls.h +1 -0
index 552d9710a0d5..7e630b612ef2 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(unsigned int flags);
 
 /*
  * Architecture-specific system calls
include/linux/time_namespace.h +13 -0
index 58bd9728df58..bdc185543893 100644
@@ -60,6 +60,15 @@ static inline void put_time_ns(struct time_namespace *ns)
 		free_time_ns(ns);
 }
 
+static inline void timens_activate_nsproxy(struct nsproxy *nsproxy)
+{
+	if (nsproxy->time_ns != nsproxy->time_ns_for_children) {
+		get_time_ns(nsproxy->time_ns_for_children);
+		put_time_ns(nsproxy->time_ns);
+		nsproxy->time_ns = nsproxy->time_ns_for_children;
+	}
+}
+
 void proc_timens_show_offsets(struct task_struct *p, struct seq_file *m);
 
 struct proc_timens_offset {
@@ -125,6 +134,10 @@ static inline void put_time_ns(struct time_namespace *ns)
 {
 }
 
+static inline void timens_activate_nsproxy(struct nsproxy *nsproxy)
+{
+}
+
 static inline
 struct time_namespace *copy_time_ns(u64 flags,
 				    struct user_namespace *user_ns,
kernel/rootns.c +106 -0

109 lines not on this page · raw message

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

RFC PATCH v4 5/14 rootns: Add ROOTNS_WAIT ioctl

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 ioctl and struct rootns_wait_args to wait freezably and interruptibly on a rootns file descriptor until its init thread group exits and report the recorded wait status. Return the init TGID translated into the caller's active PID namespace, 0 for WNOHANG while running, or -ECHILD if init was never started or is not visible to the caller.

---
 include/uapi/linux/rootns.h | 26 ++++++++++++++++++++++
 kernel/rootns.c             | 44 +++++++++++++++++++++++++++++++++++++
 2 files changed, 70 insertions(+)
include/uapi/linux/rootns.h +26 -0
index bd643bdfb43c..3fd215185398 100644
@@ -8,6 +8,7 @@
 #define _UAPI_LINUX_ROOTNS_H
 
 #include <linux/ioctl.h>
+#include <linux/types.h>
 
 /**
  * enum rootns_flags - Flags for rootns()
@@ -24,6 +25,16 @@ enum rootns_flags {
 	ROOTNS_ALL_FLAGS	= 0x00000003,
 };
 
+/**
+ * struct rootns_wait_args - Arguments for %ROOTNS_WAIT
+ * @flags: Wait options (0 or %WNOHANG).
+ * @status: Output wait status of rootns init in waitpid(2) format.
+ */
+struct rootns_wait_args {
+	__u32 flags;
+	__s32 status;
+};
+
 #define ROOTNS_IOCTL_MAGIC	0xB9
 
 /**
@@ -41,4 +52,19 @@ enum rootns_flags {
  */
 #define ROOTNS_GET_NSFD		_IO(ROOTNS_IOCTL_MAGIC, 0x01)
 
+/**
+ * DOC: ROOTNS_WAIT
+ *
+ * ``ioctl(rootnsfd, ROOTNS_WAIT, &args)`` waits interruptibly (unless
+ * ``WNOHANG`` is set in ``args.flags``) until ``rootnsfd`` reaches
+ * ``ROOTNS_DEAD``, then writes the recorded exit status of ``rootns`` init
+ * into ``args.status``.
+ *
+ * Returns the caller-visible TGID of ``rootns`` init on success, ``0`` if
+ * ``WNOHANG`` is set and the ``rootns`` has not terminated, or ``-1`` with
+ * ``errno`` set to ``ECHILD`` if init was never started or is not visible in
+ * the caller's active PID namespace.
+ */
+#define ROOTNS_WAIT		_IOWR(ROOTNS_IOCTL_MAGIC, 0x02, struct rootns_wait_args)
+
 #endif /* _UAPI_LINUX_ROOTNS_H */
kernel/rootns.c +44 -0

65 lines not on this page · raw message

Signature · 1 line
2.47.3
#9 lore raw

Re: [RFC PATCH v4 05/14] rootns: Add ROOTNS_WAIT ioctl

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] rootns: delayed PID namespace visibility check in rootns_wait() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] rootns: delayed PID namespace visibility check in rootns_wait()
--

commit 68c6e4532ee164e48940d00824536de847b1c5d0
Author: Jarkko Sakkinen <[email protected]>

rootns: Add ROOTNS_WAIT ioctl

This commit adds the ROOTNS_WAIT ioctl to wait for a root namespace's init thread group to exit and retrieve its wait status and TGID.

Quoted 29 lines
kernel/rootns.c +21 -0
index d9ef68d603a24..5f03b6ba4a543 100644
@@ -115,6 +115,45 @@ static long rootns_get_nsfd(struct rootns *rootns, unsigned long nstype)
 	return nsproxy_open_namespace(rootns->ns, rootns->user_ns, nstype);
 }
 
+static long rootns_wait(struct rootns *rootns, void __user *uarg)
+{
+	struct pid_namespace *pid_ns = task_active_pid_ns(current);
+	struct rootns_wait_args args;
+	long ret;
+
+	if (!uarg)
+		return -EINVAL;
+	if (copy_from_user(&args, uarg, sizeof(args)))
+		return -EFAULT;
+	if (args.flags & ~WNOHANG)
+		return -EINVAL;
+	if (READ_ONCE(rootns->state) == ROOTNS_INIT)
+		return -ECHILD;
+
+	if (!(args.flags & WNOHANG)) {
+		ret = wait_event_freezable(rootns->waitq,
+					   READ_ONCE(rootns->state) == ROOTNS_DEAD ||
+					   READ_ONCE(rootns->state) == ROOTNS_INIT);
+		if (ret)
+			return ret;

kernel/rootns.c static long rootns_get_nsfd(struct rootns *rootns, unsigned long nstype) · line 148

Quoted 10 lines
kernel/rootns.c +10 -0
+	}
+
+	scoped_guard(spinlock, &rootns->lock) {
+		if (rootns->state == ROOTNS_INIT)
+			return -ECHILD;
+		if (rootns->state != ROOTNS_DEAD)
+			return 0;
+		ret = pid_nr_ns(rootns->init_pid, pid_ns);
+		if (ret <= 0)
+			return -ECHILD;

[Severity: Medium]
Should rootns_wait() check whether the rootns PID namespace is visible in pid_ns before waiting or returning 0 for WNOHANG?

Because pid_nr_ns() is only checked after rootns->state reaches ROOTNS_DEAD, a caller in a non-ancestor PID namespace gets 0 instead of -ECHILD when calling ROOTNS_WAIT with WNOHANG on a running rootns, and a blocking call sleeps in wait_event_freezable() until init exits before failing with -ECHILD. Checking pidns_is_ancestor(rootns->ns->pid_ns_for_children, pid_ns) upfront (as in rootns_get_nsfd()) would reject invisible targets immediately.

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

RFC PATCH v4 6/14 rootns: Add ROOTNS_KILL ioctl

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 ioctl to require an ancestor active PID namespace, walk the root namespace's PID namespace IDR under tasklist_lock, and deliver a validated signal once to each thread group including in-flight forks, aggregating per-process delivery results.

---
 include/uapi/linux/rootns.h | 13 ++++++++++
 kernel/rootns.c             | 52 +++++++++++++++++++++++++++++++++++++
 2 files changed, 65 insertions(+)
include/uapi/linux/rootns.h +13 -0
index 3fd215185398..acd91d895c63 100644
@@ -67,4 +67,17 @@ struct rootns_wait_args {
  */
 #define ROOTNS_WAIT		_IOWR(ROOTNS_IOCTL_MAGIC, 0x02, struct rootns_wait_args)
 
+/**
+ * DOC: ROOTNS_KILL
+ *
+ * ``ioctl(rootnsfd, ROOTNS_KILL, sig)`` walks the target root namespace's PID
+ * namespace IDR under ``tasklist_lock`` and delivers ``sig`` (or ``0`` for a
+ * permission check) once to each member thread group.
+ *
+ * Returns ``0`` if at least one thread group was signaled, or ``-1`` with
+ * ``errno`` set to ``EXDEV`` if the caller's active PID namespace is not an
+ * ancestor or ``ESRCH`` if the ``rootns`` is not running or has no members.
+ */
+#define ROOTNS_KILL		_IO(ROOTNS_IOCTL_MAGIC, 0x03)
+
 #endif /* _UAPI_LINUX_ROOTNS_H */
kernel/rootns.c +52 -0

70 lines not on this page · raw message

Signature · 1 line
2.47.3
#11 lore raw

RFC PATCH v4 7/14 fork: Support CLONE_INTO_ROOTNS in clone3()

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 CLONE_INTO_ROOTNS and struct clone_args.rootns (CLONE_ARGS_SIZE_VER3) to spawn a child process directly into a rootns whose root mount has been installed. Transition the rootns from ROOTNS_INIT 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.

Derive child credentials from current, require CAP_SYS_ADMIN and CAP_SYS_CHROOT in the target user namespace and an ancestor active PID namespace, preserve caller umask, reset dumpability across user namespace transitions, commit time namespace vvar mappings after copy_process() succeeds, and look up the live mount namespace root. Restrict companion flags to CLONE_VFORK, CLONE_PIDFD, CLONE_PIDFD_AUTOKILL, CLONE_AUTOREAP, CLONE_CLEAR_SIGHAND, CLONE_INTO_CGROUP, and CLONE_NNP.

---
 fs/namespace.c                 |  16 ++++
 include/linux/cred.h           |   4 +-
 include/linux/mnt_namespace.h  |   2 +
 include/linux/nsproxy.h        |   4 +-
 include/linux/rootns.h         |  14 ++++
 include/linux/sched/task.h     |   8 ++
 include/linux/user_namespace.h |   7 ++
 include/uapi/linux/sched.h     |   5 ++
 kernel/cred.c                  |  32 +++++++-
 kernel/fork.c                  |  94 ++++++++++++++++++++---
 kernel/nsproxy.c               |  11 ++-
 kernel/rootns.c                | 136 +++++++++++++++++++++++++++++++++
 kernel/user_namespace.c        |  12 ++-
 13 files changed, 327 insertions(+), 18 deletions(-)
fs/namespace.c +16 -0
index aecd05ac0170..781380945d78 100644
@@ -6708,6 +6708,22 @@ static void mntns_put(struct ns_common *ns)
 	put_mnt_ns(to_mnt_ns(ns));
 }
 
+int mnt_ns_get_root(struct mnt_namespace *mnt_ns, struct path *root)
+{
+	int err;
+
+	err = vfs_path_lookup(mnt_ns->root->mnt.mnt_root, &mnt_ns->root->mnt,
+			      "/", LOOKUP_DOWN, root);
+	if (err)
+		return err;
+	if (root->mnt == &mnt_ns->root->mnt) {
+		path_put(root);
+		*root = (struct path){};
+		return -ENOENT;
+	}
+	return 0;
+}
+
 static int mntns_install(struct nsset *nsset, struct ns_common *ns)
 {
 	struct nsproxy *nsproxy = nsset->nsproxy;
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/mnt_namespace.h +2 -0
index 0acd1089d149..98188d1f7428 100644
@@ -8,6 +8,7 @@
 
 struct mnt_namespace;
 struct fs_struct;
+struct path;
 struct user_namespace;
 struct ns_common;
 
@@ -15,6 +16,7 @@ extern struct mnt_namespace init_mnt_ns;
 
 extern struct mnt_namespace *copy_mnt_ns(u64, struct mnt_namespace *,
 		struct user_namespace *, struct fs_struct *);
+int mnt_ns_get_root(struct mnt_namespace *mnt_ns, struct path *root);
 extern void put_mnt_ns(struct mnt_namespace *ns);
 DEFINE_FREE(put_mnt_ns, struct mnt_namespace *, if (!IS_ERR_OR_NULL(_T)) put_mnt_ns(_T))
 extern struct ns_common *from_mnt_ns(struct mnt_namespace *);
include/linux/nsproxy.h +3 -1
index cacbbbe3f1ce..26b3b788cc90 100644
@@ -12,6 +12,7 @@ struct ipc_namespace;
 struct pid_namespace;
 struct cgroup_namespace;
 struct fs_struct;
+struct rootns;
 struct user_namespace;
 
 /*
@@ -97,7 +98,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 +14 -0
index 0557ce75195d..802fc76bb66e 100644
@@ -11,6 +11,7 @@
 #include <linux/wait.h>
 
 struct file;
+struct kernel_clone_args;
 struct nsproxy;
 struct pid;
 struct pid_namespace;
@@ -46,6 +47,8 @@ bool is_rootns_file(struct file *file);
 void copy_rootns(struct task_struct *tsk, struct pid *pid,
 		 struct rootns *rootns);
 void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk);
+int rootns_prepare_fork(struct kernel_clone_args *args);
+int rootns_finish_fork(struct kernel_clone_args *args, struct task_struct *p);
 #else
 static inline struct rootns *get_rootns(struct rootns *c)
 {
@@ -70,6 +73,17 @@ static inline void exit_rootns(struct pid_namespace *pid_ns,
 			       struct task_struct *tsk)
 {
 }
+
+static inline int rootns_prepare_fork(struct kernel_clone_args *args)
+{
+	return -EINVAL;
+}
+
+static inline int rootns_finish_fork(struct kernel_clone_args *args,
+				     struct task_struct *p)
+{
+	return 0;
+}
 #endif /* CONFIG_ROOTNS */
 
 #endif /* _LINUX_ROOTNS_H */
include/linux/sched/task.h +8 -0
index 90ed5bc3c7af..e0c4e8ab02f1 100644
@@ -16,6 +16,8 @@ struct task_struct;
 struct rusage;
 union thread_union;
 struct css_set;
+struct file;
+struct rootns;
 
 /* All the bits taken by the old clone syscall. */
 #define CLONE_LEGACY_FLAGS 0xffffffffULL
@@ -39,11 +41,17 @@ struct kernel_clone_args {
 	/* Number of elements in *set_tid */
 	size_t set_tid_size;
 	int cgroup;
+	int rootns_fd;
 	int idle;
 	int (*fn)(void *);
 	void *fn_arg;
 	struct cgroup *cgrp;
 	struct css_set *cset;
+#ifdef CONFIG_ROOTNS
+	struct file *rootns_file;
+	struct rootns *rootns;
+	bool rootns_bootstrapping;
+#endif
 	unsigned int kill_seq;
 };
 
include/linux/user_namespace.h +7 -0
index 91232053775d..3600a903442e 100644
@@ -184,6 +184,7 @@ static inline struct user_namespace *get_user_ns(struct user_namespace *ns)
 }
 
 extern int create_user_ns(struct cred *new);
+int install_user_ns_cred(struct cred *cred, struct user_namespace *user_ns);
 extern int unshare_userns(unsigned long unshare_flags, struct cred **new_cred);
 extern void __put_user_ns(struct user_namespace *ns);
 
@@ -226,6 +227,12 @@ static inline int create_user_ns(struct cred *new)
 	return -EINVAL;
 }
 
+static inline int install_user_ns_cred(struct cred *cred,
+				       struct user_namespace *user_ns)
+{
+	return -EINVAL;
+}
+
 static inline int unshare_userns(unsigned long unshare_flags,
 				 struct cred **new_cred)
 {
include/uapi/linux/sched.h +5 -0
index 19ffeba89428..405cfc954ae1 100644
@@ -40,6 +40,7 @@
 #define CLONE_NNP		(1ULL << 35) /* Set no_new_privs on child. */
 #define CLONE_PIDFD_AUTOKILL	(1ULL << 36) /* Kill child when clone pidfd closes. */
 #define CLONE_EMPTY_MNTNS	(1ULL << 37) /* Create an empty mount namespace. */
+#define CLONE_INTO_ROOTNS	(1ULL << 38) /* Clone into a specific root namespace. */
 
 /*
  * cloning flags intersect with CSIGNAL so can be used with unshare and clone3
@@ -94,6 +95,8 @@
  *                kernel's limit of nested PID namespaces.
  * @cgroup:       If CLONE_INTO_CGROUP is specified set this to
  *                a file descriptor for the cgroup.
+ * @rootns:       If CLONE_INTO_ROOTNS is specified set this to
+ *                a file descriptor for the root namespace.
  *
  * The structure is versioned by size and thus extensible.
  * New struct members must go at the end of the struct and
@@ -111,12 +114,14 @@ struct clone_args {
 	__aligned_u64 set_tid;
 	__aligned_u64 set_tid_size;
 	__aligned_u64 cgroup;
+	__aligned_u64 rootns;
 };
 #endif
 
 #define CLONE_ARGS_SIZE_VER0 64 /* sizeof first published struct */
 #define CLONE_ARGS_SIZE_VER1 80 /* sizeof second published struct */
 #define CLONE_ARGS_SIZE_VER2 88 /* sizeof third published struct */
+#define CLONE_ARGS_SIZE_VER3 96 /* sizeof fourth published struct */
 
 /*
  * Scheduling policies
kernel/cred.c +31 -1
index d01df40a9a38..48a8852dab4a 100644
@@ -12,13 +12,16 @@
 #include <linux/slab.h>
 #include <linux/sched.h>
 #include <linux/sched/coredump.h>
+#include <linux/sched/exec_state.h>
 #include <linux/key.h>
 #include <linux/keyctl.h>
 #include <linux/init_task.h>
+#include <linux/rootns.h>
 #include <linux/security.h>
 #include <linux/binfmts.h>
 #include <linux/cn_proc.h>
 #include <linux/uidgid.h>
+#include <linux/user_namespace.h>
 
 #if 0
 #define kdebug(FMT, ...)						\
@@ -251,6 +254,9 @@ struct cred *prepare_exec_creds(void)
 	return new;
 }
 
+static bool cred_cap_issubset(const struct cred *set,
+			      const struct cred *subset);
+
 /*
  * Copy credentials for the new process created by fork()
  *
@@ -260,7 +266,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;
@@ -287,6 +294,29 @@ int copy_creds(struct task_struct *p, u64 clone_flags)
 	if (!new)
 		return -ENOMEM;
 
+	if (rootns) {
+		const struct cred *old = current_cred();
+
+		if (!ns_capable(rootns->user_ns, CAP_SYS_ADMIN) ||
+		    !ns_capable(rootns->user_ns, CAP_SYS_CHROOT)) {
+			ret = -EPERM;
+			goto error_put;
+		}
+		if (new->user_ns != rootns->user_ns) {
+			ret = install_user_ns_cred(new, rootns->user_ns);
+			if (ret < 0)
+				goto error_put;
+		}
+		if (!cred_cap_issubset(old, new) ||
+		    old->user_ns != new->user_ns) {
+			struct task_exec_state *exec_state;
+
+			exec_state = rcu_dereference_protected(p->exec_state, true);
+			if (exec_state != &init_task_exec_state)
+				WRITE_ONCE(exec_state->dumpable, suid_dumpable);
+		}
+	}
+
 	if (clone_flags & CLONE_NEWUSER) {
 		ret = create_user_ns(new);
 		if (ret < 0)
kernel/fork.c +85 -9

203 lines not on this page · raw message

kernel/nsproxy.c +9 -2
index 8a3c6d4e94e2..78a1e1fb2cfd 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>
@@ -166,12 +167,18 @@ struct nsproxy *create_new_namespaces(u64 flags,
  * called from clone.  This now handles copy for nsproxy and all
  * namespaces therein.
  */
-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)) {
@@ -192,7 +199,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);
 
kernel/rootns.c +136 -0

145 lines not on this page · raw message

kernel/user_namespace.c +8 -4
index cd748e1cbace..3bea86647191 100644
@@ -1372,6 +1372,13 @@ static void userns_put(struct ns_common *ns)
 	put_user_ns(to_user_ns(ns));
 }
 
+int install_user_ns_cred(struct cred *cred, struct user_namespace *user_ns)
+{
+	put_user_ns(cred->user_ns);
+	set_cred_user_ns(cred, get_user_ns(user_ns));
+	return set_cred_ucounts(cred);
+}
+
 static int userns_install(struct nsset *nsset, struct ns_common *ns)
 {
 	struct user_namespace *user_ns = to_user_ns(ns);
@@ -1397,10 +1404,7 @@ static int userns_install(struct nsset *nsset, struct ns_common *ns)
 	if (!cred)
 		return -EINVAL;
 
-	put_user_ns(cred->user_ns);
-	set_cred_user_ns(cred, get_user_ns(user_ns));
-
-	if (set_cred_ucounts(cred) < 0)
+	if (install_user_ns_cred(cred, user_ns) < 0)
 		return -EINVAL;
 
 	return 0;
Signature · 1 line
2.47.3
#12 lore raw

Re: [RFC PATCH v4 07/14] fork: Support CLONE_INTO_ROOTNS in clone3()

Quoted 20 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 CLONE_INTO_ROOTNS and struct clone_args.rootns (CLONE_ARGS_SIZE_VER3) to spawn a child process directly into a rootns whose root mount has been installed. Transition the rootns from ROOTNS_INIT 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.

Derive child credentials from current, require CAP_SYS_ADMIN and CAP_SYS_CHROOT in the target user namespace and an ancestor active PID namespace, preserve caller umask, reset dumpability across user namespace transitions, commit time namespace vvar mappings after copy_process() succeeds, and look up the live mount namespace root. Restrict companion flags to CLONE_VFORK, CLONE_PIDFD, CLONE_PIDFD_AUTOKILL, CLONE_AUTOREAP, CLONE_CLEAR_SIGHAND, CLONE_INTO_CGROUP, and CLONE_NNP.

Quoted 3 lines

Being fd-bound object the gist is that the first clone3() binds cgroups, which could e.g., different process than who build the container.

CLONE_INTO_CGROUPS is of course available as an optional flag when using CLONE_INTO_ROOTNS.

Br, Jarkko

#13 lore raw

Re: [RFC PATCH v4 07/14] fork: Support CLONE_INTO_ROOTNS in clone3()

Quoted 25 lines · Jarkko Sakkinen
Quoted 20 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 CLONE_INTO_ROOTNS and struct clone_args.rootns (CLONE_ARGS_SIZE_VER3) to spawn a child process directly into a rootns whose root mount has been installed. Transition the rootns from ROOTNS_INIT 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.

Derive child credentials from current, require CAP_SYS_ADMIN and CAP_SYS_CHROOT in the target user namespace and an ancestor active PID namespace, preserve caller umask, reset dumpability across user namespace transitions, commit time namespace vvar mappings after copy_process() succeeds, and look up the live mount namespace root. Restrict companion flags to CLONE_VFORK, CLONE_PIDFD, CLONE_PIDFD_AUTOKILL, CLONE_AUTOREAP, CLONE_CLEAR_SIGHAND, CLONE_INTO_CGROUP, and CLONE_NNP.

Quoted 3 lines
Quoted 6 lines

Being fd-bound object the gist is that the first clone3() binds cgroups, which could e.g., different process than who build the container.

CLONE_INTO_CGROUPS is of course available as an optional flag when using CLONE_INTO_ROOTNS.

The major benefit over Cells is that there is no embryonic task state and nothing from the host mount table is inherited unless explicitly moved in. Also, unshare() cannot ascend from the rootns() created hierarchy.

Shooting yourself in the foot is an explicit and planned action taken.

And further, it has provably more defence in depth than Cells because LSM hooks accurately populate the data crossings.

Br, Jarkko

#14 lore raw

Re: [RFC PATCH v4 07/14] fork: Support CLONE_INTO_ROOTNS in clone3()

In reply to Jarkko Sakkinen
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] rootns: rootns_finish_fork() rewrites copy_process() -EINVAL to -EBUSY - [Low] rootns: unreachable…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] rootns: rootns_finish_fork() rewrites copy_process() -EINVAL to -EBUSY
- [Low] rootns: unreachable PIDNS_ADDING check in rootns_prepare_fork() --

commit 1820863b7d5dcd4fd4778d2d64f24adcb966cc47
Author: Jarkko Sakkinen <[email protected]>

fork: Support CLONE_INTO_ROOTNS in clone3()

This commit adds CLONE_INTO_ROOTNS and struct clone_args.rootns to spawn a child process directly into a target root namespace via clone3().

Quoted 7 lines
kernel/rootns.c +0 -0
index ce012a07e9828..865689eed69cb 100644
@@ -423,3 +424,138 @@ SYSCALL_DEFINE1(rootns, unsigned int, flags)
 	return fd;
 }

[ ... ]

Quoted 2 lines
kernel/rootns.c +2 -0
+int rootns_prepare_fork(struct kernel_clone_args *args)
+{

[ ... ]

kernel/rootns.c SYSCALL_DEFINE1(rootns, unsigned int, flags) · line 501

Quoted 10 lines
kernel/rootns.c +10 -0
+	for (;;) {
+		bool wait = false;
+
+		scoped_guard(spinlock, &rootns->lock) {
+			switch (rootns->state) {
+			case ROOTNS_INIT:
+				if (READ_ONCE(pid_ns->child_reaper))
+					return -EBUSY;
+				if (!(READ_ONCE(pid_ns->pid_allocated) & PIDNS_ADDING))
+					return -ESRCH;

[Severity: Low]
Can the PIDNS_ADDING check under ROOTNS_INIT ever be reached?

PIDNS_ADDING is only cleared by disable_pid_allocation() in zap_pid_ns_processes() when the PID namespace's init process exits, and pid_ns->child_reaper is never reset to NULL afterwards. Because pid_ns->child_reaper is non-NULL whenever PIDNS_ADDING is cleared, testing child_reaper first always returns -EBUSY here instead of -ESRCH.

Quoted 3 lines
kernel/rootns.c +3 -0
+				WRITE_ONCE(rootns->state, ROOTNS_FORKING);
+				bootstrapping = true;
+				break;

[ ... ]

Quoted 15 lines
kernel/rootns.c +15 -0
+int rootns_finish_fork(struct kernel_clone_args *args, struct task_struct *p)
+{
+	struct file *file __free(fput) = args->rootns_file;
+	struct rootns *rootns = args->rootns;
+	struct pid_namespace *pid_ns = rootns->ns->pid_ns_for_children;
+	int ret;
+
+	args->rootns_file = NULL;
+	args->rootns = NULL;
+	if (!IS_ERR(p)) {
+		if (current->nsproxy->time_ns != rootns->ns->time_ns)
+			timens_commit(p, rootns->ns->time_ns);
+		return 0;
+	}
+

kernel/rootns.c SYSCALL_DEFINE1(rootns, unsigned int, flags) · line 555

Quoted 10 lines
kernel/rootns.c +10 -0
+	ret = PTR_ERR(p);
+	if (args->rootns_bootstrapping) {
+		scoped_guard(spinlock, &rootns->lock) {
+			if (rootns->state == ROOTNS_FORKING)
+				WRITE_ONCE(rootns->state, ROOTNS_INIT);
+		}
+		wake_up_all(&rootns->waitq);
+		if (ret == -EINVAL && !args->set_tid_size)
+			ret = -EBUSY;
+	}

[Severity: Medium]
Does this rewrite argument validation failures in copy_process() from -EINVAL to -EBUSY during bootstrap?

rootns_prepare_fork() runs before copy_process(), where companion flags allowed by CLONE_INTO_ROOTNS_FLAGS (such as CLONE_PIDFD_AUTOKILL without CLONE_PIDFD, or CLONE_AUTOREAP with a non-zero exit_signal) and copy_thread() are validated:

kernel/fork.c:copy_process() {
    ...
	if (clone_flags & CLONE_AUTOREAP) {
		if (clone_flags & CLONE_THREAD)
			return ERR_PTR(-EINVAL);
		if (clone_flags & CLONE_PARENT)
			return ERR_PTR(-EINVAL);
		if (args->exit_signal)
			return ERR_PTR(-EINVAL);
	}
    ...
}

When the initial bootstrap clone3(CLONE_INTO_ROOTNS) call with set_tid_size == 0 fails one of those checks with -EINVAL, rootns_finish_fork() treats it as an alloc_pid() collision and returns -EBUSY to userspace instead of -EINVAL.

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

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

In reply to Jarkko Sakkinen

fsopen() and fsmount() gate on CAP_SYS_ADMIN in the caller's current mount namespace and initialize filesystem contexts from current's user, network, PID, and IPC namespaces, preventing an unprivileged external manager from creating superblocks and detached mounts for 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. Allow unprivileged callers to open FS_USERNS_MOUNT contexts in FS_CONTEXT_AWAITING_NS without module autoloading until FSCONFIG_SET_ROOTNS authorizes and initializes the context, keep devpts pty_reserve restricted to host mounts, enforce mount_too_revealing() for unprivileged callers in init_mnt_ns, and wire ->set_rootns() for proc and mqueue.

---
 fs/devpts/inode.c          |   2 +
 fs/filesystems.c           |  15 ++++
 fs/fs_context.c            |  21 ++++--
 fs/fsopen.c                | 139 ++++++++++++++++++++++++++++++++++---
 fs/internal.h              |   6 ++
 fs/namespace.c             |  38 ++++++++--
 fs/proc/root.c             |  18 +++++
 include/linux/fs_context.h |   6 ++
 include/uapi/linux/mount.h |   1 +
 ipc/mqueue.c               |  13 ++++
 10 files changed, 241 insertions(+), 18 deletions(-)
fs/devpts/inode.c +2 -0
index bd1e8eb26edb..db5a5c7a07db 100644
@@ -434,6 +434,8 @@ static int devpts_init_fs_context(struct fs_context *fc)
 	fsi->mount_opts.max     = NR_UNIX98_PTY_MAX;
 
 	if (fc->purpose == FS_CONTEXT_FOR_MOUNT &&
+	    !fc->rootns_bound &&
+	    fc->user_ns == &init_user_ns &&
 	    current->nsproxy->mnt_ns == init_task.nsproxy->mnt_ns)
 		fsi->mount_opts.reserve = true;
 
fs/filesystems.c +15 -0
index 3083d904df9b..9429844bf6bf 100644
@@ -18,6 +18,7 @@
 #include <linux/uaccess.h>
 #include <linux/fs_parser.h>
 #include <linux/rculist.h>
+#include "internal.h"
 
 /*
  * Read-mostly filesystem drivers list.
@@ -390,6 +391,20 @@ static struct file_system_type *__get_fs_type(const char *name, int len)
 	return fs;
 }
 
+struct file_system_type *get_fs_type_noload(const char *name)
+{
+	struct file_system_type *fs;
+	const char *dot = strchr(name, '.');
+	int len = dot ? dot - name : strlen(name);
+
+	fs = __get_fs_type(name, len);
+	if (dot && fs && !(fs->fs_flags & FS_HAS_SUBTYPE)) {
+		put_filesystem(fs);
+		fs = NULL;
+	}
+	return fs;
+}
+
 struct file_system_type *get_fs_type(const char *name)
 {
 	struct file_system_type *fs;
fs/fs_context.c +17 -4
index a50584df97be..cd004750b99c 100644
@@ -249,6 +249,7 @@ EXPORT_SYMBOL(generic_parse_monolithic);
  * @sb_flags: Filesystem/superblock flags (SB_*)
  * @sb_flags_mask: Applicable members of @sb_flags
  * @purpose: The purpose that this configuration shall be used for.
+ * @init: Whether to initialise the filesystem context immediately.
  *
  * Open a filesystem and create a mount context.  The mount context is
  * initialised with the supplied flags and, if a submount/automount from
@@ -259,7 +260,8 @@ static struct fs_context *alloc_fs_context(struct file_system_type *fs_type,
 				      struct dentry *reference,
 				      unsigned int sb_flags,
 				      unsigned int sb_flags_mask,
-				      enum fs_context_purpose purpose)
+				      enum fs_context_purpose purpose,
+				      bool init)
 {
 	struct fs_context *fc;
 	int ret = -ENOMEM;
@@ -292,6 +294,9 @@ static struct fs_context *alloc_fs_context(struct file_system_type *fs_type,
 		break;
 	}
 
+	if (!init)
+		return fc;
+
 	ret = fc->fs_type->init_fs_context(fc);
 	if (ret < 0)
 		goto err_fc;
@@ -307,10 +312,16 @@ struct fs_context *fs_context_for_mount(struct file_system_type *fs_type,
 					unsigned int sb_flags)
 {
 	return alloc_fs_context(fs_type, NULL, sb_flags, 0,
-					FS_CONTEXT_FOR_MOUNT);
+				FS_CONTEXT_FOR_MOUNT, true);
 }
 EXPORT_SYMBOL(fs_context_for_mount);
 
+struct fs_context *fs_context_for_unpriv_mount(struct file_system_type *fs_type)
+{
+	return alloc_fs_context(fs_type, NULL, 0, 0,
+				FS_CONTEXT_FOR_MOUNT, false);
+}
+
 struct fs_context *fs_context_for_reconfigure(struct dentry *dentry,
 					unsigned int sb_flags,
 					unsigned int sb_flags_mask)
@@ -320,7 +331,8 @@ struct fs_context *fs_context_for_reconfigure(struct dentry *dentry,
 		return ERR_PTR(-EINVAL);
 
 	return alloc_fs_context(dentry->d_sb->s_type, dentry, sb_flags,
-				sb_flags_mask, FS_CONTEXT_FOR_RECONFIGURE);
+				sb_flags_mask, FS_CONTEXT_FOR_RECONFIGURE,
+				true);
 }
 
 /**
@@ -337,7 +349,8 @@ struct fs_context *fs_context_for_submount(struct file_system_type *type,
 	struct fs_context *fc;
 	int ret;
 
-	fc = alloc_fs_context(type, reference, 0, 0, FS_CONTEXT_FOR_SUBMOUNT);
+	fc = alloc_fs_context(type, reference, 0, 0, FS_CONTEXT_FOR_SUBMOUNT,
+			      true);
 	if (IS_ERR(fc))
 		return fc;
 
fs/fsopen.c +131 -8

212 lines not on this page · raw message

fs/internal.h +6 -0
index 3f2fbac40f8e..d6815bf6ea9b 100644
@@ -40,12 +40,18 @@ int __block_write_begin_int(struct folio *folio, loff_t pos, unsigned len,
  */
 extern void __init chrdev_init(void);
 
+/*
+ * filesystems.c
+ */
+struct file_system_type *get_fs_type_noload(const char *name);
+
 /*
  * fs_context.c
  */
 extern int parse_monolithic_mount_data(struct fs_context *, void *);
 extern void vfs_clean_context(struct fs_context *fc);
 extern int finish_clean_context(struct fs_context *fc);
+struct fs_context *fs_context_for_unpriv_mount(struct file_system_type *fs_type);
 
 /*
  * namei.c
fs/namespace.c +32 -6
index 781380945d78..dfe0ee9ecdcd 100644
@@ -4614,16 +4614,19 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 	struct vfsmount *new_mnt;
 	struct mount *mnt;
 	unsigned int mnt_flags = 0;
+	bool priv;
 	long ret;
 
 	if ((flags & ~(FSMOUNT_CLOEXEC | FSMOUNT_NAMESPACE)) != 0)
 		return -EINVAL;
 
+	priv = may_mount();
 	if ((flags & FSMOUNT_NAMESPACE) &&
 	    !ns_capable(current_user_ns(), CAP_SYS_ADMIN))
 		return -EPERM;
 
-	if (!(flags & FSMOUNT_NAMESPACE) && !may_mount())
+	if (!(flags & FSMOUNT_NAMESPACE) && !IS_ENABLED(CONFIG_ROOTNS) &&
+	    !priv)
 		return -EPERM;
 
 	if (attr_flags & ~FSMOUNT_VALID_FLAGS)
@@ -4658,6 +4661,15 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 	if (ret)
 		return ret;
 
+	if (fc->rootns_bound) {
+		if (flags & FSMOUNT_NAMESPACE)
+			return -EINVAL;
+		if (!ns_capable(fc->user_ns, CAP_SYS_ADMIN))
+			return -EPERM;
+	} else if (!(flags & FSMOUNT_NAMESPACE) && !priv) {
+		return -EPERM;
+	}
+
 	/* There must be a valid superblock or we can't mount it */
 	ret = -EINVAL;
 	if (!fc->root)
@@ -4699,9 +4711,12 @@ 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(priv ? current->nsproxy->mnt_ns->user_ns :
+			  fc->user_ns, true);
 	if (IS_ERR(ns))
 		return PTR_ERR(ns);
+	if (!priv)
+		ns->seq_origin = fc->rootns_mnt_id;
 	mnt = real_mount(new_path.mnt);
 	ns->root = mnt;
 	ns->nr_mounts = 1;
@@ -6582,6 +6597,7 @@ static bool mnt_already_visible(struct mnt_namespace *ns,
 				const struct super_block *sb,
 				int *new_mnt_flags)
 {
+	bool foreign_ns = !ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN);
 	int new_flags = *new_mnt_flags;
 	struct mount *mnt;
 
@@ -6611,6 +6627,11 @@ static bool mnt_already_visible(struct mnt_namespace *ns,
 		/* Don't miss readonly hidden in the superblock flags */
 		if (sb_rdonly(mnt->mnt.mnt_sb))
 			mnt_flags |= MNT_LOCK_READONLY;
+		if (foreign_ns) {
+			if (mnt_flags & MNT_READONLY)
+				mnt_flags |= MNT_LOCK_READONLY;
+			mnt_flags |= MNT_LOCK_ATIME;
+		}
 
 		/* Verify the mount flags are equal to or more permissive
 		 * than the proposed new mount.
@@ -6629,7 +6650,7 @@ static bool mnt_already_visible(struct mnt_namespace *ns,
 		list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) {
 			struct inode *inode = child->mnt_mountpoint->d_inode;
 			/* Only worry about locked mounts */
-			if (!(child->mnt.mnt_flags & MNT_LOCKED))
+			if (!foreign_ns && !(child->mnt.mnt_flags & MNT_LOCKED))
 				continue;
 			/* Is the directory permanently empty? */
 			if (!is_empty_dir_inode(inode))
@@ -6650,13 +6671,18 @@ static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flags
 	struct mnt_namespace *ns = current->nsproxy->mnt_ns;
 	unsigned long s_iflags;
 
-	if (ns->user_ns == &init_user_ns)
-		return false;
-
 	/* Can this filesystem be too revealing? */
 	if (!(sb->s_type->fs_flags & FS_USERNS_MOUNT_RESTRICTED))
 		return false;
 
+	if (ns->user_ns == &init_user_ns &&
+	    ns_capable_noaudit(&init_user_ns, CAP_SYS_ADMIN))
+		return false;
+
+	if (!ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN) &&
+	    current_chrooted())
+		return true;
+
 	s_iflags = sb->s_iflags;
 	if ((s_iflags & required_iflags) != required_iflags) {
 		WARN_ONCE(1, "Expected s_iflags to contain 0x%lx\n",
fs/proc/root.c +18 -0
index 7fbbe92bf73a..323296b03089 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,21 @@ static int proc_get_tree(struct fs_context *fc)
 	return get_tree_nodev(fc, proc_fill_super);
 }
 
+static int proc_set_rootns(struct fs_context *fc, struct rootns *rootns)
+{
+	struct proc_fs_context *ctx = fc->fs_private;
+	struct pid_namespace *target = rootns->ns->pid_ns_for_children;
+
+	if (!pidns_is_ancestor(target, task_active_pid_ns(current)))
+		return invalfc(fc, "cannot set pidns to non-descendant pidns");
+
+	put_pid_ns(ctx->pid_ns);
+	ctx->pid_ns = get_pid_ns(target);
+	put_user_ns(fc->user_ns);
+	fc->user_ns = get_user_ns(ctx->pid_ns->user_ns);
+	return 0;
+}
+
 static void proc_fs_context_free(struct fs_context *fc)
 {
 	struct proc_fs_context *ctx = fc->fs_private;
@@ -334,6 +351,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 +6 -0
index d1727dffecc5..42648bec5cfa 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,8 @@ enum fs_context_purpose {
  * Userspace usage phase for fsopen/fspick.
  */
 enum fs_context_phase {
+	FS_CONTEXT_AWAITING_NS,		/* Unprivileged context awaiting target ns */
+	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() */
@@ -101,6 +104,7 @@ struct fs_context {
 	const char		*source;	/* The source name (eg. dev path) */
 	void			*security;	/* LSM options */
 	void			*s_fs_info;	/* Proposed s_fs_info */
+	u64			rootns_mnt_id;	/* Target rootns mnt_ns ID */
 	unsigned int		sb_flags;	/* Proposed superblock flags (SB_*) */
 	unsigned int		sb_flags_mask;	/* Superblock flags that were changed */
 	unsigned int		s_iflags;	/* OR'd with sb->s_iflags */
@@ -110,6 +114,7 @@ struct fs_context {
 	bool			global:1;	/* Goes into &init_user_ns */
 	bool			oldapi:1;	/* Coming from mount(2) */
 	bool			exclusive:1;    /* create new superblock, reject existing one */
+	bool			rootns_bound:1;	/* Bound via FSCONFIG_SET_ROOTNS */
 };
 
 struct fs_context_operations {
@@ -117,6 +122,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);
+	int (*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 +13 -0
index 322c3dd98c44..f94e9b566bd0 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,17 @@ static struct inode *mqueue_get_inode(struct super_block *sb,
 	return ERR_PTR(ret);
 }
 
+static int 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);
+	return 0;
+}
+
 static int mqueue_fill_super(struct super_block *sb, struct fs_context *fc)
 {
 	struct inode *inode;
@@ -1613,6 +1625,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
#16 lore raw

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

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [High] fs: user_ns delegation and init_fs_context() mismatch in fsconfig_set_rootns() - [High] fs…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] fs: user_ns delegation and init_fs_context() mismatch in fsconfig_set_rootns()
- [High] fs: condition anon mnt_ns user_ns and seq_origin on rootns_bound in fsmount()
- [Medium] proc: allow pidns option to overwrite rootns binding in proc_parse_param()
--

commit 08909a29107ff970d2d4b5a71eaa424398baf6f2
Author: Jarkko Sakkinen <[email protected]>

fs: Support FSCONFIG_SET_ROOTNS in fsconfig()

This commit adds the FSCONFIG_SET_ROOTNS command to fsconfig() so callers holding CAP_SYS_ADMIN in a target rootns user namespace can bind a newly opened fs_context to that rootns before configuring parameters and mounting.

Quoted 4 lines
fs/fsopen.c +0 -0
index 70024870fefa2..85b31af68a4d6 100644

[ ... ]

Quoted 2 lines
fs/fsopen.c +2 -0
+static int fsconfig_set_rootns(struct fs_context *fc, struct fs_parameter *param)
+{

[ ... ]

Quoted 5 lines
fs/fsopen.c +5 -0
+	put_net(fc->net_ns);
+	fc->net_ns = get_net(c->ns->net_ns);
+	put_user_ns(fc->user_ns);
+	if ((fc->fs_type->fs_flags & (FS_USERNS_MOUNT | FS_USERNS_DELEGATABLE)) &&
+	    ((kuid_has_mapping(user_ns, fc->cred->fsuid) &&

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

Quoted 10 lines
fs/fsopen.c +10 -0
+	      kgid_has_mapping(user_ns, fc->cred->fsgid)) ||
+	     !ns_capable(fc->cred->user_ns, CAP_SYS_ADMIN)))
+		fc->user_ns = get_user_ns(user_ns);
+	else
+		fc->user_ns = get_user_ns(fc->cred->user_ns);
+
+	fc->rootns_bound = true;
+	fc->rootns_mnt_id = c->ns->mnt_ns->ns.ns_id;
+
+	ret = fc->fs_type->init_fs_context(fc);

[Severity: High]
Can fsconfig_set_rootns() leave fc->user_ns pointing to a user namespace other than c->user_ns while still marking fc->rootns_bound = true and fc->rootns_mnt_id = c->ns->mnt_ns->ns.ns_id?

First, fsopen() sets priv from may_mount() (CAP_SYS_ADMIN in current->nsproxy->mnt_ns->user_ns), whereas the fallback here tests !ns_capable(fc->cred->user_ns, CAP_SYS_ADMIN). If a task calls unshare(CLONE_NEWUSER) without CLONE_NEWNS (so priv is false in init_mnt_ns, but the caller has CAP_SYS_ADMIN in its new cred->user_ns U1) and binds to a child rootns (U2) before writing uid_map/gid_map, fc->user_ns falls back to U1 while fc->rootns_bound is true. Subsequent FSCONFIG_CMD_CREATE and fsmount() calls then authorize against U1 despite !may_mount(), and fsmount() allocates an anonymous mount namespace in U1 with ns->seq_origin set to U2's mount namespace ID.

Second, a nested container manager with CAP_SYS_ADMIN in U1 that binds a context to a child rootns U2 before U2's uid_map/gid_map are written (or when U2 maps subordinate IDs excluding fc->cred->fsuid/fsgid) also hits the else branch, leaving the superblock in U1 instead of delegating it to U2.

Third, calling fc->fs_type->init_fs_context(fc) after setting fc->user_ns allows filesystems without a ->set_rootns() hook to overwrite fc->user_ns from current->nsproxy (for example, cgroup_init_fs_context() resets fc->user_ns to current->nsproxy->cgroup_ns->user_ns).

Quoted 4 lines
fs/namespace.c +0 -0
index 781380945d784..dfe0ee9ecdcd0 100644

[ ... ]

Quoted 17 lines
fs/namespace.c +9 -0
@@ -4658,6 +4661,15 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 	if (ret)
 		return ret;
 
+	if (fc->rootns_bound) {
+		if (flags & FSMOUNT_NAMESPACE)
+			return -EINVAL;
+		if (!ns_capable(fc->user_ns, CAP_SYS_ADMIN))
+			return -EPERM;
+	} else if (!(flags & FSMOUNT_NAMESPACE) && !priv) {
+		return -EPERM;
+	}
+
 	/* There must be a valid superblock or we can't mount it */
 	ret = -EINVAL;
 	if (!fc->root)

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

Quoted 10 lines
fs/namespace.c +4 -1
@@ -4699,9 +4711,12 @@ 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(priv ? current->nsproxy->mnt_ns->user_ns :
+			  fc->user_ns, true);
 	if (IS_ERR(ns))
 		return PTR_ERR(ns);
+	if (!priv)
+		ns->seq_origin = fc->rootns_mnt_id;

[Severity: High]
Should alloc_mnt_ns() and ns->seq_origin be conditioned on fc->rootns_bound rather than priv?

When a manager process already has CAP_SYS_ADMIN in its own mount namespace (priv == true) and uses FSCONFIG_SET_ROOTNS to prepare a mount for a target rootns, testing priv allocates the anonymous mount namespace in current->nsproxy->mnt_ns->user_ns instead of fc->user_ns (causing attach_recursive_mnt() to lock the mount with MNT_LOCKED when moved into the target rootns) and leaves ns->seq_origin at 0 instead of restricting the detached mount to fc->rootns_mnt_id.

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

[ ... ]

Quoted 8 lines
fs/proc/root.c +4 -0
@@ -323,6 +325,21 @@ static int proc_get_tree(struct fs_context *fc)
 	return get_tree_nodev(fc, proc_fill_super);
 }
 
+static int proc_set_rootns(struct fs_context *fc, struct rootns *rootns)
+{
+	struct proc_fs_context *ctx = fc->fs_private;
+	struct pid_namespace *target = rootns->ns->pid_ns_for_children;

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

Quoted 10 lines
fs/proc/root.c +10 -0
+
+	if (!pidns_is_ancestor(target, task_active_pid_ns(current)))
+		return invalfc(fc, "cannot set pidns to non-descendant pidns");
+
+	put_pid_ns(ctx->pid_ns);
+	ctx->pid_ns = get_pid_ns(target);
+	put_user_ns(fc->user_ns);
+	fc->user_ns = get_user_ns(ctx->pid_ns->user_ns);
+	return 0;
+}

[Severity: Medium]
After proc_set_rootns() binds a context to a rootns, can a subsequent "pidns" mount option overwrite ctx->pid_ns and fc->user_ns?

fs/proc/root.c:proc_parse_param() {
	...
	case Opt_pidns:
		if (fc->purpose == FS_CONTEXT_FOR_RECONFIGURE) {
			errorfc(fc, "cannot reconfigure pidns for existing procfs");
			return -EBUSY;
		}
		err = proc_parse_pidns_param(fc, param, &result);
	...
}

proc_parse_pidns_param() replaces ctx->pid_ns and sets fc->user_ns to the new PID namespace's user_ns while fc->rootns_bound remains true and fc->rootns_mnt_id retains the original rootns mount namespace ID. fsmount() then checks CAP_SYS_ADMIN and allocates the anonymous mount namespace against the overwritten fc->user_ns while pairing it with ns->seq_origin = fc->rootns_mnt_id from the original rootns. Should Opt_pidns also be rejected when fc->rootns_bound is set?

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

RFC PATCH v4 9/14 fs: Support MOVE_MOUNT_T_MNTNS in move_mount()

In reply to Jarkko Sakkinen

move_mount() currently resolves target paths only against the caller's filesystem view or anonymous mount fds, preventing an external manager from populating an empty mount namespace or hot-mounting into an existing container's mount namespace without entering it first.

Add MOVE_MOUNT_T_MNTNS to attach detached anonymous mount trees into a target mount namespace nsfs file descriptor. Installing "/" attaches the initial root mount onto the nullfs root of an empty mount namespace at most once, while relative target paths resolve with LOOKUP_IN_ROOT beneath the live mount namespace root and reject root-mount aliases under namespace_lock().

Check CAP_SYS_ADMIN in the target mount namespace's owning user namespace instead of caller may_mount(), check nsfs mount loops against the destination mount namespace, and lock moved mount trees inside attach_recursive_mnt() when crossing user namespace boundaries.

---
 fs/namespace.c             | 218 +++++++++++++++++++++++++++++++------
 include/uapi/linux/mount.h |   3 +-
 2 files changed, 184 insertions(+), 37 deletions(-)
fs/namespace.c +182 -36
index dfe0ee9ecdcd..36ed48c3f646 100644
@@ -2202,7 +2202,8 @@ struct mnt_namespace *mnt_ns_from_dentry(struct dentry *dentry)
 	return to_mnt_ns(get_proc_ns(dentry->d_inode));
 }
 
-static bool mnt_ns_loop(struct dentry *dentry)
+static bool mnt_ns_loop_target(struct dentry *dentry,
+			       struct mnt_namespace *target_mnt_ns)
 {
 	/* Could bind mounting the mount namespace inode cause a
 	 * mount namespace loop?
@@ -2212,7 +2213,12 @@ static bool mnt_ns_loop(struct dentry *dentry)
 	if (!mnt_ns)
 		return false;
 
-	return current->nsproxy->mnt_ns->ns.ns_id >= mnt_ns->ns.ns_id;
+	return target_mnt_ns->ns.ns_id >= mnt_ns->ns.ns_id;
+}
+
+static bool mnt_ns_loop(struct dentry *dentry)
+{
+	return mnt_ns_loop_target(dentry, current->nsproxy->mnt_ns);
 }
 
 struct mount *copy_tree(struct mount *src_root, struct dentry *dentry,
@@ -2423,10 +2429,11 @@ static bool __has_children(struct mount *mnt, struct dentry *dentry)
  *
  * locks: mount_locked_reader || namespace_shared && pinned(subtree)
  */
-static bool check_for_nsfs_mounts(struct mount *subtree)
+static bool check_for_nsfs_mounts(struct mount *subtree,
+				  struct mnt_namespace *target_mnt_ns)
 {
 	for (struct mount *p = subtree; p; p = next_mnt(p, subtree))
-		if (mnt_ns_loop(p->mnt.mnt_root))
+		if (mnt_ns_loop_target(p->mnt.mnt_root, target_mnt_ns))
 			return false;
 	return true;
 }
@@ -2464,7 +2471,7 @@ struct vfsmount *clone_private_mount(const struct path *path)
 		if (!anon_ns_root(old_mnt))
 			return ERR_PTR(-EINVAL);
 
-		if (!check_for_nsfs_mounts(old_mnt))
+		if (!check_for_nsfs_mounts(old_mnt, current->nsproxy->mnt_ns))
 			return ERR_PTR(-EINVAL);
 	}
 
@@ -2564,12 +2571,15 @@ 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_MNTNS = BIT(2),
+	MNT_TREE_MNTNS_INIT = BIT(3),
 };
 
 /**
  * attach_recursive_mnt - attach a source mount tree
  * @source_mnt: mount tree to be attached
  * @dest:	the context for mounting at the place where the tree should go
+ * @move_mntns:	whether @source_mnt is attached via MOVE_MOUNT_T_MNTNS
  *
  *  NOTE: in the table below explains the semantics when a source mount
  *  of a given type is attached to a destination mount of a given type.
@@ -2632,7 +2642,8 @@ enum mnt_tree_flags_t {
  *         Otherwise a negative error code is returned.
  */
 static int attach_recursive_mnt(struct mount *source_mnt,
-				const struct pinned_mountpoint *dest)
+				const struct pinned_mountpoint *dest,
+				bool move_mntns)
 {
 	struct mount *dest_mnt = dest->parent;
 	struct mountpoint *dest_mp = dest->mp;
@@ -2641,6 +2652,7 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 	struct user_namespace *user_ns = ns->user_ns;
 	struct pinned_mountpoint root = {};
 	struct mountpoint *shorter = NULL;
+	struct mnt_namespace *src_ns;
 	struct mount *child, *p;
 	struct mount *top;
 	struct hlist_node *n;
@@ -2662,6 +2674,7 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 		user_ns = current->nsproxy->mnt_ns->user_ns;
 	else
 		user_ns = ns->user_ns;
+	src_ns = moving ? NULL : source_mnt->mnt_ns;
 
 	/*
 	 * Preallocate a mountpoint in case the new mounts need to be
@@ -2694,6 +2707,12 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 	if (err)
 		goto out_cleanup_ids;
 
+	if (move_mntns && src_ns && src_ns->user_ns != user_ns) {
+		lock_mnt_tree(source_mnt);
+		if (list_empty(&source_mnt->mnt_expire))
+			source_mnt->mnt.mnt_flags |= MNT_LOCKED;
+	}
+
 	if (IS_MNT_SHARED(dest_mnt)) {
 		for (p = source_mnt; p; p = next_mnt(p, source_mnt))
 			set_mnt_shared(p);
@@ -2937,7 +2956,7 @@ static int graft_tree(struct mount *mnt, const struct pinned_mountpoint *mp)
 	      d_is_dir(mnt->mnt.mnt_root))
 		return -ENOTDIR;
 
-	return attach_recursive_mnt(mnt, mp);
+	return attach_recursive_mnt(mnt, mp, false);
 }
 
 static int may_change_propagation(const struct mount *m)
@@ -3131,7 +3150,7 @@ static int do_loopback(const struct path *path, const char *old_name,
 		return PTR_ERR(mnt);
 
 	/* the copy may carry mount namespace files from below the source */
-	if (recurse && !check_for_nsfs_mounts(mnt))
+	if (recurse && !check_for_nsfs_mounts(mnt, current->nsproxy->mnt_ns))
 		err = -EINVAL;
 	else
 		err = graft_tree(mnt, &mp);
@@ -3776,9 +3795,11 @@ static inline bool may_use_mount(struct mount *mnt)
 
 static int do_move_mount(const struct path *old_path,
 			 const struct path *new_path,
-			 enum mnt_tree_flags_t flags)
+			 enum mnt_tree_flags_t flags,
+			 struct mnt_namespace *target_mnt_ns)
 {
 	struct mount *old = real_mount(old_path->mnt);
+	struct mnt_namespace *dest_mnt_ns;
 	int err;
 	bool beneath = flags & MNT_TREE_BENEATH;
 
@@ -3792,7 +3813,23 @@ 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_MNTNS) {
+		if (!anon_ns_root(old) || old->mnt_ns == mp.parent->mnt_ns ||
+		    mp.parent->mnt_ns != target_mnt_ns)
+			return -EINVAL;
+		if (flags & MNT_TREE_MNTNS_INIT) {
+			if (mp.parent != target_mnt_ns->root)
+				return -EBUSY;
+		} else if (mp.mp->m_dentry == mp.parent->mnt.mnt_root) {
+			const struct mount *m = mp.parent;
+
+			while (m != target_mnt_ns->root && mnt_has_parent(m) &&
+			       m->mnt_mountpoint == m->mnt_parent->mnt.mnt_root)
+				m = m->mnt_parent;
+			if (m == target_mnt_ns->root)
+				return beneath ? -EINVAL : -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))
@@ -3840,12 +3877,14 @@ static int do_move_mount(const struct path *old_path,
 	 */
 	if (IS_MNT_SHARED(mp.parent) && tree_contains_unbindable(old))
 		return -EINVAL;
-	if (!check_for_nsfs_mounts(old))
+	dest_mnt_ns = is_anon_ns(mp.parent->mnt_ns) ?
+		      current->nsproxy->mnt_ns : mp.parent->mnt_ns;
+	if (!check_for_nsfs_mounts(old, dest_mnt_ns))
 		return -ELOOP;
 	if (mount_is_ancestor(old, mp.parent))
 		return -ELOOP;
 
-	return attach_recursive_mnt(old, &mp);
+	return attach_recursive_mnt(old, &mp, flags & MNT_TREE_MNTNS);
 }
 
 static int do_move_mount_old(const struct path *path, const char *old_name)
@@ -3860,7 +3899,7 @@ static int do_move_mount_old(const struct path *path, const char *old_name)
 	if (err)
 		return err;
 
-	return do_move_mount(&old_path, path, 0);
+	return do_move_mount(&old_path, path, 0, NULL);
 }
 
 /*
@@ -4740,7 +4779,8 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 
 static inline int vfs_move_mount(const struct path *from_path,
 				 const struct path *to_path,
-				 enum mnt_tree_flags_t mflags)
+				 enum mnt_tree_flags_t mflags,
+				 struct mnt_namespace *target_mnt_ns)
 {
 	int ret;
 
@@ -4751,7 +4791,123 @@ static inline int vfs_move_mount(const struct path *from_path,
 	if (mflags & MNT_TREE_PROPAGATION)
 		return do_set_group(from_path, to_path);
 
-	return do_move_mount(from_path, to_path, mflags);
+	return do_move_mount(from_path, to_path, mflags, target_mnt_ns);
+}
+
+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_MNTNS
+ *
+ * ``MOVE_MOUNT_T_MNTNS`` installs detached anonymous mount trees into a target
+ * mount namespace ``nsfs`` file descriptor supplied as ``to_dfd``:
+ *
+ * 1. ``to_pathname`` of ``"/"`` attaches the initial root mount onto the
+ *    ``nullfs`` root of an empty mount namespace at most once.
+ *
+ * 2. Relative ``to_pathname`` values resolve beneath the live root of the
+ *    target mount namespace.
+ *
+ * Capability is checked against ``CAP_SYS_ADMIN`` in the target mount
+ * namespace's owning user namespace, and source trees crossing user namespace
+ * boundaries are locked with ``MNT_LOCKED`` and locked mount flags.
+ */
+static int move_mount_mntns(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 *target_mnt_ns;
+	unsigned int lflags;
+	struct ns_common *ns;
+	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_mntns)(to_dfd);
+	if (fd_empty(f_mntns))
+		return -EBADF;
+	if (!proc_ns_file(fd_file(f_mntns)))
+		return -EINVAL;
+
+	ns = get_proc_ns(file_inode(fd_file(f_mntns)));
+	if (ns->ns_type != CLONE_NEWNS)
+		return -EINVAL;
+
+	target_mnt_ns = to_mnt_ns(ns);
+	if (is_anon_ns(target_mnt_ns))
+		return -EINVAL;
+	if (!ns_capable(target_mnt_ns->user_ns, CAP_SYS_ADMIN))
+		return -EPERM;
+
+	is_root = to_name->name[0] == '/' && to_name->name[1] == '\0';
+	if (is_root) {
+		if (flags & MOVE_MOUNT_BENEATH)
+			return -EINVAL;
+
+		to_path.mnt = mntget(&target_mnt_ns->root->mnt);
+		to_path.dentry = dget(target_mnt_ns->root->mnt.mnt_root);
+		mflags |= MNT_TREE_MNTNS_INIT;
+	} else {
+		struct path mntns_root __free(path_put) = {};
+
+		if (to_name->name[0] == '/')
+			return -EINVAL;
+
+		ret = mnt_ns_get_root(target_mnt_ns, &mntns_root);
+		if (ret)
+			return ret;
+
+		lflags = LOOKUP_IN_ROOT;
+		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,
+				      &mntns_root);
+		if (ret)
+			return ret;
+	}
+
+	ret = lookup_move_mount_from(from_dfd, from_pathname, flags,
+				     &from_path);
+	if (ret)
+		return ret;
+
+	return vfs_move_mount(&from_path, &to_path, mflags | MNT_TREE_MNTNS,
+			      target_mnt_ns);
 }
 
 /*
@@ -4773,7 +4929,7 @@ SYSCALL_DEFINE5(move_mount,
 	enum mnt_tree_flags_t mflags = 0;
 	int ret = 0;
 
-	if (!may_mount())
+	if (!(flags & MOVE_MOUNT_T_MNTNS) && !may_mount())
 		return -EPERM;
 
 	if (flags & ~MOVE_MOUNT__MASK)
@@ -4786,6 +4942,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_MNTNS)) {
+		if (flags & (MOVE_MOUNT_T_EMPTY_PATH | MOVE_MOUNT_SET_GROUP))
+			return -EINVAL;
+		return move_mount_mntns(from_dfd, from_pathname,
+					to_dfd, to_pathname, flags, mflags);
+	}
+
 	uflags = 0;
 	if (flags & MOVE_MOUNT_T_EMPTY_PATH)
 		uflags = AT_EMPTY_PATH;
@@ -4809,29 +4972,12 @@ 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;
 
-	return vfs_move_mount(&from_path, &to_path, mflags);
+	return vfs_move_mount(&from_path, &to_path, mflags, NULL);
 }
 
 /*
include/uapi/linux/mount.h +2 -1
index cb55cfcfc92e..7fa93de08ceb 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_MNTNS		0x00000080 /* Resolve to_dfd as mntns fd */
 #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
#18 lore raw

Re: [RFC PATCH v4 09/14] fs: Support MOVE_MOUNT_T_MNTNS in move_mount()

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] fs: cross-userns mount locking bypass in attach_recursive_mnt() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] fs: cross-userns mount locking bypass in attach_recursive_mnt() --

commit 5e90ce5c3ee9b66d7c6a41077c19c225ae139217
Author: Jarkko Sakkinen <[email protected]>

fs: Support MOVE_MOUNT_T_MNTNS in move_mount()

This commit adds the MOVE_MOUNT_T_MNTNS flag to move_mount() so that detached anonymous mount trees can be attached directly into a target mount namespace specified by an nsfs file descriptor.

Quoted 4 lines
fs/namespace.c +0 -0
index dfe0ee9ecdcd0..36ed48c3f6467 100644

[ ... ]

Quoted 27 lines
fs/namespace.c +4 -1
@@ -2632,7 +2642,8 @@ enum mnt_tree_flags_t {
  *         Otherwise a negative error code is returned.
  */
 static int attach_recursive_mnt(struct mount *source_mnt,
-				const struct pinned_mountpoint *dest)
+				const struct pinned_mountpoint *dest,
+				bool move_mntns)
 {
 	struct mount *dest_mnt = dest->parent;
 	struct mountpoint *dest_mp = dest->mp;
@@ -2641,6 +2652,7 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 	struct user_namespace *user_ns = ns->user_ns;
 	struct pinned_mountpoint root = {};
 	struct mountpoint *shorter = NULL;
+	struct mnt_namespace *src_ns;
 	struct mount *child, *p;
 	struct mount *top;
 	struct hlist_node *n;
@@ -2662,6 +2674,7 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 		user_ns = current->nsproxy->mnt_ns->user_ns;
 	else
 		user_ns = ns->user_ns;
+	src_ns = moving ? NULL : source_mnt->mnt_ns;
 
 	/*
 	 * Preallocate a mountpoint in case the new mounts need to be

fs/namespace.c static int attach_recursive_mnt(struct mount *source_mnt, · line 2714

Quoted 8 lines
fs/namespace.c +5 -0
@@ -2694,6 +2707,12 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 	if (err)
 		goto out_cleanup_ids;
 
+	if (move_mntns && src_ns && src_ns->user_ns != user_ns) {
+		lock_mnt_tree(source_mnt);
+		if (list_empty(&source_mnt->mnt_expire))
+			source_mnt->mnt.mnt_flags |= MNT_LOCKED;
+	}

[Severity: High]
Does calling lock_mnt_tree(source_mnt) after propagate_mnt() leave secondary copies unlocked when MOVE_MOUNT_T_MNTNS attaches a tree onto a shared destination mount across user namespaces?

When IS_MNT_SHARED(dest_mnt) is true, propagate_mnt() clones source_mnt into tree_list before source_mnt is locked here, so the clones do not inherit MNT_LOCK_* or MNT_LOCKED (and copy_tree() silently skips unlocked nsfs submounts instead of failing with -EPERM). Then the tree_list loop checks:

fs/namespace.c:attach_recursive_mnt() {
	...
	hlist_for_each_entry_safe(child, n, &tree_list, mnt_hash) {
		struct mount *q;
		hlist_del_init(&child->mnt_hash);
		/* Notice when we are propagating across user namespaces */
		if (child->mnt_parent->mnt_ns->user_ns != user_ns)
			lock_mnt_tree(child);
	...
}

Because user_ns is dest_mnt->mnt_ns->user_ns rather than src_ns->user_ns, secondary copies propagated to peer or slave mounts in the target user namespace match user_ns and skip lock_mnt_tree(child), allowing root in the target user namespace to unmount masking submounts or clear read-only, nosuid, nodev, and noexec flags.

In addition, if a foreign anonymous mount from another user namespace was previously attached via regular move_mount() as a submount of an anonymous mount tree already owned by the target user namespace, commit_tree() set the submount's mnt_ns to the anonymous tree without setting MNT_LOCKED on that submount's root, and attaching the anonymous tree with MOVE_MOUNT_T_MNTNS skips lock_mnt_tree() because src_ns->user_ns already equals user_ns.

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

RFC PATCH v4 10/14 security: Add rootns LSM hooks

In reply to Jarkko Sakkinen

Security modules need visibility into root namespace creation, teardown, process entry, and container-wide signal delivery so policies and BPF LSM programs can attach per-rootns security state and mediate operations on rootns file descriptors.

Add lbs_rootns and rootns->security blob management alongside security_rootns_alloc(), security_rootns_free(), security_rootns_clone(), and security_rootns_kill(), and register the new hooks in bpf_lsm.c's sleepable and untrusted hook sets.

---
 include/linux/lsm_hook_defs.h |  7 +++
 include/linux/lsm_hooks.h     |  3 ++
 include/linux/rootns.h        |  3 ++
 include/linux/security.h      | 30 ++++++++++++
 kernel/bpf/bpf_lsm.c          | 10 ++++
 kernel/rootns.c               | 44 +++++++++++++-----
 security/lsm_init.c           |  6 +++
 security/security.c           | 86 +++++++++++++++++++++++++++++++++++
 8 files changed, 177 insertions(+), 12 deletions(-)
include/linux/lsm_hook_defs.h +7 -0
index 87d9d06710cb..2cb90ddedc14 100644
@@ -480,3 +480,10 @@ LSM_HOOK(int, 0, bdev_alloc_security, struct block_device *bdev)
 LSM_HOOK(void, LSM_RET_VOID, bdev_free_security, struct block_device *bdev)
 LSM_HOOK(int, 0, bdev_setintegrity, struct block_device *bdev,
 	 enum lsm_integrity_type type, const void *value, size_t size)
+
+#ifdef CONFIG_ROOTNS
+LSM_HOOK(int, 0, rootns_alloc, struct rootns *rootns, unsigned int flags)
+LSM_HOOK(void, LSM_RET_VOID, rootns_free, struct rootns *rootns)
+LSM_HOOK(int, 0, rootns_clone, struct rootns *rootns)
+LSM_HOOK(int, 0, rootns_kill, struct rootns *rootns, int sig)
+#endif /* CONFIG_ROOTNS */
include/linux/lsm_hooks.h +3 -0
index 13621e9e233e..217a59d428b1 100644
@@ -121,6 +121,9 @@ struct lsm_blob_sizes {
 	unsigned int lbs_bpf_map;
 	unsigned int lbs_bpf_prog;
 	unsigned int lbs_bpf_token;
+#ifdef CONFIG_ROOTNS
+	unsigned int lbs_rootns;
+#endif
 };
 
 /*
include/linux/rootns.h +3 -0
index 802fc76bb66e..795a79584231 100644
@@ -31,6 +31,9 @@ enum rootns_state {
 struct rootns {
 	refcount_t		usage;
 	int			exit_code;	/* The exit code of 'init' */
+#ifdef CONFIG_SECURITY
+	void			*security;	/* LSM security blob */
+#endif
 	struct user_namespace	*user_ns;	/* Owning user namespace */
 	struct nsproxy		*ns;		/* This rootns's namespaces */
 	struct pid		*init_pid;	/* The 'init' task's TGID (pid ref) */
include/linux/security.h +30 -0
index 40831fab5470..995292f1c92e 100644
@@ -84,6 +84,7 @@ struct audit_krule;
 struct ns_common;
 struct user_namespace;
 struct timezone;
+struct rootns;
 
 enum lsm_event {
 	LSM_POLICY_CHANGE,
@@ -2469,4 +2470,33 @@ static inline void security_initramfs_populated(void)
 }
 #endif /* CONFIG_SECURITY */
 
+#ifdef CONFIG_ROOTNS
+#ifdef CONFIG_SECURITY
+int security_rootns_alloc(struct rootns *rootns, unsigned int flags);
+void security_rootns_free(struct rootns *rootns);
+int security_rootns_clone(struct rootns *rootns);
+int security_rootns_kill(struct rootns *rootns, int sig);
+#else
+static inline int security_rootns_alloc(struct rootns *rootns,
+					unsigned int flags)
+{
+	return 0;
+}
+
+static inline void security_rootns_free(struct rootns *rootns)
+{
+}
+
+static inline int security_rootns_clone(struct rootns *rootns)
+{
+	return 0;
+}
+
+static inline int security_rootns_kill(struct rootns *rootns, int sig)
+{
+	return 0;
+}
+#endif /* CONFIG_SECURITY */
+#endif /* CONFIG_ROOTNS */
+
 #endif /* ! __LINUX_SECURITY_H */
kernel/bpf/bpf_lsm.c +10 -0
index 468e63dbd922..bbcf1433fdc2 100644
@@ -16,6 +16,7 @@
 #include <linux/btf_ids.h>
 #include <linux/ima.h>
 #include <linux/bpf-cgroup.h>
+#include <linux/rootns.h>
 
 /* For every LSM hook that allows attachment of BPF programs, declare a nop
  * function where a BPF program can be attached. Notably, we qualify each with
@@ -404,6 +405,11 @@ BTF_ID(func, bpf_lsm_task_setscheduler)
 BTF_ID(func, bpf_lsm_userns_create)
 BTF_ID(func, bpf_lsm_bdev_alloc_security)
 BTF_ID(func, bpf_lsm_bdev_setintegrity)
+#ifdef CONFIG_ROOTNS
+BTF_ID(func, bpf_lsm_rootns_alloc)
+BTF_ID(func, bpf_lsm_rootns_clone)
+BTF_ID(func, bpf_lsm_rootns_kill)
+#endif /* CONFIG_ROOTNS */
 BTF_SET_END(sleepable_lsm_hooks)
 
 BTF_SET_START(untrusted_lsm_hooks)
@@ -420,6 +426,10 @@ BTF_ID(func, bpf_lsm_sk_free_security)
 BTF_ID(func, bpf_lsm_task_free)
 BTF_ID(func, bpf_lsm_bdev_alloc_security)
 BTF_ID(func, bpf_lsm_bdev_free_security)
+#ifdef CONFIG_ROOTNS
+BTF_ID(func, bpf_lsm_rootns_alloc)
+BTF_ID(func, bpf_lsm_rootns_free)
+#endif /* CONFIG_ROOTNS */
 BTF_SET_END(untrusted_lsm_hooks)
 
 bool bpf_lsm_is_sleepable_hook(u32 btf_id)
kernel/rootns.c +32 -12

107 lines not on this page · raw message

security/lsm_init.c +6 -0
index 8d5ecea99c46..56b515b20812 100644
@@ -316,6 +316,9 @@ static void __init lsm_prepare(struct lsm_info *lsm)
 	lsm_blob_size_update(&blobs->lbs_bpf_map, &blob_sizes.lbs_bpf_map);
 	lsm_blob_size_update(&blobs->lbs_bpf_prog, &blob_sizes.lbs_bpf_prog);
 	lsm_blob_size_update(&blobs->lbs_bpf_token, &blob_sizes.lbs_bpf_token);
+#ifdef CONFIG_ROOTNS
+	lsm_blob_size_update(&blobs->lbs_rootns, &blob_sizes.lbs_rootns);
+#endif
 }
 
 /**
@@ -460,6 +463,9 @@ int __init security_init(void)
 		lsm_pr("blob(bpf_map) size %d\n", blob_sizes.lbs_bpf_map);
 		lsm_pr("blob(bpf_prog) size %d\n", blob_sizes.lbs_bpf_prog);
 		lsm_pr("blob(bpf_token) size %d\n", blob_sizes.lbs_bpf_token);
+#ifdef CONFIG_ROOTNS
+		lsm_pr("blob(rootns) size %d\n", blob_sizes.lbs_rootns);
+#endif
 	}
 
 	if (blob_sizes.lbs_file)
security/security.c +86 -0

101 lines not on this page · raw message

Signature · 1 line
2.47.3
#20 lore raw

RFC PATCH v4 11/14 arch: Wire up rootns() system call

In reply to Jarkko Sakkinen

Now that the core root namespace lifecycle and VFS mount-tree installation are in place, expose rootns() (473, 583 on Alpha) across all architecture system call tables and asm-generic unistd.h.

---
 arch/alpha/kernel/syscalls/syscall.tbl      | 1 +
 arch/arm/tools/syscall.tbl                  | 1 +
 arch/arm64/tools/syscall_32.tbl             | 1 +
 arch/m68k/kernel/syscalls/syscall.tbl       | 1 +
 arch/microblaze/kernel/syscalls/syscall.tbl | 1 +
 arch/mips/kernel/syscalls/syscall_n32.tbl   | 1 +
 arch/mips/kernel/syscalls/syscall_n64.tbl   | 1 +
 arch/mips/kernel/syscalls/syscall_o32.tbl   | 1 +
 arch/parisc/kernel/syscalls/syscall.tbl     | 1 +
 arch/powerpc/kernel/syscalls/syscall.tbl    | 1 +
 arch/s390/kernel/syscalls/syscall.tbl       | 1 +
 arch/sh/kernel/syscalls/syscall.tbl         | 1 +
 arch/sparc/kernel/syscalls/syscall.tbl      | 1 +
 arch/x86/entry/syscalls/syscall_32.tbl      | 1 +
 arch/x86/entry/syscalls/syscall_64.tbl      | 1 +
 arch/xtensa/kernel/syscalls/syscall.tbl     | 1 +
 include/uapi/asm-generic/unistd.h           | 6 +++++-
 scripts/syscall.tbl                         | 1 +
 18 files changed, 22 insertions(+), 1 deletion(-)
arch/alpha/kernel/syscalls/syscall.tbl +1 -0
index 52e3538cc7df..ea790cceb67a 100644
@@ -512,3 +512,4 @@
 580	common	listns				sys_listns
 581	common	rseq_slice_yield		sys_rseq_slice_yield
 582	common	fchroot				sys_fchroot
+583	common	rootns				sys_rootns
arch/arm/tools/syscall.tbl +1 -0
index 55717ed32c27..531b2a2dce72 100644
@@ -487,3 +487,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
arch/arm64/tools/syscall_32.tbl +1 -0
index df2d1d82fb3c..8ef224c0dd42 100644
@@ -484,3 +484,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
arch/m68k/kernel/syscalls/syscall.tbl +1 -0
index ba7a4d8903d0..77239262dc26 100644
@@ -472,3 +472,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
arch/microblaze/kernel/syscalls/syscall.tbl +1 -0
index 76d7cbe2a133..df53332ce4a5 100644
@@ -478,3 +478,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
arch/mips/kernel/syscalls/syscall_n32.tbl +1 -0
index 9ae88e4eac61..84db40158bf0 100644
@@ -411,3 +411,4 @@
 470	n32	listns				sys_listns
 471	n32	rseq_slice_yield		sys_rseq_slice_yield
 472	n32	fchroot				sys_fchroot
+473	n32	rootns				sys_rootns
arch/mips/kernel/syscalls/syscall_n64.tbl +1 -0
index 83dc93a0712f..9e874a958503 100644
@@ -387,3 +387,4 @@
 470	n64	listns				sys_listns
 471	n64	rseq_slice_yield		sys_rseq_slice_yield
 472	n64	fchroot				sys_fchroot
+473	n64	rootns				sys_rootns
arch/mips/kernel/syscalls/syscall_o32.tbl +1 -0
index 9c62429c9b7b..592c2225f4ce 100644
@@ -460,3 +460,4 @@
 470	o32	listns				sys_listns
 471	o32	rseq_slice_yield		sys_rseq_slice_yield
 472	o32	fchroot				sys_fchroot
+473	o32	rootns				sys_rootns
arch/parisc/kernel/syscalls/syscall.tbl +1 -0
index 88adc4016cce..93f8539bd179 100644
@@ -471,3 +471,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
arch/powerpc/kernel/syscalls/syscall.tbl +1 -0
index cfbb70039ff0..7e12f74a27c1 100644
@@ -563,3 +563,4 @@
 470	common	listns				sys_listns
 471	nospu	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	nospu	rootns				sys_rootns
arch/s390/kernel/syscalls/syscall.tbl +1 -0
index 1b45e68a217b..ab303fbb86f3 100644
@@ -399,3 +399,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
arch/sh/kernel/syscalls/syscall.tbl +1 -0
index ace068dff0de..e92778075bcb 100644
@@ -476,3 +476,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
arch/sparc/kernel/syscalls/syscall.tbl +1 -0
index 5b9fe0e8140f..20d6c572d3f1 100644
@@ -518,3 +518,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 2c172ef48dfd..98cb11b717e5 100644
@@ -478,3 +478,4 @@
 470	i386	listns			sys_listns
 471	i386	rseq_slice_yield	sys_rseq_slice_yield
 472	i386	fchroot			sys_fchroot
+473	i386	rootns			sys_rootns
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index d5b6045b0090..674fa2b4b238 100644
@@ -397,6 +397,7 @@
 470	common	listns			sys_listns
 471	common	rseq_slice_yield	sys_rseq_slice_yield
 472	common	fchroot			sys_fchroot
+473	common	rootns			sys_rootns
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
arch/xtensa/kernel/syscalls/syscall.tbl +1 -0
index d354bb231796..82b7344a099c 100644
@@ -443,3 +443,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
include/uapi/asm-generic/unistd.h +5 -1
index 5b7e77a7c736..25902ed39d79 100644
@@ -867,8 +867,12 @@ __SYSCALL(__NR_rseq_slice_yield, sys_rseq_slice_yield)
 #define __NR_fchroot 472
 __SYSCALL(__NR_fchroot, sys_fchroot)
 
+/* kernel/rootns.c */
+#define __NR_rootns 473
+__SYSCALL(__NR_rootns, sys_rootns)
+
 #undef __NR_syscalls
-#define __NR_syscalls 473
+#define __NR_syscalls 474
 
 /*
  * 32 bit systems traditionally used different
scripts/syscall.tbl +1 -0
index 0ab531605120..b6d1b033f49a 100644
@@ -413,3 +413,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
Signature · 1 line
2.47.3
#21 lore raw

RFC PATCH v4 12/14 docs: Document root namespace uAPI

In reply to Jarkko Sakkinen

Userspace container managers need a clear specification of rootns state transitions, control ioctls, mount-tree construction, credential rules, and process creation semantics.

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

---
 Documentation/userspace-api/index.rst         |  1 +
 .../userspace-api/ioctl/ioctl-number.rst      |  1 +
 Documentation/userspace-api/rootns.rst        | 56 +++++++++++++++++++
 3 files changed, 58 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/ioctl/ioctl-number.rst +1 -0
index dbe462040999..d8dc926ea283 100644
@@ -385,6 +385,7 @@ Code  Seq#    Include File                                             Comments
 0xB8  01-02  uapi/misc/mrvl_cn10k_dpi.h                                Marvell CN10K DPI driver
 0xB8  all    uapi/linux/mshv.h                                         Microsoft Hyper-V /dev/mshv driver
                                                                        <mailto:[email protected]>
+0xB9  00-0F  uapi/linux/rootns.h                                       Root namespace uAPI
 0xBA  00-0F  uapi/linux/liveupdate.h                                   Pasha Tatashin
                                                                        <mailto:[email protected]>
 0xC0  00-0F  linux/usb/iowarrior.h
Documentation/userspace-api/rootns.rst new file +56 -0

56 lines not on this page · raw message

Signature · 1 line
2.47.3
#22 lore raw

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

In reply to Jarkko Sakkinen

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

---
 tools/testing/selftests/Makefile              |    1 +
 tools/testing/selftests/rootns/Makefile       |    5 +
 tools/testing/selftests/rootns/config         |   10 +
 .../testing/selftests/rootns/rootns_cells.py  | 1076 +++++++++++++++
 tools/testing/selftests/rootns/rootns_test.py | 1161 +++++++++++++++++
 tools/testing/selftests/rootns/test_smoke.sh  |   11 +
 6 files changed, 2264 insertions(+)
 create mode 100644 tools/testing/selftests/rootns/Makefile
 create mode 100644 tools/testing/selftests/rootns/config
 create mode 100755 tools/testing/selftests/rootns/rootns_cells.py
 create mode 100755 tools/testing/selftests/rootns/rootns_test.py
 create mode 100755 tools/testing/selftests/rootns/test_smoke.sh
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/Makefile new file +5 -0
new file mode 100644
index 000000000000..62629d112e12
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+include ../lib.mk
+
+TEST_PROGS := test_smoke.sh
+TEST_PROGS_EXTENDED := rootns_cells.py rootns_test.py
tools/testing/selftests/rootns/config new file +10 -0
new file mode 100644
index 000000000000..21b1aecc003b
@@ -0,0 +1,10 @@
+CONFIG_CGROUPS=y
+CONFIG_IPC_NS=y
+CONFIG_NET_NS=y
+CONFIG_PID_NS=y
+CONFIG_PROC_FS=y
+CONFIG_ROOTNS=y
+CONFIG_TIME_NS=y
+CONFIG_TMPFS=y
+CONFIG_USER_NS=y
+CONFIG_UTS_NS=y
tools/testing/selftests/rootns/rootns_cells.py new file +1076 -0

1,076 lines not on this page · raw message

tools/testing/selftests/rootns/rootns_test.py new file +1161 -0

1,161 lines not on this page · raw message

tools/testing/selftests/rootns/test_smoke.sh new file +11 -0
new file mode 100755
index 000000000000..2cb23ca2ad29
@@ -0,0 +1,11 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0
+
+# Kselftest framework requirement - SKIP code is 4.
+ksft_skip=4
+
+command -v python3 >/dev/null 2>&1 || exit $ksft_skip
+
+DIR="$(dirname "$(readlink -f "$0")")"
+PYTHONPATH="$DIR${PYTHONPATH:+:$PYTHONPATH}" \
+	python3 -m unittest -v rootns_test 2>&1
Signature · 1 line
2.47.3
#23 lore raw

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

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] selftests/rootns: wrong _IOC_NONE direction in _io() on wide-ioc archs - [Low] selftests/rootns…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] selftests/rootns: wrong _IOC_NONE direction in _io() on wide-ioc archs
- [Low] selftests/rootns: non-blocking accepted socket in CellService._on_accept()
- [Low] selftests/rootns: resource leaks on Cell init and test setUp() failures
--

commit 646cdbb1cf35062e2a914f151927bb968fe747a7
Author: Jarkko Sakkinen <[email protected]>

selftests/rootns: Add root namespace test suite

This commit adds a kselftest suite for the rootns and mount-namespace configuration uAPI, covering privileged, unprivileged, and edge-case scenarios.

Quoted 5 lines
tools/testing/selftests/rootns/rootns_cells.py new file +0 -0
new file mode 100755
index 0000000000000..b690ed71a5211

[ ... ]

tools/testing/selftests/rootns/rootns_cells.py line 141

Quoted 7 lines
tools/testing/selftests/rootns/rootns_cells.py new file +7 -0
+def _io(magic: int, nr: int) -> int:
+    return _ioc(0, magic, nr, 0)
+
+
+def _iowr(magic: int, nr: int, size: int) -> int:
+    rw = 6 if _is_wide_ioc_arch() else 3
+    return _ioc(rw, magic, nr, size)

[Severity: Medium]
Should _io() pass direction 1 instead of 0 when _is_wide_ioc_arch() is True?

On PowerPC, SPARC, Alpha, and MIPS, _IOC_NONE is 1U rather than 0U, so _IO() sets bit 29. Passing 0 encodes the wrong ioctl numbers for ROOTNS_GET_NSFD, ROOTNS_KILL, and NS_GET_*, causing the kernel to reject them with ENOTTY.

[ ... ]

tools/testing/selftests/rootns/rootns_cells.py line 573

Quoted 13 lines

+@dataclass

tools/testing/selftests/rootns/rootns_cells.py new file +12 -0
+class Cell:
+    name: str
+    flags: int = ROOTNS_KILL_ON_CLOSE | ROOTNS_CLOSE_ON_EXEC
+    cfd: int = field(init=False, default=-1)
+    mntns_fd: int = field(init=False, default=-1)
+    root_dfd: int = field(init=False, default=-1)
+    init_pid: int | None = field(init=False, default=None)
+    exit_status: int | None = field(init=False, default=None)
+
+    def __post_init__(self) -> None:
+        self.cfd = rootns(self.flags)
+        self.mntns_fd = rootns_get_nsfd(self.cfd, CLONE_NEWNS)

[Severity: Low]
Does Cell.__post_init__() leak self.cfd and the namespaces it pins if rootns_get_nsfd() raises OSError?

Similarly, in rootns_test.py, unittest does not run tearDown() when setUp() fails or raises an exception, so CellServiceTest.setUp() leaks self.daemon_pid and self.tmpdir if the daemon readiness loop calls self.fail(), and RootnsUapiTest.setUp() leaks self.cell's file descriptors if setup_rootfs() fails.

[ ... ]

Quoted 2 lines
tools/testing/selftests/rootns/rootns_cells.py new file +2 -0
+class CellService:
+    def __init__(self, sock_path: str) -> None:

[ ... ]

Quoted 2 lines
tools/testing/selftests/rootns/rootns_cells.py new file +2 -0
+        self.srv.setblocking(False)
+        self.sel.register(self.srv, selectors.EVENT_READ, self._on_accept)

[ ... ]

tools/testing/selftests/rootns/rootns_cells.py line 787

Quoted 9 lines
tools/testing/selftests/rootns/rootns_cells.py new file +9 -0
+    def _on_accept(self) -> None:
+        conn, _ = self.srv.accept()
+        with conn:
+            data = b""
+            while not data.endswith(b"\n"):
+                chunk = conn.recv(4096)
+                if not chunk:
+                    break
+                data += chunk

[Severity: Low]
Can conn.recv(4096) raise an uncaught BlockingIOError here?

In Python, socket.accept() on a non-blocking listening socket returns a non-blocking client socket. If _on_accept() runs after connect() wakes the listening socket but before the client sends its request line, conn.recv() fails with EAGAIN and crashes serve_forever() unless conn.setblocking(True) is called first.

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

RFC PATCH v4 14/14 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 7cbce21ba45a..072be5ec7fd8 100644
@@ -24533,6 +24533,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
#25 lore raw
In reply to Jarkko Sakkinen
Quoted 6 lines · Jarkko Sakkinen

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() system call
rootns: Add ROOTNS_WAIT ioctl
rootns: Add ROOTNS_KILL ioctl

Quoted 8 lines

fork: Support CLONE_INTO_ROOTNS in clone3()
fs: Support FSCONFIG_SET_ROOTNS in fsconfig()
fs: Support MOVE_MOUNT_T_MNTNS in move_mount()
security: Add rootns LSM hooks
arch: Wire up rootns() system call
docs: Document root namespace uAPI
selftests/rootns: Add root namespace test suite
MAINTAINERS: Add entry for ROOT NAMESPACE

Since David's picking up patches, and starting to drill them, I've not paid apparently enough attention to patch division. Just noticed when I had hard time finding mqueue and procfs changes.

I've now re-sliced these into a bit more sane pieces:

$ git log --oneline master..
d8e24a6bc14e (HEAD -> rootns, origin/rootns) MAINTAINERS: Add entry for ROOT NAMESPACE
f2569e56a267 selftests/rootns: Add root namespace test suite
bea05e758f8e docs: Document root namespace uAPI
dd05a49aff77 arch: Wire up rootns() system call
2dee7a5fddec bpf: Register rootns LSM hooks
73c51e02b830 security: Add rootns LSM hooks
3cfd6576a037 mount: Support MOVE_MOUNT_T_MNTNS in move_mount()
9ed7387038ea ipc/mqueue: Implement ->set_rootns() fs_context operation
624f0ed9c1c7 proc: Implement ->set_rootns() fs_context operation
1085e6ae2eb3 fs: Support FSCONFIG_SET_ROOTNS in fsconfig()
d2898dbdc39b fork: Support CLONE_INTO_ROOTNS in clone3()
42dbccb5890e rootns: Add ROOTNS_KILL ioctl
14cbda3e5bca rootns: Add ROOTNS_WAIT ioctl
b2cc82539b75 rootns: Add rootns() system call
d29215aa7f0f rootns: Track init lifecycle via copy_process() and pid_namespace
0f9ce7febb49 rootns: Add core infrastructure for root namespaces
7a0e8f969fc7 mount: Enforce mount_too_revealing() for foreign mntns
8c61aee3afbf mount: Add mnt_ns_get_root()
07d239d0287c userns: Factor out install_user_ns_cred()
bf74588e706d nsfs: Add nsproxy_open_namespace()
645d31a1c516 nsproxy: Pass nsproxy to create_new_namespaces()

I would also divide "arch: Wire up rootns() system call" into multiple patches, if this was not an RFC.

Br, Jarkko

#26 lore raw
Quoted 16 lines · Jarkko Sakkinen

I've now re-sliced these into a bit more sane pieces:

$ git log --oneline master..
d8e24a6bc14e (HEAD -> rootns, origin/rootns) MAINTAINERS: Add entry for ROOT NAMESPACE
f2569e56a267 selftests/rootns: Add root namespace test suite
bea05e758f8e docs: Document root namespace uAPI
dd05a49aff77 arch: Wire up rootns() system call
2dee7a5fddec bpf: Register rootns LSM hooks
73c51e02b830 security: Add rootns LSM hooks
3cfd6576a037 mount: Support MOVE_MOUNT_T_MNTNS in move_mount()
9ed7387038ea ipc/mqueue: Implement ->set_rootns() fs_context operation
624f0ed9c1c7 proc: Implement ->set_rootns() fs_context operation
1085e6ae2eb3 fs: Support FSCONFIG_SET_ROOTNS in fsconfig()
d2898dbdc39b fork: Support CLONE_INTO_ROOTNS in clone3()
42dbccb5890e rootns: Add ROOTNS_KILL ioctl
14cbda3e5bca rootns: Add ROOTNS_WAIT ioctl
Quoted 8 lines
b2cc82539b75 rootns: Add rootns() system call
d29215aa7f0f rootns: Track init lifecycle via copy_process() and pid_namespace
0f9ce7febb49 rootns: Add core infrastructure for root namespaces
7a0e8f969fc7 mount: Enforce mount_too_revealing() for foreign mntns
8c61aee3afbf mount: Add mnt_ns_get_root()
07d239d0287c userns: Factor out install_user_ns_cred()
bf74588e706d nsfs: Add nsproxy_open_namespace()
645d31a1c516 nsproxy: Pass nsproxy to create_new_namespaces()

A "small" fact correction: rootns itself is not actually a namespace. It was at some point during the course of doing something over alonger time span :-)

I'll adjust the language and documentation.

It's like SGX enclave i.e., an isolated and opaque object with *nothing* at Epoch. Similarly as enclaves there's a build phase for building the memory environment, and a live phase that follows.

Those are the glasses that I've looked at the topic all the time; not so much with namespace glasses, as it's not my main beef and actually doing this has very little to do with namespaces and so much more on how you manage and control the threads and memory.

This is more like cross-cutting feature with no obvious subsystem ownership more than anything else.

Br, Jarkko

#27 lore raw
Quoted 36 lines · Jarkko Sakkinen
Quoted 16 lines · Jarkko Sakkinen

I've now re-sliced these into a bit more sane pieces:

$ git log --oneline master..
d8e24a6bc14e (HEAD -> rootns, origin/rootns) MAINTAINERS: Add entry for ROOT NAMESPACE
f2569e56a267 selftests/rootns: Add root namespace test suite
bea05e758f8e docs: Document root namespace uAPI
dd05a49aff77 arch: Wire up rootns() system call
2dee7a5fddec bpf: Register rootns LSM hooks
73c51e02b830 security: Add rootns LSM hooks
3cfd6576a037 mount: Support MOVE_MOUNT_T_MNTNS in move_mount()
9ed7387038ea ipc/mqueue: Implement ->set_rootns() fs_context operation
624f0ed9c1c7 proc: Implement ->set_rootns() fs_context operation
1085e6ae2eb3 fs: Support FSCONFIG_SET_ROOTNS in fsconfig()
d2898dbdc39b fork: Support CLONE_INTO_ROOTNS in clone3()
42dbccb5890e rootns: Add ROOTNS_KILL ioctl
14cbda3e5bca rootns: Add ROOTNS_WAIT ioctl
Quoted 8 lines
b2cc82539b75 rootns: Add rootns() system call
d29215aa7f0f rootns: Track init lifecycle via copy_process() and pid_namespace
0f9ce7febb49 rootns: Add core infrastructure for root namespaces
7a0e8f969fc7 mount: Enforce mount_too_revealing() for foreign mntns
8c61aee3afbf mount: Add mnt_ns_get_root()
07d239d0287c userns: Factor out install_user_ns_cred()
bf74588e706d nsfs: Add nsproxy_open_namespace()
645d31a1c516 nsproxy: Pass nsproxy to create_new_namespaces()

A "small" fact correction: rootns itself is not actually a namespace. It was at some point during the course of doing something over alonger time span :-)

I'll adjust the language and documentation.

It's like SGX enclave i.e., an isolated and opaque object with *nothing* at Epoch. Similarly as enclaves there's a build phase for building the memory environment, and a live phase that follows.

Quoted 7 lines

Those are the glasses that I've looked at the topic all the time; not so much with namespace glasses, as it's not my main beef and actually doing this has very little to do with namespaces and so much more on how you manage and control the threads and memory.

This is more like cross-cutting feature with no obvious subsystem ownership more than anything else.

I'll also move config ROOTNS out of being inside config NAMESPACES. That is a relic from the past (just noticed).

Br, Jarkko

#28 lore raw
In reply to Jarkko Sakkinen
Sashiko has finished reviewing this 14-patch series:

Sashiko has finished reviewing this 14-patch series:

- Patches 1-4, 6, and 10-12: no issues found.
- Patch 5 ("rootns: Add ROOTNS_WAIT ioctl"): 1 potential issue (1 Medium)
- Patch 7 ("fork: Support CLONE_INTO_ROOTNS in clone3()"): 2 potential issues (1 Medium, 1 Low)
- Patch 8 ("fs: Support FSCONFIG_SET_ROOTNS in fsconfig()"): 3 potential issues (2 High, 1 Medium)
- Patch 9 ("fs: Support MOVE_MOUNT_T_MNTNS in move_mount()"): 1 potential issue (1 High)
- Patch 13 ("selftests/rootns: Add root namespace test suite"): 3 potential issues (1 Medium, 2 Low)
- Patch 14: skipped (not reviewed).

Detailed reviews have been sent as separate replies to patches 5, 7-9, and 13.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]