Linux Kernel Selftest development
 help / color / mirror / Atom feed
* [RFC PATCH v9 00/29] nsexec: Staged namespace execution
@ 2026-12-01  3:09 Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 01/29] userns: Factor out idmap validation and commit helpers Jarkko Sakkinen
                   ` (29 more replies)
  0 siblings, 30 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

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/20261128235808.2369970-1-jarkko@kernel.org/
v7: https://lore.kernel.org/linux-fsdevel/20261122193539.3334213-1-jarkko@kernel.org/
v6: https://lore.kernel.org/linux-fsdevel/20261122011809.2667684-1-jarkko@kernel.org/
v5: https://lore.kernel.org/linux-fsdevel/20261121000844.1863324-1-jarkko@kernel.org/
v4: https://lore.kernel.org/linux-fsdevel/20261119224312.1037966-1-jarkko@kernel.org/
v3: https://lore.kernel.org/linux-fsdevel/20261118193539.240065-1-jarkko@kernel.org/
v2: https://lore.kernel.org/linux-fsdevel/20261117231352.3816603-1-jarkko@kernel.org/
v1: https://lore.kernel.org/linux-fsdevel/20261117050841.3289652-1-jarkko@kernel.org/

Cc: bpf@vger.kernel.org
Cc: containers@lists.linux.dev
Cc: linux-api@vger.kernel.org
Cc: linux-arch@vger.kernel.org
Cc: linux-doc@vger.kernel.org
Cc: linux-fsdevel@vger.kernel.org
Cc: linux-integrity@vger.kernel.org
Cc: linux-kernel@vger.kernel.org
Cc: linux-kselftest@vger.kernel.org
Cc: linux-mm@kvack.org
Cc: linux-security-module@vger.kernel.org
Cc: Aleksa Sarai <aleksa@amutable.com>
Cc: Alexander Mikhalitsyn <alex@amutable.com>
Cc: Alexander Viro <viro@zeniv.linux.org.uk>
Cc: Alexei Starovoitov <ast@kernel.org>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Andrii Nakryiko <andrii@kernel.org>
Cc: Andy Lutomirski <luto@amacapital.net>
Cc: Arnd Bergmann <arnd@arndb.de>
Cc: Baolin Wang <baolin.wang@linux.alibaba.com>
Cc: Ben Segall <bsegall@google.com>
Cc: Christian Brauner <brauner@kernel.org>
Cc: Daniel Borkmann <daniel@iogearbox.net>
Cc: David Hildenbrand <david@kernel.org>
Cc: David Howells <dhowells@redhat.com>
Cc: David Woodhouse <dwmw2@infradead.org>
Cc: Davidlohr Bueso <dave@stgolabs.net>
Cc: Dietmar Eggemann <dietmar.eggemann@arm.com>
Cc: Eduard Zingerman <eddyz87@gmail.com>
Cc: Emil Tsalapatis <emil@etsalapatis.com>
Cc: Eric Biggers <ebiggers@kernel.org>
Cc: Georgia Garcia <georgia.garcia@canonical.com>
Cc: Giuseppe Scrivano <giuseppe@scrivano.org>
Cc: "Günther Noack" <gnoack@google.com>
Cc: Hugh Dickins <hughd@google.com>
Cc: Ihor Solodrai <ihor.solodrai@linux.dev>
Cc: Ingo Molnar <mingo@redhat.com>
Cc: James Morris <jmorris@namei.org>
Cc: Jan Kara <jack@suse.cz>
Cc: Jason Gunthorpe <jgg@nvidia.com>
Cc: Jarkko Sakkinen <jarkko@kernel.org>
Cc: Jeff Layton <jlayton@kernel.org>
Cc: Jiri Olsa <jolsa@kernel.org>
Cc: John Johansen <john.johansen@canonical.com>
Cc: Jonathan Corbet <corbet@lwn.net>
Cc: Josef Bacik <josef@toxicpanda.com>
Cc: Juri Lelli <juri.lelli@redhat.com>
Cc: Kees Cook <kees@kernel.org>
Cc: K Prateek Nayak <kprateek.nayak@amd.com>
Cc: KP Singh <kpsingh@kernel.org>
Cc: Kumar Kartikeya Dwivedi <memxor@gmail.com>
Cc: Lennart Poettering <lennart@poettering.net>
Cc: "Liam R. Howlett" <liam@infradead.org>
Cc: Manfred Spraul <manfred@colorfullife.com>
Cc: Martin KaFai Lau <martin.lau@linux.dev>
Cc: Matt Bobrowski <matt@bobrowski.net>
Cc: Mel Gorman <mgorman@suse.de>
Cc: Michal Hocko <mhocko@suse.com>
Cc: "Mickaël Salaün" <mic@digikod.net>
Cc: Mickaël Salaün <mic@digikod.net>
Cc: Mike Rapoport <rppt@kernel.org>
Cc: Neal Gompa <neal@gompa.dev>
Cc: Oleg Nesterov <oleg@redhat.com>
Cc: Paul Moore <paul@paul-moore.com>
Cc: Pavel Tikhomirov <ptikhomirov@virtuozzo.com>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Randy Dunlap <rdunlap@infradead.org>
Cc: "Serge E. Hallyn" <serge@hallyn.com>
Cc: Serge Hallyn <sergeh@kernel.org>
Cc: Shuah Khan <skhan@linuxfoundation.org>
Cc: Song Liu <song@kernel.org>
Cc: Stephen Smalley <stephen.smalley.work@gmail.com>
Cc: Steven Rostedt <rostedt@goodmis.org>
Cc: Valentin Schneider <vschneid@redhat.com>
Cc: Vincent Guittot <vincent.guittot@linaro.org>
Cc: Yonghong Song <yonghong.song@linux.dev>
Cc: Zygmunt Krynicki <zygmunt.krynicki@canonical.com>

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


^ permalink raw reply	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 01/29] userns: Factor out idmap validation and commit helpers
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 02/29] userns: Add userns_set_idmap() system call Jarkko Sakkinen
                   ` (28 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

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.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 kernel/user_namespace.c | 229 +++++++++++++++++++++-------------------
 1 file changed, 122 insertions(+), 107 deletions(-)

diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index cd748e1cbace..caba2ac33077 100644
--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -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))
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 02/29] userns: Add userns_set_idmap() system call
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 01/29] userns: Factor out idmap validation and commit helpers Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 03/29] arch: Wire up " Jarkko Sakkinen
                   ` (27 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

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

Add userns_set_idmap() to atomically configure setgroups policy and UID,
GID, and project ID extents directly on a CLONE_NEWUSER nsfs file
descriptor. Expose USERNS_SETGROUPS_ALLOWED in uapi/linux/nsfs.h as the
flags bitmask when installing a GID mapping so setgroups(2) is disabled
by default unless explicitly preserved. Require CAP_SYS_ADMIN over the
target user namespace in either the caller's or the file opener's
credentials, and check parent ID-range capabilities strictly against the
caller's credentials.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 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(-)

diff --git a/include/linux/syscalls.h b/include/linux/syscalls.h
index 552d9710a0d5..72308cc11908 100644
--- a/include/linux/syscalls.h
+++ b/include/linux/syscalls.h
@@ -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);
diff --git a/include/linux/user_namespace.h b/include/linux/user_namespace.h
index 91232053775d..b4a50edfe003 100644
--- a/include/linux/user_namespace.h
+++ b/include/linux/user_namespace.h
@@ -35,8 +35,6 @@ struct uid_gid_map { /* 64 bytes -- 1 cache line */
 	};
 };
 
-#define USERNS_SETGROUPS_ALLOWED 1UL
-
 #define USERNS_INIT_FLAGS USERNS_SETGROUPS_ALLOWED
 
 struct ucounts;
diff --git a/include/uapi/linux/nsfs.h b/include/uapi/linux/nsfs.h
index e5909266ec3f..f919b19a2c74 100644
--- a/include/uapi/linux/nsfs.h
+++ b/include/uapi/linux/nsfs.h
@@ -44,6 +44,52 @@ struct mnt_ns_info {
 #define NS_GET_MNTNS_ID		_IOR(NSIO, 5,  __u64)
 #define NS_GET_ID		_IOR(NSIO, 13, __u64)
 
+/**
+ * struct userns_idmap_extent - Single ID mapping range for userns_set_idmap()
+ * @first: First ID inside the target user namespace.
+ * @lower_first: First ID inside the parent user namespace.
+ * @count: Number of consecutive IDs in the range.
+ * @reserved: Reserved for future use; must be zero.
+ */
+struct userns_idmap_extent {
+	__u32 first;
+	__u32 lower_first;
+	__u32 count;
+	__u32 reserved;
+};
+
+/**
+ * enum userns_flags - User namespace flags
+ * @USERNS_SETGROUPS_ALLOWED: Allow setgroups(2) inside the user namespace
+ *                            once its GID mapping is established.
+ */
+enum userns_flags {
+	USERNS_SETGROUPS_ALLOWED	= (1 << 0),
+};
+
+/**
+ * struct userns_idmap - Arguments for userns_set_idmap()
+ * @nr_uid_extents: Number of entries in @uid_extents.
+ * @nr_gid_extents: Number of entries in @gid_extents.
+ * @nr_projid_extents: Number of entries in @projid_extents.
+ * @reserved: Reserved for future use; must be zero.
+ * @uid_extents: User pointer to array of &struct userns_idmap_extent for UIDs.
+ * @gid_extents: User pointer to array of &struct userns_idmap_extent for GIDs.
+ * @projid_extents: User pointer to array of &struct userns_idmap_extent for
+ *                  project IDs.
+ */
+struct userns_idmap {
+	__u32 nr_uid_extents;
+	__u32 nr_gid_extents;
+	__u32 nr_projid_extents;
+	__u32 reserved;
+	__aligned_u64 uid_extents;
+	__aligned_u64 gid_extents;
+	__aligned_u64 projid_extents;
+};
+
+#define USERNS_IDMAP_SIZE_VER0 40 /* sizeof first published struct */
+
 enum init_ns_ino {
 	IPC_NS_INIT_INO		= 0xEFFFFFFFU,
 	UTS_NS_INIT_INO		= 0xEFFFFFFEU,
diff --git a/kernel/sys_ni.c b/kernel/sys_ni.c
index c8be0abaa407..e3202e7cc2a1 100644
--- a/kernel/sys_ni.c
+++ b/kernel/sys_ni.c
@@ -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);
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index caba2ac33077..e5054e273e93 100644
--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -22,7 +22,11 @@
 #include <linux/fs_struct.h>
 #include <linux/bsearch.h>
 #include <linux/sort.h>
+#include <linux/file.h>
 #include <linux/nstree.h>
+#include <linux/proc_fs.h>
+#include <linux/syscalls.h>
+#include <uapi/linux/nsfs.h>
 
 static struct kmem_cache *user_ns_cachep __ro_after_init;
 static DEFINE_MUTEX(userns_state_mutex);
@@ -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))
+				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);
+
+	return ns_capable(ns->parent, cap_setid);
+}
+
+static int prepare_caller_idmap(struct user_namespace *ns, int cap_setid,
+				unsigned long ns_flags,
+				struct uid_gid_map *new_map,
+				struct uid_gid_map *parent_map)
+{
+	if (!caller_idmap_permitted(ns, cap_setid, ns_flags, new_map))
+		return -EPERM;
+
+	return resolve_new_idmap(new_map, parent_map);
+}
+
+static int parse_user_idmap_extents(__u64 uptr, __u32 nr_extents,
+				    struct uid_gid_map *new_map)
+{
+	const struct userns_idmap_extent __user *uext = u64_to_user_ptr(uptr);
+	unsigned int i;
+	int ret;
+
+	if (!nr_extents || nr_extents > UID_GID_MAP_MAX_EXTENTS || !uptr)
+		return -EINVAL;
+
+	for (i = 0; i < nr_extents; i++) {
+		struct userns_idmap_extent kext;
+		struct uid_gid_extent extent;
+
+		if (copy_from_user(&kext, &uext[i], sizeof(kext)))
+			return -EFAULT;
+		if (kext.reserved)
+			return -EINVAL;
+
+		extent.first = kext.first;
+		extent.lower_first = kext.lower_first;
+		extent.count = kext.count;
+
+		ret = validate_and_insert_extent(new_map, &extent);
+		if (ret < 0)
+			return ret;
+	}
+	return 0;
+}
+
+/**
+ * sys_userns_set_idmap - Configure ID mappings on a user namespace fd
+ * @fd: File descriptor referencing a %CLONE_NEWUSER ``nsfs`` namespace
+ * @map: User pointer to &struct userns_idmap configuration
+ * @size: Size of @map structure in bytes (%USERNS_IDMAP_SIZE_VER0 to %PAGE_SIZE)
+ * @flags: Bitmask of &enum userns_flags values (%USERNS_SETGROUPS_ALLOWED)
+ *
+ * Atomically configure UID, GID, and project ID mappings (and, when
+ * @map->nr_gid_extents is non-zero, the %USERNS_SETGROUPS_ALLOWED policy) of
+ * @fd. Requires ``CAP_SYS_ADMIN`` over the target user namespace in the
+ * caller's or @fd opener's credentials, with parent ID ranges authorized
+ * against the caller's credentials.
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+SYSCALL_DEFINE4(userns_set_idmap, int, fd,
+		const struct userns_idmap __user *, map,
+		size_t, size, unsigned int, flags)
+{
+	struct uid_gid_map new_uid = {}, new_gid = {}, new_projid = {};
+	struct userns_idmap req = {};
+	struct ns_common *ns_common;
+	struct user_namespace *ns;
+	unsigned long new_flags;
+	struct file *filp;
+	bool file_ok;
+	int ret;
+
+	BUILD_BUG_ON(sizeof(struct userns_idmap) != USERNS_IDMAP_SIZE_VER0);
+
+	if (flags & ~USERNS_SETGROUPS_ALLOWED)
+		return -EINVAL;
+
+	CLASS(fd, f)(fd);
+	if (fd_empty(f))
+		return -EBADF;
+
+	filp = fd_file(f);
+	if (!proc_ns_file(filp))
+		return -EINVAL;
+
+	ns_common = get_proc_ns(file_inode(filp));
+	if (ns_common->ns_type != CLONE_NEWUSER)
+		return -EINVAL;
+	ns = to_user_ns(ns_common);
+
+	if (!map || size < USERNS_IDMAP_SIZE_VER0)
+		return -EINVAL;
+	if (unlikely(size > PAGE_SIZE))
+		return -E2BIG;
+	ret = copy_struct_from_user(&req, sizeof(req), map, size);
+	if (ret)
+		return ret;
+	if (req.reserved)
+		return -EINVAL;
+	if (!req.nr_uid_extents != !req.uid_extents ||
+	    !req.nr_gid_extents != !req.gid_extents ||
+	    !req.nr_projid_extents != !req.projid_extents)
+		return -EINVAL;
+	if (!req.nr_uid_extents && !req.nr_gid_extents &&
+	    !req.nr_projid_extents)
+		return -EINVAL;
+	if ((flags & USERNS_SETGROUPS_ALLOWED) && !req.nr_gid_extents)
+		return -EINVAL;
+
+	if (!ns->parent)
+		return -EPERM;
+	if (current_user_ns() != ns && current_user_ns() != ns->parent)
+		return -EPERM;
+
+	file_ok = (filp->f_cred->user_ns == ns ||
+		   filp->f_cred->user_ns == ns->parent) &&
+		  file_ns_capable(filp, ns, CAP_SYS_ADMIN);
+	if (!ns_capable(ns, CAP_SYS_ADMIN) && !file_ok)
+		return -EPERM;
+
+	if (req.nr_uid_extents) {
+		ret = parse_user_idmap_extents(req.uid_extents,
+					       req.nr_uid_extents, &new_uid);
+		if (ret < 0)
+			goto out_free;
+	}
+	if (req.nr_gid_extents) {
+		ret = parse_user_idmap_extents(req.gid_extents,
+					       req.nr_gid_extents, &new_gid);
+		if (ret < 0)
+			goto out_free;
+	}
+	if (req.nr_projid_extents) {
+		ret = parse_user_idmap_extents(req.projid_extents,
+					       req.nr_projid_extents,
+					       &new_projid);
+		if (ret < 0)
+			goto out_free;
+	}
+
+	mutex_lock(&userns_state_mutex);
+	new_flags = ns->flags;
+	ret = -EPERM;
+
+	if (req.nr_uid_extents && ns->uid_map.nr_extents != 0)
+		goto out_unlock;
+	if (req.nr_gid_extents && ns->gid_map.nr_extents != 0)
+		goto out_unlock;
+	if (req.nr_projid_extents && ns->projid_map.nr_extents != 0)
+		goto out_unlock;
+
+	if (req.nr_gid_extents) {
+		if ((flags & USERNS_SETGROUPS_ALLOWED) &&
+		    !(new_flags & USERNS_SETGROUPS_ALLOWED))
+			goto out_unlock;
+		if (!(flags & USERNS_SETGROUPS_ALLOWED))
+			new_flags &= ~USERNS_SETGROUPS_ALLOWED;
+	}
+
+	if (req.nr_uid_extents) {
+		ret = prepare_caller_idmap(ns, CAP_SETUID, new_flags, &new_uid,
+					   &ns->parent->uid_map);
+		if (ret < 0)
+			goto out_unlock;
+	}
+	if (req.nr_gid_extents) {
+		ret = prepare_caller_idmap(ns, CAP_SETGID, new_flags, &new_gid,
+					   &ns->parent->gid_map);
+		if (ret < 0)
+			goto out_unlock;
+	}
+	if (req.nr_projid_extents) {
+		ret = prepare_caller_idmap(ns, -1, new_flags, &new_projid,
+					   &ns->parent->projid_map);
+		if (ret < 0)
+			goto out_unlock;
+	}
+
+	if (new_flags != ns->flags)
+		WRITE_ONCE(ns->flags, new_flags);
+	if (req.nr_uid_extents)
+		commit_new_idmap(&ns->uid_map, &new_uid);
+	if (req.nr_gid_extents)
+		commit_new_idmap(&ns->gid_map, &new_gid);
+	if (req.nr_projid_extents)
+		commit_new_idmap(&ns->projid_map, &new_projid);
+
+	mutex_unlock(&userns_state_mutex);
+	return 0;
+
+out_unlock:
+	mutex_unlock(&userns_state_mutex);
+out_free:
+	free_new_idmap(&new_uid);
+	free_new_idmap(&new_gid);
+	free_new_idmap(&new_projid);
+	return ret;
+}
+
 ssize_t proc_uid_map_write(struct file *file, const char __user *buf,
 			   size_t size, loff_t *ppos)
 {
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 03/29] arch: Wire up userns_set_idmap() system call
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 01/29] userns: Factor out idmap validation and commit helpers Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 02/29] userns: Add userns_set_idmap() system call Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 04/29] mount: Add mnt_ns_get_root() Jarkko Sakkinen
                   ` (26 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

Expose userns_set_idmap() (473, 583 on Alpha) across all architecture
system call tables, asm-generic unistd.h, and the mirrored copies under
tools/.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 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(-)

diff --git a/arch/alpha/kernel/syscalls/syscall.tbl b/arch/alpha/kernel/syscalls/syscall.tbl
index 52e3538cc7df..60d330a51476 100644
--- a/arch/alpha/kernel/syscalls/syscall.tbl
+++ b/arch/alpha/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/arm/tools/syscall.tbl b/arch/arm/tools/syscall.tbl
index 55717ed32c27..d055515e98cd 100644
--- a/arch/arm/tools/syscall.tbl
+++ b/arch/arm/tools/syscall.tbl
@@ -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
diff --git a/arch/arm64/tools/syscall_32.tbl b/arch/arm64/tools/syscall_32.tbl
index df2d1d82fb3c..a18982ead3bf 100644
--- a/arch/arm64/tools/syscall_32.tbl
+++ b/arch/arm64/tools/syscall_32.tbl
@@ -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
diff --git a/arch/m68k/kernel/syscalls/syscall.tbl b/arch/m68k/kernel/syscalls/syscall.tbl
index ba7a4d8903d0..e89ec7d54b8c 100644
--- a/arch/m68k/kernel/syscalls/syscall.tbl
+++ b/arch/m68k/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/microblaze/kernel/syscalls/syscall.tbl b/arch/microblaze/kernel/syscalls/syscall.tbl
index 76d7cbe2a133..0dfcd6f9e4e7 100644
--- a/arch/microblaze/kernel/syscalls/syscall.tbl
+++ b/arch/microblaze/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/mips/kernel/syscalls/syscall_n32.tbl b/arch/mips/kernel/syscalls/syscall_n32.tbl
index 9ae88e4eac61..882ff15f3e6d 100644
--- a/arch/mips/kernel/syscalls/syscall_n32.tbl
+++ b/arch/mips/kernel/syscalls/syscall_n32.tbl
@@ -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
diff --git a/arch/mips/kernel/syscalls/syscall_n64.tbl b/arch/mips/kernel/syscalls/syscall_n64.tbl
index 83dc93a0712f..daa95049baef 100644
--- a/arch/mips/kernel/syscalls/syscall_n64.tbl
+++ b/arch/mips/kernel/syscalls/syscall_n64.tbl
@@ -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
diff --git a/arch/mips/kernel/syscalls/syscall_o32.tbl b/arch/mips/kernel/syscalls/syscall_o32.tbl
index 9c62429c9b7b..9e0040399fef 100644
--- a/arch/mips/kernel/syscalls/syscall_o32.tbl
+++ b/arch/mips/kernel/syscalls/syscall_o32.tbl
@@ -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
diff --git a/arch/parisc/kernel/syscalls/syscall.tbl b/arch/parisc/kernel/syscalls/syscall.tbl
index 88adc4016cce..b77482e68d1a 100644
--- a/arch/parisc/kernel/syscalls/syscall.tbl
+++ b/arch/parisc/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/powerpc/kernel/syscalls/syscall.tbl b/arch/powerpc/kernel/syscalls/syscall.tbl
index cfbb70039ff0..973562f20a94 100644
--- a/arch/powerpc/kernel/syscalls/syscall.tbl
+++ b/arch/powerpc/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/s390/kernel/syscalls/syscall.tbl b/arch/s390/kernel/syscalls/syscall.tbl
index 1b45e68a217b..19d7b234b31b 100644
--- a/arch/s390/kernel/syscalls/syscall.tbl
+++ b/arch/s390/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/sh/kernel/syscalls/syscall.tbl b/arch/sh/kernel/syscalls/syscall.tbl
index ace068dff0de..252e6f9aa04c 100644
--- a/arch/sh/kernel/syscalls/syscall.tbl
+++ b/arch/sh/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/sparc/kernel/syscalls/syscall.tbl b/arch/sparc/kernel/syscalls/syscall.tbl
index 5b9fe0e8140f..1263d0e825c1 100644
--- a/arch/sparc/kernel/syscalls/syscall.tbl
+++ b/arch/sparc/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/x86/entry/syscalls/syscall_32.tbl b/arch/x86/entry/syscalls/syscall_32.tbl
index 2c172ef48dfd..0f8c81c584e0 100644
--- a/arch/x86/entry/syscalls/syscall_32.tbl
+++ b/arch/x86/entry/syscalls/syscall_32.tbl
@@ -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
diff --git a/arch/x86/entry/syscalls/syscall_64.tbl b/arch/x86/entry/syscalls/syscall_64.tbl
index d5b6045b0090..5452b7567bf8 100644
--- a/arch/x86/entry/syscalls/syscall_64.tbl
+++ b/arch/x86/entry/syscalls/syscall_64.tbl
@@ -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
diff --git a/arch/xtensa/kernel/syscalls/syscall.tbl b/arch/xtensa/kernel/syscalls/syscall.tbl
index d354bb231796..f10b491c873c 100644
--- a/arch/xtensa/kernel/syscalls/syscall.tbl
+++ b/arch/xtensa/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/include/uapi/asm-generic/unistd.h b/include/uapi/asm-generic/unistd.h
index 5b7e77a7c736..695eac2d356b 100644
--- a/include/uapi/asm-generic/unistd.h
+++ b/include/uapi/asm-generic/unistd.h
@@ -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
diff --git a/scripts/syscall.tbl b/scripts/syscall.tbl
index 0ab531605120..7ba073cc0e80 100644
--- a/scripts/syscall.tbl
+++ b/scripts/syscall.tbl
@@ -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
diff --git a/tools/include/uapi/asm-generic/unistd.h b/tools/include/uapi/asm-generic/unistd.h
index 5b7e77a7c736..695eac2d356b 100644
--- a/tools/include/uapi/asm-generic/unistd.h
+++ b/tools/include/uapi/asm-generic/unistd.h
@@ -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
diff --git a/tools/perf/arch/arm/entry/syscalls/syscall.tbl b/tools/perf/arch/arm/entry/syscalls/syscall.tbl
index 55717ed32c27..d055515e98cd 100644
--- a/tools/perf/arch/arm/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/arm/entry/syscalls/syscall.tbl
@@ -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
diff --git a/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl b/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl
index 83dc93a0712f..daa95049baef 100644
--- a/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl
+++ b/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl
@@ -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
diff --git a/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl b/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl
index cfbb70039ff0..973562f20a94 100644
--- a/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl
@@ -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
diff --git a/tools/perf/arch/s390/entry/syscalls/syscall.tbl b/tools/perf/arch/s390/entry/syscalls/syscall.tbl
index 1b45e68a217b..19d7b234b31b 100644
--- a/tools/perf/arch/s390/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/s390/entry/syscalls/syscall.tbl
@@ -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
diff --git a/tools/perf/arch/sh/entry/syscalls/syscall.tbl b/tools/perf/arch/sh/entry/syscalls/syscall.tbl
index ace068dff0de..252e6f9aa04c 100644
--- a/tools/perf/arch/sh/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/sh/entry/syscalls/syscall.tbl
@@ -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
diff --git a/tools/perf/arch/sparc/entry/syscalls/syscall.tbl b/tools/perf/arch/sparc/entry/syscalls/syscall.tbl
index 5b9fe0e8140f..1263d0e825c1 100644
--- a/tools/perf/arch/sparc/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/sparc/entry/syscalls/syscall.tbl
@@ -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
diff --git a/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl b/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl
index 2c172ef48dfd..0f8c81c584e0 100644
--- a/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl
+++ b/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl
@@ -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
diff --git a/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl b/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl
index d5b6045b0090..5452b7567bf8 100644
--- a/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl
+++ b/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl
@@ -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
diff --git a/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl b/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl
index d354bb231796..f10b491c873c 100644
--- a/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl
@@ -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
diff --git a/tools/scripts/syscall.tbl b/tools/scripts/syscall.tbl
index 0ab531605120..7ba073cc0e80 100644
--- a/tools/scripts/syscall.tbl
+++ b/tools/scripts/syscall.tbl
@@ -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
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 04/29] mount: Add mnt_ns_get_root()
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (2 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 03/29] arch: Wire up " Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 05/29] mount: Enforce mount_too_revealing() for foreign mntns Jarkko Sakkinen
                   ` (25 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

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

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

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 fs/namespace.c                | 16 ++++++++++++++++
 include/linux/mnt_namespace.h |  2 ++
 2 files changed, 18 insertions(+)

diff --git a/fs/namespace.c b/fs/namespace.c
index aecd05ac0170..781380945d78 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -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;
diff --git a/include/linux/mnt_namespace.h b/include/linux/mnt_namespace.h
index 0acd1089d149..98188d1f7428 100644
--- a/include/linux/mnt_namespace.h
+++ b/include/linux/mnt_namespace.h
@@ -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 *);
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 05/29] mount: Enforce mount_too_revealing() for foreign mntns
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (3 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 04/29] mount: Add mnt_ns_get_root() Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 06/29] mount: Support MOVE_MOUNT_T_MNTNS in move_mount() Jarkko Sakkinen
                   ` (24 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

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

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

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 fs/namespace.c | 24 +++++++++++++++++-------
 1 file changed, 17 insertions(+), 7 deletions(-)

diff --git a/fs/namespace.c b/fs/namespace.c
index 781380945d78..1bb9f90a6523 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -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_flags
 	const 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 && current_chrooted())
+		return true;
+
 	s_iflags = sb->s_iflags;
 	if ((s_iflags & required_iflags) != required_iflags) {
 		WARN_ONCE(1, "Expected s_iflags to contain 0x%lx\n",
@@ -6671,7 +6681,7 @@ static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flags
 	if (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)
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 06/29] mount: Support MOVE_MOUNT_T_MNTNS in move_mount()
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (4 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 05/29] mount: Enforce mount_too_revealing() for foreign mntns Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 07/29] security: Pass flags to security_move_mount() Jarkko Sakkinen
                   ` (23 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

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

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

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

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 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(-)

diff --git a/fs/namespace.c b/fs/namespace.c
index 1bb9f90a6523..8eea00d1dbdb 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -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);
 }
 
 /*
diff --git a/fs/pnode.c b/fs/pnode.c
index 5f07fa14099b..acd1930efd68 100644
--- a/fs/pnode.c
+++ b/fs/pnode.c
@@ -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;
diff --git a/fs/pnode.h b/fs/pnode.h
index b029db225f33..8517fb75f7f7 100644
--- a/fs/pnode.h
+++ b/fs/pnode.h
@@ -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 *);
diff --git a/include/uapi/linux/mount.h b/include/uapi/linux/mount.h
index ac865edac517..7d413418426a 100644
--- a/include/uapi/linux/mount.h
+++ b/include/uapi/linux/mount.h
@@ -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.
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 07/29] security: Pass flags to security_move_mount()
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (5 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 06/29] mount: Support MOVE_MOUNT_T_MNTNS in move_mount() Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 08/29] mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS Jarkko Sakkinen
                   ` (22 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

Pass 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.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 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(-)

diff --git a/fs/namespace.c b/fs/namespace.c
index 8eea00d1dbdb..fadc4c3b1fb2 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -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);
 }
 
 /*
diff --git a/include/linux/lsm_hook_defs.h b/include/linux/lsm_hook_defs.h
index 87d9d06710cb..005a350681c3 100644
--- a/include/linux/lsm_hook_defs.h
+++ b/include/linux/lsm_hook_defs.h
@@ -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)
diff --git a/include/linux/security.h b/include/linux/security.h
index 40831fab5470..9c8f8da83251 100644
--- a/include/linux/security.h
+++ b/include/linux/security.h
@@ -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;
 }
diff --git a/security/apparmor/lsm.c b/security/apparmor/lsm.c
index eaebc3c60c5a..aefa71bc1cd2 100644
--- a/security/apparmor/lsm.c
+++ b/security/apparmor/lsm.c
@@ -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;
diff --git a/security/landlock/fs.c b/security/landlock/fs.c
index 2ab67bcad198..32d882a79001 100644
--- a/security/landlock/fs.c
+++ b/security/landlock/fs.c
@@ -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 =
diff --git a/security/security.c b/security/security.c
index 4727b8347fc4..b4d60dcf4880 100644
--- a/security/security.c
+++ b/security/security.c
@@ -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);
 }
 
 /**
diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index 6c4c64d6e904..67079105e9de 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -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();
 
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 08/29] mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (6 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 07/29] security: Pass flags to security_move_mount() Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 09/29] apparmor: Mediate MOVE_MOUNT_CLONE as recursive bind Jarkko Sakkinen
                   ` (21 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

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

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

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 fs/namespace.c             | 93 ++++++++++++++++++++++++++++++--------
 include/uapi/linux/mount.h |  3 +-
 2 files changed, 75 insertions(+), 21 deletions(-)

diff --git a/fs/namespace.c b/fs/namespace.c
index fadc4c3b1fb2..535a22f59e73 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -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))
diff --git a/include/uapi/linux/mount.h b/include/uapi/linux/mount.h
index 7d413418426a..cb4f7175db02 100644
--- a/include/uapi/linux/mount.h
+++ b/include/uapi/linux/mount.h
@@ -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.
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 09/29] apparmor: Mediate MOVE_MOUNT_CLONE as recursive bind
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (7 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 08/29] mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 10/29] userns: Factor out install_user_ns_cred() Jarkko Sakkinen
                   ` (20 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

When 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.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 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(-)

diff --git a/security/apparmor/include/mount.h b/security/apparmor/include/mount.h
index 46834f828179..d771ee240d42 100644
--- a/security/apparmor/include/mount.h
+++ b/security/apparmor/include/mount.h
@@ -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,
diff --git a/security/apparmor/include/path.h b/security/apparmor/include/path.h
index 250812a77e11..22f420d54950 100644
--- a/security/apparmor/include/path.h
+++ b/security/apparmor/include/path.h
@@ -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,
diff --git a/security/apparmor/lsm.c b/security/apparmor/lsm.c
index aefa71bc1cd2..797944de8273 100644
--- a/security/apparmor/lsm.c
+++ b/security/apparmor/lsm.c
@@ -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;
diff --git a/security/apparmor/mount.c b/security/apparmor/mount.c
index 4ed7b9136beb..2dfe26e99fc1 100644
--- a/security/apparmor/mount.c
+++ b/security/apparmor/mount.c
@@ -231,6 +231,7 @@ static int path_flags(const struct aa_profile *profile, const struct path *path)
  * @data: fs mount data (MAYBE NULL)
  * @binary: whether @data is binary
  * @devinfo: error str if (IS_ERR(@devname))
+ * @pflags: extra path lookup flags for @mntpath
  * @ad: apparmor audit data structure
  *
  * Returns: 0 on success else error
@@ -239,7 +240,7 @@ static int match_mnt_path_str(struct aa_profile *profile,
 			      const struct path *mntpath, char *buffer,
 			      const char *devname, const char *type,
 			      unsigned long flags, void *data, bool binary,
-			      const char *devinfo,
+			      const char *devinfo, int pflags,
 			      struct apparmor_audit_data *ad)
 {
 	struct aa_perms perms = { };
@@ -256,8 +257,8 @@ static int match_mnt_path_str(struct aa_profile *profile,
 
 	ad->mnt.type = type;
 
-	error = aa_path_name(mntpath, path_flags(profile, mntpath), buffer,
-			     &mntpnt, &ad->info, profile->disconnected);
+	error = aa_path_name(mntpath, path_flags(profile, mntpath) | pflags,
+			     buffer, &mntpnt, &ad->info, profile->disconnected);
 	if (error)
 		return aa_audit_perm_error(&profile->label, AA_MAY_MOUNT,
 					   error, ad, audit_cb);
@@ -294,6 +295,7 @@ static int match_mnt_path_str(struct aa_profile *profile,
  * @flags: mount flags to match
  * @data: fs mount data (MAYBE NULL)
  * @binary: whether @data is binary
+ * @pflags: extra path lookup flags for @path
  * @ad: apparmor audit data structure
  *
  * Returns: 0 on success else error
@@ -301,7 +303,8 @@ static int match_mnt_path_str(struct aa_profile *profile,
 static int match_mnt(struct aa_profile *profile, const struct path *path,
 		     char *buffer, const struct path *devpath, char *devbuffer,
 		     const char *type, unsigned long flags, void *data,
-		     bool binary, struct apparmor_audit_data *ad)
+		     bool binary, int pflags,
+		     struct apparmor_audit_data *ad)
 {
 	const char *devname = NULL, *info = NULL;
 	struct aa_ruleset *rules = profile->label.rules[0];
@@ -322,7 +325,8 @@ static int match_mnt(struct aa_profile *profile, const struct path *path,
 	}
 
 	return match_mnt_path_str(profile, path, buffer, devname,
-				  type, flags, data, binary, info, ad);
+				  type, flags, data, binary, info,
+				  pflags, ad);
 }
 
 int aa_remount(const struct cred *subj_cred,
@@ -346,7 +350,7 @@ int aa_remount(const struct cred *subj_cred,
 		return -ENOMEM;
 	error = fn_for_each(label, profile,
 			match_mnt(profile, path, buffer, NULL, NULL, NULL,
-				  flags, data, binary, &ad));
+				  flags, data, binary, 0, &ad));
 	aa_put_buffer(buffer);
 
 	return error;
@@ -384,7 +388,8 @@ int aa_bind_mount(const struct cred *subj_cred,
 
 	error = fn_for_each(label, profile,
 			match_mnt(profile, path, buffer, &old_path,
-				  old_buffer, NULL, flags, NULL, false, &ad));
+				  old_buffer, NULL, flags, NULL, false, 0,
+				  &ad));
 out:
 	aa_put_buffer(buffer);
 	aa_put_buffer(old_buffer);
@@ -415,7 +420,7 @@ int aa_mount_change_type(const struct cred *subj_cred,
 		return -ENOMEM;
 	error = fn_for_each(label, profile,
 			match_mnt(profile, path, buffer, NULL, NULL, NULL,
-				  flags, NULL, false, &ad));
+				  flags, NULL, false, 0, &ad));
 	aa_put_buffer(buffer);
 
 	return error;
@@ -423,31 +428,40 @@ int aa_mount_change_type(const struct cred *subj_cred,
 
 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)
 {
 	struct aa_profile *profile;
 	char *to_buffer = NULL, *from_buffer = NULL;
+	unsigned long mnt_flags = (flags & MOVE_MOUNT_CLONE) ?
+				  (MS_BIND | MS_REC) : MS_MOVE;
+	int pflags = 0;
 	int error;
 	DEFINE_AUDIT_MOUNT(ad, OP_MOUNT, subj_cred);
-	ad.mnt.flags = MS_MOVE;
+	ad.mnt.flags = mnt_flags;
 
 	AA_BUG(!label);
 	AA_BUG(!from_path);
 	AA_BUG(!to_path);
 
+	if (!our_mnt(from_path->mnt)) {
+		if (flags & MOVE_MOUNT_CLONE)
+			return -EINVAL;
+		/* moving a mount detached from the namespace */
+		from_path = NULL;
+	}
+
 	to_buffer = aa_get_buffer(false);
 	from_buffer = aa_get_buffer(false);
 	error = -ENOMEM;
 	if (!to_buffer || !from_buffer)
 		goto out;
 
-	if (!our_mnt(from_path->mnt))
-		/* moving a mount detached from the namespace */
-		from_path = NULL;
+	if ((flags & MOVE_MOUNT_T_MNTNS) && !our_mnt(to_path->mnt))
+		pflags = PATH_TARGET_MNTNS;
 	error = fn_for_each(label, profile,
 			match_mnt(profile, to_path, to_buffer, from_path,
-				  from_buffer, NULL, MS_MOVE, NULL, false,
-				  &ad));
+				  from_buffer, NULL, mnt_flags, NULL, false,
+				  pflags, &ad));
 out:
 	aa_put_buffer(to_buffer);
 	aa_put_buffer(from_buffer);
@@ -467,7 +481,7 @@ int aa_move_mount_old(const struct cred *subj_cred, struct aa_label *label,
 	if (error)
 		return error;
 
-	error = aa_move_mount(subj_cred, label, &old_path, path);
+	error = aa_move_mount(subj_cred, label, &old_path, path, 0);
 	path_put(&old_path);
 
 	return error;
@@ -524,12 +538,12 @@ int aa_new_mount(const struct cred *subj_cred, struct aa_label *label,
 		error = fn_for_each(label, profile,
 				match_mnt(profile, path, buffer, dev_path,
 					  dev_buffer, type, flags, data,
-					  binary, &ad));
+					  binary, 0, &ad));
 	} else {
 		error = fn_for_each(label, profile,
 				match_mnt_path_str(profile, path, buffer,
 						   dev_name, type, flags, data,
-						   binary, NULL, &ad));
+						   binary, NULL, 0, &ad));
 	}
 
 out:
diff --git a/security/apparmor/path.c b/security/apparmor/path.c
index 2494e8101538..3443f5a86871 100644
--- a/security/apparmor/path.c
+++ b/security/apparmor/path.c
@@ -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;
diff --git a/security/apparmor/policy_unpack.c b/security/apparmor/policy_unpack.c
index 24fbce2e4322..0965e2f65509 100644
--- a/security/apparmor/policy_unpack.c
+++ b/security/apparmor/policy_unpack.c
@@ -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))
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 10/29] userns: Factor out install_user_ns_cred()
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (8 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 09/29] apparmor: Mediate MOVE_MOUNT_CLONE as recursive bind Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 11/29] nsproxy: Expose create_new_namespaces() Jarkko Sakkinen
                   ` (19 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

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

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

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 include/linux/user_namespace.h |  7 +++++++
 kernel/user_namespace.c        | 12 ++++++++----
 2 files changed, 15 insertions(+), 4 deletions(-)

diff --git a/include/linux/user_namespace.h b/include/linux/user_namespace.h
index b4a50edfe003..ecee91aa2257 100644
--- a/include/linux/user_namespace.h
+++ b/include/linux/user_namespace.h
@@ -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)
 {
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index e5054e273e93..fe60a71f0ba3 100644
--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -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;
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 11/29] nsproxy: Expose create_new_namespaces()
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (9 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 10/29] userns: Factor out install_user_ns_cred() Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 12/29] nsexec: Add core infrastructure Jarkko Sakkinen
                   ` (18 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

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

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

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 include/linux/nsproxy.h | 4 ++++
 kernel/nsproxy.c        | 6 +++---
 2 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/include/linux/nsproxy.h b/include/linux/nsproxy.h
index dc2447f5f092..d611c40cb4ce 100644
--- a/include/linux/nsproxy.h
+++ b/include/linux/nsproxy.h
@@ -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);
diff --git a/kernel/nsproxy.c b/kernel/nsproxy.c
index 2dcf105e8ee2..3c4161515c3c 100644
--- a/kernel/nsproxy.c
+++ b/kernel/nsproxy.c
@@ -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;
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 12/29] nsexec: Add core infrastructure
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (10 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 11/29] nsproxy: Expose create_new_namespaces() Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 13/29] nsexec: Track init lifecycle via copy_process() and pid_namespace Jarkko Sakkinen
                   ` (17 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

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

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 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

diff --git a/include/linux/nsexec.h b/include/linux/nsexec.h
new file mode 100644
index 000000000000..9ebab74cbed4
--- /dev/null
+++ b/include/linux/nsexec.h
@@ -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 */
diff --git a/include/uapi/linux/nsexec.h b/include/uapi/linux/nsexec.h
new file mode 100644
index 000000000000..704eb206de7e
--- /dev/null
+++ b/include/uapi/linux/nsexec.h
@@ -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 */
diff --git a/init/Kconfig b/init/Kconfig
index c8a7cfa60a6e..9011e6ee72a2 100644
--- a/init/Kconfig
+++ b/init/Kconfig
@@ -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
diff --git a/kernel/Makefile b/kernel/Makefile
index 4ff92e24680c..28a8961815b7 100644
--- a/kernel/Makefile
+++ b/kernel/Makefile
@@ -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.
diff --git a/kernel/nsexec.c b/kernel/nsexec.c
new file mode 100644
index 000000000000..299f42cd7292
--- /dev/null
+++ b/kernel/nsexec.c
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.
+ * Copyright (C) 2026 Opinsys Oy
+ */
+
+/**
+ * DOC: Overview
+ *
+ * An nsexec is an anonymous-inode control object opened by ``nsexec_open()``
+ * that binds a detached namespace set, an initially empty mount namespace, an
+ * owning user namespace, and an init process lifecycle.
+ */
+
+#include <linux/poll.h>
+#include <linux/wait.h>
+#include <uapi/linux/wait.h>
+#include <linux/file.h>
+#include <linux/fs.h>
+#include <linux/anon_inodes.h>
+#include <linux/nsexec.h>
+#include <linux/sched/signal.h>
+#include <linux/sched/task.h>
+#include <linux/slab.h>
+#include <linux/syscalls.h>
+#include <linux/uaccess.h>
+#include <linux/mnt_namespace.h>
+#include <linux/nsproxy.h>
+#include <linux/ns_common.h>
+#include <linux/nsfs.h>
+#include <linux/pid.h>
+#include <linux/pid_namespace.h>
+#include <linux/time_namespace.h>
+#include <linux/user_namespace.h>
+#include <linux/idr.h>
+#include <uapi/linux/nsexec.h>
+
+void nsexec_put(struct nsexec *c)
+{
+	if (!c || !refcount_dec_and_test(&c->usage))
+		return;
+
+	if (c->ns)
+		put_nsproxy(c->ns);
+	if (c->init_pid)
+		put_pid(c->init_pid);
+	if (c->user_ns) {
+		ns_ref_active_put(c->user_ns);
+		put_user_ns(c->user_ns);
+	}
+	kfree(c);
+}
+
+static __poll_t nsexec_poll(struct file *file, poll_table *wait)
+{
+	struct nsexec *nsexec = file->private_data;
+	__poll_t mask = 0;
+
+	poll_wait(file, &nsexec->waitq, wait);
+
+	if (READ_ONCE(nsexec->state) == NSEXEC_DEAD)
+		mask |= EPOLLHUP;
+
+	return mask;
+}
+
+static int nsexec_release(struct inode *inode, struct file *file)
+{
+	struct nsexec *nsexec = file->private_data;
+
+	if (nsexec->flags & NSEXEC_AUTOKILL) {
+		struct pid *pid = NULL;
+
+		scoped_guard(spinlock, &nsexec->lock) {
+			if (nsexec->state == NSEXEC_RUNNING)
+				pid = get_pid(nsexec->init_pid);
+		}
+		if (pid) {
+			kill_pid(pid, SIGKILL, true);
+			put_pid(pid);
+		}
+	}
+	nsexec_put(nsexec);
+	return 0;
+}
+
+static const struct file_operations nsexec_fops = {
+	.poll		= nsexec_poll,
+	.release	= nsexec_release,
+};
+
+bool nsexec_is_file(struct file *file)
+{
+	return file->f_op == &nsexec_fops;
+}
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 13/29] nsexec: Track init lifecycle via copy_process() and pid_namespace
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (11 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 12/29] nsexec: Add core infrastructure Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 14/29] nsexec: Add nsexec_open() system call Jarkko Sakkinen
                   ` (16 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

An 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.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 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(+)

diff --git a/include/linux/nsexec.h b/include/linux/nsexec.h
index 9ebab74cbed4..443561072578 100644
--- a/include/linux/nsexec.h
+++ b/include/linux/nsexec.h
@@ -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 */
diff --git a/include/linux/pid_namespace.h b/include/linux/pid_namespace.h
index b20baaa7e62b..c62a5dc68c78 100644
--- a/include/linux/pid_namespace.h
+++ b/include/linux/pid_namespace.h
@@ -15,6 +15,7 @@
 #define MAX_PID_NS_LEVEL 32
 
 struct 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;
diff --git a/kernel/fork.c b/kernel/fork.c
index 77d6c8fc38c6..83c2f87aaf75 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -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);
 
diff --git a/kernel/nsexec.c b/kernel/nsexec.c
index 299f42cd7292..b9fc8fdf9b5c 100644
--- a/kernel/nsexec.c
+++ b/kernel/nsexec.c
@@ -93,3 +93,44 @@ bool nsexec_is_file(struct file *file)
 {
 	return file->f_op == &nsexec_fops;
 }
+
+void nsexec_copy(struct pid *pid, struct nsexec *c)
+{
+	if (likely(!c || !is_child_reaper(pid)))
+		return;
+
+	scoped_guard(spinlock, &c->lock) {
+		if (c->state != NSEXEC_FORKING)
+			return;
+		refcount_inc(&c->usage);
+		ns_of_pid(pid)->nsexec = c;
+		WRITE_ONCE(c->init_pid, get_pid(pid));
+		WRITE_ONCE(c->state, NSEXEC_RUNNING);
+	}
+}
+
+void nsexec_exit(struct pid_namespace *pid_ns, struct task_struct *tsk)
+{
+	struct nsexec *c = pid_ns->nsexec;
+	struct task_struct *leader;
+	kuid_t uid;
+	int status;
+
+	if (!c)
+		return;
+
+	leader = tsk->group_leader;
+	uid = task_uid(leader);
+	status = (tsk->signal->flags & SIGNAL_GROUP_EXIT) ?
+		 tsk->signal->group_exit_code : leader->exit_code;
+
+	scoped_guard(spinlock, &c->lock) {
+		c->exit_code = status;
+		c->init_uid = uid;
+		WRITE_ONCE(c->state, NSEXEC_DEAD);
+	}
+
+	pid_ns->nsexec = NULL;
+	__wake_up(&c->waitq, TASK_NORMAL, 0, poll_to_key(EPOLLHUP));
+	nsexec_put(c);
+}
diff --git a/kernel/pid_namespace.c b/kernel/pid_namespace.c
index 127a5fd23e70..6b71d194e534 100644
--- a/kernel/pid_namespace.c
+++ b/kernel/pid_namespace.c
@@ -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;
 }
 
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 14/29] nsexec: Add nsexec_open() system call
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (12 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 13/29] nsexec: Track init lifecycle via copy_process() and pid_namespace Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  6:18   ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 15/29] nsexec: Add NSEXEC_GET_NSFD ioctl Jarkko Sakkinen
                   ` (15 subsequent siblings)
  29 siblings, 1 reply; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

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

Add the 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.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 include/linux/syscalls.h |   1 +
 kernel/nsexec.c          | 107 +++++++++++++++++++++++++++++++++++++++
 kernel/sys_ni.c          |   3 ++
 3 files changed, 111 insertions(+)

diff --git a/include/linux/syscalls.h b/include/linux/syscalls.h
index 72308cc11908..7dc55fb0857e 100644
--- a/include/linux/syscalls.h
+++ b/include/linux/syscalls.h
@@ -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
diff --git a/kernel/nsexec.c b/kernel/nsexec.c
index b9fc8fdf9b5c..3277822386f6 100644
--- a/kernel/nsexec.c
+++ b/kernel/nsexec.c
@@ -134,3 +134,110 @@ void nsexec_exit(struct pid_namespace *pid_ns, struct task_struct *tsk)
 	__wake_up(&c->waitq, TASK_NORMAL, 0, poll_to_key(EPOLLHUP));
 	nsexec_put(c);
 }
+
+static struct user_namespace *nsexec_create_user_ns(void)
+{
+	struct user_namespace *user_ns;
+	struct cred *new;
+	int ret;
+
+	new = prepare_creds();
+	if (!new)
+		return ERR_PTR(-ENOMEM);
+
+	ret = create_user_ns(new);
+	if (ret < 0) {
+		abort_creds(new);
+		return ERR_PTR(ret);
+	}
+
+	user_ns = get_user_ns(new->user_ns);
+	abort_creds(new);
+	return user_ns;
+}
+
+static struct nsexec *nsexec_create(unsigned int flags)
+{
+	u64 clone_flags = CLONE_NEWNS | CLONE_EMPTY_MNTNS | CLONE_NEWPID |
+			  CLONE_NEWCGROUP | CLONE_NEWUTS | CLONE_NEWIPC |
+			  CLONE_NEWNET |
+			  (IS_ENABLED(CONFIG_TIME_NS) ? CLONE_NEWTIME : 0);
+	struct user_namespace *user_ns;
+	struct nsproxy *ns;
+	struct nsexec *c;
+	int ret;
+
+	c = kzalloc_obj(*c, GFP_KERNEL);
+	if (!c)
+		return ERR_PTR(-ENOMEM);
+
+	init_waitqueue_head(&c->waitq);
+	spin_lock_init(&c->lock);
+	refcount_set(&c->usage, 1);
+	c->flags = flags;
+
+	user_ns = nsexec_create_user_ns();
+	if (IS_ERR(user_ns)) {
+		ret = PTR_ERR(user_ns);
+		goto err_put;
+	}
+	c->user_ns = user_ns;
+	ns_ref_active_get(user_ns);
+
+	if (!ns_capable(user_ns, CAP_SYS_ADMIN)) {
+		ret = -EPERM;
+		goto err_put;
+	}
+
+	ns = create_new_namespaces(clone_flags, current, user_ns, NULL);
+	if (IS_ERR(ns)) {
+		ret = PTR_ERR(ns);
+		goto err_put;
+	}
+
+	if (ns->time_ns != ns->time_ns_for_children) {
+		get_time_ns(ns->time_ns_for_children);
+		put_time_ns(ns->time_ns);
+		ns->time_ns = ns->time_ns_for_children;
+	}
+	c->ns = ns;
+	nsproxy_ns_active_get(ns);
+
+	return c;
+
+err_put:
+	nsexec_put(c);
+	return ERR_PTR(ret);
+}
+
+/**
+ * sys_nsexec_open - Open a new nsexec
+ * @flags: Combination of &enum nsexec_flags values
+ *
+ * Allocate an nsexec owning a fresh child user namespace (with the caller's
+ * effective UID and GID as owner and initially empty ID mappings) and dedicated
+ * empty mount, PID, UTS, IPC, network, cgroup, and time namespaces. Control
+ * operations authorize against capabilities in the nsexec's owning user
+ * namespace.
+ *
+ * Return: Close-on-exec nsexec file descriptor on success, negative error code
+ *         on failure.
+ */
+SYSCALL_DEFINE1(nsexec_open, unsigned int, flags)
+{
+	struct nsexec *c;
+	int fd;
+
+	if (flags & ~NSEXEC_ALL_FLAGS)
+		return -EINVAL;
+
+	c = nsexec_create(flags);
+	if (IS_ERR(c))
+		return PTR_ERR(c);
+
+	fd = anon_inode_getfd("nsexec", &nsexec_fops, c, O_RDWR | O_CLOEXEC);
+	if (fd < 0)
+		nsexec_put(c);
+
+	return fd;
+}
diff --git a/kernel/sys_ni.c b/kernel/sys_ni.c
index e3202e7cc2a1..760724d57a0d 100644
--- a/kernel/sys_ni.c
+++ b/kernel/sys_ni.c
@@ -399,3 +399,6 @@ COND_SYSCALL(rseq_slice_yield);
 
 COND_SYSCALL(uretprobe);
 COND_SYSCALL(uprobe);
+
+/* kernel/nsexec.c */
+COND_SYSCALL(nsexec_open);
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 15/29] nsexec: Add NSEXEC_GET_NSFD ioctl
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (13 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 14/29] nsexec: Add nsexec_open() system call Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 16/29] nsexec: Add NSEXEC_SHARE_NSFD ioctl Jarkko Sakkinen
                   ` (14 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

Standalone namespace operations such as userns_set_idmap() and
move_mount(..., MOVE_MOUNT_T_MNTNS) operate on nsfs file descriptors,
requiring a way to obtain member namespace fds from 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.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 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(-)

diff --git a/fs/internal.h b/fs/internal.h
index 3f2fbac40f8e..ee3f796241ac 100644
--- a/fs/internal.h
+++ b/fs/internal.h
@@ -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);
 
 /*
diff --git a/include/linux/nsfs.h b/include/linux/nsfs.h
index 731b67fc2fec..40912c1eb5ff 100644
--- a/include/linux/nsfs.h
+++ b/include/linux/nsfs.h
@@ -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),						\
diff --git a/include/uapi/linux/nsexec.h b/include/uapi/linux/nsexec.h
index 704eb206de7e..af8e287c229d 100644
--- a/include/uapi/linux/nsexec.h
+++ b/include/uapi/linux/nsexec.h
@@ -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 */
diff --git a/kernel/nsexec.c b/kernel/nsexec.c
index 3277822386f6..383fcc7112d4 100644
--- a/kernel/nsexec.c
+++ b/kernel/nsexec.c
@@ -24,6 +24,8 @@
 #include <linux/slab.h>
 #include <linux/syscalls.h>
 #include <linux/uaccess.h>
+#include <linux/cgroup_namespace.h>
+#include <linux/ipc_namespace.h>
 #include <linux/mnt_namespace.h>
 #include <linux/nsproxy.h>
 #include <linux/ns_common.h>
@@ -32,6 +34,8 @@
 #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>
 #include <linux/idr.h>
 #include <uapi/linux/nsexec.h>
 
@@ -64,6 +68,76 @@ static __poll_t nsexec_poll(struct file *file, poll_table *wait)
 	return mask;
 }
 
+static long nsexec_get_nsfd(struct nsexec *nsexec, unsigned long nstype)
+{
+	struct ns_common *ns = NULL;
+
+	if (nstype > UINT_MAX)
+		return -EINVAL;
+	if (!ns_capable(nsexec->user_ns, CAP_SYS_ADMIN))
+		return -EPERM;
+
+	if (nstype == CLONE_NEWPID) {
+		if (!pidns_is_ancestor(nsexec->ns->pid_ns_for_children,
+				       task_active_pid_ns(current)))
+			return -EXDEV;
+		if (READ_ONCE(nsexec->state) != NSEXEC_RUNNING)
+			return -ESRCH;
+	}
+
+	scoped_guard(spinlock, &nsexec->lock) {
+		switch (nstype) {
+		case CLONE_NEWNS:
+			ns = from_mnt_ns(nsexec->ns->mnt_ns);
+			break;
+		case CLONE_NEWCGROUP:
+			ns = to_ns_common(nsexec->ns->cgroup_ns);
+			break;
+		case CLONE_NEWUTS:
+			ns = to_ns_common(nsexec->ns->uts_ns);
+			break;
+		case CLONE_NEWIPC:
+			ns = to_ns_common(nsexec->ns->ipc_ns);
+			break;
+		case CLONE_NEWUSER:
+			ns = to_ns_common(nsexec->user_ns);
+			break;
+		case CLONE_NEWPID:
+			ns = to_ns_common(nsexec->ns->pid_ns_for_children);
+			break;
+		case CLONE_NEWNET:
+			ns = to_ns_common(nsexec->ns->net_ns);
+			break;
+		case CLONE_NEWTIME:
+#ifdef CONFIG_TIME_NS
+			ns = to_ns_common(nsexec->ns->time_ns);
+			break;
+#else
+			return -EOPNOTSUPP;
+#endif
+		default:
+			return -EINVAL;
+		}
+
+		if (!__ns_ref_get(ns))
+			return -ESRCH;
+	}
+
+	return open_namespace(ns);
+}
+
+static long nsexec_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
+{
+	struct nsexec *nsexec = file->private_data;
+
+	switch (cmd) {
+	case NSEXEC_GET_NSFD:
+		return nsexec_get_nsfd(nsexec, arg);
+	default:
+		return -ENOIOCTLCMD;
+	}
+}
+
 static int nsexec_release(struct inode *inode, struct file *file)
 {
 	struct nsexec *nsexec = file->private_data;
@@ -86,6 +160,8 @@ static int nsexec_release(struct inode *inode, struct file *file)
 
 static const struct file_operations nsexec_fops = {
 	.poll		= nsexec_poll,
+	.unlocked_ioctl	= nsexec_ioctl,
+	.compat_ioctl	= nsexec_ioctl,
 	.release	= nsexec_release,
 };
 
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 16/29] nsexec: Add NSEXEC_SHARE_NSFD ioctl
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (14 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 15/29] nsexec: Add NSEXEC_GET_NSFD ioctl Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 17/29] exit: Support P_NSEXEC in waitid() Jarkko Sakkinen
                   ` (13 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

nsexec_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.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 include/uapi/linux/nsexec.h | 14 ++++++
 kernel/nsexec.c             | 90 +++++++++++++++++++++++++++++++++++++
 2 files changed, 104 insertions(+)

diff --git a/include/uapi/linux/nsexec.h b/include/uapi/linux/nsexec.h
index af8e287c229d..7b2d1280d329 100644
--- a/include/uapi/linux/nsexec.h
+++ b/include/uapi/linux/nsexec.h
@@ -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 */
diff --git a/kernel/nsexec.c b/kernel/nsexec.c
index 383fcc7112d4..8c3726b05d55 100644
--- a/kernel/nsexec.c
+++ b/kernel/nsexec.c
@@ -32,6 +32,8 @@
 #include <linux/nsfs.h>
 #include <linux/pid.h>
 #include <linux/pid_namespace.h>
+#include <linux/proc_fs.h>
+#include <linux/proc_ns.h>
 #include <linux/time_namespace.h>
 #include <linux/user_namespace.h>
 #include <linux/uts_namespace.h>
@@ -126,6 +128,92 @@ static long nsexec_get_nsfd(struct nsexec *nsexec, unsigned long nstype)
 	return open_namespace(ns);
 }
 
+static long nsexec_share_nsfd(struct nsexec *c, unsigned long arg)
+{
+	struct ns_common *old_time_children = NULL;
+	struct ns_common *old_ns = NULL;
+	struct ns_common *ns;
+
+	if (arg > INT_MAX)
+		return -EBADF;
+
+	CLASS(fd, f)((int)arg);
+	if (fd_empty(f))
+		return -EBADF;
+	if (!proc_ns_file(fd_file(f)))
+		return -EINVAL;
+
+	ns = get_proc_ns(file_inode(fd_file(f)));
+	switch (ns->ns_type) {
+	case CLONE_NEWCGROUP:
+	case CLONE_NEWIPC:
+	case CLONE_NEWUTS:
+	case CLONE_NEWNET:
+		break;
+	case CLONE_NEWTIME:
+		if (!IS_ENABLED(CONFIG_TIME_NS))
+			return -EOPNOTSUPP;
+		break;
+	default:
+		return -EINVAL;
+	}
+
+	if (!ns_capable(c->user_ns, CAP_SYS_ADMIN))
+		return -EPERM;
+	if (!is_current_namespace(ns) &&
+	    !ns_capable(ns->ops->owner(ns), CAP_SYS_ADMIN))
+		return -EPERM;
+
+	scoped_guard(spinlock, &c->lock) {
+		if (c->state != NSEXEC_INIT)
+			return -EBUSY;
+
+		__ns_ref_inc(ns);
+		__ns_ref_active_get(ns);
+
+		switch (ns->ns_type) {
+		case CLONE_NEWCGROUP:
+			old_ns = to_ns_common(c->ns->cgroup_ns);
+			c->ns->cgroup_ns = to_cg_ns(ns);
+			break;
+		case CLONE_NEWIPC:
+			old_ns = to_ns_common(c->ns->ipc_ns);
+			c->ns->ipc_ns = to_ipc_ns(ns);
+			break;
+		case CLONE_NEWUTS:
+			old_ns = to_ns_common(c->ns->uts_ns);
+			c->ns->uts_ns = to_uts_ns(ns);
+			break;
+		case CLONE_NEWNET:
+			old_ns = to_ns_common(c->ns->net_ns);
+			c->ns->net_ns = to_net_ns(ns);
+			break;
+#ifdef CONFIG_TIME_NS
+		case CLONE_NEWTIME:
+			__ns_ref_inc(ns);
+			__ns_ref_active_get(ns);
+			old_ns = to_ns_common(c->ns->time_ns);
+			old_time_children =
+				to_ns_common(c->ns->time_ns_for_children);
+			c->ns->time_ns = to_time_ns(ns);
+			c->ns->time_ns_for_children = to_time_ns(ns);
+			break;
+#endif
+		default:
+			WARN_ON_ONCE(1);
+			break;
+		}
+	}
+
+	__ns_ref_active_put(old_ns);
+	old_ns->ops->put(old_ns);
+	if (old_time_children) {
+		__ns_ref_active_put(old_time_children);
+		old_time_children->ops->put(old_time_children);
+	}
+	return 0;
+}
+
 static long nsexec_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 {
 	struct nsexec *nsexec = file->private_data;
@@ -133,6 +221,8 @@ static long nsexec_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 	switch (cmd) {
 	case NSEXEC_GET_NSFD:
 		return nsexec_get_nsfd(nsexec, arg);
+	case NSEXEC_SHARE_NSFD:
+		return nsexec_share_nsfd(nsexec, arg);
 	default:
 		return -ENOIOCTLCMD;
 	}
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 17/29] exit: Support P_NSEXEC in waitid()
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (15 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 16/29] nsexec: Add NSEXEC_SHARE_NSFD ioctl Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 18/29] signal: Support nsexec fds in pidfd_send_signal() Jarkko Sakkinen
                   ` (12 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

wait4() 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.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 include/linux/nsexec.h    | 10 +++++
 include/uapi/linux/wait.h |  1 +
 kernel/exit.c             |  4 ++
 kernel/nsexec.c           | 83 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 98 insertions(+)

diff --git a/include/linux/nsexec.h b/include/linux/nsexec.h
index 443561072578..e6d772482d1f 100644
--- a/include/linux/nsexec.h
+++ b/include/linux/nsexec.h
@@ -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 */
diff --git a/include/uapi/linux/wait.h b/include/uapi/linux/wait.h
index 85b809fc9f11..0841fb44ed10 100644
--- a/include/uapi/linux/wait.h
+++ b/include/uapi/linux/wait.h
@@ -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 */
diff --git a/kernel/exit.c b/kernel/exit.c
index d5e7bc2af804..798aad3d59c2 100644
--- a/kernel/exit.c
+++ b/kernel/exit.c
@@ -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;
diff --git a/kernel/nsexec.c b/kernel/nsexec.c
index 8c3726b05d55..1df16f70b456 100644
--- a/kernel/nsexec.c
+++ b/kernel/nsexec.c
@@ -16,6 +16,7 @@
 #include <linux/wait.h>
 #include <uapi/linux/wait.h>
 #include <linux/file.h>
+#include <linux/freezer.h>
 #include <linux/fs.h>
 #include <linux/anon_inodes.h>
 #include <linux/nsexec.h>
@@ -41,6 +42,8 @@
 #include <linux/idr.h>
 #include <uapi/linux/nsexec.h>
 
+#include "exit.h"
+
 void nsexec_put(struct nsexec *c)
 {
 	if (!c || !refcount_dec_and_test(&c->usage))
@@ -214,6 +217,86 @@ static long nsexec_share_nsfd(struct nsexec *c, unsigned long arg)
 	return 0;
 }
 
+/**
+ * DOC: P_NSEXEC
+ *
+ * ``waitid(P_NSEXEC, nsexec_fd, infop, options, NULL)`` waits freezably until
+ * ``nsexec_fd`` reaches ``NSEXEC_DEAD`` (unless ``WNOHANG`` or ``O_NONBLOCK`` is
+ * set) and writes init's exit information into ``infop`` without consuming it.
+ * ``options`` must include ``WEXITED`` and may include ``WNOHANG`` and
+ * ``WNOWAIT``; ``rusage`` must be ``NULL``, and the caller must run in an
+ * ancestor active PID namespace.
+ */
+long nsexec_waitid(int upid, struct waitid_info *infop, int options,
+		    struct rusage *ru)
+{
+	struct pid_namespace *pid_ns;
+	unsigned int f_flags;
+	struct nsexec *nsexec;
+	bool nonblock;
+	int status;
+	kuid_t uid;
+	long ret;
+
+	if (upid < 0 || ru)
+		return -EINVAL;
+	if (options & ~(WEXITED | WNOHANG | WNOWAIT))
+		return -EINVAL;
+	if (!(options & WEXITED))
+		return -EINVAL;
+
+	CLASS(fd, f)(upid);
+	if (fd_empty(f) || !nsexec_is_file(fd_file(f)))
+		return -EBADF;
+
+	f_flags = READ_ONCE(fd_file(f)->f_flags);
+	nonblock = (options & WNOHANG) || (f_flags & O_NONBLOCK);
+	nsexec = fd_file(f)->private_data;
+	pid_ns = task_active_pid_ns(current);
+
+	if (!pidns_is_ancestor(nsexec->ns->pid_ns_for_children, pid_ns))
+		return -ECHILD;
+	for (;;) {
+		enum nsexec_state state;
+
+		scoped_guard(spinlock, &nsexec->lock) {
+			state = nsexec->state;
+			if (state == NSEXEC_INIT)
+				return -ECHILD;
+			if (state == NSEXEC_DEAD) {
+				ret = pid_nr_ns(nsexec->init_pid, pid_ns);
+				if (ret <= 0)
+					return -ECHILD;
+				status = nsexec->exit_code;
+				uid = nsexec->init_uid;
+			}
+		}
+		if (state == NSEXEC_DEAD)
+			break;
+		if (nonblock)
+			return (options & WNOHANG) ? 0 : -EAGAIN;
+
+		ret = wait_event_freezable(nsexec->waitq,
+					   READ_ONCE(nsexec->state) ==
+					   NSEXEC_DEAD ||
+					   READ_ONCE(nsexec->state) ==
+					   NSEXEC_INIT);
+		if (ret)
+			return ret;
+	}
+
+	if ((status & 0x7f) == 0) {
+		infop->cause = CLD_EXITED;
+		infop->status = status >> 8;
+	} else {
+		infop->cause = (status & 0x80) ? CLD_DUMPED : CLD_KILLED;
+		infop->status = status & 0x7f;
+	}
+	infop->pid = ret;
+	infop->uid = from_kuid_munged(current_user_ns(), uid);
+	return ret;
+}
+
 static long nsexec_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 {
 	struct nsexec *nsexec = file->private_data;
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 18/29] signal: Support nsexec fds in pidfd_send_signal()
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (16 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 17/29] exit: Support P_NSEXEC in waitid() Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 19/29] fork: Support CLONE_INTO_NSEXEC in clone3() Jarkko Sakkinen
                   ` (11 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

Signaling 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.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 include/linux/nsexec.h | 10 +++++++
 kernel/nsexec.c        | 59 ++++++++++++++++++++++++++++++++++++++++++
 kernel/signal.c        |  4 +++
 3 files changed, 73 insertions(+)

diff --git a/include/linux/nsexec.h b/include/linux/nsexec.h
index e6d772482d1f..6eee61c30f3c 100644
--- a/include/linux/nsexec.h
+++ b/include/linux/nsexec.h
@@ -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 */
diff --git a/kernel/nsexec.c b/kernel/nsexec.c
index 1df16f70b456..895cc8c3429d 100644
--- a/kernel/nsexec.c
+++ b/kernel/nsexec.c
@@ -297,6 +297,65 @@ long nsexec_waitid(int upid, struct waitid_info *infop, int options,
 	return ret;
 }
 
+/**
+ * DOC: pidfd_send_signal
+ *
+ * ``pidfd_send_signal(nsexec_fd, sig, NULL, 0)`` delivers ``sig`` (or ``0`` for
+ * a permission and existence probe) once to each member thread group in a
+ * running nsexec. ``info`` must be ``NULL``, ``flags`` must be ``0``, and the
+ * caller must run in an ancestor active PID namespace.
+ */
+int nsexec_send_signal(struct file *file, int sig,
+			struct siginfo __user *info, unsigned int flags)
+{
+	struct nsexec *nsexec = file->private_data;
+	struct pid_namespace *pid_ns = nsexec->ns->pid_ns_for_children;
+	bool any_success = false;
+	bool any_other = false;
+	bool any_perm = false;
+	int other_err = 0;
+	struct pid *pid;
+	int nr;
+
+	if (info || flags || sig < 0 || !valid_signal(sig))
+		return -EINVAL;
+	if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
+		return -EXDEV;
+	if (READ_ONCE(nsexec->state) != NSEXEC_RUNNING)
+		return -ESRCH;
+
+	scoped_guard(rcu) {
+		read_lock(&tasklist_lock);
+		idr_for_each_entry(&pid_ns->idr, pid, nr) {
+			struct task_struct *task = pid_task(pid, PIDTYPE_TGID);
+			int err;
+
+			if (!task)
+				continue;
+
+			err = group_send_sig_info(sig, SEND_SIG_NOINFO, task,
+						  PIDTYPE_MAX);
+			if (!err) {
+				any_success = true;
+			} else if (err == -EPERM) {
+				any_perm = true;
+			} else if (err != -ESRCH && !any_other) {
+				any_other = true;
+				other_err = err;
+			}
+		}
+		read_unlock(&tasklist_lock);
+	}
+
+	if (any_success)
+		return 0;
+	if (any_other)
+		return other_err;
+	if (any_perm)
+		return -EPERM;
+	return -ESRCH;
+}
+
 static long nsexec_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 {
 	struct nsexec *nsexec = file->private_data;
diff --git a/kernel/signal.c b/kernel/signal.c
index dd770e68faee..217e99c6ac63 100644
--- a/kernel/signal.c
+++ b/kernel/signal.c
@@ -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))
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 19/29] fork: Support CLONE_INTO_NSEXEC in clone3()
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (17 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 18/29] signal: Support nsexec fds in pidfd_send_signal() Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 20/29] fs: Support FSCONFIG_SET_NSEXEC in fsconfig() Jarkko Sakkinen
                   ` (10 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

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

Add CLONE_INTO_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.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 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(-)

diff --git a/include/linux/cred.h b/include/linux/cred.h
index 49c26af37349..f7e2f6f25a94 100644
--- a/include/linux/cred.h
+++ b/include/linux/cred.h
@@ -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);
diff --git a/include/linux/nsexec.h b/include/linux/nsexec.h
index 6eee61c30f3c..5e1d40e51205 100644
--- a/include/linux/nsexec.h
+++ b/include/linux/nsexec.h
@@ -16,6 +16,7 @@
 #define NSEXEC_ALL_FLAGS	NSEXEC_AUTOKILL
 
 struct 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 */
diff --git a/include/linux/nsproxy.h b/include/linux/nsproxy.h
index d611c40cb4ce..46c83d2d5deb 100644
--- a/include/linux/nsproxy.h
+++ b/include/linux/nsproxy.h
@@ -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);
diff --git a/include/linux/sched/task.h b/include/linux/sched/task.h
index 90ed5bc3c7af..2053ceb91fa6 100644
--- a/include/linux/sched/task.h
+++ b/include/linux/sched/task.h
@@ -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;
 };
 
diff --git a/include/uapi/linux/sched.h b/include/uapi/linux/sched.h
index 19ffeba89428..2703c53fbdc0 100644
--- a/include/uapi/linux/sched.h
+++ b/include/uapi/linux/sched.h
@@ -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
diff --git a/kernel/cred.c b/kernel/cred.c
index d01df40a9a38..09128a4846df 100644
--- a/kernel/cred.c
+++ b/kernel/cred.c
@@ -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)
diff --git a/kernel/fork.c b/kernel/fork.c
index 83c2f87aaf75..01e55d094ff6 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -65,6 +65,7 @@
 #include <linux/rcupdate.h>
 #include <linux/ptrace.h>
 #include <linux/mount.h>
+#include <linux/mnt_namespace.h>
 #include <linux/audit.h>
 #include <linux/memcontrol.h>
 #include <linux/ftrace.h>
@@ -1616,7 +1617,7 @@ static int copy_exec_state(u64 clone_flags, struct task_struct *tsk)
 	struct task_exec_state *exec_state;
 
 	/* CLONE_VM siblings refcount-share the parent's exec_state. */
-	if (clone_flags & CLONE_VM) {
+	if ((clone_flags & (CLONE_VM | CLONE_INTO_NSEXEC)) == CLONE_VM) {
 		exec_state = rcu_dereference_protected(current->exec_state, true);
 		refcount_inc(&exec_state->count);
 		rcu_assign_pointer(tsk->exec_state, exec_state);
@@ -1633,7 +1634,7 @@ enum copy_fs_flags_t {
 };
 
 static int copy_fs(u64 clone_flags, struct task_struct *tsk,
-		   enum copy_fs_flags_t flags)
+		   enum copy_fs_flags_t flags, struct nsexec *nsexec)
 {
 	struct fs_struct *fs;
 
@@ -1649,7 +1650,7 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk,
 		if (current->nsproxy->mnt_ns != &init_mnt_ns)
 			return -EINVAL;
 		fs = userspace_init_fs;
-	} else if (flags & COPY_FS_IDLE) {
+	} else if (flags & COPY_FS_IDLE || nsexec) {
 		fs = &init_fs;
 	} else {
 		fs = current->fs;
@@ -1671,6 +1672,21 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk,
 	tsk->real_fs = tsk->fs = copy_fs_struct(fs);
 	if (!tsk->fs)
 		return -ENOMEM;
+	if (nsexec) {
+		struct path root __free(path_put) = {};
+		int err;
+
+		err = mnt_ns_get_root(nsexec->ns->mnt_ns, &root);
+		if (err) {
+			free_fs_struct(tsk->fs);
+			tsk->real_fs = NULL;
+			tsk->fs = NULL;
+			return err;
+		}
+		tsk->fs->umask = READ_ONCE(current->fs->umask);
+		set_fs_root(tsk->fs, &root);
+		set_fs_pwd(tsk->fs, &root);
+	}
 	return 0;
 }
 
@@ -2019,6 +2035,17 @@ static bool need_futex_hash_allocate_default(u64 clone_flags)
 	return clone_flags & CLONE_VM;
 }
 
+static bool pid_ns_is_adding(const struct pid *pid)
+{
+	int i;
+
+	for (i = pid->level; i >= 0; i--) {
+		if (unlikely(!(pid->numbers[i].ns->pid_allocated & PIDNS_ADDING)))
+			return false;
+	}
+	return true;
+}
+
 /*
  * This creates a new process as a copy of the old one,
  * but does not actually start it yet.
@@ -2186,7 +2213,7 @@ __latent_entropy struct task_struct *copy_process(
 #ifdef CONFIG_PROVE_LOCKING
 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
 #endif
-	retval = copy_creds(p, clone_flags);
+	retval = copy_creds(p, clone_flags, args->nsexec);
 	if (retval < 0)
 		goto bad_fork_free;
 
@@ -2317,7 +2344,7 @@ __latent_entropy struct task_struct *copy_process(
 		goto bad_fork_cleanup_semundo;
 	retval = copy_fs(clone_flags, p,
 			 (args->umh ? COPY_FS_UMH : 0) |
-			 (args->idle ? COPY_FS_IDLE : 0));
+			 (args->idle ? COPY_FS_IDLE : 0), args->nsexec);
 	if (retval)
 		goto bad_fork_cleanup_semundo;
 	retval = copy_sighand(clone_flags, p);
@@ -2329,7 +2356,7 @@ __latent_entropy struct task_struct *copy_process(
 	retval = copy_mm(clone_flags, p);
 	if (retval)
 		goto bad_fork_cleanup_signal;
-	retval = copy_namespaces(clone_flags, p);
+	retval = copy_namespaces(clone_flags, p, args->nsexec);
 	if (retval)
 		goto bad_fork_cleanup_mm;
 	retval = copy_io(clone_flags, p);
@@ -2505,11 +2532,16 @@ __latent_entropy struct task_struct *copy_process(
 	 * child missed SIGKILL.  If current is not in the same namespace,
 	 * we can't rely on fatal_signal_pending() below.
 	 */
-	if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
+	if (unlikely(!pid_ns_is_adding(pid))) {
 		retval = -ENOMEM;
 		goto bad_fork_core_free;
 	}
 
+	if (unlikely(args->nsexec_bootstrapping && !is_child_reaper(pid))) {
+		retval = -EBUSY;
+		goto bad_fork_core_free;
+	}
+
 	/* Let kill terminate clone/fork in the middle */
 	if (fatal_signal_pending(current)) {
 		retval = -EINTR;
@@ -2586,7 +2618,7 @@ __latent_entropy struct task_struct *copy_process(
 	write_unlock_irq(&tasklist_lock);
 
 	if (likely(p->pid) && thread_group_leader(p))
-		nsexec_copy(pid, NULL);
+		nsexec_copy(pid, args->nsexec);
 
 	if (pidfile)
 		fd_install(pidfd, pidfile);
@@ -2792,6 +2824,13 @@ pid_t kernel_clone(struct kernel_clone_args *args)
 	if (!valid_signal(args->exit_signal))
 		return -EINVAL;
 
+	if (unlikely(clone_flags & CLONE_INTO_NSEXEC)) {
+		int err = nsexec_prepare_fork(args);
+
+		if (err)
+			return err;
+	}
+
 	/*
 	 * Determine whether and which event to report to ptracer.  When
 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
@@ -2813,6 +2852,13 @@ pid_t kernel_clone(struct kernel_clone_args *args)
 	p = copy_process(NULL, trace, NUMA_NO_NODE, args);
 	add_latent_entropy();
 
+	if (unlikely(clone_flags & CLONE_INTO_NSEXEC)) {
+		int err = nsexec_finish_fork(args, p);
+
+		if (err)
+			return err;
+	}
+
 	if (IS_ERR(p))
 		return PTR_ERR(p);
 
@@ -2970,7 +3016,9 @@ static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs,
 		     CLONE_ARGS_SIZE_VER1);
 	BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
 		     CLONE_ARGS_SIZE_VER2);
-	BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
+	BUILD_BUG_ON(offsetofend(struct clone_args, nsexec) !=
+		     CLONE_ARGS_SIZE_VER3);
+	BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER3);
 
 	if (unlikely(usize > PAGE_SIZE))
 		return -E2BIG;
@@ -3000,6 +3048,10 @@ static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs,
 	    (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
 		return -EINVAL;
 
+	if ((args.flags & CLONE_INTO_NSEXEC) &&
+	    (args.nsexec > INT_MAX || usize < CLONE_ARGS_SIZE_VER3))
+		return -EINVAL;
+
 	*kargs = (struct kernel_clone_args){
 		.flags		= args.flags,
 		.pidfd		= u64_to_user_ptr(args.pidfd),
@@ -3011,6 +3063,7 @@ static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs,
 		.tls		= args.tls,
 		.set_tid_size	= args.set_tid_size,
 		.cgroup		= args.cgroup,
+		.nsexec_fd	= args.nsexec,
 	};
 
 	if (args.set_tid &&
@@ -3051,13 +3104,19 @@ static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
 	return true;
 }
 
+#define CLONE_INTO_NSEXEC_FLAGS \
+	(CLONE_INTO_NSEXEC | CLONE_VFORK | CLONE_PIDFD | \
+	 CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP | CLONE_AUTOREAP | \
+	 CLONE_NNP | CLONE_PIDFD_AUTOKILL)
+
 static bool clone3_args_valid(struct kernel_clone_args *kargs)
 {
 	/* Verify that no unknown flags are passed along. */
 	if (kargs->flags &
 	    ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND |
 	      CLONE_INTO_CGROUP | CLONE_AUTOREAP | CLONE_NNP |
-	      CLONE_PIDFD_AUTOKILL | CLONE_EMPTY_MNTNS))
+	      CLONE_PIDFD_AUTOKILL | CLONE_EMPTY_MNTNS |
+	      CLONE_INTO_NSEXEC))
 		return false;
 
 	/*
@@ -3075,6 +3134,10 @@ static bool clone3_args_valid(struct kernel_clone_args *kargs)
 	    kargs->exit_signal)
 		return false;
 
+	if ((kargs->flags & CLONE_INTO_NSEXEC) &&
+	    (kargs->flags & ~CLONE_INTO_NSEXEC_FLAGS))
+		return false;
+
 	if (!clone3_stack_valid(kargs))
 		return false;
 
diff --git a/kernel/nsexec.c b/kernel/nsexec.c
index 895cc8c3429d..761f994977c1 100644
--- a/kernel/nsexec.c
+++ b/kernel/nsexec.c
@@ -18,6 +18,7 @@
 #include <linux/file.h>
 #include <linux/freezer.h>
 #include <linux/fs.h>
+#include <linux/fs_struct.h>
 #include <linux/anon_inodes.h>
 #include <linux/nsexec.h>
 #include <linux/sched/signal.h>
@@ -131,6 +132,12 @@ static long nsexec_get_nsfd(struct nsexec *nsexec, unsigned long nstype)
 	return open_namespace(ns);
 }
 
+static bool nsexec_may_use_ns(struct ns_common *ns)
+{
+	return is_current_namespace(ns) ||
+	       ns_capable(ns->ops->owner(ns), CAP_SYS_ADMIN);
+}
+
 static long nsexec_share_nsfd(struct nsexec *c, unsigned long arg)
 {
 	struct ns_common *old_time_children = NULL;
@@ -163,8 +170,7 @@ static long nsexec_share_nsfd(struct nsexec *c, unsigned long arg)
 
 	if (!ns_capable(c->user_ns, CAP_SYS_ADMIN))
 		return -EPERM;
-	if (!is_current_namespace(ns) &&
-	    !ns_capable(ns->ops->owner(ns), CAP_SYS_ADMIN))
+	if (!nsexec_may_use_ns(ns))
 		return -EPERM;
 
 	scoped_guard(spinlock, &c->lock) {
@@ -549,3 +555,181 @@ SYSCALL_DEFINE1(nsexec_open, unsigned int, flags)
 
 	return fd;
 }
+
+/**
+ * DOC: CLONE_INTO_NSEXEC
+ *
+ * Passing ``CLONE_INTO_NSEXEC`` in ``struct clone_args.flags`` (with
+ * ``size >= CLONE_ARGS_SIZE_VER3``) spawns the child into the nsexec identified
+ * by ``struct clone_args.nsexec`` once ``"/"`` is mounted in its mount
+ * namespace. The first caller bootstraps PID 1 while concurrent bootstrap
+ * callers wait killably; subsequent callers join the running PID namespace
+ * until teardown begins.
+ *
+ * Requires ``CAP_SYS_ADMIN`` and ``CAP_SYS_CHROOT`` in the target user
+ * namespace (plus ``CAP_SYS_CHROOT`` in the caller's user namespace when
+ * chrooted), membership or ``CAP_SYS_ADMIN`` in the owning user namespace of
+ * any shared namespaces, and an ancestor active PID namespace. May be combined
+ * with ``CLONE_VFORK``, ``CLONE_PIDFD``, ``CLONE_PIDFD_AUTOKILL``,
+ * ``CLONE_AUTOREAP``, ``CLONE_CLEAR_SIGHAND``, ``CLONE_INTO_CGROUP``, and
+ * ``CLONE_NNP``.
+ *
+ * When ``current`` is outside the nsexec's user namespace, the child's
+ * credentials are copied from ``current`` and installed into the nsexec's
+ * user namespace with capabilities recomputed as in ``setns(CLONE_NEWUSER)``,
+ * retaining ``current``'s kernel UID, GID, and supplementary groups as mapped
+ * there.
+ *
+ * ``CLONE_VM``, ``CLONE_FILES``, ``CLONE_FS``, and ``CLONE_SIGHAND`` are
+ * rejected so the child never shares mutable task state with the caller.
+ * Whenever the caller's ``exec_state`` originates outside the nsexec's user
+ * namespace, the child keeps ``exec_state->user_ns`` in that outer user
+ * namespace and resets dumpability to ``suid_dumpable``; until ``execve()``,
+ * ``ptrace_may_access()`` checks ``CAP_SYS_PTRACE`` against the outer user
+ * namespace, preventing processes already running inside the nsexec from
+ * tracing the child or accessing ``/proc/<pid>/{exe,mem,fd}``.
+ */
+static bool nsexec_pidns_alive(struct pid_namespace *pid_ns)
+{
+	for (; pid_ns != &init_pid_ns; pid_ns = pid_ns->parent) {
+		if (!(READ_ONCE(pid_ns->pid_allocated) & PIDNS_ADDING))
+			return false;
+	}
+	return true;
+}
+
+static int nsexec_check_namespaces(struct nsexec *nsexec)
+{
+	struct nsproxy *ns = nsexec->ns;
+
+	if (!nsexec_may_use_ns(to_ns_common(ns->cgroup_ns)) ||
+	    !nsexec_may_use_ns(to_ns_common(ns->ipc_ns)) ||
+	    !nsexec_may_use_ns(to_ns_common(ns->uts_ns)) ||
+	    !nsexec_may_use_ns(to_ns_common(ns->net_ns)))
+		return -EPERM;
+#ifdef CONFIG_TIME_NS
+	if (!nsexec_may_use_ns(to_ns_common(ns->time_ns)))
+		return -EPERM;
+#endif
+	return 0;
+}
+
+int nsexec_prepare_fork(struct kernel_clone_args *args)
+{
+	struct file *file __free(fput) = fget(args->nsexec_fd);
+	struct path root __free(path_put) = {};
+	struct pid_namespace *pid_ns;
+	bool bootstrapping = false;
+	struct nsexec *nsexec;
+	int ret;
+
+	if (!file)
+		return -EBADF;
+	if (!nsexec_is_file(file))
+		return -EINVAL;
+
+	nsexec = file->private_data;
+	if (!ns_capable(nsexec->user_ns, CAP_SYS_ADMIN) ||
+	    !ns_capable(nsexec->user_ns, CAP_SYS_CHROOT))
+		return -EPERM;
+	if (current_chrooted() && !ns_capable(current_user_ns(), CAP_SYS_CHROOT))
+		return -EPERM;
+
+	pid_ns = nsexec->ns->pid_ns_for_children;
+	if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
+		return -EXDEV;
+
+	ret = mnt_ns_get_root(nsexec->ns->mnt_ns, &root);
+	if (ret)
+		return ret;
+
+	for (;;) {
+		bool wait = false;
+
+		scoped_guard(spinlock, &nsexec->lock) {
+			switch (nsexec->state) {
+			case NSEXEC_INIT:
+				if (!nsexec_pidns_alive(pid_ns))
+					return -ESRCH;
+				if (READ_ONCE(pid_ns->child_reaper))
+					return -EBUSY;
+				WRITE_ONCE(nsexec->state, NSEXEC_FORKING);
+				bootstrapping = true;
+				break;
+			case NSEXEC_FORKING:
+				wait = true;
+				break;
+			case NSEXEC_RUNNING:
+				if (!nsexec_pidns_alive(pid_ns))
+					return -ESRCH;
+				break;
+			case NSEXEC_DEAD:
+				return -ESRCH;
+			}
+		}
+		if (!wait)
+			break;
+
+		ret = wait_event_killable(nsexec->waitq,
+					  READ_ONCE(nsexec->state) !=
+					  NSEXEC_FORKING);
+		if (ret)
+			return ret;
+	}
+
+	ret = nsexec_check_namespaces(nsexec);
+	if (ret)
+		goto err_forking;
+
+	args->nsexec_file = no_free_ptr(file);
+	args->nsexec = nsexec;
+	args->nsexec_bootstrapping = bootstrapping;
+	return 0;
+
+err_forking:
+	if (bootstrapping) {
+		scoped_guard(spinlock, &nsexec->lock) {
+			if (nsexec->state == NSEXEC_FORKING)
+				WRITE_ONCE(nsexec->state, NSEXEC_INIT);
+		}
+		wake_up_all(&nsexec->waitq);
+	}
+	return ret;
+}
+
+int nsexec_finish_fork(struct kernel_clone_args *args,
+			struct task_struct *p)
+{
+	struct file *file __free(fput) = args->nsexec_file;
+	struct nsexec *nsexec = args->nsexec;
+	struct pid_namespace *pid_ns = nsexec->ns->pid_ns_for_children;
+	int ret;
+
+	args->nsexec_file = NULL;
+	args->nsexec = NULL;
+	if (!IS_ERR(p)) {
+		if (args->nsexec_bootstrapping)
+			wake_up_all(&nsexec->waitq);
+		if (current->nsproxy->time_ns != nsexec->ns->time_ns)
+			timens_commit(p, nsexec->ns->time_ns);
+		return 0;
+	}
+
+	ret = PTR_ERR(p);
+	if (args->nsexec_bootstrapping) {
+		scoped_guard(spinlock, &nsexec->lock) {
+			if (nsexec->state == NSEXEC_FORKING)
+				WRITE_ONCE(nsexec->state, NSEXEC_INIT);
+		}
+		wake_up_all(&nsexec->waitq);
+		if (ret == -EINVAL && !args->set_tid_size &&
+		    (READ_ONCE(pid_ns->child_reaper) ||
+		     (READ_ONCE(pid_ns->pid_allocated) & ~PIDNS_ADDING)))
+			ret = -EBUSY;
+	}
+	if ((ret == -ENOMEM || ret == -EBUSY) &&
+	    !nsexec_pidns_alive(pid_ns))
+		return -ESRCH;
+
+	return ret;
+}
diff --git a/kernel/nsproxy.c b/kernel/nsproxy.c
index 3c4161515c3c..83471e420b2a 100644
--- a/kernel/nsproxy.c
+++ b/kernel/nsproxy.c
@@ -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)) {
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 20/29] fs: Support FSCONFIG_SET_NSEXEC in fsconfig()
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (18 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 19/29] fork: Support CLONE_INTO_NSEXEC in clone3() Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 21/29] proc: Implement ->set_nsexec() fs_context operation Jarkko Sakkinen
                   ` (9 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

fsopen() and fsmount() gate on CAP_SYS_ADMIN in the caller's current
mount namespace and initialize filesystem contexts from current's user
and network namespaces, preventing an unprivileged external manager from
creating superblocks and detached mounts for an unentered 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.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 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(-)

diff --git a/Documentation/filesystems/mount_api.rst b/Documentation/filesystems/mount_api.rst
index e8b94357b4df..a4e9cfd13955 100644
--- a/Documentation/filesystems/mount_api.rst
+++ b/Documentation/filesystems/mount_api.rst
@@ -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);
diff --git a/fs/devpts/inode.c b/fs/devpts/inode.c
index bd1e8eb26edb..aa3c454ee2bf 100644
--- a/fs/devpts/inode.c
+++ b/fs/devpts/inode.c
@@ -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,
 };
 
 /*
diff --git a/fs/filesystems.c b/fs/filesystems.c
index 3083d904df9b..9429844bf6bf 100644
--- a/fs/filesystems.c
+++ b/fs/filesystems.c
@@ -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;
diff --git a/fs/fs_context.c b/fs/fs_context.c
index a50584df97be..cd004750b99c 100644
--- a/fs/fs_context.c
+++ b/fs/fs_context.c
@@ -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;
 
diff --git a/fs/fsopen.c b/fs/fsopen.c
index 70024870fefa..04c3f16079ae 100644
--- a/fs/fsopen.c
+++ b/fs/fsopen.c
@@ -13,9 +13,14 @@
 #include <linux/security.h>
 #include <linux/anon_inodes.h>
 #include <linux/namei.h>
+#include <linux/capability.h>
+#include <linux/nsexec.h>
+#include <linux/nsproxy.h>
+#include <linux/user_namespace.h>
 #include <linux/file.h>
 #include <uapi/linux/mount.h>
 #include <linux/audit.h>
+#include <net/net_namespace.h>
 #include "internal.h"
 #include "mount.h"
 
@@ -41,6 +46,84 @@ static inline const char *fetch_message_locked(struct fc_log *log, size_t len,
 	return p;
 }
 
+/**
+ * DOC: FSCONFIG_SET_NSEXEC
+ *
+ * ``fsconfig(fsfd, FSCONFIG_SET_NSEXEC, NULL, NULL, nsexec_fd)`` binds a newly
+ * opened ``FS_NSEXEC_MOUNT`` or ``FS_USERNS_DELEGATABLE`` filesystem context
+ * to ``nsexec_fd`` once before parameters are supplied. Requires
+ * ``CAP_SYS_ADMIN`` in the nsexec's user namespace and binds the context to the
+ * nsexec's user, network, PID (``proc``), and IPC (``mqueue``) namespaces.
+ */
+static int fsconfig_set_nsexec(struct fs_context *fc, struct fs_parameter *param)
+{
+	struct user_namespace *user_ns;
+	struct net *net;
+	struct nsexec *c;
+	int ret;
+
+	if (!nsexec_is_file(param->file))
+		return -EINVAL;
+
+	c = param->file->private_data;
+	user_ns = c->user_ns;
+	if (!ns_capable(user_ns, CAP_SYS_ADMIN))
+		return -EPERM;
+	if (!(fc->fs_type->fs_flags &
+	      (FS_NSEXEC_MOUNT | FS_USERNS_DELEGATABLE)))
+		return -EOPNOTSUPP;
+
+	if (fc->need_free && fc->ops && fc->ops->free)
+		fc->ops->free(fc);
+	fc->need_free = false;
+	fc->fs_private = NULL;
+	fc->s_fs_info = NULL;
+	fc->ops = NULL;
+	fc->sb_flags = 0;
+	fc->global = false;
+	security_free_mnt_opts(&fc->security);
+
+	scoped_guard(spinlock, &c->lock)
+		net = get_net(c->ns->net_ns);
+	put_cred(fc->cred);
+	fc->cred = get_current_cred();
+	put_net(fc->net_ns);
+	fc->net_ns = net;
+	put_user_ns(fc->user_ns);
+	fc->user_ns = get_user_ns(user_ns);
+
+	fc->nsexec_bound = true;
+	fc->nsexec_mnt_id = c->ns->mnt_ns->ns.ns_id;
+
+	ret = fc->fs_type->init_fs_context(fc);
+	if (ret < 0) {
+		fc->nsexec_bound = false;
+		fc->phase = FS_CONTEXT_FAILED;
+		return ret;
+	}
+	fc->need_free = true;
+
+	if (fc->ops->set_nsexec) {
+		ret = fc->ops->set_nsexec(fc, c);
+		if (ret < 0) {
+			fc->nsexec_bound = false;
+			fc->phase = FS_CONTEXT_FAILED;
+			return ret;
+		}
+		if (!ns_capable(fc->user_ns, CAP_SYS_ADMIN)) {
+			fc->nsexec_bound = false;
+			fc->phase = FS_CONTEXT_FAILED;
+			return -EPERM;
+		}
+	} else if (fc->user_ns != user_ns) {
+		fc->nsexec_bound = false;
+		fc->phase = FS_CONTEXT_FAILED;
+		return -EOPNOTSUPP;
+	}
+	fc->phase = FS_CONTEXT_CREATE_PARAMS;
+	return 0;
+}
+
 /*
  * Allow the user to read back any error, warning or informational messages.
  * Only one message is returned for each read(2) call.
@@ -123,9 +206,11 @@ SYSCALL_DEFINE2(fsopen, const char __user *, _fs_name, unsigned int, flags)
 	struct file_system_type *fs_type;
 	struct fs_context *fc;
 	const char *fs_name;
+	bool priv;
 	int ret;
 
-	if (!may_mount())
+	priv = may_mount();
+	if (!priv && !IS_ENABLED(CONFIG_NSEXEC))
 		return -EPERM;
 
 	if (flags & ~FSOPEN_CLOEXEC)
@@ -137,17 +222,23 @@ SYSCALL_DEFINE2(fsopen, const char __user *, _fs_name, unsigned int, flags)
 
 	audit_log_fsopen(fs_name);
 
-	fs_type = get_fs_type(fs_name);
+	fs_type = priv ? get_fs_type(fs_name) : get_fs_type_noload(fs_name);
 	kfree(fs_name);
 	if (!fs_type)
-		return -ENODEV;
+		return priv ? -ENODEV : -EPERM;
 
-	fc = fs_context_for_mount(fs_type, 0);
+	if (!priv && !(fs_type->fs_flags & FS_NSEXEC_MOUNT)) {
+		put_filesystem(fs_type);
+		return -EPERM;
+	}
+
+	fc = priv ? fs_context_for_mount(fs_type, 0) :
+		    fs_context_for_unpriv_mount(fs_type);
 	put_filesystem(fs_type);
 	if (IS_ERR(fc))
 		return PTR_ERR(fc);
 
-	fc->phase = FS_CONTEXT_CREATE_PARAMS;
+	fc->phase = priv ? FS_CONTEXT_CREATE_NS : FS_CONTEXT_AWAITING_NS;
 
 	ret = fscontext_alloc_log(fc);
 	if (ret < 0)
@@ -222,7 +313,8 @@ static int vfs_cmd_create(struct fs_context *fc, bool exclusive)
 	struct super_block *sb;
 	int ret;
 
-	if (fc->phase != FS_CONTEXT_CREATE_PARAMS)
+	if (fc->phase != FS_CONTEXT_CREATE_NS &&
+	    fc->phase != FS_CONTEXT_CREATE_PARAMS)
 		return -EBUSY;
 
 	if (!mount_capable(fc))
@@ -291,6 +383,8 @@ static int vfs_fsconfig_locked(struct fs_context *fc, int cmd,
 	ret = finish_clean_context(fc);
 	if (ret)
 		return ret;
+	if (fc->phase == FS_CONTEXT_AWAITING_NS && cmd != FSCONFIG_SET_NSEXEC)
+		return -EPERM;
 	switch (cmd) {
 	case FSCONFIG_CMD_CREATE:
 		return vfs_cmd_create(fc, false);
@@ -298,9 +392,17 @@ static int vfs_fsconfig_locked(struct fs_context *fc, int cmd,
 		return vfs_cmd_create(fc, true);
 	case FSCONFIG_CMD_RECONFIGURE:
 		return vfs_cmd_reconfigure(fc);
+	case FSCONFIG_SET_NSEXEC:
+		if (fc->phase != FS_CONTEXT_AWAITING_NS &&
+		    fc->phase != FS_CONTEXT_CREATE_NS)
+			return -EBUSY;
+		return fsconfig_set_nsexec(fc, param);
+
 	default:
-		if (fc->phase != FS_CONTEXT_CREATE_PARAMS &&
-		    fc->phase != FS_CONTEXT_RECONF_PARAMS)
+		if (fc->phase == FS_CONTEXT_CREATE_NS)
+			fc->phase = FS_CONTEXT_CREATE_PARAMS;
+		else if (fc->phase != FS_CONTEXT_CREATE_PARAMS &&
+			 fc->phase != FS_CONTEXT_RECONF_PARAMS)
 			return -EBUSY;
 
 		return vfs_parse_fs_param(fc, param);
@@ -390,6 +492,12 @@ SYSCALL_DEFINE5(fsconfig,
 		if (!_key || _value || aux < 0)
 			return -EINVAL;
 		break;
+	case FSCONFIG_SET_NSEXEC:
+		if (!IS_ENABLED(CONFIG_NSEXEC))
+			return -EOPNOTSUPP;
+		if (_key || _value || aux < 0)
+			return -EINVAL;
+		break;
 	case FSCONFIG_CMD_CREATE:
 	case FSCONFIG_CMD_CREATE_EXCL:
 	case FSCONFIG_CMD_RECONFIGURE:
@@ -457,6 +565,12 @@ SYSCALL_DEFINE5(fsconfig,
 			goto out_key;
 		param.dirfd = aux;
 		break;
+	case FSCONFIG_SET_NSEXEC:
+		ret = -EBADF;
+		param.file = fget(aux);
+		if (!param.file)
+			goto out_key;
+		break;
 	default:
 		break;
 	}
@@ -482,6 +596,7 @@ SYSCALL_DEFINE5(fsconfig,
 			putname(param.name);
 		break;
 	case FSCONFIG_SET_FD:
+	case FSCONFIG_SET_NSEXEC:
 		if (param.file)
 			fput(param.file);
 		break;
diff --git a/fs/internal.h b/fs/internal.h
index ee3f796241ac..c7b57263ac83 100644
--- a/fs/internal.h
+++ b/fs/internal.h
@@ -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
diff --git a/fs/namespace.c b/fs/namespace.c
index 535a22f59e73..020585171e41 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -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;
diff --git a/fs/ramfs/inode.c b/fs/ramfs/inode.c
index ef91b933d4e6..f46df1d5b852 100644
--- a/fs/ramfs/inode.c
+++ b/fs/ramfs/inode.c
@@ -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)
diff --git a/include/linux/fs.h b/include/linux/fs.h
index 5b3a100aba77..7069cc13a848 100644
--- a/include/linux/fs.h
+++ b/include/linux/fs.h
@@ -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;
diff --git a/include/linux/fs_context.h b/include/linux/fs_context.h
index d1727dffecc5..69be2527da41 100644
--- a/include/linux/fs_context.h
+++ b/include/linux/fs_context.h
@@ -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);
 };
diff --git a/include/uapi/linux/mount.h b/include/uapi/linux/mount.h
index cb4f7175db02..9308b382477b 100644
--- a/include/uapi/linux/mount.h
+++ b/include/uapi/linux/mount.h
@@ -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 */
 };
 
 /*
diff --git a/mm/shmem.c b/mm/shmem.c
index a5713109c843..06ac4434a8d8 100644
--- a/mm/shmem.c
+++ b/mm/shmem.c
@@ -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)
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 21/29] proc: Implement ->set_nsexec() fs_context operation
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (19 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 20/29] fs: Support FSCONFIG_SET_NSEXEC in fsconfig() Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 22/29] ipc/mqueue: " Jarkko Sakkinen
                   ` (8 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

proc_init_fs_context() binds ctx->pid_ns to task_active_pid_ns(current)
and resets fc->user_ns to ctx->pid_ns->user_ns, overriding the user
namespace delegated by FSCONFIG_SET_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.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 fs/proc/root.c | 61 +++++++++++++++++++++++++++++++++++++-------------
 1 file changed, 46 insertions(+), 15 deletions(-)

diff --git a/fs/proc/root.c b/fs/proc/root.c
index 7fbbe92bf73a..8ec022fbede4 100644
--- a/fs/proc/root.c
+++ b/fs/proc/root.c
@@ -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)
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 22/29] ipc/mqueue: Implement ->set_nsexec() fs_context operation
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (20 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 21/29] proc: Implement ->set_nsexec() fs_context operation Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 23/29] security: Add nsexec LSM hooks Jarkko Sakkinen
                   ` (7 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

mqueue_init_fs_context() captures current->nsproxy->ipc_ns and resets
fc->user_ns to ctx->ipc_ns->user_ns, overriding the user namespace
delegated by FSCONFIG_SET_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.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 ipc/mqueue.c | 28 ++++++++++++++++++++++++----
 1 file changed, 24 insertions(+), 4 deletions(-)

diff --git a/ipc/mqueue.c b/ipc/mqueue.c
index 322c3dd98c44..026462d9b40f 100644
--- a/ipc/mqueue.c
+++ b/ipc/mqueue.c
@@ -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)
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 23/29] security: Add nsexec LSM hooks
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (21 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 22/29] ipc/mqueue: " Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 24/29] landlock: Enforce namespace use restrictions on nsexec Jarkko Sakkinen
                   ` (6 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

Security 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().

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 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(-)

diff --git a/include/linux/lsm_hook_defs.h b/include/linux/lsm_hook_defs.h
index 005a350681c3..de263f05798f 100644
--- a/include/linux/lsm_hook_defs.h
+++ b/include/linux/lsm_hook_defs.h
@@ -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 */
diff --git a/include/linux/lsm_hooks.h b/include/linux/lsm_hooks.h
index 13621e9e233e..b32d540504fc 100644
--- a/include/linux/lsm_hooks.h
+++ b/include/linux/lsm_hooks.h
@@ -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
 };
 
 /*
diff --git a/include/linux/nsexec.h b/include/linux/nsexec.h
index 5e1d40e51205..750199922a7d 100644
--- a/include/linux/nsexec.h
+++ b/include/linux/nsexec.h
@@ -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;
diff --git a/include/linux/security.h b/include/linux/security.h
index 9c8f8da83251..2c613978e584 100644
--- a/include/linux/security.h
+++ b/include/linux/security.h
@@ -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 */
diff --git a/kernel/nsexec.c b/kernel/nsexec.c
index 761f994977c1..4ba295e86ccd 100644
--- a/kernel/nsexec.c
+++ b/kernel/nsexec.c
@@ -41,15 +41,13 @@
 #include <linux/uts_namespace.h>
 #include <net/net_namespace.h>
 #include <linux/idr.h>
+#include <linux/security.h>
 #include <uapi/linux/nsexec.h>
 
 #include "exit.h"
 
-void nsexec_put(struct nsexec *c)
+static void nsexec_free(struct nsexec *c)
 {
-	if (!c || !refcount_dec_and_test(&c->usage))
-		return;
-
 	if (c->ns)
 		put_nsproxy(c->ns);
 	if (c->init_pid)
@@ -61,6 +59,15 @@ void nsexec_put(struct nsexec *c)
 	kfree(c);
 }
 
+void nsexec_put(struct nsexec *c)
+{
+	if (!c || !refcount_dec_and_test(&c->usage))
+		return;
+
+	security_nsexec_free(c);
+	nsexec_free(c);
+}
+
 static __poll_t nsexec_poll(struct file *file, poll_table *wait)
 {
 	struct nsexec *nsexec = file->private_data;
@@ -143,6 +150,7 @@ static long nsexec_share_nsfd(struct nsexec *c, unsigned long arg)
 	struct ns_common *old_time_children = NULL;
 	struct ns_common *old_ns = NULL;
 	struct ns_common *ns;
+	int ret;
 
 	if (arg > INT_MAX)
 		return -EBADF;
@@ -173,6 +181,10 @@ static long nsexec_share_nsfd(struct nsexec *c, unsigned long arg)
 	if (!nsexec_may_use_ns(ns))
 		return -EPERM;
 
+	ret = security_nsexec_share(c, ns);
+	if (ret)
+		return ret;
+
 	scoped_guard(spinlock, &c->lock) {
 		if (c->state != NSEXEC_INIT)
 			return -EBUSY;
@@ -321,6 +333,7 @@ int nsexec_send_signal(struct file *file, int sig,
 	bool any_perm = false;
 	int other_err = 0;
 	struct pid *pid;
+	int ret;
 	int nr;
 
 	if (info || flags || sig < 0 || !valid_signal(sig))
@@ -330,6 +343,10 @@ int nsexec_send_signal(struct file *file, int sig,
 	if (READ_ONCE(nsexec->state) != NSEXEC_RUNNING)
 		return -ESRCH;
 
+	ret = security_nsexec_kill(nsexec, sig);
+	if (ret)
+		return ret;
+
 	scoped_guard(rcu) {
 		read_lock(&tasklist_lock);
 		idr_for_each_entry(&pid_ns->idr, pid, nr) {
@@ -493,20 +510,20 @@ static struct nsexec *nsexec_create(unsigned int flags)
 	user_ns = nsexec_create_user_ns();
 	if (IS_ERR(user_ns)) {
 		ret = PTR_ERR(user_ns);
-		goto err_put;
+		goto err_free;
 	}
 	c->user_ns = user_ns;
 	ns_ref_active_get(user_ns);
 
 	if (!ns_capable(user_ns, CAP_SYS_ADMIN)) {
 		ret = -EPERM;
-		goto err_put;
+		goto err_free;
 	}
 
 	ns = create_new_namespaces(clone_flags, current, user_ns, NULL);
 	if (IS_ERR(ns)) {
 		ret = PTR_ERR(ns);
-		goto err_put;
+		goto err_free;
 	}
 
 	if (ns->time_ns != ns->time_ns_for_children) {
@@ -517,10 +534,14 @@ static struct nsexec *nsexec_create(unsigned int flags)
 	c->ns = ns;
 	nsproxy_ns_active_get(ns);
 
+	ret = security_nsexec_alloc(c, flags);
+	if (ret < 0)
+		goto err_free;
+
 	return c;
 
-err_put:
-	nsexec_put(c);
+err_free:
+	nsexec_free(c);
 	return ERR_PTR(ret);
 }
 
@@ -681,6 +702,10 @@ int nsexec_prepare_fork(struct kernel_clone_args *args)
 	if (ret)
 		goto err_forking;
 
+	ret = security_nsexec_clone(nsexec);
+	if (ret)
+		goto err_forking;
+
 	args->nsexec_file = no_free_ptr(file);
 	args->nsexec = nsexec;
 	args->nsexec_bootstrapping = bootstrapping;
diff --git a/security/lsm_init.c b/security/lsm_init.c
index 8d5ecea99c46..374a09c124a7 100644
--- a/security/lsm_init.c
+++ b/security/lsm_init.c
@@ -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)
diff --git a/security/security.c b/security/security.c
index b4d60dcf4880..5d16e248ce37 100644
--- a/security/security.c
+++ b/security/security.c
@@ -30,6 +30,7 @@
 #include <linux/overflow.h>
 #include <linux/perf_event.h>
 #include <linux/fs.h>
+#include <linux/nsexec.h>
 #include <net/flow.h>
 #include <net/sock.h>
 
@@ -5796,3 +5797,74 @@ void security_initramfs_populated(void)
 {
 	call_void_hook(initramfs_populated);
 }
+
+#ifdef CONFIG_NSEXEC
+/**
+ * security_nsexec_alloc() - Allocate LSM blob and check nsexec creation
+ * @nsexec: the new nsexec
+ * @flags: creation flags passed to nsexec_open()
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int security_nsexec_alloc(struct nsexec *nsexec, unsigned int flags)
+{
+	int rc;
+
+	rc = lsm_blob_alloc(&nsexec->security, blob_sizes.lbs_nsexec,
+			    GFP_KERNEL);
+	if (unlikely(rc))
+		return rc;
+
+	rc = call_int_hook(nsexec_alloc, nsexec, flags);
+	if (unlikely(rc))
+		security_nsexec_free(nsexec);
+
+	return rc;
+}
+
+/**
+ * security_nsexec_free() - Release LSM blob from @nsexec
+ * @nsexec: the nsexec being freed
+ */
+void security_nsexec_free(struct nsexec *nsexec)
+{
+	call_void_hook(nsexec_free, nsexec);
+	kfree(nsexec->security);
+	nsexec->security = NULL;
+}
+
+/**
+ * security_nsexec_share() - Check permission to share @ns into @nsexec
+ * @nsexec: the target nsexec
+ * @ns: the namespace being shared
+ *
+ * Return: 0 if permission is granted, negative error code on failure.
+ */
+int security_nsexec_share(struct nsexec *nsexec, struct ns_common *ns)
+{
+	return call_int_hook(nsexec_share, nsexec, ns);
+}
+
+/**
+ * security_nsexec_clone() - Check permission to spawn into @nsexec
+ * @nsexec: the target nsexec
+ *
+ * Return: 0 if permission is granted, negative error code on failure.
+ */
+int security_nsexec_clone(struct nsexec *nsexec)
+{
+	return call_int_hook(nsexec_clone, nsexec);
+}
+
+/**
+ * security_nsexec_kill() - Check permission to signal @nsexec
+ * @nsexec: the target nsexec
+ * @sig: signal number (or 0 for permission probe)
+ *
+ * Return: 0 if permission is granted, negative error code on failure.
+ */
+int security_nsexec_kill(struct nsexec *nsexec, int sig)
+{
+	return call_int_hook(nsexec_kill, nsexec, sig);
+}
+#endif /* CONFIG_NSEXEC */
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 24/29] landlock: Enforce namespace use restrictions on nsexec
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (22 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 23/29] security: Add nsexec LSM hooks Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 25/29] bpf: Register nsexec LSM hooks Jarkko Sakkinen
                   ` (5 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

When 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.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 security/landlock/ns.c | 63 +++++++++++++++++++++++++++++++++++++++---
 1 file changed, 59 insertions(+), 4 deletions(-)

diff --git a/security/landlock/ns.c b/security/landlock/ns.c
index 3d443599b16f..b5f0aa48a1d0 100644
--- a/security/landlock/ns.c
+++ b/security/landlock/ns.c
@@ -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)
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 25/29] bpf: Register nsexec LSM hooks
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (23 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 24/29] landlock: Enforce namespace use restrictions on nsexec Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 26/29] arch: Wire up nsexec_open() system call Jarkko Sakkinen
                   ` (4 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

BPF 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.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 kernel/bpf/bpf_lsm.c | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/kernel/bpf/bpf_lsm.c b/kernel/bpf/bpf_lsm.c
index ae23511fd811..41a62fb08656 100644
--- a/kernel/bpf/bpf_lsm.c
+++ b/kernel/bpf/bpf_lsm.c
@@ -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)
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 26/29] arch: Wire up nsexec_open() system call
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (24 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 25/29] bpf: Register nsexec LSM hooks Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:09 ` [RFC PATCH v9 27/29] docs: Document nsexec uAPI Jarkko Sakkinen
                   ` (3 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

Now 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/.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 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(-)

diff --git a/arch/alpha/kernel/syscalls/syscall.tbl b/arch/alpha/kernel/syscalls/syscall.tbl
index 60d330a51476..da5325263638 100644
--- a/arch/alpha/kernel/syscalls/syscall.tbl
+++ b/arch/alpha/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/arm/tools/syscall.tbl b/arch/arm/tools/syscall.tbl
index d055515e98cd..612e96ed7794 100644
--- a/arch/arm/tools/syscall.tbl
+++ b/arch/arm/tools/syscall.tbl
@@ -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
diff --git a/arch/arm64/tools/syscall_32.tbl b/arch/arm64/tools/syscall_32.tbl
index a18982ead3bf..279863e4bb19 100644
--- a/arch/arm64/tools/syscall_32.tbl
+++ b/arch/arm64/tools/syscall_32.tbl
@@ -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
diff --git a/arch/m68k/kernel/syscalls/syscall.tbl b/arch/m68k/kernel/syscalls/syscall.tbl
index e89ec7d54b8c..1d59fbad252b 100644
--- a/arch/m68k/kernel/syscalls/syscall.tbl
+++ b/arch/m68k/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/microblaze/kernel/syscalls/syscall.tbl b/arch/microblaze/kernel/syscalls/syscall.tbl
index 0dfcd6f9e4e7..80eda90b7a6c 100644
--- a/arch/microblaze/kernel/syscalls/syscall.tbl
+++ b/arch/microblaze/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/mips/kernel/syscalls/syscall_n32.tbl b/arch/mips/kernel/syscalls/syscall_n32.tbl
index 882ff15f3e6d..ccb516fba904 100644
--- a/arch/mips/kernel/syscalls/syscall_n32.tbl
+++ b/arch/mips/kernel/syscalls/syscall_n32.tbl
@@ -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
diff --git a/arch/mips/kernel/syscalls/syscall_n64.tbl b/arch/mips/kernel/syscalls/syscall_n64.tbl
index daa95049baef..9f5077c1907c 100644
--- a/arch/mips/kernel/syscalls/syscall_n64.tbl
+++ b/arch/mips/kernel/syscalls/syscall_n64.tbl
@@ -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
diff --git a/arch/mips/kernel/syscalls/syscall_o32.tbl b/arch/mips/kernel/syscalls/syscall_o32.tbl
index 9e0040399fef..d20188c8ae37 100644
--- a/arch/mips/kernel/syscalls/syscall_o32.tbl
+++ b/arch/mips/kernel/syscalls/syscall_o32.tbl
@@ -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
diff --git a/arch/parisc/kernel/syscalls/syscall.tbl b/arch/parisc/kernel/syscalls/syscall.tbl
index b77482e68d1a..ea014e714fa2 100644
--- a/arch/parisc/kernel/syscalls/syscall.tbl
+++ b/arch/parisc/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/powerpc/kernel/syscalls/syscall.tbl b/arch/powerpc/kernel/syscalls/syscall.tbl
index 973562f20a94..f20748489a5b 100644
--- a/arch/powerpc/kernel/syscalls/syscall.tbl
+++ b/arch/powerpc/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/s390/kernel/syscalls/syscall.tbl b/arch/s390/kernel/syscalls/syscall.tbl
index 19d7b234b31b..aa2567400bc2 100644
--- a/arch/s390/kernel/syscalls/syscall.tbl
+++ b/arch/s390/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/sh/kernel/syscalls/syscall.tbl b/arch/sh/kernel/syscalls/syscall.tbl
index 252e6f9aa04c..cf960fe387a1 100644
--- a/arch/sh/kernel/syscalls/syscall.tbl
+++ b/arch/sh/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/sparc/kernel/syscalls/syscall.tbl b/arch/sparc/kernel/syscalls/syscall.tbl
index 1263d0e825c1..ce29cdbc984b 100644
--- a/arch/sparc/kernel/syscalls/syscall.tbl
+++ b/arch/sparc/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/arch/x86/entry/syscalls/syscall_32.tbl b/arch/x86/entry/syscalls/syscall_32.tbl
index 0f8c81c584e0..a391fdd4aae9 100644
--- a/arch/x86/entry/syscalls/syscall_32.tbl
+++ b/arch/x86/entry/syscalls/syscall_32.tbl
@@ -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
diff --git a/arch/x86/entry/syscalls/syscall_64.tbl b/arch/x86/entry/syscalls/syscall_64.tbl
index 5452b7567bf8..173646c89ef1 100644
--- a/arch/x86/entry/syscalls/syscall_64.tbl
+++ b/arch/x86/entry/syscalls/syscall_64.tbl
@@ -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
diff --git a/arch/xtensa/kernel/syscalls/syscall.tbl b/arch/xtensa/kernel/syscalls/syscall.tbl
index f10b491c873c..9313bb7d053d 100644
--- a/arch/xtensa/kernel/syscalls/syscall.tbl
+++ b/arch/xtensa/kernel/syscalls/syscall.tbl
@@ -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
diff --git a/include/uapi/asm-generic/unistd.h b/include/uapi/asm-generic/unistd.h
index 695eac2d356b..818f3600300b 100644
--- a/include/uapi/asm-generic/unistd.h
+++ b/include/uapi/asm-generic/unistd.h
@@ -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
diff --git a/scripts/syscall.tbl b/scripts/syscall.tbl
index 7ba073cc0e80..15ac7383c94f 100644
--- a/scripts/syscall.tbl
+++ b/scripts/syscall.tbl
@@ -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
diff --git a/tools/include/uapi/asm-generic/unistd.h b/tools/include/uapi/asm-generic/unistd.h
index 695eac2d356b..818f3600300b 100644
--- a/tools/include/uapi/asm-generic/unistd.h
+++ b/tools/include/uapi/asm-generic/unistd.h
@@ -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
diff --git a/tools/perf/arch/arm/entry/syscalls/syscall.tbl b/tools/perf/arch/arm/entry/syscalls/syscall.tbl
index d055515e98cd..612e96ed7794 100644
--- a/tools/perf/arch/arm/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/arm/entry/syscalls/syscall.tbl
@@ -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
diff --git a/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl b/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl
index daa95049baef..9f5077c1907c 100644
--- a/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl
+++ b/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl
@@ -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
diff --git a/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl b/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl
index 973562f20a94..f20748489a5b 100644
--- a/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl
@@ -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
diff --git a/tools/perf/arch/s390/entry/syscalls/syscall.tbl b/tools/perf/arch/s390/entry/syscalls/syscall.tbl
index 19d7b234b31b..aa2567400bc2 100644
--- a/tools/perf/arch/s390/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/s390/entry/syscalls/syscall.tbl
@@ -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
diff --git a/tools/perf/arch/sh/entry/syscalls/syscall.tbl b/tools/perf/arch/sh/entry/syscalls/syscall.tbl
index 252e6f9aa04c..cf960fe387a1 100644
--- a/tools/perf/arch/sh/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/sh/entry/syscalls/syscall.tbl
@@ -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
diff --git a/tools/perf/arch/sparc/entry/syscalls/syscall.tbl b/tools/perf/arch/sparc/entry/syscalls/syscall.tbl
index 1263d0e825c1..ce29cdbc984b 100644
--- a/tools/perf/arch/sparc/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/sparc/entry/syscalls/syscall.tbl
@@ -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
diff --git a/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl b/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl
index 0f8c81c584e0..a391fdd4aae9 100644
--- a/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl
+++ b/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl
@@ -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
diff --git a/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl b/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl
index 5452b7567bf8..173646c89ef1 100644
--- a/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl
+++ b/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl
@@ -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
diff --git a/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl b/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl
index f10b491c873c..9313bb7d053d 100644
--- a/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl
@@ -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
diff --git a/tools/scripts/syscall.tbl b/tools/scripts/syscall.tbl
index 7ba073cc0e80..15ac7383c94f 100644
--- a/tools/scripts/syscall.tbl
+++ b/tools/scripts/syscall.tbl
@@ -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
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 27/29] docs: Document nsexec uAPI
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (25 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 26/29] arch: Wire up nsexec_open() system call Jarkko Sakkinen
@ 2026-12-01  3:09 ` Jarkko Sakkinen
  2026-12-01  3:10 ` [RFC PATCH v9 28/29] selftests/nsexec: Add nsexec test suite Jarkko Sakkinen
                   ` (2 subsequent siblings)
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:09 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

Userspace 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.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 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

diff --git a/Documentation/userspace-api/index.rst b/Documentation/userspace-api/index.rst
index a68b1bea57a8..e48d5081bbc2 100644
--- a/Documentation/userspace-api/index.rst
+++ b/Documentation/userspace-api/index.rst
@@ -17,6 +17,7 @@ System calls
    :maxdepth: 1
 
    unshare
+   nsexec
    futex2
    ebpf/index
    ioctl/index
diff --git a/Documentation/userspace-api/ioctl/ioctl-number.rst b/Documentation/userspace-api/ioctl/ioctl-number.rst
index dbe462040999..441e4925c9ac 100644
--- a/Documentation/userspace-api/ioctl/ioctl-number.rst
+++ b/Documentation/userspace-api/ioctl/ioctl-number.rst
@@ -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:linux-hyperv@vger.kernel.org>
+0xB9  00-0F  uapi/linux/nsexec.h                                       nsexec uAPI
 0xBA  00-0F  uapi/linux/liveupdate.h                                   Pasha Tatashin
                                                                        <mailto:pasha.tatashin@soleen.com>
 0xC0  00-0F  linux/usb/iowarrior.h
diff --git a/Documentation/userspace-api/nsexec.rst b/Documentation/userspace-api/nsexec.rst
new file mode 100644
index 000000000000..81d4352a01a5
--- /dev/null
+++ b/Documentation/userspace-api/nsexec.rst
@@ -0,0 +1,77 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+===========
+nsexec uAPI
+===========
+
+Overview
+========
+
+.. kernel-doc:: kernel/nsexec.c
+   :doc: Overview
+
+Lifecycle
+=========
+
+.. kernel-doc:: include/linux/nsexec.h
+   :identifiers: nsexec_state
+
+Flags
+=====
+
+.. kernel-doc:: include/uapi/linux/nsexec.h
+   :identifiers: nsexec_flags
+
+Ioctls
+======
+
+.. kernel-doc:: include/uapi/linux/nsexec.h
+   :doc: NSEXEC_GET_NSFD
+
+.. kernel-doc:: include/uapi/linux/nsexec.h
+   :doc: NSEXEC_SHARE_NSFD
+
+System calls
+============
+
+.. kernel-doc:: kernel/nsexec.c
+   :identifiers: sys_nsexec_open
+
+Process creation
+================
+
+.. kernel-doc:: kernel/nsexec.c
+   :doc: CLONE_INTO_NSEXEC
+
+Process waiting
+===============
+
+.. kernel-doc:: kernel/nsexec.c
+   :doc: P_NSEXEC
+
+Signal delivery
+===============
+
+.. kernel-doc:: kernel/nsexec.c
+   :doc: pidfd_send_signal
+
+Filesystem configuration
+========================
+
+.. kernel-doc:: fs/fsopen.c
+   :doc: FSCONFIG_SET_NSEXEC
+
+Mount tree installation
+=======================
+
+.. kernel-doc:: fs/namespace.c
+   :doc: MOVE_MOUNT_T_MNTNS
+
+User namespace ID mapping
+=========================
+
+.. kernel-doc:: include/uapi/linux/nsfs.h
+   :identifiers: userns_idmap_extent userns_flags userns_idmap
+
+.. kernel-doc:: kernel/user_namespace.c
+   :identifiers: sys_userns_set_idmap
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 28/29] selftests/nsexec: Add nsexec test suite
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (26 preceding siblings ...)
  2026-12-01  3:09 ` [RFC PATCH v9 27/29] docs: Document nsexec uAPI Jarkko Sakkinen
@ 2026-12-01  3:10 ` Jarkko Sakkinen
  2026-12-01  3:10 ` [RFC PATCH v9 29/29] MAINTAINERS: Add entry for NSEXEC Jarkko Sakkinen
  2026-12-01  4:02 ` [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:10 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

Add 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.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 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

diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile
index 07c3719f8b04..3ec2bb6b9f6f 100644
--- a/tools/testing/selftests/Makefile
+++ b/tools/testing/selftests/Makefile
@@ -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
diff --git a/tools/testing/selftests/nsexec/Makefile b/tools/testing/selftests/nsexec/Makefile
new file mode 100644
index 000000000000..12f8598632d7
--- /dev/null
+++ b/tools/testing/selftests/nsexec/Makefile
@@ -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
diff --git a/tools/testing/selftests/nsexec/cells.py b/tools/testing/selftests/nsexec/cells.py
new file mode 100644
index 000000000000..d138d44c4df5
--- /dev/null
+++ b/tools/testing/selftests/nsexec/cells.py
@@ -0,0 +1,1560 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Copyright (C) 2026 Opinsys Oy
+
+"""Low-level nsexec(2) syscall bindings and bottleneck-free Cells runtime."""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Mapping, Sequence
+from contextlib import suppress
+import ctypes
+from dataclasses import dataclass, field
+from enum import IntEnum, IntFlag, StrEnum
+import errno
+import os
+import platform
+import select
+import signal
+import socket
+import sys
+import time
+from types import TracebackType
+from typing import Any, ClassVar, Final, NoReturn
+
+HOST_RUNTIME_DIRS: Final[tuple[str, ...]] = (
+    "usr",
+    "bin",
+    "sbin",
+    "lib",
+    "lib32",
+    "lib64",
+    "libx32",
+    "etc",
+    "opt",
+    "nix",
+)
+
+DEV_NODES: Final[tuple[str, ...]] = (
+    "null",
+    "zero",
+    "full",
+    "random",
+    "urandom",
+    "tty",
+)
+
+
+class NsExecFlag(IntFlag):
+    NONE = 0
+    AUTOKILL = 0x00000001
+    DEFAULT = AUTOKILL
+    ALL = AUTOKILL
+
+
+class CloneFlag(IntFlag):
+    NONE = 0
+    NEWTIME = 0x00000080
+    VM = 0x00000100
+    FS = 0x00000200
+    FILES = 0x00000400
+    SIGHAND = 0x00000800
+    PIDFD = 0x00001000
+    VFORK = 0x00004000
+    PARENT = 0x00008000
+    THREAD = 0x00010000
+    NEWNS = 0x00020000
+    SYSVSEM = 0x00040000
+    NEWCGROUP = 0x02000000
+    NEWUTS = 0x04000000
+    NEWIPC = 0x08000000
+    NEWUSER = 0x10000000
+    NEWPID = 0x20000000
+    NEWNET = 0x40000000
+    CLEAR_SIGHAND = 1 << 32
+    INTO_CGROUP = 1 << 33
+    AUTOREAP = 1 << 34
+    NNP = 1 << 35
+    PIDFD_AUTOKILL = 1 << 36
+    EMPTY_MNTNS = 1 << 37
+    INTO_NSEXEC = 1 << 38
+
+
+SHAREABLE_NSTYPES: Final[tuple[CloneFlag, ...]] = (
+    CloneFlag.NEWCGROUP,
+    CloneFlag.NEWIPC,
+    CloneFlag.NEWUTS,
+    CloneFlag.NEWNET,
+    CloneFlag.NEWTIME,
+)
+
+NS_NAMES: Final[Mapping[CloneFlag, str]] = {
+    CloneFlag.NEWNS: "mnt",
+    CloneFlag.NEWCGROUP: "cgroup",
+    CloneFlag.NEWUTS: "uts",
+    CloneFlag.NEWIPC: "ipc",
+    CloneFlag.NEWUSER: "user",
+    CloneFlag.NEWPID: "pid",
+    CloneFlag.NEWNET: "net",
+    CloneFlag.NEWTIME: "time",
+}
+
+
+class AtFlag(IntFlag):
+    NONE = 0
+    EMPTY_PATH = 0x1000
+
+
+class MoveMountFlag(IntFlag):
+    F_EMPTY_PATH = 0x00000004
+    T_MNTNS = 0x00000080
+    SET_GROUP = 0x00000100
+    BENEATH = 0x00000200
+    CLONE = 0x00000400
+
+class UsernsFlag(IntFlag):
+    NONE = 0
+    SETGROUPS_ALLOWED = 1 << 0
+
+
+class MountAttrFlag(IntFlag):
+    NONE = 0
+    RDONLY = 0x00000001
+    NOSUID = 0x00000002
+    NODEV = 0x00000004
+    NOEXEC = 0x00000008
+
+class UmountFlag(IntFlag):
+    NONE = 0
+    DETACH = 2
+
+
+class ResolveFlag(IntFlag):
+    NONE = 0
+    IN_ROOT = 0x10
+
+
+class FsconfigCmd(IntEnum):
+    SET_FLAG = 0
+    SET_STRING = 1
+    CMD_CREATE = 6
+    CMD_RECONFIGURE = 7
+    CMD_CREATE_EXCL = 8
+    SET_NSEXEC = 9
+
+
+class PrctlOp(IntEnum):
+    GET_DUMPABLE = 3
+    SET_DUMPABLE = 4
+    SET_KEEPCAPS = 8
+    GET_NO_NEW_PRIVS = 39
+
+
+class WaitIdType(IntEnum):
+    ALL = 0
+    PID = 1
+    PGID = 2
+    PIDFD = 3
+    NSEXEC = 4
+
+
+class PidfdInfoFlag(IntFlag):
+    PID = 1 << 0
+    CREDS = 1 << 1
+    CGROUPID = 1 << 2
+    EXIT = 1 << 3
+
+
+class PidfdInfo(ctypes.Structure):
+    SIZE_VER3: ClassVar[int] = 88
+
+    mask: int
+    cgroupid: int
+    pid: int
+    tgid: int
+    ppid: int
+    ruid: int
+    rgid: int
+    euid: int
+    egid: int
+    suid: int
+    sgid: int
+    fsuid: int
+    fsgid: int
+    exit_code: int
+    coredump_mask: int
+    coredump_signal: int
+    coredump_code: int
+    coredump_pad: int
+    supported_mask: int
+    _fields_ = [
+        ("mask", ctypes.c_uint64),
+        ("cgroupid", ctypes.c_uint64),
+        ("pid", ctypes.c_uint32),
+        ("tgid", ctypes.c_uint32),
+        ("ppid", ctypes.c_uint32),
+        ("ruid", ctypes.c_uint32),
+        ("rgid", ctypes.c_uint32),
+        ("euid", ctypes.c_uint32),
+        ("egid", ctypes.c_uint32),
+        ("suid", ctypes.c_uint32),
+        ("sgid", ctypes.c_uint32),
+        ("fsuid", ctypes.c_uint32),
+        ("fsgid", ctypes.c_uint32),
+        ("exit_code", ctypes.c_int32),
+        ("coredump_mask", ctypes.c_uint32),
+        ("coredump_signal", ctypes.c_uint32),
+        ("coredump_code", ctypes.c_uint32),
+        ("coredump_pad", ctypes.c_uint32),
+        ("supported_mask", ctypes.c_uint64),
+    ]
+
+    @property
+    def decoded_exit(self) -> int | None:
+        if not (self.mask & int(PidfdInfoFlag.EXIT)):
+            return None
+        return os.waitstatus_to_exitcode(self.exit_code)
+
+
+class CloneArgs(ctypes.Structure):
+    SIZE_VER2: ClassVar[int] = 88
+    SIZE_VER3: ClassVar[int] = 96
+
+    flags: int
+    pidfd: int
+    child_tid: int
+    parent_tid: int
+    exit_signal: int
+    stack: int
+    stack_size: int
+    tls: int
+    set_tid: int
+    set_tid_size: int
+    cgroup: int
+    nsexec: int
+    _fields_ = [
+        ("flags", ctypes.c_uint64),
+        ("pidfd", ctypes.c_uint64),
+        ("child_tid", ctypes.c_uint64),
+        ("parent_tid", ctypes.c_uint64),
+        ("exit_signal", ctypes.c_uint64),
+        ("stack", ctypes.c_uint64),
+        ("stack_size", ctypes.c_uint64),
+        ("tls", ctypes.c_uint64),
+        ("set_tid", ctypes.c_uint64),
+        ("set_tid_size", ctypes.c_uint64),
+        ("cgroup", ctypes.c_uint64),
+        ("nsexec", ctypes.c_uint64),
+    ]
+
+
+class OpenHow(ctypes.Structure):
+    flags: int
+    mode: int
+    resolve: int
+    _fields_ = [
+        ("flags", ctypes.c_uint64),
+        ("mode", ctypes.c_uint64),
+        ("resolve", ctypes.c_uint64),
+    ]
+
+
+class UsernsIdmapExtent(ctypes.Structure):
+    first: int
+    lower_first: int
+    count: int
+    reserved: int
+    _fields_ = [
+        ("first", ctypes.c_uint32),
+        ("lower_first", ctypes.c_uint32),
+        ("count", ctypes.c_uint32),
+        ("reserved", ctypes.c_uint32),
+    ]
+
+
+class UsernsIdmap(ctypes.Structure):
+    SIZE_VER0: ClassVar[int] = 40
+
+    nr_uid_extents: int
+    nr_gid_extents: int
+    nr_projid_extents: int
+    reserved: int
+    uid_extents: int
+    gid_extents: int
+    projid_extents: int
+    _fields_ = [
+        ("nr_uid_extents", ctypes.c_uint32),
+        ("nr_gid_extents", ctypes.c_uint32),
+        ("nr_projid_extents", ctypes.c_uint32),
+        ("reserved", ctypes.c_uint32),
+        ("uid_extents", ctypes.c_uint64),
+        ("gid_extents", ctypes.c_uint64),
+        ("projid_extents", ctypes.c_uint64),
+    ]
+
+
+class CapHeader(ctypes.Structure):
+    VERSION_3: ClassVar[int] = 0x20080522
+
+    version: int
+    pid: int
+    _fields_ = [("version", ctypes.c_uint32), ("pid", ctypes.c_int32)]
+
+
+class CapData(ctypes.Structure):
+    effective: int
+    permitted: int
+    inheritable: int
+    _fields_ = [
+        ("effective", ctypes.c_uint32),
+        ("permitted", ctypes.c_uint32),
+        ("inheritable", ctypes.c_uint32),
+    ]
+
+
+_LEGACY_SYSCALLS: Final[dict[str, tuple[int, int, int, int]]] = {
+    "x86_64": (155, 166, 247, 322),
+    "i386": (217, 52, 284, 358),
+    "arm": (218, 52, 280, 387),
+    "ppc": (203, 52, 272, 362),
+    "s390": (217, 52, 281, 354),
+    "sparc": (146, 45, 279, 350),
+    "parisc": (67, 52, 235, 342),
+    "m68k": (217, 52, 277, 355),
+    "microblaze": (217, 52, 284, 388),
+    "sh": (217, 52, 284, 376),
+    "xtensa": (175, 171, 122, 341),
+    "alpha": (374, 22, 438, 513),
+    "mips64": (5151, 5161, 5237, 5316),
+    "mipsn32": (6151, 6161, 6241, 6320),
+    "mips32": (4216, 4052, 4278, 4356),
+    "generic": (41, 39, 95, 281),
+}
+
+
+class Sys:
+    AT_FDCWD: Final[int] = -100
+    FSOPEN_CLOEXEC: Final[int] = 0x00000001
+    FSMOUNT_CLOEXEC: Final[int] = 0x00000001
+    CAP_SETGID: Final[int] = 6
+    CAP_SETUID: Final[int] = 7
+    _WIDE_IOC: Final[tuple[str, ...]] = (
+        "alpha",
+        "mips",
+        "powerpc",
+        "ppc",
+        "sparc",
+    )
+
+    _NR: ClassVar[dict[str, int]]
+    _LIBC: ClassVar[ctypes.CDLL]
+
+    @classmethod
+    def _is_wide_ioc(cls) -> bool:
+        return platform.machine().lower().startswith(cls._WIDE_IOC)
+
+    @classmethod
+    def ioc(cls, direction: int, magic: int, nr: int, size: int) -> int:
+        dirshift = 16 + (13 if cls._is_wide_ioc() else 14)
+        return (direction << dirshift) | (magic << 8) | nr | (size << 16)
+
+    @classmethod
+    def io(cls, magic: int, nr: int) -> int:
+        return cls.ioc(1 if cls._is_wide_ioc() else 0, magic, nr, 0)
+
+    @classmethod
+    def iowr(cls, magic: int, nr: int, size: int) -> int:
+        return cls.ioc(6 if cls._is_wide_ioc() else 3, magic, nr, size)
+
+    @staticmethod
+    def _build_syscall_numbers() -> dict[str, int]:
+        mach = platform.machine().lower()
+        ptr_sz = ctypes.sizeof(ctypes.c_void_p)
+        multi = getattr(sys.implementation, "_multiarch", "")
+        base = 0
+        key = "generic"
+
+        if mach.startswith("alpha"):
+            base, key = 110, "alpha"
+        elif mach.startswith("mips"):
+            if ptr_sz == 8:
+                base, key = 5000, "mips64"
+            elif "abin32" in multi:
+                base, key = 6000, "mipsn32"
+            else:
+                base, key = 4000, "mips32"
+        elif mach == "x86_64" and ptr_sz == 4 and "x32" in multi:
+            base = 0x40000000
+            piv, umt, wid, exv = (
+                base + 155,
+                base + 166,
+                base + 529,
+                base + 545,
+            )
+        else:
+            if mach == "x86_64" and ptr_sz == 8:
+                key = "x86_64"
+            elif mach in ("i386", "i486", "i586", "i686", "x86_64"):
+                key = "i386"
+            elif mach in ("aarch64", "arm64") and ptr_sz == 8:
+                key = "generic"
+            elif mach.startswith(("arm", "aarch64")):
+                key = "arm"
+            elif mach.startswith(("ppc", "powerpc")):
+                key = "ppc"
+            elif mach.startswith("s390"):
+                key = "s390"
+            elif mach.startswith("sparc"):
+                key = "sparc"
+            elif mach.startswith(("parisc", "hppa")):
+                key = "parisc"
+            elif mach in ("m68k", "xtensa"):
+                key = mach
+            elif mach.startswith("microblaze"):
+                key = "microblaze"
+            elif mach.startswith("sh"):
+                key = "sh"
+
+        if base != 0x40000000:
+            piv, umt, wid, exv = _LEGACY_SYSCALLS[key]
+
+        return {
+            "pivot_root": piv,
+            "umount2": umt,
+            "waitid": wid,
+            "execveat": exv,
+            "pidfd_send_signal": base + 424,
+            "move_mount": base + 429,
+            "fsopen": base + 430,
+            "fsconfig": base + 431,
+            "fsmount": base + 432,
+            "clone3": base + 435,
+            "openat2": base + 437,
+            "landlock_create_ruleset": base + 444,
+            "landlock_add_rule": base + 445,
+            "landlock_restrict_self": base + 446,
+            "userns_set_idmap": base + 473,
+            "nsexec_open": base + 474,
+        }
+
+    @staticmethod
+    def _os_err() -> NoReturn:
+        err = ctypes.get_errno()
+        raise OSError(err, os.strerror(err))
+
+    @staticmethod
+    def _cstr(val: str | bytes) -> bytes:
+        return val if isinstance(val, bytes) else os.fsencode(val)
+
+    @classmethod
+    def fork(cls) -> int:
+        sys.stdout.flush()
+        sys.stderr.flush()
+        return os.fork()
+
+    @classmethod
+    def syscall(cls, name: str, *args: Any) -> int:
+        ret: int = cls._LIBC.syscall(ctypes.c_long(cls._NR[name]), *args)
+        if ret < 0:
+            cls._os_err()
+        return int(ret)
+
+    @classmethod
+    def ioctl(cls, fd: int, cmd: int, arg: int = 0) -> int:
+        ret: int = cls._LIBC.ioctl(
+            ctypes.c_int(fd), ctypes.c_ulong(int(cmd)), ctypes.c_ulong(arg)
+        )
+        if ret < 0:
+            cls._os_err()
+        return int(ret)
+
+    @classmethod
+    def pidfd_get_info(
+        cls, pidfd: int, mask: PidfdInfoFlag | int = PidfdInfoFlag.EXIT
+    ) -> PidfdInfo:
+        info = PidfdInfo(mask=int(mask))
+        ret: int = cls._LIBC.ioctl(
+            ctypes.c_int(pidfd),
+            ctypes.c_ulong(int(Ioctl.PIDFD_GET_INFO)),
+            ctypes.byref(info),
+        )
+        if ret < 0:
+            cls._os_err()
+        return info
+
+    @classmethod
+    def fsopen(cls, fsname: str | bytes, flags: int = FSOPEN_CLOEXEC) -> int:
+        return cls.syscall(
+            "fsopen", ctypes.c_char_p(cls._cstr(fsname)), ctypes.c_uint(flags)
+        )
+
+    @classmethod
+    def fsconfig(
+        cls,
+        fsfd: int,
+        cmd: FsconfigCmd,
+        key: str | bytes | None = None,
+        value: str | bytes | None = None,
+        aux: int = 0,
+    ) -> None:
+        k_ptr = (
+            ctypes.c_char_p(cls._cstr(key))
+            if key is not None
+            else ctypes.c_void_p(0)
+        )
+        v_ptr = (
+            ctypes.c_char_p(cls._cstr(value))
+            if value is not None
+            else ctypes.c_void_p(0)
+        )
+        cls.syscall(
+            "fsconfig",
+            ctypes.c_int(fsfd),
+            ctypes.c_uint(int(cmd)),
+            k_ptr,
+            v_ptr,
+            ctypes.c_int(aux),
+        )
+
+    @classmethod
+    def fsmount(
+        cls,
+        fsfd: int,
+        flags: int = FSMOUNT_CLOEXEC,
+        attr_flags: MountAttrFlag = MountAttrFlag.NONE,
+    ) -> int:
+        return cls.syscall(
+            "fsmount",
+            ctypes.c_int(fsfd),
+            ctypes.c_uint(flags),
+            ctypes.c_uint(int(attr_flags)),
+        )
+
+    @classmethod
+    def move_mount(
+        cls,
+        from_dfd: int,
+        from_path: str | bytes,
+        to_dfd: int,
+        to_path: str | bytes,
+        flags: MoveMountFlag | int,
+    ) -> None:
+        cls.syscall(
+            "move_mount",
+            ctypes.c_int(from_dfd),
+            ctypes.c_char_p(cls._cstr(from_path)),
+            ctypes.c_int(to_dfd),
+            ctypes.c_char_p(cls._cstr(to_path)),
+            ctypes.c_uint(int(flags)),
+        )
+
+    @classmethod
+    def openat2(
+        cls,
+        dfd: int,
+        path: str | bytes,
+        flags: int,
+        mode: int = 0,
+        resolve: ResolveFlag = ResolveFlag.NONE,
+    ) -> int:
+        how = OpenHow(flags=flags, mode=mode, resolve=int(resolve))
+        return cls.syscall(
+            "openat2",
+            ctypes.c_int(dfd),
+            ctypes.c_char_p(cls._cstr(path)),
+            ctypes.byref(how),
+            ctypes.c_size_t(ctypes.sizeof(how)),
+        )
+
+    @classmethod
+    def execveat(
+        cls,
+        dfd: int,
+        path: str | bytes,
+        argv: Sequence[str],
+        envp: Mapping[str, str] | Sequence[str] | None = None,
+        flags: AtFlag = AtFlag.NONE,
+    ) -> NoReturn:
+        c_argv = (ctypes.c_char_p * (len(argv) + 1))(
+            *[cls._cstr(a) for a in argv], None
+        )
+        if envp is None:
+            env_items = [f"{k}={v}" for k, v in os.environ.items()]
+        elif isinstance(envp, Mapping):
+            env_items = [f"{k}={v}" for k, v in envp.items()]
+        else:
+            env_items = list(envp)
+        c_envp = (ctypes.c_char_p * (len(env_items) + 1))(
+            *[cls._cstr(e) for e in env_items], None
+        )
+        cls.syscall(
+            "execveat",
+            ctypes.c_int(dfd),
+            ctypes.c_char_p(cls._cstr(path)),
+            c_argv,
+            c_envp,
+            ctypes.c_int(int(flags)),
+        )
+        cls._os_err()
+
+    @classmethod
+    def pivot_root(cls, new_root: str | bytes, put_old: str | bytes) -> None:
+        cls.syscall(
+            "pivot_root",
+            ctypes.c_char_p(cls._cstr(new_root)),
+            ctypes.c_char_p(cls._cstr(put_old)),
+        )
+
+    @classmethod
+    def umount2(
+        cls, target: str | bytes, flags: UmountFlag = UmountFlag.NONE
+    ) -> None:
+        cls.syscall(
+            "umount2",
+            ctypes.c_char_p(cls._cstr(target)),
+            ctypes.c_int(int(flags)),
+        )
+
+    @classmethod
+    def setgroups_empty(cls) -> None:
+        ret: int = cls._LIBC.setgroups(ctypes.c_size_t(0), ctypes.c_void_p(0))
+        if ret < 0:
+            cls._os_err()
+
+    @classmethod
+    def unshare(cls, flags: CloneFlag | int) -> None:
+        ret: int = cls._LIBC.unshare(ctypes.c_int(int(flags)))
+        if ret < 0:
+            cls._os_err()
+
+    @classmethod
+    def setns(cls, fd: int, nstype: CloneFlag | int = 0) -> None:
+        ret: int = cls._LIBC.setns(ctypes.c_int(fd), ctypes.c_int(int(nstype)))
+        if ret < 0:
+            cls._os_err()
+
+    @classmethod
+    def drop_to_setid_helper(cls, uid: int) -> None:
+        cls.prctl(PrctlOp.SET_KEEPCAPS, 1)
+        try:
+            cls.setgroups_empty()
+        except OSError as exc:
+            if exc.errno != errno.EPERM:
+                raise
+        os.setresgid(uid, uid, uid)
+        os.setresuid(uid, uid, uid)
+        hdr = CapHeader(version=CapHeader.VERSION_3, pid=0)
+        mask = (1 << cls.CAP_SETGID) | (1 << cls.CAP_SETUID)
+        data = (CapData * 2)(
+            CapData(effective=mask, permitted=mask, inheritable=0),
+            CapData(effective=0, permitted=0, inheritable=0),
+        )
+        ret: int = cls._LIBC.capset(ctypes.byref(hdr), ctypes.byref(data))
+        if ret < 0:
+            cls._os_err()
+        cls.prctl(PrctlOp.SET_DUMPABLE, 1)
+
+    @classmethod
+    def prctl(
+        cls,
+        option: PrctlOp,
+        arg2: int = 0,
+        arg3: int = 0,
+        arg4: int = 0,
+        arg5: int = 0,
+    ) -> int:
+        ret: int = cls._LIBC.prctl(
+            ctypes.c_int(int(option)),
+            ctypes.c_ulong(arg2),
+            ctypes.c_ulong(arg3),
+            ctypes.c_ulong(arg4),
+            ctypes.c_ulong(arg5),
+        )
+        if ret < 0:
+            cls._os_err()
+        return int(ret)
+
+    @classmethod
+    def clone3(cls, args: CloneArgs, size: int | None = None) -> int:
+        actual = ctypes.sizeof(args) if size is None else size
+        sys.stdout.flush()
+        sys.stderr.flush()
+        return cls.syscall(
+            "clone3", ctypes.byref(args), ctypes.c_size_t(actual)
+        )
+
+    @staticmethod
+    def _extent_array(
+        extents: Sequence[tuple[int, int, int]],
+    ) -> ctypes.Array[UsernsIdmapExtent] | None:
+        if not extents:
+            return None
+        arr_t = UsernsIdmapExtent * len(extents)
+        return arr_t(
+            *[
+                UsernsIdmapExtent(
+                    first=first, lower_first=lower, count=count, reserved=0
+                )
+                for first, lower, count in extents
+            ]
+        )
+
+    @classmethod
+    def pidfd_send_signal(
+        cls, pidfd: int, sig: int, info_addr: int = 0, flags: int = 0
+    ) -> None:
+        cls.syscall(
+            "pidfd_send_signal",
+            ctypes.c_int(pidfd),
+            ctypes.c_int(sig),
+            ctypes.c_void_p(info_addr),
+            ctypes.c_uint(flags),
+        )
+
+    @classmethod
+    def waitid_raw(
+        cls,
+        which: int,
+        upid: int,
+        infop_addr: int,
+        options: int,
+        ru_addr: int = 0,
+    ) -> None:
+        cls.syscall(
+            "waitid",
+            ctypes.c_int(which),
+            ctypes.c_int(upid),
+            ctypes.c_void_p(infop_addr),
+            ctypes.c_int(options),
+            ctypes.c_void_p(ru_addr),
+        )
+
+    @classmethod
+    def userns_set_idmap_raw(
+        cls,
+        userns_fd: int,
+        map_addr: int,
+        size: int = UsernsIdmap.SIZE_VER0,
+        flags: int = 0,
+    ) -> None:
+        cls.syscall(
+            "userns_set_idmap",
+            ctypes.c_int(userns_fd),
+            ctypes.c_void_p(map_addr),
+            ctypes.c_size_t(size),
+            ctypes.c_uint(flags),
+        )
+
+    @classmethod
+    def set_userns_idmap(
+        cls,
+        userns_fd: int,
+        uid_extents: Sequence[tuple[int, int, int]] = (),
+        gid_extents: Sequence[tuple[int, int, int]] = (),
+        projid_extents: Sequence[tuple[int, int, int]] = (),
+        *,
+        reserved: int = 0,
+        size: int | None = None,
+        flags: UsernsFlag | int = UsernsFlag.NONE,
+    ) -> None:
+        u_arr = cls._extent_array(uid_extents)
+        g_arr = cls._extent_array(gid_extents)
+        p_arr = cls._extent_array(projid_extents)
+        req = UsernsIdmap(
+            nr_uid_extents=len(uid_extents),
+            nr_gid_extents=len(gid_extents),
+            nr_projid_extents=len(projid_extents),
+            reserved=reserved,
+            uid_extents=ctypes.addressof(u_arr) if u_arr is not None else 0,
+            gid_extents=ctypes.addressof(g_arr) if g_arr is not None else 0,
+            projid_extents=ctypes.addressof(p_arr) if p_arr is not None else 0,
+        )
+        cls.userns_set_idmap_raw(
+            userns_fd,
+            ctypes.addressof(req),
+            ctypes.sizeof(req) if size is None else size,
+            int(flags),
+        )
+
+    @staticmethod
+    def close_fd(fd: int) -> int:
+        if fd >= 0:
+            with suppress(OSError):
+                os.close(fd)
+        return -1
+
+
+Sys._NR = Sys._build_syscall_numbers()
+Sys._LIBC = ctypes.CDLL(None, use_errno=True)
+Sys._LIBC.syscall.restype = ctypes.c_long
+
+
+class Ioctl(IntEnum):
+    NSEXEC_GET_NSFD = Sys.io(0xB9, 0x01)
+    NSEXEC_SHARE_NSFD = Sys.io(0xB9, 0x02)
+    NS_GET_USERNS = Sys.io(0xB7, 0x01)
+    NS_GET_PARENT = Sys.io(0xB7, 0x02)
+    NS_GET_NSTYPE = Sys.io(0xB7, 0x03)
+    PIDFD_GET_CGROUP_NAMESPACE = Sys.io(0xFF, 1)
+    PIDFD_GET_IPC_NAMESPACE = Sys.io(0xFF, 2)
+    PIDFD_GET_MNT_NAMESPACE = Sys.io(0xFF, 3)
+    PIDFD_GET_NET_NAMESPACE = Sys.io(0xFF, 4)
+    PIDFD_GET_PID_NAMESPACE = Sys.io(0xFF, 5)
+    PIDFD_GET_TIME_NAMESPACE = Sys.io(0xFF, 7)
+    PIDFD_GET_USER_NAMESPACE = Sys.io(0xFF, 9)
+    PIDFD_GET_UTS_NAMESPACE = Sys.io(0xFF, 10)
+    PIDFD_GET_INFO = Sys.iowr(0xFF, 11, PidfdInfo.SIZE_VER3)
+
+@dataclass(frozen=True)
+class WaitResult:
+    pid: int
+    status: int = 0
+    code: int = 0
+    uid: int = 0
+
+    @property
+    def exit_code(self) -> int | None:
+        if self.pid <= 0:
+            return None
+        if self.code == os.CLD_EXITED:
+            return self.status
+        if self.code in (os.CLD_KILLED, os.CLD_DUMPED):
+            return -self.status
+        return os.waitstatus_to_exitcode(self.status)
+
+
+@dataclass
+class Session:
+    """Autoreaped pidfd workload session inside a running Cell."""
+
+    pid: int
+    pidfd: int
+    autokill: bool = False
+    _cached_exit: int | None = field(default=None, init=False, repr=False)
+
+    def fileno(self) -> int:
+        return self.pidfd
+
+    def __enter__(self) -> Session:
+        return self
+
+    def __exit__(
+        self,
+        exc_type: type[BaseException] | None,
+        exc: BaseException | None,
+        tb: TracebackType | None,
+    ) -> None:
+        self.close()
+
+    def poll(self) -> bool:
+        if self._cached_exit is not None:
+            return True
+        if self.pidfd < 0:
+            return False
+        poller = select.poll()
+        poller.register(self.pidfd, select.POLLIN)
+        return bool(poller.poll(0))
+
+    def wait(self, timeout: float = 5.0) -> int:
+        if self._cached_exit is not None:
+            return self._cached_exit
+        if self.pidfd < 0:
+            raise OSError(errno.EBADF, os.strerror(errno.EBADF))
+        poller = select.poll()
+        poller.register(self.pidfd, select.POLLIN)
+        if not poller.poll(max(0, int(timeout * 1000))):
+            raise TimeoutError(f"session pid={self.pid} timed out")
+        decoded = Sys.pidfd_get_info(self.pidfd).decoded_exit
+        if decoded is None:
+            raise RuntimeError(f"missing exit code on pidfd {self.pidfd}")
+        self._cached_exit = decoded
+        return decoded
+
+    def close(self) -> None:
+        self.pidfd = Sys.close_fd(self.pidfd)
+
+
+class NsExec:
+    fd: int
+
+    def __init__(
+        self,
+        flags: NsExecFlag | int = NsExecFlag.DEFAULT,
+        *,
+        fd: int | None = None,
+    ) -> None:
+        self.fd = (
+            fd
+            if fd is not None
+            else Sys.syscall("nsexec_open", ctypes.c_uint(int(flags)))
+        )
+
+    @classmethod
+    def from_fd(cls, fd: int) -> NsExec:
+        return cls(fd=fd)
+
+    def dup(self) -> NsExec:
+        return NsExec.from_fd(os.dup(self.fd))
+
+    def send(self, sock: socket.socket) -> None:
+        socket.send_fds(sock, [b"U"], [self.fd])
+
+    @classmethod
+    def recv(cls, sock: socket.socket, timeout: float = 5.0) -> NsExec:
+        ready, _, _ = select.select([sock], [], [], timeout)
+        if not ready:
+            raise TimeoutError("timed out receiving nsexec fd")
+        _, fds, _, _ = socket.recv_fds(sock, 1, 1)
+        if not fds:
+            raise RuntimeError("socket closed without nsexec fd")
+        return cls.from_fd(fds[0])
+
+    def fileno(self) -> int:
+        return self.fd
+
+    def __enter__(self) -> NsExec:
+        return self
+
+    def __exit__(
+        self,
+        exc_type: type[BaseException] | None,
+        exc: BaseException | None,
+        tb: TracebackType | None,
+    ) -> None:
+        self.close()
+
+    def close(self) -> None:
+        self.fd = Sys.close_fd(self.fd)
+
+    def get_nsfd(self, nstype: CloneFlag | int) -> int:
+        return Sys.ioctl(self.fd, Ioctl.NSEXEC_GET_NSFD, int(nstype))
+
+    def share_nsfd(self, nsfd: int) -> None:
+        Sys.ioctl(self.fd, Ioctl.NSEXEC_SHARE_NSFD, nsfd)
+
+    def set_idmap(
+        self,
+        uid_extents: Sequence[tuple[int, int, int]] = (),
+        gid_extents: Sequence[tuple[int, int, int]] = (),
+        projid_extents: Sequence[tuple[int, int, int]] = (),
+        *,
+        flags: UsernsFlag | int = UsernsFlag.NONE,
+    ) -> None:
+        ufd = self.get_nsfd(CloneFlag.NEWUSER)
+        try:
+            Sys.set_userns_idmap(
+                ufd,
+                uid_extents=uid_extents,
+                gid_extents=gid_extents,
+                projid_extents=projid_extents,
+                flags=flags,
+            )
+        finally:
+            os.close(ufd)
+
+    def map_self(self) -> None:
+        self.set_idmap(
+            uid_extents=((0, os.geteuid(), 1),),
+            gid_extents=((0, os.getegid(), 1),),
+        )
+
+    def wait(self, flags: int = 0) -> WaitResult:
+        res = os.waitid(int(WaitIdType.NSEXEC), self.fd, os.WEXITED | flags)
+        if res is None:
+            return WaitResult(pid=0)
+        return WaitResult(
+            pid=int(res.si_pid),
+            status=int(res.si_status),
+            code=int(res.si_code),
+            uid=int(res.si_uid),
+        )
+
+    def poll_dead(self, timeout_ms: int = 0) -> bool:
+        poller = select.poll()
+        poller.register(self.fd, select.POLLIN)
+        return any(ev & select.POLLHUP for _, ev in poller.poll(timeout_ms))
+
+    def kill(self, sig: signal.Signals | int) -> None:
+        Sys.pidfd_send_signal(self.fd, int(sig))
+
+    def clone_into(
+        self,
+        extra_flags: CloneFlag | int = CloneFlag.NONE,
+        exit_signal: int = int(signal.SIGCHLD),
+        *,
+        size: int | None = None,
+        cgroup_fd: int = -1,
+    ) -> tuple[int, int]:
+        pidfd_box = ctypes.c_int(-1)
+        args = CloneArgs()
+        args.flags = int(CloneFlag.INTO_NSEXEC) | int(extra_flags)
+        args.exit_signal = exit_signal
+        args.nsexec = self.fd & 0xFFFFFFFFFFFFFFFF
+        if int(extra_flags) & int(CloneFlag.PIDFD):
+            args.pidfd = ctypes.addressof(pidfd_box)
+        if cgroup_fd >= 0:
+            args.cgroup = cgroup_fd & 0xFFFFFFFFFFFFFFFF
+        pid = Sys.clone3(args, size=size)
+        return pid, int(pidfd_box.value)
+
+    def spawn_fn(
+        self,
+        fn: Callable[[], int | None],
+        extra_flags: CloneFlag = CloneFlag.NONE,
+        *,
+        exit_signal: int | None = None,
+    ) -> tuple[int, int]:
+        sig = (
+            (0 if extra_flags & CloneFlag.AUTOREAP else int(signal.SIGCHLD))
+            if exit_signal is None
+            else exit_signal
+        )
+        pid, pidfd = self.clone_into(extra_flags=extra_flags, exit_signal=sig)
+        if pid == 0:
+            try:
+                self.close()
+                rc = fn()
+                os._exit(0 if rc is None else int(rc))
+            except BaseException:
+                os._exit(126)
+        return pid, pidfd
+
+    def make_mount(
+        self,
+        fstype: str,
+        attr_flags: MountAttrFlag = MountAttrFlag.NONE,
+        options: Mapping[str, str | None] | None = None,
+    ) -> int:
+        fsfd = Sys.fsopen(fstype)
+        try:
+            Sys.fsconfig(fsfd, FsconfigCmd.SET_NSEXEC, aux=self.fd)
+            if options:
+                for k, v in options.items():
+                    if v is None:
+                        Sys.fsconfig(fsfd, FsconfigCmd.SET_FLAG, key=k)
+                    else:
+                        Sys.fsconfig(
+                            fsfd, FsconfigCmd.SET_STRING, key=k, value=str(v)
+                        )
+            Sys.fsconfig(fsfd, FsconfigCmd.CMD_CREATE)
+            return Sys.fsmount(fsfd, attr_flags=attr_flags)
+        finally:
+            os.close(fsfd)
+
+
+@dataclass
+class Cell:
+    """Sandbox cell managed directly from host space without helper forks."""
+
+    name: str
+    flags: NsExecFlag = NsExecFlag.DEFAULT
+    ul: NsExec = field(init=False)
+    mntns_fd: int = field(init=False, default=-1)
+    root_dfd: int = field(init=False, default=-1)
+    init_pid: int = field(init=False, default=0)
+    init_pidfd: int = field(init=False, default=-1)
+    _ctrl_wfd: int = field(init=False, default=-1, repr=False)
+
+    def __post_init__(self) -> None:
+        self.ul = NsExec(self.flags)
+        try:
+            self.mntns_fd = self.ul.get_nsfd(CloneFlag.NEWNS)
+        except Exception:
+            self.ul.close()
+            raise
+
+    @classmethod
+    def from_fds(
+        cls, name: str, ul_fd: int, mntns_fd: int, root_dfd: int = -1
+    ) -> Cell:
+        obj = cls.__new__(cls)
+        obj.name = name
+        obj.flags = NsExecFlag.DEFAULT
+        obj.ul = NsExec.from_fd(ul_fd)
+        obj.mntns_fd = mntns_fd
+        obj.root_dfd = root_dfd
+        obj.init_pid = 0
+        obj.init_pidfd = -1
+        obj._ctrl_wfd = -1
+        return obj
+
+    def send(self, sock: socket.socket) -> None:
+        fds = [self.ul.fd, self.mntns_fd]
+        if self.root_dfd >= 0:
+            fds.append(self.root_dfd)
+        socket.send_fds(sock, [b"C"], fds)
+
+    @classmethod
+    def recv(
+        cls, name: str, sock: socket.socket, timeout: float = 5.0
+    ) -> Cell:
+        ready, _, _ = select.select([sock], [], [], timeout)
+        if not ready:
+            raise TimeoutError("timed out receiving cell")
+        _, fds, _, _ = socket.recv_fds(sock, 2, 3)
+        if len(fds) < 2:
+            for fd in fds:
+                Sys.close_fd(fd)
+            raise RuntimeError("incomplete cell fd handoff")
+        return cls.from_fds(
+            name, fds[0], fds[1], fds[2] if len(fds) > 2 else -1
+        )
+
+    def __enter__(self) -> Cell:
+        return self
+
+    def __exit__(
+        self,
+        exc_type: type[BaseException] | None,
+        exc: BaseException | None,
+        tb: TracebackType | None,
+    ) -> None:
+        self.close()
+
+    def share_from(
+        self,
+        other: Cell | NsExec,
+        nstypes: Sequence[CloneFlag] = (CloneFlag.NEWNET, CloneFlag.NEWIPC),
+    ) -> None:
+        src = other.ul if isinstance(other, Cell) else other
+        for nstype in nstypes:
+            try:
+                nsfd = src.get_nsfd(nstype)
+            except OSError as exc:
+                if (
+                    nstype == CloneFlag.NEWTIME
+                    and exc.errno == errno.EOPNOTSUPP
+                ):
+                    continue
+                raise
+            try:
+                self.ul.share_nsfd(nsfd)
+            finally:
+                os.close(nsfd)
+
+    def share_host(
+        self, nstypes: Sequence[CloneFlag] = (CloneFlag.NEWNET,)
+    ) -> None:
+        for nstype in nstypes:
+            path = f"/proc/self/ns/{NS_NAMES[nstype]}"
+            if not os.path.exists(path):
+                continue
+            nsfd = os.open(path, os.O_RDONLY | os.O_CLOEXEC)
+            try:
+                self.ul.share_nsfd(nsfd)
+            finally:
+                os.close(nsfd)
+
+    def _move_to_mntns(
+        self, mfd: int, target: str, *, beneath: bool = False
+    ) -> None:
+        flags = MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS
+        if beneath:
+            flags |= MoveMountFlag.BENEATH
+        Sys.move_mount(mfd, "", self.mntns_fd, target, flags)
+
+    def _setup_devfs(self) -> None:
+        dev_nodes = [
+            n
+            for n in DEV_NODES
+            if os.path.exists(f"/dev/{n}")
+            and not os.path.islink(f"/dev/{n}")
+            and not os.path.isdir(f"/dev/{n}")
+        ]
+        dev_fd = self.ul.make_mount(
+            "tmpfs",
+            attr_flags=MountAttrFlag.NOSUID | MountAttrFlag.NOEXEC,
+            options={"mode": "0755"},
+        )
+        try:
+            for sub in ("pts", "shm", "mqueue"):
+                os.mkdir(sub, 0o755, dir_fd=dev_fd)
+            for node in dev_nodes:
+                os.close(
+                    os.open(
+                        node,
+                        os.O_CREAT | os.O_WRONLY | os.O_CLOEXEC,
+                        0o666,
+                        dir_fd=dev_fd,
+                    )
+                )
+            os.symlink("/proc/self/fd", "fd", dir_fd=dev_fd)
+            os.symlink("/proc/self/fd/0", "stdin", dir_fd=dev_fd)
+            os.symlink("/proc/self/fd/1", "stdout", dir_fd=dev_fd)
+            os.symlink("/proc/self/fd/2", "stderr", dir_fd=dev_fd)
+            os.symlink("pts/ptmx", "ptmx", dir_fd=dev_fd)
+            self._move_to_mntns(dev_fd, "dev")
+        finally:
+            os.close(dev_fd)
+
+        for node in dev_nodes:
+            self.bind_mount(f"/dev/{node}", f"dev/{node}")
+        self.mount_fs(
+            "tmpfs",
+            "dev/shm",
+            attr_flags=MountAttrFlag.NOSUID | MountAttrFlag.NODEV,
+        )
+        for fstype, target, attr_flags, opts in (
+            (
+                "devpts",
+                "dev/pts",
+                MountAttrFlag.NOSUID | MountAttrFlag.NOEXEC,
+                {"ptmxmode": "0666", "mode": "0620"},
+            ),
+            (
+                "mqueue",
+                "dev/mqueue",
+                (
+                    MountAttrFlag.NOSUID
+                    | MountAttrFlag.NODEV
+                    | MountAttrFlag.NOEXEC
+                ),
+                None,
+            ),
+        ):
+            try:
+                self.mount_fs(
+                    fstype, target, attr_flags=attr_flags, options=opts
+                )
+            except OSError as exc:
+                if exc.errno not in (errno.ENODEV, errno.EPERM):
+                    raise
+
+    def setup_rootfs(
+        self,
+        *,
+        dirs: Sequence[str] = ("proc", "tmp", "mnt"),
+        procfs: bool = True,
+        devfs: bool = False,
+        ro_root: bool = False,
+        host_runtime: bool = False,
+        map_self: bool = True,
+    ) -> None:
+        if map_self:
+            self.ul.map_self()
+
+        wanted = list(dirs)
+        for extra in (("dev",) if devfs else ()) + (
+            ("tmp", "run") if ro_root else ()
+        ):
+            if extra not in wanted:
+                wanted.append(extra)
+
+        fsfd = Sys.fsopen("tmpfs")
+        rootfd = -1
+        binds: list[str] = []
+        try:
+            Sys.fsconfig(fsfd, FsconfigCmd.SET_NSEXEC, aux=self.ul.fd)
+            Sys.fsconfig(fsfd, FsconfigCmd.CMD_CREATE)
+            attrs = (
+                MountAttrFlag.NOSUID | MountAttrFlag.NODEV
+                if ro_root
+                else MountAttrFlag.NONE
+            )
+            rootfd = Sys.fsmount(fsfd, attr_flags=attrs)
+            for d in wanted:
+                os.mkdir(d, 0o755, dir_fd=rootfd)
+            if host_runtime:
+                for entry in HOST_RUNTIME_DIRS:
+                    src = f"/{entry}"
+                    if os.path.islink(src):
+                        os.symlink(os.readlink(src), entry, dir_fd=rootfd)
+                    elif os.path.isdir(src):
+                        if entry not in wanted:
+                            os.mkdir(entry, 0o755, dir_fd=rootfd)
+                        binds.append(entry)
+            if ro_root:
+                Sys.fsconfig(fsfd, FsconfigCmd.SET_FLAG, key="ro")
+                Sys.fsconfig(fsfd, FsconfigCmd.CMD_RECONFIGURE)
+            self._move_to_mntns(rootfd, "/")
+        except Exception:
+            Sys.close_fd(rootfd)
+            raise
+        finally:
+            os.close(fsfd)
+
+        self.root_dfd = rootfd
+        for entry in binds:
+            self.bind_mount(f"/{entry}", entry)
+        if ro_root:
+            for rw in ("tmp", "run"):
+                self.mount_fs(
+                    "tmpfs",
+                    rw,
+                    attr_flags=MountAttrFlag.NOSUID | MountAttrFlag.NODEV,
+                )
+        if procfs and "proc" in wanted:
+            self.mount_fs(
+                "proc",
+                "proc",
+                attr_flags=(
+                    MountAttrFlag.NOSUID
+                    | MountAttrFlag.NODEV
+                    | MountAttrFlag.NOEXEC
+                ),
+            )
+        if devfs:
+            self._setup_devfs()
+
+    def mount_fs(
+        self,
+        fstype: str,
+        target: str,
+        *,
+        attr_flags: MountAttrFlag = MountAttrFlag.NONE,
+        options: Mapping[str, str | None] | None = None,
+        beneath: bool = False,
+    ) -> None:
+        mfd = self.ul.make_mount(
+            fstype, attr_flags=attr_flags, options=options
+        )
+        try:
+            self._move_to_mntns(mfd, target.lstrip("/"), beneath=beneath)
+        finally:
+            os.close(mfd)
+
+    def bind_mount(
+        self, host_src: str, target: str, *, beneath: bool = False
+    ) -> None:
+        flags = MoveMountFlag.T_MNTNS | MoveMountFlag.CLONE
+        if beneath:
+            flags |= MoveMountFlag.BENEATH
+        Sys.move_mount(
+            Sys.AT_FDCWD, host_src, self.mntns_fd, target.lstrip("/"), flags
+        )
+
+    def boot(self, timeout: float = 5.0) -> int:
+        ready_r, ready_w = os.pipe2(os.O_CLOEXEC)
+        ctrl_r, ctrl_w = os.pipe2(os.O_CLOEXEC)
+        try:
+
+            def supervisor() -> int:
+                low = 3
+                for keep_fd in sorted({ready_w, ctrl_r}):
+                    if keep_fd > low:
+                        os.closerange(low, keep_fd)
+                    low = keep_fd + 1
+                os.closerange(low, 0x7FFFFFFF)
+                Sys.prctl(PrctlOp.SET_DUMPABLE, 1)
+
+                def reap(_s: int, _f: Any) -> None:
+                    while True:
+                        try:
+                            if os.waitpid(-1, os.WNOHANG)[0] <= 0:
+                                break
+                        except ChildProcessError:
+                            break
+
+                signal.signal(signal.SIGCHLD, reap)
+                signal.signal(signal.SIGTERM, lambda _s, _f: os._exit(0))
+                if os.getpid() != 1:
+                    os._exit(125)
+                os.write(ready_w, b"R")
+                os.close(ready_w)
+                while True:
+                    try:
+                        cmd = os.read(ctrl_r, 1)
+                    except InterruptedError:
+                        continue
+                    break
+                os.close(ctrl_r)
+                return cmd[0] if cmd else 0
+
+            pid, pidfd = self.ul.spawn_fn(
+                supervisor,
+                extra_flags=(
+                    CloneFlag.PIDFD
+                    | CloneFlag.AUTOREAP
+                    | CloneFlag.CLEAR_SIGHAND
+                ),
+            )
+        except Exception:
+            for fd in (ready_r, ready_w, ctrl_r, ctrl_w):
+                Sys.close_fd(fd)
+            raise
+
+        os.close(ready_w)
+        os.close(ctrl_r)
+        try:
+            poller = select.poll()
+            poller.register(ready_r, select.POLLIN)
+            if not poller.poll(max(0, int(timeout * 1000))) or (
+                os.read(ready_r, 1) != b"R"
+            ):
+                raise RuntimeError("cell PID 1 failed startup")
+        except Exception:
+            Sys.close_fd(ctrl_w)
+            Sys.close_fd(pidfd)
+            with suppress(OSError):
+                self.ul.kill(signal.SIGKILL)
+            raise
+        finally:
+            os.close(ready_r)
+
+        self.init_pid = pid
+        self.init_pidfd = pidfd
+        self._ctrl_wfd = ctrl_w
+        return pid
+
+    def shutdown(
+        self, exit_code: int = 0, *, timeout: float = 5.0
+    ) -> WaitResult:
+        if self._ctrl_wfd >= 0:
+            with suppress(OSError):
+                os.write(self._ctrl_wfd, bytes([exit_code & 0xFF]))
+            self._ctrl_wfd = Sys.close_fd(self._ctrl_wfd)
+        deadline = time.monotonic() + timeout
+        while time.monotonic() < deadline:
+            ms = max(0, int((deadline - time.monotonic()) * 1000))
+            if self.ul.poll_dead(min(ms, 100)):
+                return self.wait(nohang=True)
+        raise TimeoutError(f"cell {self.name!r} shutdown timed out")
+
+    def exec_fn(
+        self,
+        fn: Callable[[], int | None],
+        *,
+        autokill: bool = False,
+        nnp: bool = False,
+    ) -> Session:
+        flags = CloneFlag.PIDFD | CloneFlag.AUTOREAP | CloneFlag.CLEAR_SIGHAND
+        if nnp or autokill:
+            flags |= CloneFlag.NNP
+        if autokill:
+            flags |= CloneFlag.PIDFD_AUTOKILL
+
+        def entry() -> int:
+            self._ctrl_wfd = Sys.close_fd(self._ctrl_wfd)
+            self.init_pidfd = Sys.close_fd(self.init_pidfd)
+            self.root_dfd = Sys.close_fd(self.root_dfd)
+            self.mntns_fd = Sys.close_fd(self.mntns_fd)
+            rc = fn()
+            return 0 if rc is None else int(rc)
+
+        pid, pidfd = self.ul.spawn_fn(entry, extra_flags=flags)
+        return Session(pid=pid, pidfd=pidfd, autokill=autokill)
+
+    def exec_argv(
+        self,
+        argv: Sequence[str],
+        env: Mapping[str, str] | None = None,
+        *,
+        autokill: bool = False,
+    ) -> Session:
+        bin_fd = -1
+        if self.root_dfd >= 0:
+            bin_fd = Sys.openat2(
+                self.root_dfd,
+                argv[0],
+                os.O_RDONLY | os.O_CLOEXEC,
+                resolve=ResolveFlag.IN_ROOT,
+            )
+        flags = (
+            CloneFlag.PIDFD
+            | CloneFlag.AUTOREAP
+            | CloneFlag.CLEAR_SIGHAND
+            | CloneFlag.VFORK
+        )
+        if autokill:
+            flags |= CloneFlag.NNP | CloneFlag.PIDFD_AUTOKILL
+        try:
+            pid, pidfd = self.ul.clone_into(extra_flags=flags, exit_signal=0)
+            if pid == 0:
+                try:
+                    self.close()
+                    if bin_fd >= 0:
+                        Sys.execveat(bin_fd, "", argv, env, AtFlag.EMPTY_PATH)
+                    if env is None:
+                        os.execv(argv[0], list(argv))
+                    os.execve(argv[0], list(argv), dict(env))
+                except BaseException:
+                    os._exit(127)
+            return Session(pid=pid, pidfd=pidfd, autokill=autokill)
+        finally:
+            Sys.close_fd(bin_fd)
+
+    def kill(self, sig: signal.Signals | int = signal.SIGTERM) -> None:
+        self.ul.kill(sig)
+
+    def wait(self, nohang: bool = False) -> WaitResult:
+        return self.ul.wait(os.WNOHANG if nohang else 0)
+
+    def close(self) -> None:
+        self._ctrl_wfd = Sys.close_fd(self._ctrl_wfd)
+        self.init_pidfd = Sys.close_fd(self.init_pidfd)
+        self.root_dfd = Sys.close_fd(self.root_dfd)
+        self.mntns_fd = Sys.close_fd(self.mntns_fd)
+        self.ul.close()
+
+
+class EventKind(StrEnum):
+    CELL = "cell"
+    SESSION = "session"
+
+
+@dataclass(frozen=True)
+class CellEvent:
+    kind: EventKind
+    name: str
+    pid: int
+    exit_code: int | None
+
+class CellManager:
+    """Single-loop epoll multiplexer for Cells and Sessions."""
+
+    def __init__(self) -> None:
+        self._epoll = select.epoll()
+        self._cells: dict[int, Cell] = {}
+        self._sessions: dict[int, tuple[str, Session]] = {}
+
+    def __enter__(self) -> CellManager:
+        return self
+
+    def __exit__(
+        self,
+        exc_type: type[BaseException] | None,
+        exc: BaseException | None,
+        tb: TracebackType | None,
+    ) -> None:
+        self.close()
+
+    def register_cell(self, cell: Cell) -> None:
+        fd = cell.ul.fd
+        self._epoll.register(fd, select.EPOLLIN | select.EPOLLEXCLUSIVE)
+        self._cells[fd] = cell
+
+    def register_session(self, name: str, session: Session) -> None:
+        fd = session.pidfd
+        self._epoll.register(fd, select.EPOLLIN)
+        self._sessions[fd] = (name, session)
+
+    def poll_events(self, timeout: float = 0.0) -> list[CellEvent]:
+        out: list[CellEvent] = []
+        for fd, ev in self._epoll.poll(timeout):
+            if fd in self._cells and (ev & select.EPOLLHUP):
+                cell = self._cells.pop(fd)
+                with suppress(OSError):
+                    self._epoll.unregister(fd)
+                res = cell.wait(nohang=True)
+                out.append(
+                    CellEvent(
+                        EventKind.CELL, cell.name, res.pid, res.exit_code
+                    )
+                )
+            elif fd in self._sessions and (ev & select.EPOLLIN):
+                name, sess = self._sessions.pop(fd)
+                with suppress(OSError):
+                    self._epoll.unregister(fd)
+                code = sess.wait(timeout=1.0)
+                sess.close()
+                out.append(CellEvent(EventKind.SESSION, name, sess.pid, code))
+        return out
+
+    def close(self) -> None:
+        for _, sess in list(self._sessions.values()):
+            sess.close()
+        self._sessions.clear()
+        for cell in list(self._cells.values()):
+            cell.close()
+        self._cells.clear()
+        self._epoll.close()
diff --git a/tools/testing/selftests/nsexec/config b/tools/testing/selftests/nsexec/config
new file mode 100644
index 000000000000..29ae7a268560
--- /dev/null
+++ b/tools/testing/selftests/nsexec/config
@@ -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
diff --git a/tools/testing/selftests/nsexec/machine.py b/tools/testing/selftests/nsexec/machine.py
new file mode 100644
index 000000000000..c08d5fe9143f
--- /dev/null
+++ b/tools/testing/selftests/nsexec/machine.py
@@ -0,0 +1,333 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Copyright (C) 2026 Opinsys Oy
+
+"""Choice-tape state-machine engine with deterministic shrinking.
+
+Every case is a pure function of (seed, scenario, case index): the case
+seed drives the choice tape, and shrinking is bounded by attempt count
+only, so re-running the same coordinates replays both the original
+failure and its minimal counterexample.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Iterator, Sequence
+from dataclasses import dataclass
+import hashlib
+import os
+import random
+import struct
+from typing import ClassVar, TypeVar
+
+T = TypeVar("T")
+
+
+class SkipScenario(Exception):
+    """Raised when a scenario's kernel capability or Kconfig is disabled."""
+
+
+class _StopTrace(Exception):
+    pass
+
+
+class ChoiceStream:
+    def __init__(
+        self, *, seed: int | None = None, replay: Sequence[int] | None = None
+    ) -> None:
+        self._rng = random.Random(seed) if replay is None else None
+        self._replay = list(replay) if replay is not None else None
+        self._cursor = 0
+        self.recorded: list[int] = []
+        self.step_spans: list[tuple[int, int]] = []
+        self._step_start: int | None = None
+
+    def begin_step(self) -> None:
+        self._step_start = len(self.recorded)
+
+    def end_step(self) -> None:
+        if self._step_start is not None:
+            self.step_spans.append((self._step_start, len(self.recorded)))
+            self._step_start = None
+
+    def draw_int(self, lo: int, hi: int) -> int:
+        span = hi - lo
+        if self._replay is not None:
+            if self._cursor >= len(self._replay):
+                raise _StopTrace()
+            val = min(self._replay[self._cursor], span)
+            self._cursor += 1
+        else:
+            assert self._rng is not None
+            val = self._rng.randint(0, span) if span > 0 else 0
+        self.recorded.append(val)
+        return lo + val
+
+    def draw_bool(self) -> bool:
+        return self.draw_int(0, 1) == 1
+
+    def pick(self, items: Sequence[T]) -> T:
+        return items[self.draw_int(0, len(items) - 1)]
+
+    def weighted(self, rules: Sequence[tuple[int, T]]) -> T:
+        point = self.draw_int(0, sum(w for w, _ in rules) - 1)
+        acc = 0
+        for weight, item in rules:
+            acc += weight
+            if point < acc:
+                return item
+        return rules[-1][1]
+
+
+@dataclass(frozen=True)
+class RunConfig:
+    seed: int
+    cases: int
+    steps: int | None = None
+    case: int | None = None
+
+
+@dataclass(frozen=True)
+class Failure:
+    scenario: str
+    case_name: str
+    reason: str
+    trace: tuple[str, ...]
+    case_index: int
+
+    def format_report(self, *, seed: int, cmd: str) -> str:
+        target = (
+            f"{self.scenario}.{self.case_name}"
+            if self.case_name
+            else self.scenario
+        )
+        lines = [
+            f"scenario {target} failed (case {self.case_index}):",
+            f"  reason: {self.reason}",
+        ]
+        if self.trace:
+            lines.append("  steps:")
+            lines.extend(f"    {line}" for line in self.trace)
+        lines.append(
+            f"  replay: NSEXEC_SEED=0x{seed:016x} "
+            f"NSEXEC_CASE={self.case_index} {cmd} {self.scenario}"
+        )
+        return "\n".join(lines)
+
+
+@dataclass(frozen=True)
+class CaseResult:
+    name: str
+    failure: Failure | None = None
+
+
+class ScenarioMachine:
+    STEPS: ClassVar[int] = 20
+
+    def __init__(self) -> None:
+        self.trace: list[str] = []
+        self.words: list[str] = []
+        self._step_no = 0
+        self._step_word = ""
+
+    def word(self, token: str) -> None:
+        self._step_word = token
+
+    def note(self, msg: str) -> None:
+        self.trace.append(f"[{self._step_no:02d}] {msg}")
+
+    def run_step(self, tc: ChoiceStream) -> None:
+        self._step_no += 1
+        self._step_word = ""
+        try:
+            self.step(tc)
+        finally:
+            if self._step_word:
+                self.words.append(self._step_word)
+    def step(self, tc: ChoiceStream) -> None:
+        raise NotImplementedError
+
+    def check_invariants(self) -> None:
+        pass
+
+    def close(self) -> None:
+        pass
+
+
+class Machine:
+    SHRINK_ATTEMPTS: ClassVar[int] = 48
+
+    @staticmethod
+    def parse_seed(raw: str) -> int:
+        val = int(raw.strip(), 0)
+        if val < 0 or val > 0xFFFFFFFFFFFFFFFF:
+            raise ValueError("seed must be an unsigned 64-bit integer")
+        return val
+
+    @staticmethod
+    def generate_seed() -> int:
+        return int.from_bytes(os.urandom(8), "big")
+
+    @staticmethod
+    def _case_seed(seed: int, name: str, idx: int) -> int:
+        h = hashlib.blake2b(digest_size=8)
+        h.update(struct.pack(">QQ", seed & 0xFFFFFFFFFFFFFFFF, idx))
+        h.update(name.encode("utf-8"))
+        return int.from_bytes(h.digest(), "big")
+
+    @staticmethod
+    def _open_fd_count() -> int | None:
+        try:
+            return len(os.listdir("/proc/self/fd"))
+        except OSError:
+            return None
+
+    @classmethod
+    def _exec_trace(
+        cls,
+        factory: Callable[[], ScenarioMachine],
+        tc: ChoiceStream,
+        steps: int,
+    ) -> tuple[str | None, list[str], str]:
+        fds_before = cls._open_fd_count()
+        machine = factory()
+        reason: str | None = None
+        try:
+            machine.check_invariants()
+            for _ in range(steps):
+                tc.begin_step()
+                try:
+                    machine.run_step(tc)
+                    machine.check_invariants()
+                except _StopTrace:
+                    break
+                finally:
+                    tc.end_step()
+        except SkipScenario:
+            raise
+        except AssertionError as exc:
+            reason = str(exc) or "assertion failed"
+        except Exception as exc:
+            reason = f"{type(exc).__name__}: {exc}"
+        finally:
+            trace = list(machine.trace)
+            case_name = "_".join(machine.words)
+            machine.close()
+        if reason is None and fds_before is not None:
+            fds_after = cls._open_fd_count()
+            if fds_after is not None and fds_after > fds_before:
+                reason = f"leaked {fds_after - fds_before} fd(s)"
+        return reason, trace, case_name
+
+    @classmethod
+    def _shrink(
+        cls,
+        factory: Callable[[], ScenarioMachine],
+        tc: ChoiceStream,
+        reason: str,
+        trace: list[str],
+        case_name: str,
+        steps: int,
+    ) -> tuple[str, list[str], str]:
+        """Minimise a failing tape by deleting steps, then lowering choices.
+
+        Bounded by attempt count rather than wall-clock time so that the
+        result is a function of the failing case alone.
+        """
+        recorded = list(tc.recorded)
+        spans = list(tc.step_spans)
+        attempts = 0
+
+        def accept(cand: list[int]) -> bool:
+            nonlocal attempts, recorded, spans, reason, trace, case_name
+            if attempts >= cls.SHRINK_ATTEMPTS or not cand:
+                return False
+            attempts += 1
+            ctc = ChoiceStream(replay=cand)
+            c_reason, c_trace, c_name = cls._exec_trace(factory, ctc, steps)
+            if c_reason is None:
+                return False
+            recorded = list(ctc.recorded)
+            spans = list(ctc.step_spans)
+            reason, trace, case_name = c_reason, c_trace, c_name
+            return True
+
+        chunk = max(1, len(spans) // 2)
+        while chunk >= 1 and attempts < cls.SHRINK_ATTEMPTS:
+            idx = len(spans) - chunk
+            moved = False
+            while idx >= 0 and len(spans) > 1:
+                if attempts >= cls.SHRINK_ATTEMPTS:
+                    break
+                lo, hi = spans[idx][0], spans[idx + chunk - 1][1]
+                if accept(recorded[:lo] + recorded[hi:]):
+                    moved = True
+                    idx = min(idx, len(spans) - chunk)
+                else:
+                    idx -= 1
+            if not moved:
+                chunk //= 2
+
+        pos = 0
+        while pos < len(recorded) and attempts < cls.SHRINK_ATTEMPTS:
+            cur = recorded[pos]
+            if cur > 0:
+                c0 = list(recorded)
+                c0[pos] = 0
+                if not accept(c0) and cur > 1:
+                    ch = list(recorded)
+                    ch[pos] = cur // 2
+                    accept(ch)
+            pos += 1
+
+        return reason, trace, case_name
+
+    @classmethod
+    def iter_cases(
+        cls,
+        scenario: str,
+        machine_cls: type[ScenarioMachine],
+        config: RunConfig,
+        *,
+        progress: Callable[[str], None] | None = None,
+    ) -> Iterator[CaseResult]:
+        steps = machine_cls.STEPS if config.steps is None else config.steps
+        indices = (
+            range(config.cases) if config.case is None else (config.case,)
+        )
+        shrunk_once = False
+        for idx in indices:
+            if progress is not None:
+                progress(f"case {idx}")
+            tc = ChoiceStream(seed=cls._case_seed(config.seed, scenario, idx))
+            reason, trace, case_name = cls._exec_trace(machine_cls, tc, steps)
+            if reason is None:
+                yield CaseResult(case_name)
+                continue
+            if not shrunk_once:
+                shrunk_once = True
+                if progress is not None:
+                    progress("shrinking")
+                reason, trace, case_name = cls._shrink(
+                    machine_cls, tc, reason, trace, case_name, steps
+                )
+            yield CaseResult(
+                case_name,
+                Failure(scenario, case_name, reason, tuple(trace), idx),
+            )
+
+    @classmethod
+    def run(
+        cls,
+        scenario: str,
+        machine_cls: type[ScenarioMachine],
+        config: RunConfig,
+        *,
+        progress: Callable[[str], None] | None = None,
+    ) -> Failure | None:
+        for res in cls.iter_cases(
+            scenario, machine_cls, config, progress=progress
+        ):
+            if res.failure is not None:
+                return res.failure
+        return None
diff --git a/tools/testing/selftests/nsexec/oracle.py b/tools/testing/selftests/nsexec/oracle.py
new file mode 100644
index 000000000000..ab643bfaff00
--- /dev/null
+++ b/tools/testing/selftests/nsexec/oracle.py
@@ -0,0 +1,386 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Copyright (C) 2026 Opinsys Oy
+
+"""Reference shadow state and uAPI decision oracle for nsexec(2)."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from enum import Enum, auto
+import errno
+import os
+from typing import Final
+
+from cells import (
+    CloneArgs,
+    CloneFlag,
+    SHAREABLE_NSTYPES,
+    NsExecFlag,
+    UsernsFlag,
+    UsernsIdmap,
+)
+
+PAGE_SIZE: Final[int] = int(os.sysconf("SC_PAGE_SIZE"))
+
+GET_NSFD_TYPES: Final[frozenset[int]] = frozenset(
+    int(f)
+    for f in (
+        CloneFlag.NEWNS,
+        CloneFlag.NEWCGROUP,
+        CloneFlag.NEWUTS,
+        CloneFlag.NEWIPC,
+        CloneFlag.NEWUSER,
+        CloneFlag.NEWPID,
+        CloneFlag.NEWNET,
+        CloneFlag.NEWTIME,
+    )
+)
+
+SHARE_NSFD_TYPES: Final[frozenset[int]] = frozenset(
+    int(f) for f in SHAREABLE_NSTYPES
+)
+
+NSEXEC_MOUNT_FS: Final[frozenset[str]] = frozenset(
+    ("tmpfs", "ramfs", "proc", "devpts", "mqueue")
+)
+
+ALLOWED_CLONE_EXTRA: Final[int] = int(
+    CloneFlag.VFORK
+    | CloneFlag.PIDFD
+    | CloneFlag.CLEAR_SIGHAND
+    | CloneFlag.INTO_CGROUP
+    | CloneFlag.AUTOREAP
+    | CloneFlag.NNP
+    | CloneFlag.PIDFD_AUTOKILL
+)
+
+
+class State(Enum):
+    INIT = auto()
+    RUNNING = auto()
+    DEAD = auto()
+
+
+class FdKind(Enum):
+    NSEXEC = auto()
+    CLOSED = auto()
+    NS_USER = auto()
+    NS_MNT = auto()
+    NS_SHAREABLE = auto()
+    NS_PID = auto()
+    OTHER = auto()
+
+
+@dataclass(frozen=True)
+class Actor:
+    owner: bool = True
+    ancestor_pidns: bool = True
+    pidns_alive: bool = True
+    unpriv: bool = False
+    can_allow_setgroups: bool = False
+    parent_setid: bool = False
+    parent_setfcap: bool = True
+    landlock_mask: int | None = None
+
+
+@dataclass
+class UnitModel:
+    state: State = State.INIT
+    autokill: bool = True
+    uid_mapped: bool = False
+    gid_mapped: bool = False
+    projid_mapped: bool = False
+    has_root: bool = False
+    has_dirs: bool = False
+    shared_host_mask: int = 0
+    foreign_shared_ns: bool = False
+    mount_depth: dict[str, int] = field(
+        default_factory=lambda: {"mnt": 0, "tmp": 0, "proc": 0}
+    )
+
+
+class Oracle:
+    """Predicts exact kernel errno (or None for success) from model state."""
+
+    @staticmethod
+    def open(actor: Actor, flags: int, active_ns_mask: int) -> int | None:
+        if flags & ~int(NsExecFlag.ALL):
+            return errno.EINVAL
+        if actor.landlock_mask is not None and (
+            active_ns_mask & ~actor.landlock_mask
+        ):
+            return errno.EPERM
+        return None
+
+    @staticmethod
+    def get_nsfd(
+        actor: Actor,
+        unit: UnitModel,
+        fd_kind: FdKind,
+        nstype: int,
+        *,
+        has_timens: bool,
+    ) -> int | None:
+        if fd_kind == FdKind.CLOSED:
+            return errno.EBADF
+        if fd_kind != FdKind.NSEXEC:
+            return errno.ENOTTY
+        if nstype < 0 or nstype > 0xFFFFFFFF:
+            return errno.EINVAL
+        if not actor.owner:
+            return errno.EPERM
+        if nstype == int(CloneFlag.NEWPID):
+            if not actor.ancestor_pidns:
+                return errno.EXDEV
+            return None if unit.state == State.RUNNING else errno.ESRCH
+        if nstype == int(CloneFlag.NEWTIME) and not has_timens:
+            return errno.EOPNOTSUPP
+        if nstype not in GET_NSFD_TYPES:
+            return errno.EINVAL
+        return None
+
+    @staticmethod
+    def share_nsfd(
+        actor: Actor,
+        unit: UnitModel,
+        ns_kind: FdKind,
+        nstype: int,
+        *,
+        ns_usable: bool = True,
+        has_timens: bool = True,
+    ) -> int | None:
+        if ns_kind == FdKind.CLOSED:
+            return errno.EBADF
+        if ns_kind not in (
+            FdKind.NS_USER,
+            FdKind.NS_MNT,
+            FdKind.NS_SHAREABLE,
+            FdKind.NS_PID,
+        ):
+            return errno.EINVAL
+        if nstype == int(CloneFlag.NEWTIME) and not has_timens:
+            return errno.EOPNOTSUPP
+        if nstype not in SHARE_NSFD_TYPES:
+            return errno.EINVAL
+        if not actor.owner or not ns_usable:
+            return errno.EPERM
+        if actor.landlock_mask is not None and not (
+            actor.landlock_mask & nstype
+        ):
+            return errno.EPERM
+        if unit.state != State.INIT:
+            return errno.EBUSY
+        return None
+
+    @staticmethod
+    def set_idmap(
+        actor: Actor,
+        unit: UnitModel,
+        fd_kind: FdKind,
+        *,
+        opener_capable: bool = True,
+        maps_host_root: bool = False,
+        multi_extent: bool = False,
+        size: int = UsernsIdmap.SIZE_VER0,
+        flags: int = 0,
+        reserved: int = 0,
+        null_map: bool = False,
+        ptr_mismatch: bool = False,
+        uid_valid: bool | None = None,
+        gid_valid: bool | None = None,
+        projid_valid: bool | None = None,
+    ) -> int | None:
+        if flags & ~int(UsernsFlag.SETGROUPS_ALLOWED):
+            return errno.EINVAL
+        if fd_kind == FdKind.CLOSED:
+            return errno.EBADF
+        if fd_kind != FdKind.NS_USER:
+            return errno.EINVAL
+        if null_map or size < UsernsIdmap.SIZE_VER0:
+            return errno.EINVAL
+        if size > PAGE_SIZE:
+            return errno.E2BIG
+        if reserved or ptr_mismatch:
+            return errno.EINVAL
+        if uid_valid is None and gid_valid is None and projid_valid is None:
+            return errno.EINVAL
+        if (flags & int(UsernsFlag.SETGROUPS_ALLOWED)) and gid_valid is None:
+            return errno.EINVAL
+        if not actor.owner and not opener_capable:
+            return errno.EPERM
+        if uid_valid is False or gid_valid is False or projid_valid is False:
+            return errno.EINVAL
+        if (
+            (uid_valid and unit.uid_mapped)
+            or (gid_valid and unit.gid_mapped)
+            or (projid_valid and unit.projid_mapped)
+        ):
+            return errno.EPERM
+        if (
+            flags & int(UsernsFlag.SETGROUPS_ALLOWED)
+        ) and not actor.can_allow_setgroups:
+            return errno.EPERM
+        if maps_host_root and not actor.parent_setfcap:
+            return errno.EPERM
+        if multi_extent and not actor.parent_setid:
+            return errno.EPERM
+        return None
+
+    @staticmethod
+    def fsconfig_nsexec(
+        actor: Actor,
+        aux_kind: FdKind,
+        fstype: str,
+        *,
+        already_bound: bool = False,
+    ) -> int | None:
+        if aux_kind == FdKind.CLOSED:
+            return errno.EBADF
+        if already_bound:
+            return errno.EBUSY
+        if aux_kind != FdKind.NSEXEC:
+            return errno.EINVAL
+        if not actor.owner:
+            return errno.EPERM
+        if fstype not in NSEXEC_MOUNT_FS:
+            return errno.EOPNOTSUPP
+        if fstype == "proc" and not actor.ancestor_pidns:
+            return errno.EINVAL
+        return None
+
+    @staticmethod
+    def move_mount(
+        actor: Actor,
+        unit: UnitModel,
+        *,
+        src_same_unit: bool = True,
+        src_nouser: bool = False,
+        target: str = "/",
+        t_mntns: bool = True,
+        clone: bool = False,
+        beneath: bool = False,
+        set_group: bool = False,
+    ) -> int | None:
+        if clone and not t_mntns:
+            return errno.EINVAL
+        if (beneath and set_group) or (t_mntns and set_group):
+            return errno.EINVAL
+        if not actor.owner:
+            return errno.EPERM
+        if target == "/":
+            if beneath:
+                return errno.EINVAL
+            if unit.has_root:
+                return errno.EBUSY
+            return errno.EINVAL if (src_nouser or not src_same_unit) else None
+        if not unit.has_root:
+            return errno.ENOENT
+        if target == ".":
+            return errno.EINVAL if beneath else errno.EBUSY
+        if not unit.has_dirs:
+            return errno.ENOENT
+        if target == "tmp/..":
+            return errno.EINVAL if beneath else errno.EBUSY
+        if beneath and unit.mount_depth.get(target, 0) == 0:
+            return errno.EINVAL
+        if src_nouser or not src_same_unit:
+            return errno.EINVAL
+        return None
+
+    @staticmethod
+    def clone_into(
+        actor: Actor,
+        unit: UnitModel,
+        fd_kind: FdKind,
+        *,
+        size: int = CloneArgs.SIZE_VER3,
+        extra_flags: int = 0,
+        exit_signal: int = 17,
+        active_ns_mask: int = 0,
+    ) -> int | None:
+        if size > PAGE_SIZE:
+            return errno.E2BIG
+        if size < CloneArgs.SIZE_VER3:
+            return errno.EINVAL
+        if extra_flags & ~ALLOWED_CLONE_EXTRA:
+            return errno.EINVAL
+        if exit_signal < 0 or exit_signal > 64:
+            return errno.EINVAL
+        if fd_kind == FdKind.CLOSED:
+            return errno.EBADF
+        if fd_kind != FdKind.NSEXEC:
+            return errno.EINVAL
+        if not actor.owner:
+            return errno.EPERM
+        if not actor.ancestor_pidns:
+            return errno.EXDEV
+        if not unit.has_root:
+            return errno.ENOENT
+        if unit.state == State.DEAD or not actor.pidns_alive:
+            return errno.ESRCH
+        if unit.foreign_shared_ns:
+            return errno.EPERM
+        if actor.landlock_mask is not None:
+            required = int(
+                CloneFlag.NEWUSER | CloneFlag.NEWNS | CloneFlag.NEWPID
+            ) | (active_ns_mask & ~unit.shared_host_mask)
+            if required & ~actor.landlock_mask:
+                return errno.EPERM
+        if (extra_flags & int(CloneFlag.AUTOREAP)) and exit_signal != 0:
+            return errno.EINVAL
+        if extra_flags & int(CloneFlag.PIDFD_AUTOKILL):
+            need = int(CloneFlag.PIDFD | CloneFlag.AUTOREAP)
+            if (extra_flags & need) != need:
+                return errno.EINVAL
+            if not (extra_flags & int(CloneFlag.NNP)) and actor.unpriv:
+                return errno.EPERM
+        return None
+
+    @staticmethod
+    def send_signal(
+        actor: Actor,
+        unit: UnitModel,
+        fd_kind: FdKind,
+        *,
+        sig: int,
+        has_info: bool = False,
+        flags: int = 0,
+    ) -> int | None:
+        if fd_kind != FdKind.NSEXEC:
+            return errno.EBADF
+        if has_info or flags or sig < 0 or sig > 64:
+            return errno.EINVAL
+        if not actor.ancestor_pidns:
+            return errno.EXDEV
+        if unit.state != State.RUNNING:
+            return errno.ESRCH
+        return None
+
+    @staticmethod
+    def waitid(
+        actor: Actor,
+        unit: UnitModel,
+        fd_kind: FdKind,
+        *,
+        neg_fd: bool = False,
+        options: int = os.WEXITED,
+        has_rusage: bool = False,
+        nonblock: bool = False,
+    ) -> int | None:
+        if neg_fd or has_rusage:
+            return errno.EINVAL
+        if options & ~(os.WEXITED | os.WNOHANG | os.WNOWAIT):
+            return errno.EINVAL
+        if not (options & os.WEXITED):
+            return errno.EINVAL
+        if fd_kind != FdKind.NSEXEC:
+            return errno.EBADF
+        if not actor.ancestor_pidns or unit.state == State.INIT:
+            return errno.ECHILD
+        if unit.state == State.RUNNING:
+            if options & os.WNOHANG:
+                return None
+            if nonblock:
+                return errno.EAGAIN
+        return None
diff --git a/tools/testing/selftests/nsexec/selftest.py b/tools/testing/selftests/nsexec/selftest.py
new file mode 100755
index 000000000000..7acf89ff7912
--- /dev/null
+++ b/tools/testing/selftests/nsexec/selftest.py
@@ -0,0 +1,2887 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+#
+# Copyright (C) 2026 Opinsys Oy
+
+"""Parametric model-based selftest suite for nsexec(2) and Cells."""
+
+from __future__ import annotations
+
+import argparse
+from collections.abc import Callable, Sequence
+from contextlib import ExitStack, suppress
+import ctypes
+from dataclasses import dataclass, field
+import errno
+import importlib
+import os
+from pathlib import Path
+import pty
+import select
+import signal
+import socket
+import struct
+import sys
+import tempfile
+import time
+import traceback
+from typing import Any, ClassVar, Final, TypeVar
+
+from cells import (
+    Cell,
+    CellManager,
+    CloneArgs,
+    CloneFlag,
+    EventKind,
+    FsconfigCmd,
+    Ioctl,
+    MoveMountFlag,
+    NS_NAMES,
+    PrctlOp,
+    SHAREABLE_NSTYPES,
+    Session,
+    Sys,
+    UmountFlag,
+    NsExec,
+    NsExecFlag,
+    UsernsFlag,
+    UsernsIdmap,
+    WaitIdType,
+    WaitResult,
+)
+from machine import (
+    ChoiceStream,
+    Machine,
+    RunConfig,
+    ScenarioMachine,
+    SkipScenario,
+)
+from oracle import (
+    Actor,
+    FdKind,
+    Oracle,
+    PAGE_SIZE,
+    State,
+    UnitModel,
+)
+
+PYTHON_BIN: Final[str] = os.path.realpath(sys.executable or "/proc/self/exe")
+SKIP_ERRNOS: Final[tuple[int, ...]] = (
+    errno.ENOSYS,
+    errno.EPERM,
+    errno.EACCES,
+    errno.EINVAL,
+    errno.ENOSPC,
+)
+PIDFD_NS_IOCTLS: Final[dict[CloneFlag, Ioctl]] = {
+    CloneFlag.NEWNS: Ioctl.PIDFD_GET_MNT_NAMESPACE,
+    CloneFlag.NEWCGROUP: Ioctl.PIDFD_GET_CGROUP_NAMESPACE,
+    CloneFlag.NEWUTS: Ioctl.PIDFD_GET_UTS_NAMESPACE,
+    CloneFlag.NEWIPC: Ioctl.PIDFD_GET_IPC_NAMESPACE,
+    CloneFlag.NEWUSER: Ioctl.PIDFD_GET_USER_NAMESPACE,
+    CloneFlag.NEWPID: Ioctl.PIDFD_GET_PID_NAMESPACE,
+    CloneFlag.NEWNET: Ioctl.PIDFD_GET_NET_NAMESPACE,
+    CloneFlag.NEWTIME: Ioctl.PIDFD_GET_TIME_NAMESPACE,
+}
+
+
+_T = TypeVar("_T")
+
+
+class NsExecMachine(ScenarioMachine):
+    @staticmethod
+    def reap_pid(pid: int) -> int:
+        _, status = os.waitpid(pid, 0)
+        return os.waitstatus_to_exitcode(status)
+
+    @staticmethod
+    def drop_to_uid(uid: int) -> None:
+        try:
+            Sys.setgroups_empty()
+        except OSError as exc:
+            if exc.errno != errno.EPERM:
+                raise
+        os.setresgid(uid, uid, uid)
+        os.setresuid(uid, uid, uid)
+        Sys.prctl(PrctlOp.SET_DUMPABLE, 1)
+
+    @staticmethod
+    def enter_userns_if_unpriv() -> None:
+        if os.geteuid() == 0:
+            return
+        uid, gid = os.geteuid(), os.getegid()
+        Sys.unshare(CloneFlag.NEWUSER | CloneFlag.NEWNS)
+        Path("/proc/self/setgroups").write_bytes(b"deny\n")
+        Path("/proc/self/uid_map").write_bytes(f"0 {uid} 1\n".encode("ascii"))
+        Path("/proc/self/gid_map").write_bytes(f"0 {gid} 1\n".encode("ascii"))
+
+    @classmethod
+    def run_isolated(cls, fn: Callable[[], object]) -> None:
+        r_fd, w_fd = os.pipe2(os.O_CLOEXEC)
+        pid = Sys.fork()
+        if pid == 0:
+            os.close(r_fd)
+            try:
+                fn()
+            except SkipScenario as exc:
+                os.write(w_fd, f"SKIP:{exc}".encode("utf-8", errors="replace"))
+                os.close(w_fd)
+                os._exit(0)
+            except BaseException as exc:
+                msg = (
+                    str(exc)
+                    if isinstance(exc, AssertionError)
+                    else traceback.format_exc()
+                )
+                os.write(w_fd, msg.encode("utf-8", errors="replace"))
+                os.close(w_fd)
+                os._exit(1)
+            os.close(w_fd)
+            os._exit(0)
+        os.close(w_fd)
+        chunks: list[bytes] = []
+        while True:
+            buf = os.read(r_fd, 4096)
+            if not buf:
+                break
+            chunks.append(buf)
+        os.close(r_fd)
+        rc = cls.reap_pid(pid)
+        text = b"".join(chunks).decode("utf-8", errors="replace").strip()
+        if text.startswith("SKIP:"):
+            raise SkipScenario(text[5:])
+        if text or rc != 0:
+            raise AssertionError(text or f"isolated child exited {rc}")
+
+    @classmethod
+    def run_in_foreign_pidns(
+        cls, ul: NsExec, fn: Callable[[], object]
+    ) -> None:
+        def outer() -> None:
+            ufd = ul.get_nsfd(CloneFlag.NEWUSER)
+            try:
+                Sys.setns(ufd, CloneFlag.NEWUSER)
+            finally:
+                os.close(ufd)
+            Sys.unshare(CloneFlag.NEWPID)
+            cls.run_isolated(fn)
+
+        cls.run_isolated(outer)
+
+    @classmethod
+    def create_nsexec_as_uid(cls, uid: int) -> NsExec | None:
+        s_p, s_c = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET)
+        pid = Sys.fork()
+        if pid == 0:
+            s_p.close()
+            try:
+                cls.drop_to_uid(uid)
+                with NsExec() as ul:
+                    ul.send(s_c)
+                os._exit(0)
+            except OSError as exc:
+                os._exit(0 if exc.errno in SKIP_ERRNOS else 1)
+            finally:
+                s_c.close()
+        s_c.close()
+        got: NsExec | None = None
+        try:
+            if select.select([s_p], [], [], 5.0)[0]:
+                _, fds, _, _ = socket.recv_fds(s_p, 1, 1)
+                if fds:
+                    got = NsExec.from_fd(fds[0])
+        finally:
+            s_p.close()
+        if cls.reap_pid(pid) != 0:
+            if got is not None:
+                got.close()
+            raise AssertionError(f"failed creating nsexec as uid {uid}")
+        return got
+
+    @staticmethod
+    def check_call(
+        what: str, exp_errno: int | None, fn: Callable[[], _T]
+    ) -> _T | None:
+        try:
+            res = fn()
+        except OSError as exc:
+            if exp_errno is None:
+                raise AssertionError(
+                    f"{what}: expected success, got {exc}"
+                ) from exc
+            if exc.errno != exp_errno:
+                exp_name = errno.errorcode.get(exp_errno, str(exp_errno))
+                got_name = errno.errorcode.get(exc.errno or 0, str(exc.errno))
+                raise AssertionError(
+                    f"{what}: expected {exp_name}, got {got_name} ({exc})"
+                ) from exc
+            return None
+        if exp_errno is not None:
+            exp_name = errno.errorcode.get(exp_errno, str(exp_errno))
+            raise AssertionError(
+                f"{what}: expected {exp_name}, succeeded with {res!r}"
+            )
+        return res
+
+
+@dataclass
+class LiveWorker:
+    pid: int
+    pidfd: int
+    ctrl_w: int
+    autoreap: bool
+    autokill: bool
+
+
+@dataclass
+class LiveUnit:
+    label: str
+    model: UnitModel
+    fds: list[int]
+    mntns_fd: int
+    ns_ids: dict[CloneFlag, os.stat_result]
+    root_dfd: int = -1
+    init_pid: int = 0
+    init_pidfd: int = -1
+    init_ctrl_w: int = -1
+    init_autoreap: bool = True
+    init_reaped: bool = False
+    expected_wait: WaitResult | None = None
+    workers: list[LiveWorker] = field(default_factory=list)
+
+    def ul_view(self, idx: int = 0) -> NsExec:
+        return NsExec.from_fd(self.fds[idx])
+
+
+class Lifecycle(NsExecMachine):
+    """Parametric model for nsexec lifecycle, fds, clone, and wait."""
+
+    STEPS: ClassVar[int] = 24
+    MAX_UNITS: ClassVar[int] = 4
+
+    def __init__(self) -> None:
+        super().__init__()
+        self._units: list[LiveUnit] = []
+        self._seq = 0
+        self._has_timens = os.path.exists("/proc/self/ns/time")
+        self._unpriv = os.geteuid() != 0
+        self._host_ns: dict[CloneFlag, tuple[int, os.stat_result]] = {}
+        for nstype in SHAREABLE_NSTYPES:
+            if nstype == CloneFlag.NEWTIME and not self._has_timens:
+                continue
+            path = f"/proc/self/ns/{NS_NAMES[nstype]}"
+            if os.path.exists(path):
+                fd = os.open(path, os.O_RDONLY | os.O_CLOEXEC)
+                self._host_ns[nstype] = (fd, os.fstat(fd))
+
+    def _active_nstypes(self) -> tuple[CloneFlag, ...]:
+        out = [
+            CloneFlag.NEWNS,
+            CloneFlag.NEWCGROUP,
+            CloneFlag.NEWUTS,
+            CloneFlag.NEWIPC,
+            CloneFlag.NEWUSER,
+            CloneFlag.NEWNET,
+        ]
+        if self._has_timens:
+            out.append(CloneFlag.NEWTIME)
+        return tuple(out)
+
+    def _active_mask(self) -> int:
+        mask = int(CloneFlag.NEWPID)
+        for nst in self._active_nstypes():
+            mask |= int(nst)
+        return mask
+
+    def _close_harness_fds(self) -> None:
+        for u in self._units:
+            for fd in u.fds:
+                Sys.close_fd(fd)
+            for w in u.workers:
+                Sys.close_fd(w.pidfd)
+                Sys.close_fd(w.ctrl_w)
+            Sys.close_fd(u.init_pidfd)
+            Sys.close_fd(u.init_ctrl_w)
+            Sys.close_fd(u.root_dfd)
+            Sys.close_fd(u.mntns_fd)
+        for fd, _ in self._host_ns.values():
+            Sys.close_fd(fd)
+    def _open_units(self) -> list[LiveUnit]:
+        return [u for u in self._units if u.fds]
+
+    def _ensure_root(self, unit: LiveUnit) -> None:
+        ul = unit.ul_view()
+        if not unit.model.uid_mapped or not unit.model.gid_mapped:
+            u_ext = () if unit.model.uid_mapped else ((0, os.geteuid(), 1),)
+            g_ext = () if unit.model.gid_mapped else ((0, os.getegid(), 1),)
+            ul.set_idmap(uid_extents=u_ext, gid_extents=g_ext)
+            unit.model.uid_mapped = True
+            unit.model.gid_mapped = True
+        if not unit.model.has_root:
+            rfd = ul.make_mount("tmpfs")
+            try:
+                for d in ("proc", "tmp", "mnt"):
+                    os.mkdir(d, 0o755, dir_fd=rfd)
+                Sys.move_mount(
+                    rfd,
+                    "",
+                    unit.mntns_fd,
+                    "/",
+                    MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+                )
+            except Exception:
+                os.close(rfd)
+                raise
+            unit.root_dfd = rfd
+            unit.model.has_root = True
+            unit.model.has_dirs = True
+
+    def _sync_death(self, unit: LiveUnit, code: int, status: int) -> None:
+        for w in unit.workers:
+            if w.autokill:
+                w.pidfd = Sys.close_fd(w.pidfd)
+            else:
+                w.ctrl_w = Sys.close_fd(w.ctrl_w)
+                if not w.autoreap and w.pid > 0:
+                    with suppress(ChildProcessError, OSError):
+                        self.reap_pid(w.pid)
+                    w.pid = 0
+            w.ctrl_w = Sys.close_fd(w.ctrl_w)
+            w.pidfd = Sys.close_fd(w.pidfd)
+        unit.workers.clear()
+        unit.init_ctrl_w = Sys.close_fd(unit.init_ctrl_w)
+
+        if unit.fds:
+            if not unit.ul_view().poll_dead(5000):
+                raise AssertionError(f"{unit.label}: missing POLLHUP on DEAD")
+        elif unit.init_pidfd >= 0:
+            poller = select.poll()
+            poller.register(unit.init_pidfd, select.POLLIN)
+            if not poller.poll(5000):
+                raise AssertionError(f"{unit.label}: init pidfd did not exit")
+
+        unit.model.state = State.DEAD
+        unit.expected_wait = WaitResult(
+            pid=unit.init_pid, status=status, code=code, uid=os.geteuid()
+        )
+
+    def _rule_open(self, tc: ChoiceStream) -> None:
+        flags = (
+            tc.pick((0, 1))
+            if len(self._units) < self.MAX_UNITS and tc.draw_int(0, 4) > 0
+            else tc.pick((0x2, 0x4, 0x100, 0x80000000))
+        )
+        exp = Oracle.open(Actor(), flags, self._active_mask())
+        self.word("open")
+        self.note(f"nsexec_open(0x{flags:x}) -> {exp or 'ok'}")
+        ul = self.check_call("nsexec_open", exp, lambda: NsExec(flags))
+        if ul is None:
+            return
+        if os.get_inheritable(ul.fd):
+            raise AssertionError("nsexec_open() missing O_CLOEXEC")
+        mntns_fd = ul.get_nsfd(CloneFlag.NEWNS)
+        ns_ids: dict[CloneFlag, os.stat_result] = {}
+        for nst in self._active_nstypes():
+            nfd = ul.get_nsfd(nst)
+            try:
+                ns_ids[nst] = os.fstat(nfd)
+            finally:
+                os.close(nfd)
+        label = f"u{self._seq}"
+        self._seq += 1
+        self._units.append(
+            LiveUnit(
+                label=label,
+                model=UnitModel(
+                    autokill=bool(flags & int(NsExecFlag.AUTOKILL))
+                ),
+                fds=[ul.fd],
+                mntns_fd=mntns_fd,
+                ns_ids=ns_ids,
+            )
+        )
+
+    def _rule_dup_or_close(self, tc: ChoiceStream) -> None:
+        avail = self._open_units()
+        if not avail:
+            self._rule_open(tc)
+            return
+        unit = tc.pick(avail)
+        if len(unit.fds) < 3 and tc.draw_bool():
+            src = tc.pick(unit.fds)
+            if tc.draw_bool():
+                unit.fds.append(os.dup(src))
+                self.word("dup")
+                self.note(f"{unit.label}: dup -> {len(unit.fds)} fds")
+            else:
+                s_a, s_b = socket.socketpair(
+                    socket.AF_UNIX, socket.SOCK_SEQPACKET
+                )
+                try:
+                    NsExec.from_fd(src).send(s_a)
+                    unit.fds.append(NsExec.recv(s_b).fd)
+                finally:
+                    s_a.close()
+                    s_b.close()
+                self.word("scm")
+                self.note(f"{unit.label}: scm_rights -> {len(unit.fds)} fds")
+            return
+
+        fd = unit.fds.pop(tc.draw_int(0, len(unit.fds) - 1))
+        was_running = unit.model.state == State.RUNNING
+        os.close(fd)
+        self.word("close")
+        self.note(
+            f"{unit.label}: close_fd (rem={len(unit.fds)}, "
+            f"autokill={unit.model.autokill})"
+        )
+        if not unit.fds and was_running:
+            if unit.model.autokill:
+                self._sync_death(unit, os.CLD_KILLED, int(signal.SIGKILL))
+                if not unit.init_autoreap and not unit.init_reaped:
+                    if self.reap_pid(unit.init_pid) != -int(signal.SIGKILL):
+                        raise AssertionError("expected -SIGKILL on AUTOKILL")
+                    unit.init_reaped = True
+            elif unit.init_pidfd >= 0:
+                poller = select.poll()
+                poller.register(unit.init_pidfd, select.POLLIN)
+                if poller.poll(0):
+                    raise AssertionError("init died without AUTOKILL")
+
+    def _rule_get_nsfd(self, tc: ChoiceStream) -> None:
+        avail = self._open_units()
+        if not avail:
+            self._rule_open(tc)
+            return
+        unit = tc.pick(avail)
+        self.word("nsfd")
+        fd_kind = tc.weighted(
+            ((8, FdKind.NSEXEC), (1, FdKind.CLOSED), (1, FdKind.NS_MNT))
+        )
+        nstype = tc.pick(
+            (
+                *(int(f) for f in self._active_nstypes()),
+                int(CloneFlag.NEWPID),
+                0,
+                int(CloneFlag.VM),
+                0x1FFFFFFFF,
+            )
+        )
+        foreign_pidns = (
+            fd_kind == FdKind.NSEXEC
+            and nstype == int(CloneFlag.NEWPID)
+            and tc.draw_int(0, 4) == 0
+        )
+        actor = Actor(ancestor_pidns=not foreign_pidns)
+        exp = Oracle.get_nsfd(
+            actor,
+            unit.model,
+            fd_kind,
+            nstype,
+            has_timens=self._has_timens,
+        )
+        target_fd = (
+            tc.pick(unit.fds)
+            if fd_kind == FdKind.NSEXEC
+            else (99999 if fd_kind == FdKind.CLOSED else unit.mntns_fd)
+        )
+        self.note(
+            f"{unit.label}: get_nsfd(kind={fd_kind.name}, 0x{nstype:x}, "
+            f"foreign_pidns={foreign_pidns}) -> {exp or 'ok'}"
+        )
+
+        def invoke() -> None:
+            nsfd = self.check_call(
+                "get_nsfd",
+                exp,
+                lambda: Sys.ioctl(target_fd, Ioctl.NSEXEC_GET_NSFD, nstype),
+            )
+            if nsfd is not None:
+                try:
+                    if Sys.ioctl(nsfd, Ioctl.NS_GET_NSTYPE) != nstype:
+                        raise AssertionError("NS_GET_NSTYPE mismatch")
+                    if not os.path.samestat(
+                        os.fstat(nsfd), unit.ns_ids[CloneFlag(nstype)]
+                    ):
+                        raise AssertionError("nsfd inode mismatch")
+                finally:
+                    os.close(nsfd)
+
+        if foreign_pidns:
+            if not unit.model.uid_mapped:
+                self._ensure_root(unit)
+            self.run_in_foreign_pidns(unit.ul_view(), invoke)
+        else:
+            invoke()
+
+    def _rule_share_nsfd(self, tc: ChoiceStream) -> None:
+        avail = self._open_units()
+        if not avail:
+            self._rule_open(tc)
+            return
+        unit = tc.pick(avail)
+        self.word("share")
+        ul = unit.ul_view(tc.draw_int(0, len(unit.fds) - 1))
+        src_choice = tc.weighted(
+            (
+                (6, "host"),
+                (4, "peer"),
+                (2, "unshareable"),
+                (1, "non_nsfs"),
+                (1, "closed"),
+            )
+        )
+        close_arg = False
+        src_id: os.stat_result | None = None
+        from_host = False
+
+        if src_choice == "closed":
+            ns_kind, nstype, arg_fd = FdKind.CLOSED, 0, 99999
+        elif src_choice == "non_nsfs":
+            ns_kind, nstype, arg_fd = FdKind.NSEXEC, 0, ul.fd
+        elif src_choice == "unshareable":
+            flag = tc.pick((CloneFlag.NEWUSER, CloneFlag.NEWNS))
+            ns_kind = (
+                FdKind.NS_USER if flag == CloneFlag.NEWUSER else FdKind.NS_MNT
+            )
+            nstype = int(flag)
+            arg_fd = ul.get_nsfd(flag)
+            close_arg = True
+        else:
+            shareable = tuple(self._host_ns.keys())
+            flag = tc.pick(shareable)
+            ns_kind, nstype = FdKind.NS_SHAREABLE, int(flag)
+            peers = [u for u in avail if u is not unit]
+            if src_choice == "peer" and peers:
+                peer = tc.pick(peers)
+                arg_fd = peer.ul_view().get_nsfd(flag)
+                src_id = peer.ns_ids[flag]
+                close_arg = True
+            else:
+                arg_fd, src_id = self._host_ns[flag]
+                from_host = True
+
+        try:
+            exp = Oracle.share_nsfd(
+                Actor(),
+                unit.model,
+                ns_kind,
+                nstype,
+                has_timens=self._has_timens,
+            )
+            self.note(
+                f"{unit.label}: share_nsfd({src_choice}, 0x{nstype:x}) "
+                f"in {unit.model.state.name} -> {exp or 'ok'}"
+            )
+            self.check_call("share_nsfd", exp, lambda: ul.share_nsfd(arg_fd))
+            if exp is None and src_id is not None:
+                cflag = CloneFlag(nstype)
+                unit.ns_ids[cflag] = src_id
+                if from_host:
+                    unit.model.shared_host_mask |= nstype
+                else:
+                    unit.model.shared_host_mask &= ~nstype
+        finally:
+            if close_arg:
+                os.close(arg_fd)
+
+    def _spawn_init(self, unit: LiveUnit, autoreap: bool, nnp: bool) -> None:
+        ul = unit.ul_view()
+        ready_r, ready_w = os.pipe2(os.O_CLOEXEC)
+        ctrl_r, ctrl_w = os.pipe2(os.O_CLOEXEC)
+        flags = CloneFlag.PIDFD | CloneFlag.CLEAR_SIGHAND
+        if autoreap:
+            flags |= CloneFlag.AUTOREAP
+        if nnp:
+            flags |= CloneFlag.NNP
+        old_umask = os.umask(0o077)
+        Sys.prctl(PrctlOp.SET_DUMPABLE, 1)
+        try:
+
+            def init_fn() -> int:
+                self._close_harness_fds()
+                os.close(ready_r)
+                os.close(ctrl_w)
+                signal.signal(signal.SIGUSR1, lambda _s, _f: None)
+                signal.signal(signal.SIGCHLD, lambda _s, _f: None)
+                cur_umask = os.umask(0o022)
+                dumpable = Sys.prctl(PrctlOp.GET_DUMPABLE)
+                nnp_val = Sys.prctl(PrctlOp.GET_NO_NEW_PRIVS)
+                if (
+                    os.getpid() != 1
+                    or cur_umask != 0o077
+                    or dumpable == 1
+                    or (nnp and nnp_val != 1)
+                ):
+                    os._exit(121)
+                os.write(ready_w, b"I")
+                os.close(ready_w)
+                while True:
+                    try:
+                        cmd = os.read(ctrl_r, 1)
+                    except InterruptedError:
+                        continue
+                    break
+                os.close(ctrl_r)
+                return cmd[0] if cmd else 0
+
+            pid, pidfd = ul.spawn_fn(init_fn, extra_flags=flags)
+        except Exception:
+            for fd in (ready_r, ready_w, ctrl_r, ctrl_w):
+                Sys.close_fd(fd)
+            raise
+        finally:
+            os.umask(old_umask)
+
+        os.close(ready_w)
+        os.close(ctrl_r)
+        try:
+            if os.read(ready_r, 1) != b"I":
+                raise AssertionError(f"{unit.label}: init check failed")
+        finally:
+            os.close(ready_r)
+
+        unit.init_pid = pid
+        unit.init_pidfd = pidfd
+        unit.init_ctrl_w = ctrl_w
+        unit.init_autoreap = autoreap
+        unit.init_reaped = False
+        unit.model.state = State.RUNNING
+
+        pfd = ul.get_nsfd(CloneFlag.NEWPID)
+        try:
+            unit.ns_ids[CloneFlag.NEWPID] = os.fstat(pfd)
+        finally:
+            os.close(pfd)
+        self._check_pidfd_ns(
+            pidfd, CloneFlag.NEWPID, unit.ns_ids[CloneFlag.NEWPID]
+        )
+
+    @staticmethod
+    def _check_pidfd_ns(
+        pidfd: int, nst: CloneFlag, expected: os.stat_result
+    ) -> None:
+        try:
+            nfd = Sys.ioctl(pidfd, PIDFD_NS_IOCTLS[nst])
+        except OSError as exc:
+            if os.geteuid() != 0 and exc.errno == errno.EACCES:
+                return
+            raise
+        try:
+            if not os.path.samestat(os.fstat(nfd), expected):
+                raise AssertionError(f"{NS_NAMES[nst]} mismatch")
+        finally:
+            os.close(nfd)
+
+    def _spawn_worker(
+        self, unit: LiveUnit, autoreap: bool, autokill: bool, with_setsid: bool
+    ) -> None:
+        ul = unit.ul_view()
+        ready_r, ready_w = os.pipe2(os.O_CLOEXEC)
+        ctrl_r, ctrl_w = os.pipe2(os.O_CLOEXEC)
+        flags = CloneFlag.PIDFD | CloneFlag.CLEAR_SIGHAND
+        if autoreap:
+            flags |= CloneFlag.AUTOREAP
+        if autokill:
+            flags |= CloneFlag.NNP | CloneFlag.PIDFD_AUTOKILL
+        try:
+
+            def worker_fn() -> int:
+                self._close_harness_fds()
+                os.close(ready_r)
+                os.close(ctrl_w)
+                signal.signal(signal.SIGUSR1, lambda _s, _f: None)
+                if os.getpid() <= 1:
+                    os._exit(122)
+                gc_w = -1
+                if with_setsid:
+                    os.setsid()
+                    gc_r, gc_w = os.pipe2(os.O_CLOEXEC)
+                    gc = Sys.fork()
+                    if gc == 0:
+                        os.close(ready_w)
+                        os.close(ctrl_r)
+                        os.close(gc_w)
+                        os.read(gc_r, 1)
+                        os.close(gc_r)
+                        os._exit(0)
+                    os.close(gc_r)
+                os.write(ready_w, b"W")
+                os.close(ready_w)
+                while True:
+                    try:
+                        cmd = os.read(ctrl_r, 1)
+                    except InterruptedError:
+                        continue
+                    break
+                os.close(ctrl_r)
+                Sys.close_fd(gc_w)
+                return cmd[0] if cmd else 0
+
+            pid, pidfd = ul.spawn_fn(worker_fn, extra_flags=flags)
+        except Exception:
+            for fd in (ready_r, ready_w, ctrl_r, ctrl_w):
+                Sys.close_fd(fd)
+            raise
+
+        os.close(ready_w)
+        os.close(ctrl_r)
+        try:
+            if os.read(ready_r, 1) != b"W":
+                raise AssertionError("worker startup failed")
+        finally:
+            os.close(ready_r)
+
+        for nst in (CloneFlag.NEWNS, CloneFlag.NEWNET):
+            self._check_pidfd_ns(pidfd, nst, unit.ns_ids[nst])
+        unit.workers.append(LiveWorker(pid, pidfd, ctrl_w, autoreap, autokill))
+
+    def _rule_clone(self, tc: ChoiceStream) -> None:
+        avail = self._open_units()
+        if not avail:
+            self._rule_open(tc)
+            return
+        unit = tc.pick(avail)
+        self.word("clone")
+        if (
+            unit.model.state == State.INIT
+            and not unit.model.has_root
+            and tc.draw_int(0, 2) > 0
+        ):
+            self._ensure_root(unit)
+
+        fd_kind = tc.weighted(
+            ((10, FdKind.NSEXEC), (1, FdKind.CLOSED), (1, FdKind.NS_MNT))
+        )
+        size = tc.weighted(
+            (
+                (12, CloneArgs.SIZE_VER3),
+                (1, CloneArgs.SIZE_VER2),
+                (1, PAGE_SIZE + 8),
+            )
+        )
+        extra = tc.weighted(
+            (
+                (5, int(CloneFlag.PIDFD | CloneFlag.CLEAR_SIGHAND)),
+                (
+                    5,
+                    int(
+                        CloneFlag.PIDFD
+                        | CloneFlag.AUTOREAP
+                        | CloneFlag.CLEAR_SIGHAND
+                    ),
+                ),
+                (
+                    3,
+                    int(
+                        CloneFlag.PIDFD
+                        | CloneFlag.AUTOREAP
+                        | CloneFlag.NNP
+                        | CloneFlag.PIDFD_AUTOKILL
+                    ),
+                ),
+                (1, int(CloneFlag.VM)),
+                (1, int(CloneFlag.FILES)),
+                (1, int(CloneFlag.NEWNS)),
+                (1, int(CloneFlag.NEWPID)),
+                (1, int(CloneFlag.PARENT)),
+                (1, int(CloneFlag.PIDFD | CloneFlag.PIDFD_AUTOKILL)),
+            )
+        )
+        exit_sig = (
+            0
+            if (extra & int(CloneFlag.AUTOREAP)) and tc.draw_int(0, 5) > 0
+            else (0 if extra == int(CloneFlag.PARENT) else int(signal.SIGCHLD))
+        )
+        foreign_pidns = (
+            fd_kind == FdKind.NSEXEC
+            and unit.model.has_root
+            and tc.draw_int(0, 7) == 0
+        )
+        actor = Actor(ancestor_pidns=not foreign_pidns, unpriv=self._unpriv)
+        exp = Oracle.clone_into(
+            actor,
+            unit.model,
+            fd_kind,
+            size=size,
+            extra_flags=extra,
+            exit_signal=exit_sig,
+            active_ns_mask=self._active_mask(),
+        )
+
+        if exp is not None:
+            target_fd = (
+                tc.pick(unit.fds)
+                if fd_kind == FdKind.NSEXEC
+                else (99999 if fd_kind == FdKind.CLOSED else unit.mntns_fd)
+            )
+            self.note(
+                f"{unit.label}: clone_into(kind={fd_kind.name}, sz={size}, "
+                f"extra=0x{extra:x}, sig={exit_sig}, fpid={foreign_pidns}) "
+                f"-> {errno.errorcode[exp]}"
+            )
+            buf = (
+                ctypes.create_string_buffer(size) if size > PAGE_SIZE else None
+            )
+
+            def bad_call() -> None:
+                if buf is not None:
+                    self.check_call(
+                        "clone3 E2BIG",
+                        exp,
+                        lambda: Sys.syscall(
+                            "clone3",
+                            ctypes.addressof(buf),
+                            ctypes.c_size_t(size),
+                        ),
+                    )
+                else:
+                    self.check_call(
+                        "clone_into",
+                        exp,
+                        lambda: NsExec.from_fd(target_fd).clone_into(
+                            extra, exit_signal=exit_sig, size=size
+                        ),
+                    )
+
+            if foreign_pidns:
+                self.run_in_foreign_pidns(unit.ul_view(), bad_call)
+            else:
+                bad_call()
+            return
+
+        autoreap = bool(extra & int(CloneFlag.AUTOREAP))
+        nnp = bool(extra & int(CloneFlag.NNP))
+        autokill = bool(extra & int(CloneFlag.PIDFD_AUTOKILL))
+        if unit.model.state == State.INIT:
+            self._spawn_init(unit, autoreap=autoreap, nnp=nnp)
+            self.note(
+                f"{unit.label}: bootstrap PID 1 (autoreap={autoreap}) "
+                f"-> RUNNING"
+            )
+        elif len(unit.workers) < 3:
+            setsid = tc.draw_bool()
+            self._spawn_worker(
+                unit,
+                autoreap=autoreap,
+                autokill=autokill,
+                with_setsid=setsid,
+            )
+            self.note(
+                f"{unit.label}: spawn worker #{len(unit.workers)} "
+                f"(autokill={autokill}, setsid={setsid})"
+            )
+
+    def _rule_concurrent_bootstrap(self, tc: ChoiceStream) -> None:
+        inits = [u for u in self._open_units() if u.model.state == State.INIT]
+        if not inits:
+            if len(self._units) >= self.MAX_UNITS:
+                self._rule_retire_or_exit(tc)
+                return
+            self._rule_open(tc)
+            inits = [
+                u for u in self._open_units() if u.model.state == State.INIT
+            ]
+            if not inits:
+                return
+        unit = tc.pick(inits)
+        self.word("race")
+        self._ensure_root(unit)
+        entrants = tc.draw_int(2, 4)
+        start_r, start_w = os.pipe2(os.O_CLOEXEC)
+        rep_r, rep_w = os.pipe2(os.O_CLOEXEC)
+        ctrl_r, ctrl_w = os.pipe2(os.O_CLOEXEC)
+        wpids: list[int] = []
+        for _ in range(entrants):
+            wp = Sys.fork()
+            if wp == 0:
+                os.close(start_w)
+                os.close(rep_r)
+                os.close(ctrl_w)
+                in_r, in_w = os.pipe2(os.O_CLOEXEC)
+                os.read(start_r, 1)
+                os.close(start_r)
+
+                def entrant() -> int:
+                    self._close_harness_fds()
+                    os.close(rep_w)
+                    os.close(in_r)
+                    signal.signal(signal.SIGUSR1, lambda _s, _f: None)
+                    signal.signal(signal.SIGCHLD, lambda _s, _f: None)
+                    mp = os.getpid()
+                    os.write(in_w, bytes([mp]))
+                    os.close(in_w)
+                    if mp != 1:
+                        os.close(ctrl_r)
+                        return 0
+                    while True:
+                        try:
+                            cmd = os.read(ctrl_r, 1)
+                        except InterruptedError:
+                            continue
+                        break
+                    os.close(ctrl_r)
+                    return cmd[0] if cmd else 0
+
+                pid, _ = unit.ul_view().spawn_fn(
+                    entrant,
+                    extra_flags=CloneFlag.AUTOREAP | CloneFlag.CLEAR_SIGHAND,
+                )
+                os.close(in_w)
+                os.close(ctrl_r)
+                inner_b = os.read(in_r, 1)
+                os.close(in_r)
+                if pid > 0 and len(inner_b) == 1:
+                    os.write(rep_w, struct.pack(">BI", inner_b[0], pid))
+                    os.close(rep_w)
+                    os._exit(0)
+                os.close(rep_w)
+                os._exit(1)
+            wpids.append(wp)
+
+        os.close(start_r)
+        os.close(rep_w)
+        os.close(ctrl_r)
+        os.close(start_w)
+        seen: set[int] = set()
+        init_host_pid = 0
+        for _ in range(entrants):
+            rec = os.read(rep_r, 5)
+            if len(rec) == 5:
+                mp, hpid = struct.unpack(">BI", rec)
+                seen.add(mp)
+                if mp == 1:
+                    init_host_pid = hpid
+        os.close(rep_r)
+        for wp in wpids:
+            if self.reap_pid(wp) != 0:
+                os.close(ctrl_w)
+                raise AssertionError("concurrent bootstrap entrant failed")
+        if seen != set(range(1, entrants + 1)) or init_host_pid <= 0:
+            os.close(ctrl_w)
+            raise AssertionError(f"unexpected entrant pids {seen}")
+
+        pfd = unit.ul_view().get_nsfd(CloneFlag.NEWPID)
+        try:
+            unit.ns_ids[CloneFlag.NEWPID] = os.fstat(pfd)
+        finally:
+            os.close(pfd)
+        unit.init_pid = init_host_pid
+        unit.init_pidfd = os.pidfd_open(init_host_pid, 0)
+        unit.init_ctrl_w = ctrl_w
+        unit.init_autoreap = True
+        unit.init_reaped = True
+        unit.model.state = State.RUNNING
+        self.note(f"{unit.label}: concurrent_bootstrap({entrants}) -> RUNNING")
+
+    def _rule_retire_or_exit(self, tc: ChoiceStream) -> None:
+        with_workers = [u for u in self._units if u.workers]
+        if with_workers and tc.draw_bool():
+            unit = tc.pick(with_workers)
+            w = unit.workers.pop(tc.draw_int(0, len(unit.workers) - 1))
+            if w.autokill and tc.draw_bool():
+                w.pidfd = Sys.close_fd(w.pidfd)
+                w.ctrl_w = Sys.close_fd(w.ctrl_w)
+                self.word("autokill")
+                self.note(f"{unit.label}: autokill worker closed")
+            else:
+                rc = tc.draw_int(0, 50)
+                os.write(w.ctrl_w, bytes([rc]))
+                w.ctrl_w = Sys.close_fd(w.ctrl_w)
+                if not w.autoreap:
+                    if self.reap_pid(w.pid) != rc:
+                        raise AssertionError("worker waitpid mismatch")
+                elif w.pidfd >= 0:
+                    poller = select.poll()
+                    poller.register(w.pidfd, select.POLLIN)
+                    poller.poll(5000)
+                    if Sys.pidfd_get_info(w.pidfd).decoded_exit != rc:
+                        raise AssertionError("worker pidfd_info mismatch")
+                w.pidfd = Sys.close_fd(w.pidfd)
+                self.word("retire")
+                self.note(f"{unit.label}: worker exited rc={rc}")
+            return
+
+        running = [
+            u for u in self._units if u.model.state == State.RUNNING and u.fds
+        ]
+        if not running:
+            self._rule_clone(tc)
+            return
+        unit = tc.pick(running)
+        self.word("exit")
+        rc = tc.draw_int(0, 99)
+        os.write(unit.init_ctrl_w, bytes([rc]))
+        unit.init_ctrl_w = Sys.close_fd(unit.init_ctrl_w)
+        self._sync_death(unit, os.CLD_EXITED, rc)
+        if not unit.init_autoreap and not unit.init_reaped and tc.draw_bool():
+            if self.reap_pid(unit.init_pid) != rc:
+                raise AssertionError("init waitpid mismatch")
+            unit.init_reaped = True
+        self.note(f"{unit.label}: init exited rc={rc} -> DEAD")
+
+    def _rule_signal(self, tc: ChoiceStream) -> None:
+        avail = self._open_units()
+        if not avail:
+            self._rule_open(tc)
+            return
+        unit = tc.pick(avail)
+        self.word("signal")
+        fd_kind = tc.weighted(
+            ((8, FdKind.NSEXEC), (1, FdKind.CLOSED), (1, FdKind.NS_MNT))
+        )
+        sig = tc.pick((0, int(signal.SIGUSR1), int(signal.SIGKILL), -1, 9999))
+        has_info = tc.draw_int(0, 7) == 0
+        flags = 1 if tc.draw_int(0, 7) == 0 else 0
+        foreign_pidns = (
+            fd_kind == FdKind.NSEXEC
+            and unit.model.uid_mapped
+            and tc.draw_int(0, 6) == 0
+        )
+        actor = Actor(ancestor_pidns=not foreign_pidns)
+        exp = Oracle.send_signal(
+            actor,
+            unit.model,
+            fd_kind,
+            sig=sig,
+            has_info=has_info,
+            flags=flags,
+        )
+        target_fd = (
+            tc.pick(unit.fds)
+            if fd_kind == FdKind.NSEXEC
+            else (99999 if fd_kind == FdKind.CLOSED else unit.mntns_fd)
+        )
+        self.note(
+            f"{unit.label}: signal(kind={fd_kind.name}, sig={sig}, "
+            f"fpid={foreign_pidns}) -> {exp or 'ok'}"
+        )
+        info_buf = ctypes.create_string_buffer(128) if has_info else None
+        info_addr = ctypes.addressof(info_buf) if info_buf is not None else 0
+
+        def do_sig() -> None:
+            self.check_call(
+                "pidfd_send_signal",
+                exp,
+                lambda: Sys.pidfd_send_signal(
+                    target_fd, sig, info_addr, flags
+                ),
+            )
+
+        if foreign_pidns and exp is not None:
+            self.run_in_foreign_pidns(unit.ul_view(), do_sig)
+            return
+
+        do_sig()
+        if exp is None and sig == int(signal.SIGKILL):
+            self._sync_death(unit, os.CLD_KILLED, int(signal.SIGKILL))
+
+    def _rule_wait_and_poll(self, tc: ChoiceStream) -> None:
+        avail = self._open_units()
+        if not avail:
+            self._rule_open(tc)
+            return
+        unit = tc.pick(avail)
+        self.word("wait")
+        fd_kind = tc.weighted(
+            ((8, FdKind.NSEXEC), (1, FdKind.CLOSED), (1, FdKind.NS_MNT))
+        )
+        neg_fd = fd_kind == FdKind.NSEXEC and tc.draw_int(0, 8) == 0
+        options = tc.weighted(
+            (
+                (6, os.WEXITED | os.WNOHANG),
+                (3, os.WEXITED | os.WNOHANG | os.WNOWAIT),
+                (1, os.WNOHANG),
+                (1, os.WEXITED | os.WSTOPPED),
+            )
+        )
+        has_ru = tc.draw_int(0, 8) == 0
+        nonblock = (
+            fd_kind == FdKind.NSEXEC
+            and not neg_fd
+            and not has_ru
+            and options == os.WEXITED
+            and unit.model.state == State.RUNNING
+        )
+        if tc.draw_int(0, 5) == 0 and unit.model.state == State.RUNNING:
+            options = os.WEXITED
+            nonblock = True
+        foreign_pidns = (
+            fd_kind == FdKind.NSEXEC
+            and not neg_fd
+            and unit.model.uid_mapped
+            and (options & os.WNOHANG) != 0
+            and tc.draw_int(0, 6) == 0
+        )
+        actor = Actor(ancestor_pidns=not foreign_pidns)
+        exp = Oracle.waitid(
+            actor,
+            unit.model,
+            fd_kind,
+            neg_fd=neg_fd,
+            options=options,
+            has_rusage=has_ru,
+            nonblock=nonblock,
+        )
+        target_fd = (
+            -1
+            if neg_fd
+            else (
+                tc.pick(unit.fds)
+                if fd_kind == FdKind.NSEXEC
+                else (99999 if fd_kind == FdKind.CLOSED else unit.mntns_fd)
+            )
+        )
+        self.note(
+            f"{unit.label}: waitid(kind={fd_kind.name}, opt=0x{options:x}, "
+            f"nb={nonblock}, fpid={foreign_pidns}) -> {exp or 'ok'}"
+        )
+
+        def do_wait() -> None:
+            if has_ru:
+                ru = ctypes.create_string_buffer(256)
+                self.check_call(
+                    "waitid rusage",
+                    exp,
+                    lambda: Sys.waitid_raw(
+                        int(WaitIdType.NSEXEC),
+                        target_fd,
+                        0,
+                        options,
+                        ctypes.addressof(ru),
+                    ),
+                )
+                return
+            can_nonblock = (
+                nonblock and fd_kind != FdKind.CLOSED and not neg_fd
+            )
+            if can_nonblock:
+                os.set_blocking(target_fd, False)
+            try:
+                res = self.check_call(
+                    "waitid",
+                    exp,
+                    lambda: os.waitid(
+                        int(WaitIdType.NSEXEC), target_fd, options
+                    ),
+                )
+            finally:
+                if can_nonblock:
+                    os.set_blocking(target_fd, True)
+            if exp is None and unit.model.state == State.DEAD:
+                assert res is not None
+                got = WaitResult(
+                    int(res.si_pid),
+                    int(res.si_status),
+                    int(res.si_code),
+                    int(res.si_uid),
+                )
+                if got != unit.expected_wait:
+                    raise AssertionError(
+                        f"waitid {got} != {unit.expected_wait}"
+                    )
+
+        if foreign_pidns:
+            self.run_in_foreign_pidns(unit.ul_view(), do_wait)
+        else:
+            do_wait()
+
+        if fd_kind == FdKind.NSEXEC and not neg_fd:
+            with select.epoll() as ep1, select.epoll() as ep2:
+                ep1.register(target_fd, select.EPOLLIN | select.EPOLLEXCLUSIVE)
+                ep2.register(target_fd, select.EPOLLIN | select.EPOLLEXCLUSIVE)
+                want = unit.model.state == State.DEAD
+                for ep in (ep1, ep2):
+                    hup = any(ev & select.EPOLLHUP for _, ev in ep.poll(0))
+                    if hup != want:
+                        raise AssertionError(
+                            f"{unit.label}: EPOLLHUP={hup} != {want}"
+                        )
+
+    def step(self, tc: ChoiceStream) -> None:
+        rule = tc.weighted(
+            (
+                (14, self._rule_open),
+                (10, self._rule_dup_or_close),
+                (12, self._rule_get_nsfd),
+                (12, self._rule_share_nsfd),
+                (20, self._rule_clone),
+                (6, self._rule_concurrent_bootstrap),
+                (10, self._rule_retire_or_exit),
+                (10, self._rule_signal),
+                (10, self._rule_wait_and_poll),
+            )
+        )
+        rule(tc)
+
+    def check_invariants(self) -> None:
+        for unit in self._units:
+            for fd in unit.fds:
+                ul = NsExec.from_fd(fd)
+                if ul.poll_dead(0) != (unit.model.state == State.DEAD):
+                    raise AssertionError(f"{unit.label}: poll_dead mismatch")
+                exp = Oracle.waitid(
+                    Actor(),
+                    unit.model,
+                    FdKind.NSEXEC,
+                    options=os.WEXITED | os.WNOHANG,
+                )
+                res = self.check_call(
+                    f"{unit.label} inv wait",
+                    exp,
+                    lambda: ul.wait(os.WNOHANG),
+                )
+                if exp is None:
+                    want = (
+                        WaitResult(0)
+                        if unit.model.state == State.RUNNING
+                        else unit.expected_wait
+                    )
+                    if res != want:
+                        raise AssertionError(
+                            f"{unit.label}: inv wait {res} != {want}"
+                        )
+
+    def close(self) -> None:
+        for unit in self._units:
+            for w in unit.workers:
+                w.ctrl_w = Sys.close_fd(w.ctrl_w)
+                if not w.autokill and not w.autoreap and w.pid > 0:
+                    with suppress(ChildProcessError, OSError):
+                        self.reap_pid(w.pid)
+                w.pidfd = Sys.close_fd(w.pidfd)
+            unit.workers.clear()
+            unit.init_ctrl_w = Sys.close_fd(unit.init_ctrl_w)
+            if unit.model.state == State.RUNNING:
+                if unit.fds:
+                    with suppress(OSError):
+                        unit.ul_view().kill(signal.SIGKILL)
+                elif unit.init_pidfd >= 0:
+                    with suppress(OSError):
+                        Sys.pidfd_send_signal(
+                            unit.init_pidfd, int(signal.SIGKILL)
+                        )
+            for fd in unit.fds:
+                Sys.close_fd(fd)
+            unit.fds.clear()
+            if (
+                unit.init_pid > 0
+                and not unit.init_autoreap
+                and not unit.init_reaped
+            ):
+                with suppress(ChildProcessError, OSError):
+                    self.reap_pid(unit.init_pid)
+                unit.init_reaped = True
+            unit.init_pidfd = Sys.close_fd(unit.init_pidfd)
+            unit.root_dfd = Sys.close_fd(unit.root_dfd)
+            unit.mntns_fd = Sys.close_fd(unit.mntns_fd)
+        self._units.clear()
+        for fd, _ in self._host_ns.values():
+            Sys.close_fd(fd)
+        self._host_ns.clear()
+
+
+@dataclass
+class IdmapSlot:
+    label: str
+    ul: NsExec
+    userns_fd: int
+    mntns_fd: int
+    model: UnitModel = field(default_factory=UnitModel)
+    setgroups_allowed: bool = False
+
+
+class Idmap(NsExecMachine):
+    """Parametric state machine for userns_set_idmap() and SCM_RIGHTS."""
+
+    STEPS: ClassVar[int] = 16
+
+    def __init__(self) -> None:
+        super().__init__()
+        self._slots: list[IdmapSlot] = []
+        self._seq = 0
+        self._has_projid = bool(Path("/proc/self/projid_map").read_bytes())
+        self._can_setgroups = (
+            os.geteuid() == 0
+            and Path("/proc/self/setgroups").read_bytes() == b"allow\n"
+        )
+
+    def _open_slot(self) -> IdmapSlot:
+        if len(self._slots) >= 4:
+            old = self._slots.pop(0)
+            Sys.close_fd(old.userns_fd)
+            Sys.close_fd(old.mntns_fd)
+            old.ul.close()
+        ul = NsExec()
+        slot = IdmapSlot(
+            label=f"id{self._seq}",
+            ul=ul,
+            userns_fd=ul.get_nsfd(CloneFlag.NEWUSER),
+            mntns_fd=ul.get_nsfd(CloneFlag.NEWNS),
+        )
+        self._seq += 1
+        self._slots.append(slot)
+        return slot
+
+    def _rule_set_idmap(self, tc: ChoiceStream) -> None:
+        slot = (
+            tc.pick(self._slots)
+            if self._slots and tc.draw_int(0, 3) > 0
+            else self._open_slot()
+        )
+        fd_kind = tc.weighted(
+            (
+                (10, FdKind.NS_USER),
+                (1, FdKind.CLOSED),
+                (1, FdKind.NSEXEC),
+                (1, FdKind.NS_MNT),
+            )
+        )
+        size = tc.weighted(
+            (
+                (12, UsernsIdmap.SIZE_VER0),
+                (1, UsernsIdmap.SIZE_VER0 - 1),
+                (1, PAGE_SIZE + 1),
+            )
+        )
+        flags = tc.weighted(
+            ((8, 0), (2, int(UsernsFlag.SETGROUPS_ALLOWED)), (1, 0x80))
+        )
+        reserved = 1 if tc.draw_int(0, 10) == 0 else 0
+        null_map = tc.draw_int(0, 12) == 0
+        ptr_mismatch = not null_map and tc.draw_int(0, 12) == 0
+
+        u_choice = tc.weighted(((5, True), (4, None), (1, False)))
+        g_choice = tc.weighted(((5, True), (4, None), (1, False)))
+        p_choice = (
+            tc.weighted(((2, True), (8, None))) if self._has_projid else None
+        )
+
+        actor = Actor(can_allow_setgroups=self._can_setgroups)
+        exp = Oracle.set_idmap(
+            actor,
+            slot.model,
+            fd_kind,
+            size=size,
+            flags=flags,
+            reserved=reserved,
+            null_map=null_map,
+            ptr_mismatch=ptr_mismatch,
+            uid_valid=u_choice,
+            gid_valid=g_choice,
+            projid_valid=p_choice,
+        )
+        target_fd = {
+            FdKind.NS_USER: slot.userns_fd,
+            FdKind.CLOSED: -1,
+            FdKind.NSEXEC: slot.ul.fd,
+            FdKind.NS_MNT: slot.mntns_fd,
+        }[fd_kind]
+        if null_map:
+            self.word("null")
+        elif size > PAGE_SIZE:
+            self.word("e2big")
+        elif ptr_mismatch:
+            self.word("badptr")
+        elif flags & int(UsernsFlag.SETGROUPS_ALLOWED):
+            self.word("setgroups")
+        elif p_choice:
+            self.word("projid")
+        else:
+            self.word("idmap")
+        self.note(
+            f"{slot.label}: set_idmap(fd={fd_kind.name}, sz={size}, "
+            f"fl=0x{flags:x}, u={u_choice}, g={g_choice}, p={p_choice}) "
+            f"-> {exp or 'ok'}"
+        )
+
+        if null_map:
+            self.check_call(
+                "idmap null",
+                exp,
+                lambda: Sys.userns_set_idmap_raw(target_fd, 0, size, flags),
+            )
+            return
+        if size > PAGE_SIZE:
+            big = ctypes.create_string_buffer(size)
+            self.check_call(
+                "idmap E2BIG",
+                exp,
+                lambda: Sys.userns_set_idmap_raw(
+                    target_fd, ctypes.addressof(big), size, flags
+                ),
+            )
+            return
+        if ptr_mismatch:
+            bad = (
+                UsernsIdmap(nr_uid_extents=1, uid_extents=0)
+                if tc.draw_bool()
+                else UsernsIdmap(nr_uid_extents=0, uid_extents=1)
+            )
+            self.check_call(
+                "idmap ptr mismatch",
+                exp,
+                lambda: Sys.userns_set_idmap_raw(
+                    target_fd, ctypes.addressof(bad), size, flags
+                ),
+            )
+            return
+
+        u_ext = (
+            ()
+            if u_choice is None
+            else (((0, os.geteuid(), 1 if u_choice else 0),))
+        )
+        g_ext = (
+            ()
+            if g_choice is None
+            else (((0, os.getegid(), 1 if g_choice else 0),))
+        )
+        p_ext = () if p_choice is None else ((0, 0, 1),)
+        self.check_call(
+            "set_userns_idmap",
+            exp,
+            lambda: Sys.set_userns_idmap(
+                target_fd,
+                uid_extents=u_ext,
+                gid_extents=g_ext,
+                projid_extents=p_ext,
+                reserved=reserved,
+                size=size,
+                flags=flags,
+            ),
+        )
+        if exp is None:
+            if u_choice:
+                slot.model.uid_mapped = True
+            if g_choice:
+                slot.model.gid_mapped = True
+                slot.setgroups_allowed = bool(
+                    flags & int(UsernsFlag.SETGROUPS_ALLOWED)
+                )
+            if p_choice:
+                slot.model.projid_mapped = True
+
+    def _rule_verify_mapped_or_setns(self, tc: ChoiceStream) -> None:
+        mapped = [
+            s
+            for s in self._slots
+            if s.model.uid_mapped
+            and s.model.gid_mapped
+            and not s.model.has_root
+        ]
+        if not mapped:
+            slot = self._open_slot()
+            slot.ul.map_self()
+            slot.model.uid_mapped = True
+            slot.model.gid_mapped = True
+        else:
+            slot = tc.pick(mapped)
+        self.word("setns")
+
+        rfd = slot.ul.make_mount("tmpfs")
+        try:
+            os.mkdir("proc", 0o755, dir_fd=rfd)
+            Sys.move_mount(
+                rfd,
+                "",
+                slot.mntns_fd,
+                "/",
+                MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+            )
+        finally:
+            os.close(rfd)
+        pfd = slot.ul.make_mount("proc")
+        try:
+            Sys.move_mount(
+                pfd,
+                "",
+                slot.mntns_fd,
+                "proc",
+                MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+            )
+        finally:
+            os.close(pfd)
+        slot.model.has_root = True
+        slot.model.state = State.DEAD
+
+        want_sg = b"allow\n" if slot.setgroups_allowed else b"deny\n"
+        ready_r, ready_w = os.pipe2(os.O_CLOEXEC)
+        hold_r, hold_w = os.pipe2(os.O_CLOEXEC)
+
+        def child_check() -> int:
+            os.close(ready_r)
+            os.close(hold_w)
+            Sys.prctl(PrctlOp.SET_DUMPABLE, 1)
+            ok = (
+                os.geteuid() == 0
+                and os.getegid() == 0
+                and Path("/proc/self/setgroups").read_bytes() == want_sg
+            )
+            os.write(ready_w, b"1" if ok else b"0")
+            os.close(ready_w)
+            os.read(hold_r, 1)
+            os.close(hold_r)
+            return 0 if ok else 1
+
+        pid, _ = slot.ul.spawn_fn(child_check)
+        os.close(ready_w)
+        os.close(hold_r)
+        try:
+            if os.read(ready_r, 1) != b"1":
+                raise AssertionError(f"{slot.label}: cred/setgroups mismatch")
+            uts_fd = os.open(f"/proc/{pid}/ns/uts", os.O_RDONLY | os.O_CLOEXEC)
+            try:
+                self.run_isolated(
+                    lambda: (
+                        Sys.setns(slot.userns_fd, CloneFlag.NEWUSER),
+                        Sys.setns(uts_fd, CloneFlag.NEWUTS),
+                    )
+                )
+                if os.geteuid() == 0:
+
+                    def check_foreign() -> None:
+                        self.drop_to_uid(1000)
+                        self.enter_userns_if_unpriv()
+                        self.check_call(
+                            "foreign setns",
+                            errno.EPERM,
+                            lambda: Sys.setns(uts_fd, CloneFlag.NEWUTS),
+                        )
+
+                    self.run_isolated(check_foreign)
+            finally:
+                os.close(uts_fd)
+        finally:
+            os.close(ready_r)
+            os.close(hold_w)
+            if self.reap_pid(pid) != 0 or slot.ul.wait().exit_code != 0:
+                raise AssertionError("mapped child exited non-zero")
+        self.note(f"{slot.label}: verified creds, setgroups, and setns")
+
+    def _rule_delegate_idmap(self, tc: ChoiceStream) -> None:
+        if os.geteuid() != 0:
+            self._rule_set_idmap(tc)
+            return
+        self.word("delegate")
+        ul = self.create_nsexec_as_uid(1000)
+        if ul is None:
+            return
+        opener_ok = tc.draw_bool()
+        maps_root = tc.draw_int(0, 3) == 0
+        multi = tc.draw_bool()
+        actor = Actor(
+            owner=False,
+            can_allow_setgroups=True,
+            parent_setid=True,
+            parent_setfcap=False,
+        )
+        unit = UnitModel()
+        exp = Oracle.set_idmap(
+            actor,
+            unit,
+            FdKind.NS_USER,
+            opener_capable=opener_ok,
+            maps_host_root=maps_root,
+            multi_extent=multi,
+            flags=int(UsernsFlag.SETGROUPS_ALLOWED),
+            uid_valid=True,
+            gid_valid=True,
+        )
+        self.note(
+            f"delegate_idmap(opener_ok={opener_ok}, root={maps_root}, "
+            f"multi={multi}) -> {exp or 'ok'}"
+        )
+
+        with ul:
+            uts_fd = ul.get_nsfd(CloneFlag.NEWUTS)
+            s_a, s_b = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET)
+            pid = Sys.fork()
+            if pid == 0:
+                s_a.close()
+                try:
+                    if opener_ok:
+                        self.drop_to_uid(1000)
+                        ufd = ul.get_nsfd(CloneFlag.NEWUSER)
+                    else:
+                        self.drop_to_uid(2000)
+                        ufd = Sys.ioctl(uts_fd, Ioctl.NS_GET_USERNS)
+                    socket.send_fds(s_b, [b"D"], [ufd])
+                    os.close(ufd)
+                    os._exit(0)
+                finally:
+                    os.close(uts_fd)
+                    s_b.close()
+            os.close(uts_fd)
+            s_b.close()
+            _, fds, _, _ = socket.recv_fds(s_a, 1, 1)
+            s_a.close()
+            if self.reap_pid(pid) != 0 or not fds:
+                raise AssertionError("failed acquiring delegated userns fd")
+            delegated_ufd = fds[0]
+            try:
+                base_uid = 0 if maps_root else 1000
+                u_ext: tuple[tuple[int, int, int], ...] = (
+                    ((0, base_uid, 1), (1, 2000, 1))
+                    if multi
+                    else ((0, base_uid, 1),)
+                )
+                g_ext: tuple[tuple[int, int, int], ...] = (
+                    ((0, 1000, 1), (1, 2000, 1)) if multi else ((0, 1000, 1),)
+                )
+                self.run_isolated(
+                    lambda: (
+                        Sys.drop_to_setid_helper(990),
+                        self.check_call(
+                            "delegated set_idmap",
+                            exp,
+                            lambda: Sys.set_userns_idmap(
+                                delegated_ufd,
+                                uid_extents=u_ext,
+                                gid_extents=g_ext,
+                                flags=UsernsFlag.SETGROUPS_ALLOWED,
+                            ),
+                        ),
+                    )
+                )
+            finally:
+                os.close(delegated_ufd)
+
+    def step(self, tc: ChoiceStream) -> None:
+        rule = tc.weighted(
+            (
+                (16, self._rule_set_idmap),
+                (6, self._rule_verify_mapped_or_setns),
+                (5, self._rule_delegate_idmap),
+            )
+        )
+        rule(tc)
+
+    def close(self) -> None:
+        for slot in self._slots:
+            Sys.close_fd(slot.userns_fd)
+            Sys.close_fd(slot.mntns_fd)
+            slot.ul.close()
+        self._slots.clear()
+
+
+@dataclass
+class MountSlot:
+    label: str
+    ul: NsExec
+    mntns_fd: int
+    model: UnitModel = field(default_factory=UnitModel)
+
+
+class Mounts(NsExecMachine):
+    """Parametric state machine for FSCONFIG_SET_NSEXEC and MOVE_MOUNT."""
+
+    STEPS: ClassVar[int] = 16
+
+    def __init__(self) -> None:
+        super().__init__()
+        self._slots: list[MountSlot] = []
+        self._seq = 0
+        self._empty_src = tempfile.TemporaryDirectory(prefix="nsexec-mnt-")
+
+    def _open_slot(self, mapped: bool = True) -> MountSlot:
+        if len(self._slots) >= 4:
+            old = self._slots.pop(0)
+            Sys.close_fd(old.mntns_fd)
+            old.ul.close()
+        ul = NsExec()
+        model = UnitModel()
+        if mapped:
+            ul.map_self()
+            model.uid_mapped = True
+            model.gid_mapped = True
+        slot = MountSlot(
+            f"m{self._seq}", ul, ul.get_nsfd(CloneFlag.NEWNS), model
+        )
+        self._seq += 1
+        self._slots.append(slot)
+        return slot
+
+    def _rule_fsconfig(self, tc: ChoiceStream) -> None:
+        slot = tc.pick(self._slots) if self._slots else self._open_slot()
+        fstype = tc.weighted(
+            (
+                (4, "tmpfs"),
+                (3, "ramfs"),
+                (4, "proc"),
+                (3, "devpts"),
+                (2, "mqueue"),
+                (2, "cgroup2"),
+            )
+        )
+        if fstype == "cgroup2" and os.geteuid() != 0:
+            fstype = "tmpfs"
+        self.word(fstype)
+        aux_kind = tc.weighted(
+            ((10, FdKind.NSEXEC), (1, FdKind.CLOSED), (1, FdKind.NS_MNT))
+        )
+        foreign_pidns = (
+            fstype == "proc"
+            and aux_kind == FdKind.NSEXEC
+            and slot.model.uid_mapped
+            and tc.draw_int(0, 3) == 0
+        )
+        actor = Actor(ancestor_pidns=not foreign_pidns)
+        exp = Oracle.fsconfig_nsexec(actor, aux_kind, fstype)
+        aux_fd = {
+            FdKind.NSEXEC: slot.ul.fd,
+            FdKind.CLOSED: 99999,
+            FdKind.NS_MNT: slot.mntns_fd,
+        }[aux_kind]
+
+        try:
+            fsfd = Sys.fsopen(fstype)
+        except OSError as exc:
+            if exc.errno in (errno.ENODEV, errno.EPERM):
+                return
+            raise
+
+        self.note(
+            f"{slot.label}: fsconfig({fstype}, aux={aux_kind.name}, "
+            f"fpid={foreign_pidns}) -> {exp or 'ok'}"
+        )
+        try:
+            if foreign_pidns:
+                self.run_in_foreign_pidns(
+                    slot.ul,
+                    lambda: (
+                        self.check_call(
+                            "proc foreign pidns",
+                            exp,
+                            lambda: Sys.fsconfig(
+                                fsfd, FsconfigCmd.SET_NSEXEC, aux=aux_fd
+                            ),
+                        ),
+                        self.check_call(
+                            "unconfigured proc create",
+                            errno.EBUSY,
+                            lambda: Sys.fsconfig(fsfd, FsconfigCmd.CMD_CREATE),
+                        ),
+                    ),
+                )
+                return
+
+            self.check_call(
+                "FSCONFIG_SET_NSEXEC",
+                exp,
+                lambda: Sys.fsconfig(
+                    fsfd, FsconfigCmd.SET_NSEXEC, aux=aux_fd
+                ),
+            )
+            if exp is not None:
+                return
+
+            if tc.draw_bool():
+                re_exp = Oracle.fsconfig_nsexec(
+                    actor, FdKind.NSEXEC, fstype, already_bound=True
+                )
+                self.check_call(
+                    "double SET_NSEXEC",
+                    re_exp,
+                    lambda: Sys.fsconfig(
+                        fsfd, FsconfigCmd.SET_NSEXEC, aux=slot.ul.fd
+                    ),
+                )
+            proc_g_toks: list[str] = []
+            if fstype == "proc":
+                if tc.draw_bool():
+                    self.check_call(
+                        "proc pidns override",
+                        errno.EBUSY,
+                        lambda: Sys.fsconfig(
+                            fsfd,
+                            FsconfigCmd.SET_STRING,
+                            key="pidns",
+                            value="/proc/self/ns/pid",
+                        ),
+                    )
+                if slot.model.uid_mapped:
+                    proc_g_toks = (
+                        Path("/proc/self/gid_map").read_text().split()
+                    )
+                    if len(proc_g_toks) >= 3 and int(proc_g_toks[2]) > 1:
+                        self.check_call(
+                            "proc unmapped gid",
+                            errno.EINVAL,
+                            lambda: Sys.fsconfig(
+                                fsfd,
+                                FsconfigCmd.SET_STRING,
+                                key="gid",
+                                value=str(os.getegid() + 1),
+                            ),
+                        )
+                    Sys.fsconfig(
+                        fsfd,
+                        FsconfigCmd.SET_STRING,
+                        key="gid",
+                        value=str(os.getegid()),
+                    )
+            elif fstype == "devpts" and slot.model.uid_mapped:
+                u_toks = Path("/proc/self/uid_map").read_text().split()
+                if len(u_toks) >= 3 and int(u_toks[2]) > 1:
+                    self.check_call(
+                        "devpts unmapped uid",
+                        errno.EINVAL,
+                        lambda: Sys.fsconfig(
+                            fsfd,
+                            FsconfigCmd.SET_STRING,
+                            key="uid",
+                            value=str(os.geteuid() + 1),
+                        ),
+                    )
+                Sys.fsconfig(
+                    fsfd,
+                    FsconfigCmd.SET_STRING,
+                    key="uid",
+                    value=str(os.geteuid()),
+                )
+
+            Sys.fsconfig(fsfd, FsconfigCmd.CMD_CREATE)
+            mfd = Sys.fsmount(fsfd)
+            os.close(mfd)
+            if fstype == "proc" and slot.model.uid_mapped:
+                if len(proc_g_toks) >= 3 and int(proc_g_toks[2]) > 1:
+                    self.check_call(
+                        "proc reconfigure unmapped gid",
+                        errno.EINVAL,
+                        lambda: Sys.fsconfig(
+                            fsfd,
+                            FsconfigCmd.SET_STRING,
+                            key="gid",
+                            value=str(os.getegid() + 1),
+                        ),
+                    )
+                Sys.fsconfig(
+                    fsfd,
+                    FsconfigCmd.SET_STRING,
+                    key="gid",
+                    value=str(os.getegid()),
+                )
+                Sys.fsconfig(fsfd, FsconfigCmd.CMD_RECONFIGURE)
+            elif tc.draw_bool():
+                self.check_call(
+                    "double fsmount", errno.EBUSY, lambda: Sys.fsmount(fsfd)
+                )
+        finally:
+            os.close(fsfd)
+
+    def _rule_move_mount(self, tc: ChoiceStream) -> None:
+        if len(self._slots) < 2:
+            self._open_slot(mapped=tc.draw_bool())
+        slot = tc.pick(self._slots)
+        peers = [s for s in self._slots if s is not slot]
+        src_same = not (peers and tc.draw_int(0, 5) == 0)
+        src_slot = slot if src_same else tc.pick(peers)
+        target = tc.weighted(
+            ((5, "/"), (2, "."), (4, "mnt"), (3, "tmp"), (1, "tmp/.."))
+        )
+        t_mntns = tc.draw_int(0, 8) > 0
+        clone = not t_mntns or tc.draw_int(0, 6) == 0
+        beneath = tc.draw_int(0, 3) == 0
+        set_group = tc.draw_int(0, 8) == 0
+        self.word("beneath" if beneath else ("clone" if clone else "move"))
+
+        exp = Oracle.move_mount(
+            Actor(),
+            slot.model,
+            src_same_unit=src_same if not clone else True,
+            target=target,
+            t_mntns=t_mntns,
+            clone=clone,
+            beneath=beneath,
+            set_group=set_group,
+        )
+        flags = MoveMountFlag(0)
+        if t_mntns:
+            flags |= MoveMountFlag.T_MNTNS
+        if clone:
+            flags |= MoveMountFlag.CLONE
+        else:
+            flags |= MoveMountFlag.F_EMPTY_PATH
+        if beneath:
+            flags |= MoveMountFlag.BENEATH
+        if set_group:
+            flags |= MoveMountFlag.SET_GROUP
+
+        self.note(
+            f"{slot.label}: move_mount(target={target!r}, same={src_same}, "
+            f"cl={clone}, ben={beneath}, sg={set_group}) -> {exp or 'ok'}"
+        )
+
+        if clone:
+            src_dir = self._empty_src.name
+            to_fd = slot.mntns_fd if t_mntns else Sys.AT_FDCWD
+            to_path = target if t_mntns else src_dir
+
+            def do_clone_mm() -> None:
+                if not t_mntns:
+                    self.enter_userns_if_unpriv()
+                self.check_call(
+                    "move_mount clone",
+                    exp,
+                    lambda: Sys.move_mount(
+                        Sys.AT_FDCWD, src_dir, to_fd, to_path, flags
+                    ),
+                )
+
+            if not t_mntns:
+                self.run_isolated(do_clone_mm)
+                return
+            do_clone_mm()
+            if exp is None:
+                if target == "/":
+                    slot.model.has_root = True
+                    slot.model.has_dirs = False
+                else:
+                    slot.model.mount_depth[target] = (
+                        slot.model.mount_depth.get(target, 0) + 1
+                    )
+            return
+
+        mfd = src_slot.ul.make_mount("tmpfs")
+        try:
+            want_dirs = (
+                exp is None
+                and target == "/"
+                and slot.model.uid_mapped
+                and slot.model.gid_mapped
+                and tc.draw_int(0, 3) > 0
+            )
+            if want_dirs:
+                for d in ("proc", "tmp", "mnt"):
+                    os.mkdir(d, 0o755, dir_fd=mfd)
+            self.check_call(
+                "move_mount",
+                exp,
+                lambda: Sys.move_mount(mfd, "", slot.mntns_fd, target, flags),
+            )
+            if exp is None:
+                if target == "/":
+                    slot.model.has_root = True
+                    slot.model.has_dirs = want_dirs
+                else:
+                    slot.model.mount_depth[target] = (
+                        slot.model.mount_depth.get(target, 0) + 1
+                    )
+        finally:
+            os.close(mfd)
+
+    def _rule_nouser_clone(self, tc: ChoiceStream) -> None:
+        slot = tc.pick(self._slots) if self._slots else self._open_slot()
+        self.word("nouser")
+        exp = Oracle.move_mount(
+            Actor(), slot.model, src_nouser=True, clone=True
+        )
+        assert exp is not None
+        self.note(
+            f"{slot.label}: move_mount(SB_NOUSER clone) -> "
+            f"{errno.errorcode[exp]}"
+        )
+
+        def worker() -> None:
+            unpriv = os.geteuid() != 0
+            self.enter_userns_if_unpriv()
+            with NsExec() as empty_u:
+                mfd = empty_u.get_nsfd(CloneFlag.NEWNS)
+                dst_u = NsExec() if unpriv else None
+                dst_mfd = (
+                    dst_u.get_nsfd(CloneFlag.NEWNS)
+                    if dst_u is not None
+                    else slot.mntns_fd
+                )
+                try:
+                    if dst_u is not None and slot.model.has_root:
+                        rfd = dst_u.make_mount("tmpfs")
+                        try:
+                            Sys.move_mount(
+                                rfd,
+                                "",
+                                dst_mfd,
+                                "/",
+                                MoveMountFlag.T_MNTNS
+                                | MoveMountFlag.F_EMPTY_PATH,
+                            )
+                        finally:
+                            os.close(rfd)
+                    Sys.setns(mfd, CloneFlag.NEWNS)
+                    self.check_call(
+                        "SB_NOUSER clone",
+                        exp,
+                        lambda: Sys.move_mount(
+                            Sys.AT_FDCWD,
+                            "/",
+                            dst_mfd,
+                            "/",
+                            MoveMountFlag.T_MNTNS | MoveMountFlag.CLONE,
+                        ),
+                    )
+                finally:
+                    if dst_u is not None:
+                        os.close(dst_mfd)
+                        dst_u.close()
+                    os.close(mfd)
+
+        self.run_isolated(worker)
+
+    def step(self, tc: ChoiceStream) -> None:
+        rule = tc.weighted(
+            (
+                (14, self._rule_fsconfig),
+                (16, self._rule_move_mount),
+                (4, self._rule_nouser_clone),
+            )
+        )
+        rule(tc)
+
+    def close(self) -> None:
+        for slot in self._slots:
+            Sys.close_fd(slot.mntns_fd)
+            slot.ul.close()
+        self._slots.clear()
+        self._empty_src.cleanup()
+
+
+@dataclass
+class LiveCell:
+    cell: Cell
+    ro_root: bool
+    devfs: bool
+    host_rt: bool
+    pod_peer: str | None
+    pivoted: bool = False
+    mnt_locked: bool = False
+    mnt_depth: int = 0
+    alive: bool = True
+
+
+class Cells(NsExecMachine):
+    """Realistic multi-Cell supervisor, pods, RO root, PTY, and hot-swap."""
+
+    STEPS: ClassVar[int] = 16
+    MAX_CELLS: ClassVar[int] = 4
+
+    def __init__(self) -> None:
+        super().__init__()
+        self._mgr = CellManager()
+        self._cells: list[LiveCell] = []
+        self._seq = 0
+        self._tmp = tempfile.TemporaryDirectory(prefix="nsexec-cells-")
+
+    def _live(self) -> list[LiveCell]:
+        return [c for c in self._cells if c.alive]
+
+    def _run_session(self, tag: str, sess: Session) -> int:
+        try:
+            self._mgr.register_session(tag, sess)
+        except Exception:
+            sess.close()
+            raise
+        deadline = time.monotonic() + 5.0
+        while time.monotonic() < deadline:
+            for ev in self._mgr.poll_events(0.1):
+                if ev.kind is EventKind.CELL:
+                    raise AssertionError(f"unexpected cell exit: {ev}")
+                if (
+                    ev.kind is EventKind.SESSION
+                    and ev.name == tag
+                    and ev.pid == sess.pid
+                ):
+                    assert ev.exit_code is not None
+                    return ev.exit_code
+        raise AssertionError(f"session {tag} timed out")
+
+    def _rule_boot(self, tc: ChoiceStream) -> None:
+        live = self._live()
+        if len(live) >= self.MAX_CELLS:
+            self._rule_stop(tc)
+            live = self._live()
+        name = f"c{self._seq}"
+        self._seq += 1
+        ro_root = tc.draw_bool()
+        devfs = tc.draw_bool()
+        host_rt = tc.draw_int(0, 3) == 0
+        cell = Cell(name)
+        peer_name: str | None = None
+        self.word("boot")
+        try:
+            if live and tc.draw_bool():
+                peer = tc.pick(live)
+                cell.share_from(
+                    peer.cell, (CloneFlag.NEWNET, CloneFlag.NEWIPC)
+                )
+                peer_name = peer.cell.name
+            cell.setup_rootfs(
+                procfs=True,
+                devfs=devfs,
+                ro_root=ro_root,
+                host_runtime=host_rt,
+            )
+            if tc.draw_int(0, 3) == 0:
+                s_a, s_b = socket.socketpair(
+                    socket.AF_UNIX, socket.SOCK_SEQPACKET
+                )
+                try:
+                    cell.send(s_a)
+                    handed = Cell.recv(name, s_b)
+                finally:
+                    s_a.close()
+                    s_b.close()
+                cell.close()
+                cell = handed
+            cell.boot()
+            self._mgr.register_cell(cell)
+        except Exception:
+            cell.close()
+            raise
+        self._cells.append(LiveCell(cell, ro_root, devfs, host_rt, peer_name))
+        if peer_name is not None:
+            self.word("pod")
+        self.note(
+            f"boot {name} (ro={ro_root}, dev={devfs}, rt={host_rt}, "
+            f"pod={peer_name})"
+        )
+
+    def _rule_exec_probe(self, tc: ChoiceStream) -> None:
+        live = self._live()
+        if not live:
+            self._rule_boot(tc)
+            live = self._live()
+        lc = tc.pick(live)
+        if lc.host_rt and tc.draw_bool():
+            self.word("argv")
+            tok = f"tok-{self._seq}-{tc.draw_int(100, 999)}"
+            code = (
+                "import os, sys; "
+                "ok = os.getpid() > 1 "
+                "and os.environ.get('CELL_TOKEN') == sys.argv[1]; "
+                "sys.exit(0 if ok else 1)"
+            )
+            rc = self._run_session(
+                f"{lc.cell.name}-argv",
+                lc.cell.exec_argv(
+                    [PYTHON_BIN, "-S", "-c", code, tok],
+                    env={"CELL_TOKEN": tok},
+                ),
+            )
+            if rc != 0:
+                raise AssertionError("exec_argv failed")
+            self.note(f"{lc.cell.name}: exec_argv(python3, env) -> ok")
+            return
+
+        ro = lc.ro_root
+        has_dev = lc.devfs
+        self.word("exec")
+
+        def probe() -> int:
+            pids = [e for e in os.listdir("/proc") if e.isdigit()]
+            if "1" not in pids or str(os.getpid()) not in pids:
+                return 1
+            if len(os.listdir("/proc/1/fd")) > 4:
+                return 4
+            if has_dev:
+                Path("/dev/null").write_bytes(b"discard")
+                if Path("/dev/null").read_bytes() != b"":
+                    return 5
+                ufd = os.open("/dev/urandom", os.O_RDONLY | os.O_CLOEXEC)
+                try:
+                    if len(os.read(ufd, 8)) != 8:
+                        return 6
+                finally:
+                    os.close(ufd)
+            Path("/tmp/ok").write_bytes(b"rw")
+            Sys.unshare(CloneFlag.NEWUTS | CloneFlag.NEWIPC | CloneFlag.NEWNET)
+            try:
+                Path("/ro-test").write_bytes(b"x")
+            except OSError as exc:
+                return 0 if (ro and exc.errno == errno.EROFS) else 2
+            return 3 if ro else 0
+
+        rc = self._run_session(
+            f"{lc.cell.name}-probe", lc.cell.exec_fn(probe)
+        )
+        if rc != 0:
+            raise AssertionError(
+                f"{lc.cell.name}: fs/ns probe failed (rc={rc})"
+            )
+        self.note(f"{lc.cell.name}: exec_fn(ro={ro}, dev={has_dev}) -> ok")
+
+    def _rule_pty_and_pod_ipc(self, tc: ChoiceStream) -> None:
+        dev_cells = [c for c in self._live() if c.devfs]
+        if not dev_cells:
+            self._rule_boot(tc)
+            return
+        lc = tc.pick(dev_cells)
+        self.word("pty")
+        msg = f"pty-{self._seq}-{tc.draw_int(10, 99)}".encode("ascii")
+
+        def check_pty() -> int:
+            if not os.path.exists("/dev/pts/ptmx"):
+                return 0
+            m_fd, s_fd = pty.openpty()
+            try:
+                os.write(s_fd, msg + b"\n")
+                return 0 if msg in os.read(m_fd, 64) else 1
+            finally:
+                os.close(m_fd)
+                os.close(s_fd)
+
+        with lc.cell.exec_fn(check_pty) as sess:
+            if sess.wait() != 0:
+                raise AssertionError("pty roundtrip failed")
+
+        mates = [
+            o
+            for o in dev_cells
+            if o is not lc
+            and (o.cell.name == lc.pod_peer or lc.cell.name == o.pod_peer)
+        ]
+        if mates:
+            mate = mates[0]
+            qname = f"/q{self._seq}_{tc.draw_int(1, 99)}".encode("ascii")
+            bare = qname[1:].decode("ascii")
+
+            def mk_q() -> int:
+                if not os.path.ismount("/dev/mqueue"):
+                    return 10
+                mqd: int = Sys._LIBC.mq_open(
+                    ctypes.c_char_p(qname),
+                    ctypes.c_int(os.O_CREAT | os.O_RDWR),
+                    ctypes.c_uint(0o600),
+                    ctypes.c_void_p(0),
+                )
+                if mqd < 0:
+                    return 11
+                os.close(mqd)
+                return 0
+
+            with lc.cell.exec_fn(mk_q) as s1:
+                if s1.wait() == 0:
+                    with mate.cell.exec_fn(
+                        lambda: (
+                            0
+                            if (
+                                bare in os.listdir("/dev/mqueue")
+                                and Sys._LIBC.mq_unlink(ctypes.c_char_p(qname))
+                                == 0
+                            )
+                            else 1
+                        )
+                    ) as s2:
+                        if s2.wait() != 0:
+                            raise AssertionError("pod mqueue not shared")
+        self.note(f"{lc.cell.name}: pty + pod mqueue -> ok")
+
+    def _rule_hot_swap_or_autokill(self, tc: ChoiceStream) -> None:
+        live = self._live()
+        if not live:
+            self._rule_boot(tc)
+            live = self._live()
+        lc = tc.pick(live)
+
+        if tc.draw_bool():
+            if lc.mnt_depth == 0:
+                self.word("mount")
+                if tc.draw_bool():
+                    sub = Path(self._tmp.name) / f"b{self._seq}"
+                    self._seq += 1
+                    sub.mkdir(mode=0o755, exist_ok=True)
+                    (sub / "v").write_bytes(b"bind")
+                    lc.cell.bind_mount(str(sub), "mnt")
+                    lc.mnt_locked = True
+                else:
+                    lc.cell.mount_fs("tmpfs", "mnt")
+                    with lc.cell.exec_fn(
+                        lambda: (Path("/mnt/v").write_bytes(b"v1"), 0)[1]
+                    ) as s:
+                        s.wait()
+                    lc.mnt_locked = False
+                lc.mnt_depth = 1
+                self.note(
+                    f"{lc.cell.name}: hot mount /mnt (locked={lc.mnt_locked})"
+                )
+                return
+
+            self.word("swap")
+            m2 = lc.cell.ul.make_mount("tmpfs")
+            try:
+                vfd = os.open(
+                    "v",
+                    os.O_CREAT | os.O_WRONLY | os.O_CLOEXEC,
+                    0o644,
+                    dir_fd=m2,
+                )
+                os.write(vfd, b"v2")
+                os.close(vfd)
+                Sys.move_mount(
+                    m2,
+                    "",
+                    lc.cell.mntns_fd,
+                    "mnt",
+                    MoveMountFlag.F_EMPTY_PATH
+                    | MoveMountFlag.T_MNTNS
+                    | MoveMountFlag.BENEATH,
+                )
+                lc.mnt_depth += 1
+            finally:
+                os.close(m2)
+
+            locked = lc.mnt_locked
+
+            def peel() -> int:
+                Sys.umount2("/mnt", UmountFlag.DETACH)
+                if Path("/mnt/v").read_bytes() != b"v2":
+                    return 3
+                if locked:
+                    try:
+                        Sys.umount2("/mnt", UmountFlag.DETACH)
+                    except OSError as exc:
+                        return 0 if exc.errno == errno.EINVAL else 1
+                    return 2
+                return 0
+
+            with lc.cell.exec_fn(peel) as s:
+                if s.wait() != 0:
+                    raise AssertionError("MOVE_MOUNT_BENEATH swap failed")
+            lc.mnt_depth -= 1
+            self.note(f"{lc.cell.name}: beneath swap (locked={locked}) -> ok")
+            return
+
+        r_p, w_p = os.pipe2(os.O_CLOEXEC)
+        hr_p, hw_p = os.pipe2(os.O_CLOEXEC)
+        try:
+            self.word("autokill")
+
+            def sleeper() -> int:
+                os.close(r_p)
+                os.close(hr_p)
+                if Sys.fork() == 0:
+                    os.close(w_p)
+                    os.close(hw_p)
+                    os._exit(0)
+                os.write(w_p, b"S")
+                os.close(w_p)
+                signal.pause()
+                return 0
+
+            sess = lc.cell.exec_fn(sleeper, autokill=True)
+        except Exception:
+            for fd in (r_p, w_p, hr_p, hw_p):
+                Sys.close_fd(fd)
+            raise
+        os.close(w_p)
+        os.close(hw_p)
+        os.read(r_p, 1)
+        os.close(r_p)
+        try:
+            dup_fd = os.dup(sess.pidfd)
+            try:
+                sess.close()
+                poller = select.poll()
+                poller.register(hr_p, select.POLLIN)
+                if poller.poll(0):
+                    raise AssertionError("autokill fired before last close")
+            finally:
+                os.close(dup_fd)
+            poller = select.poll()
+            poller.register(hr_p, select.POLLIN)
+            if not poller.poll(5000) or os.read(hr_p, 1) != b"":
+                raise AssertionError("autokill did not terminate session")
+        finally:
+            os.close(hr_p)
+        self.note(f"{lc.cell.name}: autokill refcount + orphan reap -> ok")
+
+    def _rule_pivot(self, tc: ChoiceStream) -> None:
+        cands = [
+            c
+            for c in self._live()
+            if not c.ro_root
+            and not c.devfs
+            and not c.host_rt
+            and not c.pivoted
+            and c.mnt_depth == 0
+        ]
+        if not cands:
+            self._rule_stop(tc)
+            return
+        lc = tc.pick(cands)
+        self.word("pivot")
+
+        def do_pivot() -> int:
+            fsfd = Sys.fsopen("tmpfs")
+            Sys.fsconfig(fsfd, FsconfigCmd.CMD_CREATE)
+            mfd = Sys.fsmount(fsfd)
+            os.close(fsfd)
+            for d in ("old", "mnt", "tmp", "proc"):
+                os.mkdir(d, 0o755, dir_fd=mfd)
+            Sys.move_mount(
+                mfd, "", Sys.AT_FDCWD, "/mnt", MoveMountFlag.F_EMPTY_PATH
+            )
+            os.close(mfd)
+            os.chdir("/mnt")
+            Sys.pivot_root(".", "old")
+            os.chdir("/")
+            Sys.umount2("/old", UmountFlag.DETACH)
+            return 0
+
+        with lc.cell.exec_fn(do_pivot) as s:
+            if s.wait() != 0:
+                raise AssertionError(f"{lc.cell.name}: pivot_root failed")
+        lc.cell.root_dfd = Sys.close_fd(lc.cell.root_dfd)
+        lc.cell.mount_fs("proc", "proc")
+        lc.pivoted = True
+        self.note(f"{lc.cell.name}: pivot_root + external proc remount -> ok")
+
+    def _rule_stop(self, tc: ChoiceStream) -> None:
+        live = self._live()
+        if not live:
+            self._rule_boot(tc)
+            return
+        self.word("stop")
+        lc = tc.pick(live)
+        if tc.draw_bool():
+            rc = tc.draw_int(0, 30)
+            res = lc.cell.shutdown(rc)
+            exp: int | None = rc
+        else:
+            lc.cell.kill(signal.SIGKILL)
+            res = lc.cell.wait()
+            exp = -int(signal.SIGKILL)
+        lc.alive = False
+        evs = self._mgr.poll_events(1.0)
+        got = [
+            e
+            for e in evs
+            if e.kind is EventKind.CELL and e.name == lc.cell.name
+        ]
+        if not got or got[0].exit_code != exp or res.exit_code != exp:
+            raise AssertionError(
+                f"{lc.cell.name}: stop expected {exp}, got {res}/{got}"
+            )
+        lc.cell.close()
+        self.note(f"{lc.cell.name}: stopped exit={exp}")
+
+    def step(self, tc: ChoiceStream) -> None:
+        rule = tc.weighted(
+            (
+                (16, self._rule_boot),
+                (14, self._rule_exec_probe),
+                (12, self._rule_pty_and_pod_ipc),
+                (14, self._rule_hot_swap_or_autokill),
+                (6, self._rule_pivot),
+                (8, self._rule_stop),
+            )
+        )
+        rule(tc)
+
+    def check_invariants(self) -> None:
+        for lc in self._cells:
+            if lc.alive and lc.cell.ul.poll_dead(0):
+                raise AssertionError(f"{lc.cell.name}: died unexpectedly")
+
+    def close(self) -> None:
+        self._mgr.close()
+        for lc in self._cells:
+            lc.cell.close()
+        self._cells.clear()
+        self._tmp.cleanup()
+
+
+class _LandlockRulesetAttr(ctypes.Structure):
+    _fields_ = [
+        ("handled_access_fs", ctypes.c_uint64),
+        ("handled_access_net", ctypes.c_uint64),
+        ("scoped", ctypes.c_uint64),
+        ("quiet_access_fs", ctypes.c_uint64),
+        ("quiet_access_net", ctypes.c_uint64),
+        ("quiet_scoped", ctypes.c_uint64),
+        ("handled_permissions", ctypes.c_uint64),
+    ]
+
+
+class _LandlockNamespaceAttr(ctypes.Structure):
+    _fields_ = [
+        ("permissions", ctypes.c_uint64),
+        ("allowed_namespace_types", ctypes.c_uint64),
+        ("quiet_namespace_types", ctypes.c_uint64),
+    ]
+
+
+class Landlock(NsExecMachine):
+    """Parametric Landlock LANDLOCK_PERMISSION_NAMESPACE_USE state machine."""
+
+    STEPS: ClassVar[int] = 14
+
+    def __init__(self) -> None:
+        super().__init__()
+        self._has_timens = os.path.exists("/proc/self/ns/time")
+        try:
+            abi = Sys.syscall(
+                "landlock_create_ruleset",
+                ctypes.c_void_p(0),
+                ctypes.c_size_t(0),
+                ctypes.c_uint32(1),
+            )
+        except OSError as exc:
+            if exc.errno in (errno.ENOSYS, errno.EOPNOTSUPP):
+                raise SkipScenario("Landlock not enabled") from exc
+            raise
+        if abi < 12:
+            raise SkipScenario(f"Landlock ABI {abi} < 12")
+
+    @staticmethod
+    def _restrict(allowed_mask: int) -> None:
+        rattr = _LandlockRulesetAttr(handled_permissions=1)
+        rfd = Sys.syscall(
+            "landlock_create_ruleset",
+            ctypes.c_void_p(ctypes.addressof(rattr)),
+            ctypes.c_size_t(ctypes.sizeof(rattr)),
+            ctypes.c_uint32(0),
+        )
+        try:
+            if allowed_mask:
+                nattr = _LandlockNamespaceAttr(
+                    permissions=1,
+                    allowed_namespace_types=allowed_mask,
+                    quiet_namespace_types=0,
+                )
+                Sys.syscall(
+                    "landlock_add_rule",
+                    ctypes.c_int(rfd),
+                    ctypes.c_int(3),
+                    ctypes.c_void_p(ctypes.addressof(nattr)),
+                    ctypes.c_uint32(0),
+                )
+            Sys.syscall(
+                "landlock_restrict_self",
+                ctypes.c_int(rfd),
+                ctypes.c_uint32((1 << 4) | (1 << 0)),
+            )
+        finally:
+            os.close(rfd)
+
+    def step(self, tc: ChoiceStream) -> None:
+        shareable = [
+            CloneFlag.NEWCGROUP,
+            CloneFlag.NEWIPC,
+            CloneFlag.NEWUTS,
+            CloneFlag.NEWNET,
+        ]
+        if self._has_timens:
+            shareable.append(CloneFlag.NEWTIME)
+        all_types = [
+            CloneFlag.NEWUSER,
+            CloneFlag.NEWNS,
+            CloneFlag.NEWPID,
+            *shareable,
+        ]
+
+        allowed = 0
+        for flag in all_types:
+            if tc.draw_int(0, 2) > 0:
+                allowed |= int(flag)
+        shared_flags = [f for f in shareable if tc.draw_bool()]
+        shared_mask = 0
+        for flag in shared_flags:
+            shared_mask |= int(flag)
+        active_mask = 0
+        for flag in all_types:
+            active_mask |= int(flag)
+        probe_flag = tc.pick(shareable)
+        self.word(NS_NAMES[probe_flag])
+
+        actor = Actor(landlock_mask=allowed)
+        unit = UnitModel(has_root=True, shared_host_mask=shared_mask)
+        exp_open = Oracle.open(actor, int(NsExecFlag.DEFAULT), active_mask)
+        exp_share = Oracle.share_nsfd(
+            actor,
+            UnitModel(),
+            FdKind.NS_SHAREABLE,
+            int(probe_flag),
+            has_timens=self._has_timens,
+        )
+        exp_clone = Oracle.clone_into(
+            actor,
+            unit,
+            FdKind.NSEXEC,
+            extra_flags=int(CloneFlag.AUTOREAP),
+            exit_signal=0,
+            active_ns_mask=active_mask,
+        )
+        self.note(
+            f"landlock(allow=0x{allowed:x}, shared=0x{shared_mask:x}, "
+            f"probe={NS_NAMES[probe_flag]}) -> "
+            f"open={exp_open or 0}, share={exp_share or 0}, "
+            f"clone={exp_clone or 0}"
+        )
+
+        def worker() -> None:
+            with ExitStack() as stack:
+                cell = stack.enter_context(Cell("ll"))
+                if shared_flags:
+                    cell.share_host(shared_flags)
+                cell.setup_rootfs(procfs=False)
+                dst = stack.enter_context(NsExec())
+                src_ns = cell.ul.get_nsfd(probe_flag)
+                stack.callback(Sys.close_fd, src_ns)
+
+                self._restrict(allowed)
+
+                opened = self.check_call("ll open", exp_open, NsExec)
+                if opened is not None:
+                    opened.close()
+                self.check_call(
+                    "ll share", exp_share, lambda: dst.share_nsfd(src_ns)
+                )
+                if exp_clone is None:
+                    pid, _ = cell.ul.spawn_fn(
+                        lambda: 0, extra_flags=CloneFlag.AUTOREAP
+                    )
+                    if pid <= 0 or cell.wait().exit_code != 0:
+                        raise AssertionError("allowed ll clone failed")
+                else:
+                    self.check_call(
+                        "ll clone",
+                        exp_clone,
+                        lambda: cell.ul.clone_into(
+                            CloneFlag.AUTOREAP, exit_signal=0
+                        ),
+                    )
+
+        self.run_isolated(worker)
+
+
+@dataclass(frozen=True)
+class Scenario:
+    name: str
+    machine_cls: type[NsExecMachine]
+    default_cases: int
+
+
+DEFAULT_CASES: Final[int] = 4
+
+SCENARIOS: Final[tuple[Scenario, ...]] = (
+    Scenario("lifecycle", Lifecycle, DEFAULT_CASES),
+    Scenario("idmap", Idmap, DEFAULT_CASES),
+    Scenario("mounts", Mounts, DEFAULT_CASES),
+    Scenario("cells", Cells, DEFAULT_CASES),
+    Scenario("landlock", Landlock, DEFAULT_CASES),
+)
+
+SCENARIO_MAP: Final[dict[str, Scenario]] = {s.name: s for s in SCENARIOS}
+
+
+@dataclass(frozen=True)
+class SuiteRunner:
+    selected: Sequence[Scenario]
+    seed: int
+    cases_override: int | None
+    steps_override: int | None
+    case: int | None
+
+    @staticmethod
+    def probe_nsexec() -> tuple[bool, str]:
+        try:
+            ul = NsExec()
+        except OSError as exc:
+            if exc.errno in SKIP_ERRNOS:
+                return False, f"nsexec_open() unavailable: {exc}"
+            raise
+        with ul:
+            try:
+                ul.map_self()
+                mfd = ul.make_mount("tmpfs")
+            except OSError as exc:
+                return False, f"nsexec setup unavailable: {exc}"
+            try:
+                os.mkdir("probe", 0o755, dir_fd=mfd)
+            finally:
+                os.close(mfd)
+        return True, ""
+
+    @staticmethod
+    def _load_ksft() -> Any:
+        ksft_dir = str(Path(__file__).resolve().parents[1] / "kselftest")
+        if ksft_dir not in sys.path:
+            sys.path.insert(0, ksft_dir)
+        return importlib.import_module("ksft")
+
+    def _config_for(self, spec: Scenario) -> RunConfig:
+        cases = (
+            self.cases_override
+            if self.cases_override is not None
+            else spec.default_cases
+        )
+        return RunConfig(
+            seed=self.seed,
+            cases=cases,
+            steps=self.steps_override,
+            case=self.case,
+        )
+
+    @staticmethod
+    def _planned(cfg: RunConfig) -> int:
+        return 1 if cfg.case is not None else cfg.cases
+
+    @staticmethod
+    def _case_label(name: str, idx: int) -> str:
+        return f"{name}.{idx:02d}"
+
+    def run_ktap(self) -> int:
+        ksft = self._load_ksft()
+        supported, skip_reason = self.probe_nsexec()
+        configs = [(spec, self._config_for(spec)) for spec in self.selected]
+        ksft.print_header()
+        ksft.set_plan(sum(self._planned(cfg) for _, cfg in configs))
+        ksft.print_msg(
+            f"seed 0x{self.seed:016x} "
+            f"(replay: NSEXEC_SEED=0x{self.seed:016x})"
+        )
+        sys.stdout.flush()
+
+        for spec, cfg in configs:
+            planned = self._planned(cfg)
+            if not supported:
+                ksft.print_msg(f"{spec.name}: {skip_reason}")
+                for idx in range(planned):
+                    ksft.test_result_skip(self._case_label(spec.name, idx))
+                sys.stdout.flush()
+                continue
+
+            emitted = 0
+            try:
+                for res in Machine.iter_cases(
+                    spec.name, spec.machine_cls, cfg
+                ):
+                    label = (
+                        f"{spec.name}.{res.name}"
+                        if res.name
+                        else self._case_label(spec.name, emitted)
+                    )
+                    emitted += 1
+                    if res.failure is None:
+                        ksft.test_result_pass(label)
+                    else:
+                        report = res.failure.format_report(
+                            seed=self.seed, cmd="./test_smoke.sh"
+                        )
+                        for line in report.splitlines():
+                            ksft.print_msg(line)
+                        ksft.test_result_fail(label)
+                    sys.stdout.flush()
+            except SkipScenario as exc:
+                ksft.print_msg(f"{spec.name}: {exc}")
+                for idx in range(emitted, planned):
+                    ksft.test_result_skip(self._case_label(spec.name, idx))
+                sys.stdout.flush()
+
+        ksft.print_cnts()
+        sys.stdout.flush()
+        counts: dict[str, int] = ksft.ksft_cnt
+        if counts["fail"] > 0:
+            return int(ksft.KSFT_FAIL)
+        if counts["pass"] == 0 and counts["skip"] > 0:
+            return int(ksft.KSFT_SKIP)
+        return int(ksft.KSFT_PASS)
+
+    def run_cli(self) -> int:
+        supported, skip_reason = self.probe_nsexec()
+        if not supported:
+            print(f"SKIP: {skip_reason}")
+            return 4
+
+        print(f"seed 0x{self.seed:016x}", flush=True)
+
+        tty = sys.stderr.isatty()
+        ok = True
+        for spec in self.selected:
+            cfg = self._config_for(spec)
+            t0 = time.monotonic()
+
+            def on_prog(
+                msg: str, name: str = spec.name, started: float = t0
+            ) -> None:
+                if tty:
+                    dt = time.monotonic() - started
+                    sys.stderr.write(f"\r\x1b[K{name:<12} {msg} {dt:.1f}s")
+                    sys.stderr.flush()
+
+            try:
+                failure = Machine.run(
+                    spec.name, spec.machine_cls, cfg, progress=on_prog
+                )
+            except SkipScenario as exc:
+                if tty:
+                    sys.stderr.write("\r\x1b[K")
+                print(f"{spec.name:<12} skipped ({exc})", flush=True)
+                continue
+
+            if tty:
+                sys.stderr.write("\r\x1b[K")
+                sys.stderr.flush()
+            dt = time.monotonic() - t0
+            verdict = "passed" if failure is None else "failed"
+            print(
+                f"{spec.name:<12} {verdict} {self._planned(cfg):>3} cases "
+                f"{dt:>7.1f}s",
+                flush=True,
+            )
+            if failure is not None:
+                ok = False
+                print(
+                    failure.format_report(seed=self.seed, cmd="./selftest.py"),
+                    flush=True,
+                )
+        return 0 if ok else 1
+
+
+def _env_int(name: str) -> int | None:
+    raw = os.environ.get(name)
+    return int(raw, 0) if raw else None
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+    parser = argparse.ArgumentParser(
+        description="Model-based stochastic selftest for nsexec(2)."
+    )
+    parser.add_argument("--ktap", action="store_true")
+    parser.add_argument("--seed", type=Machine.parse_seed, default=None)
+    parser.add_argument("--cases", type=int, default=None)
+    parser.add_argument("--steps", type=int, default=None)
+    parser.add_argument("--case", type=int, default=None)
+    parser.add_argument(
+        "scenarios",
+        nargs="*",
+        choices=[s.name for s in SCENARIOS],
+    )
+    ns = parser.parse_args(argv)
+
+    env_seed = os.environ.get("NSEXEC_SEED")
+    if ns.seed is not None:
+        seed = ns.seed
+    elif env_seed:
+        seed = Machine.parse_seed(env_seed)
+    else:
+        seed = Machine.generate_seed()
+    cases = ns.cases if ns.cases is not None else _env_int("NSEXEC_CASES")
+    steps = ns.steps if ns.steps is not None else _env_int("NSEXEC_STEPS")
+    case = ns.case if ns.case is not None else _env_int("NSEXEC_CASE")
+    if case is not None and case < 0:
+        print("error: case index must be non-negative", file=sys.stderr)
+        return 2
+    selected = (
+        [SCENARIO_MAP[name] for name in ns.scenarios]
+        if ns.scenarios
+        else list(SCENARIOS)
+    )
+
+    runner = SuiteRunner(selected, seed, cases, steps, case)
+    return runner.run_ktap() if ns.ktap else runner.run_cli()
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/testing/selftests/nsexec/settings b/tools/testing/selftests/nsexec/settings
new file mode 100644
index 000000000000..6091b45d226b
--- /dev/null
+++ b/tools/testing/selftests/nsexec/settings
@@ -0,0 +1 @@
+timeout=120
diff --git a/tools/testing/selftests/nsexec/test_smoke.sh b/tools/testing/selftests/nsexec/test_smoke.sh
new file mode 100755
index 000000000000..2b81ae184058
--- /dev/null
+++ b/tools/testing/selftests/nsexec/test_smoke.sh
@@ -0,0 +1,11 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0
+
+ksft_skip=4
+
+command -v python3 >/dev/null 2>&1 || exit $ksft_skip
+python3 -c 'import ctypes, sys; sys.exit(sys.version_info < (3, 11))' \
+	2>/dev/null || exit $ksft_skip
+
+DIR="$(dirname "$(readlink -f "$0")")"
+exec python3 "$DIR/selftest.py" --ktap "$@"
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* [RFC PATCH v9 29/29] MAINTAINERS: Add entry for NSEXEC
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (27 preceding siblings ...)
  2026-12-01  3:10 ` [RFC PATCH v9 28/29] selftests/nsexec: Add nsexec test suite Jarkko Sakkinen
@ 2026-12-01  3:10 ` Jarkko Sakkinen
  2026-12-01  4:02 ` [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  3:10 UTC (permalink / raw)
  To: fsdevel
  Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
	linux-doc, linux-fsdevel, linux-integrity, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Aleksa Sarai,
	Alexander Mikhalitsyn, Alexander Viro, Alexei Starovoitov,
	Andrew Morton, Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann,
	Baolin Wang, Ben Segall, Christian Brauner, Daniel Borkmann,
	David Hildenbrand, David Howells, David Woodhouse,
	Davidlohr Bueso, Dietmar Eggemann, Eduard Zingerman,
	Emil Tsalapatis, Eric Biggers, Georgia Garcia, Giuseppe Scrivano,
	Günther Noack, Hugh Dickins, Ihor Solodrai, Ingo Molnar,
	James Morris, Jan Kara, Jason Gunthorpe, Jeff Layton, Jiri Olsa,
	John Johansen, Jonathan Corbet, Josef Bacik, Juri Lelli,
	Kees Cook, K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

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

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 MAINTAINERS | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/MAINTAINERS b/MAINTAINERS
index c72a281a8167..9a856e611796 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -19976,6 +19976,17 @@ S:	Maintained
 F:	Documentation/core-api/symbol-namespaces.rst
 F:	scripts/nsdeps
 
+NSEXEC
+M:	David Howells <dhowells@redhat.com>
+M:	Jarkko Sakkinen <jarkko@kernel.org>
+L:	linux-fsdevel@vger.kernel.org
+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 <Basavaraj.Natikar@amd.com>
 M:	Shyam Sundar S K <Shyam-sundar.S-k@amd.com>
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 32+ messages in thread

* Re: [RFC PATCH v9 00/29] nsexec: Staged namespace execution
  2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
                   ` (28 preceding siblings ...)
  2026-12-01  3:10 ` [RFC PATCH v9 29/29] MAINTAINERS: Add entry for NSEXEC Jarkko Sakkinen
@ 2026-12-01  4:02 ` Jarkko Sakkinen
  29 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  4:02 UTC (permalink / raw)
  To: fsdevel
  Cc: bpf, containers, linux-api, linux-arch, linux-doc, linux-fsdevel,
	linux-integrity, linux-kernel, linux-kselftest, linux-mm,
	linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
	Alexander Viro, Alexei Starovoitov, Andrew Morton,
	Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann, Baolin Wang,
	Ben Segall, Christian Brauner, Daniel Borkmann, David Hildenbrand,
	David Howells, David Woodhouse, Davidlohr Bueso, Dietmar Eggemann,
	Eduard Zingerman, Emil Tsalapatis, Eric Biggers, Georgia Garcia,
	Giuseppe Scrivano, Günther Noack, Hugh Dickins,
	Ihor Solodrai, Ingo Molnar, James Morris, Jan Kara,
	Jason Gunthorpe, Jeff Layton, Jiri Olsa, John Johansen,
	Jonathan Corbet, Josef Bacik, Juri Lelli, Kees Cook,
	K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

On Tue, Dec 01, 2026 at 05:09:32AM +0200, Jarkko Sakkinen wrote:
> 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/20261128235808.2369970-1-jarkko@kernel.org/
> v7: https://lore.kernel.org/linux-fsdevel/20261122193539.3334213-1-jarkko@kernel.org/
> v6: https://lore.kernel.org/linux-fsdevel/20261122011809.2667684-1-jarkko@kernel.org/
> v5: https://lore.kernel.org/linux-fsdevel/20261121000844.1863324-1-jarkko@kernel.org/
> v4: https://lore.kernel.org/linux-fsdevel/20261119224312.1037966-1-jarkko@kernel.org/
> v3: https://lore.kernel.org/linux-fsdevel/20261118193539.240065-1-jarkko@kernel.org/
> v2: https://lore.kernel.org/linux-fsdevel/20261117231352.3816603-1-jarkko@kernel.org/
> v1: https://lore.kernel.org/linux-fsdevel/20261117050841.3289652-1-jarkko@kernel.org/
> 
> Cc: bpf@vger.kernel.org
> Cc: containers@lists.linux.dev
> Cc: linux-api@vger.kernel.org
> Cc: linux-arch@vger.kernel.org
> Cc: linux-doc@vger.kernel.org
> Cc: linux-fsdevel@vger.kernel.org
> Cc: linux-integrity@vger.kernel.org
> Cc: linux-kernel@vger.kernel.org
> Cc: linux-kselftest@vger.kernel.org
> Cc: linux-mm@kvack.org
> Cc: linux-security-module@vger.kernel.org
> Cc: Aleksa Sarai <aleksa@amutable.com>
> Cc: Alexander Mikhalitsyn <alex@amutable.com>
> Cc: Alexander Viro <viro@zeniv.linux.org.uk>
> Cc: Alexei Starovoitov <ast@kernel.org>
> Cc: Andrew Morton <akpm@linux-foundation.org>
> Cc: Andrii Nakryiko <andrii@kernel.org>
> Cc: Andy Lutomirski <luto@amacapital.net>
> Cc: Arnd Bergmann <arnd@arndb.de>
> Cc: Baolin Wang <baolin.wang@linux.alibaba.com>
> Cc: Ben Segall <bsegall@google.com>
> Cc: Christian Brauner <brauner@kernel.org>
> Cc: Daniel Borkmann <daniel@iogearbox.net>
> Cc: David Hildenbrand <david@kernel.org>
> Cc: David Howells <dhowells@redhat.com>
> Cc: David Woodhouse <dwmw2@infradead.org>
> Cc: Davidlohr Bueso <dave@stgolabs.net>
> Cc: Dietmar Eggemann <dietmar.eggemann@arm.com>
> Cc: Eduard Zingerman <eddyz87@gmail.com>
> Cc: Emil Tsalapatis <emil@etsalapatis.com>
> Cc: Eric Biggers <ebiggers@kernel.org>
> Cc: Georgia Garcia <georgia.garcia@canonical.com>
> Cc: Giuseppe Scrivano <giuseppe@scrivano.org>
> Cc: "Günther Noack" <gnoack@google.com>
> Cc: Hugh Dickins <hughd@google.com>
> Cc: Ihor Solodrai <ihor.solodrai@linux.dev>
> Cc: Ingo Molnar <mingo@redhat.com>
> Cc: James Morris <jmorris@namei.org>
> Cc: Jan Kara <jack@suse.cz>
> Cc: Jason Gunthorpe <jgg@nvidia.com>
> Cc: Jarkko Sakkinen <jarkko@kernel.org>
> Cc: Jeff Layton <jlayton@kernel.org>
> Cc: Jiri Olsa <jolsa@kernel.org>
> Cc: John Johansen <john.johansen@canonical.com>
> Cc: Jonathan Corbet <corbet@lwn.net>
> Cc: Josef Bacik <josef@toxicpanda.com>
> Cc: Juri Lelli <juri.lelli@redhat.com>
> Cc: Kees Cook <kees@kernel.org>
> Cc: K Prateek Nayak <kprateek.nayak@amd.com>
> Cc: KP Singh <kpsingh@kernel.org>
> Cc: Kumar Kartikeya Dwivedi <memxor@gmail.com>
> Cc: Lennart Poettering <lennart@poettering.net>
> Cc: "Liam R. Howlett" <liam@infradead.org>
> Cc: Manfred Spraul <manfred@colorfullife.com>
> Cc: Martin KaFai Lau <martin.lau@linux.dev>
> Cc: Matt Bobrowski <matt@bobrowski.net>
> Cc: Mel Gorman <mgorman@suse.de>
> Cc: Michal Hocko <mhocko@suse.com>
> Cc: "Mickaël Salaün" <mic@digikod.net>
> Cc: Mickaël Salaün <mic@digikod.net>
> Cc: Mike Rapoport <rppt@kernel.org>
> Cc: Neal Gompa <neal@gompa.dev>
> Cc: Oleg Nesterov <oleg@redhat.com>
> Cc: Paul Moore <paul@paul-moore.com>
> Cc: Pavel Tikhomirov <ptikhomirov@virtuozzo.com>
> Cc: Peter Zijlstra <peterz@infradead.org>
> Cc: Randy Dunlap <rdunlap@infradead.org>
> Cc: "Serge E. Hallyn" <serge@hallyn.com>
> Cc: Serge Hallyn <sergeh@kernel.org>
> Cc: Shuah Khan <skhan@linuxfoundation.org>
> Cc: Song Liu <song@kernel.org>
> Cc: Stephen Smalley <stephen.smalley.work@gmail.com>
> Cc: Steven Rostedt <rostedt@goodmis.org>
> Cc: Valentin Schneider <vschneid@redhat.com>
> Cc: Vincent Guittot <vincent.guittot@linaro.org>
> Cc: Yonghong Song <yonghong.song@linux.dev>
> Cc: Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
> 
> 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
> 

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

^ permalink raw reply	[flat|nested] 32+ messages in thread

* Re: [RFC PATCH v9 14/29] nsexec: Add nsexec_open() system call
  2026-12-01  3:09 ` [RFC PATCH v9 14/29] nsexec: Add nsexec_open() system call Jarkko Sakkinen
@ 2026-12-01  6:18   ` Jarkko Sakkinen
  0 siblings, 0 replies; 32+ messages in thread
From: Jarkko Sakkinen @ 2026-12-01  6:18 UTC (permalink / raw)
  To: fsdevel
  Cc: bpf, containers, linux-api, linux-arch, linux-doc, linux-fsdevel,
	linux-integrity, linux-kernel, linux-kselftest, linux-mm,
	linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
	Alexander Viro, Alexei Starovoitov, Andrew Morton,
	Andrii Nakryiko, Andy Lutomirski, Arnd Bergmann, Baolin Wang,
	Ben Segall, Christian Brauner, Daniel Borkmann, David Hildenbrand,
	David Howells, David Woodhouse, Davidlohr Bueso, Dietmar Eggemann,
	Eduard Zingerman, Emil Tsalapatis, Eric Biggers, Georgia Garcia,
	Giuseppe Scrivano, Günther Noack, Hugh Dickins,
	Ihor Solodrai, Ingo Molnar, James Morris, Jan Kara,
	Jason Gunthorpe, Jeff Layton, Jiri Olsa, John Johansen,
	Jonathan Corbet, Josef Bacik, Juri Lelli, Kees Cook,
	K Prateek Nayak, KP Singh, Kumar Kartikeya Dwivedi,
	Lennart Poettering, Liam R. Howlett, Manfred Spraul,
	Martin KaFai Lau, Matt Bobrowski, Mel Gorman, Michal Hocko,
	Mickaël Salaün, Mike Rapoport, Neal Gompa,
	Oleg Nesterov, Paul Moore, Pavel Tikhomirov, Peter Zijlstra,
	Randy Dunlap, Serge E. Hallyn, Serge Hallyn, Shuah Khan, Song Liu,
	Stephen Smalley, Steven Rostedt, Valentin Schneider,
	Vincent Guittot, Yonghong Song, Zygmunt Krynicki

On Tue, Dec 01, 2026 at 05:09:46AM +0200, Jarkko Sakkinen wrote:
> Setting up an isolated namespace environment from a multithreaded
> manager process currently requires helper processes to call unshare()
> and pass file descriptors back over sockets.
> 
> Add the 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.
> 
> Co-developed-by: David Howells <dhowells@redhat.com>
> Signed-off-by: David Howells <dhowells@redhat.com>
> Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
> ---
>  include/linux/syscalls.h |   1 +
>  kernel/nsexec.c          | 107 +++++++++++++++++++++++++++++++++++++++
>  kernel/sys_ni.c          |   3 ++
>  3 files changed, 111 insertions(+)
> 
> diff --git a/include/linux/syscalls.h b/include/linux/syscalls.h
> index 72308cc11908..7dc55fb0857e 100644
> --- a/include/linux/syscalls.h
> +++ b/include/linux/syscalls.h
> @@ -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
> diff --git a/kernel/nsexec.c b/kernel/nsexec.c
> index b9fc8fdf9b5c..3277822386f6 100644
> --- a/kernel/nsexec.c
> +++ b/kernel/nsexec.c
> @@ -134,3 +134,110 @@ void nsexec_exit(struct pid_namespace *pid_ns, struct task_struct *tsk)
>  	__wake_up(&c->waitq, TASK_NORMAL, 0, poll_to_key(EPOLLHUP));
>  	nsexec_put(c);
>  }
> +
> +static struct user_namespace *nsexec_create_user_ns(void)
> +{
> +	struct user_namespace *user_ns;
> +	struct cred *new;
> +	int ret;
> +
> +	new = prepare_creds();
> +	if (!new)
> +		return ERR_PTR(-ENOMEM);
> +
> +	ret = create_user_ns(new);
> +	if (ret < 0) {
> +		abort_creds(new);
> +		return ERR_PTR(ret);
> +	}
> +
> +	user_ns = get_user_ns(new->user_ns);
> +	abort_creds(new);
> +	return user_ns;
> +}
> +
> +static struct nsexec *nsexec_create(unsigned int flags)
> +{
> +	u64 clone_flags = CLONE_NEWNS | CLONE_EMPTY_MNTNS | CLONE_NEWPID |
> +			  CLONE_NEWCGROUP | CLONE_NEWUTS | CLONE_NEWIPC |
> +			  CLONE_NEWNET |
> +			  (IS_ENABLED(CONFIG_TIME_NS) ? CLONE_NEWTIME : 0);
> +	struct user_namespace *user_ns;
> +	struct nsproxy *ns;
> +	struct nsexec *c;
> +	int ret;
> +
> +	c = kzalloc_obj(*c, GFP_KERNEL);
> +	if (!c)
> +		return ERR_PTR(-ENOMEM);
> +
> +	init_waitqueue_head(&c->waitq);
> +	spin_lock_init(&c->lock);
> +	refcount_set(&c->usage, 1);
> +	c->flags = flags;
> +
> +	user_ns = nsexec_create_user_ns();
> +	if (IS_ERR(user_ns)) {
> +		ret = PTR_ERR(user_ns);
> +		goto err_put;
> +	}
> +	c->user_ns = user_ns;
> +	ns_ref_active_get(user_ns);
> +
> +	if (!ns_capable(user_ns, CAP_SYS_ADMIN)) {
> +		ret = -EPERM;
> +		goto err_put;
> +	}
> +
> +	ns = create_new_namespaces(clone_flags, current, user_ns, NULL);
> +	if (IS_ERR(ns)) {
> +		ret = PTR_ERR(ns);
> +		goto err_put;
> +	}
> +
> +	if (ns->time_ns != ns->time_ns_for_children) {
> +		get_time_ns(ns->time_ns_for_children);
> +		put_time_ns(ns->time_ns);
> +		ns->time_ns = ns->time_ns_for_children;
> +	}
> +	c->ns = ns;
> +	nsproxy_ns_active_get(ns);
> +
> +	return c;
> +
> +err_put:
> +	nsexec_put(c);
> +	return ERR_PTR(ret);
> +}
> +
> +/**
> + * sys_nsexec_open - Open a new nsexec
> + * @flags: Combination of &enum nsexec_flags values
> + *
> + * Allocate an nsexec owning a fresh child user namespace (with the caller's
> + * effective UID and GID as owner and initially empty ID mappings) and dedicated
> + * empty mount, PID, UTS, IPC, network, cgroup, and time namespaces. Control
> + * operations authorize against capabilities in the nsexec's owning user
> + * namespace.
> + *
> + * Return: Close-on-exec nsexec file descriptor on success, negative error code
> + *         on failure.
> + */
> +SYSCALL_DEFINE1(nsexec_open, unsigned int, flags)

This does not really matter all that much but I was going to rename this
as nsexec() but forgot to do it.

> +{
> +	struct nsexec *c;
> +	int fd;
> +
> +	if (flags & ~NSEXEC_ALL_FLAGS)
> +		return -EINVAL;
> +
> +	c = nsexec_create(flags);
> +	if (IS_ERR(c))
> +		return PTR_ERR(c);

This could be mapped to ioctls if wanted e.g.,

1.  NSEXEC_CREATE with flags parameter, which would be available up
    until clone3().
2.  One-way parameterless NSEXEC_SET_AUTOKILL and NSEXEC_CREATE.

I.e., factor even more like SGX enclave initialization.

For the time being, I don't see anything useful except dropping a single
fallible case from nsexec_open(), which by itself is not gain but in
this sudoku its good to be aware of various sequencing twists (just like
it was in SGX).

> +
> +	fd = anon_inode_getfd("nsexec", &nsexec_fops, c, O_RDWR | O_CLOEXEC);
> +	if (fd < 0)
> +		nsexec_put(c);
> +
> +	return fd;
> +}
> diff --git a/kernel/sys_ni.c b/kernel/sys_ni.c
> index e3202e7cc2a1..760724d57a0d 100644
> --- a/kernel/sys_ni.c
> +++ b/kernel/sys_ni.c
> @@ -399,3 +399,6 @@ COND_SYSCALL(rseq_slice_yield);
>  
>  COND_SYSCALL(uretprobe);
>  COND_SYSCALL(uprobe);
> +
> +/* kernel/nsexec.c */
> +COND_SYSCALL(nsexec_open);
> -- 
> 2.47.3
> 
> 

Br, Jarkko

^ permalink raw reply	[flat|nested] 32+ messages in thread

end of thread, other threads:[~2026-12-01  6:18 UTC | newest]

Thread overview: 32+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-01  3:09 [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 01/29] userns: Factor out idmap validation and commit helpers Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 02/29] userns: Add userns_set_idmap() system call Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 03/29] arch: Wire up " Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 04/29] mount: Add mnt_ns_get_root() Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 05/29] mount: Enforce mount_too_revealing() for foreign mntns Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 06/29] mount: Support MOVE_MOUNT_T_MNTNS in move_mount() Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 07/29] security: Pass flags to security_move_mount() Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 08/29] mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 09/29] apparmor: Mediate MOVE_MOUNT_CLONE as recursive bind Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 10/29] userns: Factor out install_user_ns_cred() Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 11/29] nsproxy: Expose create_new_namespaces() Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 12/29] nsexec: Add core infrastructure Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 13/29] nsexec: Track init lifecycle via copy_process() and pid_namespace Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 14/29] nsexec: Add nsexec_open() system call Jarkko Sakkinen
2026-12-01  6:18   ` Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 15/29] nsexec: Add NSEXEC_GET_NSFD ioctl Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 16/29] nsexec: Add NSEXEC_SHARE_NSFD ioctl Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 17/29] exit: Support P_NSEXEC in waitid() Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 18/29] signal: Support nsexec fds in pidfd_send_signal() Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 19/29] fork: Support CLONE_INTO_NSEXEC in clone3() Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 20/29] fs: Support FSCONFIG_SET_NSEXEC in fsconfig() Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 21/29] proc: Implement ->set_nsexec() fs_context operation Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 22/29] ipc/mqueue: " Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 23/29] security: Add nsexec LSM hooks Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 24/29] landlock: Enforce namespace use restrictions on nsexec Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 25/29] bpf: Register nsexec LSM hooks Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 26/29] arch: Wire up nsexec_open() system call Jarkko Sakkinen
2026-12-01  3:09 ` [RFC PATCH v9 27/29] docs: Document nsexec uAPI Jarkko Sakkinen
2026-12-01  3:10 ` [RFC PATCH v9 28/29] selftests/nsexec: Add nsexec test suite Jarkko Sakkinen
2026-12-01  3:10 ` [RFC PATCH v9 29/29] MAINTAINERS: Add entry for NSEXEC Jarkko Sakkinen
2026-12-01  4:02 ` [RFC PATCH v9 00/29] nsexec: Staged namespace execution Jarkko Sakkinen

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox