Skip to contentSkip to conversation

userland: Userland containers

RFC PATCH Superseded Jarkko Sakkinen 3 participants 45 messages Nov 22

Subsystems (32)

v6 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

v6 cover userland: Userland containers

OVERVIEW
========

A userland 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, with optional build-phase opt-in sharing (USERLAND_SHARE_NSFD).
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 USERNS_SETGROUPS_ALLOWED 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.

userland_open() allocates a userland 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(ufd, USERLAND_GET_NSFD, nstype) returns nsfs file descriptors for member namespaces, and ioctl(ufd, USERLAND_SHARE_NSFD, ns_fd) replaces a member cgroup, IPC, UTS, network, or time namespace while the userland is in USERLAND_INIT.

Superblocks are configured directly in the target user namespace via fsopen(), FSCONFIG_SET_USERLAND, and fsmount() for filesystems opting into FS_USERLAND_MOUNT (tmpfs, ramfs, devpts, proc, mqueue) or FS_USERNS_DELEGATABLE, allowing unprivileged callers to assemble mounts 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 userland via clone3() with CLONE_INTO_USERLAND and struct clone_args.userland, without mutating the caller in place. Pairing CLONE_INTO_USERLAND 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 waitid(P_USERLAND, ufd, &infop, options, NULL) returns init's exit status without consuming it. pidfd_send_signal(ufd, sig, NULL, 0) walks pid_ns->idr under tasklist_lock to signal member thread groups, and dedicated LSM hooks mediate userland allocation, teardown, namespace sharing, process entry, and signal delivery.

HOTPLUG
=======

1. Host calls userland_open().
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_USERLAND) (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() / fsconfig(FSCONFIG_SET_USERLAND) / 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
=======

v6:
- Rename rootns to userland (CONFIG_USERLAND, userland_open(), userland_ prefix, CLONE_INTO_USERLAND, FSCONFIG_SET_USERLAND, P_USERLAND, USERLAND_GET_NSFD).
- Replace ROOTNS_WAIT and ROOTNS_KILL ioctls with waitid(P_USERLAND) and pidfd_send_signal() support for userland file descriptors.
- Add build-phase USERLAND_SHARE_NSFD ioctl and security_userland_share() LSM hook to opt cgroup, IPC, UTS, network, or time namespaces into an existing nsfs fd before process entry.
- Pass USERNS_SETGROUPS_ALLOWED via userns_set_idmap() flags instead of in-struct request flags.
- Gate FSCONFIG_SET_USERLAND and unprivileged fsopen() on explicit FS_USERLAND_MOUNT opt-in (tmpfs, ramfs, devpts, proc, mqueue), refresh fc->cred on bind, bound userns_set_idmap() size to PAGE_SIZE (-E2BIG), enforce projid_map privilege checks and atomic ns->flags updates, fix cross-userns slave mount locking in attach_recursive_mnt(), reject SB_NOUSER and cross-mntns nsfs loops in MOVE_MOUNT_CLONE, and walk ancestor PIDNS_ADDING flags in CLONE_INTO_USERLAND (Sashiko).

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

v5: https://lore.kernel.org/linux-fsdevel/[email protected]/
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 Aleksa Sarai <[email protected]>
Cc Alexander Mikhalitsyn <[email protected]>
Cc Alexander Viro <[email protected]>
Cc Andy Lutomirski <[email protected]>
Cc Arnd Bergmann <[email protected]>
Cc Christian Brauner <[email protected]>
Cc David Howells <[email protected]>
Cc Giuseppe Scrivano <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Jan Kara <[email protected]>
Cc Jeff Layton <[email protected]>
Cc Jonathan Corbet <[email protected]>
Cc Josef Bacik <[email protected]>
Cc Kees Cook <[email protected]>
Cc KP Singh <[email protected]>
Cc Lennart Poettering <[email protected]>
Cc Neal Gompa <[email protected]>
Cc Oleg Nesterov <[email protected]>
Cc Paul Moore <[email protected]>
Cc Pavel Tikhomirov <[email protected]>
Cc Serge Hallyn <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Zygmunt Krynicki <[email protected]>

Jarkko Sakkinen (26):
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()
nsproxy: Expose create_new_namespaces()
userland: Add core infrastructure
userland: Track init lifecycle via copy_process() and pid_namespace
userland: Add userland_open() system call
userland: Add USERLAND_GET_NSFD ioctl
userland: Add USERLAND_SHARE_NSFD ioctl
exit: Support P_USERLAND in waitid()
signal: Support userland fds in pidfd_send_signal()
fork: Support CLONE_INTO_USERLAND in clone3()
fs: Support FSCONFIG_SET_USERLAND in fsconfig()
proc: Implement ->set_userland() fs_context operation ipc/mqueue: Implement ->set_userland() fs_context operation
security: Add userland LSM hooks
bpf: Register userland LSM hooks
arch: Wire up userland_open() system call
docs: Document userland uAPI
selftests/userland: Add userland test suite
MAINTAINERS: Add entry for USERLAND

 Documentation/userspace-api/index.rst         |    1 +
 .../userspace-api/ioctl/ioctl-number.rst      |    1 +
 Documentation/userspace-api/userland.rst      |   73 +
 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                             |    4 +-
 fs/filesystems.c                              |   15 +
 fs/fs_context.c                               |   21 +-
 fs/fsopen.c                                   |  137 +-
 fs/internal.h                                 |    7 +-
 fs/namespace.c                                |  352 ++-
 fs/proc/root.c                                |   26 +-
 fs/ramfs/inode.c                              |    2 +-
 include/linux/cred.h                          |    4 +-
 include/linux/fs.h                            |    1 +
 include/linux/fs_context.h                    |    6 +
 include/linux/lsm_hook_defs.h                 |    8 +
 include/linux/lsm_hooks.h                     |    3 +
 include/linux/mnt_namespace.h                 |    2 +
 include/linux/nsfs.h                          |    1 +
 include/linux/nsproxy.h                       |    8 +-
 include/linux/pid_namespace.h                 |    4 +
 include/linux/sched/task.h                    |    6 +
 include/linux/security.h                      |   37 +
 include/linux/syscalls.h                      |    5 +
 include/linux/user_namespace.h                |    9 +-
 include/linux/userland.h                      |  107 +
 include/uapi/asm-generic/unistd.h             |   10 +-
 include/uapi/linux/mount.h                    |    5 +-
 include/uapi/linux/nsfs.h                     |   46 +
 include/uapi/linux/sched.h                    |    5 +
 include/uapi/linux/userland.h                 |   58 +
 include/uapi/linux/wait.h                     |    1 +
 init/Kconfig                                  |   10 +
 ipc/mqueue.c                                  |   18 +-
 kernel/Makefile                               |    2 +
 kernel/bpf/bpf_lsm.c                          |   11 +
 kernel/cred.c                                 |   27 +-
 kernel/exit.c                                 |    4 +
 kernel/fork.c                                 |   71 +-
 kernel/nsproxy.c                              |   15 +-
 kernel/pid_namespace.c                        |    2 +
 kernel/signal.c                               |    4 +
 kernel/sys_ni.c                               |    4 +
 kernel/user_namespace.c                       |  419 ++-
 kernel/userland.c                             |  701 +++++
 mm/shmem.c                                    |    5 +-
 scripts/syscall.tbl                           |    2 +
 security/lsm_init.c                           |    6 +
 security/security.c                           |   72 +
 tools/include/uapi/asm-generic/unistd.h       |   10 +-
 .../perf/arch/arm/entry/syscalls/syscall.tbl  |    2 +
 .../arch/mips/entry/syscalls/syscall_n64.tbl  |    2 +
 .../arch/powerpc/entry/syscalls/syscall.tbl   |    2 +
 .../perf/arch/s390/entry/syscalls/syscall.tbl |    2 +
 tools/perf/arch/sh/entry/syscalls/syscall.tbl |    2 +
 .../arch/sparc/entry/syscalls/syscall.tbl     |    2 +
 .../arch/x86/entry/syscalls/syscall_32.tbl    |    2 +
 .../arch/x86/entry/syscalls/syscall_64.tbl    |    2 +
 .../arch/xtensa/entry/syscalls/syscall.tbl    |    2 +
 tools/scripts/syscall.tbl                     |    2 +
 tools/testing/selftests/Makefile              |    1 +
 tools/testing/selftests/userland/Makefile     |    5 +
 tools/testing/selftests/userland/config       |   10 +
 .../testing/selftests/userland/test_smoke.sh  |   10 +
 .../selftests/userland/userland_cells.py      | 1088 ++++++++
 .../selftests/userland/userland_test.py       | 2306 +++++++++++++++++
 82 files changed, 5663 insertions(+), 168 deletions(-)
 create mode 100644 Documentation/userspace-api/userland.rst
 create mode 100644 include/linux/userland.h
 create mode 100644 include/uapi/linux/userland.h
 create mode 100644 kernel/userland.c
 create mode 100644 tools/testing/selftests/userland/Makefile
 create mode 100644 tools/testing/selftests/userland/config
 create mode 100755 tools/testing/selftests/userland/test_smoke.sh
 create mode 100644 tools/testing/selftests/userland/userland_cells.py
 create mode 100755 tools/testing/selftests/userland/userland_test.py

--
2.47.3

#1 lore raw

RFC PATCH v6 1/26 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
#3 lore raw

RFC PATCH v6 2/26 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. Expose USERNS_SETGROUPS_ALLOWED in uapi/linux/nsfs.h as the flags bitmask when installing a GID mapping so setgroups(2) is disabled by default unless explicitly preserved. 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/linux/user_namespace.h |   2 -
 include/uapi/linux/nsfs.h      |  46 ++++++
 kernel/sys_ni.c                |   1 +
 kernel/user_namespace.c        | 258 +++++++++++++++++++++++++++++++++
 5 files changed, 309 insertions(+), 2 deletions(-)
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/linux/user_namespace.h +0 -2
index 91232053775d..b4a50edfe003 100644
@@ -35,8 +35,6 @@ struct uid_gid_map { /* 64 bytes -- 1 cache line */
 	};
 };
 
-#define USERNS_SETGROUPS_ALLOWED 1UL
-
 #define USERNS_INIT_FLAGS USERNS_SETGROUPS_ALLOWED
 
 struct ucounts;
include/uapi/linux/nsfs.h +46 -0

52 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 +258 -0

271 lines not on this page · raw message

Signature · 1 line
2.47.3
#5 lore raw

RFC PATCH v6 3/26 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, asm-generic unistd.h, and the mirrored copies under tools/.

---
 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 +
 tools/include/uapi/asm-generic/unistd.h             | 6 +++++-
 tools/perf/arch/arm/entry/syscalls/syscall.tbl      | 1 +
 tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl | 1 +
 tools/perf/arch/powerpc/entry/syscalls/syscall.tbl  | 1 +
 tools/perf/arch/s390/entry/syscalls/syscall.tbl     | 1 +
 tools/perf/arch/sh/entry/syscalls/syscall.tbl       | 1 +
 tools/perf/arch/sparc/entry/syscalls/syscall.tbl    | 1 +
 tools/perf/arch/x86/entry/syscalls/syscall_32.tbl   | 1 +
 tools/perf/arch/x86/entry/syscalls/syscall_64.tbl   | 1 +
 tools/perf/arch/xtensa/entry/syscalls/syscall.tbl   | 1 +
 tools/scripts/syscall.tbl                           | 1 +
 29 files changed, 37 insertions(+), 2 deletions(-)
arch/alpha/kernel/syscalls/syscall.tbl +1 -0
index 52e3538cc7df..60d330a51476 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_userns_set_idmap
arch/arm/tools/syscall.tbl +1 -0
index 55717ed32c27..d055515e98cd 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_userns_set_idmap
arch/arm64/tools/syscall_32.tbl +1 -0
index df2d1d82fb3c..a18982ead3bf 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_userns_set_idmap
arch/m68k/kernel/syscalls/syscall.tbl +1 -0
index ba7a4d8903d0..e89ec7d54b8c 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_userns_set_idmap
arch/microblaze/kernel/syscalls/syscall.tbl +1 -0
index 76d7cbe2a133..0dfcd6f9e4e7 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_userns_set_idmap
arch/mips/kernel/syscalls/syscall_n32.tbl +1 -0
index 9ae88e4eac61..882ff15f3e6d 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_userns_set_idmap
arch/mips/kernel/syscalls/syscall_n64.tbl +1 -0
index 83dc93a0712f..daa95049baef 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_userns_set_idmap
arch/mips/kernel/syscalls/syscall_o32.tbl +1 -0
index 9c62429c9b7b..9e0040399fef 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_userns_set_idmap
arch/parisc/kernel/syscalls/syscall.tbl +1 -0
index 88adc4016cce..b77482e68d1a 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_userns_set_idmap
arch/powerpc/kernel/syscalls/syscall.tbl +1 -0
index cfbb70039ff0..973562f20a94 100644
@@ -563,3 +563,4 @@
 470	common	listns				sys_listns
 471	nospu	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	nospu	userns_set_idmap		sys_userns_set_idmap
arch/s390/kernel/syscalls/syscall.tbl +1 -0
index 1b45e68a217b..19d7b234b31b 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_userns_set_idmap
arch/sh/kernel/syscalls/syscall.tbl +1 -0
index ace068dff0de..252e6f9aa04c 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_userns_set_idmap
arch/sparc/kernel/syscalls/syscall.tbl +1 -0
index 5b9fe0e8140f..1263d0e825c1 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_userns_set_idmap
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 2c172ef48dfd..0f8c81c584e0 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_userns_set_idmap
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index d5b6045b0090..5452b7567bf8 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_userns_set_idmap
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
arch/xtensa/kernel/syscalls/syscall.tbl +1 -0
index d354bb231796..f10b491c873c 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_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..7ba073cc0e80 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_userns_set_idmap
tools/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
tools/perf/arch/arm/entry/syscalls/syscall.tbl +1 -0
index 55717ed32c27..d055515e98cd 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_userns_set_idmap
tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl +1 -0
index 83dc93a0712f..daa95049baef 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_userns_set_idmap
tools/perf/arch/powerpc/entry/syscalls/syscall.tbl +1 -0
index cfbb70039ff0..973562f20a94 100644
@@ -563,3 +563,4 @@
 470	common	listns				sys_listns
 471	nospu	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	nospu	userns_set_idmap		sys_userns_set_idmap
tools/perf/arch/s390/entry/syscalls/syscall.tbl +1 -0
index 1b45e68a217b..19d7b234b31b 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_userns_set_idmap
tools/perf/arch/sh/entry/syscalls/syscall.tbl +1 -0
index ace068dff0de..252e6f9aa04c 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_userns_set_idmap
tools/perf/arch/sparc/entry/syscalls/syscall.tbl +1 -0
index 5b9fe0e8140f..1263d0e825c1 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_userns_set_idmap
tools/perf/arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 2c172ef48dfd..0f8c81c584e0 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_userns_set_idmap
tools/perf/arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index d5b6045b0090..5452b7567bf8 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_userns_set_idmap
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
tools/perf/arch/xtensa/entry/syscalls/syscall.tbl +1 -0
index d354bb231796..f10b491c873c 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_userns_set_idmap
tools/scripts/syscall.tbl +1 -0
index 0ab531605120..7ba073cc0e80 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_userns_set_idmap
Signature · 1 line
2.47.3
#6 lore raw

RFC PATCH v6 4/26 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
#7 lore raw

RFC PATCH v6 5/26 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
#9 lore raw

RFC PATCH v6 6/26 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             | 231 +++++++++++++++++++++++++++++++------
 include/uapi/linux/mount.h |   3 +-
 2 files changed, 196 insertions(+), 38 deletions(-)
fs/namespace.c +194 -37
index b2dc84c0d0d6..e21dd876dde3 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,16 @@ 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
+ * @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.
@@ -2632,13 +2643,15 @@ 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,
+				struct user_namespace *src_user_ns)
 {
 	struct mount *dest_mnt = dest->parent;
 	struct mountpoint *dest_mp = dest->mp;
 	HLIST_HEAD(tree_list);
 	struct mnt_namespace *ns = dest_mnt->mnt_ns;
 	struct user_namespace *user_ns = ns->user_ns;
+	bool cross_src = src_user_ns && !in_userns(ns->user_ns, src_user_ns);
 	struct pinned_mountpoint root = {};
 	struct mountpoint *shorter = NULL;
 	struct mount *child, *p;
@@ -2728,8 +2741,17 @@ 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 ||
+		    (cross_src &&
+		     !in_userns(child->mnt_parent->mnt_ns->user_ns,
+				src_user_ns))) {
 			lock_mnt_tree(child);
+			if (cross_src &&
+			    !in_userns(child->mnt_parent->mnt_ns->user_ns,
+				       src_user_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 +2959,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, NULL);
 }
 
 static int may_change_propagation(const struct mount *m)
@@ -3131,7 +3153,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 +3798,12 @@ 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 user_namespace *src_user_ns = NULL;
+	struct mnt_namespace *dest_mnt_ns;
 	int err;
 	bool beneath = flags & MNT_TREE_BENEATH;
 
@@ -3792,7 +3817,30 @@ 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;
+		src_user_ns = old->mnt_ns->user_ns;
+		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 +3888,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, src_user_ns);
 }
 
 static int do_move_mount_old(const struct path *path, const char *old_name)
@@ -3860,7 +3910,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 +4775,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 +4787,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 +4925,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 +4938,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 +4968,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
#11 lore raw

RFC PATCH v6 7/26 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             | 91 +++++++++++++++++++++++++++++---------
 include/uapi/linux/mount.h |  3 +-
 2 files changed, 73 insertions(+), 21 deletions(-)
fs/namespace.c +71 -20
index e21dd876dde3..57b4e8755fe9 100644
@@ -2573,6 +2573,7 @@ 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),
 };
 
 /**
@@ -3803,31 +3804,28 @@ static int do_move_mount(const struct path *old_path,
 {
 	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_target(old_path->dentry, target_mnt_ns))
+		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;
-		src_user_ns = old->mnt_ns->user_ns;
 		if (flags & MNT_TREE_MNTNS_INIT) {
 			if (mp.parent != target_mnt_ns->root)
 				return -EBUSY;
@@ -3840,6 +3838,36 @@ 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 ||
+			    (old->mnt.mnt_sb->s_flags & SB_NOUSER))
+				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 */
@@ -3879,23 +3907,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, src_user_ns);
+	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)
@@ -4821,8 +4862,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.
@@ -4830,6 +4871,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.
@@ -4931,12 +4977,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
#12 lore raw

RFC PATCH v6 8/26 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 b4a50edfe003..ecee91aa2257 100644
@@ -182,6 +182,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);
 
@@ -224,6 +225,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 e151ffc1f708..4a8a2ea67ddb 100644
@@ -1631,6 +1631,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);
@@ -1656,10 +1663,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
#13 lore raw

RFC PATCH v6 9/26 nsproxy: Expose create_new_namespaces()

In reply to Jarkko Sakkinen

create_new_namespaces() is currently static to kernel/nsproxy.c, preventing callers outside kernel/nsproxy.c from constructing a child nsproxy without mutating a task.

Expose create_new_namespaces() in <linux/nsproxy.h> so userland_open() can allocate a detached namespace set from current.

---
 include/linux/nsproxy.h | 4 ++++
 kernel/nsproxy.c        | 6 +++---
 2 files changed, 7 insertions(+), 3 deletions(-)
include/linux/nsproxy.h +4 -0
index dc2447f5f092..d611c40cb4ce 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,9 @@ static inline struct cred *nsset_cred(struct nsset *set)
  *
  */
 
+struct nsproxy *create_new_namespaces(u64 flags, struct task_struct *tsk,
+				      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 +3 -3
index 2dcf105e8ee2..3c4161515c3c 100644
@@ -85,9 +85,9 @@ 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 task_struct *tsk,
+				      struct user_namespace *user_ns,
+				      struct fs_struct *new_fs)
 {
 	struct nsproxy *new_nsp;
 	int err;
Signature · 1 line
2.47.3
#14 lore raw

RFC PATCH v6 10/26 userland: Add core infrastructure

In reply to Jarkko Sakkinen

Linux namespaces can be created and entered individually, but userspace orchestrators lack a single control object that binds a full detached namespace set and an init process lifecycle behind a pollable file descriptor. Because this object manages process lifecycle, wait and signal delivery, VFS mount delegation, and LSM state rather than representing an nsfs namespace entity, model it as a distinct userland abstraction.

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

---
 include/linux/userland.h      | 52 +++++++++++++++++++++
 include/uapi/linux/userland.h | 25 ++++++++++
 init/Kconfig                  | 10 ++++
 kernel/Makefile               |  2 +
 kernel/userland.c             | 87 +++++++++++++++++++++++++++++++++++
 5 files changed, 176 insertions(+)
 create mode 100644 include/linux/userland.h
 create mode 100644 include/uapi/linux/userland.h
 create mode 100644 kernel/userland.c
include/linux/userland.h new file +52 -0
new file mode 100644
index 000000000000..fa8628e1b89c
@@ -0,0 +1,52 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.
+ * Copyright (C) 2026 Opinsys Oy
+ */
+
+#ifndef _LINUX_USERLAND_H
+#define _LINUX_USERLAND_H
+
+#include <linux/refcount.h>
+#include <linux/spinlock.h>
+#include <linux/wait.h>
+
+struct file;
+struct nsproxy;
+struct pid;
+struct user_namespace;
+
+enum userland_state {
+	USERLAND_INIT		= 0,
+	USERLAND_FORKING	= 1,
+	USERLAND_RUNNING	= 2,
+	USERLAND_DEAD		= 3,
+};
+
+struct userland {
+	refcount_t		usage;
+	int			exit_code;
+	struct user_namespace	*user_ns;
+	struct nsproxy		*ns;
+	struct pid		*init_pid;
+	spinlock_t		lock;		/* Guards userland lifecycle state */
+	wait_queue_head_t	waitq;
+	unsigned int		flags;
+	enum userland_state	state;
+};
+
+#ifdef CONFIG_USERLAND
+void userland_put(struct userland *c);
+bool userland_is_file(struct file *file);
+#else
+static inline void userland_put(struct userland *c)
+{
+}
+
+static inline bool userland_is_file(struct file *file)
+{
+	return false;
+}
+#endif /* CONFIG_USERLAND */
+
+#endif /* _LINUX_USERLAND_H */
include/uapi/linux/userland.h new file +25 -0
new file mode 100644
index 000000000000..4a9031f81dda
@@ -0,0 +1,25 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+/*
+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.
+ * Copyright (C) 2026 Opinsys Oy
+ */
+
+#ifndef _UAPI_LINUX_USERLAND_H
+#define _UAPI_LINUX_USERLAND_H
+
+/**
+ * enum userland_flags - Flags for userland_open()
+ * @USERLAND_KILL_ON_CLOSE: Send %SIGKILL to userland init on final fd release.
+ * @USERLAND_CLOSE_ON_EXEC: Set %O_CLOEXEC on the returned control fd.
+ * @USERLAND_ALL_FLAGS: Mask of all valid flags accepted by userland_open().
+ *
+ * Every userland created by userland_open() allocates a full set of
+ * detached namespaces owned by a fresh user namespace.
+ */
+enum userland_flags {
+	USERLAND_KILL_ON_CLOSE	= 0x00000001,
+	USERLAND_CLOSE_ON_EXEC	= 0x00000002,
+	USERLAND_ALL_FLAGS	= 0x00000003,
+};
+
+#endif /* _UAPI_LINUX_USERLAND_H */
init/Kconfig +10 -0
index c8a7cfa60a6e..0c5fada1ba88 100644
@@ -1283,6 +1283,16 @@ config NET_NS
 
 endif # NAMESPACES
 
+config USERLAND
+	bool "Userland support"
+	depends on NAMESPACES && USER_NS && PID_NS && UTS_NS && IPC_NS && NET_NS && CGROUPS
+	help
+	  Allow user space to open and manage isolated userlands and their init
+	  process lifecycle through an anonymous-inode control file descriptor
+	  via userland_open(), waitid(P_USERLAND), pidfd_send_signal(),
+	  USERLAND_GET_NSFD, USERLAND_SHARE_NSFD, FSCONFIG_SET_USERLAND, and
+	  clone3() with CLONE_INTO_USERLAND.
+
 config CHECKPOINT_RESTORE
 	bool "Checkpoint/restore support"
 	depends on PROC_FS
kernel/Makefile +2 -0
index 4ff92e24680c..80eb26639776 100644
@@ -152,6 +152,8 @@ KCOV_INSTRUMENT_kstack_erase.o := n
 
 obj-$(CONFIG_SCF_TORTURE_TEST) += scftorture.o
 
+obj-$(CONFIG_USERLAND) += userland.o
+
 $(obj)/configs.o: $(obj)/config_data.gz
 
 # .config is small, so it is compressed with gzip rather than the image compressor.
kernel/userland.c new file +87 -0

87 lines not on this page · raw message

Signature · 1 line
2.47.3
#15 lore raw

RFC PATCH v6 11/26 userland: Track init lifecycle via copy_process() and pid_namespace

In reply to Jarkko Sakkinen

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

Commit the bootstrap child reaper and bind pid_ns->userland in userland_copy() after attach_pid(PIDTYPE_PID), and invoke userland_exit() from zap_pid_ns_processes() after the userland's PID namespace has killed and reaped all member tasks.

---
 include/linux/pid_namespace.h |  4 ++++
 include/linux/userland.h      | 17 ++++++++++++++
 kernel/fork.c                 |  3 +++
 kernel/pid_namespace.c        |  2 ++
 kernel/userland.c             | 43 +++++++++++++++++++++++++++++++++++
 5 files changed, 69 insertions(+)
include/linux/pid_namespace.h +4 -0
index b20baaa7e62b..ef703a3b8ed5 100644
@@ -15,6 +15,7 @@
 #define MAX_PID_NS_LEVEL 32
 
 struct fs_pin;
+struct userland;
 
 #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_USERLAND
+	struct userland *userland;
+#endif
 	struct ns_common ns;
 	struct work_struct	work;
 } __randomize_layout;
include/linux/userland.h +17 -0
index fa8628e1b89c..ec74eed6de1d 100644
@@ -9,11 +9,14 @@
 
 #include <linux/refcount.h>
 #include <linux/spinlock.h>
+#include <linux/uidgid.h>
 #include <linux/wait.h>
 
 struct file;
 struct nsproxy;
 struct pid;
+struct pid_namespace;
+struct task_struct;
 struct user_namespace;
 
 enum userland_state {
@@ -29,6 +32,7 @@ struct userland {
 	struct user_namespace	*user_ns;
 	struct nsproxy		*ns;
 	struct pid		*init_pid;
+	kuid_t			init_uid;
 	spinlock_t		lock;		/* Guards userland lifecycle state */
 	wait_queue_head_t	waitq;
 	unsigned int		flags;
@@ -38,6 +42,9 @@ struct userland {
 #ifdef CONFIG_USERLAND
 void userland_put(struct userland *c);
 bool userland_is_file(struct file *file);
+void userland_copy(struct task_struct *tsk, struct pid *pid,
+		   struct userland *userland);
+void userland_exit(struct pid_namespace *pid_ns, struct task_struct *tsk);
 #else
 static inline void userland_put(struct userland *c)
 {
@@ -47,6 +54,16 @@ static inline bool userland_is_file(struct file *file)
 {
 	return false;
 }
+
+static inline void userland_copy(struct task_struct *tsk, struct pid *pid,
+				 struct userland *userland)
+{
+}
+
+static inline void userland_exit(struct pid_namespace *pid_ns,
+				 struct task_struct *tsk)
+{
+}
 #endif /* CONFIG_USERLAND */
 
 #endif /* _LINUX_USERLAND_H */
kernel/fork.c +3 -0
index 5efceb8d58a7..2fceacc17e8a 100644
@@ -83,6 +83,7 @@
 #include <linux/fs_struct.h>
 #include <linux/magic.h>
 #include <linux/perf_event.h>
+#include <linux/userland.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))
+			userland_copy(p, pid, NULL);
 		nr_threads++;
 	}
 	total_forks++;
kernel/pid_namespace.c +2 -0
index 127a5fd23e70..70606d9c5b52 100644
@@ -24,6 +24,7 @@
 #include <linux/sched/signal.h>
 #include <linux/idr.h>
 #include <linux/nstree.h>
+#include <linux/userland.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);
+	userland_exit(pid_ns, me);
 	return;
 }
 
kernel/userland.c +43 -0

46 lines not on this page · raw message

Signature · 1 line
2.47.3
#17 lore raw

RFC PATCH v6 12/26 userland: Add userland_open() 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 userland_open() system call to allocate a userland owning a fresh user namespace alongside dedicated empty mount (CLONE_EMPTY_MNTNS), PID, UTS, IPC, network, cgroup, and time namespaces, and return its anonymous-inode file descriptor. Because a userland encapsulates process lifecycle and mount delegation rather than an nsfs namespace entity, keep it separate from namespace creation APIs. Finalize the nsproxy time namespace and pin active references for the lifetime of the userland.

---
 include/linux/syscalls.h |   1 +
 kernel/sys_ni.c          |   3 ++
 kernel/userland.c        | 107 +++++++++++++++++++++++++++++++++++++++
 3 files changed, 111 insertions(+)
include/linux/syscalls.h +1 -0
index 72308cc11908..2ea8ebd71743 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_userland_open(unsigned int flags);
 
 /*
  * Architecture-specific system calls
kernel/sys_ni.c +3 -0
index e3202e7cc2a1..fca9663d09b7 100644
@@ -399,3 +399,6 @@ COND_SYSCALL(rseq_slice_yield);
 
 COND_SYSCALL(uretprobe);
 COND_SYSCALL(uprobe);
+
+/* kernel/userland.c */
+COND_SYSCALL(userland_open);
kernel/userland.c +107 -0

110 lines not on this page · raw message

Signature · 1 line
2.47.3
#19 lore raw

RFC PATCH v6 13/26 userland: Add USERLAND_GET_NSFD ioctl

In reply to Jarkko Sakkinen

Standalone namespace operations such as userns_set_idmap() and move_mount(..., MOVE_MOUNT_T_MNTNS) operate on nsfs file descriptors, requiring a way to obtain member namespace fds from a userland file descriptor before any process has entered it.

Add the USERLAND_GET_NSFD ioctl to open an O_CLOEXEC nsfs file descriptor for a requested member namespace when the caller holds CAP_SYS_ADMIN in the userland's user namespace, additionally requiring an ancestor active PID namespace and a running init process for CLONE_NEWPID.

---
 fs/internal.h                 |  1 -
 include/linux/nsfs.h          |  1 +
 include/uapi/linux/userland.h | 19 +++++++++
 kernel/userland.c             | 76 +++++++++++++++++++++++++++++++++++
 4 files changed, 96 insertions(+), 1 deletion(-)
fs/internal.h +0 -1
index 3f2fbac40f8e..ee3f796241ac 100644
@@ -250,7 +250,6 @@ extern void mnt_pin_kill(struct mount *m);
  * fs/nsfs.c
  */
 extern const struct dentry_operations ns_dentry_operations;
-int open_namespace(struct ns_common *ns);
 struct file *open_namespace_file(struct ns_common *ns);
 
 /*
include/linux/nsfs.h +1 -0
index 731b67fc2fec..40912c1eb5ff 100644
@@ -23,6 +23,7 @@ bool ns_match(const struct ns_common *ns, dev_t dev, ino_t ino);
 int ns_get_name(char *buf, size_t size, struct task_struct *task,
 			const struct proc_ns_operations *ns_ops);
 void nsfs_init(void);
+int open_namespace(struct ns_common *ns);
 
 #define __current_namespace_from_type(__ns)				\
 	_Generic((__ns),						\
include/uapi/linux/userland.h +19 -0
index 4a9031f81dda..e81a06d6e9eb 100644
@@ -7,6 +7,8 @@
 #ifndef _UAPI_LINUX_USERLAND_H
 #define _UAPI_LINUX_USERLAND_H
 
+#include <linux/ioctl.h>
+
 /**
  * enum userland_flags - Flags for userland_open()
  * @USERLAND_KILL_ON_CLOSE: Send %SIGKILL to userland init on final fd release.
@@ -22,4 +24,21 @@ enum userland_flags {
 	USERLAND_ALL_FLAGS	= 0x00000003,
 };
 
+#define USERLAND_IOCTL_MAGIC	0xB9
+
+/**
+ * DOC: USERLAND_GET_NSFD
+ *
+ * ``ioctl(userland_fd, USERLAND_GET_NSFD, nstype)`` opens an ``nsfs`` file
+ * descriptor (with ``O_CLOEXEC``) for the member namespace identified by
+ * ``nstype`` (one of ``CLONE_NEWNS``, ``CLONE_NEWCGROUP``,
+ * ``CLONE_NEWUTS``, ``CLONE_NEWIPC``, ``CLONE_NEWUSER``, ``CLONE_NEWPID``,
+ * ``CLONE_NEWNET``, or ``CLONE_NEWTIME``).
+ *
+ * Requires ``CAP_SYS_ADMIN`` in the userland's user namespace.
+ * Opening ``CLONE_NEWPID`` additionally requires running in an ancestor
+ * active PID namespace and that userland init is running.
+ */
+#define USERLAND_GET_NSFD	_IO(USERLAND_IOCTL_MAGIC, 0x01)
+
 #endif /* _UAPI_LINUX_USERLAND_H */
kernel/userland.c +76 -0

100 lines not on this page · raw message

Signature · 1 line
2.47.3
#21 lore raw

RFC PATCH v6 14/26 userland: Add USERLAND_SHARE_NSFD ioctl

In reply to Jarkko Sakkinen

userland_open() isolates every namespace by default rather than relying on unshare() deny-listing, which prevents workloads such as host-networked sandboxes or sidecars sharing a network or IPC namespace from opting into specific existing namespaces.

Add the build-phase USERLAND_SHARE_NSFD ioctl to replace the userland's cgroup, IPC, UTS, network, or time namespace with a supplied nsfs file descriptor in-place under userland->lock while the userland is still in USERLAND_INIT, rejecting calls with -EBUSY once CLONE_INTO_USERLAND begins. Require CAP_SYS_ADMIN in the userland's user namespace, and require CAP_SYS_ADMIN in the target namespace's owning user namespace when the caller is not already a member of that namespace.

---
 include/uapi/linux/userland.h | 14 ++++++
 kernel/userland.c             | 92 +++++++++++++++++++++++++++++++++++
 2 files changed, 106 insertions(+)
include/uapi/linux/userland.h +14 -0
index e81a06d6e9eb..addb84e996f5 100644
@@ -41,4 +41,18 @@ enum userland_flags {
  */
 #define USERLAND_GET_NSFD	_IO(USERLAND_IOCTL_MAGIC, 0x01)
 
+/**
+ * DOC: USERLAND_SHARE_NSFD
+ *
+ * ``ioctl(userland_fd, USERLAND_SHARE_NSFD, ns_fd)`` replaces the corresponding
+ * member namespace of ``userland_fd`` with ``ns_fd`` (``CLONE_NEWCGROUP``,
+ * ``CLONE_NEWIPC``, ``CLONE_NEWUTS``, ``CLONE_NEWNET``, or ``CLONE_NEWTIME``)
+ * while ``userland_fd`` is in ``USERLAND_INIT``.
+ *
+ * Requires ``CAP_SYS_ADMIN`` in the userland's user namespace, plus
+ * ``CAP_SYS_ADMIN`` in ``ns_fd``'s owning user namespace when the caller is
+ * not already a member of ``ns_fd``.
+ */
+#define USERLAND_SHARE_NSFD	_IO(USERLAND_IOCTL_MAGIC, 0x02)
+
 #endif /* _UAPI_LINUX_USERLAND_H */
kernel/userland.c +92 -0

110 lines not on this page · raw message

Signature · 1 line
2.47.3
#22 lore raw

RFC PATCH v6 15/26 exit: Support P_USERLAND in waitid()

In reply to Jarkko Sakkinen

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

Add P_USERLAND to waitid() and wire kernel_waitid() to userland_waitid() to wait freezably and interruptibly on a userland file descriptor until the userland reaches USERLAND_DEAD and populate siginfo_t with init's caller-visible TGID, munged UID, and exit status without consuming it.

---
 include/linux/userland.h  | 10 +++++
 include/uapi/linux/wait.h |  1 +
 kernel/exit.c             |  4 ++
 kernel/userland.c         | 79 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 94 insertions(+)
include/linux/userland.h +10 -0
index ec74eed6de1d..1bab10d931b5 100644
@@ -16,8 +16,10 @@ struct file;
 struct nsproxy;
 struct pid;
 struct pid_namespace;
+struct rusage;
 struct task_struct;
 struct user_namespace;
+struct waitid_info;
 
 enum userland_state {
 	USERLAND_INIT		= 0,
@@ -45,6 +47,8 @@ bool userland_is_file(struct file *file);
 void userland_copy(struct task_struct *tsk, struct pid *pid,
 		   struct userland *userland);
 void userland_exit(struct pid_namespace *pid_ns, struct task_struct *tsk);
+long userland_waitid(int upid, struct waitid_info *infop, int options,
+		     struct rusage *ru);
 #else
 static inline void userland_put(struct userland *c)
 {
@@ -64,6 +68,12 @@ static inline void userland_exit(struct pid_namespace *pid_ns,
 				 struct task_struct *tsk)
 {
 }
+
+static inline long userland_waitid(int upid, struct waitid_info *infop,
+				   int options, struct rusage *ru)
+{
+	return -EINVAL;
+}
 #endif /* CONFIG_USERLAND */
 
 #endif /* _LINUX_USERLAND_H */
include/uapi/linux/wait.h +1 -0
index 85b809fc9f11..edd39c2cab96 100644
@@ -18,6 +18,7 @@
 #define P_PID		1
 #define P_PGID		2
 #define P_PIDFD		3
+#define P_USERLAND	4
 
 
 #endif /* _UAPI_LINUX_WAIT_H */
kernel/exit.c +4 -0
index d5e7bc2af804..5b0bd3a9187c 100644
@@ -71,6 +71,7 @@
 #include <linux/unwind_deferred.h>
 #include <linux/uaccess.h>
 #include <linux/pidfs.h>
+#include <linux/userland.h>
 
 #include <uapi/linux/wait.h>
 
@@ -1803,6 +1804,9 @@ static long kernel_waitid(int which, pid_t upid, struct waitid_info *infop,
 	struct wait_opts wo;
 	long ret;
 
+	if (which == P_USERLAND)
+		return userland_waitid(upid, infop, options, ru);
+
 	ret = kernel_waitid_prepare(&wo, which, upid, infop, options, ru);
 	if (ret)
 		return ret;
kernel/userland.c +79 -0

97 lines not on this page · raw message

Signature · 1 line
2.47.3
#24 lore raw

RFC PATCH v6 16/26 signal: Support userland fds in pidfd_send_signal()

In reply to Jarkko Sakkinen

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

Teach pidfd_send_signal() to dispatch userland file descriptors to userland_send_signal() when info is NULL and flags is 0. Require an ancestor active PID namespace, walk the userland's PID namespace IDR under tasklist_lock, and deliver a validated signal once to each thread group including in-flight forks, aggregating per-process delivery results.

---
 include/linux/userland.h | 10 +++++++
 kernel/signal.c          |  4 +++
 kernel/userland.c        | 59 ++++++++++++++++++++++++++++++++++++++++
 3 files changed, 73 insertions(+)
include/linux/userland.h +10 -0
index 1bab10d931b5..173c22c27ae9 100644
@@ -17,6 +17,7 @@ struct nsproxy;
 struct pid;
 struct pid_namespace;
 struct rusage;
+struct siginfo;
 struct task_struct;
 struct user_namespace;
 struct waitid_info;
@@ -49,6 +50,8 @@ void userland_copy(struct task_struct *tsk, struct pid *pid,
 void userland_exit(struct pid_namespace *pid_ns, struct task_struct *tsk);
 long userland_waitid(int upid, struct waitid_info *infop, int options,
 		     struct rusage *ru);
+int userland_send_signal(struct file *file, int sig,
+			 struct siginfo __user *info, unsigned int flags);
 #else
 static inline void userland_put(struct userland *c)
 {
@@ -74,6 +77,13 @@ static inline long userland_waitid(int upid, struct waitid_info *infop,
 {
 	return -EINVAL;
 }
+
+static inline int userland_send_signal(struct file *file, int sig,
+				       struct siginfo __user *info,
+				       unsigned int flags)
+{
+	return -EBADF;
+}
 #endif /* CONFIG_USERLAND */
 
 #endif /* _LINUX_USERLAND_H */
kernel/signal.c +4 -0
index dd770e68faee..5b11e67dc98a 100644
@@ -37,6 +37,7 @@
 #include <linux/capability.h>
 #include <linux/freezer.h>
 #include <linux/pid_namespace.h>
+#include <linux/userland.h>
 #include <linux/nsproxy.h>
 #include <linux/user_namespace.h>
 #include <linux/uprobes.h>
@@ -4181,6 +4182,9 @@ SYSCALL_DEFINE4(pidfd_send_signal, int, pidfd, int, sig,
 		if (fd_empty(f))
 			return -EBADF;
 
+		if (userland_is_file(fd_file(f)))
+			return userland_send_signal(fd_file(f), sig, info, flags);
+
 		/* Is this a pidfd? */
 		pid = pidfd_to_pid(fd_file(f));
 		if (IS_ERR(pid))
kernel/userland.c +59 -0

65 lines not on this page · raw message

Signature · 1 line
2.47.3
#26 lore raw

RFC PATCH v6 17/26 fork: Support CLONE_INTO_USERLAND 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_USERLAND and struct clone_args.userland (CLONE_ARGS_SIZE_VER3) to spawn a child process directly into a userland whose root mount has been installed. Transition the userland from USERLAND_INIT through USERLAND_FORKING to USERLAND_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/sched/task.h |   6 ++
 include/linux/userland.h   |  15 +++++
 include/uapi/linux/sched.h |   5 ++
 kernel/cred.c              |  27 +++++++-
 kernel/fork.c              |  70 ++++++++++++++++---
 kernel/nsproxy.c           |   9 ++-
 kernel/userland.c          | 133 +++++++++++++++++++++++++++++++++++++
 9 files changed, 260 insertions(+), 13 deletions(-)
include/linux/cred.h +3 -1
index 49c26af37349..e0bb4d3eab17 100644
@@ -19,6 +19,7 @@
 
 struct cred;
 struct inode;
+struct userland;
 
 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 userland *userland);
 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 d611c40cb4ce..17bd48433bba 100644
@@ -12,6 +12,7 @@ struct ipc_namespace;
 struct pid_namespace;
 struct cgroup_namespace;
 struct fs_struct;
+struct userland;
 struct user_namespace;
 
 /*
@@ -96,7 +97,8 @@ static inline struct cred *nsset_cred(struct nsset *set)
 struct nsproxy *create_new_namespaces(u64 flags, struct task_struct *tsk,
 				      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 userland *userland);
 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/sched/task.h +6 -0
index 90ed5bc3c7af..c21ac74d7b72 100644
@@ -16,6 +16,8 @@ struct task_struct;
 struct rusage;
 union thread_union;
 struct css_set;
+struct file;
+struct userland;
 
 /* All the bits taken by the old clone syscall. */
 #define CLONE_LEGACY_FLAGS 0xffffffffULL
@@ -39,11 +41,15 @@ struct kernel_clone_args {
 	/* Number of elements in *set_tid */
 	size_t set_tid_size;
 	int cgroup;
+	int userland_fd;
 	int idle;
 	int (*fn)(void *);
 	void *fn_arg;
 	struct cgroup *cgrp;
 	struct css_set *cset;
+	struct file *userland_file;
+	struct userland *userland;
+	bool userland_bootstrapping;
 	unsigned int kill_seq;
 };
 
include/linux/userland.h +15 -0
index 173c22c27ae9..3d24789ce7c2 100644
@@ -13,6 +13,7 @@
 #include <linux/wait.h>
 
 struct file;
+struct kernel_clone_args;
 struct nsproxy;
 struct pid;
 struct pid_namespace;
@@ -52,6 +53,9 @@ long userland_waitid(int upid, struct waitid_info *infop, int options,
 		     struct rusage *ru);
 int userland_send_signal(struct file *file, int sig,
 			 struct siginfo __user *info, unsigned int flags);
+int userland_prepare_fork(struct kernel_clone_args *args);
+int userland_finish_fork(struct kernel_clone_args *args,
+			 struct task_struct *p);
 #else
 static inline void userland_put(struct userland *c)
 {
@@ -84,6 +88,17 @@ static inline int userland_send_signal(struct file *file, int sig,
 {
 	return -EBADF;
 }
+
+static inline int userland_prepare_fork(struct kernel_clone_args *args)
+{
+	return -EINVAL;
+}
+
+static inline int userland_finish_fork(struct kernel_clone_args *args,
+				       struct task_struct *p)
+{
+	return 0;
+}
 #endif /* CONFIG_USERLAND */
 
 #endif /* _LINUX_USERLAND_H */
include/uapi/linux/sched.h +5 -0
index 19ffeba89428..30551f4cdedb 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_USERLAND	(1ULL << 38) /* Clone into a userland. */
 
 /*
  * 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.
+ * @userland:     If CLONE_INTO_USERLAND is specified set this to
+ *                a file descriptor for the userland.
  *
  * 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 userland;
 };
 #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 +26 -1
index d01df40a9a38..6bb83edd22b5 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/userland.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 userland *userland)
 {
 	struct cred *new;
 	int ret;
@@ -287,6 +294,24 @@ int copy_creds(struct task_struct *p, u64 clone_flags)
 	if (!new)
 		return -ENOMEM;
 
+	if (userland) {
+		const struct cred *old = current_cred();
+
+		if (new->user_ns != userland->user_ns) {
+			ret = install_user_ns_cred(new, userland->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 +61 -9

178 lines not on this page · raw message

kernel/nsproxy.c +8 -1
index 3c4161515c3c..90cf3c799152 100644
@@ -13,6 +13,7 @@
 #include <linux/export.h>
 #include <linux/nsproxy.h>
 #include <linux/ns/ns_common_types.h>
+#include <linux/userland.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, struct task_struct *tsk,
  * 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 userland *userland)
 {
 	struct nsproxy *old_ns = tsk->nsproxy;
 	struct user_namespace *user_ns = task_cred_xxx(tsk, user_ns);
 	struct nsproxy *new_ns;
 
+	if (userland) {
+		get_nsproxy(userland->ns);
+		tsk->nsproxy = userland->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)) {
kernel/userland.c +133 -0

142 lines not on this page · raw message

Signature · 1 line
2.47.3
#29 lore raw

RFC PATCH v6 18/26 fs: Support FSCONFIG_SET_USERLAND 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 userland.

Add FSCONFIG_SET_USERLAND and the ->set_userland() fs_context operation so callers holding CAP_SYS_ADMIN in the target userland's user namespace can bind a newly opened fs_context to that userland once before offering parameters. Gate userland context binding on explicit FS_USERLAND_MOUNT opt-in (or FS_USERNS_DELEGATABLE), mark tmpfs, ramfs, and devpts with FS_USERLAND_MOUNT, refresh fc->cred when FSCONFIG_SET_USERLAND authorizes and initializes the context, and keep devpts pty_reserve restricted to host mounts.

---
 fs/devpts/inode.c          |   4 +-
 fs/filesystems.c           |  15 ++++
 fs/fs_context.c            |  21 ++++--
 fs/fsopen.c                | 137 ++++++++++++++++++++++++++++++++++---
 fs/internal.h              |   6 ++
 fs/namespace.c             |  19 ++++-
 fs/ramfs/inode.c           |   2 +-
 include/linux/fs.h         |   1 +
 include/linux/fs_context.h |   6 ++
 include/uapi/linux/mount.h |   1 +
 mm/shmem.c                 |   5 +-
 11 files changed, 199 insertions(+), 18 deletions(-)
fs/devpts/inode.c +3 -1
index bd1e8eb26edb..921b67d18fa2 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->userland_bound &&
+	    fc->user_ns == &init_user_ns &&
 	    current->nsproxy->mnt_ns == init_task.nsproxy->mnt_ns)
 		fsi->mount_opts.reserve = true;
 
@@ -457,7 +459,7 @@ static struct file_system_type devpts_fs_type = {
 	.init_fs_context = devpts_init_fs_context,
 	.parameters	= devpts_param_specs,
 	.kill_sb	= devpts_kill_sb,
-	.fs_flags	= FS_USERNS_MOUNT,
+	.fs_flags	= FS_USERNS_MOUNT | FS_USERLAND_MOUNT,
 };
 
 /*
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 +129 -8

210 lines not on this page · raw message

fs/internal.h +6 -0
index ee3f796241ac..c7b57263ac83 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 57b4e8755fe9..9c4ac2df172d 100644
@@ -4705,16 +4705,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_USERLAND) &&
+	    !priv)
 		return -EPERM;
 
 	if (attr_flags & ~FSMOUNT_VALID_FLAGS)
@@ -4749,6 +4752,15 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 	if (ret)
 		return ret;
 
+	if (fc->userland_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)
@@ -4790,9 +4802,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->userland_bound ? fc->user_ns :
+			  current->nsproxy->mnt_ns->user_ns, true);
 	if (IS_ERR(ns))
 		return PTR_ERR(ns);
+	if (fc->userland_bound)
+		ns->seq_origin = fc->userland_mnt_id;
 	mnt = real_mount(new_path.mnt);
 	ns->root = mnt;
 	ns->nr_mounts = 1;
fs/ramfs/inode.c +1 -1
index ef91b933d4e6..d15542145704 100644
@@ -319,7 +319,7 @@ static struct file_system_type ramfs_fs_type = {
 	.init_fs_context = ramfs_init_fs_context,
 	.parameters	= ramfs_fs_parameters,
 	.kill_sb	= ramfs_kill_sb,
-	.fs_flags	= FS_USERNS_MOUNT,
+	.fs_flags	= FS_USERNS_MOUNT | FS_USERLAND_MOUNT,
 };
 
 static int __init init_ramfs_fs(void)
include/linux/fs.h +1 -0
index 5b3a100aba77..afb514600372 100644
@@ -2306,6 +2306,7 @@ struct file_system_type {
 #define FS_USERNS_MOUNT_RESTRICTED 512	/* Restrict mount in userns if not already visible */
 #define FS_USERNS_DELEGATABLE	1024	/* Can be mounted inside userns from outside */
 #define FS_DISALLOW_NOTIFY	2048	/* No fsnotify marks on its objects */
+#define FS_USERLAND_MOUNT	4096	/* Supports FSCONFIG_SET_USERLAND */
 #define FS_RENAME_DOES_D_MOVE	32768	/* FS will handle d_move() during rename() internally. */
 	int (*init_fs_context)(struct fs_context *);
 	const struct fs_parameter_spec *parameters;
include/linux/fs_context.h +6 -0
index d1727dffecc5..a98e5a40d54c 100644
@@ -23,6 +23,7 @@ struct net;
 struct pid_namespace;
 struct super_block;
 struct user_namespace;
+struct userland;
 struct vfsmount;
 struct path;
 
@@ -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			userland_mnt_id;	/* Target userland 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			userland_bound:1;	/* Bound via FSCONFIG_SET_USERLAND */
 };
 
 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_userland)(struct fs_context *fc, struct userland *userland);
 	int (*get_tree)(struct fs_context *fc);
 	int (*reconfigure)(struct fs_context *fc);
 };
include/uapi/linux/mount.h +1 -0
index cb4f7175db02..4c70c0183f5e 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_USERLAND	= 9,	/* Set target userland, supplied by fd */
 };
 
 /*
mm/shmem.c +3 -2
index 10cef89b00b0..61503304be6b 100644
@@ -5592,7 +5592,8 @@ static struct file_system_type shmem_fs_type = {
 	.parameters	= shmem_fs_parameters,
 #endif
 	.kill_sb	= kill_anon_super,
-	.fs_flags	= FS_USERNS_MOUNT | FS_ALLOW_IDMAP | FS_MGTIME,
+	.fs_flags	= FS_USERNS_MOUNT | FS_USERLAND_MOUNT |
+			  FS_ALLOW_IDMAP | FS_MGTIME,
 };
 
 #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS)
@@ -6021,7 +6022,7 @@ static struct file_system_type shmem_fs_type = {
 	.init_fs_context = ramfs_init_fs_context,
 	.parameters	= ramfs_fs_parameters,
 	.kill_sb	= ramfs_kill_sb,
-	.fs_flags	= FS_USERNS_MOUNT,
+	.fs_flags	= FS_USERNS_MOUNT | FS_USERLAND_MOUNT,
 };
 
 void __init shmem_init(void)
Signature · 1 line
2.47.3
#32 lore raw

RFC PATCH v6 19/26 proc: Implement ->set_userland() 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_USERLAND and leaving the context attached to the caller's PID namespace.

Wire up proc_set_userland() to verify that the target userland's PID namespace is a descendant of the caller's active PID namespace and rebind ctx->pid_ns and fc->user_ns accordingly, and mark proc with FS_USERLAND_MOUNT.

---
 fs/proc/root.c | 26 +++++++++++++++++++++++++-
 1 file changed, 25 insertions(+), 1 deletion(-)
fs/proc/root.c +25 -1
index 7fbbe92bf73a..e61b1a559172 100644
@@ -15,6 +15,8 @@
 #include <linux/sched/stat.h>
 #include <linux/module.h>
 #include <linux/bitops.h>
+#include <linux/nsproxy.h>
+#include <linux/userland.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->userland_bound) {
+			errorfc(fc, "cannot override pidns on userland-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_userland(struct fs_context *fc, struct userland *userland)
+{
+	struct proc_fs_context *ctx = fc->fs_private;
+	struct pid_namespace *target = userland->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_userland	= proc_set_userland,
 	.get_tree	= proc_get_tree,
 	.reconfigure	= proc_reconfigure,
 };
@@ -371,7 +393,9 @@ static struct file_system_type proc_fs_type = {
 	.init_fs_context	= proc_init_fs_context,
 	.parameters		= proc_fs_parameters,
 	.kill_sb		= proc_kill_sb,
-	.fs_flags		= FS_USERNS_MOUNT | FS_USERNS_MOUNT_RESTRICTED | FS_DISALLOW_NOTIFY_PERM,
+	.fs_flags		= FS_USERNS_MOUNT | FS_USERLAND_MOUNT |
+				  FS_USERNS_MOUNT_RESTRICTED |
+				  FS_DISALLOW_NOTIFY_PERM,
 };
 
 void __init proc_root_init(void)
Signature · 1 line
2.47.3
#33 lore raw

RFC PATCH v6 20/26 ipc/mqueue: Implement ->set_userland() 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_USERLAND and leaving the context bound to the caller's IPC namespace.

Wire up mqueue_set_userland() to switch ctx->ipc_ns to the target userland's IPC namespace, update fc->user_ns to match, and mark mqueue with FS_USERLAND_MOUNT.

---
 ipc/mqueue.c | 18 +++++++++++++++++-
 1 file changed, 17 insertions(+), 1 deletion(-)
ipc/mqueue.c +17 -1
index 322c3dd98c44..f3079f7d888b 100644
@@ -32,6 +32,7 @@
 #include <linux/mutex.h>
 #include <linux/nsproxy.h>
 #include <linux/pid.h>
+#include <linux/userland.h>
 #include <linux/ipc_namespace.h>
 #include <linux/user_namespace.h>
 #include <linux/slab.h>
@@ -400,6 +401,20 @@ static struct inode *mqueue_get_inode(struct super_block *sb,
 	return ERR_PTR(ret);
 }
 
+static int mqueue_set_userland(struct fs_context *fc, struct userland *userland)
+{
+	struct mqueue_fs_context *ctx = fc->fs_private;
+	struct ipc_namespace *ipc_ns;
+
+	scoped_guard(spinlock, &userland->lock)
+		ipc_ns = get_ipc_ns(userland->ns->ipc_ns);
+	put_ipc_ns(ctx->ipc_ns);
+	ctx->ipc_ns = ipc_ns;
+	put_user_ns(fc->user_ns);
+	fc->user_ns = get_user_ns(ipc_ns->user_ns);
+	return 0;
+}
+
 static int mqueue_fill_super(struct super_block *sb, struct fs_context *fc)
 {
 	struct inode *inode;
@@ -1613,6 +1628,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_userland	= mqueue_set_userland,
 	.get_tree	= mqueue_get_tree,
 };
 
@@ -1620,7 +1636,7 @@ static struct file_system_type mqueue_fs_type = {
 	.name			= "mqueue",
 	.init_fs_context	= mqueue_init_fs_context,
 	.kill_sb		= kill_anon_super,
-	.fs_flags		= FS_USERNS_MOUNT,
+	.fs_flags		= FS_USERNS_MOUNT | FS_USERLAND_MOUNT,
 };
 
 int mq_init_ns(struct ipc_namespace *ns)
Signature · 1 line
2.47.3
#34 lore raw

RFC PATCH v6 21/26 security: Add userland LSM hooks

In reply to Jarkko Sakkinen

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

Add lbs_userland and userland->security blob management alongside security_userland_alloc(), security_userland_free(), security_userland_share(), security_userland_clone(), and security_userland_kill().

---
 include/linux/lsm_hook_defs.h |  8 ++++
 include/linux/lsm_hooks.h     |  3 ++
 include/linux/security.h      | 37 ++++++++++++++++++
 include/linux/userland.h      |  3 ++
 kernel/userland.c             | 43 ++++++++++++++++-----
 security/lsm_init.c           |  6 +++
 security/security.c           | 72 +++++++++++++++++++++++++++++++++++
 7 files changed, 163 insertions(+), 9 deletions(-)
include/linux/lsm_hook_defs.h +8 -0
index 87d9d06710cb..be858bfdc534 100644
@@ -480,3 +480,11 @@ 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_USERLAND
+LSM_HOOK(int, 0, userland_alloc, struct userland *userland, unsigned int flags)
+LSM_HOOK(void, LSM_RET_VOID, userland_free, struct userland *userland)
+LSM_HOOK(int, 0, userland_share, struct userland *userland, struct ns_common *ns)
+LSM_HOOK(int, 0, userland_clone, struct userland *userland)
+LSM_HOOK(int, 0, userland_kill, struct userland *userland, int sig)
+#endif /* CONFIG_USERLAND */
include/linux/lsm_hooks.h +3 -0
index 13621e9e233e..7c18370ac427 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_USERLAND
+	unsigned int lbs_userland;
+#endif
 };
 
 /*
include/linux/security.h +37 -0
index 40831fab5470..2638ee1aa397 100644
@@ -84,6 +84,7 @@ struct audit_krule;
 struct ns_common;
 struct user_namespace;
 struct timezone;
+struct userland;
 
 enum lsm_event {
 	LSM_POLICY_CHANGE,
@@ -2469,4 +2470,40 @@ static inline void security_initramfs_populated(void)
 }
 #endif /* CONFIG_SECURITY */
 
+#ifdef CONFIG_USERLAND
+#ifdef CONFIG_SECURITY
+int security_userland_alloc(struct userland *userland, unsigned int flags);
+void security_userland_free(struct userland *userland);
+int security_userland_share(struct userland *userland, struct ns_common *ns);
+int security_userland_clone(struct userland *userland);
+int security_userland_kill(struct userland *userland, int sig);
+#else
+static inline int security_userland_alloc(struct userland *userland,
+					  unsigned int flags)
+{
+	return 0;
+}
+
+static inline void security_userland_free(struct userland *userland)
+{
+}
+
+static inline int security_userland_share(struct userland *userland,
+					  struct ns_common *ns)
+{
+	return 0;
+}
+
+static inline int security_userland_clone(struct userland *userland)
+{
+	return 0;
+}
+
+static inline int security_userland_kill(struct userland *userland, int sig)
+{
+	return 0;
+}
+#endif /* CONFIG_SECURITY */
+#endif /* CONFIG_USERLAND */
+
 #endif /* ! __LINUX_SECURITY_H */
include/linux/userland.h +3 -0
index 3d24789ce7c2..d472f14dd435 100644
@@ -33,6 +33,9 @@ enum userland_state {
 struct userland {
 	refcount_t		usage;
 	int			exit_code;
+#ifdef CONFIG_SECURITY
+	void			*security;
+#endif
 	struct user_namespace	*user_ns;
 	struct nsproxy		*ns;
 	struct pid		*init_pid;
kernel/userland.c +34 -9

115 lines not on this page · raw message

security/lsm_init.c +6 -0
index 8d5ecea99c46..b1af1d922c58 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_USERLAND
+	lsm_blob_size_update(&blobs->lbs_userland, &blob_sizes.lbs_userland);
+#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_USERLAND
+		lsm_pr("blob(userland) size %d\n", blob_sizes.lbs_userland);
+#endif
 	}
 
 	if (blob_sizes.lbs_file)
security/security.c +72 -0

81 lines not on this page · raw message

Signature · 1 line
2.47.3
#35 lore raw

RFC PATCH v6 22/26 bpf: Register userland LSM hooks

In reply to Jarkko Sakkinen

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

Register bpf_lsm_userland_alloc, bpf_lsm_userland_share, bpf_lsm_userland_clone, and bpf_lsm_userland_kill in sleepable_lsm_hooks, and bpf_lsm_userland_alloc and bpf_lsm_userland_free in untrusted_lsm_hooks under CONFIG_USERLAND.

---
 kernel/bpf/bpf_lsm.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
kernel/bpf/bpf_lsm.c +11 -0
index 468e63dbd922..ac8508a6b242 100644
@@ -16,6 +16,7 @@
 #include <linux/btf_ids.h>
 #include <linux/ima.h>
 #include <linux/bpf-cgroup.h>
+#include <linux/userland.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,12 @@ 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_USERLAND
+BTF_ID(func, bpf_lsm_userland_alloc)
+BTF_ID(func, bpf_lsm_userland_share)
+BTF_ID(func, bpf_lsm_userland_clone)
+BTF_ID(func, bpf_lsm_userland_kill)
+#endif /* CONFIG_USERLAND */
 BTF_SET_END(sleepable_lsm_hooks)
 
 BTF_SET_START(untrusted_lsm_hooks)
@@ -420,6 +427,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_USERLAND
+BTF_ID(func, bpf_lsm_userland_alloc)
+BTF_ID(func, bpf_lsm_userland_free)
+#endif /* CONFIG_USERLAND */
 BTF_SET_END(untrusted_lsm_hooks)
 
 bool bpf_lsm_is_sleepable_hook(u32 btf_id)
Signature · 1 line
2.47.3
#36 lore raw

RFC PATCH v6 23/26 arch: Wire up userland_open() system call

In reply to Jarkko Sakkinen

Now that userland lifecycle and VFS mount-tree installation are in place, expose userland_open() (474, 584 on Alpha) across all architecture system call tables, asm-generic unistd.h, and the mirrored copies under tools/.

---
 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 +
 tools/include/uapi/asm-generic/unistd.h             | 6 +++++-
 tools/perf/arch/arm/entry/syscalls/syscall.tbl      | 1 +
 tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl | 1 +
 tools/perf/arch/powerpc/entry/syscalls/syscall.tbl  | 1 +
 tools/perf/arch/s390/entry/syscalls/syscall.tbl     | 1 +
 tools/perf/arch/sh/entry/syscalls/syscall.tbl       | 1 +
 tools/perf/arch/sparc/entry/syscalls/syscall.tbl    | 1 +
 tools/perf/arch/x86/entry/syscalls/syscall_32.tbl   | 1 +
 tools/perf/arch/x86/entry/syscalls/syscall_64.tbl   | 1 +
 tools/perf/arch/xtensa/entry/syscalls/syscall.tbl   | 1 +
 tools/scripts/syscall.tbl                           | 1 +
 29 files changed, 37 insertions(+), 2 deletions(-)
arch/alpha/kernel/syscalls/syscall.tbl +1 -0
index 60d330a51476..2d66a28b610d 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_userns_set_idmap
+584	common	userland_open			sys_userland_open
arch/arm/tools/syscall.tbl +1 -0
index d055515e98cd..4d2608f907de 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
arch/arm64/tools/syscall_32.tbl +1 -0
index a18982ead3bf..2f3e7a4686bf 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
arch/m68k/kernel/syscalls/syscall.tbl +1 -0
index e89ec7d54b8c..ad1b3326c478 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
arch/microblaze/kernel/syscalls/syscall.tbl +1 -0
index 0dfcd6f9e4e7..4a9f4e1e7e31 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
arch/mips/kernel/syscalls/syscall_n32.tbl +1 -0
index 882ff15f3e6d..7483d569dcb0 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_userns_set_idmap
+474	n32	userland_open			sys_userland_open
arch/mips/kernel/syscalls/syscall_n64.tbl +1 -0
index daa95049baef..fe5c3ab9ffa7 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_userns_set_idmap
+474	n64	userland_open			sys_userland_open
arch/mips/kernel/syscalls/syscall_o32.tbl +1 -0
index 9e0040399fef..233e0b6850ae 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_userns_set_idmap
+474	o32	userland_open			sys_userland_open
arch/parisc/kernel/syscalls/syscall.tbl +1 -0
index b77482e68d1a..7c251ea35d4c 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
arch/powerpc/kernel/syscalls/syscall.tbl +1 -0
index 973562f20a94..b07ab66144b5 100644
@@ -564,3 +564,4 @@
 471	nospu	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
 473	nospu	userns_set_idmap		sys_userns_set_idmap
+474	nospu	userland_open			sys_userland_open
arch/s390/kernel/syscalls/syscall.tbl +1 -0
index 19d7b234b31b..4daa1f92e171 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
arch/sh/kernel/syscalls/syscall.tbl +1 -0
index 252e6f9aa04c..df51ac4faaf4 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
arch/sparc/kernel/syscalls/syscall.tbl +1 -0
index 1263d0e825c1..3db2b5a99b1f 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 0f8c81c584e0..68e3e01c8751 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_userns_set_idmap
+474	i386	userland_open		sys_userland_open
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index 5452b7567bf8..f8ad4c72a86e 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_userns_set_idmap
+474	common	userland_open		sys_userland_open
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
arch/xtensa/kernel/syscalls/syscall.tbl +1 -0
index f10b491c873c..b87586ff006c 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
include/uapi/asm-generic/unistd.h +5 -1
index 695eac2d356b..201335a08837 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/userland.c */
+#define __NR_userland_open 474
+__SYSCALL(__NR_userland_open, sys_userland_open)
+
 #undef __NR_syscalls
-#define __NR_syscalls 474
+#define __NR_syscalls 475
 
 /*
  * 32 bit systems traditionally used different
scripts/syscall.tbl +1 -0
index 7ba073cc0e80..c3d07ff911a7 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
tools/include/uapi/asm-generic/unistd.h +5 -1
index 695eac2d356b..201335a08837 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/userland.c */
+#define __NR_userland_open 474
+__SYSCALL(__NR_userland_open, sys_userland_open)
+
 #undef __NR_syscalls
-#define __NR_syscalls 474
+#define __NR_syscalls 475
 
 /*
  * 32 bit systems traditionally used different
tools/perf/arch/arm/entry/syscalls/syscall.tbl +1 -0
index d055515e98cd..4d2608f907de 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl +1 -0
index daa95049baef..fe5c3ab9ffa7 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_userns_set_idmap
+474	n64	userland_open			sys_userland_open
tools/perf/arch/powerpc/entry/syscalls/syscall.tbl +1 -0
index 973562f20a94..b07ab66144b5 100644
@@ -564,3 +564,4 @@
 471	nospu	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
 473	nospu	userns_set_idmap		sys_userns_set_idmap
+474	nospu	userland_open			sys_userland_open
tools/perf/arch/s390/entry/syscalls/syscall.tbl +1 -0
index 19d7b234b31b..4daa1f92e171 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
tools/perf/arch/sh/entry/syscalls/syscall.tbl +1 -0
index 252e6f9aa04c..df51ac4faaf4 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
tools/perf/arch/sparc/entry/syscalls/syscall.tbl +1 -0
index 1263d0e825c1..3db2b5a99b1f 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
tools/perf/arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 0f8c81c584e0..68e3e01c8751 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_userns_set_idmap
+474	i386	userland_open		sys_userland_open
tools/perf/arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index 5452b7567bf8..f8ad4c72a86e 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_userns_set_idmap
+474	common	userland_open		sys_userland_open
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
tools/perf/arch/xtensa/entry/syscalls/syscall.tbl +1 -0
index f10b491c873c..b87586ff006c 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
tools/scripts/syscall.tbl +1 -0
index 7ba073cc0e80..c3d07ff911a7 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_userns_set_idmap
+474	common	userland_open			sys_userland_open
Signature · 1 line
2.47.3
#37 lore raw

RFC PATCH v6 24/26 docs: Document userland uAPI

In reply to Jarkko Sakkinen

Userspace orchestrators need a clear specification of what a userland is, its build and live state transitions, USERLAND_GET_NSFD, USERLAND_SHARE_NSFD, waitid(P_USERLAND), pidfd_send_signal(), mount-tree construction, user namespace ID mapping, credential rules, and process creation semantics.

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

---
 Documentation/userspace-api/index.rst         |  1 +
 .../userspace-api/ioctl/ioctl-number.rst      |  1 +
 Documentation/userspace-api/userland.rst      | 73 +++++++++++++++++++
 3 files changed, 75 insertions(+)
 create mode 100644 Documentation/userspace-api/userland.rst
Documentation/userspace-api/index.rst +1 -0
index a68b1bea57a8..ac665b8fea72 100644
@@ -17,6 +17,7 @@ System calls
    :maxdepth: 1
 
    unshare
+   userland
    futex2
    ebpf/index
    ioctl/index
Documentation/userspace-api/ioctl/ioctl-number.rst +1 -0
index dbe462040999..4cf194e7b648 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/userland.h                                     userland uAPI
 0xBA  00-0F  uapi/linux/liveupdate.h                                   Pasha Tatashin
                                                                        <mailto:[email protected]>
 0xC0  00-0F  linux/usb/iowarrior.h
Documentation/userspace-api/userland.rst new file +73 -0

73 lines not on this page · raw message

Signature · 1 line
2.47.3
#39 lore raw

RFC PATCH v6 25/26 selftests/userland: Add userland test suite

In reply to Jarkko Sakkinen

Verify the userland_open() control object, namespace sharing, mount-namespace configuration, waitid(P_USERLAND), pidfd_send_signal(), 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/userland/Makefile     |    5 +
 tools/testing/selftests/userland/config       |   10 +
 .../testing/selftests/userland/test_smoke.sh  |   10 +
 .../selftests/userland/userland_cells.py      | 1088 ++++++++
 .../selftests/userland/userland_test.py       | 2306 +++++++++++++++++
 6 files changed, 3420 insertions(+)
 create mode 100644 tools/testing/selftests/userland/Makefile
 create mode 100644 tools/testing/selftests/userland/config
 create mode 100755 tools/testing/selftests/userland/test_smoke.sh
 create mode 100644 tools/testing/selftests/userland/userland_cells.py
 create mode 100755 tools/testing/selftests/userland/userland_test.py
tools/testing/selftests/Makefile +1 -0
index 07c3719f8b04..4bf12d0cfd1e 100644
@@ -145,6 +145,7 @@ TARGETS += tty
 TARGETS += ublk
 TARGETS += uevent
 TARGETS += user_events
+TARGETS += userland
 TARGETS += vDSO
 TARGETS += mm
 TARGETS += vfio
tools/testing/selftests/userland/Makefile new file +5 -0
new file mode 100644
index 000000000000..baf26c6780bb
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+include ../lib.mk
+
+TEST_PROGS := test_smoke.sh
+TEST_FILES := userland_cells.py userland_test.py
tools/testing/selftests/userland/config new file +10 -0
new file mode 100644
index 000000000000..c144ef706856
@@ -0,0 +1,10 @@
+CONFIG_CGROUPS=y
+CONFIG_IPC_NS=y
+CONFIG_NET_NS=y
+CONFIG_PID_NS=y
+CONFIG_PROC_FS=y
+CONFIG_TIME_NS=y
+CONFIG_TMPFS=y
+CONFIG_USER_NS=y
+CONFIG_UTS_NS=y
+CONFIG_USERLAND=y
tools/testing/selftests/userland/test_smoke.sh new file +10 -0
new file mode 100755
index 000000000000..fdd4aaa01804
@@ -0,0 +1,10 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0
+
+# Kselftest framework requirement - SKIP code is 4.
+ksft_skip=4
+
+command -v python3 >/dev/null 2>&1 || exit $ksft_skip
+
+DIR="$(dirname "$(readlink -f "$0")")"
+exec python3 "$DIR/userland_test.py" "$@"
tools/testing/selftests/userland/userland_cells.py new file +1088 -0

1,088 lines not on this page · raw message

tools/testing/selftests/userland/userland_test.py new file +2306 -0

1,880 lines not on this page · 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.

#42 lore raw

RFC PATCH v6 26/26 MAINTAINERS: Add entry for USERLAND

In reply to Jarkko Sakkinen

Record maintainership and mailing list routing for userlands across their uAPI headers, core implementation, documentation, and selftests.

---
 MAINTAINERS | 11 +++++++++++
 1 file changed, 11 insertions(+)
MAINTAINERS +11 -0
index 7cbce21ba45a..54d8f628cb87 100644
@@ -29285,6 +29285,17 @@ F:	arch/um/
 F:	arch/x86/um/
 F:	fs/hostfs/
 
+USERLAND
+M:	David Howells <[email protected]>
+M:	Jarkko Sakkinen <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	Documentation/userspace-api/userland.rst
+F:	include/linux/userland.h
+F:	include/uapi/linux/userland.h
+F:	kernel/userland.c
+F:	tools/testing/selftests/userland/
+
 USERSPACE COPYIN/COPYOUT (UIOVEC)
 M:	Alexander Viro <[email protected]>
 L:	[email protected]
Signature · 1 line
2.47.3
#40 lore raw

Re: [RFC PATCH v6 25/26] selftests/userland: Add userland test suite

In reply to Jarkko Sakkinen
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] selftests/userland: host /tmp mount leak in check_child_src_slave_locking() - [Medium]…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] selftests/userland: host /tmp mount leak in check_child_src_slave_locking()
- [Medium] selftests/userland: 64K-page E2BIG failure in test_userns_set_idmap()
- [Low] selftests/userland: Python 3.10+ parenthesized with-statements in test
--

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

selftests/userland: Add userland test suite

This commit adds a kselftest suite for the userland control object uAPI, covering namespace sharing, mount-namespace configuration, waitid(P_USERLAND), pidfd_send_signal(), and userns_set_idmap().

Quoted 6 lines
tools/testing/selftests/userland/userland_test.py new file +0 -0
new file mode 100755
index 0000000000000..eb29cbc9c8f10
@@ -0,0 +1,2306 @@

[ ... ]

tools/testing/selftests/userland/userland_test.py line 457

Quoted 4 lines
tools/testing/selftests/userland/userland_test.py new file +4 -0
+            with (
+                self.closing_fd(rns.get_nsfd(CloneFlag.NEWNS)) as mntns_fd,
+                self.closing_fd(rns.make_mount("tmpfs")) as rootfd,
+            ):

[Severity: Low]
Will parenthesized multi-item with-statements fail with a SyntaxError on Python 3.9?

Documentation/process/changes.rst specifies Python 3.9.x as the minimal supported version, whereas parenthesized context managers across multiple clauses were added in Python 3.10.

[ ... ]

tools/testing/selftests/userland/userland_test.py line 1068

Quoted 12 lines
tools/testing/selftests/userland/userland_test.py new file +12 -0
+            def check_child_src_slave_locking() -> None:
+                self.enter_userns_if_unpriv()
+                os.unshare(CloneFlag.NEWNS)
+                with self.closing_fd(self.make_plain_mount("tmpfs")) as tfd:
+                    os.mkdir("sub", 0o755, dir_fd=tfd)
+                    Sys.move_mount(
+                        tfd,
+                        "",
+                        Sys.AT_FDCWD,
+                        "/tmp",
+                        MoveMountFlag.F_EMPTY_PATH,
+                    )

[Severity: Medium]
When running as root, does check_child_src_slave_locking() propagate its tmpfs mount onto the host /tmp and leave it mounted after the test exits?

enter_userns_if_unpriv() is a no-op when os.geteuid() == 0, so os.unshare(CloneFlag.NEWNS) stays in the initial user namespace and preserves MS_SHARED peer groups with the host mount namespace. Mounting tfd onto /tmp without first calling Sys.set_mount_propagation("/") (as check_standalone_mntns() does) propagates a fresh tmpfs over the host /tmp, and cleanup only detaches /tmp/sub.

[ ... ]

tools/testing/selftests/userland/userland_test.py line 1796

Quoted 6 lines
tools/testing/selftests/userland/userland_test.py new file +6 -0
+            big_buf = ctypes.create_string_buffer(65536)
+            with self.assertRaises(OSError) as cm:
+                Sys.userns_set_idmap_raw(
+                    userns_fd, ctypes.addressof(big_buf), size=65536
+                )
+            self.assertEqual(cm.exception.errno, errno.E2BIG)

[Severity: Medium]
Does this assertion fail on kernels with 64 KiB (or larger) base pages?

userns_set_idmap() returns -E2BIG only when size > PAGE_SIZE. On a 64 KiB page kernel, size=65536 passes the PAGE_SIZE check, copy_struct_from_user() succeeds on the zero-filled buffer, and the syscall returns -EINVAL instead because the extent counts are all zero. Sizing the buffer with os.sysconf("SC_PAGE_SIZE") + 1 would exceed PAGE_SIZE on all architectures.

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

Re: [RFC PATCH v6 17/26] fork: Support CLONE_INTO_USERLAND in clone3()

In reply to Jarkko Sakkinen
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] userland: missing namespace owner permission check in userland_prepare_fork() - [Medium] userland…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] userland: missing namespace owner permission check in userland_prepare_fork()
- [Medium] userland: missing namespace_install LSM check in userland_prepare_fork()
--

commit 705db8da85300ec68db1d2ce6e9711aa2f376bb1
Author: Jarkko Sakkinen <[email protected]>

fork: Support CLONE_INTO_USERLAND in clone3()

This commit adds CLONE_INTO_USERLAND and struct clone_args.userland to allow clone3() to spawn a child process directly into an initialized userland's namespaces and root mount.

Quoted 9 lines
kernel/userland.c +1 -0
index 739f6b98c1035..283b90869d2c6 100644
@@ -541,3 +542,135 @@ SYSCALL_DEFINE1(userland_open, unsigned int, flags)
 
 	return fd;
 }
+

[ ... ]

Quoted 8 lines
kernel/userland.c +8 -0
+int userland_prepare_fork(struct kernel_clone_args *args)
+{
+	struct file *file __free(fput) = fget(args->userland_fd);
+	struct path root __free(path_put) = {};
+	struct pid_namespace *pid_ns;
+	bool bootstrapping = false;
+	struct userland *userland;
+	int ret;

kernel/userland.c SYSCALL_DEFINE1(userland_open, unsigned int, flags) · line 589

Quoted 10 lines
kernel/userland.c +10 -0
+
+	if (!file)
+		return -EBADF;
+	if (!userland_is_file(file))
+		return -EINVAL;
+
+	userland = file->private_data;
+	if (!ns_capable(userland->user_ns, CAP_SYS_ADMIN) ||
+	    !ns_capable(userland->user_ns, CAP_SYS_CHROOT))
+		return -EPERM;

[Severity: Medium]
Should userland_prepare_fork() also invoke security_namespace_install() or a matching LSM check for the target namespaces in userland->user_ns and userland->ns?

Landlock enforces LANDLOCK_PERMISSION_NAMESPACE_USE via its namespace_install hook when entering pre-opened namespaces with setns(), and commit "security: Add userland LSM hooks" later in this series does not wire Landlock up to security_userland_clone(). Without an LSM check on those namespaces, a Landlock-sandboxed task holding a pre-opened userland fd can use clone3(CLONE_INTO_USERLAND) to enter namespaces that its Landlock domain denies.

kernel/userland.c SYSCALL_DEFINE1(userland_open, unsigned int, flags) · line 595

Quoted 6 lines
kernel/userland.c +6 -0
+	if (current_chrooted() && !ns_capable(current_user_ns(), CAP_SYS_CHROOT))
+		return -EPERM;
+
+	pid_ns = userland->ns->pid_ns_for_children;
+	if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
+		return -EXDEV;

[Severity: High]
Does userland_prepare_fork() need to verify that current either already belongs to each namespace in userland->ns or holds CAP_SYS_ADMIN in that namespace's owning user namespace?

In userland_share_nsfd(), a cgroup, IPC, UTS, network, or time namespace owned by a more privileged user namespace (such as init_user_ns) can be attached to userland->ns without CAP_SYS_ADMIN in ns->ops->owner(ns) as long as the caller is currently in that namespace:

kernel/userland.c:userland_share_nsfd() {
    ...
	if (!ns_capable(c->user_ns, CAP_SYS_ADMIN))
		return -EPERM;
	if (!is_current_namespace(ns) &&
	    !ns_capable(ns->ops->owner(ns), CAP_SYS_ADMIN))
		return -EPERM;
    ...
}

Because userland_prepare_fork() only checks capabilities against userland->user_ns and current_user_ns() before copy_namespaces() installs userland->ns on the child, a process that shares a parent or host namespace into a userland and later isolates itself with unshare() (for example, unshare(CLONE_NEWNET)) can call clone3(CLONE_INTO_USERLAND) to spawn a child back into the unisolated namespace without holding CAP_SYS_ADMIN in its owning user namespace.

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

Re: [RFC PATCH v6 18/26] fs: Support FSCONFIG_SET_USERLAND in fsconfig()

In reply to Jarkko Sakkinen
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] devpts: missing fc->user_ns uid/gid mapping check in devpts_parse_param() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] devpts: missing fc->user_ns uid/gid mapping check in devpts_parse_param()
--

commit 3b686423ce72875c03141d25884aa118403b95e4
Author: Jarkko Sakkinen <[email protected]>

fs: Support FSCONFIG_SET_USERLAND in fsconfig()

This commit adds FSCONFIG_SET_USERLAND to bind an fs_context to a target userland's user and network namespaces before parameter configuration, and opts tmpfs, ramfs, and devpts into FS_USERLAND_MOUNT.

Quoted 4 lines
fs/devpts/inode.c +0 -0
index bd1e8eb26edb7..921b67d18fa2e 100644

[ ... ]

fs/devpts/inode.c static struct file_system_type devpts_fs_type = { · line 463

Quoted 7 lines
fs/devpts/inode.c +1 -1
@@ -457,7 +459,7 @@ static struct file_system_type devpts_fs_type = {
 	.init_fs_context = devpts_init_fs_context,
 	.parameters	= devpts_param_specs,
 	.kill_sb	= devpts_kill_sb,
-	.fs_flags	= FS_USERNS_MOUNT,
+	.fs_flags	= FS_USERNS_MOUNT | FS_USERLAND_MOUNT,
 };

[Severity: High]
Can opting devpts into FS_USERLAND_MOUNT allow an unprivileged user to create slave PTY device nodes owned by arbitrary host UIDs and GIDs that are not mapped in fc->user_ns?

When a process in init_user_ns binds a devpts context to a child userland via FSCONFIG_SET_USERLAND and passes uid or gid options, fs_param_is_uid() and fs_param_is_gid() resolve them against current_user_ns() rather than fc->user_ns. Unlike shmem_parse_one(), devpts_parse_param() does not verify kuid_has_mapping(fc->user_ns, result.uid) or kgid_has_mapping(fc->user_ns, result.gid):

fs/devpts/inode.c:devpts_parse_param() {
    ...
	case Opt_uid:
		opts->uid = result.uid;
		opts->setuid = 1;
		break;
	case Opt_gid:
		opts->gid = result.gid;
		opts->setgid = 1;
		break;
    ...
}

devpts_pty_new() then assigns opts->uid and opts->gid directly to inode->i_uid and inode->i_gid on the userns-owned superblock, allowing slave PTY device nodes to be created with unmapped host IDs such as GLOBAL_ROOT_UID.

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

Sashiko has finished reviewing this 26-patch series:

- Patches 1-16 and 19-24: no issues found.
- Patch 17 ("fork: Support CLONE_INTO_USERLAND in clone3()"): 2 potential issues (1 High, 1 Medium)
- Patch 18 ("fs: Support FSCONFIG_SET_USERLAND in fsconfig()"): 1 potential issue (1 High)
- Patch 25 ("selftests/userland: Add userland test suite"): 3 potential issues (2 Medium, 1 Low)
- Patch 26: skipped (not reviewed).

Detailed reviews have been sent as separate replies to patches 17, 18, and 25.

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

Re: [RFC PATCH v6 24/26] docs: Document userland uAPI

In reply to Jarkko Sakkinen
TL;DR: Documentation only: the new userland uAPI doc never defines the INIT/RUNNING/DEAD states or their transitions, so readers can't tell when USERLAND_SHARE_NSFD is allowed. Commit message also…
Quoted 1 line

docs: Document userland uAPI

TL;DR: Documentation only: the new userland uAPI doc never defines the INIT/RUNNING/DEAD states or their transitions, so readers can't tell when USERLAND_SHARE_NSFD is allowed. Commit message also misattributes ioctl docs to nsfs.h.

Quoted 8 lines

docs: Document userland uAPI

Userspace orchestrators need a clear specification of what a userland is, its build and live state transitions, USERLAND_GET_NSFD, USERLAND_SHARE_NSFD, waitid(P_USERLAND), pidfd_send_signal(), mount-tree construction, user namespace ID mapping, credential rules, and process creation semantics.

Quoted 8 lines

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

The message says the ioctl descriptions come from the listed files, including include/uapi/linux/nsfs.h. Is that accurate?

The only nsfs.h content included by userland.rst is:

.. kernel-doc:: include/uapi/linux/nsfs.h
:identifiers: userns_idmap_extent userns_flags userns_idmap

which documents the structures and enum used by userns_set_idmap(). The ioctl descriptions (USERLAND_GET_NSFD, USERLAND_SHARE_NSFD) come from include/uapi/linux/userland.h.

This isn't a bug, but the body paragraphs and the Signed-off-by tag are also not separated by blank lines in the message as rendered.

Quoted 9 lines
Documentation/userspace-api/userland.rst new file +3 -0
new file mode 100644
index 000000000000..47d5c39ccb1c
@@ -0,0 +1,73 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=============

Documentation/userspace-api/userland.rst line 13

Quoted 10 lines
Documentation/userspace-api/userland.rst new file +10 -0
+userland uAPI
+=============
+
+Overview
+========
+
+A userland is an anonymous-inode control object opened by ``userland_open()`` (not
+an ``nsfs`` namespace) that binds a detached namespace set, an initially empty
+mount namespace, an owning user namespace, and an init process lifecycle across
+build (``USERLAND_INIT``) and live (``USERLAND_RUNNING`` / ``USERLAND_DEAD``) phases.

Where are USERLAND_INIT, USERLAND_RUNNING and USERLAND_DEAD defined for the reader?

These states are not in any uapi header and are only used inside kernel/userland.c, and no section of this document defines them or the transitions between them. Yet the included sections rely on them:

USERLAND_SHARE_NSFD works only while userland_fd is in USERLAND_INIT P_USERLAND waits until USERLAND_DEAD
USERLAND_GET_NSFD for CLONE_NEWPID needs the init to be running

What moves a userland from USERLAND_INIT to USERLAND_RUNNING, and from USERLAND_RUNNING to USERLAND_DEAD? The commit message promises a specification of the build and live state transitions and of credential rules, but the document only has this one-paragraph overview plus the included kernel-doc, so a userspace reader cannot tell when USERLAND_SHARE_NSFD is still allowed.

[ ... ]

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44972669664

#2 lore raw

Re: [RFC PATCH v6 01/26] userns: Factor out idmap validation and commit helpers

In reply to Jarkko Sakkinen
TL;DR: Nit only: the smp_rmb() pairing comment in commit_new_idmap() names map_id_up(), which has no barrier; it should name map_id_range_up(), map_id_range_down() and m_start().
Quoted 1 line

userns: Factor out idmap validation and commit helpers

TL;DR: Nit only: the smp_rmb() pairing comment in commit_new_idmap() names map_id_up(), which has no barrier; it should name map_id_range_up(), map_id_range_down() and m_start().

Quoted 3 lines
kernel/user_namespace.c +0 -0

[ ... ]

kernel/user_namespace.c static bool verify_root_map(const struct file *file, · line 1009

Quoted 11 lines
kernel/user_namespace.c +11 -0
+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(). */
                                                         ^^^^^^^^^

This isn't a bug, but the comment doesn't match the readers that contain the paired smp_rmb(). map_id_up() has no barrier of its own:

    u32 map_id_up(const struct uid_gid_map *map, u32 id)
    {
            return map_id_range_up(map, id, 1);
    }

The barrier is in map_id_range_up(), which is also called directly (for example from statmount_mnt_idmap()). The procfs reader m_start() also pairs with this barrier:

    unsigned extents = map->nr_extents;
    smp_rmb();

Could the comment name map_id_range_down(), map_id_range_up() and m_start() instead?

kernel/user_namespace.c static bool verify_root_map(const struct file *file, · line 1013

Quoted 4 lines
kernel/user_namespace.c +4 -0
+	smp_wmb();
+	map->nr_extents = new_map->nr_extents;
+	memset(new_map, 0, sizeof(*new_map));
+}

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44972669664

#44 lore raw
In reply to Jarkko Sakkinen
Quoted 3 lines · Jarkko Sakkinen

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.

This text is out-of-date and need to be updated.

To put short, this is a continuation of "Failed" and "Repeatedly" :-)
[1]

When I looked David's patches in 2025, I thought that while the packaging might be a bit unfinished the mechanics made sense to me, so since then I've occasionally worked on this problem (with long pauses in-between).

The lack of embryonic state, a compact and policy-agnostic implementation,, the lack of weird parallel syscall API, clean allow-list security model (with LSM hooks) and the enablers for hotplug are I guess the main differentiators to the pre-existing science.

I used a lot of same thinking in the life-cycle model as in SGX driver, which can be seen e.g., as in the staircase initialization i.e., how ioctl's work and some other things. It was a reference of an isolated container I guess that pre-exist in mainline.

[1] https://lwn.net/Articles/1102593/

Br, Jarkko

#23 lore raw

Re: [RFC PATCH v6 15/26] exit: Support P_USERLAND in waitid()

In reply to Jarkko Sakkinen
TL;DR: A blocking waitid(P_USERLAND) may return an unexpected -EAGAIN if a failed clone3() bootstrap is retried while it sleeps; it should probably return -ECHILD or keep waiting.
Quoted 1 line

exit: Support P_USERLAND in waitid()

TL;DR: A blocking waitid(P_USERLAND) may return an unexpected -EAGAIN if a failed clone3() bootstrap is retried while it sleeps; it should probably return -ECHILD or keep waiting.

Quoted 3 lines
kernel/userland.c +0 -0

[ ... ]

Quoted 6 lines

+/**
+ * DOC: P_USERLAND
+ *
+ * ``waitid(P_USERLAND, userland_fd, &infop, options, NULL)`` waits freezably until
+ * ``userland_fd`` reaches ``USERLAND_DEAD`` (unless ``WNOHANG`` or ``O_NONBLOCK`` is
+ * set) and writes init's exit information into ``infop`` without consuming it.

[ ... ]

Quoted 5 lines
kernel/userland.c +5 -0
+	if (!nonblock) {
+		ret = wait_event_freezable(userland->waitq,
+					   READ_ONCE(userland->state) ==
+					   USERLAND_DEAD ||
+					   READ_ONCE(userland->state) ==

kernel/userland.c static long userland_share_nsfd(struct userland *c, unsigned long arg) · line 270

Quoted 10 lines
kernel/userland.c +10 -0
+					   USERLAND_INIT);
+		if (ret)
+			return ret;
+	}
+
+	scoped_guard(spinlock, &userland->lock) {
+		if (userland->state == USERLAND_INIT)
+			return -ECHILD;
+		if (userland->state != USERLAND_DEAD)
+			return (options & WNOHANG) ? 0 : -EAGAIN;

Can a blocking waitid(P_USERLAND) return -EAGAIN here, even though the DOC comment says it waits until USERLAND_DEAD unless WNOHANG or O_NONBLOCK is set?

The wait above ends on DEAD or INIT, but userland->lock is only taken after the wait returns, so the state can change in between. INIT is not terminal once 498ccb2ffbc4 ("fork: Support CLONE_INTO_USERLAND in clone3()") is
applied: userland_finish_fork() sets FORKING back to INIT under userland->lock when copy_process() fails, and then calls wake_up_all(&userland->waitq).

Sequence:

Task A: waitid(P_USERLAND, fd, &si, WEXITED, NULL), blocking fd
passes the early INIT check and sleeps in wait_event_freezable()

Task B: clone3(CLONE_INTO_USERLAND), state is FORKING
copy_process() fails (e.g. -EAGAIN from RLIMIT_NPROC) userland_finish_fork() sets INIT and wakes A

Task B or C: retries clone3(CLONE_INTO_USERLAND)
userland_prepare_fork() sees INIT and sets FORKING again

Task A: takes userland->lock, state is FORKING or RUNNING,
neither INIT nor DEAD, WNOHANG is clear, returns -EAGAIN

With neither WNOHANG nor O_NONBLOCK set, waitid() does not return -EAGAIN for P_PID or P_PIDFD, so a manager doing a blocking wait gets an error it has no reason to expect, possibly while the new init is running.

In the !nonblock case a non-DEAD state under the lock means a bootstrap failed, so should this return -ECHILD like the early INIT check, or go back to waiting? -EAGAIN and 0 would then only apply to the nonblock case.

userland_waitid() is unchanged through the end of the series, so no later commit fixes this. The path is only reachable once 498ccb2ffbc4 adds the FORKING state; in this commit the state never leaves INIT.

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44972669664

#16 lore raw

Re: [RFC PATCH v6 11/26] userland: Track init lifecycle via copy_process() and pid_namespace

In reply to Jarkko Sakkinen
TL;DR: userland_copy() may take c->lock inside siglock and tasklist_lock, while c->lock is taken with IRQs enabled elsewhere; this could trigger a lockdep report and a possible deadlock once…
Quoted 1 line

userland: Track init lifecycle via copy_process() and pid_namespace

TL;DR: userland_copy() may take c->lock inside siglock and tasklist_lock, while c->lock is taken with IRQs enabled elsewhere; this could trigger a lockdep report and a possible deadlock once CLONE_INTO_USERLAND goes live.

Quoted 3 lines
kernel/fork.c +0 -0

[ ... ]

Quoted 9 lines
kernel/fork.c +2 -0
@@ -2573,12 +2574,14 @@ __latent_entropy struct task_struct *copy_process(
 		attach_pid(p, PIDTYPE_PID);
+		if (thread_group_leader(p))
+			userland_copy(p, pid, NULL);
 		nr_threads++;
 	}
 	total_forks++;
 	hlist_del_init(&delayed.node);
 	spin_unlock(&current->sighand->siglock);

[ ... ]

Quoted 4 lines
kernel/userland.c +0 -0
@@ -82,6 +82,49 @@ static const struct file_operations userland_fops = {

[ ... ]

kernel/userland.c bool userland_is_file(struct file *file) · line 97

Quoted 9 lines
kernel/userland.c +9 -0
+void userland_copy(struct task_struct *tsk, struct pid *pid, struct userland *c)
+{
+	if (likely(!c || !is_child_reaper(pid)))
+		return;
+
+	scoped_guard(spinlock, &c->lock) {
+		if (c->state != USERLAND_FORKING)
+			return;
+		refcount_inc(&c->usage);

Can this nest c->lock inside siglock and tasklist_lock in an unsafe way?

userland_copy() is called from copy_process() while tasklist_lock is held for write with interrupts disabled, and while current->sighand->siglock is held:

    attach_pid(p, PIDTYPE_PID);
    if (thread_group_leader(p))
        userland_copy(p, pid, NULL);
    nr_threads++;
    ...
    spin_unlock(&current->sighand->siglock);
    write_unlock_irq(&tasklist_lock);

siglock is taken from hard interrupt context. For example, the ITIMER_REAL timer uses a non-soft hrtimer, and it_real_fn() -> kill_pid_info() -> do_send_sig_info() -> lock_task_sighand() takes siglock in hardirq. So holding siglock while acquiring c->lock records a siglock -> c->lock dependency.

Every other acquisition of c->lock in the series uses plain scoped_guard(spinlock, ...) with interrupts enabled: userland_release(), userland_exit(), and, from later commits, userland_prepare_fork(), userland_finish_fork(), userland_waitid(), userland_get_nsfd() and userland_share_nsfd(). That makes c->lock hardirq-unsafe while it is nested under a hardirq-safe lock, and lockdep should report "HARDIRQ-safe -> HARDIRQ-unsafe lock order detected" the first time a userland is bootstrapped on a CONFIG_PROVE_LOCKING kernel.

It also looks like a real deadlock:

CPU0: a second clone3(CLONE_INTO_USERLAND) caller in userland_prepare_fork() (or waitid(P_USERLAND), or USERLAND_SHARE_NSFD on the same userland) holds c->lock with IRQs enabled.

CPU1: the bootstrapping parent is in copy_process() holding tasklist_lock (write) and its siglock, and spins in userland_copy() on c->lock.

CPU0: takes the parent's ITIMER_REAL (or a posix-timer) hrtimer interrupt, and it_real_fn() spins on the parent's siglock, which CPU1 holds.

Neither CPU can make progress. This looks reachable without privilege, since userland_open() creates its own user namespace and the caller holds CAP_SYS_ADMIN/CAP_SYS_CHROOT there.

In this commit the call passes NULL, so userland_copy() returns early. The path becomes live with 498ccb2ffbc4 ("fork: Support CLONE_INTO_USERLAND in clone3()"), which changes the call to userland_copy(p, pid, args->userland). I don't see a later commit in the series that addresses this; at 942764a55437 every c->lock user still uses scoped_guard(spinlock, ...).

Should c->lock be taken IRQ-safe everywhere (spinlock_irq/spinlock_irqsave), or should the FORKING->RUNNING commit happen outside the tasklist_lock and siglock section?

kernel/userland.c bool userland_is_file(struct file *file) · line 102

Quoted 5 lines
kernel/userland.c +5 -0
+		ns_of_pid(pid)->userland = c;
+		WRITE_ONCE(c->init_pid, get_pid(pid));
+		WRITE_ONCE(c->state, USERLAND_RUNNING);
+	}
+}

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44972669664

#25 lore raw

Re: [RFC PATCH v6 16/26] signal: Support userland fds in pidfd_send_signal()

In reply to Jarkko Sakkinen
TL;DR: userland_send_signal() may miss a child forked by a parent outside the userland's PID namespace (e.g. after setns()), so a broadcast SIGSTOP/SIGTERM could skip it; otherwise the commit…
Quoted 1 line

signal: Support userland fds in pidfd_send_signal()

TL;DR: userland_send_signal() may miss a child forked by a parent outside the userland's PID namespace (e.g. after setns()), so a broadcast SIGSTOP/SIGTERM could skip it; otherwise the commit message needs narrowing.

Quoted 3 lines
kernel/userland.c +0 -0

[ ... ]

Quoted 3 lines
kernel/userland.c +3 -0
+int userland_send_signal(struct file *file, int sig,
+			 struct siginfo __user *info, unsigned int flags)
+{

[ ... ]

kernel/userland.c long userland_waitid(int upid, struct waitid_info *infop, int options, · line 327

Quoted 11 lines
kernel/userland.c +11 -0
+	scoped_guard(rcu) {
+		read_lock(&tasklist_lock);
+		idr_for_each_entry(&pid_ns->idr, pid, nr) {
+			struct task_struct *task = pid_task(pid, PIDTYPE_TGID);
+			int err;
+
+			if (!task)
+				continue;
+
+			err = group_send_sig_info(sig, SEND_SIG_NOINFO, task,
+						  PIDTYPE_MAX);

The commit message says the signal is delivered "once to each thread group including in-flight forks". Does that hold when the forking parent is not a member of the userland's PID namespace?

The delayed multiprocess signal handling only reaches a child if the parent itself is in pid_ns->idr, so that group_send_sig_info(..., PIDTYPE_MAX) hits the parent. A parent outside the userland can still create a member process, for example by calling setns() on the PID nsfd from USERLAND_GET_NSFD(CLONE_NEWPID) and then fork(). A later patch in this series, "fork: Support CLONE_INTO_USERLAND in clone3()", also lets subsequent callers join the running PID namespace.

In that case:

parent P (outside pid_ns) userland_send_signal()
copy_process()

    alloc_pid() -> idr_replace()
      child pid now in pid_ns->idr
                                     read_lock(&tasklist_lock)
                                     idr walk: pid_task(child, TGID) == NULL
                                       -> continue (skipped)
                                     P is not in pid_ns->idr, so it is
                                       never signalled
                                     read_unlock(&tasklist_lock); return 0
    write_lock_irq(&tasklist_lock)
    fatal_signal_pending(P) == false
    attach_pid(p, PIDTYPE_TGID)

child runs without the signal

The comment in copy_process() already notes "If current is not in the same namespace, we can't rely on fatal_signal_pending() below", and only the zap_pid_ns_processes() case is covered through the PIDNS_ADDING check.

Can a SIGSTOP, SIGTERM or SIGHUP broadcast miss a process that is being spawned or exec'd into the userland at the same moment? Should the walk cover these entrants, or should the commit message and the DOC comment be narrowed to forks by member processes?

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44972669664

#18 lore raw

Re: [RFC PATCH v6 12/26] userland: Add userland_open() system call

In reply to Jarkko Sakkinen
TL;DR: Nit only: the current->nsproxy NULL check and -EOPNOTSUPP return in userland_open() look unnecessary, since unshare() and setns() don't test it; could it be dropped?
Quoted 1 line

userland: Add userland_open() system call

TL;DR: Nit only: the current->nsproxy NULL check and -EOPNOTSUPP return in userland_open() look unnecessary, since unshare() and setns() don't test it; could it be dropped?

Quoted 3 lines
kernel/userland.c +0 -0

[ ... ]

kernel/userland.c void userland_exit(struct pid_namespace *pid_ns, struct task_struct *tsk) · line 224

Quoted 9 lines
kernel/userland.c +9 -0
+SYSCALL_DEFINE1(userland_open, unsigned int, flags)
+{
+	struct userland *c;
+	int fd;
+
+	if (flags & ~USERLAND_ALL_FLAGS)
+		return -EINVAL;
+	if (unlikely(!current->nsproxy))
+		return -EOPNOTSUPP;

This isn't a bug, but can current->nsproxy actually be NULL in a syscall here?

A task only loses its nsproxy in exit_task_namespaces() from do_exit(), after which it never returns to user mode. unshare() and setns() dereference current->nsproxy without such a test, and userland_create() itself passes current to create_new_namespaces(), which dereferences tsk->nsproxy unconditionally.

Could this check (and its -EOPNOTSUPP return) be dropped to match unshare()/setns()?

[ ... ]

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44972669664

#20 lore raw

Re: [RFC PATCH v6 13/26] userland: Add USERLAND_GET_NSFD ioctl

In reply to Jarkko Sakkinen
TL;DR: userland->lock is taken with irqs enabled but, once clone3(CLONE_INTO_USERLAND) lands later in the series, also under siglock; a possible deadlock lockdep would report. Latent at this commit.
Quoted 1 line

userland: Add USERLAND_GET_NSFD ioctl

TL;DR: userland->lock is taken with irqs enabled but, once clone3(CLONE_INTO_USERLAND) lands later in the series, also under siglock; a possible deadlock lockdep would report. Latent at this commit.

Quoted 3 lines
kernel/userland.c +0 -0

[ ... ]

Quoted 2 lines
kernel/userland.c +2 -0
+static long userland_get_nsfd(struct userland *userland, unsigned long nstype)
+{

[ ... ]

kernel/userland.c static __poll_t userland_poll(struct file *file, poll_table *wait) · line 84

Quoted 5 lines
kernel/userland.c +5 -0
+	scoped_guard(spinlock, &userland->lock) {
+		switch (nstype) {
+		case CLONE_NEWNS:
+			ns = from_mnt_ns(userland->ns->mnt_ns);
+			break;

[ ... ]

Can this lock be taken with hardirqs enabled? Later in the series, commit 498ccb2ffbc4 ("fork: Support CLONE_INTO_USERLAND in clone3()") passes args->userland to userland_copy(), and copy_process() calls it while holding write_lock_irq(&tasklist_lock) and spin_lock(&current->sighand->siglock):

copy_process()
write_lock_irq(&tasklist_lock)
spin_lock(&current->sighand->siglock)
userland_copy()

    scoped_guard(spinlock, &c->lock)

siglock is hardirq-safe, since it_real_fn() reaches it through kill_pid_info()->lock_task_sighand() from a hard hrtimer callback. That gives siglock -> userland->lock, with userland->lock taken here with irqs enabled, which lockdep will report and which can deadlock:

CPU0
ioctl(USERLAND_GET_NSFD, CLONE_NEWNET)
spin_lock(&userland->lock) irqs still enabled

CPU1
clone3(CLONE_INTO_USERLAND)
copy_process()

    write_lock_irq(&tasklist_lock)
    spin_lock(&parent->sighand->siglock)
    userland_copy()
      spins on userland->lock

CPU0
hardirq: parent's ITIMER_REAL fires
it_real_fn()
lock_task_sighand(parent) spins on siglock held by CPU1

GET_NSFD has no state check for types other than CLONE_NEWPID, so it can run while the userland is in USERLAND_INIT or USERLAND_FORKING, at the same time as the bootstrapping clone.

At this commit userland_copy() is still passed NULL, so this is latent until that later commit. userland_release(), userland_exit() and the later userland_share_nsfd() take the lock the same way, and the series up to 942764a55437 still uses scoped_guard(spinlock, ...) at every site. Should these sites use spinlock_irq, or should the userland_copy() bookkeeping move out of the tasklist_lock/siglock section?

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44972669664

#4 lore raw

Re: [RFC PATCH v6 02/26] userns: Add userns_set_idmap() system call

In reply to Jarkko Sakkinen
TL;DR: Design nit only: the new idmap permission checks in userns_set_idmap() seem to duplicate existing new_idmap_permitted()/verify_root_map() logic; the review suggests a shared helper. No bug is…
Quoted 1 line

userns: Add userns_set_idmap() system call

TL;DR: Design nit only: the new idmap permission checks in userns_set_idmap() seem to duplicate existing new_idmap_permitted()/verify_root_map() logic; the review suggests a shared helper. No bug is claimed.

Quoted 3 lines
kernel/user_namespace.c +0 -0

[ ... ]

Quoted 24 lines
kernel/user_namespace.c +24 -0
+static bool idmap_maps_root(const struct uid_gid_map *new_map)
+{
+	unsigned int idx;
+
+	for (idx = 0; idx < new_map->nr_extents; idx++) {
+		const struct uid_gid_extent *e;
+
+		if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
+			e = &new_map->extent[idx];
+		else
+			e = &new_map->forward[idx];
+		if (e->lower_first == 0)
+			return true;
+	}
+	return false;
+}
+
+static bool caller_idmap_permitted(struct user_namespace *ns, int cap_setid,
+				   unsigned long ns_flags,
+				   const struct uid_gid_map *new_map)
+{
+	const struct cred *cred = current_cred();
+
+	if (cap_setid == CAP_SETUID && idmap_maps_root(new_map)) {

[ ... ]

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

Quoted 3 lines
kernel/user_namespace.c +3 -0
+	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;

[ ... ]

This isn't a bug, but the root-mapping loop in idmap_maps_root() and the single-extent unprivileged block here look like copies of the logic in verify_root_map() and new_idmap_permitted(), differing only in where the cred (current_cred() vs file->f_cred) and the setgroups flags (ns_flags vs ns->flags) come from.

Could new_idmap_permitted()/verify_root_map() and caller_idmap_permitted()/idmap_maps_root() share a helper that takes the cred and the setgroups flags, so the unprivileged single-ID rule and the root-mapping test are written only once?

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44972669664

#8 lore raw

Re: [RFC PATCH v6 05/26] mount: Enforce mount_too_revealing() for foreign mntns

In reply to Jarkko Sakkinen
TL;DR: Nit only, not a bug: the CAP_SYS_ADMIN check on ns->user_ns in mount_too_revealing() is repeated, up to three times, and could be computed once and passed to mnt_already_visible().
Quoted 1 line

mount: Enforce mount_too_revealing() for foreign mntns

TL;DR: Nit only, not a bug: the CAP_SYS_ADMIN check on ns->user_ns in mount_too_revealing() is repeated, up to three times, and could be computed once and passed to mnt_already_visible().

Quoted 3 lines
fs/namespace.c +0 -0

[ ... ]

Quoted 7 lines
fs/namespace.c +1 -0
@@ -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;

[ ... ]

Quoted 9 lines
fs/namespace.c +0 -3
@@ -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))

fs/namespace.c static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flags · line 6670

Quoted 10 lines
fs/namespace.c +8 -0
 		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;
+

This isn't a bug, but could the CAP_SYS_ADMIN-over-ns->user_ns result be computed once in mount_too_revealing() and passed to mnt_already_visible(), rather than calling ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN) again for foreign_ns?

When ns->user_ns is &init_user_ns, the first check here is the same test as the second, and mnt_already_visible() evaluates it a third time.

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44972669664

#31 lore raw

Re: [RFC PATCH v6 18/26] fs: Support FSCONFIG_SET_USERLAND in fsconfig()

In reply to Jarkko Sakkinen
TL;DR: - fsmount() may call may_mount() needlessly for userland-bound contexts, possibly causing spurious LSM denial logs and BPF-LSM hooks - mount_api.rst may need updating for ->set_userland()
Quoted 1 line

fs: Support FSCONFIG_SET_USERLAND in fsconfig()

TL;DR:
- fsmount() may call may_mount() needlessly for userland-bound contexts, possibly causing spurious LSM denial logs and BPF-LSM hooks
- mount_api.rst may need updating for ->set_userland()

Quoted 3 lines
fs/namespace.c +0 -0

[ ... ]

Quoted 4 lines
fs/namespace.c +0 -0
@@ -4705,16 +4705,19 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 	struct vfsmount *new_mnt;
 	struct mount *mnt;
 	unsigned int mnt_flags = 0;

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

Quoted 10 lines
fs/namespace.c +2 -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;

Previously may_mount() was only called when FSMOUNT_NAMESPACE was clear. Now it runs on every fsmount() call, but priv is only read later in:

    } else if (!(flags & FSMOUNT_NAMESPACE) && !priv) {

so the result is discarded for FSMOUNT_NAMESPACE callers and for every userland-bound context.

may_mount() is an audited ns_capable() that goes through security_capable() and sets PF_SUPERPRIV on success. Can an external manager under an LSM policy that denies capability sys_admin but allows the user namespace check now trigger an LSM denial log entry and BPF-LSM capable programs on each userland-bound fsmount(), for a privilege the call does not need?

The other conditional callers in this file only evaluate it when the result matters:

    if ((flags & OPEN_TREE_CLONE) && !may_mount())
    if (!(flags & MOVE_MOUNT_T_MNTNS) && !may_mount())

Could may_mount() be called only on the unbound, non-FSMOUNT_NAMESPACE path once fc->userland_bound is known?

[ ... ]

Quoted 3 lines
include/linux/fs_context.h +0 -0

[ ... ]

include/linux/fs_context.h struct fs_context_operations { · line 128

Quoted 9 lines

struct fs_context_operations {

include/linux/fs_context.h +1 -0
@@ -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_userland)(struct fs_context *fc, struct userland *userland);
 	int (*get_tree)(struct fs_context *fc);
 	int (*reconfigure)(struct fs_context *fc);
 };

Documentation/filesystems/mount_api.rst keeps its own copy of struct fs_context_operations and documents each method. Should it be updated for ->set_userland(), the new userland_bound and userland_mnt_id fields and the new fs_context_phase states?

Filesystem implementers currently have to read fsconfig_set_userland() in fs/fsopen.c to learn the contract:

- it is called after ->init_fs_context() has run with fc->user_ns, fc->net_ns and fc->cred already rebound;
- it may rebind fc->user_ns, but must leave it equal to the userland's user namespace, or the bind fails with -EOPNOTSUPP;
- the context moves to FS_CONTEXT_FAILED on error.

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44972669664

#28 lore raw

Re: [RFC PATCH v6 17/26] fork: Support CLONE_INTO_USERLAND in clone3()

In reply to Jarkko Sakkinen
TL;DR: In clone3(CLONE_INTO_USERLAND), userland_copy() takes c->lock under tasklist_lock and siglock, but c->lock is taken elsewhere with interrupts enabled. This may deadlock system-wide, and…
Quoted 1 line

fork: Support CLONE_INTO_USERLAND in clone3()

TL;DR: In clone3(CLONE_INTO_USERLAND), userland_copy() takes c->lock under tasklist_lock and siglock, but c->lock is taken elsewhere with interrupts enabled. This may deadlock system-wide, and lockdep may report it.

Quoted 4 lines
kernel/fork.c +0 -0
index 2fceacc17e8a..3dd2c098bf32 100644

[ ... ]

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

Quoted 9 lines
kernel/fork.c +1 -1
@@ -2578,7 +2599,7 @@ __latent_entropy struct task_struct *copy_process(
 		}
 		attach_pid(p, PIDTYPE_PID);
 		if (thread_group_leader(p))
-			userland_copy(p, pid, NULL);
+			userland_copy(p, pid, args->userland);
 		nr_threads++;
 	}
 	total_forks++;

Before this patch userland_copy() was always called with a NULL userland and returned immediately. Now the bootstrapping CLONE_INTO_USERLAND child reaches this in copy_process() while holding write_lock_irq(&tasklist_lock) and spin_lock(&current->sighand->siglock):

    void userland_copy(struct task_struct *tsk, struct pid *pid,
                       struct userland *c)
    {
        if (likely(!c || !is_child_reaper(pid)))
            return;
        scoped_guard(spinlock, &c->lock) {
            ...

sighand->siglock is taken from hard interrupt context, for example it_real_fn() -> kill_pid_info() -> lock_task_sighand(), and posix_timer_fn() -> posix_timer_queue_signal().

Every other user of c->lock takes it with a plain spin_lock() and interrupts
enabled: userland_prepare_fork(), userland_finish_fork(), userland_waitid(), userland_get_nsfd(), userland_share_nsfd(), userland_release() and userland_exit().

Can this produce a HARDIRQ-safe -> HARDIRQ-unsafe lock order report from lockdep on the first bootstrap clone3(CLONE_INTO_USERLAND)?

It also looks like a real deadlock is possible:

CPU0
thread T2 of process P, in userland_prepare_fork() or waitid(P_USERLAND), holds c->lock with interrupts enabled
hrtimer interrupt for P's ITIMER_REAL runs it_real_fn()

    spins on P->sighand->siglock

CPU1
thread T1 of process P, in copy_process(), holds tasklist_lock for write and P->sighand->siglock

    userland_copy() spins on c->lock

Neither CPU can make progress, and since tasklist_lock is write-held, fork, exit and wait stall system-wide.

Should c->lock be taken with spin_lock_irq()/irqsave at every site, or should the FORKING -> RUNNING transition move out of the tasklist_lock/siglock section, for example into userland_finish_fork()? I did not find a later patch in the series (up to 942764a55437) that changes this.

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44972669664

#10 lore raw

Re: [RFC PATCH v6 06/26] mount: Support MOVE_MOUNT_T_MNTNS in move_mount()

In reply to Jarkko Sakkinen
TL;DR: Nits only in attach_recursive_mnt(): the repeated cross-userns condition could be computed once into a local, and the comment doesn't cover the new case.
Quoted 1 line

mount: Support MOVE_MOUNT_T_MNTNS in move_mount()

TL;DR: Nits only in attach_recursive_mnt(): the repeated cross-userns condition could be computed once into a local, and the comment doesn't cover the new case.

Quoted 3 lines
fs/namespace.c +0 -0

[ ... ]

Quoted 6 lines
fs/namespace.c +1 -1
@@ -2728,8 +2741,17 @@ 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 ||

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

Quoted 10 lines
fs/namespace.c +9 -0
+		    (cross_src &&
+		     !in_userns(child->mnt_parent->mnt_ns->user_ns,
+				src_user_ns))) {
 			lock_mnt_tree(child);
+			if (cross_src &&
+			    !in_userns(child->mnt_parent->mnt_ns->user_ns,
+				       src_user_ns) &&
+			    list_empty(&child->mnt_expire))
+				child->mnt.mnt_flags |= MNT_LOCKED;
+		}

This isn't a bug, but could the repeated test

    cross_src && !in_userns(child->mnt_parent->mnt_ns->user_ns, src_user_ns)

be computed once into a local here? It is evaluated in both the outer condition and the inner one, and child->mnt_parent->mnt_ns->user_ns is spelled out three times.

Also, the comment above ("Notice when we are propagating across user namespaces") doesn't describe the new arm, which fires for the mount the caller placed itself (child == source_mnt) when the source tree's owner is outside the destination's user namespace, with no propagation involved. Could the comment be updated to cover that case?

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44972669664

#41 lore raw

Re: [RFC PATCH v6 25/26] selftests/userland: Add userland test suite

In reply to Jarkko Sakkinen
TL;DR: - Selftest may fail on out-of-tree builds: ksft.py helper isn't installed (TEST_INCLUDES) - Plain i386 userspace on x86_64 may get x32 syscall numbers and wrongly skip - Time-namespace case…
Quoted 1 line

selftests/userland: Add userland test suite

TL;DR:
- Selftest may fail on out-of-tree builds: ksft.py helper isn't installed (TEST_INCLUDES)
- Plain i386 userspace on x86_64 may get x32 syscall numbers and wrongly skip
- Time-namespace case may fail without TIME_NS; a socket recv may hang on failure

tools/testing/selftests/userland/Makefile line 5

Quoted 11 lines
tools/testing/selftests/userland/Makefile new file +5 -0
new file mode 100644
index 000000000000..baf26c6780bb
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+include ../lib.mk
+
+TEST_PROGS := test_smoke.sh
+TEST_FILES := userland_cells.py userland_test.py

Will this suite run under an out-of-tree build such as "make O=/tmp/kselftest kselftest"?

With O= set, the run_tests recipe in lib.mk copies only $(TEST_PROGS) and $(TEST_FILES) into $(OUTPUT), and INSTALL_INCLUDES copies nothing because TEST_INCLUDES is not set.

test_smoke.sh then execs userland_test.py from the copied location, and KtapRunner._load_ksft() looks for the helper relative to that file:

    ksft_dir = str(Path(__file__).resolve().parents[1] / "kselftest")
    ...
    return importlib.import_module("ksft")

Nothing in that flow creates <dir>/kselftest/kselftest, so import_module() raises ModuleNotFoundError and run_one() records "not ok ... selftests: userland: test_smoke.sh # exit=1" even on a kernel with CONFIG_USERLAND=y.

Would adding the helper to TEST_INCLUDES keep the layout that _load_ksft() expects?

TEST_INCLUDES := ../kselftest/ksft.py

net/packetdrill/Makefile does this for ../../kselftest/ktap_helpers.sh.

[ ... ]

Quoted 4 lines
tools/testing/selftests/userland/userland_cells.py new file +0 -0
new file mode 100644

[ ... ]

tools/testing/selftests/userland/userland_cells.py line 324

Quoted 8 lines
tools/testing/selftests/userland/userland_cells.py new file +8 -0
+        elif mach == "x86_64" and ptr_size == 4:
+            base = 0x40000000
+            arch_legacy = {
+                "pivot_root": base + 155,
+                "umount2": base + 166,
+                "waitid": base + 529,
+                "execveat": base + 545,
+            }

Does this branch also catch plain i386 userspace running on an x86_64 kernel?

platform.machine() comes from uname(), and a 32-bit task only sees the compat machine string when it runs with PER_LINUX32:

    #define override_architecture(name) \
            (personality(current->personality) == PER_LINUX32 && \
             copy_to_user(name->machine, COMPAT_UTS_MACHINE, ...

So an i386 Docker image or chroot entered without linux32 reports mach == "x86_64" with ptr_size == 4, and gets the x32 numbering. The test then calls userland_open as 0x40000000 + 474 instead of 474, and do_syscall_32_irqs_on() returns -ENOSYS for nr >= IA32_NR_syscalls.

ENOSYS is in SKIP_ERRNOS, so probe_pre_idmap_mkdir() reports "userland_open() unavailable" and the suite exits KSFT_SKIP. The compat entry paths of userland_open, userns_set_idmap, clone3, fsconfig and waitid(P_USERLAND) are then never exercised in the configuration that needs them.

The function already tells these cases apart on other architectures. Would gating this branch on "x32" in multiarch, and sending the remaining x86_64/ptr_size == 4 case to the i386 numbers (217/52/284/358), work?

[ ... ]

Quoted 4 lines
tools/testing/selftests/userland/userland_test.py new file +0 -0
new file mode 100755

[ ... ]

tools/testing/selftests/userland/userland_test.py line 440

Quoted 11 lines
tools/testing/selftests/userland/userland_test.py new file +11 -0
+    def test_get_nsfd(self) -> None:
+        try:
+            rns = Userland()
+        except OSError as exc:
+            if exc.errno in SKIP_ERRNOS:
+                self.skipTest(f"userland_open() unavailable: {exc}")
+            raise
+        with rns:
+            for case in NS_TYPE_CASES:
+                with self.subTest(ns=case.name):
+                    with self.closing_fd(rns.get_nsfd(case.nstype)) as nsfd:

A subsystem pattern flags this as potentially concerning: test_get_nsfd() requires USERLAND_GET_NSFD to succeed for every entry in NS_TYPE_CASES, including NsTypeCase("time", CloneFlag.NEWTIME).

CONFIG_USERLAND does not depend on TIME_NS, and userland_get_nsfd() handles that configuration explicitly:

    case CLONE_NEWTIME:
    #ifdef CONFIG_TIME_NS
            ns = to_ns_common(userland->ns->time_ns);
            break;
    #else
            return -EOPNOTSUPP;
    #endif

On a CONFIG_USERLAND=y, CONFIG_TIME_NS=n kernel, the OSError(EOPNOTSUPP) is raised inside subTest(ns="time"), the test is marked failed, and KtapRunner.main() exits KSFT_FAIL. The selftest config fragment sets CONFIG_TIME_NS=y, so a run that follows it does not hit this.

Should the time case be skipped on EOPNOTSUPP? test_share_nsfd() already handles a missing time namespace with "if not os.path.exists(ns_path):
continue".

[ ... ]

Quoted 11 lines
tools/testing/selftests/userland/userland_test.py new file +11 -0
+        def check_dead_ancestor_pidns() -> None:
+            self.enter_userns_if_unpriv()
+            s_p, s_c = socket.socketpair(socket.AF_UNIX, socket.SOCK_DGRAM)
+            p1 = os.fork()
+            if p1 == 0:
+                s_p.close()
+                try:
+                    os.unshare(CloneFlag.NEWPID)
+                    p2 = os.fork()
+                    if p2 == 0:
+                        with Userland() as nested_u:

tools/testing/selftests/userland/userland_test.py line 1533

Quoted 10 lines
tools/testing/selftests/userland/userland_test.py new file +10 -0
+                            socket.send_fds(s_c, [b"U"], [nested_u.fd])
+                        os._exit(0)
+                    os._exit(self.reap_exit_code(p2))
+                finally:
+                    s_c.close()
+            s_c.close()
+            try:
+                _, recv_u, _, _ = socket.recv_fds(s_p, 1, 1)
+            finally:
+                s_p.close()

Can this recv_fds() block forever?

If p1's os.unshare(CloneFlag.NEWPID) fails, or p2's Userland() or send_fds() fails, nothing is ever sent. Closing the other end of an AF_UNIX SOCK_DGRAM socketpair does not wake the reader, because unix_release_sock() only sets the peer's sk_shutdown for SOCK_STREAM and SOCK_SEQPACKET.

p1 and p2 are forks of the run_forked() child, so their exceptions end in _exit(1) after writing a fail payload, while the run_forked() child stays blocked in recv_fds() and keeps the pipe's write end open. The parent then blocks in pipe.read_all(), so a failure turns into a hang. Under run_kselftest.sh the 45s default timeout kills it, and the tests that sort after test_clone_flags_and_pidns_ancestry never run.

create_userland_as_uid() in the same file guards the same fd-passing pattern with select.select([s_parent], [], [], 5.0). Would the same timeout, or a SOCK_SEQPACKET socketpair, turn this into a normal test failure?

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44972669664