nsexec: Staged namespace execution
Subsystems (36)
Jarkko Sakkinen
maintainerv9 cover nsexec: Staged namespace execution
MOTIVATION
==========
Self-modifying uninitialized state in containers is probably one of the biggest security challenges we have at the moment.
The primitives for namespaces, credentials, and mounts were designed to be invoked from inside the process being isolated, one step at a time.
Container runtimes and sandboxes (runc, systemd-nspawn, bubblewrap, etc.) approach the problem with a chain of short-lived helper processes, which are managed by pausing them behind pipes or socket pairs.
While this is happening, the parent process does the whole shebang of obscure management tasks:
1. Writes /proc/<pid>/uid_map and /proc/<pid>/gid_map.
2. Clones the host's entire mount table only to tear it back down with pivot_root() and fork yet again before PID 1 can finally call execve().
runc has one of the worst-case scenarios in this regard given that the Go runtime is always multi-threaded. This disallows calling unshare(CLONE_NEWUSER | CLONE_NEWNS) or setns(CLONE_NEWUSER) directly from Go. The workaround addressing this is based on a C trampoline.
I.e., packing the cargo happens exactly at the time when the ship is lifting the anchor and detaching from the harbor, and with the current syscall API there's no common-sense way around this.
For what it is worth, any practical cryptography such as authenticated measurement is also not doable, because the primitives can only measure a static and immutable target.
OVERVIEW
========
If the root of the problem is that an isolated process has to assemble its own prison from the inside while already running, the natural alternative is to invert the sequence: construct the entire execution environment from the outside while it is still inert, and only spawn a process once setup is complete.
Building on David Howells' earlier work on kernel container objects [1], this series introduces nsexec: an anonymous-inode control descriptor that splits namespace setup and process execution into distinct build and live phases.
Opening an nsexec descriptor allocates a fresh user namespace together with a detached set of mount, PID, UTS, IPC, network, cgroup, and time namespaces. Crucially, the mount namespace starts completely empty (CLONE_EMPTY_MNTNS) rather than cloning the caller's mount table, and no task exists inside any of the new namespaces during the build phase (NSEXEC_INIT).
Because the caller's own credentials, root directory, and thread group are never mutated during construction, even a multi-threaded runtime such as Go can drive the entire setup directly over file descriptors without helper processes or C trampolines. Rather than introducing a parallel namespace API, nsexec plugs into existing descriptor-based syscalls for ID mapping, filesystem configuration, mount placement, process creation, waiting, and signaling.
[1] https://lwn.net/Articles/780364/
SOLUTION
========
The standalone primitives at the front of the series (patches 01-09) make both user namespaces and mount namespaces configurable via nsfs file descriptors without a paused child task, while the remaining patches tie them together around the nsexec lifecycle.
1. Allocating namespaces and programming ID maps
A manager begins by calling nsexec_open(), which returns a close-on-exec control descriptor in NSEXEC_INIT. While in this build phase, the manager can optionally opt individual cgroup, IPC, UTS, network, or time namespaces into existing nsfs descriptors via ioctl(NSEXEC_SHARE_NSFD), or extract nsfs descriptors for member namespaces via ioctl(NSEXEC_GET_NSFD).
Instead of formatting text into /proc/<pid>/uid_map and gid_map while a helper blocks on a pipe, userns_set_idmap() programs UID, GID, and project ID extents (along with USERNS_SETGROUPS_ALLOWED) atomically on the user namespace descriptor:
nsexec_fd = nsexec_open(NSEXEC_AUTOKILL);
userns_fd = ioctl(nsexec_fd, NSEXEC_GET_NSFD, CLONE_NEWUSER);
mntns_fd = ioctl(nsexec_fd, NSEXEC_GET_NSFD, CLONE_NEWNS);
struct userns_idmap_extent ext = {
.first = 0,
.lower_first = 1000,
.count = 1,
};
struct userns_idmap map = {
.nr_uid_extents = 1,
.nr_gid_extents = 1,
.uid_extents = (__u64)(uintptr_t)&ext,
.gid_extents = (__u64)(uintptr_t)&ext,
};
userns_set_idmap(userns_fd, &map, sizeof(map), 0);Parent ID ranges are authorized against the caller of userns_set_idmap(), allowing an unprivileged runtime to pass userns_fd over SCM_RIGHTS to a privileged mapping helper without keeping an embryonic child alive.
2. Assembling the mount tree without pivot_root()
With ID mappings in place, superblocks can be instantiated directly inside the nsexec's user, network, PID (proc), and IPC (mqueue) namespaces by binding a mount-API context via FSCONFIG_SET_NSEXEC. Filesystems opt into unprivileged delegation with FS_NSEXEC_MOUNT (tmpfs, ramfs, devpts, proc, and mqueue) or FS_USERNS_DELEGATABLE.
To populate the empty mount namespace without entering it, move_mount() learns two flags: MOVE_MOUNT_T_MNTNS resolves to_dfd as a mount namespace descriptor (attaching "/" onto its nullfs root once, and resolving relative paths beneath that root thereafter), and MOVE_MOUNT_CLONE recursively bind-clones a source tree without requiring OPEN_TREE_CLONE or host CAP_SYS_ADMIN:
fs_fd = fsopen("tmpfs", FSOPEN_CLOEXEC);
fsconfig(fs_fd, FSCONFIG_SET_NSEXEC, NULL, NULL, nsexec_fd);
fsconfig(fs_fd, FSCONFIG_CMD_CREATE, NULL, NULL, 0);
root_fd = fsmount(fs_fd, FSMOUNT_CLOEXEC, 0);
mkdirat(root_fd, "usr", 0755);
move_mount(root_fd, "", mntns_fd, "/",
MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_MNTNS);
move_mount(AT_FDCWD, "/usr", mntns_fd, "usr",
MOVE_MOUNT_T_MNTNS | MOVE_MOUNT_CLONE);Mounts crossing user namespace boundaries are locked with MNT_LOCKED, and LSMs mediate MOVE_MOUNT_CLONE as MS_BIND | MS_REC. The same MOVE_MOUNT_T_MNTNS path remains available after boot for live mount hotplug, which workloads can observe via fanotify(FAN_MNT_ATTACH) and statmount().
3. Spawning PID 1 and supervising the lifecycle
Once "/" has been installed, clone3() with CLONE_INTO_NSEXEC spawns the first child directly into the configured environment as PID 1, transitioning the descriptor from NSEXEC_INIT through NSEXEC_FORKING to NSEXEC_RUNNING:
struct clone_args args = {
.flags = CLONE_INTO_NSEXEC,
.nsexec = nsexec_fd,
};
pid = clone3(&args, sizeof(args));
if (pid == 0)
execve("/sbin/init", argv, envp);
waitid(P_NSEXEC, nsexec_fd, &info, WEXITED);Subsequent CLONE_INTO_NSEXEC calls join the running PID namespace directly for management or diagnostic sessions. To prevent half-transitioned task state, CLONE_VM, CLONE_FILES, CLONE_FS, and CLONE_SIGHAND are rejected; when the caller originates outside the target user namespace, exec_state->user_ns stays anchored in that outer namespace with dumpability reset to suid_dumpable until execve(), blocking member tasks from tracing the child or reading /proc/<pid>/{exe,mem,fd}.
At runtime, pidfd_send_signal() broadcasts signals across member thread groups, poll() reports EPOLLHUP once PID 1 exits and the PID namespace is reaped, and waitid(P_NSEXEC) reads init's exit status without consuming it. Dedicated LSM hooks (wired into Landlock and BPF LSM) mediate allocation, namespace sharing, process entry, and signaling.
Experimental userspace support with runtime fallback on older kernels is maintained for systemd [2], bubblewrap [3], and podman [4], integrated end to end in linux-tpmdd-test [5].
[2] https://github.com/jarkkojs/systemd/commits/nsexec
[3] https://github.com/jarkkojs/bubblewrap/commits/nsexec
[4] https://github.com/jarkkojs/podman/commits/nsexec
[5] https://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd-test.git/
CHANGES
=======
v9:
- The main theme is the refactorization of userland_open() into nsexec() and rewriting the cover letter to be focused on execution rather than data structures, as latter should be only consequence of the former.
- Rewrite the kselftest as a seed-replayable model-based fuzzer.
- Rename userland to nsexec across syscalls, ioctls, clone3(), waitid(), fsconfig(), LSM hooks, documentation, selftests, and MAINTAINERS.
- Rename USERLAND_KILL_ON_CLOSE to NSEXEC_AUTOKILL and drop USERLAND_CLOEXEC in favor of unconditional O_CLOEXEC on nsexec_open().
- Recheck CAP_SYS_ADMIN on fc->user_ns after ->set_nsexec(), gate FSCONFIG_SET_NSEXEC on CONFIG_NSEXEC, preserve proc and mqueue namespaces on FS_CONTEXT_FOR_RECONFIGURE, and validate proc gid= against fc->user_ns via fsparam_gid().
- NOTE: Despite the patch set size grows, the feature size does not, which is about 2400 lines added and 260 removed. This patch set is dominated by the Python test suite (for a good reason).
v8:
- Pass MOVE_MOUNT_* flags to security_move_mount(), mediate MOVE_MOUNT_CLONE as MS_BIND | MS_REC in AppArmor, and enforce Landlock namespace restrictions on userland entry and sharing (Sashiko).
- Move USERLAND_ALL_FLAGS out of uAPI, rename USERLAND_CLOSE_ON_EXEC to USERLAND_CLOEXEC, drop unused userland_copy(), userland_exit(), and fsconfig_set_userland() code, and reset exec_state->dumpable whenever exec_state->user_ns originates outside the target user namespace (Sashiko, Askar Safin).
- Fix sys_userns_set_idmap() kernel-doc range syntax and document CLONE_INTO_USERLAND pre-execve() ptrace_may_access() isolation (Sashiko, Askar Safin).
- Route unshare() and setns() via ctypes for Python 3.9 compatibility, isolate /tmp mount propagation when running as root, and derive the E2BIG buffer size from SC_PAGE_SIZE in selftests/userland (Sashiko).
v7:
- Move userland_copy() outside tasklist_lock, loop in userland_waitid() across bootstrap retries, defer fsmount() may_mount() on userland_bound contexts, and clean up mount/idmap helpers (Sashiko).
- Move userland.rst prose into modular kernel-doc comments, document ->set_userland() in mount_api.rst, and harden selftests/userland for x32/i386, CONFIG_TIME_NS=n, and SOCK_SEQPACKET fd passing (Sashiko).
v6:
- Rename rootns to userland, replace ROOTNS_WAIT and ROOTNS_KILL ioctls with waitid(P_USERLAND) and pidfd_send_signal(), and add USERLAND_SHARE_NSFD plus security_userland_share().
- Gate FSCONFIG_SET_USERLAND on FS_USERLAND_MOUNT, pass USERNS_SETGROUPS_ALLOWED via syscall flags, bound userns_set_idmap() size to PAGE_SIZE, and tighten mount and pidns checks (Sashiko).
v5:
- Split standalone fd-based user and mount namespace setup ahead of core control object patches, and add userns_set_idmap() (Andy Lutomirski) plus MOVE_MOUNT_CLONE.
v4:
- Consolidate control syscalls into an anonymous-inode fd, add LSM hooks and bpf_lsm wiring, disallow CLONE_VM, and rewrite kselftests in Python (Sashiko).
v3:
- Replace MOVE_MOUNT_T_ROOTNS_ROOT with MOVE_MOUNT_T_MNTNS, add GET_NSFD ioctl, and support unprivileged FSCONFIG_SET_ROOTNS mount configuration (Andy Lutomirski, Sashiko).
v2:
- Rely on user_namespace ownership for setns() isolation and replace rootns_enter() with clone3() entry (Andy Lutomirski).
VERSIONS
========
v8: https://lore.kernel.org/linux-fsdevel/[email protected]/
v7: https://lore.kernel.org/linux-fsdevel/[email protected]/
v6: https://lore.kernel.org/linux-fsdevel/[email protected]/
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]/
Jarkko Sakkinen (29):
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()
security: Pass flags to security_move_mount()
mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS
apparmor: Mediate MOVE_MOUNT_CLONE as recursive bind
userns: Factor out install_user_ns_cred()
nsproxy: Expose create_new_namespaces()
nsexec: Add core infrastructure
nsexec: Track init lifecycle via copy_process() and pid_namespace
nsexec: Add nsexec_open() system call
nsexec: Add NSEXEC_GET_NSFD ioctl
nsexec: Add NSEXEC_SHARE_NSFD ioctl
exit: Support P_NSEXEC in waitid()
signal: Support nsexec fds in pidfd_send_signal()
fork: Support CLONE_INTO_NSEXEC in clone3()
fs: Support FSCONFIG_SET_NSEXEC in fsconfig()
proc: Implement ->set_nsexec() fs_context operation ipc/mqueue: Implement ->set_nsexec() fs_context operation
security: Add nsexec LSM hooks
landlock: Enforce namespace use restrictions on nsexec
bpf: Register nsexec LSM hooks
arch: Wire up nsexec_open() system call
docs: Document nsexec uAPI
selftests/nsexec: Add nsexec test suite
MAINTAINERS: Add entry for NSEXEC
Documentation/filesystems/mount_api.rst | 35 +- Documentation/userspace-api/index.rst | 1 + .../userspace-api/ioctl/ioctl-number.rst | 1 + Documentation/userspace-api/nsexec.rst | 77 + 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 | 8 +- fs/filesystems.c | 15 + fs/fs_context.c | 21 +- fs/fsopen.c | 131 +- fs/internal.h | 7 +- fs/namespace.c | 376 ++- fs/pnode.c | 7 +- fs/pnode.h | 3 +- fs/proc/root.c | 61 +- 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 | 10 +- include/linux/lsm_hooks.h | 3 + include/linux/mnt_namespace.h | 2 + include/linux/nsexec.h | 136 + 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 | 43 +- include/linux/syscalls.h | 5 + include/linux/user_namespace.h | 9 +- include/uapi/asm-generic/unistd.h | 10 +- include/uapi/linux/mount.h | 5 +- include/uapi/linux/nsexec.h | 55 + include/uapi/linux/nsfs.h | 46 + include/uapi/linux/sched.h | 5 + include/uapi/linux/wait.h | 1 + init/Kconfig | 10 + ipc/mqueue.c | 28 +- kernel/Makefile | 2 + kernel/bpf/bpf_lsm.c | 11 + kernel/cred.c | 20 +- kernel/exit.c | 4 + kernel/fork.c | 85 +- kernel/nsexec.c | 760 +++++ kernel/nsproxy.c | 15 +- kernel/pid_namespace.c | 2 + kernel/signal.c | 4 + kernel/sys_ni.c | 4 + kernel/user_namespace.c | 459 ++- mm/shmem.c | 5 +- scripts/syscall.tbl | 2 + security/apparmor/include/mount.h | 2 +- security/apparmor/include/path.h | 1 + security/apparmor/lsm.c | 4 +- security/apparmor/mount.c | 50 +- security/apparmor/path.c | 6 +- security/apparmor/policy_unpack.c | 6 +- security/landlock/fs.c | 3 +- security/landlock/ns.c | 63 +- security/lsm_init.c | 6 + security/security.c | 79 +- security/selinux/hooks.c | 2 +- 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/nsexec/Makefile | 7 + tools/testing/selftests/nsexec/cells.py | 1560 +++++++++ tools/testing/selftests/nsexec/config | 13 + tools/testing/selftests/nsexec/machine.py | 333 ++ tools/testing/selftests/nsexec/oracle.py | 386 +++ tools/testing/selftests/nsexec/selftest.py | 2887 +++++++++++++++++ tools/testing/selftests/nsexec/settings | 1 + tools/testing/selftests/nsexec/test_smoke.sh | 11 + 97 files changed, 7745 insertions(+), 265 deletions(-) create mode 100644 Documentation/userspace-api/nsexec.rst create mode 100644 include/linux/nsexec.h create mode 100644 include/uapi/linux/nsexec.h create mode 100644 kernel/nsexec.c create mode 100644 tools/testing/selftests/nsexec/Makefile create mode 100644 tools/testing/selftests/nsexec/cells.py create mode 100644 tools/testing/selftests/nsexec/config create mode 100644 tools/testing/selftests/nsexec/machine.py create mode 100644 tools/testing/selftests/nsexec/oracle.py create mode 100755 tools/testing/selftests/nsexec/selftest.py create mode 100644 tools/testing/selftests/nsexec/settings create mode 100755 tools/testing/selftests/nsexec/test_smoke.sh
base-commit: fd7e96c6c90bb18c9b23f2bbfbbde4d89ac6d88a --
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 1/29 userns: Factor out idmap validation and commit helpers
map_write() and its permission helpers validate extent ranges, check root and unprivileged self-mappings, translate parent ID ranges, sort extents, and install the resulting map inline for procfs text writes, preventing non-procfs callers from reusing the same validation and commit path.
Extract idmap_maps_root(), unpriv_idmap_permitted(), validate_and_insert_extent(), free_new_idmap(), resolve_new_idmap(), and commit_new_idmap() with no functional change.
--- kernel/user_namespace.c | 229 +++++++++++++++++++++------------------- 1 file changed, 122 insertions(+), 107 deletions(-)
kernel/user_namespace.c +122 -107
@@ -884,6 +884,22 @@ VISIBLE_IF_KUNIT int uid_gid_map_sort(struct uid_gid_map *map) }EXPORT_SYMBOL_IF_KUNIT (uid_gid_map_sort); +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; +}/** * verify_root_map() - check the uid 0 mapping * @file: idmapping file
@@ -900,22 +916,9 @@ static bool verify_root_map(const struct file *file,struct user_namespace *map_ns, struct uid_gid_map *new_map) { - int idx; const struct user_namespace *file_ns = file->f_cred->user_ns; -struct uid_gid_extent *extent0 =NULL ; - -for (idx =0 ; idx < new_map->nr_extents; idx++) { -if (new_map->nr_extents <=UID_GID_MAP_MAX_BASE_EXTENTS ) - extent0 = &new_map->extent[idx]; -else - extent0 = &new_map->forward[idx]; -if (extent0->lower_first ==0 ) -break ; - - extent0 =NULL ; - } -if (!extent0) +if (!idmap_maps_root (new_map))return true;if (map_ns == file_ns) {
@@ -938,6 +941,103 @@ 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_range_up(), +* and m_start(). +*/ +smp_wmb (); + map->nr_extents = new_map->nr_extents; +memset (new_map,0 ,sizeof (*new_map)); +} + +static bool unpriv_idmap_permitted (const struct user_namespace *ns, +const struct cred *cred,int cap_setid, +unsigned long ns_flags, +const struct uid_gid_map *new_map) +{ +u32 id; + +if (new_map->nr_extents !=1 || new_map->extent[0 ].count !=1 || + !uid_eq (ns->owner, cred->euid)) +return false; + + id = new_map->extent[0 ].lower_first; +if (cap_setid ==CAP_SETUID ) +return uid_eq (make_kuid (ns->parent, id), cred->euid); +if (cap_setid ==CAP_SETGID ) +return !(ns_flags &USERNS_SETGROUPS_ALLOWED ) && +gid_eq (make_kgid (ns->parent, id), cred->egid); +return false; +} +/* * Parse the decimal u32 at *pos, up to the next whitespace or NUL, and * leave *pos pointing at that character.
@@ -966,8 +1066,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 +1101,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 +1149,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;
@@ -1213,20 +1240,8 @@ static bool new_idmap_permitted(const struct file *file,/* Don't allow mappings that would allow anything that wouldn't * be allowed without the establishment of unprivileged mappings. */ -if ((new_map->nr_extents ==1 ) && (new_map->extent[0 ].count ==1 ) && -uid_eq (ns->owner, cred->euid)) { -u32 id = new_map->extent[0 ].lower_first; -if (cap_setid ==CAP_SETUID ) { -kuid_t uid =make_kuid (ns->parent, id); -if (uid_eq (uid, cred->euid)) -return true; - }else if (cap_setid ==CAP_SETGID ) { -kgid_t gid =make_kgid (ns->parent, id); -if (!(ns->flags &USERNS_SETGROUPS_ALLOWED ) && -gid_eq (gid, cred->egid)) -return true; - } - } +if (unpriv_idmap_permitted (ns, cred, cap_setid, ns->flags, new_map)) +return true;/* Allow anyone to set a mapping that doesn't require privilege */ if (!cap_valid (cap_setid))
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 2/29 userns: Add userns_set_idmap() system call
In reply to Jarkko SakkinenConfiguring 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 | 226 +++++++++++++++++++++++++++++++++ 5 files changed, 277 insertions(+), 2 deletions(-)
include/linux/syscalls.h +4 -0
@@ -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
@@ -35,8 +35,6 @@ struct uid_gid_map { /* 64 bytes -- 1 cache line */ }; }; -#define USERNS_SETGROUPS_ALLOWED 1UL -#define USERNS_INIT_FLAGS USERNS_SETGROUPS_ALLOWEDstruct ucounts ;
include/uapi/linux/nsfs.h +46 -0
52 lines not on this page · raw message
kernel/sys_ni.c +1 -0
@@ -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 +226 -0
239 lines not on this page · raw message
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 3/29 arch: Wire up userns_set_idmap() system call
In reply to Jarkko SakkinenExpose 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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
Jarkko Sakkinen
maintainerRFC PATCH v9 4/29 mount: Add mnt_ns_get_root()
In reply to Jarkko SakkinenEmpty 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
@@ -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
@@ -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
Jarkko Sakkinen
maintainerRFC PATCH v9 5/29 mount: Enforce mount_too_revealing() for foreign mntns
In reply to Jarkko Sakkinenmount_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 | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-)
fs/namespace.c +17 -7
@@ -6580,7 +6580,7 @@ bool current_chrooted(void)static bool mnt_already_visible (struct mnt_namespace *ns,const struct super_block *sb, -int *new_mnt_flags) +int *new_mnt_flags,bool foreign_ns) {int new_flags = *new_mnt_flags;struct mount *mnt;
@@ -6606,11 +6606,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 +6634,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))
@@ -6649,14 +6654,19 @@ static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flagsconst unsigned long required_iflags =SB_I_NOEXEC |SB_I_NODEV ;struct mnt_namespace *ns = current->nsproxy->mnt_ns;unsigned long s_iflags; - -if (ns->user_ns == &init_user_ns) -return false; +bool foreign_ns;/* Can this filesystem be too revealing? */ if (!(sb->s_type->fs_flags &FS_USERNS_MOUNT_RESTRICTED ))return false; + foreign_ns = !ns_capable_noaudit (ns->user_ns,CAP_SYS_ADMIN ); +if (ns->user_ns == &init_user_ns && !foreign_ns) +return false; + +if (foreign_ns &¤t_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",
@@ -6671,7 +6681,7 @@ static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flagsif (s_iflags &SB_I_RESTRICTED_VARIANT )return false; -return !mnt_already_visible (ns, sb, new_mnt_flags); +return !mnt_already_visible (ns, sb, new_mnt_flags, foreign_ns); }bool mnt_may_suid (struct vfsmount *mnt)
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 6/29 mount: Support MOVE_MOUNT_T_MNTNS in move_mount()
In reply to Jarkko Sakkinenmove_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 | 248 ++++++++++++++++++++++++++++++------- fs/pnode.c | 7 +- fs/pnode.h | 3 +- include/uapi/linux/mount.h | 3 +- 4 files changed, 215 insertions(+), 46 deletions(-)
fs/namespace.c +206 -42
@@ -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,
@@ -2239,9 +2245,13 @@ struct mount *copy_tree(struct mount *src_root, struct dentry *dentry,for (src_mnt = src_root_child; src_mnt; src_mnt =next_mnt (src_mnt, src_root_child)) { +bool src_locked = (src_mnt->mnt.mnt_flags &MNT_LOCKED ) || + ((flag &CL_LOCK_SOURCE ) && +list_empty (&src_mnt->mnt_expire)); +if (!(flag &CL_COPY_UNBINDABLE ) &&IS_MNT_UNBINDABLE (src_mnt)) { -if (src_mnt->mnt.mnt_flags &MNT_LOCKED ) { +if (src_locked) {/* Both unbindable and locked. */ dst_mnt =ERR_PTR (-EPERM ); goto out;
@@ -2252,7 +2262,7 @@ struct mount *copy_tree(struct mount *src_root, struct dentry *dentry, }if (!(flag &CL_COPY_MNT_NS_FILE ) &&is_mnt_ns_file (src_mnt->mnt.mnt_root)) { -if (src_mnt->mnt.mnt_flags &MNT_LOCKED ) { +if (src_locked) {/* Both a mount namespace file and locked. */ dst_mnt =ERR_PTR (-EPERM ); goto out;
@@ -2271,7 +2281,7 @@ struct mount *copy_tree(struct mount *src_root, struct dentry *dentry,if (IS_ERR (dst_mnt)) goto out;lock_mount_hash (); -if (src_mnt->mnt.mnt_flags &MNT_LOCKED ) +if (src_locked) dst_mnt->mnt.mnt_flags |=MNT_LOCKED ;if (unlikely (flag &CL_EXPIRE )) {/* stick the duplicate mount on the same expiry
@@ -2423,10 +2433,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 +2475,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 +2575,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 +2647,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;
@@ -2688,7 +2705,8 @@ static int attach_recursive_mnt(struct mount *source_mnt, err =invent_group_ids (source_mnt, true);if (err) goto out; - err =propagate_mnt (dest_mnt, dest_mp, source_mnt, &tree_list); + err =propagate_mnt (dest_mnt, dest_mp, source_mnt, &tree_list, + cross_src); }lock_mount_hash ();if (err)
@@ -2725,11 +2743,22 @@ static int attach_recursive_mnt(struct mount *source_mnt,hlist_add_head (&source_mnt->mnt_hash, &tree_list);hlist_for_each_entry_safe (child, n, &tree_list, mnt_hash) { +struct user_namespace *child_user_ns = + child->mnt_parent->mnt_ns->user_ns; +bool cross_child_src = cross_src && + !in_userns (child_user_ns, src_user_ns);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) +/* +* Notice when we are propagating or attaching a foreign +* source tree across user namespaces. +*/ +if (child_user_ns != user_ns || cross_child_src) {lock_mnt_tree (child); +if (cross_child_src &&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 +2966,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 +3160,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 +3805,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 +3824,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 +3895,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 +3917,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 +4782,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 +4794,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 +4932,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 +4945,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 +4975,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 ); }/*
fs/pnode.c +5 -2
@@ -302,6 +302,7 @@ static struct mount *find_master(struct mount *m,* @dest_mp: destination mountpoint. * @source_mnt: source mount. * @tree_list: list of secondaries to be attached. +* @lock_source: treat non-expiring @source_mnt submounts as locked. * * Create secondary copies for attaching a tree with root @source_mnt * at mount @dest_mnt with mountpoint @dest_mp. Link all new mounts
@@ -309,7 +310,8 @@ static struct mount *find_master(struct mount *m,* link their roots into @tree_list via ->mnt_hash. */ int propagate_mnt (struct mount *dest_mnt,struct mountpoint *dest_mp, -struct mount *source_mnt,struct hlist_head *tree_list) +struct mount *source_mnt,struct hlist_head *tree_list, +bool lock_source) {struct mount *m, *n, *copy, *this;int err =0 , type;
@@ -337,7 +339,8 @@ int propagate_mnt(struct mount *dest_mnt, struct mountpoint *dest_mp,continue ;if (type &CL_SLAVE )// first in this peer group copy =find_master (n, copy, source_mnt); - this =copy_tree (copy, copy->mnt.mnt_root, type); + this =copy_tree (copy, copy->mnt.mnt_root, + type | (lock_source ?CL_LOCK_SOURCE :0 ));if (IS_ERR (this)) { err =PTR_ERR (this);break ;
fs/pnode.h +2 -1
@@ -26,6 +26,7 @@#define CL_MAKE_SHARED 0x08#define CL_PRIVATE 0x10#define CL_COPY_MNT_NS_FILE 0x40 +#define CL_LOCK_SOURCE 0x80/* * EXCL[namespace_sem]
@@ -44,7 +45,7 @@ static inline bool peers(const struct mount *m1, const struct mount *m2)void change_mnt_propagation (struct mount *,int );void bulk_make_private (struct list_head *);int propagate_mnt (struct mount *,struct mountpoint *,struct mount *, -struct hlist_head *); +struct hlist_head *,bool );void propagate_umount (struct list_head *);int propagate_mount_busy (struct mount *,int );void propagate_mount_unlock (struct mount *);
include/uapi/linux/mount.h +2 -1
@@ -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
Jarkko Sakkinen
maintainerRFC PATCH v9 7/29 security: Pass flags to security_move_mount()
In reply to Jarkko SakkinenPass the MOVE_MOUNT_* flags from move_mount() to security_move_mount() and the move_mount LSM hook so security modules can distinguish mount operations that carry behavioral flags such as cloning versus moving.
--- fs/namespace.c | 9 +++++---- include/linux/lsm_hook_defs.h | 2 +- include/linux/security.h | 6 ++++-- security/apparmor/lsm.c | 2 +- security/landlock/fs.c | 3 ++- security/security.c | 7 ++++--- security/selinux/hooks.c | 2 +- 7 files changed, 18 insertions(+), 13 deletions(-)
fs/namespace.c +5 -4
@@ -4782,12 +4782,13 @@ 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, +unsigned int flags,enum mnt_tree_flags_t mflags,struct mnt_namespace *target_mnt_ns) {int ret; - ret =security_move_mount (from_path, to_path); + ret =security_move_mount (from_path, to_path, flags);if (ret)return ret;
@@ -4909,8 +4910,8 @@ static int move_mount_mntns(int from_dfd, const char __user *from_pathname,if (ret)return ret; -return vfs_move_mount (&from_path, &to_path, mflags |MNT_TREE_MNTNS , - target_mnt_ns); +return vfs_move_mount (&from_path, &to_path, flags, + mflags |MNT_TREE_MNTNS , target_mnt_ns); }/*
@@ -4980,7 +4981,7 @@ SYSCALL_DEFINE5(move_mount,if (ret)return ret; -return vfs_move_mount (&from_path, &to_path, mflags,NULL ); +return vfs_move_mount (&from_path, &to_path, flags, mflags,NULL ); }/*
include/linux/lsm_hook_defs.h +1 -1
@@ -80,7 +80,7 @@ LSM_HOOK(int, 0, sb_clone_mnt_opts, const struct super_block *oldsb, struct super_block *newsb, unsigned long kern_flags, unsigned long *set_kern_flags) LSM_HOOK(int, 0, move_mount, const struct path *from_path, - const struct path *to_path) + const struct path *to_path, unsigned int flags) LSM_HOOK(int, -EOPNOTSUPP, dentry_init_security, struct dentry *dentry, int mode, const struct qstr *name, const char **xattr_name, struct lsm_context *cp)
include/linux/security.h +4 -2
@@ -387,7 +387,8 @@ int security_sb_clone_mnt_opts(const struct super_block *oldsb,struct super_block *newsb, unsigned long kern_flags, unsigned long *set_kern_flags); -int security_move_mount (const struct path *from_path,const struct path *to_path); +int security_move_mount (const struct path *from_path, +const struct path *to_path,unsigned int flags); int security_dentry_init_security(struct dentry *dentry, int mode, const struct qstr *name, const char **xattr_name,
@@ -858,7 +859,8 @@ static inline int security_sb_clone_mnt_opts(const struct super_block *oldsb, }static inline int security_move_mount (const struct path *from_path, -const struct path *to_path) +const struct path *to_path, +unsigned int flags) {return 0 ; }
security/apparmor/lsm.c +1 -1
@@ -742,7 +742,7 @@ static int apparmor_sb_mount(const char *dev_name, const struct path *path, }static int apparmor_move_mount (const struct path *from_path, -const struct path *to_path) +const struct path *to_path,unsigned int flags) {struct aa_label *label;int error =0 ;
security/landlock/fs.c +2 -1
@@ -1547,7 +1547,8 @@ static int hook_sb_mount(const char *const dev_name, }static int hook_move_mount (const struct path *const from_path, -const struct path *const to_path) +const struct path *const to_path, +unsigned int flags) {size_t handle_layer; const struct landlock_cred_security *const subject =
security/security.c +4 -3
@@ -1185,15 +1185,16 @@ EXPORT_SYMBOL(security_sb_clone_mnt_opts);* security_move_mount() - Check permissions for moving a mount * @from_path: source mount point * @to_path: destination mount point +* @flags: MOVE_MOUNT_* flags * -* Check permission before a mount is moved. +* Check permission before a mount is moved or cloned. * * Return: Returns 0 if permission is granted. */ int security_move_mount (const struct path *from_path, -const struct path *to_path) +const struct path *to_path,unsigned int flags) { -return call_int_hook (move_mount, from_path, to_path); +return call_int_hook (move_mount, from_path, to_path, flags); }/**
security/selinux/hooks.c +1 -1
@@ -2833,7 +2833,7 @@ static int selinux_mount(const char *dev_name, }static int selinux_move_mount (const struct path *from_path, -const struct path *to_path) +const struct path *to_path,unsigned int flags) {const struct cred *cred =current_cred ();
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 8/29 mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS
In reply to Jarkko SakkinenUnprivileged 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 | CL_LOCK_SOURCE when crossing into a foreign user namespace, and lock cross-user-namespace cloned subtrees with MNT_LOCKED inside attach_recursive_mnt().
--- fs/namespace.c | 93 ++++++++++++++++++++++++++++++-------- include/uapi/linux/mount.h | 3 +- 2 files changed, 75 insertions(+), 21 deletions(-)
fs/namespace.c +73 -20
@@ -2577,6 +2577,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), };/**
@@ -3810,31 +3811,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 ;
@@ -3847,6 +3845,38 @@ 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; +if (!in_userns (target_mnt_ns->user_ns, src_user_ns)) + copy_flags =CL_SLAVE |CL_COPY_UNBINDABLE | +CL_LOCK_SOURCE ; +else + copy_flags =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 */
@@ -3886,23 +3916,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)
@@ -4829,8 +4872,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.
@@ -4838,6 +4881,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.
@@ -4939,12 +4987,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
@@ -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
Jarkko Sakkinen
maintainerRFC PATCH v9 9/29 apparmor: Mediate MOVE_MOUNT_CLONE as recursive bind
In reply to Jarkko SakkinenWhen move_mount() is invoked with MOVE_MOUNT_CLONE, the source mount is recursively loopback-cloned from the caller's mount namespace into a target mount namespace file descriptor rather than moved or attached from a detached anonymous mount.
Pass flags through aa_move_mount(), mediate MOVE_MOUNT_CLONE as MS_BIND | MS_REC while keeping from_path, reject detached or foreign MOVE_MOUNT_CLONE sources with -EINVAL, and resolve cross-namespace MOVE_MOUNT_T_MNTNS destination paths against the target mount namespace root instead of treating them as disconnected paths.
--- security/apparmor/include/mount.h | 2 +- security/apparmor/include/path.h | 1 + security/apparmor/lsm.c | 2 +- security/apparmor/mount.c | 50 ++++++++++++++++++++----------- security/apparmor/path.c | 6 ++-- security/apparmor/policy_unpack.c | 6 ++-- 6 files changed, 42 insertions(+), 25 deletions(-)
security/apparmor/include/mount.h +1 -1
@@ -43,7 +43,7 @@ int aa_move_mount_old(const struct cred *subj_cred, const char *old_name);int aa_move_mount (const struct cred *subj_cred,struct aa_label *label,const struct path *from_path, -const struct path *to_path); +const struct path *to_path,unsigned int flags); int aa_new_mount(const struct cred *subj_cred, struct aa_label *label, const char *dev_name,
security/apparmor/include/path.h +1 -0
@@ -23,6 +23,7 @@ enum path_flags {PATH_DELEGATE_DELETED =0x10000 ,/* delegate deleted files */ PATH_MEDIATE_DELETED =0x20000 ,/* mediate deleted paths */ + PATH_TARGET_MNTNS = 0x40000, /* resolve path in target mntns */ }; int aa_path_name(const struct path *path, int flags, char *buffer,
security/apparmor/lsm.c +1 -1
@@ -751,7 +751,7 @@ static int apparmor_move_mount(const struct path *from_path, label =__begin_current_label_crit_section (&needput);if (!unconfined (label)) error =aa_move_mount (current_cred (), label, from_path, - to_path); + to_path, flags);__end_current_label_crit_section (label, needput);return error;
security/apparmor/mount.c +32 -18
144 lines not on this page · raw message
security/apparmor/path.c +3 -3
@@ -116,14 +116,14 @@ static int d_namespace_path(const struct path *path, char *buf, char **name, }/* resolve paths relative to chroot?*/ -if (flags &PATH_CHROOT_REL ) { +if ((flags &PATH_CHROOT_REL ) && !(flags &PATH_TARGET_MNTNS )) {struct path root;get_fs_root (current->fs, &root); res =__d_path (path, &root, buf, buflen);path_put (&root); }else { res =d_absolute_path (path, buf, buflen); -if (!our_mnt (path->mnt)) +if (!(flags &PATH_TARGET_MNTNS ) && !our_mnt (path->mnt)) connected =0 ; }
@@ -143,7 +143,7 @@ static int d_namespace_path(const struct path *path, char *buf, char **name, *name = buf; goto out; } - }else if (!our_mnt (path->mnt)) + }else if (!(flags &PATH_TARGET_MNTNS ) && !our_mnt (path->mnt)) connected =0 ; *name = res;
security/apparmor/policy_unpack.c +4 -2
@@ -1244,12 +1244,14 @@ static struct aa_profile *unpack_profile(struct aa_ext *e, char **ns_name) goto fail;/* path_flags is optional */ -if (aa_unpack_u32 (e, &profile->path_flags,"path_flags" )) +if (aa_unpack_u32 (e, &profile->path_flags,"path_flags" )) { + profile->path_flags &= ~PATH_TARGET_MNTNS ; profile->path_flags |= profile->label.flags &PATH_MEDIATE_DELETED ; -else + }else {/* set a default value if path_flags field is not present */ profile->path_flags =PATH_MEDIATE_DELETED ; + } info ="failed to unpack profile capabilities" ;if (!aa_unpack_cap_low (e, &rules->caps.allow,NULL ))
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 10/29 userns: Factor out install_user_ns_cred()
In reply to Jarkko Sakkinenuserns_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
@@ -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
@@ -1613,6 +1613,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);
@@ -1638,10 +1645,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
Jarkko Sakkinen
maintainerRFC PATCH v9 11/29 nsproxy: Expose create_new_namespaces()
In reply to Jarkko Sakkinencreate_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 nsexec_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
@@ -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
@@ -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
Jarkko Sakkinen
maintainerRFC PATCH v9 12/29 nsexec: Add core infrastructure
In reply to Jarkko SakkinenLinux 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 nsexec abstraction.
Add struct nsexec, its lifecycle states, reference counting, uAPI flags, and anonymous inode file operations under CONFIG_NSEXEC. Drop active and passive namespace references on final release, send SIGKILL to the nsexec init thread group on close when NSEXEC_AUTOKILL is set, and report EPOLLHUP from poll() once the nsexec reaches NSEXEC_DEAD.
--- include/linux/nsexec.h | 83 ++++++++++++++++++++++++++++++++ include/uapi/linux/nsexec.h | 22 +++++++++ init/Kconfig | 10 ++++ kernel/Makefile | 2 + kernel/nsexec.c | 95 +++++++++++++++++++++++++++++++++++++ 5 files changed, 212 insertions(+) create mode 100644 include/linux/nsexec.h create mode 100644 include/uapi/linux/nsexec.h create mode 100644 kernel/nsexec.c
include/linux/nsexec.h new file +83 -0
@@ -0,0 +1,83 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved. +* Copyright (C) 2026 Opinsys Oy +*/ + +#ifndef _LINUX_NSEXEC_H +#define _LINUX_NSEXEC_H + +#include <linux/refcount.h> +#include <linux/spinlock.h> +#include <linux/wait.h> +#include <uapi/linux/nsexec.h> + +#define NSEXEC_ALL_FLAGS NSEXEC_AUTOKILL + +struct file ; +struct nsproxy ; +struct pid ; +struct user_namespace ; + +/** +* enum nsexec_state - nsexec lifecycle states +* @NSEXEC_INIT: Build phase after ``nsexec_open()`` before any +* process has entered. ``NSEXEC_SHARE_NSFD`` is +* permitted, ID mappings may be configured on the owning +* user namespace, and ``"/"`` must be mounted in the +* mount namespace before entry. +* @NSEXEC_FORKING: Bootstrap phase while the first +* ``clone3(CLONE_INTO_NSEXEC)`` call creates PID 1. +* Concurrent callers wait killably; reverts to +* %NSEXEC_INIT if ``copy_process()`` fails, or advances +* to %NSEXEC_RUNNING once PID 1 is attached. +* @NSEXEC_RUNNING: Live phase while PID 1 is attached. Subsequent +* ``clone3(CLONE_INTO_NSEXEC)`` calls join the PID +* namespace until teardown begins, +* ``NSEXEC_GET_NSFD(CLONE_NEWPID)`` and +* ``pidfd_send_signal()`` are enabled, and +* ``NSEXEC_SHARE_NSFD`` returns ``-EBUSY``. +* @NSEXEC_DEAD: Terminal phase entered after PID 1 exits and the PID +* namespace has killed and reaped all member processes. +* ``poll()`` reports ``EPOLLHUP`` and +* ``waitid(P_NSEXEC, ...)`` reports PID 1's exit status +* without consuming it. +* +* State transitions advance from %NSEXEC_INIT through %NSEXEC_FORKING and +* %NSEXEC_RUNNING to %NSEXEC_DEAD, reverting from %NSEXEC_FORKING to +* %NSEXEC_INIT only if the initial bootstrap fork fails. +*/ +enum nsexec_state { +NSEXEC_INIT =0 , +NSEXEC_FORKING =1 , +NSEXEC_RUNNING =2 , +NSEXEC_DEAD =3 , +}; + +struct nsexec { +refcount_t usage; +int exit_code; +struct user_namespace *user_ns; +struct nsproxy *ns; +struct pid *init_pid; +spinlock_t lock;/* Guards nsexec lifecycle state */ +wait_queue_head_t waitq; +unsigned int flags; +enum nsexec_state state; +}; + +#ifdef CONFIG_NSEXEC +void nsexec_put (struct nsexec *c); +bool nsexec_is_file (struct file *file); +#else +static inline void nsexec_put (struct nsexec *c) +{ +} + +static inline bool nsexec_is_file (struct file *file) +{ +return false; +} +#endif /* CONFIG_NSEXEC */ + +#endif /* _LINUX_NSEXEC_H */
include/uapi/linux/nsexec.h new file +22 -0
@@ -0,0 +1,22 @@ +/* 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_NSEXEC_H +#define _UAPI_LINUX_NSEXEC_H + +/** +* enum nsexec_flags - Flags for nsexec_open() +* @NSEXEC_AUTOKILL: Send %SIGKILL to nsexec init on final fd release. +* +* Every nsexec created by nsexec_open() allocates a full set of +* detached namespaces owned by a fresh user namespace and sets %O_CLOEXEC +* on the returned control file descriptor. +*/ +enum nsexec_flags { +NSEXEC_AUTOKILL =0x00000001 , +}; + +#endif /* _UAPI_LINUX_NSEXEC_H */
init/Kconfig +10 -0
@@ -1281,6 +1281,16 @@ config NET_NS Allow user space to create what appear to be multiple instances of the network stack. +config NSEXEC + bool "Namespace group support" + depends on USER_NS && PID_NS && UTS_NS && IPC_NS && NET_NS && CGROUPS + help + Allow user space to open and manage isolated nsexecs and their init + process lifecycle through an anonymous-inode control file descriptor + via nsexec_open(), waitid(P_NSEXEC), pidfd_send_signal(), + NSEXEC_GET_NSFD, NSEXEC_SHARE_NSFD, FSCONFIG_SET_NSEXEC, and + clone3() with CLONE_INTO_NSEXEC. + endif # NAMESPACES config CHECKPOINT_RESTORE
kernel/Makefile +2 -0
@@ -152,6 +152,8 @@ KCOV_INSTRUMENT_kstack_erase.o := n obj-$(CONFIG_SCF_TORTURE_TEST) += scftorture.o +obj-$(CONFIG_NSEXEC) += nsexec.o + $(obj)/configs.o: $(obj)/config_data.gz # .config is small, so it is compressed with gzip rather than the image compressor.
kernel/nsexec.c new file +95 -0
95 lines not on this page · raw message
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 13/29 nsexec: Track init lifecycle via copy_process() and pid_namespace
In reply to Jarkko SakkinenAn nsexec needs to record its init thread group's PID when bootstrapped and capture its exit status and UID once all processes in the nsexec have terminated, without serializing normal fork() and exit() paths inside the nsexec.
Commit the bootstrap child reaper and bind pid_ns->nsexec in nsexec_copy() after copy_process() attaches PIDs and drops tasklist_lock, and invoke nsexec_exit() from zap_pid_ns_processes() after the nsexec's PID namespace has killed and reaped all member tasks.
--- include/linux/nsexec.h | 15 +++++++++++++ include/linux/pid_namespace.h | 4 ++++ kernel/fork.c | 4 ++++ kernel/nsexec.c | 41 +++++++++++++++++++++++++++++++++++ kernel/pid_namespace.c | 2 ++ 5 files changed, 66 insertions(+)
include/linux/nsexec.h +15 -0
@@ -9,6 +9,7 @@#include <linux/refcount.h> #include <linux/spinlock.h> +#include <linux/uidgid.h> #include <linux/wait.h> #include <uapi/linux/nsexec.h>
@@ -17,6 +18,8 @@struct file ;struct nsproxy ;struct pid ; +struct pid_namespace ; +struct task_struct ;struct user_namespace ;/**
@@ -60,6 +63,7 @@ struct nsexec {struct user_namespace *user_ns;struct nsproxy *ns;struct pid *init_pid; +kuid_t init_uid;spinlock_t lock;/* Guards nsexec lifecycle state */ wait_queue_head_t waitq;unsigned int flags;
@@ -69,6 +73,8 @@ struct nsexec {#ifdef CONFIG_NSEXEC void nsexec_put (struct nsexec *c);bool nsexec_is_file (struct file *file); +void nsexec_copy (struct pid *pid,struct nsexec *nsexec); +void nsexec_exit (struct pid_namespace *pid_ns,struct task_struct *tsk);#else static inline void nsexec_put (struct nsexec *c) {
@@ -78,6 +84,15 @@ static inline bool nsexec_is_file(struct file *file) {return false; } + +static inline void nsexec_copy (struct pid *pid,struct nsexec *nsexec) +{ +} + +static inline void nsexec_exit (struct pid_namespace *pid_ns, +struct task_struct *tsk) +{ +}#endif /* CONFIG_NSEXEC */ #endif /* _LINUX_NSEXEC_H */
include/linux/pid_namespace.h +4 -0
@@ -15,6 +15,7 @@#define MAX_PID_NS_LEVEL 32struct fs_pin ; +struct nsexec ;#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_NSEXEC +struct nsexec *nsexec; +#endif struct ns_common ns;struct work_struct work; } __randomize_layout;
kernel/fork.c +4 -0
@@ -83,6 +83,7 @@#include <linux/fs_struct.h> #include <linux/magic.h> #include <linux/perf_event.h> +#include <linux/nsexec.h> #include <linux/posix-timers.h> #include <linux/user-return-notifier.h> #include <linux/oom.h>
@@ -2584,6 +2585,9 @@ __latent_entropy struct task_struct *copy_process(syscall_tracepoint_update (p);write_unlock_irq (&tasklist_lock); +if (likely (p->pid) &&thread_group_leader (p)) +nsexec_copy (pid,NULL ); +if (pidfile)fd_install (pidfd, pidfile);
kernel/nsexec.c +41 -0
44 lines not on this page · raw message
kernel/pid_namespace.c +2 -0
@@ -24,6 +24,7 @@#include <linux/sched/signal.h> #include <linux/idr.h> #include <linux/nstree.h> +#include <linux/nsexec.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); +nsexec_exit (pid_ns, me);return ; }
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 14/29 nsexec: Add nsexec_open() system call
In reply to Jarkko SakkinenSetting 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 nsexec_open() system call to allocate an nsexec 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 nsexec 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 nsexec.
--- include/linux/syscalls.h | 1 + kernel/nsexec.c | 107 +++++++++++++++++++++++++++++++++++++++ kernel/sys_ni.c | 3 ++ 3 files changed, 111 insertions(+)
include/linux/syscalls.h +1 -0
@@ -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_nsexec_open (unsigned int flags);/* * Architecture-specific system calls
kernel/nsexec.c +107 -0
110 lines not on this page · raw message
kernel/sys_ni.c +3 -0
@@ -399,3 +399,6 @@ COND_SYSCALL(rseq_slice_yield);COND_SYSCALL (uretprobe);COND_SYSCALL (uprobe); + +/* kernel/nsexec.c */ +COND_SYSCALL (nsexec_open);
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 15/29 nsexec: Add NSEXEC_GET_NSFD ioctl
In reply to Jarkko SakkinenStandalone 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 an nsexec file descriptor before any process has entered it.
Add the NSEXEC_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 nsexec'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/nsexec.h | 19 ++++++++++ kernel/nsexec.c | 76 +++++++++++++++++++++++++++++++++++++ 4 files changed, 96 insertions(+), 1 deletion(-)
fs/internal.h +0 -1
@@ -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
@@ -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/nsexec.h +19 -0
@@ -7,6 +7,8 @@#ifndef _UAPI_LINUX_NSEXEC_H#define _UAPI_LINUX_NSEXEC_H +#include <linux/ioctl.h> +/** * enum nsexec_flags - Flags for nsexec_open() * @NSEXEC_AUTOKILL: Send %SIGKILL to nsexec init on final fd release.
@@ -19,4 +21,21 @@ enum nsexec_flags { NSEXEC_AUTOKILL = 0x00000001, }; +#define NSEXEC_IOCTL_MAGIC 0xB9 + +/** +* DOC: NSEXEC_GET_NSFD +* +* ``ioctl(nsexec_fd, NSEXEC_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 nsexec's user namespace. +* Opening ``CLONE_NEWPID`` additionally requires running in an ancestor +* active PID namespace and that nsexec init is running. +*/ +#define NSEXEC_GET_NSFD _IO(NSEXEC_IOCTL_MAGIC, 0x01) +#endif /* _UAPI_LINUX_NSEXEC_H */
kernel/nsexec.c +76 -0
100 lines not on this page · raw message
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 16/29 nsexec: Add NSEXEC_SHARE_NSFD ioctl
In reply to Jarkko Sakkinennsexec_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 NSEXEC_SHARE_NSFD ioctl to replace the nsexec's cgroup, IPC, UTS, network, or time namespace with a supplied nsfs file descriptor in-place under nsexec->lock while the nsexec is still in NSEXEC_INIT, rejecting calls with -EBUSY once CLONE_INTO_NSEXEC begins. Require CAP_SYS_ADMIN in the nsexec'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/nsexec.h | 14 ++++++ kernel/nsexec.c | 90 +++++++++++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+)
include/uapi/linux/nsexec.h +14 -0
@@ -38,4 +38,18 @@ enum nsexec_flags {*/ #define NSEXEC_GET_NSFD _IO(NSEXEC_IOCTL_MAGIC, 0x01) +/** +* DOC: NSEXEC_SHARE_NSFD +* +* ``ioctl(nsexec_fd, NSEXEC_SHARE_NSFD, ns_fd)`` replaces the corresponding +* member namespace of ``nsexec_fd`` with ``ns_fd`` (``CLONE_NEWCGROUP``, +* ``CLONE_NEWIPC``, ``CLONE_NEWUTS``, ``CLONE_NEWNET``, or ``CLONE_NEWTIME``) +* while ``nsexec_fd`` is in ``NSEXEC_INIT``. +* +* Requires ``CAP_SYS_ADMIN`` in the nsexec'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 NSEXEC_SHARE_NSFD _IO(NSEXEC_IOCTL_MAGIC, 0x02) +#endif /* _UAPI_LINUX_NSEXEC_H */
kernel/nsexec.c +90 -0
108 lines not on this page · raw message
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 17/29 exit: Support P_NSEXEC in waitid()
In reply to Jarkko Sakkinenwait4() and waitid() only allow a parent or subreaper to collect exit status, so an external manager holding an nsexec file descriptor cannot wait on an nsexec init process forked by another process or observe exit status multiple times across observers.
Add P_NSEXEC to waitid() and wire kernel_waitid() to nsexec_waitid() to wait freezably and interruptibly on an nsexec file descriptor until the nsexec reaches NSEXEC_DEAD and populate siginfo_t with init's caller-visible TGID, munged UID, and exit status without consuming it.
--- include/linux/nsexec.h | 10 +++++ include/uapi/linux/wait.h | 1 + kernel/exit.c | 4 ++ kernel/nsexec.c | 83 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 98 insertions(+)
include/linux/nsexec.h +10 -0
@@ -19,8 +19,10 @@ struct file;struct nsproxy ;struct pid ;struct pid_namespace ; +struct rusage ;struct task_struct ;struct user_namespace ; +struct waitid_info ;/** * enum nsexec_state - nsexec lifecycle states
@@ -75,6 +77,8 @@ void nsexec_put(struct nsexec *c);bool nsexec_is_file (struct file *file);void nsexec_copy (struct pid *pid,struct nsexec *nsexec);void nsexec_exit (struct pid_namespace *pid_ns,struct task_struct *tsk); +long nsexec_waitid (int upid,struct waitid_info *infop,int options, +struct rusage *ru);#else static inline void nsexec_put (struct nsexec *c) {
@@ -93,6 +97,12 @@ static inline void nsexec_exit(struct pid_namespace *pid_ns, struct task_struct *tsk) { } + +static inline long nsexec_waitid (int upid,struct waitid_info *infop, +int options,struct rusage *ru) +{ +return -EINVAL ; +}#endif /* CONFIG_NSEXEC */ #endif /* _LINUX_NSEXEC_H */
include/uapi/linux/wait.h +1 -0
@@ -18,6 +18,7 @@#define P_PID 1#define P_PGID 2#define P_PIDFD 3 +#define P_NSEXEC 4#endif /* _UAPI_LINUX_WAIT_H */
kernel/exit.c +4 -0
@@ -71,6 +71,7 @@#include <linux/unwind_deferred.h> #include <linux/uaccess.h> #include <linux/pidfs.h> +#include <linux/nsexec.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_NSEXEC ) +return nsexec_waitid (upid, infop, options, ru); + ret =kernel_waitid_prepare (&wo, which, upid, infop, options, ru);if (ret)return ret;
kernel/nsexec.c +83 -0
101 lines not on this page · raw message
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 18/29 signal: Support nsexec fds in pidfd_send_signal()
In reply to Jarkko SakkinenSignaling every process inside an nsexec from userspace via /proc is racy against concurrent fork() calls.
Teach pidfd_send_signal() to dispatch nsexec file descriptors to nsexec_send_signal() when info is NULL and flags is 0. Require an ancestor active PID namespace, walk the nsexec's PID namespace IDR under tasklist_lock, and deliver a validated signal once to each thread group including in-flight forks by member processes, aggregating per-process delivery results.
--- include/linux/nsexec.h | 10 +++++++ kernel/nsexec.c | 59 ++++++++++++++++++++++++++++++++++++++++++ kernel/signal.c | 4 +++ 3 files changed, 73 insertions(+)
include/linux/nsexec.h +10 -0
@@ -20,6 +20,7 @@ struct nsproxy;struct pid ;struct pid_namespace ;struct rusage ; +struct siginfo ;struct task_struct ;struct user_namespace ;struct waitid_info ;
@@ -79,6 +80,8 @@ void nsexec_copy(struct pid *pid, struct nsexec *nsexec);void nsexec_exit (struct pid_namespace *pid_ns,struct task_struct *tsk);long nsexec_waitid (int upid,struct waitid_info *infop,int options,struct rusage *ru); +int nsexec_send_signal (struct file *file,int sig, +struct siginfo __user *info,unsigned int flags);#else static inline void nsexec_put (struct nsexec *c) {
@@ -103,6 +106,13 @@ static inline long nsexec_waitid(int upid, struct waitid_info *infop, {return -EINVAL ; } + +static inline int nsexec_send_signal (struct file *file,int sig, +struct siginfo __user *info, +unsigned int flags) +{ +return -EBADF ; +}#endif /* CONFIG_NSEXEC */ #endif /* _LINUX_NSEXEC_H */
kernel/nsexec.c +59 -0
65 lines not on this page · raw message
kernel/signal.c +4 -0
@@ -37,6 +37,7 @@#include <linux/capability.h> #include <linux/freezer.h> #include <linux/pid_namespace.h> +#include <linux/nsexec.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 (nsexec_is_file (fd_file (f))) +return nsexec_send_signal (fd_file (f), sig, info, flags); +/* Is this a pidfd? */ pid =pidfd_to_pid (fd_file (f));if (IS_ERR (pid))
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 19/29 fork: Support CLONE_INTO_NSEXEC in clone3()
In reply to Jarkko SakkinenMultithreaded 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_NSEXEC and struct clone_args.nsexec (CLONE_ARGS_SIZE_VER3) to spawn a child process directly into an nsexec whose root mount has been installed. Transition the nsexec from NSEXEC_INIT through NSEXEC_FORKING to NSEXEC_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 when exec_state originates outside the target user namespace, 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/nsexec.h | 15 +++ include/linux/nsproxy.h | 4 +- include/linux/sched/task.h | 6 ++ include/uapi/linux/sched.h | 5 + kernel/cred.c | 20 +++- kernel/fork.c | 83 ++++++++++++++-- kernel/nsexec.c | 188 ++++++++++++++++++++++++++++++++++++- kernel/nsproxy.c | 9 +- 9 files changed, 318 insertions(+), 16 deletions(-)
include/linux/cred.h +3 -1
@@ -19,6 +19,7 @@struct cred ;struct inode ; +struct nsexec ;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 nsexec *nsexec);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/nsexec.h +15 -0
@@ -16,6 +16,7 @@#define NSEXEC_ALL_FLAGS NSEXEC_AUTOKILLstruct file ; +struct kernel_clone_args ;struct nsproxy ;struct pid ;struct pid_namespace ;
@@ -82,6 +83,9 @@ long nsexec_waitid(int upid, struct waitid_info *infop, int options, struct rusage *ru);int nsexec_send_signal (struct file *file,int sig,struct siginfo __user *info,unsigned int flags); +int nsexec_prepare_fork (struct kernel_clone_args *args); +int nsexec_finish_fork (struct kernel_clone_args *args, +struct task_struct *p);#else static inline void nsexec_put (struct nsexec *c) {
@@ -113,6 +117,17 @@ static inline int nsexec_send_signal(struct file *file, int sig, {return -EBADF ; } + +static inline int nsexec_prepare_fork (struct kernel_clone_args *args) +{ +return -EINVAL ; +} + +static inline int nsexec_finish_fork (struct kernel_clone_args *args, +struct task_struct *p) +{ +return 0 ; +}#endif /* CONFIG_NSEXEC */ #endif /* _LINUX_NSEXEC_H */
include/linux/nsproxy.h +3 -1
@@ -12,6 +12,7 @@ struct ipc_namespace;struct pid_namespace ;struct cgroup_namespace ;struct fs_struct ; +struct nsexec ;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 nsexec *nsexec);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
@@ -16,6 +16,8 @@ struct task_struct;struct rusage ;union thread_union ;struct css_set ; +struct file ; +struct nsexec ;/* 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 nsexec_fd;int idle;int (*fn)(void *);void *fn_arg;struct cgroup *cgrp;struct css_set *cset; +struct file *nsexec_file; +struct nsexec *nsexec; +bool nsexec_bootstrapping;unsigned int kill_seq; };
include/uapi/linux/sched.h +5 -0
@@ -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_NSEXEC (1ULL << 38)/* Clone into an nsexec. */ /* * 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. +* @nsexec: If CLONE_INTO_NSEXEC is specified set this to +* a file descriptor for the nsexec. * * 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 nsexec; };#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 +19 -1
@@ -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/nsexec.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 , ...) \
@@ -260,7 +263,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 nsexec *nsexec) {struct cred *new;int ret;
@@ -287,6 +291,20 @@ int copy_creds(struct task_struct *p, u64 clone_flags)if (!new)return -ENOMEM ; +if (nsexec) { +struct task_exec_state *exec_state; + +if (new->user_ns != nsexec->user_ns) { + ret =install_user_ns_cred (new, nsexec->user_ns); +if (ret <0 ) + goto error_put; + } + exec_state =rcu_dereference_protected (p->exec_state, true); +if (exec_state->user_ns != nsexec->user_ns) +WRITE_ONCE (exec_state->dumpable, +READ_ONCE (suid_dumpable)); + } +if (clone_flags &CLONE_NEWUSER ) { ret =create_user_ns (new);if (ret <0 )
kernel/fork.c +73 -10
201 lines not on this page · raw message
kernel/nsexec.c +186 -2
209 lines not on this page · raw message
kernel/nsproxy.c +8 -1
@@ -11,6 +11,7 @@#include <linux/slab.h> #include <linux/export.h> +#include <linux/nsexec.h> #include <linux/nsproxy.h> #include <linux/ns/ns_common_types.h> #include <linux/init_task.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 nsexec *nsexec) {struct nsproxy *old_ns = tsk->nsproxy;struct user_namespace *user_ns =task_cred_xxx (tsk, user_ns);struct nsproxy *new_ns; +if (nsexec) { +get_nsproxy (nsexec->ns); + tsk->nsproxy = nsexec->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)) {
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 20/29 fs: Support FSCONFIG_SET_NSEXEC in fsconfig()
In reply to Jarkko Sakkinenfsopen() 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 nsexec.
Add FSCONFIG_SET_NSEXEC and the ->set_nsexec() fs_context operation so callers holding CAP_SYS_ADMIN in the target nsexec's user namespace can bind a newly opened fs_context to that nsexec once before offering parameters. Gate nsexec context binding on explicit FS_NSEXEC_MOUNT opt-in (or FS_USERNS_DELEGATABLE), mark tmpfs, ramfs, and devpts with FS_NSEXEC_MOUNT, refresh fc->cred when FSCONFIG_SET_NSEXEC authorizes and initializes the context, and keep devpts pty_reserve restricted to host mounts.
--- Documentation/filesystems/mount_api.rst | 35 ++++++- fs/devpts/inode.c | 8 +- fs/filesystems.c | 15 +++ fs/fs_context.c | 21 +++- fs/fsopen.c | 131 ++++++++++++++++++++++-- fs/internal.h | 6 ++ fs/namespace.c | 18 +++- 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 +- 12 files changed, 230 insertions(+), 19 deletions(-)
Documentation/filesystems/mount_api.rst +34 -1
@@ -80,6 +80,7 @@ context. This is represented by the fs_context structure:: unsigned int sb_flags_mask; unsigned int s_iflags; enum fs_context_purpose purpose:8; + bool nsexec_bound:1; ... };
@@ -123,7 +124,8 @@ The fs_context fields are as follows: There are a subset of the namespaces in use by the invoking process. They retain references on each namespace. The subscribed namespaces may be replaced by the filesystem to reflect other sources, such as the parent - mount superblock on an automount. + mount superblock on an automount, or to the target nsexec's + namespaces when bound via FSCONFIG_SET_NSEXEC. * ::
@@ -186,6 +188,15 @@ The fs_context fields are as follows: FS_CONTEXT_FOR_RECONFIGURE Change an existing mount ========================== ====================================== + * :: + + bool nsexec_bound:1 + + Set when the filesystem context has been bound to a target nsexec via + FSCONFIG_SET_NSEXEC. Filesystems may inspect this flag (for example in + ->init_fs_context() or ->parse_param()) to distinguish nsexec-delegated + mounts from host mounts. + The mount context is created by calling vfs_new_fs_context() or vfs_dup_fs_context() and is destroyed with put_fs_context(). Note that the structure is not refcounted.
@@ -214,6 +225,8 @@ The filesystem context points to a table of operations:: int (*parse_param)(struct fs_context *fc, struct fs_parameter *param); int (*parse_monolithic)(struct fs_context *fc, void *data); + int (*set_nsexec)(struct fs_context *fc, + struct nsexec *nsexec); int (*get_tree)(struct fs_context *fc); int (*reconfigure)(struct fs_context *fc); };
@@ -272,6 +285,26 @@ manage the filesystem context. They are as follows: finds it's the standard key-val list then it may pass it off to generic_parse_monolithic(). + * :: + + int (*set_nsexec)(struct fs_context *fc, + struct nsexec *nsexec); + + Called by FSCONFIG_SET_NSEXEC after updating fc->user_ns, fc->net_ns, + and fc->cred, setting fc->nsexec_bound, and re-running + ->init_fs_context(). Filesystems opting into FS_NSEXEC_MOUNT (or + FS_USERNS_DELEGATABLE) that capture additional namespaces from current in + ->init_fs_context() (such as PID or IPC namespaces) can implement this + operation to rebind their private context to the target nsexec's + namespaces. It may update fc->user_ns (for example to a shared + namespace's owning user namespace), in which case the caller must hold + CAP_SYS_ADMIN in fc->user_ns or the bind fails with -EPERM. When + ->set_nsexec is NULL, fc->user_ns must equal nsexec->user_ns after + ->init_fs_context() or the bind fails with -EOPNOTSUPP. + + On success it should return 0. In the case of an error, it should return + a negative error code and the context transitions to FS_CONTEXT_FAILED. + * :: int (*get_tree)(struct fs_context *fc);
fs/devpts/inode.c +7 -1
@@ -231,10 +231,14 @@ static int devpts_parse_param(struct fs_context *fc, struct fs_parameter *param)switch (opt) {case Opt_uid: +if (!kuid_has_mapping (fc->user_ns, result.uid)) +return invalf (fc,"Invalid uid" ); opts->uid = result.uid; opts->setuid =1 ;break ;case Opt_gid: +if (!kgid_has_mapping (fc->user_ns, result.gid)) +return invalf (fc,"Invalid gid" ); opts->gid = result.gid; opts->setgid =1 ;break ;
@@ -434,6 +438,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->nsexec_bound && + fc->user_ns == &init_user_ns && current->nsproxy->mnt_ns == init_task.nsproxy->mnt_ns) fsi->mount_opts.reserve = true;
@@ -457,7 +463,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_NSEXEC_MOUNT, };/*
fs/filesystems.c +15 -0
@@ -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
@@ -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 +123 -8
204 lines not on this page · raw message
fs/internal.h +6 -0
@@ -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 +16 -2
@@ -4723,7 +4723,8 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags, !ns_capable(current_user_ns(), CAP_SYS_ADMIN))return -EPERM ; -if (!(flags &FSMOUNT_NAMESPACE ) && !may_mount ()) +if (!(flags &FSMOUNT_NAMESPACE ) && !IS_ENABLED (CONFIG_NSEXEC ) && + !may_mount ())return -EPERM ;if (attr_flags & ~FSMOUNT_VALID_FLAGS )
@@ -4758,6 +4759,16 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,if (ret)return ret; +if (fc->nsexec_bound) { +if (flags &FSMOUNT_NAMESPACE ) +return -EINVAL ; +if (!ns_capable (fc->user_ns,CAP_SYS_ADMIN )) +return -EPERM ; + }else if (!(flags &FSMOUNT_NAMESPACE ) && +IS_ENABLED (CONFIG_NSEXEC ) && !may_mount ()) { +return -EPERM ; + } +/* There must be a valid superblock or we can't mount it */ ret = -EINVAL ;if (!fc->root)
@@ -4799,9 +4810,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->nsexec_bound ? fc->user_ns : + current->nsproxy->mnt_ns->user_ns, true);if (IS_ERR (ns))return PTR_ERR (ns); +if (fc->nsexec_bound) + ns->seq_origin = fc->nsexec_mnt_id; mnt =real_mount (new_path.mnt); ns->root = mnt; ns->nr_mounts =1 ;
fs/ramfs/inode.c +1 -1
@@ -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_NSEXEC_MOUNT, };static int __init init_ramfs_fs (void )
include/linux/fs.h +1 -0
@@ -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_NSEXEC_MOUNT 4096/* Supports FSCONFIG_SET_NSEXEC */ #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
@@ -23,6 +23,7 @@ struct net;struct pid_namespace ;struct super_block ;struct user_namespace ; +struct nsexec ;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 nsexec_mnt_id;/* Target nsexec 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 nsexec_bound:1; /* Bound via FSCONFIG_SET_NSEXEC */ };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_nsexec)(struct fs_context *fc,struct nsexec *nsexec);int (*get_tree)(struct fs_context *fc);int (*reconfigure)(struct fs_context *fc); };
include/uapi/linux/mount.h +1 -0
@@ -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_NSEXEC = 9, /* Set target nsexec, supplied by fd */ };/*
mm/shmem.c +3 -2
@@ -5632,7 +5632,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_NSEXEC_MOUNT | + FS_ALLOW_IDMAP | FS_MGTIME, };#if defined(CONFIG_SYSFS ) && defined(CONFIG_TMPFS )
@@ -6061,7 +6062,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_NSEXEC_MOUNT, };void __init shmem_init (void )
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 21/29 proc: Implement ->set_nsexec() fs_context operation
In reply to Jarkko Sakkinenproc_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_NSEXEC and leaving the context attached to the caller's PID namespace.
Wire up proc_set_nsexec() to verify that the target nsexec'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_NSEXEC_MOUNT.
--- fs/proc/root.c | 61 +++++++++++++++++++++++++++++++++++++------------- 1 file changed, 46 insertions(+), 15 deletions(-)
fs/proc/root.c +46 -15
@@ -15,6 +15,8 @@#include <linux/sched/stat.h> #include <linux/module.h> #include <linux/bitops.h> +#include <linux/nsexec.h> +#include <linux/nsproxy.h> #include <linux/user_namespace.h> #include <linux/fs_context.h> #include <linux/mount.h>
@@ -30,7 +32,7 @@ struct proc_fs_context {struct pid_namespace *pid_ns;unsigned int mask;enum proc_hidepid hidepid; -int gid; +kgid_t gid;enum proc_pidonly pidonly; };
@@ -42,7 +44,7 @@ enum proc_param { };static const struct fs_parameter_spec proc_fs_parameters[] = { -fsparam_u32 ("gid" , Opt_gid), +fsparam_gid ("gid" , Opt_gid),fsparam_string ("hidepid" , Opt_hidepid),fsparam_string ("subset" , Opt_subset),fsparam_file_or_string ("pidns" , Opt_pidns),
@@ -178,7 +180,9 @@ static int proc_parse_param(struct fs_context *fc, struct fs_parameter *param)switch (opt) {case Opt_gid: - ctx->gid = result.uint_32; +if (!kgid_has_mapping (fc->user_ns, result.gid)) +return invalfc (fc,"Invalid gid" ); + ctx->gid = result.gid;break ;case Opt_hidepid:
@@ -206,6 +210,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->nsexec_bound) { +errorfc (fc,"cannot override pidns on nsexec-bound procfs" ); +return -EBUSY ; + } err =proc_parse_pidns_param (fc, param, &result);if (err)return err;
@@ -224,8 +232,7 @@ static int proc_parse_param(struct fs_context *fc, struct fs_parameter *param) }static int proc_apply_options (struct proc_fs_info *fs_info, -struct fs_context *fc, -struct user_namespace *user_ns) +struct fs_context *fc) {struct proc_fs_context *ctx = fc->fs_private;
@@ -234,8 +241,11 @@ static int proc_apply_options(struct proc_fs_info *fs_info, ctx->pidonly != fs_info->pidonly)return invalf (fc,"proc: subset=pid cannot be changed\n" ); -if (ctx->mask & (1 << Opt_gid)) - fs_info->pid_gid =make_kgid (user_ns, ctx->gid); +if (ctx->mask & (1 << Opt_gid)) { +if (!kgid_has_mapping (fc->user_ns, ctx->gid)) +return invalfc (fc,"Invalid gid" ); + fs_info->pid_gid = ctx->gid; + }if (ctx->mask & (1 << Opt_hidepid)) fs_info->hide_pid = ctx->hidepid;if (ctx->mask & (1 << Opt_subset))
@@ -261,7 +271,8 @@ static int proc_fill_super(struct super_block *s, struct fs_context *fc) fs_info->pid_ns =get_pid_ns (ctx->pid_ns); fs_info->mounter_cred =get_cred (fc->cred); - ret =proc_apply_options (fs_info, fc,current_user_ns ()); + s->s_fs_info = fs_info; + ret =proc_apply_options (fs_info, fc);if (ret)return ret;
@@ -273,8 +284,6 @@ static int proc_fill_super(struct super_block *s, struct fs_context *fc) s->s_magic =PROC_SUPER_MAGIC ; s->s_op = &proc_sops; s->s_time_gran =1 ; - s->s_fs_info = fs_info; -if (fs_info->pidonly ==PROC_PIDONLY_ON ) s->s_iflags |=SB_I_RESTRICTED_VARIANT ;
@@ -315,7 +324,7 @@ static int proc_reconfigure(struct fs_context *fc)sync_filesystem (sb); -return proc_apply_options (fs_info, fc,current_user_ns ()); +return proc_apply_options (fs_info, fc); }static int proc_get_tree (struct fs_context *fc)
@@ -323,6 +332,21 @@ static int proc_get_tree(struct fs_context *fc)return get_tree_nodev (fc, proc_fill_super); } +static int proc_set_nsexec (struct fs_context *fc,struct nsexec *nsexec) +{ +struct proc_fs_context *ctx = fc->fs_private; +struct pid_namespace *target = nsexec->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 +358,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_nsexec = proc_set_nsexec, .get_tree = proc_get_tree, .reconfigure = proc_reconfigure, };
@@ -346,9 +371,13 @@ static int proc_init_fs_context(struct fs_context *fc)if (!ctx)return -ENOMEM ; - ctx->pid_ns =get_pid_ns (task_active_pid_ns (current)); -put_user_ns (fc->user_ns); - fc->user_ns =get_user_ns (ctx->pid_ns->user_ns); +if (fc->purpose ==FS_CONTEXT_FOR_RECONFIGURE ) { + ctx->pid_ns =get_pid_ns (proc_sb_info (fc->root->d_sb)->pid_ns); + }else { + ctx->pid_ns =get_pid_ns (task_active_pid_ns (current)); +put_user_ns (fc->user_ns); + fc->user_ns =get_user_ns (ctx->pid_ns->user_ns); + } fc->fs_private = ctx; fc->ops = &proc_fs_context_ops;return 0 ;
@@ -371,7 +400,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_NSEXEC_MOUNT | +FS_USERNS_MOUNT_RESTRICTED | + FS_DISALLOW_NOTIFY_PERM, };void __init proc_root_init (void )
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 22/29 ipc/mqueue: Implement ->set_nsexec() fs_context operation
In reply to Jarkko Sakkinenmqueue_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_NSEXEC and leaving the context bound to the caller's IPC namespace.
Wire up mqueue_set_nsexec() to switch ctx->ipc_ns to the target nsexec's IPC namespace, update fc->user_ns to match, and mark mqueue with FS_NSEXEC_MOUNT.
--- ipc/mqueue.c | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-)
ipc/mqueue.c +24 -4
@@ -30,6 +30,7 @@#include <linux/audit.h> #include <linux/signal.h> #include <linux/mutex.h> +#include <linux/nsexec.h> #include <linux/nsproxy.h> #include <linux/pid.h> #include <linux/ipc_namespace.h>
@@ -400,6 +401,20 @@ static struct inode *mqueue_get_inode(struct super_block *sb,return ERR_PTR (ret); } +static int mqueue_set_nsexec (struct fs_context *fc,struct nsexec *nsexec) +{ +struct mqueue_fs_context *ctx = fc->fs_private; +struct ipc_namespace *ipc_ns; + +scoped_guard (spinlock, &nsexec->lock) + ipc_ns = get_ipc_ns(nsexec->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;
@@ -453,9 +468,13 @@ static int mqueue_init_fs_context(struct fs_context *fc)if (!ctx)return -ENOMEM ; - ctx->ipc_ns =get_ipc_ns (current->nsproxy->ipc_ns); -put_user_ns (fc->user_ns); - fc->user_ns =get_user_ns (ctx->ipc_ns->user_ns); +if (fc->purpose ==FS_CONTEXT_FOR_RECONFIGURE ) { + ctx->ipc_ns =get_ipc_ns (fc->root->d_sb->s_fs_info); + }else { + ctx->ipc_ns =get_ipc_ns (current->nsproxy->ipc_ns); +put_user_ns (fc->user_ns); + fc->user_ns =get_user_ns (ctx->ipc_ns->user_ns); + } fc->fs_private = ctx; fc->ops = &mqueue_fs_context_ops;return 0 ;
@@ -1613,6 +1632,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_nsexec = mqueue_set_nsexec, .get_tree = mqueue_get_tree, };
@@ -1620,7 +1640,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_NSEXEC_MOUNT, };int mq_init_ns (struct ipc_namespace *ns)
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 23/29 security: Add nsexec LSM hooks
In reply to Jarkko SakkinenSecurity modules need visibility into nsexec creation, teardown, namespace sharing, process entry, and nsexec-wide signal delivery so policies can attach per-nsexec security state and mediate operations on nsexec file descriptors.
Add lbs_nsexec and nsexec->security blob management alongside security_nsexec_alloc(), security_nsexec_free(), security_nsexec_share(), security_nsexec_clone(), and security_nsexec_kill().
--- include/linux/lsm_hook_defs.h | 8 ++++ include/linux/lsm_hooks.h | 3 ++ include/linux/nsexec.h | 3 ++ include/linux/security.h | 37 ++++++++++++++++++ kernel/nsexec.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
@@ -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_NSEXEC +LSM_HOOK(int, 0, nsexec_alloc, struct nsexec *nsexec, unsigned int flags) +LSM_HOOK(void, LSM_RET_VOID, nsexec_free, struct nsexec *nsexec) +LSM_HOOK(int, 0, nsexec_share, struct nsexec *nsexec, struct ns_common *ns) +LSM_HOOK(int, 0, nsexec_clone, struct nsexec *nsexec) +LSM_HOOK(int, 0, nsexec_kill, struct nsexec *nsexec, int sig) +#endif /* CONFIG_NSEXEC */
include/linux/lsm_hooks.h +3 -0
@@ -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_NSEXEC +unsigned int lbs_nsexec; +#endif };/*
include/linux/nsexec.h +3 -0
@@ -64,6 +64,9 @@ enum nsexec_state {struct nsexec {refcount_t usage;int exit_code; +#ifdef CONFIG_SECURITY +void *security; +#endif struct user_namespace *user_ns;struct nsproxy *ns;struct pid *init_pid;
include/linux/security.h +37 -0
@@ -84,6 +84,7 @@ struct audit_krule;struct ns_common ;struct user_namespace ;struct timezone ; +struct nsexec ;enum lsm_event {LSM_POLICY_CHANGE ,
@@ -2471,4 +2472,40 @@ static inline void security_initramfs_populated(void) }#endif /* CONFIG_SECURITY */ +#ifdef CONFIG_NSEXEC +#ifdef CONFIG_SECURITY +int security_nsexec_alloc (struct nsexec *nsexec,unsigned int flags); +void security_nsexec_free (struct nsexec *nsexec); +int security_nsexec_share (struct nsexec *nsexec,struct ns_common *ns); +int security_nsexec_clone (struct nsexec *nsexec); +int security_nsexec_kill (struct nsexec *nsexec,int sig); +#else +static inline int security_nsexec_alloc (struct nsexec *nsexec, +unsigned int flags) +{ +return 0 ; +} + +static inline void security_nsexec_free (struct nsexec *nsexec) +{ +} + +static inline int security_nsexec_share (struct nsexec *nsexec, +struct ns_common *ns) +{ +return 0 ; +} + +static inline int security_nsexec_clone (struct nsexec *nsexec) +{ +return 0 ; +} + +static inline int security_nsexec_kill (struct nsexec *nsexec,int sig) +{ +return 0 ; +} +#endif /* CONFIG_SECURITY */ +#endif /* CONFIG_NSEXEC */ +#endif /* ! __LINUX_SECURITY_H */
kernel/nsexec.c +34 -9
115 lines not on this page · raw message
security/lsm_init.c +6 -0
@@ -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_NSEXEC +lsm_blob_size_update (&blobs->lbs_nsexec, &blob_sizes.lbs_nsexec); +#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_NSEXEC +lsm_pr ("blob(nsexec) size %d\n" , blob_sizes.lbs_nsexec); +#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
Jarkko Sakkinen
maintainerRFC PATCH v9 24/29 landlock: Enforce namespace use restrictions on nsexec
In reply to Jarkko SakkinenWhen a Landlock-sandboxed task holds a pre-opened nsexec file descriptor, sharing namespaces via NSEXEC_SHARE_NSFD or spawning a child via clone3(CLONE_INTO_NSEXEC) switches into existing namespaces without passing through security_namespace_install().
Wire nsexec_share and nsexec_clone in Landlock's namespace hooks so LANDLOCK_PERMISSION_NAMESPACE_USE mediates sharing a namespace into a nsexec and entering any nsexec namespace that differs from the caller's current namespaces.
--- security/landlock/ns.c | 63 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 59 insertions(+), 4 deletions(-)
security/landlock/ns.c +59 -4
@@ -13,6 +13,17 @@#include <linux/ns_common.h> #include <linux/nsproxy.h> #include <uapi/linux/landlock.h> +#ifdef CONFIG_NSEXEC +#include <linux/cgroup_namespace.h> +#include <linux/ipc_namespace.h> +#include <linux/mnt_namespace.h> +#include <linux/nsexec.h> +#include <linux/pid_namespace.h> +#include <linux/time_namespace.h> +#include <linux/user_namespace.h> +#include <linux/uts_namespace.h> +#include <net/net_namespace.h> +#endif #include "cred.h" #include "domain.h"
@@ -93,10 +104,10 @@ static const struct access_masks ns_permission = {* @request_type: Namespace operation reported on denial. * * Shared check for namespace_init (creation via clone(2), unshare(2), -* open_tree(2), or fsmount(2)) and namespace_install (use via setns(2)): denies -* when the namespace type is not in the domain's allowed set. At allocation -* time @ns->ns_id is already set even though the namespace is not reachable -* from user space yet. +* open_tree(2), fsmount(2), or nsexec_open(2)), namespace_install (use via +* setns(2)), and nsexec_share / nsexec_clone: denies when the namespace +* type is not in the domain's allowed set. At allocation time @ns->ns_id is +* already set even though the namespace is not reachable from user space yet. * * Return: 0 if allowed, -EPERM if denied. */
@@ -141,9 +152,53 @@ static int hook_namespace_install(const struct nsset *const nsset,return check_ns_type (ns,LANDLOCK_REQUEST_NAMESPACE_ENTER ); } +#ifdef CONFIG_NSEXEC +static int check_nsexec_ns (struct ns_common *const ns) +{ +if (is_current_namespace (ns)) +return 0 ; +return check_ns_type (ns,LANDLOCK_REQUEST_NAMESPACE_ENTER ); +} + +static int hook_nsexec_share (struct nsexec *const nsexec, +struct ns_common *const ns) +{ +return check_ns_type (ns,LANDLOCK_REQUEST_NAMESPACE_ENTER ); +} + +static int hook_nsexec_clone (struct nsexec *const nsexec) +{ +struct ns_common *const namespaces[] = { +to_ns_common (nsexec->user_ns), +from_mnt_ns (nsexec->ns->mnt_ns), +to_ns_common (nsexec->ns->pid_ns_for_children), +to_ns_common (nsexec->ns->cgroup_ns), +to_ns_common (nsexec->ns->ipc_ns), +to_ns_common (nsexec->ns->uts_ns), +to_ns_common (nsexec->ns->net_ns), +#ifdef CONFIG_TIME_NS +to_ns_common (nsexec->ns->time_ns), +#endif + }; +size_t i; + +for (i =0 ; i <ARRAY_SIZE (namespaces); i++) { +int err =check_nsexec_ns (namespaces[i]); + +if (err) +return err; + } +return 0 ; +} +#endif /* CONFIG_NSEXEC */ +static struct security_hook_list landlock_hooks[]__ro_after_init = {LSM_HOOK_INIT (namespace_init, hook_namespace_init),LSM_HOOK_INIT (namespace_install, hook_namespace_install), +#ifdef CONFIG_NSEXEC +LSM_HOOK_INIT (nsexec_share, hook_nsexec_share), +LSM_HOOK_INIT (nsexec_clone, hook_nsexec_clone), +#endif };__init void landlock_add_ns_hooks (void )
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 25/29 bpf: Register nsexec LSM hooks
In reply to Jarkko SakkinenBPF LSM programs need sleepable and untrusted hook classifications for the nsexec LSM hooks in order to attach policies to nsexec allocation, namespace sharing, cloning, signaling, and release.
Register bpf_lsm_nsexec_alloc, bpf_lsm_nsexec_share, bpf_lsm_nsexec_clone, and bpf_lsm_nsexec_kill in sleepable_lsm_hooks, and bpf_lsm_nsexec_alloc and bpf_lsm_nsexec_free in untrusted_lsm_hooks under CONFIG_NSEXEC.
--- kernel/bpf/bpf_lsm.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
kernel/bpf/bpf_lsm.c +11 -0
@@ -16,6 +16,7 @@#include <linux/btf_ids.h> #include <linux/ima.h> #include <linux/bpf-cgroup.h> +#include <linux/nsexec.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_NSEXEC +BTF_ID(func, bpf_lsm_nsexec_alloc) +BTF_ID(func, bpf_lsm_nsexec_share) +BTF_ID(func, bpf_lsm_nsexec_clone) +BTF_ID(func, bpf_lsm_nsexec_kill) +#endif /* CONFIG_NSEXEC */ BTF_SET_END (sleepable_lsm_hooks)BTF_SET_START (untrusted_lsm_hooks)
@@ -422,6 +429,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_NSEXEC +BTF_ID(func, bpf_lsm_nsexec_alloc) +BTF_ID(func, bpf_lsm_nsexec_free) +#endif /* CONFIG_NSEXEC */ BTF_SET_END (untrusted_lsm_hooks) bool bpf_lsm_is_sleepable_hook(u32 btf_id)
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 26/29 arch: Wire up nsexec_open() system call
In reply to Jarkko SakkinenNow that nsexec lifecycle and VFS mount-tree installation are in place, expose nsexec_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
@@ -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 nsexec_open sys_nsexec_open
arch/arm/tools/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
arch/arm64/tools/syscall_32.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
arch/m68k/kernel/syscalls/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
arch/microblaze/kernel/syscalls/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
arch/mips/kernel/syscalls/syscall_n32.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
arch/mips/kernel/syscalls/syscall_n64.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
arch/mips/kernel/syscalls/syscall_o32.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
arch/parisc/kernel/syscalls/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
arch/powerpc/kernel/syscalls/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
arch/s390/kernel/syscalls/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
arch/sh/kernel/syscalls/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
arch/sparc/kernel/syscalls/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open # # Due to a historical design error, certain syscalls are numbered differently
arch/xtensa/kernel/syscalls/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
include/uapi/asm-generic/unistd.h +5 -1
@@ -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/nsexec.c */ +#define __NR_nsexec_open 474 +__SYSCALL(__NR_nsexec_open, sys_nsexec_open) +#undef __NR_syscalls -#define __NR_syscalls 474 +#define __NR_syscalls 475/* * 32 bit systems traditionally used different
scripts/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
tools/include/uapi/asm-generic/unistd.h +5 -1
@@ -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/nsexec.c */ +#define __NR_nsexec_open 474 +__SYSCALL(__NR_nsexec_open, sys_nsexec_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
@@ -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 nsexec_open sys_nsexec_open
tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
tools/perf/arch/powerpc/entry/syscalls/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
tools/perf/arch/s390/entry/syscalls/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
tools/perf/arch/sh/entry/syscalls/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
tools/perf/arch/sparc/entry/syscalls/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
tools/perf/arch/x86/entry/syscalls/syscall_32.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
tools/perf/arch/x86/entry/syscalls/syscall_64.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open # # Due to a historical design error, certain syscalls are numbered differently
tools/perf/arch/xtensa/entry/syscalls/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
tools/scripts/syscall.tbl +1 -0
@@ -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 nsexec_open sys_nsexec_open
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 27/29 docs: Document nsexec uAPI
In reply to Jarkko SakkinenUserspace orchestrators need a clear specification of what an nsexec is, its build and live state transitions, NSEXEC_GET_NSFD, NSEXEC_SHARE_NSFD, waitid(P_NSEXEC), pidfd_send_signal(), mount-tree construction, user namespace ID mapping, credential rules, and process creation semantics.
Add Documentation/userspace-api/nsexec.rst including the kernel-doc sections, type definitions, ioctl descriptions, and system call reference from include/linux/nsexec.h, include/uapi/linux/nsexec.h, include/uapi/linux/nsfs.h, kernel/nsexec.c, kernel/user_namespace.c, fs/fsopen.c, and fs/namespace.c, and register the nsexec ioctl magic in ioctl-number.rst.
--- Documentation/userspace-api/index.rst | 1 + .../userspace-api/ioctl/ioctl-number.rst | 1 + Documentation/userspace-api/nsexec.rst | 77 +++++++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 Documentation/userspace-api/nsexec.rst
Documentation/userspace-api/index.rst +1 -0
@@ -17,6 +17,7 @@ System calls :maxdepth: 1 unshare + nsexec futex2 ebpf/index ioctl/index
Documentation/userspace-api/ioctl/ioctl-number.rst +1 -0
@@ -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/nsexec.h nsexec uAPI 0xBA 00-0F uapi/linux/liveupdate.h Pasha Tatashin <mailto:[email protected]> 0xC0 00-0F linux/usb/iowarrior.h
Documentation/userspace-api/nsexec.rst new file +77 -0
77 lines not on this page · raw message
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH v9 28/29 selftests/nsexec: Add nsexec test suite
In reply to Jarkko SakkinenAdd a model-based stochastic kselftest suite for nsexec_open(), NSEXEC_GET_NSFD, NSEXEC_SHARE_NSFD, waitid(P_NSEXEC), pidfd_send_signal(), userns_set_idmap(), FSCONFIG_SET_NSEXEC, MOVE_MOUNT_T_MNTNS, CLONE_INTO_NSEXEC, and Landlock namespace mediation.
Drive lifecycle, ID-mapping, mount-tree, multi-cell supervisor, and Landlock scenarios from a seeded choice stream against a reference uAPI oracle. Each case is a pure function of the seed, scenario, and case index, and shrinking is bounded by attempt count, so NSEXEC_SEED and NSEXEC_CASE replay both a failure and its minimal trace.
--- tools/testing/selftests/Makefile | 1 + tools/testing/selftests/nsexec/Makefile | 7 + tools/testing/selftests/nsexec/cells.py | 1560 ++++++++++ tools/testing/selftests/nsexec/config | 13 + tools/testing/selftests/nsexec/machine.py | 333 ++ tools/testing/selftests/nsexec/oracle.py | 386 +++ tools/testing/selftests/nsexec/selftest.py | 2887 ++++++++++++++++++ tools/testing/selftests/nsexec/settings | 1 + tools/testing/selftests/nsexec/test_smoke.sh | 11 + 9 files changed, 5199 insertions(+) create mode 100644 tools/testing/selftests/nsexec/Makefile create mode 100644 tools/testing/selftests/nsexec/cells.py create mode 100644 tools/testing/selftests/nsexec/config create mode 100644 tools/testing/selftests/nsexec/machine.py create mode 100644 tools/testing/selftests/nsexec/oracle.py create mode 100755 tools/testing/selftests/nsexec/selftest.py create mode 100644 tools/testing/selftests/nsexec/settings create mode 100755 tools/testing/selftests/nsexec/test_smoke.sh
tools/testing/selftests/Makefile +1 -0
@@ -101,6 +101,7 @@ TARGETS += net/rds TARGETS += net/tcp_ao TARGETS += nfsd TARGETS += nolibc +TARGETS += nsexec TARGETS += pci_endpoint TARGETS += pcie_bwctrl TARGETS += perf_events
tools/testing/selftests/nsexec/Makefile new file +7 -0
@@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0 +include ../lib.mk + +TEST_PROGS := test_smoke.sh +TEST_PROGS_EXTENDED := selftest.py +TEST_FILES := cells.py machine.py oracle.py +TEST_INCLUDES := ../kselftest/ksft.py
tools/testing/selftests/nsexec/cells.py new file +1560 -0
1,560 lines not on this page · raw message
tools/testing/selftests/nsexec/config new file +13 -0
@@ -0,0 +1,13 @@ +CONFIG_CGROUPS=y +CONFIG_IPC_NS=y +CONFIG_NET_NS=y +CONFIG_NSEXEC=y +CONFIG_PID_NS=y +CONFIG_POSIX_MQUEUE=y +CONFIG_PROC_FS=y +CONFIG_SECURITY=y +CONFIG_SECURITY_LANDLOCK=y +CONFIG_TIME_NS=y +CONFIG_TMPFS=y +CONFIG_USER_NS=y +CONFIG_UTS_NS=y
tools/testing/selftests/nsexec/machine.py new file +333 -0
333 lines not on this page · raw message
tools/testing/selftests/nsexec/oracle.py new file +386 -0
386 lines not on this page · raw message
tools/testing/selftests/nsexec/selftest.py new file +2887 -0
694 lines not on this page · raw message
tools/testing/selftests/nsexec/settings new file +1 -0
Lines of this file are not shown. View the raw message.
tools/testing/selftests/nsexec/test_smoke.sh new file +11 -0
Lines of this file are not shown. View the raw message.
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.47.3
Part of the diff is not shown here. View the raw message.
Jarkko Sakkinen
maintainerRFC PATCH v9 29/29 MAINTAINERS: Add entry for NSEXEC
In reply to Jarkko SakkinenRecord maintainership and mailing list routing for nsexecs across their uAPI headers, core implementation, documentation, and selftests.
--- MAINTAINERS | 11 +++++++++++ 1 file changed, 11 insertions(+)
MAINTAINERS +11 -0
@@ -19976,6 +19976,17 @@ S: Maintained F: Documentation/core-api/symbol-namespaces.rst F: scripts/nsdeps +NSEXEC +M: David Howells <[email protected]> +M: Jarkko Sakkinen <[email protected]> +L: [email protected] +S: Maintained +F: Documentation/userspace-api/nsexec.rst +F: include/linux/nsexec.h +F: include/uapi/linux/nsexec.h +F: kernel/nsexec.c +F: tools/testing/selftests/nsexec/ + NTB AMD DRIVER M: Basavaraj Natikar <[email protected]> M: Shyam Sundar S K <[email protected]>
Signature · 1 line
2.47.3
[email protected]
AI reviewRe: [RFC PATCH v9 02/29] userns: Add userns_set_idmap() system call
In reply to Jarkko SakkinenThank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] userns: caller_idmap_permitted() rejects delegated projid_map without CAP_SETUID --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] userns: caller_idmap_permitted() rejects delegated projid_map without CAP_SETUID
--
commit 58bf5f681d11a23cb6edc84d8207c82688e2ecbb
Author: Jarkko Sakkinen <[email protected]>
userns: Add userns_set_idmap() system call
This commit adds the userns_set_idmap() system call to atomically configure UID, GID, and project ID mappings as well as the setgroups policy on a user namespace file descriptor.
Quoted 4 lines
kernel/user_namespace.c +0
-0
[ ... ]
Quoted 16 lines
kernel/user_namespace.c +12
-0@@ -1176,6 +1180,228 @@ static ssize_t map_write(struct file *file, const char __user *buf,return ret; } +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)) { +if (cred->user_ns == ns) { +if (!ns->parent_could_setfcap) +return false; + }else { +if (!ns_capable (ns->parent,CAP_SETFCAP ))
kernel/user_namespace.c static ssize_t map_write(struct file *file, const char __user *buf, · line 1204
Quoted 10 lines
kernel/user_namespace.c +10
-0+return false; + } + } + +if (unpriv_idmap_permitted (ns, cred, cap_setid, ns_flags, new_map)) +return true; + +if (!cap_valid (cap_setid)) +return ns_capable (ns,CAP_SYS_ADMIN ) || +ns_capable (ns->parent,CAP_SETUID );
[Severity: Medium]
Should !cap_valid(cap_setid) return true here, matching new_idmap_permitted() for project ID mappings?
sys_userns_set_idmap() already verifies that either the caller or the file opener holds CAP_SYS_ADMIN in ns, and project ID mappings do not require any parent namespace capability. Requiring the caller itself to hold CAP_SYS_ADMIN in ns or CAP_SETUID in ns->parent causes configuring projid_extents via a delegated userns fd to fail with -EPERM when the caller does not have CAP_SETUID (for example, an unprivileged process or a helper holding only CAP_SETGID).
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
[email protected]
AI reviewRe: [RFC PATCH v9 22/29] ipc/mqueue: Implement ->set_nsexec() fs_context operation
In reply to Jarkko SakkinenThank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Critical] ipc/mqueue: unlocked s_fs_info access in mqueue_init_fs_context() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Critical] ipc/mqueue: unlocked s_fs_info access in mqueue_init_fs_context()
--
commit 067998e02a49b9e15984753bd84467279b66c72f
Author: Jarkko Sakkinen <[email protected]>
ipc/mqueue: Implement ->set_nsexec() fs_context operation
This commit implements the ->set_nsexec() fs_context operation for mqueue so that FSCONFIG_SET_NSEXEC binds the mount context to the target nsexec's IPC and user namespaces, and marks mqueue with FS_NSEXEC_MOUNT.
Quoted 4 lines
ipc/mqueue.c +0
-0
[ ... ]
ipc/mqueue.c static int mqueue_init_fs_context(struct fs_context *fc) · line 472
Quoted 9 lines
ipc/mqueue.c +2
-3@@ -453,9 +468,13 @@ static int mqueue_init_fs_context(struct fs_context *fc)if (!ctx)return -ENOMEM ; - ctx->ipc_ns =get_ipc_ns (current->nsproxy->ipc_ns); -put_user_ns (fc->user_ns); - fc->user_ns =get_user_ns (ctx->ipc_ns->user_ns); +if (fc->purpose ==FS_CONTEXT_FOR_RECONFIGURE ) { + ctx->ipc_ns =get_ipc_ns (fc->root->d_sb->s_fs_info);
[Severity: Critical]
Can this race with put_ipc_ns() and cause a use-after-free on struct ipc_namespace?
An mqueue superblock does not hold a reference to the ipc_namespace in sb->s_fs_info; instead, put_ipc_ns() drops the last reference and clears sb->s_fs_info under mq_lock (which is why get_ns_from_inode() takes mq_lock around get_ipc_ns(inode->i_sb->s_fs_info)). Without mq_lock, a reconfiguration context created via fspick() can read s_fs_info as the last reference is dropped:
CPU0 CPU1mqueue_init_fs_context() put_ipc_ns(ns)
ns = fc->root->d_sb->s_fs_info
ns_ref_put_and_lock(ns, &mq_lock)
mq_clear_sbinfo(ns)
spin_unlock(&mq_lock)
schedule_work(&free_ipc_work) get_ipc_ns(ns) <-- refcount inc on 0
free_ipc()
free_ipc_ns(ns) <-- frees nsmqueue_fs_context_free()
put_ipc_ns(ctx->ipc_ns) <-- use-after-free
Acquiring ctx->ipc_ns under spin_lock(&mq_lock) (or leaving ctx->ipc_ns as NULL for FS_CONTEXT_FOR_RECONFIGURE, since mqueue does not use it during reconfiguration) would avoid this race.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=22
[email protected]
AI reviewRe: [RFC PATCH v9 06/29] mount: Support MOVE_MOUNT_T_MNTNS in move_mount()
In reply to Jarkko SakkinenThank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] fs: wrong cross-userns mount locking in attach_recursive_mnt() propagation --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] fs: wrong cross-userns mount locking in attach_recursive_mnt() propagation
--
commit 01b19cb52ebce04625295530b64ccf410f04c2f8
Author: Jarkko Sakkinen <[email protected]>
mount: Support MOVE_MOUNT_T_MNTNS in move_mount()
This commit adds the MOVE_MOUNT_T_MNTNS flag to move_mount() to attach detached anonymous mount trees into a target mount namespace specified by an nsfs file descriptor.
Quoted 4 lines
fs/namespace.c +0
-0
[ ... ]
Quoted 42 lines
fs/namespace.c +12
-4@@ -2632,13 +2647,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;@@ -2688,7 +2705,8 @@ static int attach_recursive_mnt(struct mount *source_mnt, err =invent_group_ids (source_mnt, true);if (err) goto out; - err =propagate_mnt (dest_mnt, dest_mp, source_mnt, &tree_list); + err =propagate_mnt (dest_mnt, dest_mp, source_mnt, &tree_list, + cross_src); }lock_mount_hash ();if (err)@@ -2725,11 +2743,22 @@ static int attach_recursive_mnt(struct mount *source_mnt,hlist_add_head (&source_mnt->mnt_hash, &tree_list);hlist_for_each_entry_safe (child, n, &tree_list, mnt_hash) { +struct user_namespace *child_user_ns = + child->mnt_parent->mnt_ns->user_ns; +bool cross_child_src = cross_src && + !in_userns (child_user_ns, src_user_ns);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) +/* +* Notice when we are propagating or attaching a foreign
fs/namespace.c static int attach_recursive_mnt(struct mount *source_mnt, · line 2764
Quoted 10 lines
fs/namespace.c +6
-0+* source tree across user namespaces. +*/ +if (child_user_ns != user_ns || cross_child_src) {lock_mnt_tree (child); +if (cross_child_src &&list_empty (&child->mnt_expire)) + child->mnt.mnt_flags |=MNT_LOCKED ; + } q =__lookup_mnt (&child->mnt_parent->mnt, child->mnt_mountpoint);commit_tree (child);
[Severity: High]
Does gating cross_child_src and propagate_mnt()'s lock_source on cross_src mishandle shared mount propagation across different user namespaces?
cross_src only compares src_user_ns against the primary destination ns->user_ns. When in_userns(ns->user_ns, src_user_ns) is true (so cross_src is false), but dest_mnt propagates to a slave or peer mount in a less-privileged user namespace where !in_userns(child_user_ns, src_user_ns) holds, propagate_mnt() runs without CL_LOCK_SOURCE and copy_tree() silently drops unlocked unbindable or nsfs submounts instead of returning -EPERM, exposing the underlying covered directories. In the tree_list loop, cross_child_src also stays false, leaving child without MNT_LOCKED even when child_user_ns == user_ns does not hold or when lock_mnt_tree() only locks submounts below child.
Conversely, when cross_src is true, propagate_mnt() passes CL_LOCK_SOURCE to copy_tree() for every secondary mount n regardless of n->mnt_ns->user_ns (and chains copy = this with MNT_LOCKED already set on submounts), rejecting unbindable/nsfs submounts with -EPERM and locking submounts even in peer namespaces that are privileged over src_user_ns.
Checking !in_userns(n->mnt_ns->user_ns, src_user_ns) per secondary target in propagate_mnt() (without mutating the source tree used for subsequent peers) and dropping cross_src from the cross_child_src condition would evaluate each target namespace against src_user_ns directly.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
[email protected]
AI reviewSashiko has finished reviewing this 29-patch series:
Sashiko has finished reviewing this 29-patch series:
- Patches 1, 3-5, 7-21, and 23-28: no issues found.
- Patch 2 ("userns: Add userns_set_idmap() system call"): 1 potential issue (1 Medium)
- Patch 6 ("mount: Support MOVE_MOUNT_T_MNTNS in move_mount()"): 1 potential issue (1 High)
- Patch 22 ("ipc/mqueue: Implement ->set_nsexec() fs_context oper..."):
1 potential issue (1 Critical)
- Patch 29: skipped (not reviewed).
Detailed reviews have been sent as separate replies to patches 2, 6, and 22.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]
Jarkko Sakkinen
maintainerQuoted 484 lines · Jarkko Sakkinen
MOTIVATION
==========Self-modifying uninitialized state in containers is probably one of the biggest security challenges we have at the moment.
The primitives for namespaces, credentials, and mounts were designed to be invoked from inside the process being isolated, one step at a time.
Container runtimes and sandboxes (runc, systemd-nspawn, bubblewrap, etc.) approach the problem with a chain of short-lived helper processes, which are managed by pausing them behind pipes or socket pairs.
While this is happening, the parent process does the whole shebang of obscure management tasks:
1. Writes /proc/<pid>/uid_map and /proc/<pid>/gid_map.
2. Clones the host's entire mount table only to tear it back down withpivot_root()and fork yet again before PID 1 can finally callexecve().runc has one of the worst-case scenarios in this regard given that the Go runtime is always multi-threaded. This disallows calling
unshare(CLONE_NEWUSER | CLONE_NEWNS)orsetns(CLONE_NEWUSER)directly from Go. The workaround addressing this is based on a C trampoline.I.e., packing the cargo happens exactly at the time when the ship is lifting the anchor and detaching from the harbor, and with the current syscall API there's no common-sense way around this.
For what it is worth, any practical cryptography such as authenticated measurement is also not doable, because the primitives can only measure a static and immutable target.
OVERVIEW
========If the root of the problem is that an isolated process has to assemble its own prison from the inside while already running, the natural alternative is to invert the sequence: construct the entire execution environment from the outside while it is still inert, and only spawn a process once setup is complete.
Building on David Howells' earlier work on kernel container objects [1], this series introduces nsexec: an anonymous-inode control descriptor that splits namespace setup and process execution into distinct build and live phases.
Opening an nsexec descriptor allocates a fresh user namespace together with a detached set of mount, PID, UTS, IPC, network, cgroup, and time namespaces. Crucially, the mount namespace starts completely empty (
CLONE_EMPTY_MNTNS) rather than cloning the caller's mount table, and no task exists inside any of the new namespaces during the build phase (NSEXEC_INIT).Because the caller's own credentials, root directory, and thread group are never mutated during construction, even a multi-threaded runtime such as Go can drive the entire setup directly over file descriptors without helper processes or C trampolines. Rather than introducing a parallel namespace API, nsexec plugs into existing descriptor-based syscalls for ID mapping, filesystem configuration, mount placement, process creation, waiting, and signaling.
[1] https://lwn.net/Articles/780364/
SOLUTION
========The standalone primitives at the front of the series (patches 01-09) make both user namespaces and mount namespaces configurable via nsfs file descriptors without a paused child task, while the remaining patches tie them together around the nsexec lifecycle.
1. Allocating namespaces and programming ID maps
A manager begins by calling
nsexec_open(), which returns a close-on-exec control descriptor inNSEXEC_INIT. While in this build phase, the manager can optionally opt individual cgroup, IPC, UTS, network, or time namespaces into existing nsfs descriptors viaioctl(NSEXEC_SHARE_NSFD), or extract nsfs descriptors for member namespaces viaioctl(NSEXEC_GET_NSFD).Instead of formatting text into /proc/<pid>/uid_map and
gid_mapwhile a helper blocks on a pipe,userns_set_idmap()programs UID, GID, and project ID extents (along withUSERNS_SETGROUPS_ALLOWED) atomically on the user namespace descriptor:nsexec_fd = nsexec_open(NSEXEC_AUTOKILL); userns_fd = ioctl(nsexec_fd, NSEXEC_GET_NSFD, CLONE_NEWUSER); mntns_fd = ioctl(nsexec_fd, NSEXEC_GET_NSFD, CLONE_NEWNS); struct userns_idmap_extent ext = { .first = 0, .lower_first = 1000, .count = 1, }; struct userns_idmap map = { .nr_uid_extents = 1, .nr_gid_extents = 1, .uid_extents = (__u64)(uintptr_t)&ext, .gid_extents = (__u64)(uintptr_t)&ext, }; userns_set_idmap(userns_fd, &map, sizeof(map), 0);Parent ID ranges are authorized against the caller of
userns_set_idmap(), allowing an unprivileged runtime to passuserns_fdoverSCM_RIGHTSto a privileged mapping helper without keeping an embryonic child alive.2. Assembling the mount tree without
pivot_root()With ID mappings in place, superblocks can be instantiated directly inside the nsexec's user, network, PID (proc), and IPC (mqueue) namespaces by binding a mount-API context via
FSCONFIG_SET_NSEXEC. Filesystems opt into unprivileged delegation withFS_NSEXEC_MOUNT(tmpfs, ramfs, devpts, proc, and mqueue) orFS_USERNS_DELEGATABLE.To populate the empty mount namespace without entering it,
move_mount()learns two flags:MOVE_MOUNT_T_MNTNSresolvesto_dfdas a mount namespace descriptor (attaching "/" onto its nullfs root once, and resolving relative paths beneath that root thereafter), andMOVE_MOUNT_CLONErecursively bind-clones a source tree without requiringOPEN_TREE_CLONEor hostCAP_SYS_ADMIN:fs_fd = fsopen("tmpfs", FSOPEN_CLOEXEC); fsconfig(fs_fd, FSCONFIG_SET_NSEXEC, NULL, NULL, nsexec_fd); fsconfig(fs_fd, FSCONFIG_CMD_CREATE, NULL, NULL, 0); root_fd = fsmount(fs_fd, FSMOUNT_CLOEXEC, 0); mkdirat(root_fd, "usr", 0755); move_mount(root_fd, "", mntns_fd, "/", MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_MNTNS); move_mount(AT_FDCWD, "/usr", mntns_fd, "usr", MOVE_MOUNT_T_MNTNS | MOVE_MOUNT_CLONE);Mounts crossing user namespace boundaries are locked with
MNT_LOCKED, and LSMs mediateMOVE_MOUNT_CLONEasMS_BIND|MS_REC. The sameMOVE_MOUNT_T_MNTNSpath remains available after boot for live mount hotplug, which workloads can observe viafanotify(FAN_MNT_ATTACH)andstatmount().3. Spawning PID 1 and supervising the lifecycle
Once "/" has been installed,
clone3()withCLONE_INTO_NSEXECspawns the first child directly into the configured environment as PID 1, transitioning the descriptor fromNSEXEC_INITthroughNSEXEC_FORKINGtoNSEXEC_RUNNING:struct clone_args args = { .flags = CLONE_INTO_NSEXEC, .nsexec = nsexec_fd, }; pid = clone3(&args, sizeof(args)); if (pid == 0) execve("/sbin/init", argv, envp); waitid(P_NSEXEC, nsexec_fd, &info, WEXITED);Subsequent
CLONE_INTO_NSEXECcalls join the running PID namespace directly for management or diagnostic sessions. To prevent half-transitioned task state,CLONE_VM,CLONE_FILES,CLONE_FS, andCLONE_SIGHANDare rejected; when the caller originates outside the target user namespace,exec_state->user_nsstays anchored in that outer namespace with dumpability reset tosuid_dumpableuntilexecve(), blocking member tasks from tracing the child or reading /proc/<pid>/{exe,mem,fd}.At runtime,
pidfd_send_signal()broadcasts signals across member thread groups,poll()reports EPOLLHUP once PID 1 exits and the PID namespace is reaped, andwaitid(P_NSEXEC)reads init's exit status without consuming it. Dedicated LSM hooks (wired into Landlock and BPF LSM) mediate allocation, namespace sharing, process entry, and signaling.Experimental userspace support with runtime fallback on older kernels is maintained for systemd [2], bubblewrap [3], and podman [4], integrated end to end in linux-tpmdd-test [5].
[2] https://github.com/jarkkojs/systemd/commits/nsexec
[3] https://github.com/jarkkojs/bubblewrap/commits/nsexec
[4] https://github.com/jarkkojs/podman/commits/nsexec
[5] https://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd-test.git/CHANGES
=======v9:
- The main theme is the refactorization ofuserland_open()intonsexec()and rewriting the cover letter to be focused on execution rather than data structures, as latter should be only consequence of the former.
- Rewrite the kselftest as a seed-replayable model-based fuzzer.
- Rename userland to nsexec across syscalls, ioctls,clone3(),waitid(),fsconfig(), LSM hooks, documentation, selftests, andMAINTAINERS.
- RenameUSERLAND_KILL_ON_CLOSEtoNSEXEC_AUTOKILLand dropUSERLAND_CLOEXECin favor of unconditionalO_CLOEXEConnsexec_open().
- RecheckCAP_SYS_ADMINonfc->user_nsafter ->set_nsexec(), gateFSCONFIG_SET_NSEXEConCONFIG_NSEXEC, preserve proc and mqueue namespaces onFS_CONTEXT_FOR_RECONFIGURE, and validate proc gid= againstfc->user_nsviafsparam_gid().
- NOTE: Despite the patch set size grows, the feature size does not, which is about 2400 lines added and 260 removed. This patch set is dominated by the Python test suite (for a good reason).v8:
- Pass MOVE_MOUNT_* flags tosecurity_move_mount(), mediateMOVE_MOUNT_CLONEasMS_BIND|MS_RECin AppArmor, and enforce Landlock namespace restrictions on userland entry and sharing (Sashiko).
- MoveUSERLAND_ALL_FLAGSout of uAPI, renameUSERLAND_CLOSE_ON_EXECtoUSERLAND_CLOEXEC, drop unuseduserland_copy(),userland_exit(), andfsconfig_set_userland()code, and resetexec_state->dumpablewheneverexec_state->user_nsoriginates outside the target user namespace (Sashiko, Askar Safin).
- Fixsys_userns_set_idmap()kernel-doc range syntax and documentCLONE_INTO_USERLANDpre-execve()ptrace_may_access()isolation (Sashiko, Askar Safin).
- Routeunshare()andsetns()via ctypes for Python 3.9 compatibility, isolate /tmp mount propagation when running as root, and derive the E2BIG buffer size fromSC_PAGE_SIZEin selftests/userland (Sashiko).v7:
- Moveuserland_copy()outsidetasklist_lock, loop inuserland_waitid()across bootstrap retries, deferfsmount()may_mount()onuserland_boundcontexts, and clean up mount/idmap helpers (Sashiko).
- Moveuserland.rstprose into modular kernel-doc comments, document ->set_userland() inmount_api.rst, and harden selftests/userland for x32/i386,CONFIG_TIME_NS=n, andSOCK_SEQPACKETfd passing (Sashiko).v6:
- Rename rootns to userland, replaceROOTNS_WAITandROOTNS_KILLioctls withwaitid(P_USERLAND)andpidfd_send_signal(), and addUSERLAND_SHARE_NSFDplussecurity_userland_share().
- GateFSCONFIG_SET_USERLANDonFS_USERLAND_MOUNT, passUSERNS_SETGROUPS_ALLOWEDvia syscall flags, bounduserns_set_idmap()size toPAGE_SIZE, and tighten mount and pidns checks (Sashiko).v5:
- Split standalone fd-based user and mount namespace setup ahead of core control object patches, and adduserns_set_idmap()(Andy Lutomirski) plusMOVE_MOUNT_CLONE.v4:
- Consolidate control syscalls into an anonymous-inode fd, add LSM hooks andbpf_lsmwiring, disallowCLONE_VM, and rewrite kselftests in Python (Sashiko).v3:
- ReplaceMOVE_MOUNT_T_ROOTNS_ROOTwithMOVE_MOUNT_T_MNTNS, addGET_NSFDioctl, and support unprivilegedFSCONFIG_SET_ROOTNSmount configuration (Andy Lutomirski, Sashiko).v2:
- Rely onuser_namespaceownership forsetns()isolation and replacerootns_enter()withclone3()entry (Andy Lutomirski).VERSIONS
========v8: https://lore.kernel.org/linux-fsdevel/[email protected]/
v7: https://lore.kernel.org/linux-fsdevel/[email protected]/
v6: https://lore.kernel.org/linux-fsdevel/[email protected]/
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 Alexei Starovoitov <[email protected]>Cc Andrew Morton <[email protected]>Cc Andrii Nakryiko <[email protected]>Cc Andy Lutomirski <[email protected]>Cc Arnd Bergmann <[email protected]>Cc Baolin Wang <[email protected]>Cc Ben Segall <[email protected]>Cc Christian Brauner <[email protected]>Cc Daniel Borkmann <[email protected]>Cc David Hildenbrand <[email protected]>Cc David Howells <[email protected]>Cc David Woodhouse <[email protected]>Cc Davidlohr Bueso <[email protected]>Cc Dietmar Eggemann <[email protected]>Cc Eduard Zingerman <[email protected]>Cc Emil Tsalapatis <[email protected]>Cc Eric Biggers <[email protected]>Cc Georgia Garcia <[email protected]>Cc Giuseppe Scrivano <[email protected]>Cc "Günther Noack" <[email protected]>Cc Hugh Dickins <[email protected]>Cc Ihor Solodrai <[email protected]>Cc Ingo Molnar <[email protected]>Cc James Morris <[email protected]>Cc Jan Kara <[email protected]>Cc Jason Gunthorpe <[email protected]>Cc Jarkko Sakkinen <[email protected]>Cc Jeff Layton <[email protected]>Cc Jiri Olsa <[email protected]>Cc John Johansen <[email protected]>Cc Jonathan Corbet <[email protected]>Cc Josef Bacik <[email protected]>Cc Juri Lelli <[email protected]>Cc Kees Cook <[email protected]>Cc K Prateek Nayak <[email protected]>Cc KP Singh <[email protected]>Cc Kumar Kartikeya Dwivedi <[email protected]>Cc Lennart Poettering <[email protected]>Cc "Liam R. Howlett" <[email protected]>Cc Manfred Spraul <[email protected]>Cc Martin KaFai Lau <[email protected]>Cc Matt Bobrowski <[email protected]>Cc Mel Gorman <[email protected]>Cc Michal Hocko <[email protected]>Cc "Mickaël Salaün" <[email protected]>Cc Mickaël Salaün <[email protected]>Cc Mike Rapoport <[email protected]>Cc Neal Gompa <[email protected]>Cc Oleg Nesterov <[email protected]>Cc Paul Moore <[email protected]>Cc Pavel Tikhomirov <[email protected]>Cc Peter Zijlstra <[email protected]>Cc Randy Dunlap <[email protected]>Cc "Serge E. Hallyn" <[email protected]>Cc Serge Hallyn <[email protected]>Cc Shuah Khan <[email protected]>Cc Song Liu <[email protected]>Cc Stephen Smalley <[email protected]>Cc Steven Rostedt <[email protected]>Cc Valentin Schneider <[email protected]>Cc Vincent Guittot <[email protected]>Cc Yonghong Song <[email protected]>Cc Zygmunt Krynicki <[email protected]>Jarkko Sakkinen (29):
userns: Factor out idmap validation and commit helpers
userns: Adduserns_set_idmap()system call
arch: Wire upuserns_set_idmap()system call
mount: Addmnt_ns_get_root()
mount: Enforcemount_too_revealing()for foreign mntns
mount: SupportMOVE_MOUNT_T_MNTNSinmove_mount()
security: Pass flags tosecurity_move_mount()
mount: SupportMOVE_MOUNT_CLONEwithMOVE_MOUNT_T_MNTNS
apparmor: MediateMOVE_MOUNT_CLONEas recursive bind
userns: Factor outinstall_user_ns_cred()
nsproxy: Exposecreate_new_namespaces()
nsexec: Add core infrastructure
nsexec: Track init lifecycle viacopy_process()andpid_namespace
nsexec: Addnsexec_open()system call
nsexec: AddNSEXEC_GET_NSFDioctl
nsexec: AddNSEXEC_SHARE_NSFDioctl
exit: SupportP_NSEXECinwaitid()
signal: Support nsexec fds inpidfd_send_signal()
fork: SupportCLONE_INTO_NSEXECinclone3()
fs: SupportFSCONFIG_SET_NSEXECinfsconfig()
proc: Implement ->set_nsexec()fs_contextoperation ipc/mqueue: Implement ->set_nsexec()fs_contextoperation
security: Add nsexec LSM hooks
landlock: Enforce namespace use restrictions on nsexec
bpf: Register nsexec LSM hooks
arch: Wire upnsexec_open()system call
docs: Document nsexec uAPI
selftests/nsexec: Add nsexec test suite
MAINTAINERS: Add entry for NSEXECDocumentation/filesystems/mount_api.rst | 35 +- Documentation/userspace-api/index.rst | 1 + .../userspace-api/ioctl/ioctl-number.rst | 1 + Documentation/userspace-api/nsexec.rst | 77 + 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 | 8 +- fs/filesystems.c | 15 + fs/fs_context.c | 21 +- fs/fsopen.c | 131 +- fs/internal.h | 7 +- fs/namespace.c | 376 ++- fs/pnode.c | 7 +- fs/pnode.h | 3 +- fs/proc/root.c | 61 +- 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 | 10 +- include/linux/lsm_hooks.h | 3 + include/linux/mnt_namespace.h | 2 + include/linux/nsexec.h | 136 + 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 | 43 +- include/linux/syscalls.h | 5 + include/linux/user_namespace.h | 9 +- include/uapi/asm-generic/unistd.h | 10 +- include/uapi/linux/mount.h | 5 +- include/uapi/linux/nsexec.h | 55 + include/uapi/linux/nsfs.h | 46 + include/uapi/linux/sched.h | 5 + include/uapi/linux/wait.h | 1 + init/Kconfig | 10 + ipc/mqueue.c | 28 +- kernel/Makefile | 2 + kernel/bpf/bpf_lsm.c | 11 + kernel/cred.c | 20 +- kernel/exit.c | 4 + kernel/fork.c | 85 +- kernel/nsexec.c | 760 +++++ kernel/nsproxy.c | 15 +- kernel/pid_namespace.c | 2 + kernel/signal.c | 4 + kernel/sys_ni.c | 4 + kernel/user_namespace.c | 459 ++- mm/shmem.c | 5 +- scripts/syscall.tbl | 2 + security/apparmor/include/mount.h | 2 +- security/apparmor/include/path.h | 1 + security/apparmor/lsm.c | 4 +- security/apparmor/mount.c | 50 +- security/apparmor/path.c | 6 +- security/apparmor/policy_unpack.c | 6 +- security/landlock/fs.c | 3 +- security/landlock/ns.c | 63 +- security/lsm_init.c | 6 + security/security.c | 79 +- security/selinux/hooks.c | 2 +- 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/nsexec/Makefile | 7 + tools/testing/selftests/nsexec/cells.py | 1560 +++++++++ tools/testing/selftests/nsexec/config | 13 + tools/testing/selftests/nsexec/machine.py | 333 ++ tools/testing/selftests/nsexec/oracle.py | 386 +++ tools/testing/selftests/nsexec/selftest.py | 2887 +++++++++++++++++ tools/testing/selftests/nsexec/settings | 1 + tools/testing/selftests/nsexec/test_smoke.sh | 11 + 97 files changed, 7745 insertions(+), 265 deletions(-) create mode 100644 Documentation/userspace-api/nsexec.rst create mode 100644 include/linux/nsexec.h create mode 100644 include/uapi/linux/nsexec.h create mode 100644 kernel/nsexec.c create mode 100644 tools/testing/selftests/nsexec/Makefile create mode 100644 tools/testing/selftests/nsexec/cells.py create mode 100644 tools/testing/selftests/nsexec/config create mode 100644 tools/testing/selftests/nsexec/machine.py create mode 100644 tools/testing/selftests/nsexec/oracle.py create mode 100755 tools/testing/selftests/nsexec/selftest.py create mode 100644 tools/testing/selftests/nsexec/settings create mode 100755 tools/testing/selftests/nsexec/test_smoke.sh
Quoted 4 lines
base-commit:
fd7e96c6c90bb18c9b23f2bbfbbde4d89ac6d88a--
2.47.3
I.e. this is the beef:
int nsexec_fd = nsexec();
if (nsexec_fd < 0) {
perror("nsexec");
exit(1);
}
/*
* Configure mount points and shared namespaces
* (NSEXEC_SHARE_NSFD), credentials (userns_set_idmap()) and
* what not. Nothing is going on right now except cargo
* is being loaded.
*/
bootstrap(nsexec_fd);
struct clone_args args = {
.flags = CLONE_INTO_NSEXEC,
.nsexec = nsexec_fd,
};
int pid = clone3(&args, sizeof(args));
if (pid == 0)
execve("/sbin/init", argv, envp);
waitid(P_NSEXEC, nsexec_fd, &info, WEXITED);Br, Jarkko