Skip to contentSkip to conversation

Namespace for namespace roots

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

Subsystems (31)

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v3 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_create() 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_VM | CLONE_VFORK and opening the target binary via openat2(..., RESOLVE_IN_ROOT) on the retained "/" mount fd allows spawning with execveat() without copying page tables.

The first entrant becomes PID 1; once it exits and zap_pid_ns_processes() reaps all members, poll() reports EPOLLHUP and rootns_wait() returns init's exit status and rusage. rootns_kill() walks pid_ns->idr under tasklist_lock to signal member thread groups.

CHANGES
=======

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
========

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

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

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

 Documentation/userspace-api/index.rst         |    1 +
 .../userspace-api/ioctl/ioctl-number.rst      |    1 +
 Documentation/userspace-api/rootns.rst        |   47 +
 MAINTAINERS                                   |   11 +
 arch/alpha/kernel/syscalls/syscall.tbl        |    3 +
 arch/arm/tools/syscall.tbl                    |    3 +
 arch/arm64/tools/syscall_32.tbl               |    3 +
 arch/m68k/kernel/syscalls/syscall.tbl         |    3 +
 arch/microblaze/kernel/syscalls/syscall.tbl   |    3 +
 arch/mips/kernel/syscalls/syscall_n32.tbl     |    3 +
 arch/mips/kernel/syscalls/syscall_n64.tbl     |    3 +
 arch/mips/kernel/syscalls/syscall_o32.tbl     |    3 +
 arch/parisc/kernel/syscalls/syscall.tbl       |    3 +
 arch/powerpc/kernel/syscalls/syscall.tbl      |    3 +
 arch/s390/kernel/syscalls/syscall.tbl         |    3 +
 arch/sh/kernel/syscalls/syscall.tbl           |    3 +
 arch/sparc/kernel/syscalls/syscall.tbl        |    3 +
 arch/x86/entry/syscalls/syscall_32.tbl        |    3 +
 arch/x86/entry/syscalls/syscall_64.tbl        |    3 +
 arch/xtensa/kernel/syscalls/syscall.tbl       |    3 +
 fs/filesystems.c                              |   15 +
 fs/fs_context.c                               |   20 +-
 fs/fsopen.c                                   |  121 +-
 fs/internal.h                                 |    6 +
 fs/namespace.c                                |  245 ++-
 fs/nsfs.c                                     |   64 +
 fs/proc/root.c                                |   18 +
 include/linux/compat.h                        |    4 +
 include/linux/cred.h                          |    4 +-
 include/linux/fs_context.h                    |    5 +
 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                        |   91 +
 include/linux/sched/task.h                    |    8 +
 include/linux/syscalls.h                      |    4 +
 include/linux/time_namespace.h                |   21 +
 include/linux/user_namespace.h                |    7 +
 include/uapi/asm-generic/unistd.h             |   10 +-
 include/uapi/linux/mount.h                    |    4 +-
 include/uapi/linux/rootns.h                   |   44 +
 include/uapi/linux/sched.h                    |    5 +
 init/Kconfig                                  |    9 +
 ipc/mqueue.c                                  |   13 +
 kernel/Makefile                               |    2 +
 kernel/cred.c                                 |   31 +-
 kernel/fork.c                                 |   97 +-
 kernel/nsproxy.c                              |   44 +-
 kernel/pid_namespace.c                        |    2 +
 kernel/rootns.c                               |  609 ++++++
 kernel/sys_ni.c                               |    6 +
 kernel/time/namespace_vdso.c                  |    8 +
 kernel/user_namespace.c                       |   12 +-
 scripts/syscall.tbl                           |    3 +
 tools/testing/selftests/Makefile              |    1 +
 tools/testing/selftests/rootns/.gitignore     |    2 +
 tools/testing/selftests/rootns/Makefile       |    5 +
 tools/testing/selftests/rootns/config         |   10 +
 tools/testing/selftests/rootns/smoke.c        | 1934 +++++++++++++++++
 60 files changed, 3529 insertions(+), 80 deletions(-)
 create mode 100644 Documentation/userspace-api/rootns.rst
 create mode 100644 include/linux/rootns.h
 create mode 100644 include/uapi/linux/rootns.h
 create mode 100644 kernel/rootns.c
 create mode 100644 tools/testing/selftests/rootns/.gitignore
 create mode 100644 tools/testing/selftests/rootns/Makefile
 create mode 100644 tools/testing/selftests/rootns/config
 create mode 100644 tools/testing/selftests/rootns/smoke.c

--
2.47.3

#1 lore raw

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

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

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

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

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

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

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

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

Sashiko has reviewed this patch and found no issues.

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

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

In reply to Jarkko Sakkinen

Linux namespaces can be created and entered individually, but userspace orchestrators lack a single kernel object that binds a 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      |  62 ++++++++++++++
 include/uapi/linux/rootns.h |  44 ++++++++++
 init/Kconfig                |   9 ++
 kernel/Makefile             |   2 +
 kernel/rootns.c             | 160 ++++++++++++++++++++++++++++++++++++
 7 files changed, 343 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 +62 -0

62 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..3b857b105d2c 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_create(), rootns_wait(),
+	  rootns_kill(), 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 +160 -0

160 lines not on this page · raw message

Signature · 1 line
2.47.3
#4 lore raw

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

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

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.

Quoted 3 lines

Sashiko has reviewed this patch and found no issues.

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

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

In reply to Jarkko Sakkinen

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

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               | 41 +++++++++++++++++++++++++++++++++++
 5 files changed, 65 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 a1b2c3f8958b..2c34d6cd211a 100644
@@ -14,6 +14,8 @@
 struct file;
 struct nsproxy;
 struct pid;
+struct pid_namespace;
+struct task_struct;
 struct user_namespace;
 
 enum rootns_state {
@@ -43,6 +45,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)
 {
@@ -57,6 +62,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 +41 -0

44 lines not on this page · raw message

Signature · 1 line
2.47.3
#6 lore raw

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

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

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

Quoted 8 lines

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.

Sashiko has reviewed this patch and found no issues.

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

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

In reply to Jarkko Sakkinen

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

Add the rootns_create() system call to allocate a detached rootns instance 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..272d54bddbe2 100644
@@ -1006,6 +1006,7 @@ asmlinkage long sys_lsm_get_self_attr(unsigned int attr, struct lsm_ctx __user *
 asmlinkage long sys_lsm_set_self_attr(unsigned int attr, struct lsm_ctx __user *ctx,
 				      u32 size, u32 flags);
 asmlinkage long sys_lsm_list_modules(u64 __user *ids, u32 __user *size, u32 flags);
+asmlinkage long sys_rootns_create(unsigned int flags);
 
 /*
  * Architecture-specific system calls
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..4a6c4337cc74 100644
@@ -398,3 +398,6 @@ COND_SYSCALL(rseq_slice_yield);
 
 COND_SYSCALL(uretprobe);
 COND_SYSCALL(uprobe);
+
+/* kernel/rootns.c */
+COND_SYSCALL(rootns_create);
Signature · 1 line
2.47.3
#8 lore raw

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

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

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

Add the rootns_create() system call to allocate a detached rootns instance 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.

Quoted 3 lines

Sashiko has reviewed this patch and found no issues.

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

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

In reply to Jarkko Sakkinen

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

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

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

106 lines not on this page · raw message

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

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

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] rootns: unreachable init_pid check and missing -ECHILD in rootns_wait_common() - [Medium] rootns…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] rootns: unreachable init_pid check and missing -ECHILD in rootns_wait_common()
- [Medium] rootns: non-freezable TASK_KILLABLE sleep in rootns_wait_common()
--

commit 8a805a3f4fb79d05bf397b0ae4fb7738f0017723
Author: Jarkko Sakkinen <[email protected]>

rootns: Add rootns_wait() system call

This commit adds the rootns_wait() system call and its compat entry point to wait for a root namespace init process to terminate and collect its exit status and resource usage.

Quoted 22 lines
kernel/rootns.c +14 -0
index c420e36af603f..5582ff010ca53 100644
@@ -305,3 +305,106 @@ SYSCALL_DEFINE1(rootns_create, unsigned int, flags)
 
 	return fd;
 }
+
+/*
+ * Wait for rootns init to exit and report results for the caller.
+ *
+ * Returns caller-visible init TGID on success, 0 for WNOHANG when still
+ * running, and -ECHILD when init pid is not visible in caller pidns.
+ */
+static long rootns_wait_common(int rootnsfd, unsigned int options,
+			       int *status, struct rusage *ru)
+{
+	CLASS(fd, f)(rootnsfd);
+	struct pid_namespace *pid_ns = task_active_pid_ns(current);
+	struct rootns *rootns;
+	long ret;

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

Quoted 10 lines
kernel/rootns.c +10 -0
+
+	if (fd_empty(f))
+		return -EBADF;
+	if (!is_rootns_file(fd_file(f)) || (options & ~WNOHANG))
+		return -EINVAL;
+
+	rootns = fd_file(f)->private_data;
+	if (!(options & WNOHANG)) {
+		ret = wait_event_killable(rootns->waitq,
+					  READ_ONCE(rootns->state) == ROOTNS_DEAD);

[Severity: Medium]
Should rootns_wait_common() use a freezable and interruptible wait such as wait_event_freezable() instead of wait_event_killable()?

Sleeping in TASK_KILLABLE for the lifetime of a running root namespace prevents the PM and cgroup v2 freezers from freezing the waiting task (which causes system suspend or hibernation to time out and fail), blocks non-fatal signals and job control, and counts every blocked waiter toward the system load average.

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

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

[Severity: Medium]
Can the !rootns->init_pid check here ever be reached, and what happens when rootns_wait() is called before an init process has been started?

The kernel-doc for sys_rootns_wait() states that -ECHILD is returned if init was never started. However, rootns->state only reaches ROOTNS_DEAD in exit_rootns() after copy_rootns() has already populated rootns->init_pid. When init has not been started (rootns->state == ROOTNS_INIT), a call with WNOHANG hits the rootns->state != ROOTNS_DEAD check first and returns 0, while a call without WNOHANG sleeps in wait_event_killable() instead of returning -ECHILD.

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

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

In reply to Jarkko Sakkinen

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

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

74 lines not on this page · raw message

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

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

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

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

Add the rootns_kill() system call 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.

Sashiko has reviewed this patch and found no issues.

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

RFC PATCH v3 7/13 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 in the target user namespace and an ancestor active PID namespace, update dumpability across user namespace transitions, commit time namespace vvar mappings, and look up the live mount namespace root. Restrict companion flags to CLONE_VFORK, CLONE_VM (with 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/time_namespace.h |   8 +++
 include/linux/user_namespace.h |   7 ++
 include/uapi/linux/sched.h     |   5 ++
 kernel/cred.c                  |  31 +++++++-
 kernel/fork.c                  |  96 ++++++++++++++++++++++---
 kernel/nsproxy.c               |  14 +++-
 kernel/rootns.c                | 128 +++++++++++++++++++++++++++++++++
 kernel/time/namespace_vdso.c   |   8 +++
 kernel/user_namespace.c        |  12 ++--
 15 files changed, 339 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 2c34d6cd211a..265d90c24e3a 100644
@@ -12,6 +12,7 @@
 #include <linux/wait.h>
 
 struct file;
+struct kernel_clone_args;
 struct nsproxy;
 struct pid;
 struct pid_namespace;
@@ -48,6 +49,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)
 {
@@ -72,6 +75,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/time_namespace.h +8 -0
index bdc185543893..2e975a00cfc3 100644
@@ -173,12 +173,20 @@ static inline ktime_t timens_ktime_to_host(clockid_t clockid, ktime_t tim)
 
 #ifdef CONFIG_TIME_NS_VDSO
 extern void timens_commit(struct task_struct *tsk, struct time_namespace *ns);
+void timens_commit_fork(struct task_struct *tsk, struct time_namespace *ns,
+			bool shared_vm);
 struct page *find_timens_vvar_page(struct vm_area_struct *vma);
 #else /* !CONFIG_TIME_NS_VDSO */
 static inline void timens_commit(struct task_struct *tsk, struct time_namespace *ns)
 {
 }
 
+static inline void timens_commit_fork(struct task_struct *tsk,
+				      struct time_namespace *ns,
+				      bool shared_vm)
+{
+}
+
 static inline struct page *find_timens_vvar_page(struct vm_area_struct *vma)
 {
 	return NULL;
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 +30 -1
index d01df40a9a38..5bc3d455141b 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,28 @@ 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)) {
+			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) ||
+		    ((clone_flags & CLONE_VM) && 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 +87 -9

205 lines not on this page · raw message

kernel/nsproxy.c +12 -2
index 8a3c6d4e94e2..ec8b6fac7fbf 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,21 @@ 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) {
+		if (old_ns->time_ns != rootns->ns->time_ns)
+			timens_commit_fork(tsk, rootns->ns->time_ns,
+					   flags & CLONE_VM);
+		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 +202,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 +128 -0

131 lines not on this page · raw message

kernel/time/namespace_vdso.c +8 -0
index 5ac7b6a6d3a8..3ab12d1ee342 100644
@@ -142,6 +142,14 @@ void timens_commit(struct task_struct *tsk, struct time_namespace *ns)
 	vdso_join_timens(tsk, ns);
 }
 
+void timens_commit_fork(struct task_struct *tsk, struct time_namespace *ns,
+			bool shared_vm)
+{
+	timens_set_vvar_page(tsk, ns);
+	if (!shared_vm)
+		vdso_join_timens(tsk, ns);
+}
+
 int timens_vdso_alloc_vvar_page(struct time_namespace *ns)
 {
 	ns->vvar_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
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
#14 lore raw

Re: [RFC PATCH v3 07/13] fork: Support CLONE_INTO_ROOTNS in clone3()

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [High] cred: missing dumpability reset across userns without CLONE_VM in copy_creds() - [Medium] fork…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] cred: missing dumpability reset across userns without CLONE_VM in copy_creds()
- [Medium] fork: missing CAP_SYS_CHROOT check and umask reset to init_fs in copy_fs()
- [Medium] nsproxy: shared mm and timens vvar mismatch in copy_namespaces()
- [Low] rootns: wrong errno on external PID 1 race during bootstrap in copy_process()
--

commit 9762bc2570e709528c82312b63771aa4f8d6c6d8
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 4 lines
kernel/cred.c +0 -0
index d01df40a9a386..5bc3d455141b5 100644

[ ... ]

Quoted 15 lines
kernel/cred.c +11 -0
@@ -287,6 +294,28 @@ 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)) {
+			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;

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

Quoted 10 lines
kernel/cred.c +10 -0
+		}
+		if (!cred_cap_issubset(old, new) ||
+		    ((clone_flags & CLONE_VM) && 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);
+		}
+	}

[Severity: High]
Should exec_state->dumpable be reset whenever old->user_ns != new->user_ns, even when CLONE_VM is not set?

When a dumpable daemon (TASK_DUMPABLE_OWNER) creates a rootns and spawns a child into it without CLONE_VM, old->euid owns rootns->user_ns, so cred_cap_issubset(old, new) returns true:

kernel/cred.c:cred_cap_issubset() {
    ...
	for (;subset_ns != &init_user_ns; subset_ns = subset_ns->parent) {
		if ((set_ns == subset_ns->parent)  &&
		    uid_eq(subset_ns->owner, set->euid))
			return true;
	}
    ...
}

Because CLONE_VM is clear, p->exec_state->dumpable remains TASK_DUMPABLE_OWNER while p->real_cred->user_ns is switched to rootns->user_ns. In __ptrace_may_access(), a process in rootns->user_ns with CAP_SYS_PTRACE passes ptrace_has_cap(tcred->user_ns, mode), and task_still_dumpable() returns true on TASK_DUMPABLE_OWNER without checking ptrace_has_cap(exec_state->user_ns, mode). Until the child changes UID or calls execve(), an unprivileged container root process can attach via ptrace or read /proc/<pid>/mem and /proc/<pid>/fd/* while the child still holds the parent daemon's forked memory, O_CLOEXEC descriptors, and host UID.

Quoted 4 lines
kernel/fork.c +0 -0
index 08fc28ad1eedf..f5b98eea9ce92 100644

[ ... ]

Quoted 19 lines
kernel/fork.c +7 -1
@@ -1649,7 +1672,7 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk,
 		if (current->nsproxy->mnt_ns != &init_mnt_ns)
 			return -EINVAL;
 		fs = userspace_init_fs;
-	} else if (flags & COPY_FS_IDLE) {
+	} else if (flags & COPY_FS_IDLE || rootns) {
 		fs = &init_fs;
 	} else {
 		fs = current->fs;
@@ -1671,6 +1694,20 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk,
 	tsk->real_fs = tsk->fs = copy_fs_struct(fs);
 	if (!tsk->fs)
 		return -ENOMEM;
+	if (rootns) {
+		struct path root __free(path_put) = {};
+		int err;
+
+		err = mnt_ns_get_root(rootns->ns->mnt_ns, &root);
+		if (err) {

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

Quoted 10 lines
kernel/fork.c +8 -0
+			free_fs_struct(tsk->fs);
+			tsk->real_fs = NULL;
+			tsk->fs = NULL;
+			return err;
+		}
+		set_fs_root(tsk->fs, &root);
+		set_fs_pwd(tsk->fs, &root);
+	}
 	return 0;
 }

[Severity: Medium]
Does copying init_fs when rootns is set discard current->fs->umask, and should changing tsk->fs->root require CAP_SYS_CHROOT in rootns->user_ns?

Selecting init_fs causes copy_fs_struct() to initialize tsk->fs->umask from init_fs.umask (0022) instead of inheriting the parent's umask. In addition, unlike mntns_install() on setns(CLONE_NEWNS), neither rootns_prepare_fork() nor copy_creds() checks ns_capable(rootns->user_ns, CAP_SYS_CHROOT). A chrooted process already running in rootns->user_ns that has dropped CAP_SYS_CHROOT while retaining CAP_SYS_ADMIN can call clone3(CLONE_INTO_ROOTNS) to spawn a child with fs->root reset to the mount namespace root and escape its chroot.

[ ... ]

Quoted 27 lines
kernel/fork.c +6 -0
@@ -2510,6 +2548,12 @@ __latent_entropy struct task_struct *copy_process(
 		goto bad_fork_core_free;
 	}
 
+	if (unlikely(clone_args_rootns_bootstrapping(args) &&
+		     !is_child_reaper(pid))) {
+		retval = -EBUSY;
+		goto bad_fork_core_free;
+	}
+
 	/* Let kill terminate clone/fork in the middle */
 	if (fatal_signal_pending(current)) {
 		retval = -EINTR;
kernel/nsproxy.c +2 -1
index 8a3c6d4e94e2a..ec8b6fac7fbf1 100644
@@ -166,12 +167,21 @@ 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);

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

Quoted 10 lines
kernel/nsproxy.c +8 -0
 	struct nsproxy *new_ns;
 
+	if (rootns) {
+		if (old_ns->time_ns != rootns->ns->time_ns)
+			timens_commit_fork(tsk, rootns->ns->time_ns,
+					   flags & CLONE_VM);
+		get_nsproxy(rootns->ns);
+		tsk->nsproxy = rootns->ns;
+		return 0;
+	}

[Severity: Medium]
Can switching tsk->nsproxy->time_ns under CLONE_VM | CLONE_VFORK install the child time namespace's vvar page into the parent's shared mm_struct?

When clone3() is called with CLONE_INTO_ROOTNS | CLONE_VM | CLONE_VFORK and rootns has a different time namespace, timens_commit_fork() skips vdso_join_timens() because shared_vm is true, while tsk->nsproxy is switched immediately to rootns->ns (where time_ns == time_ns_for_children). The parent and the vfork child now share current->mm while having different nsproxy->time_ns pointers.

If VDSO_TIME_PAGE_OFFSET in the shared mm's [vvar] VMA has not been faulted in yet and the child calls a VDSO time function before execve(), vvar_fault() calls find_timens_vvar_page(), which sees vma->vm_mm == current->mm and maps rootns->ns->time_ns->vvar_page into the shared page tables. Because time_ns already equals time_ns_for_children in rootns->ns, exec_task_namespaces() on the child's later execve() is a no-op, leaving the parent's mm permanently mapped to the child time namespace's vvar page. Conversely, if the parent already faulted [vvar] before clone3(), the child observes the parent's time namespace through VDSO and rootns->ns->time_ns through syscalls until execve().

Also, calling timens_set_vvar_page() in copy_namespaces() before fallible steps in copy_process() (such as alloc_pid() and cgroup_can_fork()) permanently sets rootns->ns->time_ns->frozen_offsets = true even when the fork fails.

Quoted 4 lines
kernel/rootns.c +0 -0
index 32bb8ef5ed584..cfc33c243dba4 100644

[ ... ]

Quoted 16 lines
kernel/rootns.c +16 -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))
+		return 0;
+
+	ret = PTR_ERR(p);
+	if (args->rootns_bootstrapping) {
+		scoped_guard(spinlock, &rootns->lock) {
+			if (rootns->state == ROOTNS_FORKING)

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

Quoted 10 lines
kernel/rootns.c +10 -0
+				WRITE_ONCE(rootns->state, ROOTNS_INIT);
+		}
+		wake_up_all(&rootns->waitq);
+	} else if (ret == -ENOMEM &&
+		   !(READ_ONCE(pid_ns->pid_allocated) & PIDNS_ADDING)) {
+		return -ESRCH;
+	}
+
+	return ret;
+}

[Severity: Low]
Can a bootstrap race with an external fork into pid_ns return -EINVAL or -ENOMEM instead of the documented -EBUSY or -ESRCH?

If an external process enters pid_ns and allocates PID 1 in alloc_pid() after rootns_prepare_fork() checks READ_ONCE(pid_ns->child_reaper) but before setting child_reaper under tasklist_lock, the bootstrapping task's alloc_pid() allocates nr == 2 while child_reaper is still NULL and fails with -EINVAL, never reaching the !is_child_reaper(pid) check in copy_process(). Similarly, if that external PID 1 exits and clears PIDNS_ADDING before the bootstrapping task finishes copy_process(), copy_process() returns -ENOMEM, and rootns_finish_fork() only translates -ENOMEM to -ESRCH in the !args->rootns_bootstrapping branch.

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

RFC PATCH v3 8/13 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, allocate fsmount()'s anonymous mount namespace in fc->user_ns, enforce mount_too_revealing() for unprivileged callers in init_mnt_ns, and wire ->set_rootns() for proc and mqueue.

---
 fs/filesystems.c           |  15 +++++
 fs/fs_context.c            |  20 ++++--
 fs/fsopen.c                | 121 ++++++++++++++++++++++++++++++++++---
 fs/internal.h              |   6 ++
 fs/namespace.c             |  35 +++++++++--
 fs/proc/root.c             |  18 ++++++
 include/linux/fs_context.h |   5 ++
 include/uapi/linux/mount.h |   1 +
 ipc/mqueue.c               |  13 ++++
 9 files changed, 216 insertions(+), 18 deletions(-)
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 +16 -4
index a50584df97be..542dede2f864 100644
@@ -259,7 +259,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 +293,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 +311,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 +330,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 +348,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 +113 -8

194 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 +29 -6
index 781380945d78..a6c0a31e275a 100644
@@ -4623,7 +4623,8 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 	    !ns_capable(current_user_ns(), CAP_SYS_ADMIN))
 		return -EPERM;
 
-	if (!(flags & FSMOUNT_NAMESPACE) && !may_mount())
+	if (!(flags & FSMOUNT_NAMESPACE) && !IS_ENABLED(CONFIG_ROOTNS) &&
+	    !may_mount())
 		return -EPERM;
 
 	if (attr_flags & ~FSMOUNT_VALID_FLAGS)
@@ -4658,6 +4659,16 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 	if (ret)
 		return ret;
 
+	if (!(flags & FSMOUNT_NAMESPACE)) {
+		if (fc->rootns_bound) {
+			if (!ns_capable(fc->user_ns, CAP_SYS_ADMIN) &&
+			    !may_mount())
+				return -EPERM;
+		} else if (!may_mount()) {
+			return -EPERM;
+		}
+	}
+
 	/* There must be a valid superblock or we can't mount it */
 	ret = -EINVAL;
 	if (!fc->root)
@@ -4699,7 +4710,8 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 		return FD_ADD((flags & FSMOUNT_CLOEXEC) ? O_CLOEXEC : 0,
 			      open_new_namespace(&new_path, MOUNT_COPY_NEW));
 
-	ns = alloc_mnt_ns(current->nsproxy->mnt_ns->user_ns, true);
+	ns = alloc_mnt_ns(fc->rootns_bound ? fc->user_ns :
+			  current->nsproxy->mnt_ns->user_ns, true);
 	if (IS_ERR(ns))
 		return PTR_ERR(ns);
 	mnt = real_mount(new_path.mnt);
@@ -6582,6 +6594,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 +6624,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 +6647,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 +6668,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 +5 -0
index d1727dffecc5..b1adcd6ed693 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() */
@@ -110,6 +113,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 +121,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 v3 08/13] fs: Support FSCONFIG_SET_ROOTNS in fsconfig()

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider: - [High] fs: unprivileged devpts mount via fsconfig_set_rootns() bypasses pty_reserve - [High] fs…

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider:
- [High] fs: unprivileged devpts mount via fsconfig_set_rootns() bypasses pty_reserve
- [High] fs: alloc_mnt_ns(fc->user_ns) in fsmount() breaks submount MNT_LOCKED
- [Medium] fs: missing FS_CONTEXT_FAILED transition on set_rootns() error
- [Medium] fs: fsconfig_set_rootns() loses cpuset context state on re-init
- [Medium] fs: may_mount() in fsmount() bypasses fc->user_ns capability check
- [Low] fs: missing @init kernel-doc entry in alloc_fs_context() --

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

fs: Support FSCONFIG_SET_ROOTNS in fsconfig()

This commit adds FSCONFIG_SET_ROOTNS to bind a newly opened fs_context to a target rootns before supplying parameters, allowing unprivileged callers to open FS_USERNS_MOUNT contexts and configure mounts for a rootns where they hold CAP_SYS_ADMIN.

fs/fs_context.c static struct fs_context *alloc_fs_context(struct file_system_type *fs_type, · line 264

Quoted 12 lines
fs/fs_context.c +2 -1
index a50584df97bea..542dede2f8643 100644
@@ -259,7 +259,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)
 {

[Severity: Low]
The kernel-doc comment above alloc_fs_context() is missing an @init entry for the new parameter.

[ ... ]

Quoted 52 lines
fs/fsopen.c +44 -0
index 70024870fefa2..3e36270baadb3 100644
@@ -41,6 +46,76 @@ static inline const char *fetch_message_locked(struct fc_log *log, size_t len,
 	return p;
 }
 
+/**
+ * DOC: FSCONFIG_SET_ROOTNS
+ *
+ * ``fsconfig(fsfd, FSCONFIG_SET_ROOTNS, NULL, NULL, rootnsfd)`` binds a newly
+ * opened filesystem context to ``rootnsfd`` once before any parameters are
+ * supplied (subsequent calls fail with ``-EBUSY``).
+ *
+ * The caller must hold ``CAP_SYS_ADMIN`` in the target ``rootns`` user
+ * namespace, allowing unprivileged callers to configure ``FS_USERNS_MOUNT``
+ * filesystems without entering the user namespace first.
+ *
+ * The context is initialized against the ``rootns`` network namespace,
+ * ``fc->user_ns`` is delegated to the ``rootns`` user namespace for
+ * ``FS_USERNS_MOUNT`` and ``FS_USERNS_DELEGATABLE`` filesystems when the
+ * mounter ``fsuid``/``fsgid`` map into it or the caller lacks
+ * ``CAP_SYS_ADMIN`` in its own user namespace, and ``proc`` and ``mqueue``
+ * contexts bind to the target ``rootns`` PID and IPC namespaces.
+ */
+static int fsconfig_set_rootns(struct fs_context *fc, struct fs_parameter *param)
+{
+	struct user_namespace *user_ns;
+	struct rootns *c;
+	int ret;
+
+	if (!is_rootns_file(param->file))
+		return -EINVAL;
+
+	c = param->file->private_data;
+	user_ns = c->user_ns;
+	if (!ns_capable(user_ns, CAP_SYS_ADMIN))
+		return -EPERM;
+
+	if (fc->need_free && fc->ops && fc->ops->free)
+		fc->ops->free(fc);
+	fc->need_free = false;
+	fc->fs_private = NULL;
+	fc->s_fs_info = NULL;
+	fc->ops = NULL;
+	fc->sb_flags = 0;
+	fc->global = false;
+	security_free_mnt_opts(&fc->security);
+
+	put_net(fc->net_ns);
+	fc->net_ns = get_net(c->ns->net_ns);

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

Quoted 10 lines
fs/fsopen.c +10 -0
+	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) &&
+	      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);
+
+	ret = fc->fs_type->init_fs_context(fc);

[Severity: Medium]
Does re-calling fc->fs_type->init_fs_context(fc) here lose the cpuset configuration when fsopen("cpuset", 0) was opened by a caller with may_mount() == true?

During the initial fs_context_for_mount() in fsopen(), cpuset_init_fs_context() configures cpuset_fs_context_ops, ctx->subsys_mask, and CGRP_ROOT_NOPREFIX, and then replaces fc->fs_type with &cgroup_fs_type:

kernel/cgroup/cgroup.c:cpuset_init_fs_context() {
    ...
	get_filesystem(&cgroup_fs_type);
	put_filesystem(fc->fs_type);
	fc->fs_type = &cgroup_fs_type;
    ...
}

When fsconfig_set_rootns() frees the initial context and calls fc->fs_type->init_fs_context(fc) again, it invokes cgroup_init_fs_context() instead of cpuset_init_fs_context(), leaving ctx->subsys_mask as 0 and fc->ops as &cgroup1_fs_context_ops so cpuset parameter parsing or superblock creation fails.

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

Quoted 11 lines
fs/fsopen.c +11 -0
+	if (ret < 0) {
+		fc->phase = FS_CONTEXT_FAILED;
+		return ret;
+	}
+	fc->need_free = true;
+
+	if (fc->ops->set_rootns) {
+		ret = fc->ops->set_rootns(fc, c);
+		if (ret < 0)
+			return ret;
+	}

[Severity: Medium]
Should fc->phase be set to FS_CONTEXT_FAILED when fc->ops->set_rootns() fails?

By the time set_rootns() runs, the prior filesystem-private state has been freed, fc->net_ns and fc->user_ns have been overwritten, and init_fs_context() has re-run in the fsconfig() caller's task context. If proc_set_rootns() returns -EINVAL, leaving fc->phase in FS_CONTEXT_CREATE_NS (or FS_CONTEXT_AWAITING_NS) with fc->rootns_bound still false leaves a partially mutated context usable for subsequent parameter parsing, superblock creation, or repeated FSCONFIG_SET_ROOTNS calls.

[ ... ]

Quoted 9 lines
fs/fsopen.c +1 -2
@@ -137,17 +214,23 @@ SYSCALL_DEFINE2(fsopen, const char __user *, _fs_name, unsigned int, flags)
 
 	audit_log_fsopen(fs_name);
 
-	fs_type = get_fs_type(fs_name);
+	fs_type = priv ? get_fs_type(fs_name) : get_fs_type_noload(fs_name);
 	kfree(fs_name);
 	if (!fs_type)
-		return -ENODEV;

fs/fsopen.c SYSCALL_DEFINE2(fsopen, const char __user *, _fs_name, unsigned int, flags) · line 228

Quoted 10 lines
fs/fsopen.c +8 -1
+		return priv ? -ENODEV : -EPERM;
 
-	fc = fs_context_for_mount(fs_type, 0);
+	if (!priv && !(fs_type->fs_flags & FS_USERNS_MOUNT)) {
+		put_filesystem(fs_type);
+		return -EPERM;
+	}
+
+	fc = priv ? fs_context_for_mount(fs_type, 0) :
+		    fs_context_for_unpriv_mount(fs_type);

[Severity: High]
Does allowing an unprivileged caller in the initial mount namespace to open and configure a devpts context via FSCONFIG_SET_ROOTNS bypass pty_reserve?

devpts has FS_USERNS_MOUNT set, and devpts_init_fs_context() grants access to the reserved PTY pool solely based on whether current is in the initial mount namespace:

fs/devpts/inode.c:devpts_init_fs_context() {
    ...
	if (fc->purpose == FS_CONTEXT_FOR_MOUNT &&
	    current->nsproxy->mnt_ns == init_task.nsproxy->mnt_ns)
		fsi->mount_opts.reserve = true;
    ...
}

Previously, fsopen() required may_mount(), forcing unprivileged callers to unshare a mount namespace first. With this regression, an unprivileged user in init_task.nsproxy->mnt_ns can open devpts, bind it to a userns via FSCONFIG_SET_ROOTNS (which runs devpts_init_fs_context() while still in the initial mount namespace, setting fsi->mount_opts.reserve = true), and allocate PTYs from the host emergency reserve up to pty_limit.

[ ... ]

Quoted 7 lines
fs/namespace.c +0 -0
index 781380945d784..a6c0a31e275ae 100644
@@ -4658,6 +4659,16 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 	if (ret)
 		return ret;

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

Quoted 10 lines
fs/namespace.c +9 -0
 
+	if (!(flags & FSMOUNT_NAMESPACE)) {
+		if (fc->rootns_bound) {
+			if (!ns_capable(fc->user_ns, CAP_SYS_ADMIN) &&
+			    !may_mount())
+				return -EPERM;
+		} else if (!may_mount()) {
+			return -EPERM;
+		}
+	}

[Severity: Medium]
When fc->rootns_bound is true, can a caller lacking CAP_SYS_ADMIN in fc->user_ns bypass the fc->user_ns capability check by satisfying may_mount() in its own unprivileged mount namespace (or by passing FSMOUNT_NAMESPACE)?

Because alloc_mnt_ns() below unconditionally uses fc->user_ns whenever fc->rootns_bound is true, a task that passes this check via may_mount() in an unrelated user namespace still allocates the anonymous mount namespace in fc->user_ns and charges UCOUNT_MNT_NAMESPACES against fc->user_ns.

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

Quoted 11 lines
fs/namespace.c +3 -1
+
 	/* There must be a valid superblock or we can't mount it */
 	ret = -EINVAL;
 	if (!fc->root)
@@ -4699,7 +4710,8 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 		return FD_ADD((flags & FSMOUNT_CLOEXEC) ? O_CLOEXEC : 0,
 			      open_new_namespace(&new_path, MOUNT_COPY_NEW));
 
-	ns = alloc_mnt_ns(current->nsproxy->mnt_ns->user_ns, true);
+	ns = alloc_mnt_ns(fc->rootns_bound ? fc->user_ns :
+			  current->nsproxy->mnt_ns->user_ns, true);

[Severity: High]
Does allocating fsmount()'s anonymous mount namespace in fc->user_ns leave host submounts without MNT_LOCKED when an external manager in init_user_ns assembles a mount tree for an unprivileged rootns?

When a manager in init_user_ns creates a rootns-bound anonymous root mount (so dest_mnt->mnt_ns is anonymous with user_ns == fc->user_ns) and attaches a host submount from init_user_ns onto it via move_mount(), attach_recursive_mnt() compares child->mnt_parent->mnt_ns->user_ns (fc->user_ns) against current->nsproxy->mnt_ns->user_ns (&init_user_ns):

fs/namespace.c:attach_recursive_mnt() {
    ...
	if (is_anon_ns(ns))
		user_ns = current->nsproxy->mnt_ns->user_ns;
	else
		user_ns = ns->user_ns;
    ...
		/* Notice when we are propagating across user namespaces */
		if (child->mnt_parent->mnt_ns->user_ns != user_ns)
			lock_mnt_tree(child);
    ...
}

lock_mnt_tree(child) only sets MNT_LOCKED on descendants p != child, leaving child itself unlocked, and commit_tree(child) then moves child into the anonymous mount namespace owned by fc->user_ns. When the assembled anonymous tree is later moved into the target mount namespace (also owned by fc->user_ns), the user namespaces match, so attach_recursive_mnt() does not lock the tree and unprivileged users in the target namespace can unmount the host submount to expose the underlying directory. Conversely, attaching a submount that was also created with FSCONFIG_SET_ROOTNS for fc->user_ns onto the anonymous root mount sees child->mnt_parent->mnt_ns->user_ns != user_ns and spuriously runs lock_mnt_tree().

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

RFC PATCH v3 9/13 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 attach anonymous mounts beneath the live mount namespace root and reject root-mount aliases.

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             | 194 +++++++++++++++++++++++++++++++------
 include/uapi/linux/mount.h |   3 +-
 2 files changed, 168 insertions(+), 29 deletions(-)
fs/namespace.c +166 -28
index a6c0a31e275a..2bd973a490d3 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,6 +2571,8 @@ int count_mounts(struct mnt_namespace *ns, struct mount *mnt)
 enum mnt_tree_flags_t {
 	MNT_TREE_BENEATH = BIT(0),
 	MNT_TREE_PROPAGATION = BIT(1),
+	MNT_TREE_MNTNS = BIT(2),
+	MNT_TREE_MNTNS_INIT = BIT(3),
 };
 
 /**
@@ -2639,6 +2648,7 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 	HLIST_HEAD(tree_list);
 	struct mnt_namespace *ns = dest_mnt->mnt_ns;
 	struct user_namespace *user_ns = ns->user_ns;
+	struct user_namespace *source_user_ns;
 	struct pinned_mountpoint root = {};
 	struct mountpoint *shorter = NULL;
 	struct mount *child, *p;
@@ -2662,6 +2672,8 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 		user_ns = current->nsproxy->mnt_ns->user_ns;
 	else
 		user_ns = ns->user_ns;
+	source_user_ns = (!moving && source_mnt->mnt_ns) ?
+			 source_mnt->mnt_ns->user_ns : user_ns;
 
 	/*
 	 * Preallocate a mountpoint in case the new mounts need to be
@@ -2730,6 +2742,12 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 		/* Notice when we are propagating across user namespaces */
 		if (child->mnt_parent->mnt_ns->user_ns != user_ns)
 			lock_mnt_tree(child);
+		if (!is_anon_ns(child->mnt_parent->mnt_ns) &&
+		    child->mnt_parent->mnt_ns->user_ns != source_user_ns) {
+			lock_mnt_tree(child);
+			if (list_empty(&child->mnt_expire))
+				child->mnt.mnt_flags |= MNT_LOCKED;
+		}
 		q = __lookup_mnt(&child->mnt_parent->mnt,
 				 child->mnt_mountpoint);
 		commit_tree(child);
@@ -3131,7 +3149,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);
@@ -3779,6 +3797,7 @@ static int do_move_mount(const struct path *old_path,
 			 enum mnt_tree_flags_t flags)
 {
 	struct mount *old = real_mount(old_path->mnt);
+	struct mnt_namespace *target_mnt_ns;
 	int err;
 	bool beneath = flags & MNT_TREE_BENEATH;
 
@@ -3792,7 +3811,13 @@ static int do_move_mount(const struct path *old_path,
 	if (IS_ERR(mp.parent))
 		return PTR_ERR(mp.parent);
 
-	if (check_mnt(old)) {
+	if (flags & MNT_TREE_MNTNS) {
+		if (!anon_ns_root(old) || old->mnt_ns == mp.parent->mnt_ns)
+			return -EINVAL;
+		if ((flags & MNT_TREE_MNTNS_INIT) &&
+		    mp.parent != real_mount(new_path->mnt))
+			return -EBUSY;
+	} else if (check_mnt(old)) {
 		/* if the source is in our namespace... */
 		/* ... it should be detachable from parent */
 		if (!mnt_has_parent(old) || IS_MNT_LOCKED(old))
@@ -3840,7 +3865,9 @@ 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))
+	target_mnt_ns = is_anon_ns(mp.parent->mnt_ns) ?
+			current->nsproxy->mnt_ns : mp.parent->mnt_ns;
+	if (!check_for_nsfs_mounts(old, target_mnt_ns))
 		return -ELOOP;
 	if (mount_is_ancestor(old, mp.parent))
 		return -ELOOP;
@@ -4751,6 +4778,127 @@ static inline int vfs_move_mount(const struct path *from_path,
 	return do_move_mount(from_path, to_path, mflags);
 }
 
+static int lookup_move_mount_from(int from_dfd,
+				  const char __user *from_pathname,
+				  unsigned int flags, struct path *from_path)
+{
+	unsigned int uflags = 0;
+	unsigned int lflags = 0;
+
+	if (flags & MOVE_MOUNT_F_EMPTY_PATH)
+		uflags = AT_EMPTY_PATH;
+
+	CLASS(filename_maybe_null, from_name)(from_pathname, uflags);
+	if (!from_name && from_dfd >= 0) {
+		CLASS(fd_raw, f_from)(from_dfd);
+		if (fd_empty(f_from))
+			return -EBADF;
+
+		*from_path = fd_file(f_from)->f_path;
+		path_get(from_path);
+		return 0;
+	}
+
+	if (flags & MOVE_MOUNT_F_SYMLINKS)
+		lflags |= LOOKUP_FOLLOW;
+	if (flags & MOVE_MOUNT_F_AUTOMOUNTS)
+		lflags |= LOOKUP_AUTOMOUNT;
+	return filename_lookup(from_dfd, from_name, lflags, from_path, NULL);
+}
+
+/**
+ * DOC: MOVE_MOUNT_T_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 = 0;
+		if (flags & MOVE_MOUNT_T_SYMLINKS)
+			lflags |= LOOKUP_FOLLOW;
+		if (flags & MOVE_MOUNT_T_AUTOMOUNTS)
+			lflags |= LOOKUP_AUTOMOUNT;
+		ret = filename_lookup(AT_FDCWD, to_name, lflags, &to_path,
+				      &mntns_root);
+		if (ret)
+			return ret;
+		if (real_mount(to_path.mnt)->mnt_ns != target_mnt_ns ||
+		    to_path.mnt == &target_mnt_ns->root->mnt)
+			return -EINVAL;
+		if (real_mount(to_path.mnt)->mnt_parent == target_mnt_ns->root &&
+		    to_path.dentry == to_path.mnt->mnt_root)
+			return (flags & MOVE_MOUNT_BENEATH) ? -EINVAL : -EBUSY;
+	}
+
+	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);
+}
+
 /*
  * Move a mount from one place to another.  In combination with
  * fsopen()/fsmount() this is used to install a new mount and in combination
@@ -4770,7 +4918,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)
@@ -4783,6 +4931,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;
@@ -4806,25 +4961,8 @@ SYSCALL_DEFINE5(move_mount,
 			return ret;
 	}
 
-	uflags = 0;
-	if (flags & MOVE_MOUNT_F_EMPTY_PATH)
-		uflags = AT_EMPTY_PATH;
-
-	CLASS(filename_maybe_null,from_name)(from_pathname, uflags);
-	if (!from_name && from_dfd >= 0) {
-		CLASS(fd_raw, f_from)(from_dfd);
-		if (fd_empty(f_from))
-			return -EBADF;
-
-		return vfs_move_mount(&fd_file(f_from)->f_path, &to_path, mflags);
-	}
-
-	lflags = 0;
-	if (flags & MOVE_MOUNT_F_SYMLINKS)
-		lflags |= LOOKUP_FOLLOW;
-	if (flags & MOVE_MOUNT_F_AUTOMOUNTS)
-		lflags |= LOOKUP_AUTOMOUNT;
-	ret = filename_lookup(from_dfd, from_name, lflags, &from_path, NULL);
+	ret = lookup_move_mount_from(from_dfd, from_pathname, flags,
+				     &from_path);
 	if (ret)
 		return ret;
 
include/uapi/linux/mount.h +2 -1
index cb55cfcfc92e..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 v3 09/13] fs: Support MOVE_MOUNT_T_MNTNS in move_mount()

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] fs: broken cross-userns mount locking in attach_recursive_mnt() - [High] fs: relative root-mount…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] fs: broken cross-userns mount locking in attach_recursive_mnt()
- [High] fs: relative root-mount alias bypass and unlocked check in move_mount_mntns()
--

commit 444327893c38a5707689f91b2605debf89b46300
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() to allow attaching detached anonymous mount trees directly into a target mount namespace identified by an nsfs file descriptor.

Quoted 4 lines
fs/namespace.c +0 -0
index a6c0a31e275ae..2bd973a490d34 100644

[ ... ]

Quoted 20 lines
fs/namespace.c +3 -0
@@ -2639,6 +2648,7 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 	HLIST_HEAD(tree_list);
 	struct mnt_namespace *ns = dest_mnt->mnt_ns;
 	struct user_namespace *user_ns = ns->user_ns;
+	struct user_namespace *source_user_ns;
 	struct pinned_mountpoint root = {};
 	struct mountpoint *shorter = NULL;
 	struct mount *child, *p;
@@ -2662,6 +2672,8 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 		user_ns = current->nsproxy->mnt_ns->user_ns;
 	else
 		user_ns = ns->user_ns;
+	source_user_ns = (!moving && source_mnt->mnt_ns) ?
+			 source_mnt->mnt_ns->user_ns : user_ns;
 
 	/*
 	 * Preallocate a mountpoint in case the new mounts need to be
@@ -2730,6 +2742,12 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 		/* Notice when we are propagating across user namespaces */
 		if (child->mnt_parent->mnt_ns->user_ns != user_ns)

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

Quoted 10 lines
fs/namespace.c +6 -0
 			lock_mnt_tree(child);
+		if (!is_anon_ns(child->mnt_parent->mnt_ns) &&
+		    child->mnt_parent->mnt_ns->user_ns != source_user_ns) {
+			lock_mnt_tree(child);
+			if (list_empty(&child->mnt_expire))
+				child->mnt.mnt_flags |= MNT_LOCKED;
+		}
 		q = __lookup_mnt(&child->mnt_parent->mnt,
 				 child->mnt_mountpoint);
 		commit_tree(child);

[Severity: High]
Can cross-user-namespace mount locking be bypassed when a detached mount tree is staged onto an anonymous mount before being attached to a target mount namespace?

If an anonymous mount tree S owned by a privileged user namespace is attached via move_mount() onto a subdirectory of an anonymous mount R owned by a less-privileged user_ns_B (for example, created with FSCONFIG_SET_ROOTNS or by a task in user_ns_B), is_anon_ns(child->mnt_parent->mnt_ns) is true, so the new source_user_ns check is skipped. If the caller is in user_ns_B, user_ns is also user_ns_B, so lock_mnt_tree() is not called either. commit_tree(S) then moves every mount in S into R->mnt_ns (owned by user_ns_B), so when R is later attached into a mount namespace owned by user_ns_B, source_user_ns == user_ns_B and S is never locked, allowing tasks in user_ns_B to unmount masked directories or clear read-only/nosuid/nodev/ noexec flags.

Conversely, when a privileged manager in init_user_ns attaches a submount owned by user_ns_B onto an anonymous root mount R also owned by user_ns_B (via FSCONFIG_SET_ROOTNS), is_anon_ns(ns) sets user_ns to init_user_ns rather than ns->user_ns, so child->mnt_parent->mnt_ns->user_ns != user_ns spuriously locks the submount.

In addition, tree_list contains all secondary mounts created by propagate_mnt(), and for normal mounts or automounts source_user_ns equals user_ns. Every secondary copy propagated into a non-anonymous mount namespace in another user namespace therefore hits this block and gets MNT_LOCKED set on its root even when q == NULL (nothing was covered at the mountpoint), preventing unprivileged users or shrink_submounts() from unmounting uncovered propagated mounts. And because source_user_ns is computed unconditionally for all !moving mounts, regular move_mount() without MOVE_MOUNT_T_MNTNS also locks detached trees intentionally handed over across user namespaces via SCM_RIGHTS or inheritance, regressing 33aadc7c7205 ("namespace: handle mount locking for automounts correctly").

[ ... ]

Quoted 1 line
fs/namespace.c +0 -0
@@ -4751,6 +4778,127 @@ static inline int vfs_move_mount(const struct path *from_path,

[ ... ]

Quoted 4 lines
fs/namespace.c +4 -0
+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)
+{

[ ... ]

Quoted 14 lines
fs/namespace.c +14 -0
+		lflags = 0;
+		if (flags & MOVE_MOUNT_T_SYMLINKS)
+			lflags |= LOOKUP_FOLLOW;
+		if (flags & MOVE_MOUNT_T_AUTOMOUNTS)
+			lflags |= LOOKUP_AUTOMOUNT;
+		ret = filename_lookup(AT_FDCWD, to_name, lflags, &to_path,
+				      &mntns_root);
+		if (ret)
+			return ret;
+		if (real_mount(to_path.mnt)->mnt_ns != target_mnt_ns ||
+		    to_path.mnt == &target_mnt_ns->root->mnt)
+			return -EINVAL;
+		if (real_mount(to_path.mnt)->mnt_parent == target_mnt_ns->root &&
+		    to_path.dentry == to_path.mnt->mnt_root)

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

Quoted 10 lines
fs/namespace.c +10 -0
+			return (flags & MOVE_MOUNT_BENEATH) ? -EINVAL : -EBUSY;
+	}
+
+	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);
+}

[Severity: High]
Does the root-mount alias check in move_mount_mntns() miss any target mount namespace where more than one mount is stacked on target_mnt_ns->root?

mnt_ns_get_root() follows the entire overmount chain on target_mnt_ns->root (nullfs) to the topmost live root mount in mntns_root. Whenever two or more mounts are stacked on target_mnt_ns->root (for example nullfs -> rootfs -> real_root in a cloned namespace, or a root that has been overmounted), the live root mount's mnt_parent is the intermediate mount rather than target_mnt_ns->root. A relative path such as "." or "subdir/.." then resolves to mntns_root with mnt_parent != target_mnt_ns->root, bypassing this check and allowing the caller to overmount the namespace root or mount beneath it with MOVE_MOUNT_BENEATH.

Also, filename_lookup() does not enforce LOOKUP_IS_SCOPED (or recheck reachability from mntns_root under lock), so following a procfs magic link inside target_mnt_ns can escape to a mount outside or beneath mntns_root. Finally, these checks inspect to_path.mnt->mnt_ns and mnt_parent without holding namespace_sem or mount_lock, and do_move_mount() only revalidates MNT_TREE_MNTNS_INIT after locking the mountpoint; if a resolved submount is concurrently pivoted to the root of target_mnt_ns before do_lock_mount() acquires namespace_lock(), MOVE_MOUNT_BENEATH will attach the new mount directly onto target_mnt_ns->root beneath the namespace root.

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

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

In reply to Jarkko Sakkinen

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

---
 arch/alpha/kernel/syscalls/syscall.tbl      |  3 +++
 arch/arm/tools/syscall.tbl                  |  3 +++
 arch/arm64/tools/syscall_32.tbl             |  3 +++
 arch/m68k/kernel/syscalls/syscall.tbl       |  3 +++
 arch/microblaze/kernel/syscalls/syscall.tbl |  3 +++
 arch/mips/kernel/syscalls/syscall_n32.tbl   |  3 +++
 arch/mips/kernel/syscalls/syscall_n64.tbl   |  3 +++
 arch/mips/kernel/syscalls/syscall_o32.tbl   |  3 +++
 arch/parisc/kernel/syscalls/syscall.tbl     |  3 +++
 arch/powerpc/kernel/syscalls/syscall.tbl    |  3 +++
 arch/s390/kernel/syscalls/syscall.tbl       |  3 +++
 arch/sh/kernel/syscalls/syscall.tbl         |  3 +++
 arch/sparc/kernel/syscalls/syscall.tbl      |  3 +++
 arch/x86/entry/syscalls/syscall_32.tbl      |  3 +++
 arch/x86/entry/syscalls/syscall_64.tbl      |  3 +++
 arch/xtensa/kernel/syscalls/syscall.tbl     |  3 +++
 include/uapi/asm-generic/unistd.h           | 10 +++++++++-
 scripts/syscall.tbl                         |  3 +++
 18 files changed, 60 insertions(+), 1 deletion(-)
arch/alpha/kernel/syscalls/syscall.tbl +3 -0
index 52e3538cc7df..c7bec286deff 100644
@@ -512,3 +512,6 @@
 580	common	listns				sys_listns
 581	common	rseq_slice_yield		sys_rseq_slice_yield
 582	common	fchroot				sys_fchroot
+583	common	rootns_create			sys_rootns_create
+584	common	rootns_wait			sys_rootns_wait
+585	common	rootns_kill			sys_rootns_kill
arch/arm/tools/syscall.tbl +3 -0
index 55717ed32c27..59f78bf991c9 100644
@@ -487,3 +487,6 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
arch/arm64/tools/syscall_32.tbl +3 -0
index df2d1d82fb3c..8ef57696c6a8 100644
@@ -484,3 +484,6 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait		compat_sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
arch/m68k/kernel/syscalls/syscall.tbl +3 -0
index ba7a4d8903d0..36eb16ae659f 100644
@@ -472,3 +472,6 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
arch/microblaze/kernel/syscalls/syscall.tbl +3 -0
index 76d7cbe2a133..54739d61a9ee 100644
@@ -478,3 +478,6 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
arch/mips/kernel/syscalls/syscall_n32.tbl +3 -0
index 9ae88e4eac61..f0a58c6b4516 100644
@@ -411,3 +411,6 @@
 470	n32	listns				sys_listns
 471	n32	rseq_slice_yield		sys_rseq_slice_yield
 472	n32	fchroot				sys_fchroot
+473	n32	rootns_create			sys_rootns_create
+474	n32	rootns_wait			compat_sys_rootns_wait
+475	n32	rootns_kill			sys_rootns_kill
arch/mips/kernel/syscalls/syscall_n64.tbl +3 -0
index 83dc93a0712f..c1d2774c6283 100644
@@ -387,3 +387,6 @@
 470	n64	listns				sys_listns
 471	n64	rseq_slice_yield		sys_rseq_slice_yield
 472	n64	fchroot				sys_fchroot
+473	n64	rootns_create			sys_rootns_create
+474	n64	rootns_wait			sys_rootns_wait
+475	n64	rootns_kill			sys_rootns_kill
arch/mips/kernel/syscalls/syscall_o32.tbl +3 -0
index 9c62429c9b7b..99a753234dbf 100644
@@ -460,3 +460,6 @@
 470	o32	listns				sys_listns
 471	o32	rseq_slice_yield		sys_rseq_slice_yield
 472	o32	fchroot				sys_fchroot
+473	o32	rootns_create			sys_rootns_create
+474	o32	rootns_wait			sys_rootns_wait			compat_sys_rootns_wait
+475	o32	rootns_kill			sys_rootns_kill
arch/parisc/kernel/syscalls/syscall.tbl +3 -0
index 88adc4016cce..f3bac8085491 100644
@@ -471,3 +471,6 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait			compat_sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
arch/powerpc/kernel/syscalls/syscall.tbl +3 -0
index cfbb70039ff0..7ab1948f76b7 100644
@@ -563,3 +563,6 @@
 470	common	listns				sys_listns
 471	nospu	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	nospu	rootns_create			sys_rootns_create
+474	nospu	rootns_wait			sys_rootns_wait			compat_sys_rootns_wait
+475	nospu	rootns_kill			sys_rootns_kill
arch/s390/kernel/syscalls/syscall.tbl +3 -0
index 1b45e68a217b..7f8cd4147860 100644
@@ -399,3 +399,6 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
arch/sh/kernel/syscalls/syscall.tbl +3 -0
index ace068dff0de..9bfcb96dcdeb 100644
@@ -476,3 +476,6 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
arch/sparc/kernel/syscalls/syscall.tbl +3 -0
index 5b9fe0e8140f..a847f4cbea3a 100644
@@ -518,3 +518,6 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait			compat_sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
arch/x86/entry/syscalls/syscall_32.tbl +3 -0
index 2c172ef48dfd..e49c96692038 100644
@@ -478,3 +478,6 @@
 470	i386	listns			sys_listns
 471	i386	rseq_slice_yield	sys_rseq_slice_yield
 472	i386	fchroot			sys_fchroot
+473	i386	rootns_create		sys_rootns_create
+474	i386	rootns_wait		sys_rootns_wait		compat_sys_rootns_wait
+475	i386	rootns_kill		sys_rootns_kill
arch/x86/entry/syscalls/syscall_64.tbl +3 -0
index d5b6045b0090..d6f7fb7be172 100644
@@ -397,6 +397,9 @@
 470	common	listns			sys_listns
 471	common	rseq_slice_yield	sys_rseq_slice_yield
 472	common	fchroot			sys_fchroot
+473	common	rootns_create		sys_rootns_create
+474	common	rootns_wait		sys_rootns_wait
+475	common	rootns_kill		sys_rootns_kill
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
arch/xtensa/kernel/syscalls/syscall.tbl +3 -0
index d354bb231796..268c0d577788 100644
@@ -443,3 +443,6 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
include/uapi/asm-generic/unistd.h +9 -1
index 5b7e77a7c736..571db09eb571 100644
@@ -867,8 +867,16 @@ __SYSCALL(__NR_rseq_slice_yield, sys_rseq_slice_yield)
 #define __NR_fchroot 472
 __SYSCALL(__NR_fchroot, sys_fchroot)
 
+/* kernel/rootns.c */
+#define __NR_rootns_create 473
+__SYSCALL(__NR_rootns_create, sys_rootns_create)
+#define __NR_rootns_wait 474
+__SC_COMP(__NR_rootns_wait, sys_rootns_wait, compat_sys_rootns_wait)
+#define __NR_rootns_kill 475
+__SYSCALL(__NR_rootns_kill, sys_rootns_kill)
+
 #undef __NR_syscalls
-#define __NR_syscalls 473
+#define __NR_syscalls 476
 
 /*
  * 32 bit systems traditionally used different
scripts/syscall.tbl +3 -0
index 0ab531605120..e9ff99c03b2b 100644
@@ -413,3 +413,6 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns_create			sys_rootns_create
+474	common	rootns_wait			sys_rootns_wait			compat_sys_rootns_wait
+475	common	rootns_kill			sys_rootns_kill
Signature · 1 line
2.47.3
#20 lore raw

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

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

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

Sashiko has reviewed this patch and found no issues.

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

RFC PATCH v3 11/13 docs: Document root namespace uAPI

In reply to Jarkko Sakkinen

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

Add Documentation/userspace-api/rootns.rst to include the kernel-doc sections and system call reference from kernel/rootns.c, include/uapi/linux/rootns.h, fs/fsopen.c, and fs/namespace.c, 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        | 47 +++++++++++++++++++
 3 files changed, 49 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 +47 -0

47 lines not on this page · raw message

Signature · 1 line
2.47.3
#22 lore raw

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

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

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

Quoted 8 lines

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

Sashiko has reviewed this patch and found no issues.

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

RFC PATCH v3 12/13 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.

Add a kselftest harness suite under tools/testing/selftests/rootns exercising rootns creation, ROOTNS_GET_NSFD, clone3(CLONE_INTO_ROOTNS) init and concurrent bootstrap lifecycle, poll(EPOLLHUP) and WNOHANG/rusage reporting, unprivileged external FSCONFIG_SET_ROOTNS and MOVE_MOUNT_T_MNTNS setup without entering a user namespace, hot-mounting into existing mount namespaces, pivot_root(), and setns() isolation.

---
 tools/testing/selftests/Makefile          |    1 +
 tools/testing/selftests/rootns/.gitignore |    2 +
 tools/testing/selftests/rootns/Makefile   |    5 +
 tools/testing/selftests/rootns/config     |   10 +
 tools/testing/selftests/rootns/smoke.c    | 1934 +++++++++++++++++++++
 5 files changed, 1952 insertions(+)
 create mode 100644 tools/testing/selftests/rootns/.gitignore
 create mode 100644 tools/testing/selftests/rootns/Makefile
 create mode 100644 tools/testing/selftests/rootns/config
 create mode 100644 tools/testing/selftests/rootns/smoke.c
tools/testing/selftests/Makefile +1 -0
index 07c3719f8b04..7c44f93e57a4 100644
@@ -117,6 +117,7 @@ TARGETS += rdma
 TARGETS += resctrl
 TARGETS += riscv
 TARGETS += rlimits
+TARGETS += rootns
 TARGETS += rseq
 TARGETS += rtc
 TARGETS += rust
tools/testing/selftests/rootns/.gitignore new file +2 -0
new file mode 100644
index 000000000000..9a018c20d310
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0-only
+/smoke
tools/testing/selftests/rootns/Makefile new file +5 -0
new file mode 100644
index 000000000000..79162fba3c2b
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+
+CFLAGS += -Wall -Wextra -O2 -g $(KHDR_INCLUDES)
+TEST_GEN_PROGS := smoke
+include ../lib.mk
tools/testing/selftests/rootns/config new file +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/smoke.c new file +1934 -0

1,934 lines not on this page · raw message

Signature · 1 line
2.47.3
#24 lore raw

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

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] selftests/rootns: shared mount propagation in move_mount_existing_mntns() - [Medium]…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] selftests/rootns: shared mount propagation in move_mount_existing_mntns()
- [Medium] selftests/rootns: missing SKIP() on ENOSYS and silent skips in child helpers
- [Low] selftests/rootns: stack direction and lifetime hazard in clone_with_flags()
--

commit 101069d69b43912a16a7832bfad97b5398c581ce
Author: Jarkko Sakkinen <[email protected]>

selftests/rootns: Add root namespace test suite

This commit adds a kselftest harness suite under tools/testing/selftests/rootns to verify the root namespace and mount namespace configuration uAPI and security invariants.

Quoted 6 lines
tools/testing/selftests/rootns/smoke.c new file +0 -0
new file mode 100644
index 0000000000000..f0e3158ea4bec
@@ -0,0 +1,1934 @@

[ ... ]

Quoted 16 lines
tools/testing/selftests/rootns/smoke.c new file +16 -0
+static int clone_with_flags(int flags)
+{
+	const size_t stack_size = 64 * 1024;
+	void *stack;
+	pid_t pid;
+	int status;
+	int ret;
+
+	stack = malloc(stack_size);
+	if (!stack)
+		return -ENOMEM;
+
+	pid = clone(clone_exit, (char *)stack + stack_size,
+		    SIGCHLD | flags, NULL);
+	if (pid < 0)
+		ret = -errno;

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

Quoted 10 lines
tools/testing/selftests/rootns/smoke.c new file +10 -0
+	else if (waitpid(pid, &status, 0) < 0)
+		ret = -errno;
+	else if (!WIFEXITED(status) || WEXITSTATUS(status))
+		ret = -EIO;
+	else
+		ret = 0;
+
+	free(stack);
+	return ret;
+}

[Severity: Low]
Can passing (char *)stack + stack_size to clone() write past the end of the heap buffer on architectures where the stack grows upward, such as PA-RISC? Also, if waitpid() fails (for example on EINTR), free(stack) runs while the child may still be executing on that stack. Using sys_clone3() with stack = 0 and stack_size = 0 would avoid manual stack allocation and work regardless of stack growth direction.

[ ... ]

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

Quoted 9 lines
tools/testing/selftests/rootns/smoke.c new file +9 -0
+FIXTURE_SETUP(rootns) {
+	self->cfd = create_test_rootns(false, ROOTNS_KILL_ON_CLOSE |
+				       ROOTNS_CLOSE_ON_EXEC);
+	if (self->cfd < 0 && geteuid() != 0 &&
+	    (errno == EPERM || errno == EACCES || errno == EINVAL ||
+	     errno == ENOSPC || errno == EOVERFLOW))
+		SKIP(return, "pre-idmap submount setup requires mapped userns");
+	ASSERT_GE(self->cfd, 0);
+}

[Severity: Medium]
Will this fail instead of skipping when CONFIG_ROOTNS is disabled (errno == ENOSYS) or when geteuid() == 0 hits EPERM, EACCES, or ENOSPC? Because rootns is added unconditionally to TARGETS in tools/testing/selftests/Makefile while CONFIG_ROOTNS defaults to n, running make run_tests on a kernel without CONFIG_ROOTNS will fail all tests in this binary instead of skipping them.

The same issue applies to TEST(get_nsfd), while TEST_F(rootns, mount_perms) omits -ENOSPC when checking the return value of create_rootns_as_uid(). In addition, the forked child helpers in mount_perms, clone_perms, fsconfig, and unpriv_no_userns call _exit(0) when unprivileged namespace creation fails with EPERM, EACCES, EINVAL, or ENOSPC, causing the parent to report a silent pass instead of a skip with a reason string (and unpriv_no_userns fails with exit status 4 on ENOSYS).

[ ... ]

Quoted 63 lines
tools/testing/selftests/rootns/smoke.c new file +63 -0
+TEST_F(rootns, move_mount_existing_mntns) {
+	int ready_pipe[2];
+	int hold_pipe[2];
+	char path[64];
+	int marker_fd;
+	int mntns_fd;
+	char ch;
+	pid_t pid;
+	int fsfd;
+	int mfd;
+
+	ASSERT_EQ(pipe2(ready_pipe, O_CLOEXEC), 0);
+	ASSERT_EQ(pipe2(hold_pipe, O_CLOEXEC), 0);
+
+	pid = fork();
+	ASSERT_GE(pid, 0);
+	if (pid == 0) {
+		struct statfs st;
+
+		close(self->cfd);
+		close(ready_pipe[0]);
+		close(hold_pipe[1]);
+
+		if (unshare(CLONE_NEWNS) < 0)
+			_exit(1);
+		if (write(ready_pipe[1], "r", 1) != 1)
+			_exit(2);
+		close(ready_pipe[1]);
+
+		if (read(hold_pipe[0], &ch, 1) != 1)
+			_exit(3);
+		close(hold_pipe[0]);
+
+		if (statfs("/tmp", &st) < 0)
+			_exit(4);
+		if ((unsigned long)st.f_type != (unsigned long)TMPFS_MAGIC)
+			_exit(5);
+		if (access("/tmp/hot_mounted", F_OK) < 0)
+			_exit(6);
+		_exit(0);
+	}
+	close(ready_pipe[1]);
+	close(hold_pipe[0]);
+
+	ASSERT_EQ(read(ready_pipe[0], &ch, 1), 1);
+	close(ready_pipe[0]);
+
+	snprintf(path, sizeof(path), "/proc/%d/ns/mnt", (int)pid);
+	mntns_fd = open(path, O_RDONLY | O_CLOEXEC);
+	ASSERT_GE(mntns_fd, 0);
+
+	fsfd = sys_fsopen("tmpfs", 0);
+	ASSERT_GE(fsfd, 0);
+	ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0), 0);
+	mfd = sys_fsmount(fsfd, 0, 0);
+	close(fsfd);
+	ASSERT_GE(mfd, 0);
+
+	marker_fd = openat(mfd, "hot_mounted",
+			   O_CREAT | O_WRONLY | O_CLOEXEC, 0644);
+	ASSERT_GE(marker_fd, 0);
+	close(marker_fd);
+

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

Quoted 10 lines
tools/testing/selftests/rootns/smoke.c new file +10 -0
+	/* Existing mnt_ns already has "/", so "/" must fail with EBUSY. */
+	ASSERT_EQ(sys_move_mount(mfd, "", mntns_fd, "/",
+				 MOVE_MOUNT_F_EMPTY_PATH |
+				 MOVE_MOUNT_T_MNTNS), -1);
+	ASSERT_EQ(errno, EBUSY);
+
+	/* Hot-mounting onto a relative path inside the live mnt_ns succeeds. */
+	ASSERT_EQ(sys_move_mount(mfd, "", mntns_fd, "tmp",
+				 MOVE_MOUNT_F_EMPTY_PATH |
+				 MOVE_MOUNT_T_MNTNS), 0);

[Severity: Medium]
Does sys_move_mount() here propagate the new tmpfs mount onto /tmp in the host mount namespace?

Because the child calls unshare(CLONE_NEWNS) without unsharing a user namespace or remounting "/" with MS_REC | MS_PRIVATE, its mounts stay in the same shared peer group as the host mount namespace when "/" or "/tmp" is mounted MS_SHARED (the default on systemd hosts). Attaching mfd onto "tmp" in mntns_fd then propagates a peer tmpfs mount onto the host's /tmp that remains mounted after the child and mntns_fd exit, hiding the host's /tmp contents.

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

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

In reply to Jarkko Sakkinen

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

---
 MAINTAINERS | 11 +++++++++++
 1 file changed, 11 insertions(+)
MAINTAINERS +11 -0
index 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
#26 lore raw
In reply to Jarkko Sakkinen
Quoted 64 lines · Jarkko Sakkinen

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_create() 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_VM | CLONE_VFORK and opening the target binary via openat2(..., RESOLVE_IN_ROOT) on the retained "/" mount fd allows spawning with execveat() without copying page tables.

The first entrant becomes PID 1; once it exits and zap_pid_ns_processes() reaps all members, poll() reports EPOLLHUP and rootns_wait() returns init's exit status and rusage. rootns_kill() walks pid_ns->idr under tasklist_lock to signal member thread groups.

CHANGES
=======

Quoted 15 lines

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.

I.e. before PID 1 and /proc/<pid>/ns/* existss, nsfd for namespace other than root nsfd can be acquired as follows:

	int mnts_fd = ioctl(root_fd, ROOTNS_GET_NSFD, CLONE_NEWNS);

Br, Jarkko

#27 lore raw
Quoted 81 lines · Jarkko Sakkinen
Quoted 64 lines · Jarkko Sakkinen

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_create() 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_VM | CLONE_VFORK and opening the target binary via openat2(..., RESOLVE_IN_ROOT) on the retained "/" mount fd allows spawning with execveat() without copying page tables.

The first entrant becomes PID 1; once it exits and zap_pid_ns_processes() reaps all members, poll() reports EPOLLHUP and rootns_wait() returns init's exit status and rusage. rootns_kill() walks pid_ns->idr under tasklist_lock to signal member thread groups.

CHANGES
=======

Quoted 15 lines

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.

Quoted 4 lines

I.e. before PID 1 and /proc/<pid>/ns/* existss, nsfd for namespace other than root nsfd can be acquired as follows:

	int mnts_fd = ioctl(root_fd, ROOTNS_GET_NSFD, CLONE_NEWNS);

Unprivileged caller becomes the owner of rootns->user_ns. Each mount syscall then just checks CAP_SYS_ADMIN against rootns->user_ns.

The user space wiring goes along the lines of:

        int root_fd = rootns_create(ROOTNS_KILL_ON_CLOSE | ROOTNS_CLOSE_ON_EXEC);
        int mntns_fd = ioctl(root_fd, ROOTNS_GET_NSFD, CLONE_NEWNS);

        int tmpfs_fd = fsopen("tmpfs", 0);
        fsconfig(tmpfs_fd, FSCONFIG_SET_ROOTNS, NULL, NULL, root_fd);
        fsconfig(tmpfs_fd, FSCONFIG_CMD_CREATE, NULL, NULL, 0);
        int rootfs_fd = fsmount(tmpfs_fd, 0, 0);

        move_mount(rootfs_fd, "", mntns_fd, "/", MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_MNTNS);

        struct clone_args args = {
                .flags  = CLONE_INTO_ROOTNS,
                .rootns = root_fd,
        };
        pid_t pid = clone3(&args, sizeof(args));

Note that example is uncompiled :-)

This example makes me feel that perhaps RootNS is not the best possible name for this but this rather should be e.g., NullNS?

Br, Jarkko

#28 lore raw
Quoted 109 lines · Jarkko Sakkinen
Quoted 81 lines · Jarkko Sakkinen
Quoted 64 lines · Jarkko Sakkinen

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_create() 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_VM | CLONE_VFORK and opening the target binary via openat2(..., RESOLVE_IN_ROOT) on the retained "/" mount fd allows spawning with execveat() without copying page tables.

The first entrant becomes PID 1; once it exits and zap_pid_ns_processes() reaps all members, poll() reports EPOLLHUP and rootns_wait() returns init's exit status and rusage. rootns_kill() walks pid_ns->idr under tasklist_lock to signal member thread groups.

CHANGES
=======

Quoted 15 lines

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.

Quoted 4 lines

I.e. before PID 1 and /proc/<pid>/ns/* existss, nsfd for namespace other than root nsfd can be acquired as follows:

	int mnts_fd = ioctl(root_fd, ROOTNS_GET_NSFD, CLONE_NEWNS);

Unprivileged caller becomes the owner of rootns->user_ns. Each mount syscall then just checks CAP_SYS_ADMIN against rootns->user_ns.

The user space wiring goes along the lines of:

        int root_fd = rootns_create(ROOTNS_KILL_ON_CLOSE | ROOTNS_CLOSE_ON_EXEC);
        int mntns_fd = ioctl(root_fd, ROOTNS_GET_NSFD, CLONE_NEWNS);

        int tmpfs_fd = fsopen("tmpfs", 0);
        fsconfig(tmpfs_fd, FSCONFIG_SET_ROOTNS, NULL, NULL, root_fd);
        fsconfig(tmpfs_fd, FSCONFIG_CMD_CREATE, NULL, NULL, 0);
        int rootfs_fd = fsmount(tmpfs_fd, 0, 0);

        move_mount(rootfs_fd, "", mntns_fd, "/", MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_MNTNS);

        struct clone_args args = {
                .flags  = CLONE_INTO_ROOTNS,
                .rootns = root_fd,
        };
        pid_t pid = clone3(&args, sizeof(args));
Quoted 4 lines

Note that example is uncompiled :-)

This example makes me feel that perhaps RootNS is not the best possible name for this but this rather should be e.g., NullNS?

Before judging this, keep in mind that I've not just suddenly invented this. I first encountered the topic when David posted his patches, and felt that they were a bit unfairly judged.

Somewhere at 2025 David rebased his branch when I asked, and slow-cooked the result that we're seeing during a period of 1.5 years. It has not been a priority topic at work so this has been more like a spare time sudoku.

So if you count the David's original patch set version, this has history spanning since 2017.

Br, Jarkko

#29 lore raw
In reply to Jarkko Sakkinen
Quoted 11 lines · Jarkko Sakkinen
Quoted 4 lines

I.e. before PID 1 and /proc/<pid>/ns/* existss, nsfd for namespace other than root nsfd can be acquired as follows:

	int mnts_fd = ioctl(root_fd, ROOTNS_GET_NSFD, CLONE_NEWNS);

Unprivileged caller becomes the owner of rootns->user_ns. Each mount syscall then just checks CAP_SYS_ADMIN against rootns->user_ns.

The user space wiring goes along the lines of:

Quoted 15 lines
        int root_fd = rootns_create(ROOTNS_KILL_ON_CLOSE | ROOTNS_CLOSE_ON_EXEC);
        int mntns_fd = ioctl(root_fd, ROOTNS_GET_NSFD, CLONE_NEWNS);

        int tmpfs_fd = fsopen("tmpfs", 0);
        fsconfig(tmpfs_fd, FSCONFIG_SET_ROOTNS, NULL, NULL, root_fd);
        fsconfig(tmpfs_fd, FSCONFIG_CMD_CREATE, NULL, NULL, 0);
        int rootfs_fd = fsmount(tmpfs_fd, 0, 0);

        move_mount(rootfs_fd, "", mntns_fd, "/", MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_MNTNS);

        struct clone_args args = {
                .flags  = CLONE_INTO_ROOTNS,
                .rootns = root_fd,
        };
        pid_t pid = clone3(&args, sizeof(args));

[BTW, this patch set is pointed out to David and not fsdevel mailing by a
mishap, apologies.]

I reduced syscalls can be further to only a single syscall: rootns()

The complete API after this:

1. rootns(flags)
2. ioctl(rootfs_fd, ROOTNS_GET_NSFD, ns)
3. ioctl(rootfs_fd, ROOTNS_WAIT, NULL)
4. ioctl(rootfs_fd, ROOTNS_KILL, signum)

An updated version of the patch set is available over here:

https://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd.git/log/?h=rootns

In order to find more evidence that the API is trimmed and code has no extra fat, I tried how LSM hooks size-fit.

Attached are the experimental LSM hooks and while possibly not exactly right they should not be at least in the ballpar (Paul?).

Not perfect, but very usable, and there's a steady track of convergence where resolving a bottleneck leads into a better symmetry and coherency overall.

Br, Jarkko

From a72fe460eab3ac1ef459ab6294515a0d665f94c2 Mon Sep 17 00:00:00 2001
From: Jarkko Sakkinen <[email protected]>
Date: Thu, 19 Nov 2026 06:20:07 +0200
Subject: [PATCH] security: Add LSM hooks for rootns

Add lbs_rootns and rootns->security blob management LSM hooks:

1. security_rootns_alloc()
2. security_rootns_free()
3. security_rootns_clone(),
4. security_rootns_kill()

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
#30 lore raw
Quoted 48 lines · Jarkko Sakkinen
Quoted 11 lines · Jarkko Sakkinen
Quoted 4 lines

I.e. before PID 1 and /proc/<pid>/ns/* existss, nsfd for namespace other than root nsfd can be acquired as follows:

	int mnts_fd = ioctl(root_fd, ROOTNS_GET_NSFD, CLONE_NEWNS);

Unprivileged caller becomes the owner of rootns->user_ns. Each mount syscall then just checks CAP_SYS_ADMIN against rootns->user_ns.

The user space wiring goes along the lines of:

Quoted 15 lines
        int root_fd = rootns_create(ROOTNS_KILL_ON_CLOSE | ROOTNS_CLOSE_ON_EXEC);
        int mntns_fd = ioctl(root_fd, ROOTNS_GET_NSFD, CLONE_NEWNS);

        int tmpfs_fd = fsopen("tmpfs", 0);
        fsconfig(tmpfs_fd, FSCONFIG_SET_ROOTNS, NULL, NULL, root_fd);
        fsconfig(tmpfs_fd, FSCONFIG_CMD_CREATE, NULL, NULL, 0);
        int rootfs_fd = fsmount(tmpfs_fd, 0, 0);

        move_mount(rootfs_fd, "", mntns_fd, "/", MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_MNTNS);

        struct clone_args args = {
                .flags  = CLONE_INTO_ROOTNS,
                .rootns = root_fd,
        };
        pid_t pid = clone3(&args, sizeof(args));

[BTW, this patch set is pointed out to David and not fsdevel mailing by a
mishap, apologies.]

I reduced syscalls can be further to only a single syscall: rootns()

The complete API after this:

1. rootns(flags)
2. ioctl(rootfs_fd, ROOTNS_GET_NSFD, ns)
3. ioctl(rootfs_fd, ROOTNS_WAIT, NULL)
4. ioctl(rootfs_fd, ROOTNS_KILL, signum)

An updated version of the patch set is available over here:

https://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd.git/log/?h=rootns

In order to find more evidence that the API is trimmed and code has no extra fat, I tried how LSM hooks size-fit.

Quoted 6 lines

Attached are the experimental LSM hooks and while possibly not exactly right they should not be at least in the ballpar (Paul?).

Not perfect, but very usable, and there's a steady track of convergence where resolving a bottleneck leads into a better symmetry and coherency overall.

Orthogonally, solely fd-local security model (as all is tied to fd) is the best thing ever when defining mandatory access control policies as the full flow can be meaningfully described; i.e. roonts(), sendmsg() and other calls track the fd's data flow with almost the highest achievable granularity.

Br, Jarkko

#32 lore raw
Quoted 9 lines · Vlastimil Babka (SUSE)
Quoted 5 lines · Jarkko Sakkinen

VERSIONS
========

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

3 versions in 2 days, with 13 patches and such a vast CC list? Maybe slow down a bit, please?

It has been a version per day (or along the lines), which is not spectacular but I'll pause for now.

v2 and v3 address the initial architectural bottlenecks that came up. Those really required updated changes + kselftest providing the evidence because I was not immediately sure myself whether they can be addressed without experimentation.

I would presume whatever happens to this would be more in details, and can be projected without extending feature and/or test coverage.

Br, Jarkko