Skip to contentSkip to conversation

rootns: fd-bound process closures

RFC PATCH Superseded Jarkko Sakkinen 2 participants 52 messages Nov 21 – Nov 22

Subsystems (30)

v5 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

v5 cover rootns: fd-bound process closures

OVERVIEW
========

A rootns is an anonymous-inode control object (not an nsfs namespace itself) with separate build and live phases 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
==============

Standalone fd-based namespace configuration (patches 01-07) decouples user and mount namespace setup from live helper tasks. userns_set_idmap() atomically configures setgroups policy and UID, GID, and project ID mappings on a CLONE_NEWUSER nsfs fd, checking current_cred() so an unprivileged creator can delegate the fd via SCM_RIGHTS to a privileged mapping daemon. 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, attaches relative submounts both before entry and into live mount namespaces, and supports MOVE_MOUNT_CLONE for recursive bind mounts without OPEN_TREE_CLONE.

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

Superblocks are configured directly in the target user namespace via fsopen(), FSCONFIG_SET_ROOTNS, and fsmount(), allowing unprivileged callers to assemble FS_USERNS_MOUNT filesystems without holding CAP_SYS_ADMIN in their own user namespace or entering the target user namespace first.

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

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

HOTPLUG
=======

1. Host creates rootns().
2. Host sets uid/gid maps with userns_set_idmap().
3. Host populates "/" with MOVE_MOUNT_T_MNTNS, optionally combined with MOVE_MOUNT_CLONE for bind mounts.
4. Host spawns PID 1 with clone3(CLONE_INTO_ROOTNS) (optionally passing an AF_UNIX socketpair fd for communication).
5. PID 1 watches /proc/self/ns/mnt via fanotify(FAN_REPORT_MNT | FAN_MARK_MNTNS, FAN_MNT_ATTACH) or polls /proc/self/mountinfo.
6. On hotplug, host mounts the filesystem via fsopen()/fsmount() (plus optional MOUNT_ATTR_IDMAP).
7. Host creates the mountpoint with openat2(RESOLVE_IN_ROOT) + mkdirat() and attaches the mount with MOVE_MOUNT_T_MNTNS.
8. PID 1 receives FAN_MNT_ATTACH and queries the new mount via statmount().

CHANGES
=======

v5:
- Heavy reduction of cc-list. More added by request.
- Re-slice the patch set into standalone fd-based user and mount namespace configuration (01-07) followed by rootns (08-25), and split proc, ipc/mqueue, and bpf_lsm changes into separate commits.
- Add userns_set_idmap() system call to atomically configure setgroups and UID, GID, and project ID mappings on CLONE_NEWUSER nsfs fds without /proc/<pid>/*_map, checking current_cred() so unprivileged userns fds can be delegated via SCM_RIGHTS to a privileged mapping daemon (Andy Lutomirski).
- Add MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS in move_mount() to recursively bind-clone host mount subtrees into a target mount namespace fd without OPEN_TREE_CLONE.
- Clarify in overview and uAPI documentation that rootns is an anonymous-inode control object rather than an nsfs namespace.
- Fix upfront pidns ancestry check in ROOTNS_WAIT, bootstrap -EINVAL preservation in CLONE_INTO_ROOTNS, FSCONFIG_SET_ROOTNS user_ns delegation and fsmount() rootns_bound/seq_origin handling, proc pidns= mount option override check, cross-userns anonymous mount MNT_LOCKED propagation, and selftest wide-arch _IOC_NONE, socket blocking, and cleanup handling (Sashiko).
- Extend selftests/rootns with userns_set_idmap(), SCM_RIGHTS delegation, MOVE_MOUNT_CLONE, and hotplug mount coverage.

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

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

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

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

VERSIONS
========

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

Cc Alexander Mikhalitsyn <[email protected]>
Cc Alexander Viro <[email protected]>
Cc Andy Lutomirski <[email protected]>
Cc Christian Brauner <[email protected]>
Cc David Howells <[email protected]>
Cc Jan Kara <[email protected]>
Cc Jonathan Corbet <[email protected]>
Cc Josef Bacik <[email protected]>
Cc Kees Cook <[email protected]>
Cc Neal Gompa <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Cc Zygmunt Krynicki <[email protected]>

Jarkko Sakkinen (25):
userns: Factor out idmap validation and commit helpers
userns: Add userns_set_idmap() system call
arch: Wire up userns_set_idmap() system call
mount: Add mnt_ns_get_root()
mount: Enforce mount_too_revealing() for foreign mntns
mount: Support MOVE_MOUNT_T_MNTNS in move_mount()
mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS
userns: Factor out install_user_ns_cred()
nsfs: Add nsproxy_open_namespace()
nsproxy: Pass nsproxy to create_new_namespaces()
rootns: Add core infrastructure for root namespaces
rootns: Track init lifecycle via copy_process() and pid_namespace
rootns: Add rootns() system call
rootns: Add ROOTNS_WAIT ioctl
rootns: Add ROOTNS_KILL ioctl
fork: Support CLONE_INTO_ROOTNS in clone3()
fs: Support FSCONFIG_SET_ROOTNS in fsconfig()
proc: Implement ->set_rootns() fs_context operation ipc/mqueue: Implement ->set_rootns() fs_context operation
security: Add rootns LSM hooks
bpf: Register rootns LSM hooks
arch: Wire up rootns() system call
docs: Document root namespace uAPI
selftests/rootns: Add root namespace test suite
MAINTAINERS: Add entry for ROOT NAMESPACE

 Documentation/userspace-api/index.rst         |    1 +
 .../userspace-api/ioctl/ioctl-number.rst      |    1 +
 Documentation/userspace-api/rootns.rst        |   65 +
 MAINTAINERS                                   |   11 +
 arch/alpha/kernel/syscalls/syscall.tbl        |    2 +
 arch/arm/tools/syscall.tbl                    |    2 +
 arch/arm64/tools/syscall_32.tbl               |    2 +
 arch/m68k/kernel/syscalls/syscall.tbl         |    2 +
 arch/microblaze/kernel/syscalls/syscall.tbl   |    2 +
 arch/mips/kernel/syscalls/syscall_n32.tbl     |    2 +
 arch/mips/kernel/syscalls/syscall_n64.tbl     |    2 +
 arch/mips/kernel/syscalls/syscall_o32.tbl     |    2 +
 arch/parisc/kernel/syscalls/syscall.tbl       |    2 +
 arch/powerpc/kernel/syscalls/syscall.tbl      |    2 +
 arch/s390/kernel/syscalls/syscall.tbl         |    2 +
 arch/sh/kernel/syscalls/syscall.tbl           |    2 +
 arch/sparc/kernel/syscalls/syscall.tbl        |    2 +
 arch/x86/entry/syscalls/syscall_32.tbl        |    2 +
 arch/x86/entry/syscalls/syscall_64.tbl        |    2 +
 arch/xtensa/kernel/syscalls/syscall.tbl       |    2 +
 fs/devpts/inode.c                             |    2 +
 fs/filesystems.c                              |   15 +
 fs/fs_context.c                               |   21 +-
 fs/fsopen.c                                   |  140 +-
 fs/internal.h                                 |    6 +
 fs/namespace.c                                |  348 +++-
 fs/nsfs.c                                     |   64 +
 fs/proc/root.c                                |   22 +
 include/linux/cred.h                          |    4 +-
 include/linux/fs_context.h                    |    6 +
 include/linux/lsm_hook_defs.h                 |    7 +
 include/linux/lsm_hooks.h                     |    3 +
 include/linux/mnt_namespace.h                 |    2 +
 include/linux/nsfs.h                          |    2 +
 include/linux/nsproxy.h                       |    9 +-
 include/linux/pid_namespace.h                 |    4 +
 include/linux/rootns.h                        |   93 +
 include/linux/sched/task.h                    |    8 +
 include/linux/security.h                      |   30 +
 include/linux/syscalls.h                      |    5 +
 include/linux/time_namespace.h                |   13 +
 include/linux/user_namespace.h                |    7 +
 include/uapi/asm-generic/unistd.h             |   10 +-
 include/uapi/linux/mount.h                    |    5 +-
 include/uapi/linux/nsfs.h                     |   53 +
 include/uapi/linux/rootns.h                   |   83 +
 include/uapi/linux/sched.h                    |    5 +
 init/Kconfig                                  |    9 +
 ipc/mqueue.c                                  |   13 +
 kernel/Makefile                               |    2 +
 kernel/bpf/bpf_lsm.c                          |   10 +
 kernel/cred.c                                 |   32 +-
 kernel/fork.c                                 |   95 +-
 kernel/nsproxy.c                              |   41 +-
 kernel/pid_namespace.c                        |    2 +
 kernel/rootns.c                               |  588 ++++++
 kernel/sys_ni.c                               |    4 +
 kernel/user_namespace.c                       |  420 ++++-
 scripts/syscall.tbl                           |    2 +
 security/lsm_init.c                           |    6 +
 security/security.c                           |   86 +
 tools/testing/selftests/Makefile              |    1 +
 tools/testing/selftests/rootns/Makefile       |    5 +
 tools/testing/selftests/rootns/config         |   10 +
 .../testing/selftests/rootns/rootns_cells.py  | 1400 ++++++++++++++
 tools/testing/selftests/rootns/rootns_test.py | 1645 +++++++++++++++++
 tools/testing/selftests/rootns/test_smoke.sh  |   10 +
 67 files changed, 5286 insertions(+), 172 deletions(-)
 create mode 100644 Documentation/userspace-api/rootns.rst
 create mode 100644 include/linux/rootns.h
 create mode 100644 include/uapi/linux/rootns.h
 create mode 100644 kernel/rootns.c
 create mode 100644 tools/testing/selftests/rootns/Makefile
 create mode 100644 tools/testing/selftests/rootns/config
 create mode 100755 tools/testing/selftests/rootns/rootns_cells.py
 create mode 100755 tools/testing/selftests/rootns/rootns_test.py
 create mode 100755 tools/testing/selftests/rootns/test_smoke.sh

--
2.47.3

#1 lore raw

RFC PATCH v5 1/25 userns: Factor out idmap validation and commit helpers

map_write() validates extent ranges, translates parent ID ranges, sorts extents, and installs the resulting map inline for procfs text writes, preventing non-procfs callers from reusing the same validation and commit path.

Extract validate_and_insert_extent(), free_new_idmap(), resolve_new_idmap(), and commit_new_idmap() out of map_write() with no functional change.

---
 kernel/user_namespace.c | 159 ++++++++++++++++++++--------------------
 1 file changed, 80 insertions(+), 79 deletions(-)
kernel/user_namespace.c +80 -79
index cd748e1cbace..6b9673dcdc67 100644
@@ -938,6 +938,80 @@ static bool verify_root_map(const struct file *file,
 	return true;
 }
 
+static int validate_and_insert_extent(struct uid_gid_map *new_map,
+				      struct uid_gid_extent *extent)
+{
+	if ((extent->first == (u32)-1) || (extent->lower_first == (u32)-1))
+		return -EINVAL;
+
+	if ((extent->first + extent->count) <= extent->first)
+		return -EINVAL;
+	if ((extent->lower_first + extent->count) <= extent->lower_first)
+		return -EINVAL;
+
+	if (mappings_overlap(new_map, extent))
+		return -EINVAL;
+
+	if (new_map->nr_extents >= UID_GID_MAP_MAX_EXTENTS)
+		return -EINVAL;
+
+	return uid_gid_map_insert_extent(new_map, extent);
+}
+
+static void free_new_idmap(struct uid_gid_map *new_map)
+{
+	if (new_map->nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
+		kfree(new_map->forward);
+		kfree(new_map->reverse);
+	}
+	memset(new_map, 0, sizeof(*new_map));
+}
+
+static int resolve_new_idmap(struct uid_gid_map *new_map,
+			     struct uid_gid_map *parent_map)
+{
+	unsigned int idx;
+
+	if (new_map->nr_extents == 0)
+		return -EINVAL;
+
+	for (idx = 0; idx < new_map->nr_extents; idx++) {
+		struct uid_gid_extent *e;
+		u32 lower_first;
+
+		if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
+			e = &new_map->extent[idx];
+		else
+			e = &new_map->forward[idx];
+
+		lower_first = map_id_range_down(parent_map,
+						e->lower_first,
+						e->count);
+		if (lower_first == (u32)-1)
+			return -EPERM;
+
+		e->lower_first = lower_first;
+	}
+
+	return uid_gid_map_sort(new_map);
+}
+
+static void commit_new_idmap(struct uid_gid_map *map,
+			     struct uid_gid_map *new_map)
+{
+	if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) {
+		memcpy(map->extent, new_map->extent,
+		       new_map->nr_extents * sizeof(new_map->extent[0]));
+	} else {
+		map->forward = new_map->forward;
+		map->reverse = new_map->reverse;
+	}
+	/* Pairs with smp_rmb() in map_id_range_down() / map_id_up(). */
+	smp_wmb();
+	map->nr_extents = new_map->nr_extents;
+	memset(new_map, 0, sizeof(*new_map));
+}
+
 /*
  * Parse the decimal u32 at *pos, up to the next whitespace or NUL, and
  * leave *pos pointing at that character.
@@ -966,8 +1040,7 @@ static ssize_t map_write(struct file *file, const char __user *buf,
 {
 	struct seq_file *seq = file->private_data;
 	struct user_namespace *map_ns = seq->private;
-	struct uid_gid_map new_map;
-	unsigned idx;
+	struct uid_gid_map new_map = {};
 	struct uid_gid_extent extent;
 	char *kbuf, *pos, *next_line;
 	ssize_t ret;
@@ -1002,8 +1075,6 @@ static ssize_t map_write(struct file *file, const char __user *buf,
 	 */
 	mutex_lock(&userns_state_mutex);
 
-	memset(&new_map, 0, sizeof(struct uid_gid_map));
-
 	ret = -EPERM;
 	/* Only allow one successful write to the map */
 	if (map->nr_extents != 0)
@@ -1052,98 +1123,28 @@ static ssize_t map_write(struct file *file, const char __user *buf,
 		if (*pos != '\0')
 			goto out;
 
-		/* Verify we have been given valid starting values */
-		if ((extent.first == (u32) -1) ||
-		    (extent.lower_first == (u32) -1))
-			goto out;
-
-		/* Verify count is not zero and does not cause the
-		 * extent to wrap
-		 */
-		if ((extent.first + extent.count) <= extent.first)
-			goto out;
-		if ((extent.lower_first + extent.count) <=
-		     extent.lower_first)
-			goto out;
-
-		/* Do the ranges in extent overlap any previous extents? */
-		if (mappings_overlap(&new_map, &extent))
-			goto out;
-
-		if ((new_map.nr_extents + 1) == UID_GID_MAP_MAX_EXTENTS &&
-		    (next_line != NULL))
-			goto out;
-
-		ret = uid_gid_map_insert_extent(&new_map, &extent);
+		ret = validate_and_insert_extent(&new_map, &extent);
 		if (ret < 0)
 			goto out;
 		ret = -EINVAL;
 	}
-	/* Be very certain the new map actually exists */
+
 	if (new_map.nr_extents == 0)
 		goto out;
 
 	ret = -EPERM;
-	/* Validate the user is allowed to use user id's mapped to. */
 	if (!new_idmap_permitted(file, map_ns, cap_setid, &new_map))
 		goto out;
 
-	ret = -EPERM;
-	/* Map the lower ids from the parent user namespace to the
-	 * kernel global id space.
-	 */
-	for (idx = 0; idx < new_map.nr_extents; idx++) {
-		struct uid_gid_extent *e;
-		u32 lower_first;
-
-		if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
-			e = &new_map.extent[idx];
-		else
-			e = &new_map.forward[idx];
-
-		lower_first = map_id_range_down(parent_map,
-						e->lower_first,
-						e->count);
-
-		/* Fail if we can not map the specified extent to
-		 * the kernel global id space.
-		 */
-		if (lower_first == (u32) -1)
-			goto out;
-
-		e->lower_first = lower_first;
-	}
-
-	/*
-	 * If we want to use binary search for lookup, this clones the extent
-	 * array and sorts both copies.
-	 */
-	ret = uid_gid_map_sort(&new_map);
+	ret = resolve_new_idmap(&new_map, parent_map);
 	if (ret < 0)
 		goto out;
 
-	/* Install the map */
-	if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) {
-		memcpy(map->extent, new_map.extent,
-		       new_map.nr_extents * sizeof(new_map.extent[0]));
-	} else {
-		map->forward = new_map.forward;
-		map->reverse = new_map.reverse;
-	}
-	smp_wmb();
-	map->nr_extents = new_map.nr_extents;
-
+	commit_new_idmap(map, &new_map);
 	*ppos = count;
 	ret = count;
 out:
-	if (ret < 0 && new_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
-		kfree(new_map.forward);
-		kfree(new_map.reverse);
-		map->forward = NULL;
-		map->reverse = NULL;
-		map->nr_extents = 0;
-	}
-
+	free_new_idmap(&new_map);
 	mutex_unlock(&userns_state_mutex);
 	kfree(kbuf);
 	return ret;
Signature · 1 line
2.47.3
#2 lore raw

RFC PATCH v5 2/25 userns: Add userns_set_idmap() system call

In reply to Jarkko Sakkinen

Configuring UID, GID, and project ID mappings currently requires writing formatted text to /proc/<pid>/{uid_map,gid_map,projid_map,setgroups}, which depends on a live task in /proc and enforces write(2) file-opener CAP_SETUID/CAP_SETGID checks that prevent passing an unprivileged userns file descriptor over SCM_RIGHTS to a dedicated CAP_SETUID/CAP_SETGID mapping helper.

Add userns_set_idmap() to atomically configure setgroups policy and UID, GID, and project ID extents directly on a CLONE_NEWUSER nsfs file descriptor. Require CAP_SYS_ADMIN over the target user namespace in either the caller's or the file opener's credentials, and check parent ID-range capabilities strictly against the caller's credentials.

---
 include/linux/syscalls.h  |   4 +
 include/uapi/linux/nsfs.h |  53 ++++++++
 kernel/sys_ni.c           |   1 +
 kernel/user_namespace.c   | 259 ++++++++++++++++++++++++++++++++++++++
 4 files changed, 317 insertions(+)
include/linux/syscalls.h +4 -0
index 552d9710a0d5..72308cc11908 100644
@@ -77,6 +77,7 @@ struct cachestat;
 struct statmount;
 struct mnt_id_req;
 struct ns_id_req;
+struct userns_idmap;
 struct xattr_args;
 struct file_attr;
 
@@ -909,6 +910,9 @@ asmlinkage long sys_clock_adjtime32(clockid_t which_clock,
 				struct old_timex32 __user *tx);
 asmlinkage long sys_syncfs(int fd);
 asmlinkage long sys_setns(int fd, int nstype);
+asmlinkage long sys_userns_set_idmap(int fd,
+				     const struct userns_idmap __user *map,
+				     size_t size, unsigned int flags);
 asmlinkage long sys_pidfd_open(pid_t pid, unsigned int flags);
 asmlinkage long sys_sendmmsg(int fd, struct mmsghdr __user *msg,
 			     unsigned int vlen, unsigned flags);
include/uapi/linux/nsfs.h +53 -0

59 lines not on this page · raw message

kernel/sys_ni.c +1 -0
index c8be0abaa407..e3202e7cc2a1 100644
@@ -172,6 +172,7 @@ COND_SYSCALL_COMPAT(fadvise64_64);
 COND_SYSCALL(lsm_get_self_attr);
 COND_SYSCALL(lsm_set_self_attr);
 COND_SYSCALL(lsm_list_modules);
+COND_SYSCALL(userns_set_idmap);
 
 /* CONFIG_MMU only */
 COND_SYSCALL(swapon);
kernel/user_namespace.c +259 -0

272 lines not on this page · raw message

Signature · 1 line
2.47.3
#7 lore raw

RFC PATCH v5 3/25 arch: Wire up userns_set_idmap() system call

In reply to Jarkko Sakkinen

Expose userns_set_idmap() (473, 583 on Alpha) across all architecture system call tables and asm-generic unistd.h.

---
 arch/alpha/kernel/syscalls/syscall.tbl      | 1 +
 arch/arm/tools/syscall.tbl                  | 1 +
 arch/arm64/tools/syscall_32.tbl             | 1 +
 arch/m68k/kernel/syscalls/syscall.tbl       | 1 +
 arch/microblaze/kernel/syscalls/syscall.tbl | 1 +
 arch/mips/kernel/syscalls/syscall_n32.tbl   | 1 +
 arch/mips/kernel/syscalls/syscall_n64.tbl   | 1 +
 arch/mips/kernel/syscalls/syscall_o32.tbl   | 1 +
 arch/parisc/kernel/syscalls/syscall.tbl     | 1 +
 arch/powerpc/kernel/syscalls/syscall.tbl    | 1 +
 arch/s390/kernel/syscalls/syscall.tbl       | 1 +
 arch/sh/kernel/syscalls/syscall.tbl         | 1 +
 arch/sparc/kernel/syscalls/syscall.tbl      | 1 +
 arch/x86/entry/syscalls/syscall_32.tbl      | 1 +
 arch/x86/entry/syscalls/syscall_64.tbl      | 1 +
 arch/xtensa/kernel/syscalls/syscall.tbl     | 1 +
 include/uapi/asm-generic/unistd.h           | 6 +++++-
 scripts/syscall.tbl                         | 1 +
 18 files changed, 22 insertions(+), 1 deletion(-)
arch/alpha/kernel/syscalls/syscall.tbl +1 -0
index 52e3538cc7df..9384d59a44dc 100644
@@ -512,3 +512,4 @@
 580	common	listns				sys_listns
 581	common	rseq_slice_yield		sys_rseq_slice_yield
 582	common	fchroot				sys_fchroot
+583	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/arm/tools/syscall.tbl +1 -0
index 55717ed32c27..6130366b7681 100644
@@ -487,3 +487,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/arm64/tools/syscall_32.tbl +1 -0
index df2d1d82fb3c..3fcc7899fd08 100644
@@ -484,3 +484,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/m68k/kernel/syscalls/syscall.tbl +1 -0
index ba7a4d8903d0..5607635bd4bd 100644
@@ -472,3 +472,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/microblaze/kernel/syscalls/syscall.tbl +1 -0
index 76d7cbe2a133..97ee93f42fac 100644
@@ -478,3 +478,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/mips/kernel/syscalls/syscall_n32.tbl +1 -0
index 9ae88e4eac61..da4ed57a91d3 100644
@@ -411,3 +411,4 @@
 470	n32	listns				sys_listns
 471	n32	rseq_slice_yield		sys_rseq_slice_yield
 472	n32	fchroot				sys_fchroot
+473	n32	userns_set_idmap		sys_sys_userns_set_idmap
arch/mips/kernel/syscalls/syscall_n64.tbl +1 -0
index 83dc93a0712f..5e9839b6b389 100644
@@ -387,3 +387,4 @@
 470	n64	listns				sys_listns
 471	n64	rseq_slice_yield		sys_rseq_slice_yield
 472	n64	fchroot				sys_fchroot
+473	n64	userns_set_idmap		sys_sys_userns_set_idmap
arch/mips/kernel/syscalls/syscall_o32.tbl +1 -0
index 9c62429c9b7b..290c1b61be47 100644
@@ -460,3 +460,4 @@
 470	o32	listns				sys_listns
 471	o32	rseq_slice_yield		sys_rseq_slice_yield
 472	o32	fchroot				sys_fchroot
+473	o32	userns_set_idmap		sys_sys_userns_set_idmap
arch/parisc/kernel/syscalls/syscall.tbl +1 -0
index 88adc4016cce..fc0fa917eb92 100644
@@ -471,3 +471,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/powerpc/kernel/syscalls/syscall.tbl +1 -0
index cfbb70039ff0..d12e49022b23 100644
@@ -563,3 +563,4 @@
 470	common	listns				sys_listns
 471	nospu	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/s390/kernel/syscalls/syscall.tbl +1 -0
index 1b45e68a217b..dc427811d30d 100644
@@ -399,3 +399,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/sh/kernel/syscalls/syscall.tbl +1 -0
index ace068dff0de..e62ac9acc7ad 100644
@@ -476,3 +476,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/sparc/kernel/syscalls/syscall.tbl +1 -0
index 5b9fe0e8140f..df074bf322c4 100644
@@ -518,3 +518,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 2c172ef48dfd..243a3f55834d 100644
@@ -478,3 +478,4 @@
 470	i386	listns			sys_listns
 471	i386	rseq_slice_yield	sys_rseq_slice_yield
 472	i386	fchroot			sys_fchroot
+473	i386	userns_set_idmap	sys_sys_userns_set_idmap
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index d5b6045b0090..f11700e3af65 100644
@@ -397,6 +397,7 @@
 470	common	listns			sys_listns
 471	common	rseq_slice_yield	sys_rseq_slice_yield
 472	common	fchroot			sys_fchroot
+473	common	userns_set_idmap	sys_sys_userns_set_idmap
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
arch/xtensa/kernel/syscalls/syscall.tbl +1 -0
index d354bb231796..1d28de95915f 100644
@@ -443,3 +443,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
include/uapi/asm-generic/unistd.h +5 -1
index 5b7e77a7c736..695eac2d356b 100644
@@ -867,8 +867,12 @@ __SYSCALL(__NR_rseq_slice_yield, sys_rseq_slice_yield)
 #define __NR_fchroot 472
 __SYSCALL(__NR_fchroot, sys_fchroot)
 
+/* kernel/user_namespace.c */
+#define __NR_userns_set_idmap 473
+__SYSCALL(__NR_userns_set_idmap, sys_userns_set_idmap)
+
 #undef __NR_syscalls
-#define __NR_syscalls 473
+#define __NR_syscalls 474
 
 /*
  * 32 bit systems traditionally used different
scripts/syscall.tbl +1 -0
index 0ab531605120..0dddd465d1c5 100644
@@ -413,3 +413,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
Signature · 1 line
2.47.3
#11 lore raw

RFC PATCH v5 4/25 mount: Add mnt_ns_get_root()

In reply to Jarkko Sakkinen

Empty mount namespaces created with CLONE_EMPTY_MNTNS start with only an internal nullfs root mount until a real root filesystem is mounted over it, and external callers have no helper to resolve the live root path of an unentered mount namespace.

Add mnt_ns_get_root() to look up "/" with LOOKUP_DOWN from the mount namespace's base root mount and return -ENOENT if no filesystem has been mounted over the initial nullfs root yet.

---
 fs/namespace.c                | 16 ++++++++++++++++
 include/linux/mnt_namespace.h |  2 ++
 2 files changed, 18 insertions(+)
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/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 *);
Signature · 1 line
2.47.3
#12 lore raw

RFC PATCH v5 5/25 mount: Enforce mount_too_revealing() for foreign mntns

In reply to Jarkko Sakkinen

mount_too_revealing() skips visibility checks whenever current->nsproxy->mnt_ns belongs to init_user_ns, assuming the caller holds CAP_SYS_ADMIN in its current mount namespace. That assumption does not hold when an unprivileged caller creates mounts for a child user namespace while running in init_mnt_ns or another foreign mount namespace.

Require CAP_SYS_ADMIN in init_user_ns before bypassing mount_too_revealing() for init_mnt_ns, reject chrooted callers lacking CAP_SYS_ADMIN in their current mount namespace, and treat existing mounts and child overmounts in a foreign mount namespace as locked during mnt_already_visible() checks.

---
 fs/namespace.c | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)
fs/namespace.c +16 -5
index 781380945d78..b2dc84c0d0d6 100644
@@ -6582,6 +6582,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;
 
@@ -6606,11 +6607,16 @@ static bool mnt_already_visible(struct mnt_namespace *ns,
 			continue;
 
 		/* A local view of the mount flags */
-		mnt_flags = mnt->mnt.mnt_flags;
+		mnt_flags = READ_ONCE(mnt->mnt.mnt_flags);
 
 		/* 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 +6635,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 && !(READ_ONCE(child->mnt.mnt_flags) & MNT_LOCKED))
 				continue;
 			/* Is the directory permanently empty? */
 			if (!is_empty_dir_inode(inode))
@@ -6650,13 +6656,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",
Signature · 1 line
2.47.3
#13 lore raw

RFC PATCH v5 6/25 mount: Support MOVE_MOUNT_T_MNTNS in move_mount()

In reply to Jarkko Sakkinen

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

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

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

---
 fs/namespace.c             | 226 +++++++++++++++++++++++++++++++------
 include/uapi/linux/mount.h |   3 +-
 2 files changed, 191 insertions(+), 38 deletions(-)
fs/namespace.c +189 -37
index b2dc84c0d0d6..b65f1fdd9281 100644
@@ -2202,7 +2202,8 @@ struct mnt_namespace *mnt_ns_from_dentry(struct dentry *dentry)
 	return to_mnt_ns(get_proc_ns(dentry->d_inode));
 }
 
-static bool mnt_ns_loop(struct dentry *dentry)
+static bool mnt_ns_loop_target(struct dentry *dentry,
+			       struct mnt_namespace *target_mnt_ns)
 {
 	/* Could bind mounting the mount namespace inode cause a
 	 * mount namespace loop?
@@ -2212,7 +2213,12 @@ static bool mnt_ns_loop(struct dentry *dentry)
 	if (!mnt_ns)
 		return false;
 
-	return current->nsproxy->mnt_ns->ns.ns_id >= mnt_ns->ns.ns_id;
+	return target_mnt_ns->ns.ns_id >= mnt_ns->ns.ns_id;
+}
+
+static bool mnt_ns_loop(struct dentry *dentry)
+{
+	return mnt_ns_loop_target(dentry, current->nsproxy->mnt_ns);
 }
 
 struct mount *copy_tree(struct mount *src_root, struct dentry *dentry,
@@ -2423,10 +2429,11 @@ static bool __has_children(struct mount *mnt, struct dentry *dentry)
  *
  * locks: mount_locked_reader || namespace_shared && pinned(subtree)
  */
-static bool check_for_nsfs_mounts(struct mount *subtree)
+static bool check_for_nsfs_mounts(struct mount *subtree,
+				  struct mnt_namespace *target_mnt_ns)
 {
 	for (struct mount *p = subtree; p; p = next_mnt(p, subtree))
-		if (mnt_ns_loop(p->mnt.mnt_root))
+		if (mnt_ns_loop_target(p->mnt.mnt_root, target_mnt_ns))
 			return false;
 	return true;
 }
@@ -2464,7 +2471,7 @@ struct vfsmount *clone_private_mount(const struct path *path)
 		if (!anon_ns_root(old_mnt))
 			return ERR_PTR(-EINVAL);
 
-		if (!check_for_nsfs_mounts(old_mnt))
+		if (!check_for_nsfs_mounts(old_mnt, current->nsproxy->mnt_ns))
 			return ERR_PTR(-EINVAL);
 	}
 
@@ -2564,12 +2571,15 @@ int count_mounts(struct mnt_namespace *ns, struct mount *mnt)
 enum mnt_tree_flags_t {
 	MNT_TREE_BENEATH = BIT(0),
 	MNT_TREE_PROPAGATION = BIT(1),
+	MNT_TREE_MNTNS = BIT(2),
+	MNT_TREE_MNTNS_INIT = BIT(3),
 };
 
 /**
  * attach_recursive_mnt - attach a source mount tree
  * @source_mnt: mount tree to be attached
  * @dest:	the context for mounting at the place where the tree should go
+ * @move_mntns:	whether @source_mnt is attached via MOVE_MOUNT_T_MNTNS
  *
  *  NOTE: in the table below explains the semantics when a source mount
  *  of a given type is attached to a destination mount of a given type.
@@ -2632,7 +2642,8 @@ enum mnt_tree_flags_t {
  *         Otherwise a negative error code is returned.
  */
 static int attach_recursive_mnt(struct mount *source_mnt,
-				const struct pinned_mountpoint *dest)
+				const struct pinned_mountpoint *dest,
+				bool move_mntns)
 {
 	struct mount *dest_mnt = dest->parent;
 	struct mountpoint *dest_mp = dest->mp;
@@ -2641,6 +2652,7 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 	struct user_namespace *user_ns = ns->user_ns;
 	struct pinned_mountpoint root = {};
 	struct mountpoint *shorter = NULL;
+	struct mnt_namespace *src_ns;
 	struct mount *child, *p;
 	struct mount *top;
 	struct hlist_node *n;
@@ -2662,6 +2674,9 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 		user_ns = current->nsproxy->mnt_ns->user_ns;
 	else
 		user_ns = ns->user_ns;
+	src_ns = moving ? NULL : source_mnt->mnt_ns;
+	if (move_mntns && src_ns)
+		user_ns = src_ns->user_ns;
 
 	/*
 	 * Preallocate a mountpoint in case the new mounts need to be
@@ -2728,8 +2743,12 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 		struct mount *q;
 		hlist_del_init(&child->mnt_hash);
 		/* Notice when we are propagating across user namespaces */
-		if (child->mnt_parent->mnt_ns->user_ns != user_ns)
+		if (child->mnt_parent->mnt_ns->user_ns != user_ns) {
 			lock_mnt_tree(child);
+			if ((move_mntns || is_anon_ns(ns)) &&
+			    list_empty(&child->mnt_expire))
+				child->mnt.mnt_flags |= MNT_LOCKED;
+		}
 		q = __lookup_mnt(&child->mnt_parent->mnt,
 				 child->mnt_mountpoint);
 		commit_tree(child);
@@ -2937,7 +2956,7 @@ static int graft_tree(struct mount *mnt, const struct pinned_mountpoint *mp)
 	      d_is_dir(mnt->mnt.mnt_root))
 		return -ENOTDIR;
 
-	return attach_recursive_mnt(mnt, mp);
+	return attach_recursive_mnt(mnt, mp, false);
 }
 
 static int may_change_propagation(const struct mount *m)
@@ -3131,7 +3150,7 @@ static int do_loopback(const struct path *path, const char *old_name,
 		return PTR_ERR(mnt);
 
 	/* the copy may carry mount namespace files from below the source */
-	if (recurse && !check_for_nsfs_mounts(mnt))
+	if (recurse && !check_for_nsfs_mounts(mnt, current->nsproxy->mnt_ns))
 		err = -EINVAL;
 	else
 		err = graft_tree(mnt, &mp);
@@ -3776,9 +3795,11 @@ static inline bool may_use_mount(struct mount *mnt)
 
 static int do_move_mount(const struct path *old_path,
 			 const struct path *new_path,
-			 enum mnt_tree_flags_t flags)
+			 enum mnt_tree_flags_t flags,
+			 struct mnt_namespace *target_mnt_ns)
 {
 	struct mount *old = real_mount(old_path->mnt);
+	struct mnt_namespace *dest_mnt_ns;
 	int err;
 	bool beneath = flags & MNT_TREE_BENEATH;
 
@@ -3792,7 +3813,29 @@ 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) {
+		u64 seq;
+
+		if (!anon_ns_root(old) || old->mnt_ns == mp.parent->mnt_ns ||
+		    mp.parent->mnt_ns != target_mnt_ns)
+			return -EINVAL;
+		seq = old->mnt_ns->seq_origin;
+		if (seq && seq != target_mnt_ns->ns.ns_id &&
+		    seq != current->nsproxy->mnt_ns->ns.ns_id)
+			return -EINVAL;
+		if (flags & MNT_TREE_MNTNS_INIT) {
+			if (mp.parent != target_mnt_ns->root)
+				return -EBUSY;
+		} else if (mp.mp->m_dentry == mp.parent->mnt.mnt_root) {
+			const struct mount *m = mp.parent;
+
+			while (m != target_mnt_ns->root && mnt_has_parent(m) &&
+			       m->mnt_mountpoint == m->mnt_parent->mnt.mnt_root)
+				m = m->mnt_parent;
+			if (m == target_mnt_ns->root)
+				return beneath ? -EINVAL : -EBUSY;
+		}
+	} else if (check_mnt(old)) {
 		/* if the source is in our namespace... */
 		/* ... it should be detachable from parent */
 		if (!mnt_has_parent(old) || IS_MNT_LOCKED(old))
@@ -3840,12 +3883,14 @@ static int do_move_mount(const struct path *old_path,
 	 */
 	if (IS_MNT_SHARED(mp.parent) && tree_contains_unbindable(old))
 		return -EINVAL;
-	if (!check_for_nsfs_mounts(old))
+	dest_mnt_ns = is_anon_ns(mp.parent->mnt_ns) ?
+		      current->nsproxy->mnt_ns : mp.parent->mnt_ns;
+	if (!check_for_nsfs_mounts(old, dest_mnt_ns))
 		return -ELOOP;
 	if (mount_is_ancestor(old, mp.parent))
 		return -ELOOP;
 
-	return attach_recursive_mnt(old, &mp);
+	return attach_recursive_mnt(old, &mp, flags & MNT_TREE_MNTNS);
 }
 
 static int do_move_mount_old(const struct path *path, const char *old_name)
@@ -3860,7 +3905,7 @@ static int do_move_mount_old(const struct path *path, const char *old_name)
 	if (err)
 		return err;
 
-	return do_move_mount(&old_path, path, 0);
+	return do_move_mount(&old_path, path, 0, NULL);
 }
 
 /*
@@ -4725,7 +4770,8 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 
 static inline int vfs_move_mount(const struct path *from_path,
 				 const struct path *to_path,
-				 enum mnt_tree_flags_t mflags)
+				 enum mnt_tree_flags_t mflags,
+				 struct mnt_namespace *target_mnt_ns)
 {
 	int ret;
 
@@ -4736,7 +4782,123 @@ static inline int vfs_move_mount(const struct path *from_path,
 	if (mflags & MNT_TREE_PROPAGATION)
 		return do_set_group(from_path, to_path);
 
-	return do_move_mount(from_path, to_path, mflags);
+	return do_move_mount(from_path, to_path, mflags, target_mnt_ns);
+}
+
+static int lookup_move_mount_from(int from_dfd,
+				  const char __user *from_pathname,
+				  unsigned int flags, struct path *from_path)
+{
+	unsigned int uflags = 0;
+	unsigned int lflags = 0;
+
+	if (flags & MOVE_MOUNT_F_EMPTY_PATH)
+		uflags = AT_EMPTY_PATH;
+
+	CLASS(filename_maybe_null, from_name)(from_pathname, uflags);
+	if (!from_name && from_dfd >= 0) {
+		CLASS(fd_raw, f_from)(from_dfd);
+		if (fd_empty(f_from))
+			return -EBADF;
+
+		*from_path = fd_file(f_from)->f_path;
+		path_get(from_path);
+		return 0;
+	}
+
+	if (flags & MOVE_MOUNT_F_SYMLINKS)
+		lflags |= LOOKUP_FOLLOW;
+	if (flags & MOVE_MOUNT_F_AUTOMOUNTS)
+		lflags |= LOOKUP_AUTOMOUNT;
+	return filename_lookup(from_dfd, from_name, lflags, from_path, NULL);
+}
+
+/**
+ * DOC: MOVE_MOUNT_T_MNTNS
+ *
+ * ``MOVE_MOUNT_T_MNTNS`` installs detached anonymous mount trees into a target
+ * mount namespace ``nsfs`` file descriptor supplied as ``to_dfd``:
+ *
+ * 1. ``to_pathname`` of ``"/"`` attaches the initial root mount onto the
+ *    ``nullfs`` root of an empty mount namespace at most once.
+ *
+ * 2. Relative ``to_pathname`` values resolve beneath the live root of the
+ *    target mount namespace.
+ *
+ * Capability is checked against ``CAP_SYS_ADMIN`` in the target mount
+ * namespace's owning user namespace, and source trees crossing user namespace
+ * boundaries are locked with ``MNT_LOCKED`` and locked mount flags.
+ */
+static int move_mount_mntns(int from_dfd, const char __user *from_pathname,
+			    int to_dfd, const char __user *to_pathname,
+			    unsigned int flags, enum mnt_tree_flags_t mflags)
+{
+	struct path from_path __free(path_put) = {};
+	struct path to_path __free(path_put) = {};
+	struct mnt_namespace *target_mnt_ns;
+	unsigned int lflags;
+	struct ns_common *ns;
+	bool is_root;
+	int ret;
+
+	CLASS(filename_maybe_null, to_name)(to_pathname, AT_EMPTY_PATH);
+	if (IS_ERR(to_name))
+		return PTR_ERR(to_name);
+	if (!to_name)
+		return -EINVAL;
+
+	CLASS(fd, f_mntns)(to_dfd);
+	if (fd_empty(f_mntns))
+		return -EBADF;
+	if (!proc_ns_file(fd_file(f_mntns)))
+		return -EINVAL;
+
+	ns = get_proc_ns(file_inode(fd_file(f_mntns)));
+	if (ns->ns_type != CLONE_NEWNS)
+		return -EINVAL;
+
+	target_mnt_ns = to_mnt_ns(ns);
+	if (is_anon_ns(target_mnt_ns))
+		return -EINVAL;
+	if (!ns_capable(target_mnt_ns->user_ns, CAP_SYS_ADMIN))
+		return -EPERM;
+
+	is_root = to_name->name[0] == '/' && to_name->name[1] == '\0';
+	if (is_root) {
+		if (flags & MOVE_MOUNT_BENEATH)
+			return -EINVAL;
+
+		to_path.mnt = mntget(&target_mnt_ns->root->mnt);
+		to_path.dentry = dget(target_mnt_ns->root->mnt.mnt_root);
+		mflags |= MNT_TREE_MNTNS_INIT;
+	} else {
+		struct path mntns_root __free(path_put) = {};
+
+		if (to_name->name[0] == '/')
+			return -EINVAL;
+
+		ret = mnt_ns_get_root(target_mnt_ns, &mntns_root);
+		if (ret)
+			return ret;
+
+		lflags = LOOKUP_IN_ROOT;
+		if (flags & MOVE_MOUNT_T_SYMLINKS)
+			lflags |= LOOKUP_FOLLOW;
+		if (flags & MOVE_MOUNT_T_AUTOMOUNTS)
+			lflags |= LOOKUP_AUTOMOUNT;
+		ret = filename_lookup(AT_FDCWD, to_name, lflags, &to_path,
+				      &mntns_root);
+		if (ret)
+			return ret;
+	}
+
+	ret = lookup_move_mount_from(from_dfd, from_pathname, flags,
+				     &from_path);
+	if (ret)
+		return ret;
+
+	return vfs_move_mount(&from_path, &to_path, mflags | MNT_TREE_MNTNS,
+			      target_mnt_ns);
 }
 
 /*
@@ -4758,7 +4920,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)
@@ -4771,6 +4933,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;
@@ -4794,29 +4963,12 @@ SYSCALL_DEFINE5(move_mount,
 			return ret;
 	}
 
-	uflags = 0;
-	if (flags & MOVE_MOUNT_F_EMPTY_PATH)
-		uflags = AT_EMPTY_PATH;
-
-	CLASS(filename_maybe_null,from_name)(from_pathname, uflags);
-	if (!from_name && from_dfd >= 0) {
-		CLASS(fd_raw, f_from)(from_dfd);
-		if (fd_empty(f_from))
-			return -EBADF;
-
-		return vfs_move_mount(&fd_file(f_from)->f_path, &to_path, mflags);
-	}
-
-	lflags = 0;
-	if (flags & MOVE_MOUNT_F_SYMLINKS)
-		lflags |= LOOKUP_FOLLOW;
-	if (flags & MOVE_MOUNT_F_AUTOMOUNTS)
-		lflags |= LOOKUP_AUTOMOUNT;
-	ret = filename_lookup(from_dfd, from_name, lflags, &from_path, NULL);
+	ret = lookup_move_mount_from(from_dfd, from_pathname, flags,
+				     &from_path);
 	if (ret)
 		return ret;
 
-	return vfs_move_mount(&from_path, &to_path, mflags);
+	return vfs_move_mount(&from_path, &to_path, mflags, NULL);
 }
 
 /*
include/uapi/linux/mount.h +2 -1
index ac865edac517..7d413418426a 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
#15 lore raw

RFC PATCH v5 7/25 mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS

In reply to Jarkko Sakkinen

Unprivileged container managers cannot use open_tree(OPEN_TREE_CLONE) in the host mount namespace because it requires may_mount() against the caller's current mount namespace rather than the destination namespace.

Add MOVE_MOUNT_CLONE for use with MOVE_MOUNT_T_MNTNS so move_mount() can recursively loopback-clone a path from the caller's mount namespace directly into the target mount namespace file descriptor. Authorize the operation against CAP_SYS_ADMIN in target_mnt_ns->user_ns, apply CL_SLAVE | CL_COPY_UNBINDABLE when crossing user namespace boundaries, and lock cross-user-namespace cloned subtrees with MNT_LOCKED inside attach_recursive_mnt().

---
 fs/namespace.c             | 106 +++++++++++++++++++++++++++----------
 include/uapi/linux/mount.h |   3 +-
 2 files changed, 80 insertions(+), 29 deletions(-)
fs/namespace.c +78 -28
index b65f1fdd9281..1e7d776c0966 100644
@@ -2573,13 +2573,15 @@ enum mnt_tree_flags_t {
 	MNT_TREE_PROPAGATION = BIT(1),
 	MNT_TREE_MNTNS = BIT(2),
 	MNT_TREE_MNTNS_INIT = BIT(3),
+	MNT_TREE_CLONE = BIT(4),
 };
 
 /**
  * attach_recursive_mnt - attach a source mount tree
  * @source_mnt: mount tree to be attached
  * @dest:	the context for mounting at the place where the tree should go
- * @move_mntns:	whether @source_mnt is attached via MOVE_MOUNT_T_MNTNS
+ * @src_user_ns: owning user namespace of @source_mnt for MOVE_MOUNT_T_MNTNS,
+ *               or NULL
  *
  *  NOTE: in the table below explains the semantics when a source mount
  *  of a given type is attached to a destination mount of a given type.
@@ -2643,7 +2645,7 @@ enum mnt_tree_flags_t {
  */
 static int attach_recursive_mnt(struct mount *source_mnt,
 				const struct pinned_mountpoint *dest,
-				bool move_mntns)
+				struct user_namespace *src_user_ns)
 {
 	struct mount *dest_mnt = dest->parent;
 	struct mountpoint *dest_mp = dest->mp;
@@ -2652,7 +2654,6 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 	struct user_namespace *user_ns = ns->user_ns;
 	struct pinned_mountpoint root = {};
 	struct mountpoint *shorter = NULL;
-	struct mnt_namespace *src_ns;
 	struct mount *child, *p;
 	struct mount *top;
 	struct hlist_node *n;
@@ -2670,13 +2671,12 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 	 * the attaching task's mount namespace is authoritative, not
 	 * the creator of the detached tree.
 	 */
-	if (is_anon_ns(ns))
+	if (src_user_ns)
+		user_ns = src_user_ns;
+	else if (is_anon_ns(ns))
 		user_ns = current->nsproxy->mnt_ns->user_ns;
 	else
 		user_ns = ns->user_ns;
-	src_ns = moving ? NULL : source_mnt->mnt_ns;
-	if (move_mntns && src_ns)
-		user_ns = src_ns->user_ns;
 
 	/*
 	 * Preallocate a mountpoint in case the new mounts need to be
@@ -2745,7 +2745,7 @@ 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 ((move_mntns || is_anon_ns(ns)) &&
+			if ((src_user_ns || is_anon_ns(ns)) &&
 			    list_empty(&child->mnt_expire))
 				child->mnt.mnt_flags |= MNT_LOCKED;
 		}
@@ -2956,7 +2956,7 @@ static int graft_tree(struct mount *mnt, const struct pinned_mountpoint *mp)
 	      d_is_dir(mnt->mnt.mnt_root))
 		return -ENOTDIR;
 
-	return attach_recursive_mnt(mnt, mp, false);
+	return attach_recursive_mnt(mnt, mp, NULL);
 }
 
 static int may_change_propagation(const struct mount *m)
@@ -3799,29 +3799,27 @@ static int do_move_mount(const struct path *old_path,
 			 struct mnt_namespace *target_mnt_ns)
 {
 	struct mount *old = real_mount(old_path->mnt);
+	struct user_namespace *src_user_ns = NULL;
+	struct mount *cloned = NULL;
 	struct mnt_namespace *dest_mnt_ns;
 	int err;
 	bool beneath = flags & MNT_TREE_BENEATH;
 
-	if (!path_mounted(old_path))
+	if (!(flags & MNT_TREE_CLONE) && !path_mounted(old_path))
 		return -EINVAL;
 
 	if (d_is_dir(new_path->dentry) != d_is_dir(old_path->dentry))
 		return -EINVAL;
 
+	if ((flags & MNT_TREE_CLONE) && mnt_ns_loop(old_path->dentry))
+		return -EINVAL;
+
 	LOCK_MOUNT_MAYBE_BENEATH(mp, new_path, beneath);
 	if (IS_ERR(mp.parent))
 		return PTR_ERR(mp.parent);
 
 	if (flags & MNT_TREE_MNTNS) {
-		u64 seq;
-
-		if (!anon_ns_root(old) || old->mnt_ns == mp.parent->mnt_ns ||
-		    mp.parent->mnt_ns != target_mnt_ns)
-			return -EINVAL;
-		seq = old->mnt_ns->seq_origin;
-		if (seq && seq != target_mnt_ns->ns.ns_id &&
-		    seq != current->nsproxy->mnt_ns->ns.ns_id)
+		if (mp.parent->mnt_ns != target_mnt_ns)
 			return -EINVAL;
 		if (flags & MNT_TREE_MNTNS_INIT) {
 			if (mp.parent != target_mnt_ns->root)
@@ -3835,6 +3833,35 @@ static int do_move_mount(const struct path *old_path,
 			if (m == target_mnt_ns->root)
 				return beneath ? -EINVAL : -EBUSY;
 		}
+		if (flags & MNT_TREE_CLONE) {
+			unsigned int copy_flags;
+
+			if (!check_mnt(old) || old->mnt_ns == target_mnt_ns)
+				return -EINVAL;
+			src_user_ns = old->mnt_ns->user_ns;
+			copy_flags = (target_mnt_ns->user_ns != src_user_ns) ?
+				     (CL_SLAVE | CL_COPY_UNBINDABLE) :
+				     CL_COPY_MNT_NS_FILE;
+			cloned = __do_loopback(old_path, true, copy_flags);
+			if (IS_ERR(cloned))
+				return PTR_ERR(cloned);
+			old = cloned;
+			if (d_is_symlink(old->mnt.mnt_root)) {
+				err = -EINVAL;
+				goto out_cloned;
+			}
+		} else {
+			u64 seq;
+
+			if (!anon_ns_root(old) ||
+			    old->mnt_ns == mp.parent->mnt_ns)
+				return -EINVAL;
+			seq = old->mnt_ns->seq_origin;
+			if (seq && seq != target_mnt_ns->ns.ns_id &&
+			    seq != current->nsproxy->mnt_ns->ns.ns_id)
+				return -EINVAL;
+			src_user_ns = old->mnt_ns->user_ns;
+		}
 	} else if (check_mnt(old)) {
 		/* if the source is in our namespace... */
 		/* ... it should be detachable from parent */
@@ -3874,23 +3901,36 @@ static int do_move_mount(const struct path *old_path,
 			over = mp.parent->overmount;
 		err = can_move_mount_beneath(old, over, &mp);
 		if (err)
-			return err;
+			goto out_cloned;
 	}
 
 	/*
 	 * Don't move a mount tree containing unbindable mounts to a destination
 	 * mount which is shared.
 	 */
-	if (IS_MNT_SHARED(mp.parent) && tree_contains_unbindable(old))
-		return -EINVAL;
+	if (IS_MNT_SHARED(mp.parent) && tree_contains_unbindable(old)) {
+		err = -EINVAL;
+		goto out_cloned;
+	}
 	dest_mnt_ns = is_anon_ns(mp.parent->mnt_ns) ?
 		      current->nsproxy->mnt_ns : mp.parent->mnt_ns;
-	if (!check_for_nsfs_mounts(old, dest_mnt_ns))
-		return -ELOOP;
-	if (mount_is_ancestor(old, mp.parent))
-		return -ELOOP;
+	if (!check_for_nsfs_mounts(old, dest_mnt_ns)) {
+		err = -ELOOP;
+		goto out_cloned;
+	}
+	if (mount_is_ancestor(old, mp.parent)) {
+		err = -ELOOP;
+		goto out_cloned;
+	}
 
-	return attach_recursive_mnt(old, &mp, flags & MNT_TREE_MNTNS);
+	err = attach_recursive_mnt(old, &mp, src_user_ns);
+out_cloned:
+	if (err && cloned) {
+		lock_mount_hash();
+		umount_tree(cloned, UMOUNT_SYNC);
+		unlock_mount_hash();
+	}
+	return err;
 }
 
 static int do_move_mount_old(const struct path *path, const char *old_name)
@@ -4816,8 +4856,8 @@ static int lookup_move_mount_from(int from_dfd,
 /**
  * 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``:
+ * ``MOVE_MOUNT_T_MNTNS`` installs 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.
@@ -4825,6 +4865,11 @@ static int lookup_move_mount_from(int from_dfd,
  * 2. Relative ``to_pathname`` values resolve beneath the live root of the
  *    target mount namespace.
  *
+ * 3. Combining ``MOVE_MOUNT_CLONE`` with ``MOVE_MOUNT_T_MNTNS`` recursively
+ *    loopback-clones ``from_pathname`` from the caller's mount namespace into
+ *    ``to_dfd`` without requiring ``OPEN_TREE_CLONE`` or ``may_mount()`` in
+ *    the caller's own 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.
@@ -4926,12 +4971,17 @@ SYSCALL_DEFINE5(move_mount,
 	if (flags & ~MOVE_MOUNT__MASK)
 		return -EINVAL;
 
+	if ((flags & MOVE_MOUNT_CLONE) && !(flags & MOVE_MOUNT_T_MNTNS))
+		return -EINVAL;
+
 	if ((flags & (MOVE_MOUNT_BENEATH | MOVE_MOUNT_SET_GROUP)) ==
 	    (MOVE_MOUNT_BENEATH | MOVE_MOUNT_SET_GROUP))
 		return -EINVAL;
 
 	if (flags & MOVE_MOUNT_SET_GROUP)	mflags |= MNT_TREE_PROPAGATION;
 	if (flags & MOVE_MOUNT_BENEATH)		mflags |= MNT_TREE_BENEATH;
+	if (flags & MOVE_MOUNT_CLONE)
+		mflags |= MNT_TREE_CLONE;
 
 	if (unlikely(flags & MOVE_MOUNT_T_MNTNS)) {
 		if (flags & (MOVE_MOUNT_T_EMPTY_PATH | MOVE_MOUNT_SET_GROUP))
include/uapi/linux/mount.h +2 -1
index 7d413418426a..cb4f7175db02 100644
@@ -78,7 +78,8 @@
 #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		0x000003f7
+#define MOVE_MOUNT_CLONE		0x00000400 /* Recursively clone from path */
+#define MOVE_MOUNT__MASK		0x000007f7
 
 /*
  * fsopen() flags.
Signature · 1 line
2.47.3
#17 lore raw

RFC PATCH v5 8/25 userns: Factor out install_user_ns_cred()

In reply to Jarkko Sakkinen

userns_install() updates a credential's owning user namespace and rebinds its ucounts inline, which cannot be reused by fork paths that switch a newly allocated child credential into a target user namespace.

Factor this logic out into install_user_ns_cred() with a !CONFIG_USER_NS stub so callers outside kernel/user_namespace.c can install a target user namespace on a prepared struct cred.

---
 include/linux/user_namespace.h |  7 +++++++
 kernel/user_namespace.c        | 12 ++++++++----
 2 files changed, 15 insertions(+), 4 deletions(-)
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)
 {
kernel/user_namespace.c +8 -4
index d7f2cad388c8..4cf5d802032c 100644
@@ -1632,6 +1632,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);
@@ -1657,10 +1664,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
#18 lore raw

RFC PATCH v5 9/25 nsfs: Add nsproxy_open_namespace()

In reply to Jarkko Sakkinen

Opening nsfs file descriptors currently operates on a live task via procfs or pidfs, preventing callers that own a detached struct nsproxy and struct user_namespace from opening member namespace file descriptors directly.

Add nsproxy_open_namespace() to take a passive reference on the requested namespace type (CLONE_NEWNS, CLONE_NEWCGROUP, CLONE_NEWUTS, CLONE_NEWIPC, CLONE_NEWUSER, CLONE_NEWPID, CLONE_NEWNET, or CLONE_NEWTIME) from a supplied nsproxy and user_ns pair and return an nsfs file descriptor via open_namespace().

---
 fs/nsfs.c            | 64 ++++++++++++++++++++++++++++++++++++++++++++
 include/linux/nsfs.h |  2 ++
 2 files changed, 66 insertions(+)
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 */
Signature · 1 line
2.47.3
#19 lore raw

RFC PATCH v5 10/25 nsproxy: Pass nsproxy to create_new_namespaces()

In reply to Jarkko Sakkinen

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
#20 lore raw

RFC PATCH v5 11/25 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.

---
 include/linux/rootns.h      |  61 ++++++++++++
 include/uapi/linux/rootns.h |  44 +++++++++
 init/Kconfig                |   9 ++
 kernel/Makefile             |   2 +
 kernel/rootns.c             | 187 ++++++++++++++++++++++++++++++++++++
 5 files changed, 303 insertions(+)
 create mode 100644 include/linux/rootns.h
 create mode 100644 include/uapi/linux/rootns.h
 create mode 100644 kernel/rootns.c
include/linux/rootns.h new file +61 -0
new file mode 100644
index 000000000000..dcdba08cfaeb
@@ -0,0 +1,61 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.
+ * Copyright (C) 2026 Opinsys Oy
+ */
+
+#ifndef _LINUX_ROOTNS_H
+#define _LINUX_ROOTNS_H
+
+#include <linux/refcount.h>
+#include <linux/spinlock.h>
+#include <linux/wait.h>
+
+struct file;
+struct nsproxy;
+struct pid;
+struct user_namespace;
+
+enum rootns_state {
+	ROOTNS_INIT	= 0,
+	ROOTNS_FORKING	= 1,
+	ROOTNS_RUNNING	= 2,
+	ROOTNS_DEAD	= 3,
+};
+
+/*
+ * The rootns object.
+ */
+struct rootns {
+	refcount_t		usage;
+	int			exit_code;	/* The exit code of 'init' */
+	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) */
+	spinlock_t		lock;		/* Guards rootns lifecycle state */
+	wait_queue_head_t	waitq;		/* Someone waiting for init to exit waits here */
+	unsigned int		flags;		/* Validated rootns() flags */
+	enum rootns_state	state;		/* Root namespace lifecycle state */
+};
+
+#ifdef CONFIG_ROOTNS
+struct rootns *get_rootns(struct rootns *c);
+void put_rootns(struct rootns *c);
+bool is_rootns_file(struct file *file);
+#else
+static inline struct rootns *get_rootns(struct rootns *c)
+{
+	return NULL;
+}
+
+static inline void put_rootns(struct rootns *c)
+{
+}
+
+static inline bool is_rootns_file(struct file *file)
+{
+	return false;
+}
+#endif /* CONFIG_ROOTNS */
+
+#endif /* _LINUX_ROOTNS_H */
include/uapi/linux/rootns.h new file +44 -0

44 lines not on this page · raw message

init/Kconfig +9 -0
index c8a7cfa60a6e..58eafca2f42a 100644
@@ -1283,6 +1283,15 @@ config NET_NS
 
 endif # NAMESPACES
 
+config ROOTNS
+	bool "Root namespace descriptor support"
+	depends on NAMESPACES && USER_NS && PID_NS && UTS_NS && IPC_NS && NET_NS && CGROUPS
+	help
+	  Allow user space to create and manage isolated namespace sets and
+	  their init process lifecycle through an anonymous-inode control file
+	  descriptor via rootns(), rootns ioctls, FSCONFIG_SET_ROOTNS, and
+	  clone3() with CLONE_INTO_ROOTNS.
+
 config CHECKPOINT_RESTORE
 	bool "Checkpoint/restore support"
 	depends on PROC_FS
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 +187 -0

187 lines not on this page · raw message

Signature · 1 line
2.47.3
#21 lore raw

RFC PATCH v5 12/25 rootns: Track init lifecycle via copy_process() and pid_namespace

In reply to Jarkko Sakkinen

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

Commit the bootstrap child reaper and bind pid_ns->rootns 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               | 37 +++++++++++++++++++++++++++++++++++
 5 files changed, 61 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 dcdba08cfaeb..6add4dd55550 100644
@@ -14,6 +14,8 @@
 struct file;
 struct nsproxy;
 struct pid;
+struct pid_namespace;
+struct task_struct;
 struct user_namespace;
 
 enum rootns_state {
@@ -42,6 +44,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)
 {
@@ -56,6 +61,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 +37 -0
index 033e0aae386f..fd8ce59de61a 100644
@@ -185,3 +185,40 @@ bool is_rootns_file(struct file *file)
 {
 	return file->f_op == &rootns_fops;
 }
+
+void copy_rootns(struct task_struct *tsk, struct pid *pid, struct rootns *c)
+{
+	if (likely(!c || !is_child_reaper(pid)))
+		return;
+
+	scoped_guard(spinlock, &c->lock) {
+		if (c->state != ROOTNS_FORKING)
+			return;
+		ns_of_pid(pid)->rootns = get_rootns(c);
+		WRITE_ONCE(c->init_pid, get_pid(pid));
+		WRITE_ONCE(c->state, ROOTNS_RUNNING);
+	}
+}
+
+void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk)
+{
+	struct rootns *c = pid_ns->rootns;
+	struct task_struct *leader;
+	int status;
+
+	if (!c)
+		return;
+
+	leader = tsk->group_leader;
+	status = (tsk->signal->flags & SIGNAL_GROUP_EXIT) ?
+		 tsk->signal->group_exit_code : leader->exit_code;
+
+	scoped_guard(spinlock, &c->lock) {
+		c->exit_code = status;
+		WRITE_ONCE(c->state, ROOTNS_DEAD);
+	}
+
+	pid_ns->rootns = NULL;
+	__wake_up(&c->waitq, TASK_NORMAL, 0, poll_to_key(EPOLLHUP));
+	put_rootns(c);
+}
Signature · 1 line
2.47.3
#24 lore raw

RFC PATCH v5 13/25 rootns: Add rootns() system call

In reply to Jarkko Sakkinen

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

Add the rootns() system call to allocate a detached rootns instance owning a fresh user namespace alongside dedicated empty mount (CLONE_EMPTY_MNTNS), PID, UTS, IPC, network, cgroup, and time namespaces, and return its control file descriptor. Finalize the nsproxy time namespace and pin active references for the lifetime of the rootns.

---
 include/linux/syscalls.h       |   1 +
 include/linux/time_namespace.h |  13 ++++
 kernel/rootns.c                | 106 +++++++++++++++++++++++++++++++++
 kernel/sys_ni.c                |   3 +
 4 files changed, 123 insertions(+)
include/linux/syscalls.h +1 -0
index 72308cc11908..8284bce1c31e 100644
@@ -1010,6 +1010,7 @@ asmlinkage long sys_lsm_get_self_attr(unsigned int attr, struct lsm_ctx __user *
 asmlinkage long sys_lsm_set_self_attr(unsigned int attr, struct lsm_ctx __user *ctx,
 				      u32 size, u32 flags);
 asmlinkage long sys_lsm_list_modules(u64 __user *ids, u32 __user *size, u32 flags);
+asmlinkage long sys_rootns(unsigned int flags);
 
 /*
  * Architecture-specific system calls
include/linux/time_namespace.h +13 -0
index 58bd9728df58..bdc185543893 100644
@@ -60,6 +60,15 @@ static inline void put_time_ns(struct time_namespace *ns)
 		free_time_ns(ns);
 }
 
+static inline void timens_activate_nsproxy(struct nsproxy *nsproxy)
+{
+	if (nsproxy->time_ns != nsproxy->time_ns_for_children) {
+		get_time_ns(nsproxy->time_ns_for_children);
+		put_time_ns(nsproxy->time_ns);
+		nsproxy->time_ns = nsproxy->time_ns_for_children;
+	}
+}
+
 void proc_timens_show_offsets(struct task_struct *p, struct seq_file *m);
 
 struct proc_timens_offset {
@@ -125,6 +134,10 @@ static inline void put_time_ns(struct time_namespace *ns)
 {
 }
 
+static inline void timens_activate_nsproxy(struct nsproxy *nsproxy)
+{
+}
+
 static inline
 struct time_namespace *copy_time_ns(u64 flags,
 				    struct user_namespace *user_ns,
kernel/rootns.c +106 -0

109 lines not on this page · raw message

kernel/sys_ni.c +3 -0
index e3202e7cc2a1..f095401bed24 100644
@@ -399,3 +399,6 @@ COND_SYSCALL(rseq_slice_yield);
 
 COND_SYSCALL(uretprobe);
 COND_SYSCALL(uprobe);
+
+/* kernel/rootns.c */
+COND_SYSCALL(rootns);
Signature · 1 line
2.47.3
#29 lore raw

RFC PATCH v5 14/25 rootns: Add ROOTNS_WAIT ioctl

In reply to Jarkko Sakkinen

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

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

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

67 lines not on this page · raw message

Signature · 1 line
2.47.3
#33 lore raw

RFC PATCH v5 15/25 rootns: Add ROOTNS_KILL ioctl

In reply to Jarkko Sakkinen

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

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

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

70 lines not on this page · raw message

Signature · 1 line
2.47.3
#36 lore raw

RFC PATCH v5 16/25 fork: Support CLONE_INTO_ROOTNS in clone3()

In reply to Jarkko Sakkinen

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

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

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

---
 include/linux/cred.h       |   4 +-
 include/linux/nsproxy.h    |   4 +-
 include/linux/rootns.h     |  14 ++++
 include/linux/sched/task.h |   8 +++
 include/uapi/linux/sched.h |   5 ++
 kernel/cred.c              |  32 ++++++++-
 kernel/fork.c              |  94 ++++++++++++++++++++++---
 kernel/nsproxy.c           |  11 ++-
 kernel/rootns.c            | 140 +++++++++++++++++++++++++++++++++++++
 9 files changed, 298 insertions(+), 14 deletions(-)
include/linux/cred.h +3 -1
index 49c26af37349..9849366fd44b 100644
@@ -19,6 +19,7 @@
 
 struct cred;
 struct inode;
+struct rootns;
 
 extern struct task_struct init_task;
 
@@ -152,7 +153,8 @@ struct cred {
 
 extern void __put_cred(struct cred *);
 extern void exit_creds(struct task_struct *);
-extern int copy_creds(struct task_struct *, u64);
+int copy_creds(struct task_struct *tsk, u64 clone_flags,
+	       struct rootns *rootns);
 extern const struct cred *get_task_cred(struct task_struct *);
 extern struct cred *cred_alloc_blank(void);
 extern struct cred *prepare_creds(void);
include/linux/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 6add4dd55550..68590b27e4ee 100644
@@ -12,6 +12,7 @@
 #include <linux/wait.h>
 
 struct file;
+struct kernel_clone_args;
 struct nsproxy;
 struct pid;
 struct pid_namespace;
@@ -47,6 +48,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)
 {
@@ -71,6 +74,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/uapi/linux/sched.h +5 -0
index 19ffeba89428..405cfc954ae1 100644
@@ -40,6 +40,7 @@
 #define CLONE_NNP		(1ULL << 35) /* Set no_new_privs on child. */
 #define CLONE_PIDFD_AUTOKILL	(1ULL << 36) /* Kill child when clone pidfd closes. */
 #define CLONE_EMPTY_MNTNS	(1ULL << 37) /* Create an empty mount namespace. */
+#define CLONE_INTO_ROOTNS	(1ULL << 38) /* Clone into a specific root namespace. */
 
 /*
  * cloning flags intersect with CSIGNAL so can be used with unshare and clone3
@@ -94,6 +95,8 @@
  *                kernel's limit of nested PID namespaces.
  * @cgroup:       If CLONE_INTO_CGROUP is specified set this to
  *                a file descriptor for the cgroup.
+ * @rootns:       If CLONE_INTO_ROOTNS is specified set this to
+ *                a file descriptor for the root namespace.
  *
  * The structure is versioned by size and thus extensible.
  * New struct members must go at the end of the struct and
@@ -111,12 +114,14 @@ struct clone_args {
 	__aligned_u64 set_tid;
 	__aligned_u64 set_tid_size;
 	__aligned_u64 cgroup;
+	__aligned_u64 rootns;
 };
 #endif
 
 #define CLONE_ARGS_SIZE_VER0 64 /* sizeof first published struct */
 #define CLONE_ARGS_SIZE_VER1 80 /* sizeof second published struct */
 #define CLONE_ARGS_SIZE_VER2 88 /* sizeof third published struct */
+#define CLONE_ARGS_SIZE_VER3 96 /* sizeof fourth published struct */
 
 /*
  * Scheduling policies
kernel/cred.c +31 -1
index d01df40a9a38..48a8852dab4a 100644
@@ -12,13 +12,16 @@
 #include <linux/slab.h>
 #include <linux/sched.h>
 #include <linux/sched/coredump.h>
+#include <linux/sched/exec_state.h>
 #include <linux/key.h>
 #include <linux/keyctl.h>
 #include <linux/init_task.h>
+#include <linux/rootns.h>
 #include <linux/security.h>
 #include <linux/binfmts.h>
 #include <linux/cn_proc.h>
 #include <linux/uidgid.h>
+#include <linux/user_namespace.h>
 
 #if 0
 #define kdebug(FMT, ...)						\
@@ -251,6 +254,9 @@ struct cred *prepare_exec_creds(void)
 	return new;
 }
 
+static bool cred_cap_issubset(const struct cred *set,
+			      const struct cred *subset);
+
 /*
  * Copy credentials for the new process created by fork()
  *
@@ -260,7 +266,8 @@ struct cred *prepare_exec_creds(void)
  * The new process gets the current process's subjective credentials as its
  * objective and subjective credentials
  */
-int copy_creds(struct task_struct *p, u64 clone_flags)
+int copy_creds(struct task_struct *p, u64 clone_flags,
+	       struct rootns *rootns)
 {
 	struct cred *new;
 	int ret;
@@ -287,6 +294,29 @@ int copy_creds(struct task_struct *p, u64 clone_flags)
 	if (!new)
 		return -ENOMEM;
 
+	if (rootns) {
+		const struct cred *old = current_cred();
+
+		if (!ns_capable(rootns->user_ns, CAP_SYS_ADMIN) ||
+		    !ns_capable(rootns->user_ns, CAP_SYS_CHROOT)) {
+			ret = -EPERM;
+			goto error_put;
+		}
+		if (new->user_ns != rootns->user_ns) {
+			ret = install_user_ns_cred(new, rootns->user_ns);
+			if (ret < 0)
+				goto error_put;
+		}
+		if (!cred_cap_issubset(old, new) ||
+		    old->user_ns != new->user_ns) {
+			struct task_exec_state *exec_state;
+
+			exec_state = rcu_dereference_protected(p->exec_state, true);
+			if (exec_state != &init_task_exec_state)
+				WRITE_ONCE(exec_state->dumpable, suid_dumpable);
+		}
+	}
+
 	if (clone_flags & CLONE_NEWUSER) {
 		ret = create_user_ns(new);
 		if (ret < 0)
kernel/fork.c +85 -9

203 lines not on this page · raw message

kernel/nsproxy.c +9 -2
index 8a3c6d4e94e2..78a1e1fb2cfd 100644
@@ -13,6 +13,7 @@
 #include <linux/export.h>
 #include <linux/nsproxy.h>
 #include <linux/ns/ns_common_types.h>
+#include <linux/rootns.h>
 #include <linux/init_task.h>
 #include <linux/mnt_namespace.h>
 #include <linux/utsname.h>
@@ -166,12 +167,18 @@ struct nsproxy *create_new_namespaces(u64 flags,
  * called from clone.  This now handles copy for nsproxy and all
  * namespaces therein.
  */
-int copy_namespaces(u64 flags, struct task_struct *tsk)
+int copy_namespaces(u64 flags, struct task_struct *tsk,
+		    struct rootns *rootns)
 {
 	struct nsproxy *old_ns = tsk->nsproxy;
 	struct user_namespace *user_ns = task_cred_xxx(tsk, user_ns);
 	struct nsproxy *new_ns;
 
+	if (rootns) {
+		get_nsproxy(rootns->ns);
+		tsk->nsproxy = rootns->ns;
+		return 0;
+	}
 	if (likely(!(flags & (CLONE_NS_ALL & ~CLONE_NEWUSER)))) {
 		if ((flags & CLONE_VM) ||
 		    likely(old_ns->time_ns_for_children == old_ns->time_ns)) {
@@ -192,7 +199,7 @@ int copy_namespaces(u64 flags, struct task_struct *tsk)
 		(CLONE_NEWIPC | CLONE_SYSVSEM))
 		return -EINVAL;
 
-	new_ns = create_new_namespaces(flags, tsk->nsproxy, user_ns, tsk->fs);
+	new_ns = create_new_namespaces(flags, old_ns, user_ns, tsk->fs);
 	if (IS_ERR(new_ns))
 		return  PTR_ERR(new_ns);
 
kernel/rootns.c +140 -0

149 lines not on this page · raw message

Signature · 1 line
2.47.3
#38 lore raw

RFC PATCH v5 17/25 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 and network namespaces, preventing an unprivileged external manager from creating superblocks and detached mounts for an unentered root namespace.

Add FSCONFIG_SET_ROOTNS and the ->set_rootns() fs_context operation 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, and keep devpts pty_reserve restricted to host mounts.

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

213 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 +17 -2
index 1e7d776c0966..162ecb52f6eb 100644
@@ -4699,16 +4699,19 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 	struct vfsmount *new_mnt;
 	struct mount *mnt;
 	unsigned int mnt_flags = 0;
+	bool priv;
 	long ret;
 
 	if ((flags & ~(FSMOUNT_CLOEXEC | FSMOUNT_NAMESPACE)) != 0)
 		return -EINVAL;
 
+	priv = may_mount();
 	if ((flags & FSMOUNT_NAMESPACE) &&
 	    !ns_capable(current_user_ns(), CAP_SYS_ADMIN))
 		return -EPERM;
 
-	if (!(flags & FSMOUNT_NAMESPACE) && !may_mount())
+	if (!(flags & FSMOUNT_NAMESPACE) && !IS_ENABLED(CONFIG_ROOTNS) &&
+	    !priv)
 		return -EPERM;
 
 	if (attr_flags & ~FSMOUNT_VALID_FLAGS)
@@ -4743,6 +4746,15 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 	if (ret)
 		return ret;
 
+	if (fc->rootns_bound) {
+		if (flags & FSMOUNT_NAMESPACE)
+			return -EINVAL;
+		if (!ns_capable(fc->user_ns, CAP_SYS_ADMIN))
+			return -EPERM;
+	} else if (!(flags & FSMOUNT_NAMESPACE) && !priv) {
+		return -EPERM;
+	}
+
 	/* There must be a valid superblock or we can't mount it */
 	ret = -EINVAL;
 	if (!fc->root)
@@ -4784,9 +4796,12 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 		return FD_ADD((flags & FSMOUNT_CLOEXEC) ? O_CLOEXEC : 0,
 			      open_new_namespace(&new_path, MOUNT_COPY_NEW));
 
-	ns = alloc_mnt_ns(current->nsproxy->mnt_ns->user_ns, true);
+	ns = alloc_mnt_ns(fc->rootns_bound ? fc->user_ns :
+			  current->nsproxy->mnt_ns->user_ns, true);
 	if (IS_ERR(ns))
 		return PTR_ERR(ns);
+	if (fc->rootns_bound)
+		ns->seq_origin = fc->rootns_mnt_id;
 	mnt = real_mount(new_path.mnt);
 	ns->root = mnt;
 	ns->nr_mounts = 1;
include/linux/fs_context.h +6 -0
index d1727dffecc5..42648bec5cfa 100644
@@ -21,6 +21,7 @@ struct file_system_type;
 struct mnt_namespace;
 struct net;
 struct pid_namespace;
+struct rootns;
 struct super_block;
 struct user_namespace;
 struct vfsmount;
@@ -36,6 +37,8 @@ enum fs_context_purpose {
  * Userspace usage phase for fsopen/fspick.
  */
 enum fs_context_phase {
+	FS_CONTEXT_AWAITING_NS,		/* Unprivileged context awaiting target ns */
+	FS_CONTEXT_CREATE_NS,		/* Set namespaces for sb creation */
 	FS_CONTEXT_CREATE_PARAMS,	/* Loading params for sb creation */
 	FS_CONTEXT_CREATING,		/* A superblock is being created */
 	FS_CONTEXT_AWAITING_MOUNT,	/* Superblock created, awaiting fsmount() */
@@ -101,6 +104,7 @@ struct fs_context {
 	const char		*source;	/* The source name (eg. dev path) */
 	void			*security;	/* LSM options */
 	void			*s_fs_info;	/* Proposed s_fs_info */
+	u64			rootns_mnt_id;	/* Target rootns mnt_ns ID */
 	unsigned int		sb_flags;	/* Proposed superblock flags (SB_*) */
 	unsigned int		sb_flags_mask;	/* Superblock flags that were changed */
 	unsigned int		s_iflags;	/* OR'd with sb->s_iflags */
@@ -110,6 +114,7 @@ struct fs_context {
 	bool			global:1;	/* Goes into &init_user_ns */
 	bool			oldapi:1;	/* Coming from mount(2) */
 	bool			exclusive:1;    /* create new superblock, reject existing one */
+	bool			rootns_bound:1;	/* Bound via FSCONFIG_SET_ROOTNS */
 };
 
 struct fs_context_operations {
@@ -117,6 +122,7 @@ struct fs_context_operations {
 	int (*dup)(struct fs_context *fc, struct fs_context *src_fc);
 	int (*parse_param)(struct fs_context *fc, struct fs_parameter *param);
 	int (*parse_monolithic)(struct fs_context *fc, void *data);
+	int (*set_rootns)(struct fs_context *fc, struct rootns *rootns);
 	int (*get_tree)(struct fs_context *fc);
 	int (*reconfigure)(struct fs_context *fc);
 };
include/uapi/linux/mount.h +1 -0
index cb4f7175db02..5d4d93edb9df 100644
@@ -107,6 +107,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 */
 };
 
 /*
Signature · 1 line
2.47.3
#40 lore raw

RFC PATCH v5 18/25 proc: Implement ->set_rootns() fs_context operation

In reply to Jarkko Sakkinen

proc_init_fs_context() binds ctx->pid_ns to task_active_pid_ns(current) and resets fc->user_ns to ctx->pid_ns->user_ns, overriding the user namespace delegated by FSCONFIG_SET_ROOTNS and leaving the context attached to the caller's PID namespace.

Wire up proc_set_rootns() to verify that the target root namespace's PID namespace is a descendant of the caller's active PID namespace and rebind ctx->pid_ns and fc->user_ns accordingly.

---
 fs/proc/root.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
fs/proc/root.c +22 -0
index 7fbbe92bf73a..8d2b9bbfa1c1 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>
@@ -206,6 +208,10 @@ static int proc_parse_param(struct fs_context *fc, struct fs_parameter *param)
 			errorfc(fc, "cannot reconfigure pidns for existing procfs");
 			return -EBUSY;
 		}
+		if (fc->rootns_bound) {
+			errorfc(fc, "cannot override pidns on rootns-bound procfs");
+			return -EBUSY;
+		}
 		err = proc_parse_pidns_param(fc, param, &result);
 		if (err)
 			return err;
@@ -323,6 +329,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 +355,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,
 };
Signature · 1 line
2.47.3
#41 lore raw

RFC PATCH v5 19/25 ipc/mqueue: Implement ->set_rootns() fs_context operation

In reply to Jarkko Sakkinen

mqueue_init_fs_context() captures current->nsproxy->ipc_ns and resets fc->user_ns to ctx->ipc_ns->user_ns, overriding the user namespace delegated by FSCONFIG_SET_ROOTNS and leaving the context bound to the caller's IPC namespace.

Wire up mqueue_set_rootns() to switch ctx->ipc_ns to the target root namespace's IPC namespace and update fc->user_ns to match.

---
 ipc/mqueue.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
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
#42 lore raw

RFC PATCH v5 20/25 security: Add rootns LSM hooks

In reply to Jarkko Sakkinen

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

Add lbs_rootns and rootns->security blob management alongside security_rootns_alloc(), security_rootns_free(), security_rootns_clone(), and security_rootns_kill().

---
 include/linux/lsm_hook_defs.h |  7 +++
 include/linux/lsm_hooks.h     |  3 ++
 include/linux/rootns.h        |  3 ++
 include/linux/security.h      | 30 ++++++++++++
 kernel/rootns.c               | 44 +++++++++++++-----
 security/lsm_init.c           |  6 +++
 security/security.c           | 86 +++++++++++++++++++++++++++++++++++
 7 files changed, 167 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 68590b27e4ee..1301bc6961f1 100644
@@ -32,6 +32,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/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
#44 lore raw

RFC PATCH v5 21/25 bpf: Register rootns LSM hooks

In reply to Jarkko Sakkinen

BPF LSM programs need sleepable and untrusted hook classifications for the new root namespace LSM hooks in order to attach policies to root namespace allocation, cloning, signaling, and release.

Register bpf_lsm_rootns_alloc, bpf_lsm_rootns_clone, and bpf_lsm_rootns_kill in sleepable_lsm_hooks, and bpf_lsm_rootns_alloc and bpf_lsm_rootns_free in untrusted_lsm_hooks under CONFIG_ROOTNS.

---
 kernel/bpf/bpf_lsm.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
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)
Signature · 1 line
2.47.3
#45 lore raw

RFC PATCH v5 22/25 arch: Wire up rootns() system call

In reply to Jarkko Sakkinen

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

---
 arch/alpha/kernel/syscalls/syscall.tbl      | 1 +
 arch/arm/tools/syscall.tbl                  | 1 +
 arch/arm64/tools/syscall_32.tbl             | 1 +
 arch/m68k/kernel/syscalls/syscall.tbl       | 1 +
 arch/microblaze/kernel/syscalls/syscall.tbl | 1 +
 arch/mips/kernel/syscalls/syscall_n32.tbl   | 1 +
 arch/mips/kernel/syscalls/syscall_n64.tbl   | 1 +
 arch/mips/kernel/syscalls/syscall_o32.tbl   | 1 +
 arch/parisc/kernel/syscalls/syscall.tbl     | 1 +
 arch/powerpc/kernel/syscalls/syscall.tbl    | 1 +
 arch/s390/kernel/syscalls/syscall.tbl       | 1 +
 arch/sh/kernel/syscalls/syscall.tbl         | 1 +
 arch/sparc/kernel/syscalls/syscall.tbl      | 1 +
 arch/x86/entry/syscalls/syscall_32.tbl      | 1 +
 arch/x86/entry/syscalls/syscall_64.tbl      | 1 +
 arch/xtensa/kernel/syscalls/syscall.tbl     | 1 +
 include/uapi/asm-generic/unistd.h           | 6 +++++-
 scripts/syscall.tbl                         | 1 +
 18 files changed, 22 insertions(+), 1 deletion(-)
arch/alpha/kernel/syscalls/syscall.tbl +1 -0
index 9384d59a44dc..2087b83d6d2c 100644
@@ -513,3 +513,4 @@
 581	common	rseq_slice_yield		sys_rseq_slice_yield
 582	common	fchroot				sys_fchroot
 583	common	userns_set_idmap		sys_sys_userns_set_idmap
+584	common	rootns				sys_sys_rootns
arch/arm/tools/syscall.tbl +1 -0
index 6130366b7681..93e609de0bad 100644
@@ -488,3 +488,4 @@
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
 473	common	userns_set_idmap		sys_sys_userns_set_idmap
+474	common	rootns				sys_sys_rootns
arch/arm64/tools/syscall_32.tbl +1 -0
index 3fcc7899fd08..5dd5172b5118 100644
@@ -485,3 +485,4 @@
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
 473	common	userns_set_idmap		sys_sys_userns_set_idmap
+474	common	rootns				sys_sys_rootns
arch/m68k/kernel/syscalls/syscall.tbl +1 -0
index 5607635bd4bd..4fa5db7d1e62 100644
@@ -473,3 +473,4 @@
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
 473	common	userns_set_idmap		sys_sys_userns_set_idmap
+474	common	rootns				sys_sys_rootns
arch/microblaze/kernel/syscalls/syscall.tbl +1 -0
index 97ee93f42fac..5bfe96f7ec5c 100644
@@ -479,3 +479,4 @@
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
 473	common	userns_set_idmap		sys_sys_userns_set_idmap
+474	common	rootns				sys_sys_rootns
arch/mips/kernel/syscalls/syscall_n32.tbl +1 -0
index da4ed57a91d3..e664ef0d1e56 100644
@@ -412,3 +412,4 @@
 471	n32	rseq_slice_yield		sys_rseq_slice_yield
 472	n32	fchroot				sys_fchroot
 473	n32	userns_set_idmap		sys_sys_userns_set_idmap
+474	n32	rootns				sys_sys_rootns
arch/mips/kernel/syscalls/syscall_n64.tbl +1 -0
index 5e9839b6b389..725c0e5a5ab8 100644
@@ -388,3 +388,4 @@
 471	n64	rseq_slice_yield		sys_rseq_slice_yield
 472	n64	fchroot				sys_fchroot
 473	n64	userns_set_idmap		sys_sys_userns_set_idmap
+474	n64	rootns				sys_sys_rootns
arch/mips/kernel/syscalls/syscall_o32.tbl +1 -0
index 290c1b61be47..2c8472b83d23 100644
@@ -461,3 +461,4 @@
 471	o32	rseq_slice_yield		sys_rseq_slice_yield
 472	o32	fchroot				sys_fchroot
 473	o32	userns_set_idmap		sys_sys_userns_set_idmap
+474	o32	rootns				sys_sys_rootns
arch/parisc/kernel/syscalls/syscall.tbl +1 -0
index fc0fa917eb92..0a32c40cfcbe 100644
@@ -472,3 +472,4 @@
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
 473	common	userns_set_idmap		sys_sys_userns_set_idmap
+474	common	rootns				sys_sys_rootns
arch/powerpc/kernel/syscalls/syscall.tbl +1 -0
index d12e49022b23..d2fd229b8da8 100644
@@ -564,3 +564,4 @@
 471	nospu	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
 473	common	userns_set_idmap		sys_sys_userns_set_idmap
+474	nospu	rootns				sys_sys_rootns
arch/s390/kernel/syscalls/syscall.tbl +1 -0
index dc427811d30d..8251cad9530d 100644
@@ -400,3 +400,4 @@
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
 473	common	userns_set_idmap		sys_sys_userns_set_idmap
+474	common	rootns				sys_sys_rootns
arch/sh/kernel/syscalls/syscall.tbl +1 -0
index e62ac9acc7ad..13105c503bf6 100644
@@ -477,3 +477,4 @@
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
 473	common	userns_set_idmap		sys_sys_userns_set_idmap
+474	common	rootns				sys_sys_rootns
arch/sparc/kernel/syscalls/syscall.tbl +1 -0
index df074bf322c4..7542448ab4eb 100644
@@ -519,3 +519,4 @@
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
 473	common	userns_set_idmap		sys_sys_userns_set_idmap
+474	common	rootns				sys_sys_rootns
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 243a3f55834d..35cb517befbf 100644
@@ -479,3 +479,4 @@
 471	i386	rseq_slice_yield	sys_rseq_slice_yield
 472	i386	fchroot			sys_fchroot
 473	i386	userns_set_idmap	sys_sys_userns_set_idmap
+474	i386	rootns			sys_sys_rootns
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index f11700e3af65..387ca7628bae 100644
@@ -398,6 +398,7 @@
 471	common	rseq_slice_yield	sys_rseq_slice_yield
 472	common	fchroot			sys_fchroot
 473	common	userns_set_idmap	sys_sys_userns_set_idmap
+474	common	rootns			sys_sys_rootns
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
arch/xtensa/kernel/syscalls/syscall.tbl +1 -0
index 1d28de95915f..f9869ffeeed1 100644
@@ -444,3 +444,4 @@
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
 473	common	userns_set_idmap		sys_sys_userns_set_idmap
+474	common	rootns				sys_sys_rootns
include/uapi/asm-generic/unistd.h +5 -1
index 695eac2d356b..726b39b6b47c 100644
@@ -871,8 +871,12 @@ __SYSCALL(__NR_fchroot, sys_fchroot)
 #define __NR_userns_set_idmap 473
 __SYSCALL(__NR_userns_set_idmap, sys_userns_set_idmap)
 
+/* kernel/rootns.c */
+#define __NR_rootns 474
+__SYSCALL(__NR_rootns, sys_rootns)
+
 #undef __NR_syscalls
-#define __NR_syscalls 474
+#define __NR_syscalls 475
 
 /*
  * 32 bit systems traditionally used different
scripts/syscall.tbl +1 -0
index 0dddd465d1c5..1670f575d3e4 100644
@@ -414,3 +414,4 @@
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
 473	common	userns_set_idmap		sys_sys_userns_set_idmap
+474	common	rootns				sys_sys_rootns
Signature · 1 line
2.47.3
#47 lore raw

RFC PATCH v5 23/25 docs: Document root namespace uAPI

In reply to Jarkko Sakkinen

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

Add Documentation/userspace-api/rootns.rst to include the kernel-doc sections, ioctl descriptions, and system call reference from kernel/rootns.c, kernel/user_namespace.c, include/uapi/linux/rootns.h, include/uapi/linux/nsfs.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        | 65 +++++++++++++++++++
 3 files changed, 67 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 +65 -0

65 lines not on this page · raw message

Signature · 1 line
2.47.3
#48 lore raw

RFC PATCH v5 24/25 selftests/rootns: Add root namespace test suite

In reply to Jarkko Sakkinen

Verify the root namespace, mount-namespace configuration, and userns_set_idmap() uAPI and security invariants across privileged, unprivileged, SCM_RIGHTS delegation, and edge-case scenarios.

---
 tools/testing/selftests/Makefile              |    1 +
 tools/testing/selftests/rootns/Makefile       |    5 +
 tools/testing/selftests/rootns/config         |   10 +
 .../testing/selftests/rootns/rootns_cells.py  | 1400 ++++++++++++++
 tools/testing/selftests/rootns/rootns_test.py | 1645 +++++++++++++++++
 tools/testing/selftests/rootns/test_smoke.sh  |   10 +
 6 files changed, 3071 insertions(+)
 create mode 100644 tools/testing/selftests/rootns/Makefile
 create mode 100644 tools/testing/selftests/rootns/config
 create mode 100755 tools/testing/selftests/rootns/rootns_cells.py
 create mode 100755 tools/testing/selftests/rootns/rootns_test.py
 create mode 100755 tools/testing/selftests/rootns/test_smoke.sh
tools/testing/selftests/Makefile +1 -0
index 07c3719f8b04..7c44f93e57a4 100644
@@ -117,6 +117,7 @@ TARGETS += rdma
 TARGETS += resctrl
 TARGETS += riscv
 TARGETS += rlimits
+TARGETS += rootns
 TARGETS += rseq
 TARGETS += rtc
 TARGETS += rust
tools/testing/selftests/rootns/Makefile new file +5 -0
new file mode 100644
index 000000000000..62629d112e12
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+include ../lib.mk
+
+TEST_PROGS := test_smoke.sh
+TEST_PROGS_EXTENDED := rootns_cells.py rootns_test.py
tools/testing/selftests/rootns/config new file +10 -0
new file mode 100644
index 000000000000..21b1aecc003b
@@ -0,0 +1,10 @@
+CONFIG_CGROUPS=y
+CONFIG_IPC_NS=y
+CONFIG_NET_NS=y
+CONFIG_PID_NS=y
+CONFIG_PROC_FS=y
+CONFIG_ROOTNS=y
+CONFIG_TIME_NS=y
+CONFIG_TMPFS=y
+CONFIG_USER_NS=y
+CONFIG_UTS_NS=y
tools/testing/selftests/rootns/rootns_cells.py new file +1400 -0

1,400 lines not on this page · raw message

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

1,578 lines not on this page · raw message

tools/testing/selftests/rootns/test_smoke.sh new file +10 -0
new file mode 100755
index 000000000000..729e0c275602

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.47.3

Part of the diff is not shown here. View the raw message.

#49 lore raw

RFC PATCH v5 25/25 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
#30 lore raw

Re: [RFC PATCH v5 14/25] rootns: Add ROOTNS_WAIT ioctl

In reply to Jarkko Sakkinen
Quoted 147 lines · Jarkko Sakkinen

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

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

---
 include/uapi/linux/rootns.h | 26 +++++++++++++++++++++
 kernel/rootns.c             | 46 +++++++++++++++++++++++++++++++++++++
 2 files changed, 72 insertions(+)
include/uapi/linux/rootns.h +26 -0
index bd643bdfb43c..3fd215185398 100644
@@ -8,6 +8,7 @@
 #define _UAPI_LINUX_ROOTNS_H
 
 #include <linux/ioctl.h>
+#include <linux/types.h>
 
 /**
  * enum rootns_flags - Flags for rootns()
@@ -24,6 +25,16 @@ enum rootns_flags {
 	ROOTNS_ALL_FLAGS	= 0x00000003,
 };
 
+/**
+ * struct rootns_wait_args - Arguments for %ROOTNS_WAIT
+ * @flags: Wait options (0 or %WNOHANG).
+ * @status: Output wait status of rootns init in waitpid(2) format.
+ */
+struct rootns_wait_args {
+	__u32 flags;
+	__s32 status;
+};
+
 #define ROOTNS_IOCTL_MAGIC	0xB9
 
 /**
@@ -41,4 +52,19 @@ enum rootns_flags {
  */
 #define ROOTNS_GET_NSFD		_IO(ROOTNS_IOCTL_MAGIC, 0x01)
 
+/**
+ * DOC: ROOTNS_WAIT
+ *
+ * ``ioctl(rootnsfd, ROOTNS_WAIT, &args)`` waits interruptibly (unless
+ * ``WNOHANG`` is set in ``args.flags``) until ``rootnsfd`` reaches
+ * ``ROOTNS_DEAD``, then writes the recorded exit status of ``rootns`` init
+ * into ``args.status``.
+ *
+ * Returns the caller-visible TGID of ``rootns`` init on success, ``0`` if
+ * ``WNOHANG`` is set and the ``rootns`` has not terminated, or ``-1`` with
+ * ``errno`` set to ``ECHILD`` if init was never started or is not visible in
+ * the caller's active PID namespace.
+ */
+#define ROOTNS_WAIT		_IOWR(ROOTNS_IOCTL_MAGIC, 0x02, struct rootns_wait_args)
+
 #endif /* _UAPI_LINUX_ROOTNS_H */
kernel/rootns.c +46 -0
index 5d59fc9a591d..cb74ddc8363c 100644
@@ -117,6 +117,47 @@ static long rootns_get_nsfd(struct rootns *rootns, unsigned long nstype)
 	return nsproxy_open_namespace(rootns->ns, rootns->user_ns, nstype);
 }
 
+static long rootns_wait(struct rootns *rootns, void __user *uarg)
+{
+	struct pid_namespace *pid_ns = task_active_pid_ns(current);
+	struct rootns_wait_args args;
+	long ret;
+
+	if (!uarg)
+		return -EINVAL;
+	if (copy_from_user(&args, uarg, sizeof(args)))
+		return -EFAULT;
+	if (args.flags & ~WNOHANG)
+		return -EINVAL;
+	if (!pidns_is_ancestor(rootns->ns->pid_ns_for_children, pid_ns))
+		return -ECHILD;
+	if (READ_ONCE(rootns->state) == ROOTNS_INIT)
+		return -ECHILD;
+
+	if (!(args.flags & WNOHANG)) {
+		ret = wait_event_freezable(rootns->waitq,
+					   READ_ONCE(rootns->state) == ROOTNS_DEAD ||
+					   READ_ONCE(rootns->state) == ROOTNS_INIT);
+		if (ret)
+			return ret;
+	}
+
+	scoped_guard(spinlock, &rootns->lock) {
+		if (rootns->state == ROOTNS_INIT)
+			return -ECHILD;
+		if (rootns->state != ROOTNS_DEAD)
+			return 0;
+		ret = pid_nr_ns(rootns->init_pid, pid_ns);
+		if (ret <= 0)
+			return -ECHILD;
+		args.status = rootns->exit_code;
+	}
+
+	if (copy_to_user(uarg, &args, sizeof(args)))
+		return -EFAULT;
+	return ret;
+}
+
 static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 {
 	struct rootns *rootns = file->private_data;
@@ -124,6 +165,8 @@ static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 	switch (cmd) {
 	case ROOTNS_GET_NSFD:
 		return rootns_get_nsfd(rootns, arg);
+	case ROOTNS_WAIT:
+		return rootns_wait(rootns, (void __user *)arg);
 	default:
 		return -ENOIOCTLCMD;
 	}
@@ -134,6 +177,8 @@ static long rootns_compat_ioctl(struct file *file, unsigned int cmd,
 				unsigned long arg)
 {
 	switch (cmd) {
+	case ROOTNS_WAIT:
+		return rootns_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
 	case ROOTNS_GET_NSFD:
 		return rootns_ioctl(file, cmd, arg);
 	default:
@@ -328,3 +373,4 @@ SYSCALL_DEFINE1(rootns, unsigned int, flags)
 
 	return fd;
 }
+
Signature · 1 line
2.47.3

Ought to be dropped but seemed too irrelevant detail for the time being.

Br, Jarkko

#31 lore raw

Re: [RFC PATCH v5 14/25] rootns: Add ROOTNS_WAIT ioctl

Quoted 142 lines · Jarkko Sakkinen
Quoted 141 lines · Jarkko Sakkinen

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

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

---
 include/uapi/linux/rootns.h | 26 +++++++++++++++++++++
 kernel/rootns.c             | 46 +++++++++++++++++++++++++++++++++++++
 2 files changed, 72 insertions(+)
include/uapi/linux/rootns.h +26 -0
index bd643bdfb43c..3fd215185398 100644
@@ -8,6 +8,7 @@
 #define _UAPI_LINUX_ROOTNS_H
 
 #include <linux/ioctl.h>
+#include <linux/types.h>
 
 /**
  * enum rootns_flags - Flags for rootns()
@@ -24,6 +25,16 @@ enum rootns_flags {
 	ROOTNS_ALL_FLAGS	= 0x00000003,
 };
 
+/**
+ * struct rootns_wait_args - Arguments for %ROOTNS_WAIT
+ * @flags: Wait options (0 or %WNOHANG).
+ * @status: Output wait status of rootns init in waitpid(2) format.
+ */
+struct rootns_wait_args {
+	__u32 flags;
+	__s32 status;
+};
+
 #define ROOTNS_IOCTL_MAGIC	0xB9
 
 /**
@@ -41,4 +52,19 @@ enum rootns_flags {
  */
 #define ROOTNS_GET_NSFD		_IO(ROOTNS_IOCTL_MAGIC, 0x01)
 
+/**
+ * DOC: ROOTNS_WAIT
+ *
+ * ``ioctl(rootnsfd, ROOTNS_WAIT, &args)`` waits interruptibly (unless
+ * ``WNOHANG`` is set in ``args.flags``) until ``rootnsfd`` reaches
+ * ``ROOTNS_DEAD``, then writes the recorded exit status of ``rootns`` init
+ * into ``args.status``.
+ *
+ * Returns the caller-visible TGID of ``rootns`` init on success, ``0`` if
+ * ``WNOHANG`` is set and the ``rootns`` has not terminated, or ``-1`` with
+ * ``errno`` set to ``ECHILD`` if init was never started or is not visible in
+ * the caller's active PID namespace.
+ */
+#define ROOTNS_WAIT		_IOWR(ROOTNS_IOCTL_MAGIC, 0x02, struct rootns_wait_args)
+
 #endif /* _UAPI_LINUX_ROOTNS_H */
kernel/rootns.c +45 -0
index 5d59fc9a591d..cb74ddc8363c 100644
@@ -117,6 +117,47 @@ static long rootns_get_nsfd(struct rootns *rootns, unsigned long nstype)
 	return nsproxy_open_namespace(rootns->ns, rootns->user_ns, nstype);
 }
 
+static long rootns_wait(struct rootns *rootns, void __user *uarg)
+{
+	struct pid_namespace *pid_ns = task_active_pid_ns(current);
+	struct rootns_wait_args args;
+	long ret;
+
+	if (!uarg)
+		return -EINVAL;
+	if (copy_from_user(&args, uarg, sizeof(args)))
+		return -EFAULT;
+	if (args.flags & ~WNOHANG)
+		return -EINVAL;
+	if (!pidns_is_ancestor(rootns->ns->pid_ns_for_children, pid_ns))
+		return -ECHILD;
+	if (READ_ONCE(rootns->state) == ROOTNS_INIT)
+		return -ECHILD;
+
+	if (!(args.flags & WNOHANG)) {
+		ret = wait_event_freezable(rootns->waitq,
+					   READ_ONCE(rootns->state) == ROOTNS_DEAD ||
+					   READ_ONCE(rootns->state) == ROOTNS_INIT);
+		if (ret)
+			return ret;
+	}
+
+	scoped_guard(spinlock, &rootns->lock) {
+		if (rootns->state == ROOTNS_INIT)
+			return -ECHILD;
+		if (rootns->state != ROOTNS_DEAD)
+			return 0;
+		ret = pid_nr_ns(rootns->init_pid, pid_ns);
+		if (ret <= 0)
+			return -ECHILD;
+		args.status = rootns->exit_code;
+	}
+
+	if (copy_to_user(uarg, &args, sizeof(args)))
+		return -EFAULT;
+	return ret;
+}
+
 static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 {
 	struct rootns *rootns = file->private_data;
@@ -124,6 +165,8 @@ static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 	switch (cmd) {
 	case ROOTNS_GET_NSFD:
 		return rootns_get_nsfd(rootns, arg);
+	case ROOTNS_WAIT:
+		return rootns_wait(rootns, (void __user *)arg);
 	default:
 		return -ENOIOCTLCMD;
 	}
@@ -134,6 +177,8 @@ static long rootns_compat_ioctl(struct file *file, unsigned int cmd,
 				unsigned long arg)
 {
 	switch (cmd) {
+	case ROOTNS_WAIT:
+		return rootns_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
 	case ROOTNS_GET_NSFD:
 		return rootns_ioctl(file, cmd, arg);
 	default:
@@ -328,3 +373,4 @@ SYSCALL_DEFINE1(rootns, unsigned int, flags)
 
Quoted 9 lines
Quoted 6 lines
kernel/rootns.c +1 -0
 	return fd;
 }
+
Signature · 1 line
2.47.3

Ought to be dropped but seemed too irrelevant detail for the time being.

I mean replaced with a syscall path.

Br, Jarkko

#32 lore raw

Re: [RFC PATCH v5 14/25] rootns: Add ROOTNS_WAIT ioctl

Quoted 4 lines · Jarkko Sakkinen
Quoted 2 lines

Ought to be dropped but seemed too irrelevant detail for the time being

I mean replaced with a syscall path.

Yeah, a lot better overall (less fallible paths).

+long rootns_waitid(int upid, struct waitid_info *infop, int options,
+ struct rusage *ru)
{

-       struct pid_namespace *pid_ns = task_active_pid_ns(current);
-       struct rootns_wait_args args;
+       struct pid_namespace *pid_ns;
+       unsigned int f_flags;
+       struct rootns *rootns;
+       bool nonblock;
+       int status;
+       kuid_t uid;
        long ret;

- if (!uarg)
+ if (upid < 0 || ru)

                return -EINVAL;

- if (copy_from_user(&args, uarg, sizeof(args)))
- return -EFAULT;
- if (args.flags & ~WNOHANG)
+ if (options & ~(WEXITED | WNOHANG | WNOWAIT))

                return -EINVAL;

+ if (!(options & WEXITED))
+ return -EINVAL;
+
+ CLASS(fd, f)(upid);
+ if (fd_empty(f) || !is_rootns_file(fd_file(f)))
+ return -EBADF;
+

+       f_flags = READ_ONCE(fd_file(f)->f_flags);
+       nonblock = (options & WNOHANG) || (f_flags & O_NONBLOCK);
+       rootns = fd_file(f)->private_data;
+       pid_ns = task_active_pid_ns(current);
+
        if (!pidns_is_ancestor(rootns->ns->pid_ns_for_children, pid_ns))
                return -ECHILD;
        if (READ_ONCE(rootns->state) == ROOTNS_INIT)
                return -ECHILD;

- if (!(args.flags & WNOHANG)) {

+       if (!nonblock) {
                ret = wait_event_freezable(rootns->waitq,
                                           READ_ONCE(rootns->state) == ROOTNS_DEAD ||
                                           READ_ONCE(rootns->state) == ROOTNS_INIT);
@@ -154,15 +191,23 @@ static long rootns_wait(struct rootns *rootns, void __user *uarg)
                if (rootns->state == ROOTNS_INIT)
                        return -ECHILD;
                if (rootns->state != ROOTNS_DEAD)
-                       return 0;
+                       return (options & WNOHANG) ? 0 : -EAGAIN;
                ret = pid_nr_ns(rootns->init_pid, pid_ns);
                if (ret <= 0)
                        return -ECHILD;
-               args.status = rootns->exit_code;
+               status = rootns->exit_code;
+               uid = rootns->init_uid;
        }

- if (copy_to_user(uarg, &args, sizeof(args)))
- return -EFAULT;
+ if ((status & 0x7f) == 0) {
+ infop->cause = CLD_EXITED;
+ infop->status = status >> 8;
+ } else {
+ infop->cause = (status & 0x80) ? CLD_DUMPED : CLD_KILLED;
+ infop->status = status & 0x7f;

+       }
+       infop->pid = ret;
+       infop->uid = from_kuid_munged(current_user_ns(), uid);
        return ret;

}

Br, Jarkko

#34 lore raw

Re: [RFC PATCH v5 15/25] rootns: Add ROOTNS_KILL ioctl

In reply to Jarkko Sakkinen
Quoted 9 lines · Jarkko Sakkinen

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

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

Will be gone i.e., can do also pidfd_send_signal(fd, signum, NULL, 0).

Br, Jarkko

#22 lore raw

Re: [RFC PATCH v5 12/25] rootns: Track init lifecycle via copy_process() and pid_namespace

In reply to Jarkko Sakkinen
Quoted 5 lines · Jarkko Sakkinen

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

Quoted 8 lines

Commit the bootstrap child reaper and bind pid_ns->rootns 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.

ROOTNS_GET_NSFD will be the only surviving ioctl, which make access control wise sense.

This leaves room for ROOTNS_SHARE_NSFD, which would share a namespace from host. This makes whole a lot more sense than unsharing security wise as it is allow listing (instead of deny listing).

It can be post-clone3 disabled. This is what we do in SGX driver i.e., have build phase enabled ioctls.

Br, Jarkko

#35 lore raw

Re: [RFC PATCH v5 15/25] rootns: Add ROOTNS_KILL ioctl

In reply to Jarkko Sakkinen
Quoted 4 lines · Jarkko Sakkinen
Quoted 3 lines · Jarkko Sakkinen

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

Quoted 8 lines
Quoted 6 lines

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

Will be gone i.e., can do also pidfd_send_signal(fd, signum, NULL, 0).

Wiring:

        case PIDFD_SELF_THREAD_GROUP:
                pid = get_task_pid(current, PIDTYPE_TGID);
                type = PIDTYPE_TGID;
                break;
        default: {
                CLASS(fd, f)(pidfd);
                if (fd_empty(f))
                        return -EBADF;

                if (is_rootns_file(fd_file(f)))
                        return rootns_send_signal(fd_file(f), sig, info, flags);

After this only ROONTS_GET_NSFD remains.

Br, Jarkko

#43 lore raw

Re: [RFC PATCH v5 20/25] security: Add rootns LSM hooks

In reply to Jarkko Sakkinen
Quoted 27 lines · Jarkko Sakkinen

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

Add lbs_rootns and rootns->security blob management alongside security_rootns_alloc(), security_rootns_free(), security_rootns_clone(), and security_rootns_kill().

---
 include/linux/lsm_hook_defs.h |  7 +++
 include/linux/lsm_hooks.h     |  3 ++
 include/linux/rootns.h        |  3 ++
 include/linux/security.h      | 30 ++++++++++++
 kernel/rootns.c               | 44 +++++++++++++-----
 security/lsm_init.c           |  6 +++
 security/security.c           | 86 +++++++++++++++++++++++++++++++++++
 7 files changed, 167 insertions(+), 12 deletions(-)
include/linux/lsm_hook_defs.h +0 -0
index 87d9d06710cb..2cb90ddedc14 100644

include/linux/lsm_hook_defs.h LSM_HOOK(int, 0, bdev_alloc_security, struct block_device *bdev) · line 488

Quoted 9 lines
include/linux/lsm_hook_defs.h +6 -0
@@ -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)

Rootns objects have a security model:

1. No embryonic state by design. Especially staircase initialization contributes to this property.
2. Unshare logic is inverted. Right now ROOTNS_SHARE ioctl does not exist right now but it is (obviously) doable.
3. Dead obvious and transparent LSM hooks. Really hard to get them wrong.
4. We already know by experience that opaque fd-bound objects with two-phase state machine (build, live) works. It's what make this secure and policy-free implementatiion.

The choices how to do things with closures used in SGX driver are translatable and they are also pretty well reviewed choices, given all those years... I would put some weight on this too.

Br, Jarkko

#8 lore raw

Re: [RFC PATCH v5 03/25] arch: Wire up userns_set_idmap() system call

In reply to Jarkko Sakkinen
Quoted 16 lines · Jarkko Sakkinen

Expose userns_set_idmap() (473, 583 on Alpha) across all architecture system call tables and asm-generic unistd.h.

---
 arch/alpha/kernel/syscalls/syscall.tbl      | 1 +
 arch/arm/tools/syscall.tbl                  | 1 +
 arch/arm64/tools/syscall_32.tbl             | 1 +
 arch/m68k/kernel/syscalls/syscall.tbl       | 1 +
 arch/microblaze/kernel/syscalls/syscall.tbl | 1 +
 arch/mips/kernel/syscalls/syscall_n32.tbl   | 1 +
 arch/mips/kernel/syscalls/syscall_n64.tbl   | 1 +
 arch/mips/kernel/syscalls/syscall_o32.tbl   | 1 +
 arch/parisc/kernel/syscalls/syscall.tbl     | 1 +
 arch/powerpc/kernel/syscalls/syscall.tbl    | 1 +
 arch/s390/kernel/syscalls/syscall.tbl       | 1 +
Quoted 8 lines
 arch/sh/kernel/syscalls/syscall.tbl         | 1 +
 arch/sparc/kernel/syscalls/syscall.tbl      | 1 +
 arch/x86/entry/syscalls/syscall_32.tbl      | 1 +
 arch/x86/entry/syscalls/syscall_64.tbl      | 1 +
 arch/xtensa/kernel/syscalls/syscall.tbl     | 1 +
 include/uapi/asm-generic/unistd.h           | 6 +++++-
 scripts/syscall.tbl                         | 1 +
 18 files changed, 22 insertions(+), 1 deletion(-)

I'll populate remaining arch's at the time when I split this. It has enough coverage for the time being.

Br, Jarkko

#3 lore raw

Re: [RFC PATCH v5 02/25] userns: Add userns_set_idmap() system call

In reply to Jarkko Sakkinen
Quoted 7 lines · Jarkko Sakkinen

Configuring UID, GID, and project ID mappings currently requires writing formatted text to /proc/<pid>/{uid_map,gid_map,projid_map,setgroups}, which depends on a live task in /proc and enforces write(2) file-opener CAP_SETUID/CAP_SETGID checks that prevent passing an unprivileged userns file descriptor over SCM_RIGHTS to a dedicated CAP_SETUID/CAP_SETGID mapping helper.

Quoted 7 lines

Add userns_set_idmap() to atomically configure setgroups policy and UID, GID, and project ID extents directly on a CLONE_NEWUSER nsfs file descriptor. Require CAP_SYS_ADMIN over the target user namespace in either the caller's or the file opener's credentials, and check parent ID-range capabilities strictly against the caller's credentials.

I'll remove the flags. I forgot to remove them from final version.

Br, Jarkko

#4 lore raw

Re: [RFC PATCH v5 02/25] userns: Add userns_set_idmap() system call

Quoted 14 lines · Jarkko Sakkinen
Quoted 13 lines · Jarkko Sakkinen

Configuring UID, GID, and project ID mappings currently requires writing formatted text to /proc/<pid>/{uid_map,gid_map,projid_map,setgroups}, which depends on a live task in /proc and enforces write(2) file-opener CAP_SETUID/CAP_SETGID checks that prevent passing an unprivileged userns file descriptor over SCM_RIGHTS to a dedicated CAP_SETUID/CAP_SETGID mapping helper.

Add userns_set_idmap() to atomically configure setgroups policy and UID, GID, and project ID extents directly on a CLONE_NEWUSER nsfs file descriptor. Require CAP_SYS_ADMIN over the target user namespace in either the caller's or the file opener's credentials, and check parent ID-range capabilities strictly against the caller's credentials.

Quoted 3 lines
Quoted 1 line

I'll remove the flags. I forgot to remove them from final version.

userns_set_idmap() still has flags-parameter but it is gated:

	if (flags & ~USERNS_SETGROUPS_ALLOWED)
		return -EINVAL;

And used as a bitmask:

	ns->flags = ns->flags & flags;

Br, Jarkko

#5 lore raw

Re: [RFC PATCH v5 02/25] userns: Add userns_set_idmap() system call

Quoted 19 lines · Jarkko Sakkinen
Quoted 14 lines · Jarkko Sakkinen
Quoted 13 lines · Jarkko Sakkinen

Configuring UID, GID, and project ID mappings currently requires writing formatted text to /proc/<pid>/{uid_map,gid_map,projid_map,setgroups}, which depends on a live task in /proc and enforces write(2) file-opener CAP_SETUID/CAP_SETGID checks that prevent passing an unprivileged userns file descriptor over SCM_RIGHTS to a dedicated CAP_SETUID/CAP_SETGID mapping helper.

Add userns_set_idmap() to atomically configure setgroups policy and UID, GID, and project ID extents directly on a CLONE_NEWUSER nsfs file descriptor. Require CAP_SYS_ADMIN over the target user namespace in either the caller's or the file opener's credentials, and check parent ID-range capabilities strictly against the caller's credentials.

Quoted 3 lines
Quoted 1 line

I'll remove the flags. I forgot to remove them from final version.

Quoted 8 lines

userns_set_idmap() still has flags-parameter but it is gated:

	if (flags & ~USERNS_SETGROUPS_ALLOWED)
		return -EINVAL;

And used as a bitmask:

	ns->flags = ns->flags & flags;

SYSCALL_DEFINE4(userns_set_idmap, int, fd,
const struct userns_idmap __user *, map, size_t, size, unsigned int, flags)

{
        struct uid_gid_map new_uid = {}, new_gid = {}, new_projid = {};
        struct userns_idmap req = {};
        struct ns_common *ns_common;
        struct user_namespace *ns;
        unsigned long old_flags;
        struct file *filp;
        int ret;

        BUILD_BUG_ON(sizeof(struct userns_idmap) != USERNS_IDMAP_SIZE_VER0);

        if (flags & ~USERNS_SETGROUPS_ALLOWED)
                return -EINVAL;

        CLASS(fd, f)(fd);
        if (fd_empty(f))
                return -EBADF;

        filp = fd_file(f);
        if (!proc_ns_file(filp))
                return -EINVAL;

        ns_common = get_proc_ns(file_inode(filp));
        if (ns_common->ns_type != CLONE_NEWUSER)
                return -EINVAL;
        ns = to_user_ns(ns_common);

        if (!map || size < USERNS_IDMAP_SIZE_VER0)
                return -EINVAL;
        ret = copy_struct_from_user(&req, sizeof(req), map, size);
        if (ret)
                return ret;
        if (req.reserved)
                return -EINVAL;
        if (!req.nr_uid_extents != !req.uid_extents ||
            !req.nr_gid_extents != !req.gid_extents ||
            !req.nr_projid_extents != !req.projid_extents)
                return -EINVAL;
        if (!req.nr_uid_extents && !req.nr_gid_extents &&
            !req.nr_projid_extents)
                return -EINVAL;
        if ((flags & USERNS_SETGROUPS_ALLOWED) && !req.nr_gid_extents)
                return -EINVAL;

        if (!ns->parent)
                return -EPERM;
        if (current_user_ns() != ns && current_user_ns() != ns->parent)
                return -EPERM;

        if (req.nr_uid_extents || req.nr_gid_extents) {
                bool file_ok = (filp->f_cred->user_ns == ns ||
                                filp->f_cred->user_ns == ns->parent) &&
                               file_ns_capable(filp, ns, CAP_SYS_ADMIN);

                if (!ns_capable(ns, CAP_SYS_ADMIN) && !file_ok)
                        return -EPERM;
        }

        if (req.nr_uid_extents) {
                ret = parse_user_idmap_extents(req.uid_extents,
                                               req.nr_uid_extents, &new_uid);
                if (ret < 0)
                        goto out_free;
        }
        if (req.nr_gid_extents) {
                ret = parse_user_idmap_extents(req.gid_extents,
                                               req.nr_gid_extents, &new_gid);
                if (ret < 0)
                        goto out_free;
        }
        if (req.nr_projid_extents) {
                ret = parse_user_idmap_extents(req.projid_extents,
                                               req.nr_projid_extents,
                                               &new_projid);
                if (ret < 0)
                        goto out_free;
        }

        mutex_lock(&userns_state_mutex);
        old_flags = ns->flags;
        ret = -EPERM;

        if (req.nr_uid_extents && ns->uid_map.nr_extents != 0)
                goto out_unlock;
        if (req.nr_gid_extents && ns->gid_map.nr_extents != 0)
                goto out_unlock;
        if (req.nr_projid_extents && ns->projid_map.nr_extents != 0)
                goto out_unlock;

        if (req.nr_gid_extents) {
                if ((flags & USERNS_SETGROUPS_ALLOWED) &&
                    !(ns->flags & USERNS_SETGROUPS_ALLOWED))
                        goto out_unlock;
                if (!(flags & USERNS_SETGROUPS_ALLOWED))
                        ns->flags &= ~USERNS_SETGROUPS_ALLOWED;
        }

        if (req.nr_uid_extents) {
                ret = prepare_caller_idmap(ns, CAP_SETUID, &new_uid,
                                           &ns->parent->uid_map);
                if (ret < 0)
                        goto out_restore;
        }
        if (req.nr_gid_extents) {
                ret = prepare_caller_idmap(ns, CAP_SETGID, &new_gid,
                                           &ns->parent->gid_map);
                if (ret < 0)
                        goto out_restore;
        }
        if (req.nr_projid_extents) {
                ret = prepare_caller_idmap(ns, -1, &new_projid,
                                           &ns->parent->projid_map);
                if (ret < 0)
                        goto out_restore;
        }

        if (req.nr_uid_extents)
                commit_new_idmap(&ns->uid_map, &new_uid);
        if (req.nr_gid_extents)
                commit_new_idmap(&ns->gid_map, &new_gid);
        if (req.nr_projid_extents)
                commit_new_idmap(&ns->projid_map, &new_projid);

        mutex_unlock(&userns_state_mutex);
        return 0;

out_restore:

        ns->flags = old_flags;
out_unlock:
        mutex_unlock(&userns_state_mutex);
out_free:
        free_new_idmap(&new_uid);
        free_new_idmap(&new_gid);
        free_new_idmap(&new_projid);
        return ret;
}

Br, Jarkko

#50 lore raw

Re: [RFC PATCH v5 25/25] MAINTAINERS: Add entry for ROOT NAMESPACE

In reply to Jarkko Sakkinen
Quoted 14 lines · 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 +0 -0
index 7cbce21ba45a..072be5ec7fd8 100644

MAINTAINERS F: include/linux/mfd/rohm-bd96802.h · line 24536

Quoted 4 lines
MAINTAINERS +1 -0
@@ -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

Out-of-date.

Not sure if rootns is a great name overall, it just randomly picked WiP name. What gets produced are opaque fd-bound containers so maybe even calling syscall as container() would not be such a bad idea (unweighted and unconsidered idea).

Br, Jarkko

#23 lore raw

Re: [RFC PATCH v5 12/25] rootns: Track init lifecycle via copy_process() and pid_namespace

In reply to Jarkko Sakkinen
Quoted 18 lines · Jarkko Sakkinen
Quoted 5 lines · Jarkko Sakkinen

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

Quoted 8 lines

Commit the bootstrap child reaper and bind pid_ns->rootns 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.

ROOTNS_GET_NSFD will be the only surviving ioctl, which make access control wise sense.

Quoted 6 lines

This leaves room for ROOTNS_SHARE_NSFD, which would share a namespace from host. This makes whole a lot more sense than unsharing security wise as it is allow listing (instead of deny listing).

It can be post-clone3 disabled. This is what we do in SGX driver i.e., have build phase enabled ioctls.

/**
* DOC: ROOTNS_SHARE_NSFD
*
* ``ioctl(rootns_fd, ROOTNS_SHARE_NSFD, ns_fd)`` replaces the corresponding
* member namespace of ``rootns_fd`` with the ``nsfs`` namespace referenced by
* ``ns_fd`` (one of ``CLONE_NEWCGROUP``, ``CLONE_NEWIPC``, ``CLONE_NEWUTS``,
* ``CLONE_NEWNET``, or ``CLONE_NEWTIME``) while ``rootns_fd`` is in its
* initial build phase (``ROOTNS_INIT``).
*
* Requires ``CAP_SYS_ADMIN`` in the container object's user namespace, and
* when the caller is not already a member of ``ns_fd``, ``CAP_SYS_ADMIN``
* in the owning user namespace of ``ns_fd``.
*
* Returns ``0`` on success, or ``-1`` with ``errno`` set to ``EBADF`` if
* ``ns_fd`` is not an open file descriptor, ``EINVAL`` if ``ns_fd`` is not a
* shareable ``nsfs`` namespace file descriptor, ``EOPNOTSUPP`` if the
* namespace type is unsupported, ``EPERM`` without required capabilities, or
* ``EBUSY`` once ``CLONE_INTO_ROOTNS`` has transitioned ``rootns_fd`` out of
* ``ROOTNS_INIT``.
*/
#define ROOTNS_SHARE_NSFD _IO(ROOTNS_IOCTL_MAGIC, 0x02)

Makes sense enough to include to the next version.

Br, Jarkko

#9 lore raw

Re: [RFC PATCH v5 03/25] arch: Wire up userns_set_idmap() system call

In reply to Jarkko Sakkinen
Quoted 26 lines · Jarkko Sakkinen
Quoted 16 lines · Jarkko Sakkinen

Expose userns_set_idmap() (473, 583 on Alpha) across all architecture system call tables and asm-generic unistd.h.

---
 arch/alpha/kernel/syscalls/syscall.tbl      | 1 +
 arch/arm/tools/syscall.tbl                  | 1 +
 arch/arm64/tools/syscall_32.tbl             | 1 +
 arch/m68k/kernel/syscalls/syscall.tbl       | 1 +
 arch/microblaze/kernel/syscalls/syscall.tbl | 1 +
 arch/mips/kernel/syscalls/syscall_n32.tbl   | 1 +
 arch/mips/kernel/syscalls/syscall_n64.tbl   | 1 +
 arch/mips/kernel/syscalls/syscall_o32.tbl   | 1 +
 arch/parisc/kernel/syscalls/syscall.tbl     | 1 +
 arch/powerpc/kernel/syscalls/syscall.tbl    | 1 +
 arch/s390/kernel/syscalls/syscall.tbl       | 1 +
Quoted 8 lines
 arch/sh/kernel/syscalls/syscall.tbl         | 1 +
 arch/sparc/kernel/syscalls/syscall.tbl      | 1 +
 arch/x86/entry/syscalls/syscall_32.tbl      | 1 +
 arch/x86/entry/syscalls/syscall_64.tbl      | 1 +
 arch/xtensa/kernel/syscalls/syscall.tbl     | 1 +
 include/uapi/asm-generic/unistd.h           | 6 +++++-
 scripts/syscall.tbl                         | 1 +
 18 files changed, 22 insertions(+), 1 deletion(-)
Quoted 2 lines

I'll populate remaining arch's at the time when I split this. It has enough coverage for the time being.

Ugh, I have all populated but I found some other issues to fixup while checking this.

Br, Jarkko

#25 lore raw

Re: [RFC PATCH v5 13/25] rootns: Add rootns() system call

In reply to Jarkko Sakkinen
Quoted 10 lines · Jarkko Sakkinen

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

Add the rootns() system call to allocate a detached rootns instance owning a fresh user namespace alongside dedicated empty mount (CLONE_EMPTY_MNTNS), PID, UTS, IPC, network, cgroup, and time namespaces, and return its control file descriptor. Finalize the nsproxy time namespace and pin active references for the lifetime of the rootns.

Quoted 3 lines

Syscall name is outdated. I'll rename it as container_create(). Does not have to be final name, but is a better wip name.

Br, Jarkko

#26 lore raw

Re: [RFC PATCH v5 13/25] rootns: Add rootns() system call

Quoted 11 lines · Jarkko Sakkinen
Quoted 10 lines · Jarkko Sakkinen

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

Add the rootns() system call to allocate a detached rootns instance owning a fresh user namespace alongside dedicated empty mount (CLONE_EMPTY_MNTNS), PID, UTS, IPC, network, cgroup, and time namespaces, and return its control file descriptor. Finalize the nsproxy time namespace and pin active references for the lifetime of the rootns.

Quoted 6 lines
Quoted 3 lines

Syscall name is outdated. I'll rename it as container_create(). Does not have to be final name, but is a better wip name.

Something more non-generic as it inevitably would collide to something (did not check). I'll figure something out.

Br, Jarkko

#27 lore raw

Re: [RFC PATCH v5 13/25] rootns: Add rootns() system call

Quoted 16 lines · Jarkko Sakkinen
Quoted 15 lines · Jarkko Sakkinen
Quoted 13 lines · Jarkko Sakkinen

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

Add the rootns() system call to allocate a detached rootns instance owning a fresh user namespace alongside dedicated empty mount (CLONE_EMPTY_MNTNS), PID, UTS, IPC, network, cgroup, and time namespaces, and return its control file descriptor. Finalize the nsproxy time namespace and pin active references for the lifetime of the rootns.

Quoted 5 lines
Quoted 2 lines

Syscall name is outdated. I'll rename it as container_create(). Does not have to be final name, but is a better wip name.

Something more non-generic as it inevitably would collide to something (did not check). I'll figure something out.

At least for the next iteration I call the object as "vault" and rename the syscall as vault_open(), and that is based on:

	$ cat /proc/kallsyms | sed -n '/call_meta__/p' | sed 's/.*call_meta__\(.*\)/\1/g; s/\(.*\)/SYS_\1 \1/; 1i #include <sys/syscall.h>' | gcc -E -P - | grep -v 'SYS_' | sort -n | uniq | grep _open
	240 mq_open
	298 perf_event_open
	434 pidfd_open

Br, Jarkko

#28 lore raw

Re: [RFC PATCH v5 13/25] rootns: Add rootns() system call

Quoted 23 lines · Jarkko Sakkinen
Quoted 16 lines · Jarkko Sakkinen
Quoted 15 lines · Jarkko Sakkinen
Quoted 13 lines · Jarkko Sakkinen

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

Add the rootns() system call to allocate a detached rootns instance owning a fresh user namespace alongside dedicated empty mount (CLONE_EMPTY_MNTNS), PID, UTS, IPC, network, cgroup, and time namespaces, and return its control file descriptor. Finalize the nsproxy time namespace and pin active references for the lifetime of the rootns.

Quoted 5 lines
Quoted 2 lines

Syscall name is outdated. I'll rename it as container_create(). Does not have to be final name, but is a better wip name.

Something more non-generic as it inevitably would collide to something (did not check). I'll figure something out.

Quoted 7 lines

At least for the next iteration I call the object as "vault" and rename the syscall as vault_open(), and that is based on:

	$ cat /proc/kallsyms | sed -n '/call_meta__/p' | sed 's/.*call_meta__\(.*\)/\1/g; s/\(.*\)/SYS_\1 \1/; 1i #include <sys/syscall.h>' | gcc -E -P - | grep -v 'SYS_' | sort -n | uniq | grep _open
	240 mq_open
	298 perf_event_open
	434 pidfd_open

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

Br, Jarkko

#6 lore raw

Re: [RFC PATCH v5 02/25] userns: Add userns_set_idmap() system call

In reply to Jarkko Sakkinen
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [High] userns: missing target CAP_SYS_ADMIN and caller checks in sys_userns_set_idmap() - [Medium] userns…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] userns: missing target CAP_SYS_ADMIN and caller checks in sys_userns_set_idmap()
- [Medium] userns: unbounded size passed to copy_struct_from_user() in sys_userns_set_idmap()
- [Medium] userns: transient ns->flags mutation in sys_userns_set_idmap() before validation
--

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

userns: Add userns_set_idmap() system call

This commit introduces the userns_set_idmap() system call to atomically configure setgroups policy and UID, GID, and project ID mappings directly on a user namespace file descriptor.

Quoted 4 lines
kernel/user_namespace.c +0 -0
index 6b9673dcdc670..d7f2cad388c8c 100644

[ ... ]

Quoted 38 lines
kernel/user_namespace.c +38 -0
+static bool caller_idmap_permitted(struct user_namespace *ns, int cap_setid,
+				   const struct uid_gid_map *new_map)
+{
+	const struct cred *cred = current_cred();
+
+	if (cap_setid == CAP_SETUID && idmap_maps_root(new_map)) {
+		if (cred->user_ns == ns) {
+			if (!ns->parent_could_setfcap)
+				return false;
+		} else {
+			if (!ns_capable(ns->parent, CAP_SETFCAP))
+				return false;
+		}
+	}
+
+	if (new_map->nr_extents == 1 && new_map->extent[0].count == 1 &&
+	    uid_eq(ns->owner, cred->euid)) {
+		u32 id = new_map->extent[0].lower_first;
+
+		if (cap_setid == CAP_SETUID) {
+			kuid_t uid = make_kuid(ns->parent, id);
+
+			if (uid_eq(uid, cred->euid))
+				return true;
+		} else if (cap_setid == CAP_SETGID) {
+			kgid_t gid = make_kgid(ns->parent, id);
+
+			if (!(ns->flags & USERNS_SETGROUPS_ALLOWED) &&
+			    gid_eq(gid, cred->egid))
+				return true;
+		}
+	}
+
+	if (!cap_valid(cap_setid))
+		return true;
+
+	return ns_capable(ns->parent, cap_setid);
+}

[ ... ]

Quoted 4 lines
kernel/user_namespace.c +4 -0
+SYSCALL_DEFINE4(userns_set_idmap, int, fd,
+		const struct userns_idmap __user *, map,
+		size_t, size, unsigned int, flags)
+{

[ ... ]

kernel/user_namespace.c static ssize_t map_write(struct file *file, const char __user *buf, · line 1307

Quoted 6 lines
kernel/user_namespace.c +6 -0
+	if (!map || size < USERNS_IDMAP_SIZE_VER0)
+		return -EINVAL;
+
+	ret = copy_struct_from_user(&req, sizeof(req), map, size);
+	if (ret)
+		return ret;

[Severity: Medium]
Should sys_userns_set_idmap() reject size > PAGE_SIZE with -E2BIG before calling copy_struct_from_user()? When size exceeds sizeof(req), copy_struct_from_user() calls check_zeroed_user() on the trailing bytes, which scans the user range word-by-word inside user_read_access_begin() without rescheduling or checking for pending signals. An unprivileged caller can pass a multi-gigabyte zero-filled mapping and stall a CPU in the kernel.

Quoted 17 lines
kernel/user_namespace.c +17 -0
+
+	if (!req.flags || (req.flags & ~USERNS_IDMAP_ALL_FLAGS))
+		return -EINVAL;
+	if (!(req.flags & USERNS_IDMAP_UID) &&
+	    (req.nr_uid_extents || req.uid_extents))
+		return -EINVAL;
+	if (!(req.flags & USERNS_IDMAP_GID) &&
+	    (req.nr_gid_extents || req.gid_extents))
+		return -EINVAL;
+	if (!(req.flags & USERNS_IDMAP_PROJID) &&
+	    (req.nr_projid_extents || req.projid_extents))
+		return -EINVAL;
+
+	if (!ns->parent)
+		return -EPERM;
+	if (current_user_ns() != ns && current_user_ns() != ns->parent)
+		return -EPERM;

kernel/user_namespace.c static ssize_t map_write(struct file *file, const char __user *buf, · line 1334

Quoted 10 lines
kernel/user_namespace.c +10 -0
+
+	if (req.flags & (USERNS_IDMAP_UID | USERNS_IDMAP_GID |
+			 USERNS_SETGROUPS_DENY)) {
+		bool file_ok = (filp->f_cred->user_ns == ns ||
+				filp->f_cred->user_ns == ns->parent) &&
+			       file_ns_capable(filp, ns, CAP_SYS_ADMIN);
+
+		if (!ns_capable(ns, CAP_SYS_ADMIN) && !file_ok)
+			return -EPERM;
+	}

[Severity: High]
Does omitting USERNS_IDMAP_PROJID from this CAP_SYS_ADMIN check allow any unprivileged process holding a read-only userns fd to write ns->projid_map?

For /proc/<pid>/projid_map, writing requires opening the procfs file (mode 0644, owned by the target task) for write, so VFS permission checks block unrelated users in ns->parent and unprivileged non-owner tasks inside ns. By contrast, nsfs files have mode 0444 and are always opened O_RDONLY, and caller_idmap_permitted() returns true unconditionally when cap_setid is -1. As a result, an unprivileged task inside ns that dropped capabilities, or an unrelated user in ns->parent that obtained an nsfs fd (for example via NS_GET_USERNS), can call userns_set_idmap() with USERNS_IDMAP_PROJID and lock in the write-once projid_map.

In addition, when file_ok is true on a delegated nsfs fd and the caller lacks ns_capable(ns, CAP_SYS_ADMIN), neither USERNS_SETGROUPS_DENY nor USERNS_IDMAP_PROJID verifies any privilege on current_cred() in ns->parent, allowing an unprivileged recipient of a read-only userns fd to disable setgroups(2) or configure projid_map on ns.

[ ... ]

Quoted 24 lines
kernel/user_namespace.c +24 -0
+	if (req.flags & USERNS_SETGROUPS_DENY)
+		ns->flags &= ~USERNS_SETGROUPS_ALLOWED;
+
+	if (req.flags & USERNS_IDMAP_UID) {
+		ret = prepare_caller_idmap(ns, CAP_SETUID, &new_uid,
+					   &ns->parent->uid_map);
+		if (ret < 0)
+			goto out_restore;
+	}
+	if (req.flags & USERNS_IDMAP_GID) {
+		ret = prepare_caller_idmap(ns, CAP_SETGID, &new_gid,
+					   &ns->parent->gid_map);
+		if (ret < 0)
+			goto out_restore;
+	}
+	if (req.flags & USERNS_IDMAP_PROJID) {
+		ret = prepare_caller_idmap(ns, -1, &new_projid,
+					   &ns->parent->projid_map);
+		if (ret < 0)
+			goto out_restore;
+	}
+
+	if (req.flags & USERNS_IDMAP_UID)
+		commit_new_idmap(&ns->uid_map, &new_uid);

kernel/user_namespace.c static ssize_t map_write(struct file *file, const char __user *buf, · line 1402

Quoted 10 lines
kernel/user_namespace.c +10 -0
+	if (req.flags & USERNS_IDMAP_GID)
+		commit_new_idmap(&ns->gid_map, &new_gid);
+	if (req.flags & USERNS_IDMAP_PROJID)
+		commit_new_idmap(&ns->projid_map, &new_projid);
+
+	mutex_unlock(&userns_state_mutex);
+	return 0;
+
+out_restore:
+	ns->flags = old_flags;

[Severity: Medium]
Can clearing USERNS_SETGROUPS_ALLOWED in ns->flags before prepare_caller_idmap() expose a transient "deny" state to concurrent readers if preparation fails?

proc_setgroups_show() reads READ_ONCE(ns->flags) without holding userns_state_mutex:

kernel/user_namespace.c:proc_setgroups_show() {
	struct user_namespace *ns = seq->private;
	unsigned long userns_flags = READ_ONCE(ns->flags);

	seq_printf(seq, "%s\n",
		   (userns_flags & USERNS_SETGROUPS_ALLOWED) ?
		   "allow" : "deny");
	return 0;
}

While prepare_caller_idmap() needs USERNS_SETGROUPS_ALLOWED cleared when checking an unprivileged caller's GID mapping, mutating ns->flags in place and restoring old_flags on failure lets a concurrent reader of /proc/<pid>/setgroups observe "deny" before it reverts to "allow". Could caller_idmap_permitted() check the effective flags value and leave the update to ns->flags until the commit phase after all prepare_caller_idmap() calls succeed?

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

Re: [RFC PATCH v5 03/25] arch: Wire up userns_set_idmap() system call

In reply to Jarkko Sakkinen
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] arch: duplicate sys_ prefix in syscall.tbl for userns_set_idmap() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] arch: duplicate sys_ prefix in syscall.tbl for userns_set_idmap()
--

commit 830eeaaedd55436f6eba477c154843b0a257eb5d
Author: Jarkko Sakkinen <[email protected]>

arch: Wire up userns_set_idmap() system call

This commit wires up the userns_set_idmap() system call across the architecture syscall tables and include/uapi/asm-generic/unistd.h.

Quoted 170 lines
arch/alpha/kernel/syscalls/syscall.tbl +1 -0
index 52e3538cc7df4..9384d59a44dcd 100644
@@ -512,3 +512,4 @@
 580	common	listns				sys_listns
 581	common	rseq_slice_yield		sys_rseq_slice_yield
 582	common	fchroot				sys_fchroot
+583	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/arm/tools/syscall.tbl +1 -0
index 55717ed32c27e..6130366b76812 100644
@@ -487,3 +487,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/arm64/tools/syscall_32.tbl +1 -0
index df2d1d82fb3cc..3fcc7899fd087 100644
@@ -484,3 +484,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/m68k/kernel/syscalls/syscall.tbl +1 -0
index ba7a4d8903d04..5607635bd4bd7 100644
@@ -472,3 +472,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/microblaze/kernel/syscalls/syscall.tbl +1 -0
index 76d7cbe2a133c..97ee93f42fac2 100644
@@ -478,3 +478,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/mips/kernel/syscalls/syscall_n32.tbl +1 -0
index 9ae88e4eac61e..da4ed57a91d3b 100644
@@ -411,3 +411,4 @@
 470	n32	listns				sys_listns
 471	n32	rseq_slice_yield		sys_rseq_slice_yield
 472	n32	fchroot				sys_fchroot
+473	n32	userns_set_idmap		sys_sys_userns_set_idmap
arch/mips/kernel/syscalls/syscall_n64.tbl +1 -0
index 83dc93a0712f1..5e9839b6b3891 100644
@@ -387,3 +387,4 @@
 470	n64	listns				sys_listns
 471	n64	rseq_slice_yield		sys_rseq_slice_yield
 472	n64	fchroot				sys_fchroot
+473	n64	userns_set_idmap		sys_sys_userns_set_idmap
arch/mips/kernel/syscalls/syscall_o32.tbl +1 -0
index 9c62429c9b7b4..290c1b61be47d 100644
@@ -460,3 +460,4 @@
 470	o32	listns				sys_listns
 471	o32	rseq_slice_yield		sys_rseq_slice_yield
 472	o32	fchroot				sys_fchroot
+473	o32	userns_set_idmap		sys_sys_userns_set_idmap
arch/parisc/kernel/syscalls/syscall.tbl +1 -0
index 88adc4016cce0..fc0fa917eb92a 100644
@@ -471,3 +471,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/powerpc/kernel/syscalls/syscall.tbl +1 -0
index cfbb70039ff00..d12e49022b235 100644
@@ -563,3 +563,4 @@
 470	common	listns				sys_listns
 471	nospu	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/s390/kernel/syscalls/syscall.tbl +1 -0
index 1b45e68a217bb..dc427811d30d7 100644
@@ -399,3 +399,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/sh/kernel/syscalls/syscall.tbl +1 -0
index ace068dff0de0..e62ac9acc7ada 100644
@@ -476,3 +476,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/sparc/kernel/syscalls/syscall.tbl +1 -0
index 5b9fe0e8140f2..df074bf322c41 100644
@@ -518,3 +518,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 2c172ef48dfd3..243a3f55834dd 100644
@@ -478,3 +478,4 @@
 470	i386	listns			sys_listns
 471	i386	rseq_slice_yield	sys_rseq_slice_yield
 472	i386	fchroot			sys_fchroot
+473	i386	userns_set_idmap	sys_sys_userns_set_idmap
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index d5b6045b0090c..f11700e3af657 100644
@@ -397,6 +397,7 @@
 470	common	listns			sys_listns
 471	common	rseq_slice_yield	sys_rseq_slice_yield
 472	common	fchroot			sys_fchroot
+473	common	userns_set_idmap	sys_sys_userns_set_idmap
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
arch/xtensa/kernel/syscalls/syscall.tbl +1 -0
index d354bb231796c..1d28de95915f5 100644
@@ -443,3 +443,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap
include/uapi/asm-generic/unistd.h +5 -1
index 5b7e77a7c736e..695eac2d356bc 100644
@@ -867,8 +867,12 @@ __SYSCALL(__NR_rseq_slice_yield, sys_rseq_slice_yield)
 #define __NR_fchroot 472
 __SYSCALL(__NR_fchroot, sys_fchroot)
 
+/* kernel/user_namespace.c */
+#define __NR_userns_set_idmap 473
+__SYSCALL(__NR_userns_set_idmap, sys_userns_set_idmap)
+
 #undef __NR_syscalls
-#define __NR_syscalls 473
+#define __NR_syscalls 474
 
 /*
  * 32 bit systems traditionally used different
scripts/syscall.tbl +0 -0
index 0ab5316051202..0dddd465d1c5a 100644

scripts/syscall.tbl line 416

Quoted 4 lines
scripts/syscall.tbl +1 -0
@@ -413,3 +413,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	userns_set_idmap		sys_sys_userns_set_idmap

[Severity: High]
Should the entry point in scripts/syscall.tbl and the architecture syscall*.tbl files be sys_userns_set_idmap rather than sys_sys_userns_set_idmap? Because the syscall is defined with SYSCALL_DEFINE4(userns_set_idmap, ...), the duplicated sys_ prefix causes the generated syscall tables to reference undefined symbols such as sys_sys_userns_set_idmap and __x64_sys_sys_userns_set_idmap, breaking the build across all architectures.

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

Re: [RFC PATCH v5 06/25] mount: Support MOVE_MOUNT_T_MNTNS in move_mount()

In reply to Jarkko Sakkinen
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] fs: namespace: broken cross-userns locking in attach_recursive_mnt() --

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

commit 74ae0b488300551c347e9b244e2d68e31f9a48cf
Author: Jarkko Sakkinen <[email protected]>

mount: 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 specified by an nsfs file descriptor.

Quoted 4 lines
fs/namespace.c +0 -0
index b2dc84c0d0d66..b65f1fdd92811 100644

[ ... ]

Quoted 22 lines
fs/namespace.c +4 -0
@@ -2641,6 +2652,7 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 	struct user_namespace *user_ns = ns->user_ns;
 	struct pinned_mountpoint root = {};
 	struct mountpoint *shorter = NULL;
+	struct mnt_namespace *src_ns;
 	struct mount *child, *p;
 	struct mount *top;
 	struct hlist_node *n;
@@ -2662,6 +2674,9 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 		user_ns = current->nsproxy->mnt_ns->user_ns;
 	else
 		user_ns = ns->user_ns;
+	src_ns = moving ? NULL : source_mnt->mnt_ns;
+	if (move_mntns && src_ns)
+		user_ns = src_ns->user_ns;
 
 	/*
 	 * Preallocate a mountpoint in case the new mounts need to be
@@ -2728,8 +2743,12 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 		struct mount *q;
 		hlist_del_init(&child->mnt_hash);
 		/* Notice when we are propagating across user namespaces */

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

Quoted 10 lines
fs/namespace.c +5 -1
-		if (child->mnt_parent->mnt_ns->user_ns != user_ns)
+		if (child->mnt_parent->mnt_ns->user_ns != user_ns) {
 			lock_mnt_tree(child);
+			if ((move_mntns || is_anon_ns(ns)) &&
+			    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]
Does overwriting user_ns with src_ns->user_ns break cross-user-namespace mount locking when source_mnt is attached via MOVE_MOUNT_T_MNTNS?

move_mount_mntns() checks CAP_SYS_ADMIN in target_mnt_ns->user_ns (ns->user_ns), not src_ns->user_ns. When src_ns->user_ns differs from ns->user_ns (for example, an anonymous mount created in a less-privileged user namespace U2 is attached by a manager into a mount namespace owned by U1) and dest_mnt propagates to a slave mount in a namespace owned by U2, child->mnt_parent->mnt_ns->user_ns == user_ns (both U2). lock_mnt_tree(child) is then skipped on the copy propagated from U1 into U2, leaving MNT_READONLY, MNT_NOSUID, MNT_NODEV, MNT_NOEXEC, and submounts unlocked in U2.

In the same case, for the primary mount (child == source_mnt) attached into target_mnt_ns, child->mnt_parent->mnt_ns->user_ns (U1) != user_ns (U2) is true, which locks source_mnt with MNT_LOCKED inside the privileged target_mnt_ns itself. Also, checking move_mntns unconditionally for all entries in tree_list sets MNT_LOCKED on the root of every cross-userns propagated copy (child != source_mnt), preventing slave namespaces from unmounting propagated mounts that did not cover an existing locked mount.

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

Re: [RFC PATCH v5 07/25] mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS

In reply to Jarkko Sakkinen
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] mount: missing SB_NOUSER check in do_move_mount() for MOVE_MOUNT_CLONE --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] mount: missing SB_NOUSER check in do_move_mount() for MOVE_MOUNT_CLONE
--

commit 0d056169d39e8a161d1951b83a6a28ab91fbc2ea
Author: Jarkko Sakkinen <[email protected]>

mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS

This commit adds MOVE_MOUNT_CLONE for use with MOVE_MOUNT_T_MNTNS so move_mount() can recursively loopback-clone a path from the caller's mount namespace directly into a target mount namespace file descriptor.

Quoted 4 lines
fs/namespace.c +0 -0
index b65f1fdd92811..1e7d776c09660 100644

[ ... ]

Quoted 11 lines
fs/namespace.c +7 -0
@@ -3835,6 +3833,35 @@ static int do_move_mount(const struct path *old_path,
 			if (m == target_mnt_ns->root)
 				return beneath ? -EINVAL : -EBUSY;
 		}
+		if (flags & MNT_TREE_CLONE) {
+			unsigned int copy_flags;
+
+			if (!check_mnt(old) || old->mnt_ns == target_mnt_ns)
+				return -EINVAL;
+			src_user_ns = old->mnt_ns->user_ns;
+			copy_flags = (target_mnt_ns->user_ns != src_user_ns) ?

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

Quoted 10 lines
fs/namespace.c +10 -0
+				     (CL_SLAVE | CL_COPY_UNBINDABLE) :
+				     CL_COPY_MNT_NS_FILE;
+			cloned = __do_loopback(old_path, true, copy_flags);
+			if (IS_ERR(cloned))
+				return PTR_ERR(cloned);
+			old = cloned;
+			if (d_is_symlink(old->mnt.mnt_root)) {
+				err = -EINVAL;
+				goto out_cloned;
+			}

[Severity: Medium]
Does this allow cloning and attaching an SB_NOUSER mount such as the caller's base nullfs mount?

do_loopback() pairs __do_loopback() with graft_tree(), which rejects SB_NOUSER mounts, and the non-cloning check_mnt(old) branch below rejects !mnt_has_parent(old). Here __do_loopback() is followed directly by attach_recursive_mnt(). If old_path resolves to a mount namespace's base nullfs mount (for example via an O_PATH fd or a pre-init root) and is cloned onto "/" of an empty target_mnt_ns, a second nullfs mount is attached on top of target_mnt_ns->root, causing mnt_ns_get_root() to treat it as a live root filesystem and permanently blocking subsequent rootfs installation on target_mnt_ns with -EBUSY.

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

Re: [RFC PATCH v5 16/25] fork: Support CLONE_INTO_ROOTNS in clone3()

In reply to Jarkko Sakkinen
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] rootns: leaf-only PIDNS_ADDING check returns -ENOMEM on dead ancestor pid_ns --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] rootns: leaf-only PIDNS_ADDING check returns -ENOMEM on dead ancestor pid_ns
--

commit 62f2477b1da0630c69ec1a2d1d679d2b7228b9f8
Author: Jarkko Sakkinen <[email protected]>

fork: Support CLONE_INTO_ROOTNS in clone3()

This commit adds CLONE_INTO_ROOTNS and struct clone_args.rootns to allow clone3() to spawn a child process directly into an initialized or running root namespace.

Quoted 16 lines
kernel/rootns.c +1 -0
index 5ae975604571f..6fb49c20cc2df 100644
@@ -36,6 +36,7 @@
 #include <uapi/linux/wait.h>
 #include <linux/file.h>
 #include <linux/fs.h>
+#include <linux/fs_struct.h>
 #include <linux/anon_inodes.h>
 #include <linux/rootns.h>
 #include <linux/sched/signal.h>
@@ -426,3 +427,142 @@ SYSCALL_DEFINE1(rootns, unsigned int, flags)
 	return fd;
 }
 

[ ... ]

Quoted 93 lines
kernel/rootns.c +93 -0
+int rootns_prepare_fork(struct kernel_clone_args *args)
+{
+	struct file *file __free(fput) = fget(args->rootns_fd);
+	struct path root __free(path_put) = {};
+	struct pid_namespace *pid_ns;
+	bool bootstrapping = false;
+	struct rootns *rootns;
+	int ret;
+
+	if (!file)
+		return -EBADF;
+	if (!is_rootns_file(file))
+		return -EINVAL;
+
+	rootns = file->private_data;
+	if (!ns_capable(rootns->user_ns, CAP_SYS_ADMIN) ||
+	    !ns_capable(rootns->user_ns, CAP_SYS_CHROOT))
+		return -EPERM;
+	if (current_chrooted() && !ns_capable(current_user_ns(), CAP_SYS_CHROOT))
+		return -EPERM;
+
+	pid_ns = rootns->ns->pid_ns_for_children;
+	if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
+		return -EXDEV;
+
+	ret = mnt_ns_get_root(rootns->ns->mnt_ns, &root);
+	if (ret)
+		return ret;
+
+	for (;;) {
+		bool wait = false;
+
+		scoped_guard(spinlock, &rootns->lock) {
+			switch (rootns->state) {
+			case ROOTNS_INIT:
+				if (!(READ_ONCE(pid_ns->pid_allocated) & PIDNS_ADDING))
+					return -ESRCH;
+				if (READ_ONCE(pid_ns->child_reaper))
+					return -EBUSY;
+				WRITE_ONCE(rootns->state, ROOTNS_FORKING);
+				bootstrapping = true;
+				break;
+			case ROOTNS_FORKING:
+				wait = true;
+				break;
+			case ROOTNS_RUNNING:
+				if (!(READ_ONCE(pid_ns->pid_allocated) & PIDNS_ADDING))
+					return -ESRCH;
+				break;
+			case ROOTNS_DEAD:
+				return -ESRCH;
+			}
+		}
+		if (!wait)
+			break;
+
+		ret = wait_event_killable(rootns->waitq,
+					  READ_ONCE(rootns->state) != ROOTNS_FORKING);
+		if (ret)
+			return ret;
+	}
+
+	args->rootns_file = no_free_ptr(file);
+	args->rootns = rootns;
+	args->rootns_bootstrapping = bootstrapping;
+	return 0;
+}
+
+int rootns_finish_fork(struct kernel_clone_args *args, struct task_struct *p)
+{
+	struct file *file __free(fput) = args->rootns_file;
+	struct rootns *rootns = args->rootns;
+	struct pid_namespace *pid_ns = rootns->ns->pid_ns_for_children;
+	int ret;
+
+	args->rootns_file = NULL;
+	args->rootns = NULL;
+	if (!IS_ERR(p)) {
+		if (args->rootns_bootstrapping)
+			wake_up_all(&rootns->waitq);
+		if (current->nsproxy->time_ns != rootns->ns->time_ns)
+			timens_commit(p, rootns->ns->time_ns);
+		return 0;
+	}
+
+	ret = PTR_ERR(p);
+	if (args->rootns_bootstrapping) {
+		scoped_guard(spinlock, &rootns->lock) {
+			if (rootns->state == ROOTNS_FORKING)
+				WRITE_ONCE(rootns->state, ROOTNS_INIT);
+		}
+		wake_up_all(&rootns->waitq);
+		if (ret == -EINVAL && !args->set_tid_size &&

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

Quoted 10 lines
kernel/rootns.c +10 -0
+		    (READ_ONCE(pid_ns->child_reaper) ||
+		     (READ_ONCE(pid_ns->pid_allocated) & ~PIDNS_ADDING)))
+			ret = -EBUSY;
+	}
+	if ((ret == -ENOMEM || ret == -EBUSY) &&
+	    !(READ_ONCE(pid_ns->pid_allocated) & PIDNS_ADDING))
+		return -ESRCH;
+
+	return ret;
+}

[Severity: Medium]
Can clone3(CLONE_INTO_ROOTNS) return -ENOMEM instead of -ESRCH when an intermediate ancestor PID namespace is tearing down?

rootns_prepare_fork() allows callers in any ancestor active PID namespace, but both rootns_prepare_fork() and rootns_finish_fork() only check PIDNS_ADDING on the leaf pid_ns. If the target rootns was created inside an intermediate PID namespace whose init exits while the leaf pid_ns still has PIDNS_ADDING set (for example, when the nested rootns has not been bootstrapped yet), rootns_prepare_fork() proceeds into copy_process(), alloc_pid() fails with -ENOMEM when it walks the ancestor PID namespaces, and rootns_finish_fork() leaves the error as -ENOMEM.

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

Re: [RFC PATCH v5 17/25] fs: Support FSCONFIG_SET_ROOTNS in fsconfig()

In reply to Jarkko Sakkinen
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] fs: incomplete namespace binding validation in fsconfig_set_rootns() - [Medium] fs: stale fsopen()…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] fs: incomplete namespace binding validation in fsconfig_set_rootns()
- [Medium] fs: stale fsopen() credentials retained in fc->cred by fsconfig_set_rootns()
--

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

fs: Support FSCONFIG_SET_ROOTNS in fsconfig()

This commit adds FSCONFIG_SET_ROOTNS and the ->set_rootns() fs_context operation so callers with CAP_SYS_ADMIN in a target rootns user namespace can bind a newly opened fs_context to that rootns before supplying mount parameters.

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

[ ... ]

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

[ ... ]

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

Quoted 4 lines
fs/fsopen.c +4 -0
+	put_net(fc->net_ns);
+	fc->net_ns = get_net(c->ns->net_ns);
+	put_user_ns(fc->user_ns);
+	fc->user_ns = get_user_ns(user_ns);

[Severity: Medium]
Should fsconfig_set_rootns() also replace fc->cred with get_current_cred()?

alloc_fs_context() sets fc->cred at fsopen() time, when an unprivileged FS_CONTEXT_AWAITING_NS context has not yet been authorized against any target namespace. If the fscontext fd is passed to another task or credentials change before FSCONFIG_SET_ROOTNS, consumers such as dentry_open(..., fc->cred) in fsmount() and proc_fill_super() (fs_info->mounter_cred) will use the fsopen() caller's credentials rather than the credentials that authorized FSCONFIG_SET_ROOTNS.

Quoted 15 lines
fs/fsopen.c +15 -0
+
+	fc->rootns_bound = true;
+	fc->rootns_mnt_id = c->ns->mnt_ns->ns.ns_id;
+
+	ret = fc->fs_type->init_fs_context(fc);
+	if (ret < 0) {
+		fc->rootns_bound = false;
+		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) {

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

Quoted 10 lines
fs/fsopen.c +10 -0
+			fc->rootns_bound = false;
+			fc->phase = FS_CONTEXT_FAILED;
+			return ret;
+		}
+	}
+	if (fc->user_ns != user_ns) {
+		fc->rootns_bound = false;
+		fc->phase = FS_CONTEXT_FAILED;
+		return -EOPNOTSUPP;
+	}

[Severity: High]
Is checking fc->user_ns != user_ns enough to verify that the filesystem supports binding to the target rootns?

binder_fs_type sets FS_USERNS_MOUNT, and binderfs_init_fs_context() neither changes fc->user_ns nor implements ->set_rootns(), so fsconfig_set_rootns() succeeds with fc->user_ns set to c->user_ns. When FSCONFIG_CMD_CREATE then runs binderfs_fill_super(), it captures the caller's current IPC namespace instead of c->ns->ipc_ns:

drivers/android/binder/rust_binderfs.c:binderfs_fill_super() {
    ...
	info->ipc_ns = get_ipc_ns(current->nsproxy->ipc_ns);
    ...
}
drivers/android/binder/rust_binderfs.c:binderfs_binder_device_create() {
    ...
	bool use_reserve = (info->ipc_ns == &init_ipc_ns);
    ...
}

An unprivileged caller in init_ipc_ns that binds a binderfs context to an unprivileged rootns gets a superblock owned by c->user_ns with info->ipc_ns == &init_ipc_ns, allowing it to bypass BINDERFS_MAX_MINOR_CAPPED and allocate from the minor pool reserved for the initial IPC namespace.

Similarly, sysfs_init_fs_context() and cgroup_init_fs_context() capture current's net or cgroup namespace and overwrite fc->user_ns with that namespace's owning user_ns without implementing ->set_rootns(); if current's net or cgroup namespace happens to be owned by c->user_ns, fc->user_ns == user_ns holds and the context silently binds to current's namespace instead of c->ns.

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

Re: [RFC PATCH v5 22/25] arch: Wire up rootns() system call

In reply to Jarkko Sakkinen
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] arch: syscall tables wire rootns() to non-existent sys_sys_rootns symbol - [High] arch: syscall…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] arch: syscall tables wire rootns() to non-existent sys_sys_rootns symbol
- [High] arch: syscall tables wire userns_set_idmap() to sys_sys_userns_set_idmap
--

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

arch: Wire up rootns() system call

This commit wires up the rootns() system call across the architecture system call tables and asm-generic unistd.h.

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

Quoted 8 lines
arch/alpha/kernel/syscalls/syscall.tbl +0 -0
index 9384d59a44dcd..2087b83d6d2ce 100644
@@ -513,3 +513,4 @@
 581	common	rseq_slice_yield		sys_rseq_slice_yield
 582	common	fchroot				sys_fchroot
 583	common	userns_set_idmap		sys_sys_userns_set_idmap

[Severity: High]
Should the userns_set_idmap entry added by commit "arch: Wire up userns_set_idmap() system call" in this series use sys_userns_set_idmap instead of sys_sys_userns_set_idmap here and in the other 16 syscall tables?

kernel/user_namespace.c defines the entry point with SYSCALL_DEFINE4(userns_set_idmap, ...), so the doubled sys_ prefix causes syscall table compilation or linking to fail with an undeclared or undefined sys_sys_userns_set_idmap symbol.

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

Quoted 1 line
arch/alpha/kernel/syscalls/syscall.tbl +1 -0
+584	common	rootns				sys_sys_rootns

[Severity: High]
Should the rootns entry use sys_rootns instead of sys_sys_rootns here and in all 16 other syscall.tbl files modified by this patch?

kernel/rootns.c defines the entry point via SYSCALL_DEFINE1(rootns, ...) and include/uapi/asm-generic/unistd.h maps __NR_rootns to sys_rootns, so the doubled sys_ prefix causes the build or vmlinux link to fail across all architectures using syscall.tbl files.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=22
#51 lore raw
In reply to Jarkko Sakkinen
Sashiko has finished reviewing this 25-patch series:

Sashiko has finished reviewing this 25-patch series:

- Patches 1, 4, 5, 8-15, 18-21, 23, and 24: no issues found.
- Patch 2 ("userns: Add userns_set_idmap() system call"): 3 potential issues (1 High, 2 Medium)
- Patch 3 ("arch: Wire up userns_set_idmap() system call"): 1 potential issue (1 High)
- Patch 6 ("mount: Support MOVE_MOUNT_T_MNTNS in move_mount()"): 1 potential issue (1 High)
- Patch 7 ("mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS"): 1 potential issue (1 Medium)
- Patch 16 ("fork: Support CLONE_INTO_ROOTNS in clone3()"): 1 potential issue (1 Medium)
- Patch 17 ("fs: Support FSCONFIG_SET_ROOTNS in fsconfig()"): 2 potential issues (1 High, 1 Medium)
- Patch 22 ("arch: Wire up rootns() system call"): 2 potential issues (2 High)
- Patch 25: skipped (not reviewed).

Detailed reviews have been sent as separate replies to patches 2, 3, 6, 7, 16, 17, and 22.

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