* [RFC PATCH v5 01/25] userns: Factor out idmap validation and commit helpers
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 02/25] userns: Add userns_set_idmap() system call Jarkko Sakkinen
` (23 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
Zygmunt Krynicki
map_write() validates extent ranges, translates parent ID ranges, sorts
extents, and installs the resulting map inline for procfs text writes,
preventing non-procfs callers from reusing the same validation and
commit path.
Extract validate_and_insert_extent(), free_new_idmap(),
resolve_new_idmap(), and commit_new_idmap() out of map_write() with no
functional change.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
kernel/user_namespace.c | 159 ++++++++++++++++++++--------------------
1 file changed, 80 insertions(+), 79 deletions(-)
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index cd748e1cbace..6b9673dcdc67 100644
--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -938,6 +938,80 @@ static bool verify_root_map(const struct file *file,
return true;
}
+static int validate_and_insert_extent(struct uid_gid_map *new_map,
+ struct uid_gid_extent *extent)
+{
+ if ((extent->first == (u32)-1) || (extent->lower_first == (u32)-1))
+ return -EINVAL;
+
+ if ((extent->first + extent->count) <= extent->first)
+ return -EINVAL;
+ if ((extent->lower_first + extent->count) <= extent->lower_first)
+ return -EINVAL;
+
+ if (mappings_overlap(new_map, extent))
+ return -EINVAL;
+
+ if (new_map->nr_extents >= UID_GID_MAP_MAX_EXTENTS)
+ return -EINVAL;
+
+ return uid_gid_map_insert_extent(new_map, extent);
+}
+
+static void free_new_idmap(struct uid_gid_map *new_map)
+{
+ if (new_map->nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
+ kfree(new_map->forward);
+ kfree(new_map->reverse);
+ }
+ memset(new_map, 0, sizeof(*new_map));
+}
+
+static int resolve_new_idmap(struct uid_gid_map *new_map,
+ struct uid_gid_map *parent_map)
+{
+ unsigned int idx;
+
+ if (new_map->nr_extents == 0)
+ return -EINVAL;
+
+ for (idx = 0; idx < new_map->nr_extents; idx++) {
+ struct uid_gid_extent *e;
+ u32 lower_first;
+
+ if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
+ e = &new_map->extent[idx];
+ else
+ e = &new_map->forward[idx];
+
+ lower_first = map_id_range_down(parent_map,
+ e->lower_first,
+ e->count);
+ if (lower_first == (u32)-1)
+ return -EPERM;
+
+ e->lower_first = lower_first;
+ }
+
+ return uid_gid_map_sort(new_map);
+}
+
+static void commit_new_idmap(struct uid_gid_map *map,
+ struct uid_gid_map *new_map)
+{
+ if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) {
+ memcpy(map->extent, new_map->extent,
+ new_map->nr_extents * sizeof(new_map->extent[0]));
+ } else {
+ map->forward = new_map->forward;
+ map->reverse = new_map->reverse;
+ }
+ /* Pairs with smp_rmb() in map_id_range_down() / map_id_up(). */
+ smp_wmb();
+ map->nr_extents = new_map->nr_extents;
+ memset(new_map, 0, sizeof(*new_map));
+}
+
/*
* Parse the decimal u32 at *pos, up to the next whitespace or NUL, and
* leave *pos pointing at that character.
@@ -966,8 +1040,7 @@ static ssize_t map_write(struct file *file, const char __user *buf,
{
struct seq_file *seq = file->private_data;
struct user_namespace *map_ns = seq->private;
- struct uid_gid_map new_map;
- unsigned idx;
+ struct uid_gid_map new_map = {};
struct uid_gid_extent extent;
char *kbuf, *pos, *next_line;
ssize_t ret;
@@ -1002,8 +1075,6 @@ static ssize_t map_write(struct file *file, const char __user *buf,
*/
mutex_lock(&userns_state_mutex);
- memset(&new_map, 0, sizeof(struct uid_gid_map));
-
ret = -EPERM;
/* Only allow one successful write to the map */
if (map->nr_extents != 0)
@@ -1052,98 +1123,28 @@ static ssize_t map_write(struct file *file, const char __user *buf,
if (*pos != '\0')
goto out;
- /* Verify we have been given valid starting values */
- if ((extent.first == (u32) -1) ||
- (extent.lower_first == (u32) -1))
- goto out;
-
- /* Verify count is not zero and does not cause the
- * extent to wrap
- */
- if ((extent.first + extent.count) <= extent.first)
- goto out;
- if ((extent.lower_first + extent.count) <=
- extent.lower_first)
- goto out;
-
- /* Do the ranges in extent overlap any previous extents? */
- if (mappings_overlap(&new_map, &extent))
- goto out;
-
- if ((new_map.nr_extents + 1) == UID_GID_MAP_MAX_EXTENTS &&
- (next_line != NULL))
- goto out;
-
- ret = uid_gid_map_insert_extent(&new_map, &extent);
+ ret = validate_and_insert_extent(&new_map, &extent);
if (ret < 0)
goto out;
ret = -EINVAL;
}
- /* Be very certain the new map actually exists */
+
if (new_map.nr_extents == 0)
goto out;
ret = -EPERM;
- /* Validate the user is allowed to use user id's mapped to. */
if (!new_idmap_permitted(file, map_ns, cap_setid, &new_map))
goto out;
- ret = -EPERM;
- /* Map the lower ids from the parent user namespace to the
- * kernel global id space.
- */
- for (idx = 0; idx < new_map.nr_extents; idx++) {
- struct uid_gid_extent *e;
- u32 lower_first;
-
- if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
- e = &new_map.extent[idx];
- else
- e = &new_map.forward[idx];
-
- lower_first = map_id_range_down(parent_map,
- e->lower_first,
- e->count);
-
- /* Fail if we can not map the specified extent to
- * the kernel global id space.
- */
- if (lower_first == (u32) -1)
- goto out;
-
- e->lower_first = lower_first;
- }
-
- /*
- * If we want to use binary search for lookup, this clones the extent
- * array and sorts both copies.
- */
- ret = uid_gid_map_sort(&new_map);
+ ret = resolve_new_idmap(&new_map, parent_map);
if (ret < 0)
goto out;
- /* Install the map */
- if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) {
- memcpy(map->extent, new_map.extent,
- new_map.nr_extents * sizeof(new_map.extent[0]));
- } else {
- map->forward = new_map.forward;
- map->reverse = new_map.reverse;
- }
- smp_wmb();
- map->nr_extents = new_map.nr_extents;
-
+ commit_new_idmap(map, &new_map);
*ppos = count;
ret = count;
out:
- if (ret < 0 && new_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
- kfree(new_map.forward);
- kfree(new_map.reverse);
- map->forward = NULL;
- map->reverse = NULL;
- map->nr_extents = 0;
- }
-
+ free_new_idmap(&new_map);
mutex_unlock(&userns_state_mutex);
kfree(kbuf);
return ret;
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 02/25] userns: Add userns_set_idmap() system call
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 01/25] userns: Factor out idmap validation and commit helpers Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 03/25] arch: Wire up " Jarkko Sakkinen
` (22 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
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. 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/uapi/linux/nsfs.h | 53 ++++++++
kernel/sys_ni.c | 1 +
kernel/user_namespace.c | 259 ++++++++++++++++++++++++++++++++++++++
4 files changed, 317 insertions(+)
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/uapi/linux/nsfs.h b/include/uapi/linux/nsfs.h
index e5909266ec3f..e773f15a76c8 100644
--- a/include/uapi/linux/nsfs.h
+++ b/include/uapi/linux/nsfs.h
@@ -44,6 +44,59 @@ 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_idmap_flags - Flags for &struct userns_idmap
+ * @USERNS_IDMAP_UID: Install UID mappings from @uid_extents.
+ * @USERNS_IDMAP_GID: Install GID mappings from @gid_extents.
+ * @USERNS_IDMAP_PROJID: Install project ID mappings from @projid_extents.
+ * @USERNS_SETGROUPS_DENY: Permanently disable setgroups(2) in target userns.
+ * @USERNS_IDMAP_ALL_FLAGS: Bitmask of all valid flags.
+ */
+enum userns_idmap_flags {
+ USERNS_IDMAP_UID = (1U << 0),
+ USERNS_IDMAP_GID = (1U << 1),
+ USERNS_IDMAP_PROJID = (1U << 2),
+ USERNS_SETGROUPS_DENY = (1U << 3),
+ USERNS_IDMAP_ALL_FLAGS = 0x0fU,
+};
+
+/**
+ * struct userns_idmap - Arguments for userns_set_idmap()
+ * @flags: Combination of &enum userns_idmap_flags values.
+ * @nr_uid_extents: Number of entries in @uid_extents.
+ * @uid_extents: User pointer to array of &struct userns_idmap_extent for UIDs.
+ * @nr_gid_extents: Number of entries in @gid_extents.
+ * @nr_projid_extents: Number of entries in @projid_extents.
+ * @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 flags;
+ __u32 nr_uid_extents;
+ __aligned_u64 uid_extents;
+ __u32 nr_gid_extents;
+ __u32 nr_projid_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 6b9673dcdc67..d7f2cad388c8 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);
@@ -1150,6 +1154,261 @@ static ssize_t map_write(struct file *file, const char __user *buf,
return ret;
}
+static bool idmap_maps_root(const struct uid_gid_map *new_map)
+{
+ unsigned int idx;
+
+ for (idx = 0; idx < new_map->nr_extents; idx++) {
+ const struct uid_gid_extent *e;
+
+ if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
+ e = &new_map->extent[idx];
+ else
+ e = &new_map->forward[idx];
+ if (e->lower_first == 0)
+ return true;
+ }
+ return false;
+}
+
+static bool caller_idmap_permitted(struct user_namespace *ns, int cap_setid,
+ const struct uid_gid_map *new_map)
+{
+ const struct cred *cred = current_cred();
+
+ if (cap_setid == CAP_SETUID && idmap_maps_root(new_map)) {
+ if (cred->user_ns == ns) {
+ if (!ns->parent_could_setfcap)
+ return false;
+ } else {
+ if (!ns_capable(ns->parent, CAP_SETFCAP))
+ return false;
+ }
+ }
+
+ if (new_map->nr_extents == 1 && new_map->extent[0].count == 1 &&
+ uid_eq(ns->owner, cred->euid)) {
+ u32 id = new_map->extent[0].lower_first;
+
+ if (cap_setid == CAP_SETUID) {
+ kuid_t uid = make_kuid(ns->parent, id);
+
+ if (uid_eq(uid, cred->euid))
+ return true;
+ } else if (cap_setid == CAP_SETGID) {
+ kgid_t gid = make_kgid(ns->parent, id);
+
+ if (!(ns->flags & USERNS_SETGROUPS_ALLOWED) &&
+ gid_eq(gid, cred->egid))
+ return true;
+ }
+ }
+
+ if (!cap_valid(cap_setid))
+ return true;
+
+ return ns_capable(ns->parent, cap_setid);
+}
+
+static int prepare_caller_idmap(struct user_namespace *ns, int cap_setid,
+ struct uid_gid_map *new_map,
+ struct uid_gid_map *parent_map)
+{
+ if (!caller_idmap_permitted(ns, cap_setid, 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)
+ * @flags: Reserved for future extensions; must be zero
+ *
+ * Atomically configure the ``setgroups(2)`` policy and UID, GID, and project
+ * ID mappings of the target user namespace without requiring a live process
+ * in ``/proc``.
+ *
+ * Modifying UID, GID, or ``setgroups(2)`` settings requires ``CAP_SYS_ADMIN``
+ * over the target user namespace either in the caller's credentials or in the
+ * file opener's credentials (allowing an unprivileged creator to delegate
+ * @fd over ``SCM_RIGHTS`` to a privileged ID-mapping helper). Parent ID-range
+ * authorization is checked 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 old_flags;
+ struct file *filp;
+ int ret;
+
+ BUILD_BUG_ON(sizeof(struct userns_idmap) != USERNS_IDMAP_SIZE_VER0);
+
+ if (flags)
+ return -EINVAL;
+
+ CLASS(fd, f)(fd);
+ if (fd_empty(f))
+ return -EBADF;
+
+ filp = fd_file(f);
+ if (!proc_ns_file(filp))
+ return -EINVAL;
+
+ ns_common = get_proc_ns(file_inode(filp));
+ if (ns_common->ns_type != CLONE_NEWUSER)
+ return -EINVAL;
+ ns = to_user_ns(ns_common);
+
+ if (!map || size < USERNS_IDMAP_SIZE_VER0)
+ return -EINVAL;
+
+ ret = copy_struct_from_user(&req, sizeof(req), map, size);
+ if (ret)
+ return ret;
+
+ if (!req.flags || (req.flags & ~USERNS_IDMAP_ALL_FLAGS))
+ return -EINVAL;
+ if (!(req.flags & USERNS_IDMAP_UID) &&
+ (req.nr_uid_extents || req.uid_extents))
+ return -EINVAL;
+ if (!(req.flags & USERNS_IDMAP_GID) &&
+ (req.nr_gid_extents || req.gid_extents))
+ return -EINVAL;
+ if (!(req.flags & USERNS_IDMAP_PROJID) &&
+ (req.nr_projid_extents || req.projid_extents))
+ return -EINVAL;
+
+ if (!ns->parent)
+ return -EPERM;
+ if (current_user_ns() != ns && current_user_ns() != ns->parent)
+ return -EPERM;
+
+ if (req.flags & (USERNS_IDMAP_UID | USERNS_IDMAP_GID |
+ USERNS_SETGROUPS_DENY)) {
+ bool file_ok = (filp->f_cred->user_ns == ns ||
+ filp->f_cred->user_ns == ns->parent) &&
+ file_ns_capable(filp, ns, CAP_SYS_ADMIN);
+
+ if (!ns_capable(ns, CAP_SYS_ADMIN) && !file_ok)
+ return -EPERM;
+ }
+
+ if (req.flags & USERNS_IDMAP_UID) {
+ ret = parse_user_idmap_extents(req.uid_extents,
+ req.nr_uid_extents, &new_uid);
+ if (ret < 0)
+ goto out_free;
+ }
+ if (req.flags & USERNS_IDMAP_GID) {
+ ret = parse_user_idmap_extents(req.gid_extents,
+ req.nr_gid_extents, &new_gid);
+ if (ret < 0)
+ goto out_free;
+ }
+ if (req.flags & USERNS_IDMAP_PROJID) {
+ ret = parse_user_idmap_extents(req.projid_extents,
+ req.nr_projid_extents,
+ &new_projid);
+ if (ret < 0)
+ goto out_free;
+ }
+
+ mutex_lock(&userns_state_mutex);
+ old_flags = ns->flags;
+ ret = -EPERM;
+
+ if ((req.flags & USERNS_SETGROUPS_DENY) && ns->gid_map.nr_extents != 0)
+ goto out_unlock;
+ if ((req.flags & USERNS_IDMAP_UID) && ns->uid_map.nr_extents != 0)
+ goto out_unlock;
+ if ((req.flags & USERNS_IDMAP_GID) && ns->gid_map.nr_extents != 0)
+ goto out_unlock;
+ if ((req.flags & USERNS_IDMAP_PROJID) && ns->projid_map.nr_extents != 0)
+ goto out_unlock;
+
+ if (req.flags & USERNS_SETGROUPS_DENY)
+ ns->flags &= ~USERNS_SETGROUPS_ALLOWED;
+
+ if (req.flags & USERNS_IDMAP_UID) {
+ ret = prepare_caller_idmap(ns, CAP_SETUID, &new_uid,
+ &ns->parent->uid_map);
+ if (ret < 0)
+ goto out_restore;
+ }
+ if (req.flags & USERNS_IDMAP_GID) {
+ ret = prepare_caller_idmap(ns, CAP_SETGID, &new_gid,
+ &ns->parent->gid_map);
+ if (ret < 0)
+ goto out_restore;
+ }
+ if (req.flags & USERNS_IDMAP_PROJID) {
+ ret = prepare_caller_idmap(ns, -1, &new_projid,
+ &ns->parent->projid_map);
+ if (ret < 0)
+ goto out_restore;
+ }
+
+ if (req.flags & USERNS_IDMAP_UID)
+ commit_new_idmap(&ns->uid_map, &new_uid);
+ if (req.flags & USERNS_IDMAP_GID)
+ commit_new_idmap(&ns->gid_map, &new_gid);
+ if (req.flags & USERNS_IDMAP_PROJID)
+ commit_new_idmap(&ns->projid_map, &new_projid);
+
+ mutex_unlock(&userns_state_mutex);
+ return 0;
+
+out_restore:
+ ns->flags = old_flags;
+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 [flat|nested] 33+ messages in thread* [RFC PATCH v5 03/25] arch: Wire up userns_set_idmap() system call
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 01/25] userns: Factor out idmap validation and commit helpers Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 02/25] userns: Add userns_set_idmap() system call Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 04/25] mount: Add mnt_ns_get_root() Jarkko Sakkinen
` (21 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
Zygmunt Krynicki
Expose userns_set_idmap() (473, 583 on Alpha) across all architecture
system call tables and asm-generic unistd.h.
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 +
18 files changed, 22 insertions(+), 1 deletion(-)
diff --git a/arch/alpha/kernel/syscalls/syscall.tbl b/arch/alpha/kernel/syscalls/syscall.tbl
index 52e3538cc7df..9384d59a44dc 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_sys_userns_set_idmap
diff --git a/arch/arm/tools/syscall.tbl b/arch/arm/tools/syscall.tbl
index 55717ed32c27..6130366b7681 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_sys_userns_set_idmap
diff --git a/arch/arm64/tools/syscall_32.tbl b/arch/arm64/tools/syscall_32.tbl
index df2d1d82fb3c..3fcc7899fd08 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_sys_userns_set_idmap
diff --git a/arch/m68k/kernel/syscalls/syscall.tbl b/arch/m68k/kernel/syscalls/syscall.tbl
index ba7a4d8903d0..5607635bd4bd 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_sys_userns_set_idmap
diff --git a/arch/microblaze/kernel/syscalls/syscall.tbl b/arch/microblaze/kernel/syscalls/syscall.tbl
index 76d7cbe2a133..97ee93f42fac 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_sys_userns_set_idmap
diff --git a/arch/mips/kernel/syscalls/syscall_n32.tbl b/arch/mips/kernel/syscalls/syscall_n32.tbl
index 9ae88e4eac61..da4ed57a91d3 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_sys_userns_set_idmap
diff --git a/arch/mips/kernel/syscalls/syscall_n64.tbl b/arch/mips/kernel/syscalls/syscall_n64.tbl
index 83dc93a0712f..5e9839b6b389 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_sys_userns_set_idmap
diff --git a/arch/mips/kernel/syscalls/syscall_o32.tbl b/arch/mips/kernel/syscalls/syscall_o32.tbl
index 9c62429c9b7b..290c1b61be47 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_sys_userns_set_idmap
diff --git a/arch/parisc/kernel/syscalls/syscall.tbl b/arch/parisc/kernel/syscalls/syscall.tbl
index 88adc4016cce..fc0fa917eb92 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_sys_userns_set_idmap
diff --git a/arch/powerpc/kernel/syscalls/syscall.tbl b/arch/powerpc/kernel/syscalls/syscall.tbl
index cfbb70039ff0..d12e49022b23 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 common userns_set_idmap sys_sys_userns_set_idmap
diff --git a/arch/s390/kernel/syscalls/syscall.tbl b/arch/s390/kernel/syscalls/syscall.tbl
index 1b45e68a217b..dc427811d30d 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_sys_userns_set_idmap
diff --git a/arch/sh/kernel/syscalls/syscall.tbl b/arch/sh/kernel/syscalls/syscall.tbl
index ace068dff0de..e62ac9acc7ad 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_sys_userns_set_idmap
diff --git a/arch/sparc/kernel/syscalls/syscall.tbl b/arch/sparc/kernel/syscalls/syscall.tbl
index 5b9fe0e8140f..df074bf322c4 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_sys_userns_set_idmap
diff --git a/arch/x86/entry/syscalls/syscall_32.tbl b/arch/x86/entry/syscalls/syscall_32.tbl
index 2c172ef48dfd..243a3f55834d 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_sys_userns_set_idmap
diff --git a/arch/x86/entry/syscalls/syscall_64.tbl b/arch/x86/entry/syscalls/syscall_64.tbl
index d5b6045b0090..f11700e3af65 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_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..1d28de95915f 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_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..0dddd465d1c5 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_sys_userns_set_idmap
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 04/25] mount: Add mnt_ns_get_root()
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (2 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 03/25] arch: Wire up " Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 05/25] mount: Enforce mount_too_revealing() for foreign mntns Jarkko Sakkinen
` (20 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
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 [flat|nested] 33+ messages in thread* [RFC PATCH v5 05/25] mount: Enforce mount_too_revealing() for foreign mntns
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (3 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 04/25] mount: Add mnt_ns_get_root() Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 06/25] mount: Support MOVE_MOUNT_T_MNTNS in move_mount() Jarkko Sakkinen
` (19 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
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 | 21 ++++++++++++++++-----
1 file changed, 16 insertions(+), 5 deletions(-)
diff --git a/fs/namespace.c b/fs/namespace.c
index 781380945d78..b2dc84c0d0d6 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -6582,6 +6582,7 @@ static bool mnt_already_visible(struct mnt_namespace *ns,
const struct super_block *sb,
int *new_mnt_flags)
{
+ bool foreign_ns = !ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN);
int new_flags = *new_mnt_flags;
struct mount *mnt;
@@ -6606,11 +6607,16 @@ static bool mnt_already_visible(struct mnt_namespace *ns,
continue;
/* A local view of the mount flags */
- mnt_flags = mnt->mnt.mnt_flags;
+ mnt_flags = READ_ONCE(mnt->mnt.mnt_flags);
/* Don't miss readonly hidden in the superblock flags */
if (sb_rdonly(mnt->mnt.mnt_sb))
mnt_flags |= MNT_LOCK_READONLY;
+ if (foreign_ns) {
+ if (mnt_flags & MNT_READONLY)
+ mnt_flags |= MNT_LOCK_READONLY;
+ mnt_flags |= MNT_LOCK_ATIME;
+ }
/* Verify the mount flags are equal to or more permissive
* than the proposed new mount.
@@ -6629,7 +6635,7 @@ static bool mnt_already_visible(struct mnt_namespace *ns,
list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) {
struct inode *inode = child->mnt_mountpoint->d_inode;
/* Only worry about locked mounts */
- if (!(child->mnt.mnt_flags & MNT_LOCKED))
+ if (!foreign_ns && !(READ_ONCE(child->mnt.mnt_flags) & MNT_LOCKED))
continue;
/* Is the directory permanently empty? */
if (!is_empty_dir_inode(inode))
@@ -6650,13 +6656,18 @@ static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flags
struct mnt_namespace *ns = current->nsproxy->mnt_ns;
unsigned long s_iflags;
- if (ns->user_ns == &init_user_ns)
- return false;
-
/* Can this filesystem be too revealing? */
if (!(sb->s_type->fs_flags & FS_USERNS_MOUNT_RESTRICTED))
return false;
+ if (ns->user_ns == &init_user_ns &&
+ ns_capable_noaudit(&init_user_ns, CAP_SYS_ADMIN))
+ return false;
+
+ if (!ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN) &&
+ current_chrooted())
+ return true;
+
s_iflags = sb->s_iflags;
if ((s_iflags & required_iflags) != required_iflags) {
WARN_ONCE(1, "Expected s_iflags to contain 0x%lx\n",
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 06/25] mount: Support MOVE_MOUNT_T_MNTNS in move_mount()
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (4 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 05/25] mount: Enforce mount_too_revealing() for foreign mntns Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 07/25] mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS Jarkko Sakkinen
` (18 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
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 | 226 +++++++++++++++++++++++++++++++------
include/uapi/linux/mount.h | 3 +-
2 files changed, 191 insertions(+), 38 deletions(-)
diff --git a/fs/namespace.c b/fs/namespace.c
index b2dc84c0d0d6..b65f1fdd9281 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,
@@ -2423,10 +2429,11 @@ static bool __has_children(struct mount *mnt, struct dentry *dentry)
*
* locks: mount_locked_reader || namespace_shared && pinned(subtree)
*/
-static bool check_for_nsfs_mounts(struct mount *subtree)
+static bool check_for_nsfs_mounts(struct mount *subtree,
+ struct mnt_namespace *target_mnt_ns)
{
for (struct mount *p = subtree; p; p = next_mnt(p, subtree))
- if (mnt_ns_loop(p->mnt.mnt_root))
+ if (mnt_ns_loop_target(p->mnt.mnt_root, target_mnt_ns))
return false;
return true;
}
@@ -2464,7 +2471,7 @@ struct vfsmount *clone_private_mount(const struct path *path)
if (!anon_ns_root(old_mnt))
return ERR_PTR(-EINVAL);
- if (!check_for_nsfs_mounts(old_mnt))
+ if (!check_for_nsfs_mounts(old_mnt, current->nsproxy->mnt_ns))
return ERR_PTR(-EINVAL);
}
@@ -2564,12 +2571,15 @@ int count_mounts(struct mnt_namespace *ns, struct mount *mnt)
enum mnt_tree_flags_t {
MNT_TREE_BENEATH = BIT(0),
MNT_TREE_PROPAGATION = BIT(1),
+ MNT_TREE_MNTNS = BIT(2),
+ MNT_TREE_MNTNS_INIT = BIT(3),
};
/**
* attach_recursive_mnt - attach a source mount tree
* @source_mnt: mount tree to be attached
* @dest: the context for mounting at the place where the tree should go
+ * @move_mntns: whether @source_mnt is attached via MOVE_MOUNT_T_MNTNS
*
* NOTE: in the table below explains the semantics when a source mount
* of a given type is attached to a destination mount of a given type.
@@ -2632,7 +2642,8 @@ enum mnt_tree_flags_t {
* Otherwise a negative error code is returned.
*/
static int attach_recursive_mnt(struct mount *source_mnt,
- const struct pinned_mountpoint *dest)
+ const struct pinned_mountpoint *dest,
+ bool move_mntns)
{
struct mount *dest_mnt = dest->parent;
struct mountpoint *dest_mp = dest->mp;
@@ -2641,6 +2652,7 @@ static int attach_recursive_mnt(struct mount *source_mnt,
struct user_namespace *user_ns = ns->user_ns;
struct pinned_mountpoint root = {};
struct mountpoint *shorter = NULL;
+ struct mnt_namespace *src_ns;
struct mount *child, *p;
struct mount *top;
struct hlist_node *n;
@@ -2662,6 +2674,9 @@ static int attach_recursive_mnt(struct mount *source_mnt,
user_ns = current->nsproxy->mnt_ns->user_ns;
else
user_ns = ns->user_ns;
+ src_ns = moving ? NULL : source_mnt->mnt_ns;
+ if (move_mntns && src_ns)
+ user_ns = src_ns->user_ns;
/*
* Preallocate a mountpoint in case the new mounts need to be
@@ -2728,8 +2743,12 @@ static int attach_recursive_mnt(struct mount *source_mnt,
struct mount *q;
hlist_del_init(&child->mnt_hash);
/* Notice when we are propagating across user namespaces */
- if (child->mnt_parent->mnt_ns->user_ns != user_ns)
+ if (child->mnt_parent->mnt_ns->user_ns != user_ns) {
lock_mnt_tree(child);
+ if ((move_mntns || is_anon_ns(ns)) &&
+ list_empty(&child->mnt_expire))
+ child->mnt.mnt_flags |= MNT_LOCKED;
+ }
q = __lookup_mnt(&child->mnt_parent->mnt,
child->mnt_mountpoint);
commit_tree(child);
@@ -2937,7 +2956,7 @@ static int graft_tree(struct mount *mnt, const struct pinned_mountpoint *mp)
d_is_dir(mnt->mnt.mnt_root))
return -ENOTDIR;
- return attach_recursive_mnt(mnt, mp);
+ return attach_recursive_mnt(mnt, mp, false);
}
static int may_change_propagation(const struct mount *m)
@@ -3131,7 +3150,7 @@ static int do_loopback(const struct path *path, const char *old_name,
return PTR_ERR(mnt);
/* the copy may carry mount namespace files from below the source */
- if (recurse && !check_for_nsfs_mounts(mnt))
+ if (recurse && !check_for_nsfs_mounts(mnt, current->nsproxy->mnt_ns))
err = -EINVAL;
else
err = graft_tree(mnt, &mp);
@@ -3776,9 +3795,11 @@ static inline bool may_use_mount(struct mount *mnt)
static int do_move_mount(const struct path *old_path,
const struct path *new_path,
- enum mnt_tree_flags_t flags)
+ enum mnt_tree_flags_t flags,
+ struct mnt_namespace *target_mnt_ns)
{
struct mount *old = real_mount(old_path->mnt);
+ struct mnt_namespace *dest_mnt_ns;
int err;
bool beneath = flags & MNT_TREE_BENEATH;
@@ -3792,7 +3813,29 @@ static int do_move_mount(const struct path *old_path,
if (IS_ERR(mp.parent))
return PTR_ERR(mp.parent);
- if (check_mnt(old)) {
+ if (flags & MNT_TREE_MNTNS) {
+ u64 seq;
+
+ if (!anon_ns_root(old) || old->mnt_ns == mp.parent->mnt_ns ||
+ mp.parent->mnt_ns != target_mnt_ns)
+ return -EINVAL;
+ seq = old->mnt_ns->seq_origin;
+ if (seq && seq != target_mnt_ns->ns.ns_id &&
+ seq != current->nsproxy->mnt_ns->ns.ns_id)
+ return -EINVAL;
+ if (flags & MNT_TREE_MNTNS_INIT) {
+ if (mp.parent != target_mnt_ns->root)
+ return -EBUSY;
+ } else if (mp.mp->m_dentry == mp.parent->mnt.mnt_root) {
+ const struct mount *m = mp.parent;
+
+ while (m != target_mnt_ns->root && mnt_has_parent(m) &&
+ m->mnt_mountpoint == m->mnt_parent->mnt.mnt_root)
+ m = m->mnt_parent;
+ if (m == target_mnt_ns->root)
+ return beneath ? -EINVAL : -EBUSY;
+ }
+ } else if (check_mnt(old)) {
/* if the source is in our namespace... */
/* ... it should be detachable from parent */
if (!mnt_has_parent(old) || IS_MNT_LOCKED(old))
@@ -3840,12 +3883,14 @@ static int do_move_mount(const struct path *old_path,
*/
if (IS_MNT_SHARED(mp.parent) && tree_contains_unbindable(old))
return -EINVAL;
- if (!check_for_nsfs_mounts(old))
+ dest_mnt_ns = is_anon_ns(mp.parent->mnt_ns) ?
+ current->nsproxy->mnt_ns : mp.parent->mnt_ns;
+ if (!check_for_nsfs_mounts(old, dest_mnt_ns))
return -ELOOP;
if (mount_is_ancestor(old, mp.parent))
return -ELOOP;
- return attach_recursive_mnt(old, &mp);
+ return attach_recursive_mnt(old, &mp, flags & MNT_TREE_MNTNS);
}
static int do_move_mount_old(const struct path *path, const char *old_name)
@@ -3860,7 +3905,7 @@ static int do_move_mount_old(const struct path *path, const char *old_name)
if (err)
return err;
- return do_move_mount(&old_path, path, 0);
+ return do_move_mount(&old_path, path, 0, NULL);
}
/*
@@ -4725,7 +4770,8 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
static inline int vfs_move_mount(const struct path *from_path,
const struct path *to_path,
- enum mnt_tree_flags_t mflags)
+ enum mnt_tree_flags_t mflags,
+ struct mnt_namespace *target_mnt_ns)
{
int ret;
@@ -4736,7 +4782,123 @@ static inline int vfs_move_mount(const struct path *from_path,
if (mflags & MNT_TREE_PROPAGATION)
return do_set_group(from_path, to_path);
- return do_move_mount(from_path, to_path, mflags);
+ return do_move_mount(from_path, to_path, mflags, target_mnt_ns);
+}
+
+static int lookup_move_mount_from(int from_dfd,
+ const char __user *from_pathname,
+ unsigned int flags, struct path *from_path)
+{
+ unsigned int uflags = 0;
+ unsigned int lflags = 0;
+
+ if (flags & MOVE_MOUNT_F_EMPTY_PATH)
+ uflags = AT_EMPTY_PATH;
+
+ CLASS(filename_maybe_null, from_name)(from_pathname, uflags);
+ if (!from_name && from_dfd >= 0) {
+ CLASS(fd_raw, f_from)(from_dfd);
+ if (fd_empty(f_from))
+ return -EBADF;
+
+ *from_path = fd_file(f_from)->f_path;
+ path_get(from_path);
+ return 0;
+ }
+
+ if (flags & MOVE_MOUNT_F_SYMLINKS)
+ lflags |= LOOKUP_FOLLOW;
+ if (flags & MOVE_MOUNT_F_AUTOMOUNTS)
+ lflags |= LOOKUP_AUTOMOUNT;
+ return filename_lookup(from_dfd, from_name, lflags, from_path, NULL);
+}
+
+/**
+ * DOC: MOVE_MOUNT_T_MNTNS
+ *
+ * ``MOVE_MOUNT_T_MNTNS`` installs detached anonymous mount trees into a target
+ * mount namespace ``nsfs`` file descriptor supplied as ``to_dfd``:
+ *
+ * 1. ``to_pathname`` of ``"/"`` attaches the initial root mount onto the
+ * ``nullfs`` root of an empty mount namespace at most once.
+ *
+ * 2. Relative ``to_pathname`` values resolve beneath the live root of the
+ * target mount namespace.
+ *
+ * Capability is checked against ``CAP_SYS_ADMIN`` in the target mount
+ * namespace's owning user namespace, and source trees crossing user namespace
+ * boundaries are locked with ``MNT_LOCKED`` and locked mount flags.
+ */
+static int move_mount_mntns(int from_dfd, const char __user *from_pathname,
+ int to_dfd, const char __user *to_pathname,
+ unsigned int flags, enum mnt_tree_flags_t mflags)
+{
+ struct path from_path __free(path_put) = {};
+ struct path to_path __free(path_put) = {};
+ struct mnt_namespace *target_mnt_ns;
+ unsigned int lflags;
+ struct ns_common *ns;
+ bool is_root;
+ int ret;
+
+ CLASS(filename_maybe_null, to_name)(to_pathname, AT_EMPTY_PATH);
+ if (IS_ERR(to_name))
+ return PTR_ERR(to_name);
+ if (!to_name)
+ return -EINVAL;
+
+ CLASS(fd, f_mntns)(to_dfd);
+ if (fd_empty(f_mntns))
+ return -EBADF;
+ if (!proc_ns_file(fd_file(f_mntns)))
+ return -EINVAL;
+
+ ns = get_proc_ns(file_inode(fd_file(f_mntns)));
+ if (ns->ns_type != CLONE_NEWNS)
+ return -EINVAL;
+
+ target_mnt_ns = to_mnt_ns(ns);
+ if (is_anon_ns(target_mnt_ns))
+ return -EINVAL;
+ if (!ns_capable(target_mnt_ns->user_ns, CAP_SYS_ADMIN))
+ return -EPERM;
+
+ is_root = to_name->name[0] == '/' && to_name->name[1] == '\0';
+ if (is_root) {
+ if (flags & MOVE_MOUNT_BENEATH)
+ return -EINVAL;
+
+ to_path.mnt = mntget(&target_mnt_ns->root->mnt);
+ to_path.dentry = dget(target_mnt_ns->root->mnt.mnt_root);
+ mflags |= MNT_TREE_MNTNS_INIT;
+ } else {
+ struct path mntns_root __free(path_put) = {};
+
+ if (to_name->name[0] == '/')
+ return -EINVAL;
+
+ ret = mnt_ns_get_root(target_mnt_ns, &mntns_root);
+ if (ret)
+ return ret;
+
+ lflags = LOOKUP_IN_ROOT;
+ if (flags & MOVE_MOUNT_T_SYMLINKS)
+ lflags |= LOOKUP_FOLLOW;
+ if (flags & MOVE_MOUNT_T_AUTOMOUNTS)
+ lflags |= LOOKUP_AUTOMOUNT;
+ ret = filename_lookup(AT_FDCWD, to_name, lflags, &to_path,
+ &mntns_root);
+ if (ret)
+ return ret;
+ }
+
+ ret = lookup_move_mount_from(from_dfd, from_pathname, flags,
+ &from_path);
+ if (ret)
+ return ret;
+
+ return vfs_move_mount(&from_path, &to_path, mflags | MNT_TREE_MNTNS,
+ target_mnt_ns);
}
/*
@@ -4758,7 +4920,7 @@ SYSCALL_DEFINE5(move_mount,
enum mnt_tree_flags_t mflags = 0;
int ret = 0;
- if (!may_mount())
+ if (!(flags & MOVE_MOUNT_T_MNTNS) && !may_mount())
return -EPERM;
if (flags & ~MOVE_MOUNT__MASK)
@@ -4771,6 +4933,13 @@ SYSCALL_DEFINE5(move_mount,
if (flags & MOVE_MOUNT_SET_GROUP) mflags |= MNT_TREE_PROPAGATION;
if (flags & MOVE_MOUNT_BENEATH) mflags |= MNT_TREE_BENEATH;
+ if (unlikely(flags & MOVE_MOUNT_T_MNTNS)) {
+ if (flags & (MOVE_MOUNT_T_EMPTY_PATH | MOVE_MOUNT_SET_GROUP))
+ return -EINVAL;
+ return move_mount_mntns(from_dfd, from_pathname,
+ to_dfd, to_pathname, flags, mflags);
+ }
+
uflags = 0;
if (flags & MOVE_MOUNT_T_EMPTY_PATH)
uflags = AT_EMPTY_PATH;
@@ -4794,29 +4963,12 @@ SYSCALL_DEFINE5(move_mount,
return ret;
}
- uflags = 0;
- if (flags & MOVE_MOUNT_F_EMPTY_PATH)
- uflags = AT_EMPTY_PATH;
-
- CLASS(filename_maybe_null,from_name)(from_pathname, uflags);
- if (!from_name && from_dfd >= 0) {
- CLASS(fd_raw, f_from)(from_dfd);
- if (fd_empty(f_from))
- return -EBADF;
-
- return vfs_move_mount(&fd_file(f_from)->f_path, &to_path, mflags);
- }
-
- lflags = 0;
- if (flags & MOVE_MOUNT_F_SYMLINKS)
- lflags |= LOOKUP_FOLLOW;
- if (flags & MOVE_MOUNT_F_AUTOMOUNTS)
- lflags |= LOOKUP_AUTOMOUNT;
- ret = filename_lookup(from_dfd, from_name, lflags, &from_path, NULL);
+ ret = lookup_move_mount_from(from_dfd, from_pathname, flags,
+ &from_path);
if (ret)
return ret;
- return vfs_move_mount(&from_path, &to_path, mflags);
+ return vfs_move_mount(&from_path, &to_path, mflags, NULL);
}
/*
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 [flat|nested] 33+ messages in thread* [RFC PATCH v5 07/25] mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (5 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 06/25] mount: Support MOVE_MOUNT_T_MNTNS in move_mount() Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 08/25] userns: Factor out install_user_ns_cred() Jarkko Sakkinen
` (17 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
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 when crossing user namespace boundaries,
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 | 106 +++++++++++++++++++++++++++----------
include/uapi/linux/mount.h | 3 +-
2 files changed, 80 insertions(+), 29 deletions(-)
diff --git a/fs/namespace.c b/fs/namespace.c
index b65f1fdd9281..1e7d776c0966 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -2573,13 +2573,15 @@ enum mnt_tree_flags_t {
MNT_TREE_PROPAGATION = BIT(1),
MNT_TREE_MNTNS = BIT(2),
MNT_TREE_MNTNS_INIT = BIT(3),
+ MNT_TREE_CLONE = BIT(4),
};
/**
* attach_recursive_mnt - attach a source mount tree
* @source_mnt: mount tree to be attached
* @dest: the context for mounting at the place where the tree should go
- * @move_mntns: whether @source_mnt is attached via MOVE_MOUNT_T_MNTNS
+ * @src_user_ns: owning user namespace of @source_mnt for MOVE_MOUNT_T_MNTNS,
+ * or NULL
*
* NOTE: in the table below explains the semantics when a source mount
* of a given type is attached to a destination mount of a given type.
@@ -2643,7 +2645,7 @@ enum mnt_tree_flags_t {
*/
static int attach_recursive_mnt(struct mount *source_mnt,
const struct pinned_mountpoint *dest,
- bool move_mntns)
+ struct user_namespace *src_user_ns)
{
struct mount *dest_mnt = dest->parent;
struct mountpoint *dest_mp = dest->mp;
@@ -2652,7 +2654,6 @@ static int attach_recursive_mnt(struct mount *source_mnt,
struct user_namespace *user_ns = ns->user_ns;
struct pinned_mountpoint root = {};
struct mountpoint *shorter = NULL;
- struct mnt_namespace *src_ns;
struct mount *child, *p;
struct mount *top;
struct hlist_node *n;
@@ -2670,13 +2671,12 @@ static int attach_recursive_mnt(struct mount *source_mnt,
* the attaching task's mount namespace is authoritative, not
* the creator of the detached tree.
*/
- if (is_anon_ns(ns))
+ if (src_user_ns)
+ user_ns = src_user_ns;
+ else if (is_anon_ns(ns))
user_ns = current->nsproxy->mnt_ns->user_ns;
else
user_ns = ns->user_ns;
- src_ns = moving ? NULL : source_mnt->mnt_ns;
- if (move_mntns && src_ns)
- user_ns = src_ns->user_ns;
/*
* Preallocate a mountpoint in case the new mounts need to be
@@ -2745,7 +2745,7 @@ static int attach_recursive_mnt(struct mount *source_mnt,
/* Notice when we are propagating across user namespaces */
if (child->mnt_parent->mnt_ns->user_ns != user_ns) {
lock_mnt_tree(child);
- if ((move_mntns || is_anon_ns(ns)) &&
+ if ((src_user_ns || is_anon_ns(ns)) &&
list_empty(&child->mnt_expire))
child->mnt.mnt_flags |= MNT_LOCKED;
}
@@ -2956,7 +2956,7 @@ static int graft_tree(struct mount *mnt, const struct pinned_mountpoint *mp)
d_is_dir(mnt->mnt.mnt_root))
return -ENOTDIR;
- return attach_recursive_mnt(mnt, mp, false);
+ return attach_recursive_mnt(mnt, mp, NULL);
}
static int may_change_propagation(const struct mount *m)
@@ -3799,29 +3799,27 @@ static int do_move_mount(const struct path *old_path,
struct mnt_namespace *target_mnt_ns)
{
struct mount *old = real_mount(old_path->mnt);
+ struct user_namespace *src_user_ns = NULL;
+ struct mount *cloned = NULL;
struct mnt_namespace *dest_mnt_ns;
int err;
bool beneath = flags & MNT_TREE_BENEATH;
- if (!path_mounted(old_path))
+ if (!(flags & MNT_TREE_CLONE) && !path_mounted(old_path))
return -EINVAL;
if (d_is_dir(new_path->dentry) != d_is_dir(old_path->dentry))
return -EINVAL;
+ if ((flags & MNT_TREE_CLONE) && mnt_ns_loop(old_path->dentry))
+ return -EINVAL;
+
LOCK_MOUNT_MAYBE_BENEATH(mp, new_path, beneath);
if (IS_ERR(mp.parent))
return PTR_ERR(mp.parent);
if (flags & MNT_TREE_MNTNS) {
- u64 seq;
-
- if (!anon_ns_root(old) || old->mnt_ns == mp.parent->mnt_ns ||
- mp.parent->mnt_ns != target_mnt_ns)
- return -EINVAL;
- seq = old->mnt_ns->seq_origin;
- if (seq && seq != target_mnt_ns->ns.ns_id &&
- seq != current->nsproxy->mnt_ns->ns.ns_id)
+ if (mp.parent->mnt_ns != target_mnt_ns)
return -EINVAL;
if (flags & MNT_TREE_MNTNS_INIT) {
if (mp.parent != target_mnt_ns->root)
@@ -3835,6 +3833,35 @@ static int do_move_mount(const struct path *old_path,
if (m == target_mnt_ns->root)
return beneath ? -EINVAL : -EBUSY;
}
+ if (flags & MNT_TREE_CLONE) {
+ unsigned int copy_flags;
+
+ if (!check_mnt(old) || old->mnt_ns == target_mnt_ns)
+ return -EINVAL;
+ src_user_ns = old->mnt_ns->user_ns;
+ copy_flags = (target_mnt_ns->user_ns != src_user_ns) ?
+ (CL_SLAVE | CL_COPY_UNBINDABLE) :
+ CL_COPY_MNT_NS_FILE;
+ cloned = __do_loopback(old_path, true, copy_flags);
+ if (IS_ERR(cloned))
+ return PTR_ERR(cloned);
+ old = cloned;
+ if (d_is_symlink(old->mnt.mnt_root)) {
+ err = -EINVAL;
+ goto out_cloned;
+ }
+ } else {
+ u64 seq;
+
+ if (!anon_ns_root(old) ||
+ old->mnt_ns == mp.parent->mnt_ns)
+ return -EINVAL;
+ seq = old->mnt_ns->seq_origin;
+ if (seq && seq != target_mnt_ns->ns.ns_id &&
+ seq != current->nsproxy->mnt_ns->ns.ns_id)
+ return -EINVAL;
+ src_user_ns = old->mnt_ns->user_ns;
+ }
} else if (check_mnt(old)) {
/* if the source is in our namespace... */
/* ... it should be detachable from parent */
@@ -3874,23 +3901,36 @@ static int do_move_mount(const struct path *old_path,
over = mp.parent->overmount;
err = can_move_mount_beneath(old, over, &mp);
if (err)
- return err;
+ goto out_cloned;
}
/*
* Don't move a mount tree containing unbindable mounts to a destination
* mount which is shared.
*/
- if (IS_MNT_SHARED(mp.parent) && tree_contains_unbindable(old))
- return -EINVAL;
+ if (IS_MNT_SHARED(mp.parent) && tree_contains_unbindable(old)) {
+ err = -EINVAL;
+ goto out_cloned;
+ }
dest_mnt_ns = is_anon_ns(mp.parent->mnt_ns) ?
current->nsproxy->mnt_ns : mp.parent->mnt_ns;
- if (!check_for_nsfs_mounts(old, dest_mnt_ns))
- return -ELOOP;
- if (mount_is_ancestor(old, mp.parent))
- return -ELOOP;
+ if (!check_for_nsfs_mounts(old, dest_mnt_ns)) {
+ err = -ELOOP;
+ goto out_cloned;
+ }
+ if (mount_is_ancestor(old, mp.parent)) {
+ err = -ELOOP;
+ goto out_cloned;
+ }
- return attach_recursive_mnt(old, &mp, flags & MNT_TREE_MNTNS);
+ err = attach_recursive_mnt(old, &mp, src_user_ns);
+out_cloned:
+ if (err && cloned) {
+ lock_mount_hash();
+ umount_tree(cloned, UMOUNT_SYNC);
+ unlock_mount_hash();
+ }
+ return err;
}
static int do_move_mount_old(const struct path *path, const char *old_name)
@@ -4816,8 +4856,8 @@ static int lookup_move_mount_from(int from_dfd,
/**
* DOC: MOVE_MOUNT_T_MNTNS
*
- * ``MOVE_MOUNT_T_MNTNS`` installs detached anonymous mount trees into a target
- * mount namespace ``nsfs`` file descriptor supplied as ``to_dfd``:
+ * ``MOVE_MOUNT_T_MNTNS`` installs mount trees into a target mount namespace
+ * ``nsfs`` file descriptor supplied as ``to_dfd``:
*
* 1. ``to_pathname`` of ``"/"`` attaches the initial root mount onto the
* ``nullfs`` root of an empty mount namespace at most once.
@@ -4825,6 +4865,11 @@ static int lookup_move_mount_from(int from_dfd,
* 2. Relative ``to_pathname`` values resolve beneath the live root of the
* target mount namespace.
*
+ * 3. Combining ``MOVE_MOUNT_CLONE`` with ``MOVE_MOUNT_T_MNTNS`` recursively
+ * loopback-clones ``from_pathname`` from the caller's mount namespace into
+ * ``to_dfd`` without requiring ``OPEN_TREE_CLONE`` or ``may_mount()`` in
+ * the caller's own mount namespace.
+ *
* Capability is checked against ``CAP_SYS_ADMIN`` in the target mount
* namespace's owning user namespace, and source trees crossing user namespace
* boundaries are locked with ``MNT_LOCKED`` and locked mount flags.
@@ -4926,12 +4971,17 @@ SYSCALL_DEFINE5(move_mount,
if (flags & ~MOVE_MOUNT__MASK)
return -EINVAL;
+ if ((flags & MOVE_MOUNT_CLONE) && !(flags & MOVE_MOUNT_T_MNTNS))
+ return -EINVAL;
+
if ((flags & (MOVE_MOUNT_BENEATH | MOVE_MOUNT_SET_GROUP)) ==
(MOVE_MOUNT_BENEATH | MOVE_MOUNT_SET_GROUP))
return -EINVAL;
if (flags & MOVE_MOUNT_SET_GROUP) mflags |= MNT_TREE_PROPAGATION;
if (flags & MOVE_MOUNT_BENEATH) mflags |= MNT_TREE_BENEATH;
+ if (flags & MOVE_MOUNT_CLONE)
+ mflags |= MNT_TREE_CLONE;
if (unlikely(flags & MOVE_MOUNT_T_MNTNS)) {
if (flags & (MOVE_MOUNT_T_EMPTY_PATH | MOVE_MOUNT_SET_GROUP))
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 [flat|nested] 33+ messages in thread* [RFC PATCH v5 08/25] userns: Factor out install_user_ns_cred()
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (6 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 07/25] mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 09/25] nsfs: Add nsproxy_open_namespace() Jarkko Sakkinen
` (16 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
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 91232053775d..3600a903442e 100644
--- a/include/linux/user_namespace.h
+++ b/include/linux/user_namespace.h
@@ -184,6 +184,7 @@ static inline struct user_namespace *get_user_ns(struct user_namespace *ns)
}
extern int create_user_ns(struct cred *new);
+int install_user_ns_cred(struct cred *cred, struct user_namespace *user_ns);
extern int unshare_userns(unsigned long unshare_flags, struct cred **new_cred);
extern void __put_user_ns(struct user_namespace *ns);
@@ -226,6 +227,12 @@ static inline int create_user_ns(struct cred *new)
return -EINVAL;
}
+static inline int install_user_ns_cred(struct cred *cred,
+ struct user_namespace *user_ns)
+{
+ return -EINVAL;
+}
+
static inline int unshare_userns(unsigned long unshare_flags,
struct cred **new_cred)
{
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index d7f2cad388c8..4cf5d802032c 100644
--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -1632,6 +1632,13 @@ static void userns_put(struct ns_common *ns)
put_user_ns(to_user_ns(ns));
}
+int install_user_ns_cred(struct cred *cred, struct user_namespace *user_ns)
+{
+ put_user_ns(cred->user_ns);
+ set_cred_user_ns(cred, get_user_ns(user_ns));
+ return set_cred_ucounts(cred);
+}
+
static int userns_install(struct nsset *nsset, struct ns_common *ns)
{
struct user_namespace *user_ns = to_user_ns(ns);
@@ -1657,10 +1664,7 @@ static int userns_install(struct nsset *nsset, struct ns_common *ns)
if (!cred)
return -EINVAL;
- put_user_ns(cred->user_ns);
- set_cred_user_ns(cred, get_user_ns(user_ns));
-
- if (set_cred_ucounts(cred) < 0)
+ if (install_user_ns_cred(cred, user_ns) < 0)
return -EINVAL;
return 0;
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 09/25] nsfs: Add nsproxy_open_namespace()
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (7 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 08/25] userns: Factor out install_user_ns_cred() Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 10/25] nsproxy: Pass nsproxy to create_new_namespaces() Jarkko Sakkinen
` (15 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
Zygmunt Krynicki
Opening nsfs file descriptors currently operates on a live task via
procfs or pidfs, preventing callers that own a detached struct nsproxy
and struct user_namespace from opening member namespace file descriptors
directly.
Add nsproxy_open_namespace() to take a passive reference on the
requested namespace type (CLONE_NEWNS, CLONE_NEWCGROUP, CLONE_NEWUTS,
CLONE_NEWIPC, CLONE_NEWUSER, CLONE_NEWPID, CLONE_NEWNET, or
CLONE_NEWTIME) from a supplied nsproxy and user_ns pair and return an
nsfs file descriptor via open_namespace().
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/nsfs.c | 64 ++++++++++++++++++++++++++++++++++++++++++++
include/linux/nsfs.h | 2 ++
2 files changed, 66 insertions(+)
diff --git a/fs/nsfs.c b/fs/nsfs.c
index 8179d69da038..1de51cd47508 100644
--- a/fs/nsfs.c
+++ b/fs/nsfs.c
@@ -711,3 +711,67 @@ void nsproxy_ns_active_put(struct nsproxy *ns)
ns_ref_active_put(ns->time_ns);
ns_ref_active_put(ns->time_ns_for_children);
}
+
+int nsproxy_open_namespace(struct nsproxy *nsp, struct user_namespace *user_ns,
+ unsigned long nstype)
+{
+ struct ns_common *ns = NULL;
+
+ switch (nstype) {
+ case CLONE_NEWNS:
+ if (ns_ref_get(nsp->mnt_ns))
+ ns = to_ns_common(nsp->mnt_ns);
+ break;
+#ifdef CONFIG_CGROUPS
+ case CLONE_NEWCGROUP:
+ if (ns_ref_get(nsp->cgroup_ns))
+ ns = to_ns_common(nsp->cgroup_ns);
+ break;
+#endif
+#ifdef CONFIG_UTS_NS
+ case CLONE_NEWUTS:
+ if (ns_ref_get(nsp->uts_ns))
+ ns = to_ns_common(nsp->uts_ns);
+ break;
+#endif
+#ifdef CONFIG_IPC_NS
+ case CLONE_NEWIPC:
+ if (ns_ref_get(nsp->ipc_ns))
+ ns = to_ns_common(nsp->ipc_ns);
+ break;
+#endif
+#ifdef CONFIG_USER_NS
+ case CLONE_NEWUSER:
+ if (ns_ref_get(user_ns))
+ ns = to_ns_common(user_ns);
+ break;
+#endif
+#ifdef CONFIG_PID_NS
+ case CLONE_NEWPID:
+ if (ns_ref_get(nsp->pid_ns_for_children))
+ ns = to_ns_common(nsp->pid_ns_for_children);
+ break;
+#endif
+#ifdef CONFIG_NET_NS
+ case CLONE_NEWNET:
+ if (ns_ref_get(nsp->net_ns))
+ ns = to_ns_common(nsp->net_ns);
+ break;
+#endif
+ case CLONE_NEWTIME:
+#ifdef CONFIG_TIME_NS
+ if (ns_ref_get(nsp->time_ns))
+ ns = to_ns_common(nsp->time_ns);
+ break;
+#else
+ return -EOPNOTSUPP;
+#endif
+ default:
+ return -EINVAL;
+ }
+
+ if (!ns)
+ return -ESRCH;
+
+ return open_namespace(ns);
+}
diff --git a/include/linux/nsfs.h b/include/linux/nsfs.h
index 731b67fc2fec..bfba790ee1a7 100644
--- a/include/linux/nsfs.h
+++ b/include/linux/nsfs.h
@@ -39,5 +39,7 @@ void nsfs_init(void);
void nsproxy_ns_active_get(struct nsproxy *ns);
void nsproxy_ns_active_put(struct nsproxy *ns);
+int nsproxy_open_namespace(struct nsproxy *nsp, struct user_namespace *user_ns,
+ unsigned long nstype);
#endif /* _LINUX_NSFS_H */
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 10/25] nsproxy: Pass nsproxy to create_new_namespaces()
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (8 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 09/25] nsfs: Add nsproxy_open_namespace() Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 11/25] rootns: Add core infrastructure for root namespaces Jarkko Sakkinen
` (14 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
Zygmunt Krynicki
create_new_namespaces() takes a struct task_struct pointer even though
it only reads tsk->nsproxy, preventing callers outside kernel/nsproxy.c
from constructing a child nsproxy without mutating a task.
Expose create_new_namespaces() and pass the source struct nsproxy
pointer directly so root namespace creation can allocate a detached
namespace set from current->nsproxy.
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 | 5 +++++
kernel/nsproxy.c | 32 ++++++++++++++++----------------
2 files changed, 21 insertions(+), 16 deletions(-)
diff --git a/include/linux/nsproxy.h b/include/linux/nsproxy.h
index dc2447f5f092..cacbbbe3f1ce 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,10 @@ static inline struct cred *nsset_cred(struct nsset *set)
*
*/
+struct nsproxy *create_new_namespaces(u64 flags,
+ struct nsproxy *ns,
+ struct user_namespace *user_ns,
+ struct fs_struct *new_fs);
int copy_namespaces(u64 flags, struct task_struct *tsk);
void switch_cred_namespaces(const struct cred *old, const struct cred *new);
void exit_nsproxy_namespaces(struct task_struct *tsk);
diff --git a/kernel/nsproxy.c b/kernel/nsproxy.c
index 2dcf105e8ee2..8a3c6d4e94e2 100644
--- a/kernel/nsproxy.c
+++ b/kernel/nsproxy.c
@@ -85,9 +85,10 @@ void deactivate_nsproxy(struct nsproxy *ns)
* Return the newly created nsproxy. Do not attach this to the task,
* leave it to the caller to do proper locking and attach it to task.
*/
-static struct nsproxy *create_new_namespaces(u64 flags,
- struct task_struct *tsk, struct user_namespace *user_ns,
- struct fs_struct *new_fs)
+struct nsproxy *create_new_namespaces(u64 flags,
+ struct nsproxy *ns,
+ struct user_namespace *user_ns,
+ struct fs_struct *new_fs)
{
struct nsproxy *new_nsp;
int err;
@@ -96,52 +97,51 @@ static struct nsproxy *create_new_namespaces(u64 flags,
if (!new_nsp)
return ERR_PTR(-ENOMEM);
- new_nsp->mnt_ns = copy_mnt_ns(flags, tsk->nsproxy->mnt_ns,
- user_ns, new_fs);
+ new_nsp->mnt_ns = copy_mnt_ns(flags, ns->mnt_ns, user_ns, new_fs);
if (IS_ERR(new_nsp->mnt_ns)) {
err = PTR_ERR(new_nsp->mnt_ns);
goto out_ns;
}
- new_nsp->uts_ns = copy_utsname(flags, user_ns, tsk->nsproxy->uts_ns);
+ new_nsp->uts_ns = copy_utsname(flags, user_ns, ns->uts_ns);
if (IS_ERR(new_nsp->uts_ns)) {
err = PTR_ERR(new_nsp->uts_ns);
goto out_uts;
}
- new_nsp->ipc_ns = copy_ipcs(flags, user_ns, tsk->nsproxy->ipc_ns);
+ new_nsp->ipc_ns = copy_ipcs(flags, user_ns, ns->ipc_ns);
if (IS_ERR(new_nsp->ipc_ns)) {
err = PTR_ERR(new_nsp->ipc_ns);
goto out_ipc;
}
new_nsp->pid_ns_for_children =
- copy_pid_ns(flags, user_ns, tsk->nsproxy->pid_ns_for_children);
+ copy_pid_ns(flags, user_ns, ns->pid_ns_for_children);
if (IS_ERR(new_nsp->pid_ns_for_children)) {
err = PTR_ERR(new_nsp->pid_ns_for_children);
goto out_pid;
}
new_nsp->cgroup_ns = copy_cgroup_ns(flags, user_ns,
- tsk->nsproxy->cgroup_ns);
+ ns->cgroup_ns);
if (IS_ERR(new_nsp->cgroup_ns)) {
err = PTR_ERR(new_nsp->cgroup_ns);
goto out_cgroup;
}
- new_nsp->net_ns = copy_net_ns(flags, user_ns, tsk->nsproxy->net_ns);
+ new_nsp->net_ns = copy_net_ns(flags, user_ns, ns->net_ns);
if (IS_ERR(new_nsp->net_ns)) {
err = PTR_ERR(new_nsp->net_ns);
goto out_net;
}
new_nsp->time_ns_for_children = copy_time_ns(flags, user_ns,
- tsk->nsproxy->time_ns_for_children);
+ ns->time_ns_for_children);
if (IS_ERR(new_nsp->time_ns_for_children)) {
err = PTR_ERR(new_nsp->time_ns_for_children);
goto out_time;
}
- new_nsp->time_ns = get_time_ns(tsk->nsproxy->time_ns);
+ new_nsp->time_ns = get_time_ns(ns->time_ns);
return new_nsp;
@@ -192,7 +192,7 @@ int copy_namespaces(u64 flags, struct task_struct *tsk)
(CLONE_NEWIPC | CLONE_SYSVSEM))
return -EINVAL;
- new_ns = create_new_namespaces(flags, tsk, user_ns, tsk->fs);
+ new_ns = create_new_namespaces(flags, tsk->nsproxy, user_ns, tsk->fs);
if (IS_ERR(new_ns))
return PTR_ERR(new_ns);
@@ -231,7 +231,7 @@ int unshare_nsproxy_namespaces(unsigned long unshare_flags,
flags |= CLONE_EMPTY_MNTNS;
}
- *new_nsp = create_new_namespaces(flags, current, user_ns,
+ *new_nsp = create_new_namespaces(flags, current->nsproxy, user_ns,
new_fs ? new_fs : current->fs);
if (IS_ERR(*new_nsp)) {
err = PTR_ERR(*new_nsp);
@@ -289,7 +289,7 @@ int exec_task_namespaces(void)
if (tsk->nsproxy->time_ns_for_children == tsk->nsproxy->time_ns)
return 0;
- new = create_new_namespaces(0, tsk, current_user_ns(), tsk->fs);
+ new = create_new_namespaces(0, tsk->nsproxy, current_user_ns(), tsk->fs);
if (IS_ERR(new))
return PTR_ERR(new);
@@ -356,7 +356,7 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)
struct task_struct *me = current;
nsset->flags = flags;
- nsset->nsproxy = create_new_namespaces(0, me, current_user_ns(), me->fs);
+ nsset->nsproxy = create_new_namespaces(0, me->nsproxy, current_user_ns(), me->fs);
if (IS_ERR(nsset->nsproxy))
return PTR_ERR(nsset->nsproxy);
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 11/25] rootns: Add core infrastructure for root namespaces
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (9 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 10/25] nsproxy: Pass nsproxy to create_new_namespaces() Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 12/25] rootns: Track init lifecycle via copy_process() and pid_namespace Jarkko Sakkinen
` (13 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
Zygmunt Krynicki
Linux namespaces can be created and entered individually, but userspace
orchestrators lack a single kernel object that binds a full detached
namespace set and an init process behind a pollable file descriptor.
Add struct rootns, its lifecycle states, reference counting, uAPI
creation flags, ROOTNS_GET_NSFD ioctl, and anonymous inode file
operations under CONFIG_ROOTNS. Drop active and passive namespace
references on final release, send SIGKILL to the rootns init thread
group on close when ROOTNS_KILL_ON_CLOSE is set, report EPOLLHUP from
poll() once the rootns reaches ROOTNS_DEAD, and allow holders with
CAP_SYS_ADMIN in the rootns user namespace to open member nsfs fds.
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/rootns.h | 61 ++++++++++++
include/uapi/linux/rootns.h | 44 +++++++++
init/Kconfig | 9 ++
kernel/Makefile | 2 +
kernel/rootns.c | 187 ++++++++++++++++++++++++++++++++++++
5 files changed, 303 insertions(+)
create mode 100644 include/linux/rootns.h
create mode 100644 include/uapi/linux/rootns.h
create mode 100644 kernel/rootns.c
diff --git a/include/linux/rootns.h b/include/linux/rootns.h
new file mode 100644
index 000000000000..dcdba08cfaeb
--- /dev/null
+++ b/include/linux/rootns.h
@@ -0,0 +1,61 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.
+ * Copyright (C) 2026 Opinsys Oy
+ */
+
+#ifndef _LINUX_ROOTNS_H
+#define _LINUX_ROOTNS_H
+
+#include <linux/refcount.h>
+#include <linux/spinlock.h>
+#include <linux/wait.h>
+
+struct file;
+struct nsproxy;
+struct pid;
+struct user_namespace;
+
+enum rootns_state {
+ ROOTNS_INIT = 0,
+ ROOTNS_FORKING = 1,
+ ROOTNS_RUNNING = 2,
+ ROOTNS_DEAD = 3,
+};
+
+/*
+ * The rootns object.
+ */
+struct rootns {
+ refcount_t usage;
+ int exit_code; /* The exit code of 'init' */
+ struct user_namespace *user_ns; /* Owning user namespace */
+ struct nsproxy *ns; /* This rootns's namespaces */
+ struct pid *init_pid; /* The 'init' task's TGID (pid ref) */
+ spinlock_t lock; /* Guards rootns lifecycle state */
+ wait_queue_head_t waitq; /* Someone waiting for init to exit waits here */
+ unsigned int flags; /* Validated rootns() flags */
+ enum rootns_state state; /* Root namespace lifecycle state */
+};
+
+#ifdef CONFIG_ROOTNS
+struct rootns *get_rootns(struct rootns *c);
+void put_rootns(struct rootns *c);
+bool is_rootns_file(struct file *file);
+#else
+static inline struct rootns *get_rootns(struct rootns *c)
+{
+ return NULL;
+}
+
+static inline void put_rootns(struct rootns *c)
+{
+}
+
+static inline bool is_rootns_file(struct file *file)
+{
+ return false;
+}
+#endif /* CONFIG_ROOTNS */
+
+#endif /* _LINUX_ROOTNS_H */
diff --git a/include/uapi/linux/rootns.h b/include/uapi/linux/rootns.h
new file mode 100644
index 000000000000..bd643bdfb43c
--- /dev/null
+++ b/include/uapi/linux/rootns.h
@@ -0,0 +1,44 @@
+/* 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_ROOTNS_H
+#define _UAPI_LINUX_ROOTNS_H
+
+#include <linux/ioctl.h>
+
+/**
+ * enum rootns_flags - Flags for rootns()
+ * @ROOTNS_KILL_ON_CLOSE: Send %SIGKILL to rootns init on final fd release.
+ * @ROOTNS_CLOSE_ON_EXEC: Set %O_CLOEXEC on the returned control fd.
+ * @ROOTNS_ALL_FLAGS: Mask of all valid flags accepted by rootns().
+ *
+ * Every root namespace allocates a full set of detached namespaces owned
+ * by a fresh user namespace.
+ */
+enum rootns_flags {
+ ROOTNS_KILL_ON_CLOSE = 0x00000001,
+ ROOTNS_CLOSE_ON_EXEC = 0x00000002,
+ ROOTNS_ALL_FLAGS = 0x00000003,
+};
+
+#define ROOTNS_IOCTL_MAGIC 0xB9
+
+/**
+ * DOC: ROOTNS_GET_NSFD
+ *
+ * ``ioctl(rootnsfd, ROOTNS_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 ``rootns`` user namespace. Opening
+ * ``CLONE_NEWPID`` additionally requires running in an ancestor active PID
+ * namespace and that ``rootns`` init is running.
+ */
+#define ROOTNS_GET_NSFD _IO(ROOTNS_IOCTL_MAGIC, 0x01)
+
+#endif /* _UAPI_LINUX_ROOTNS_H */
diff --git a/init/Kconfig b/init/Kconfig
index c8a7cfa60a6e..58eafca2f42a 100644
--- a/init/Kconfig
+++ b/init/Kconfig
@@ -1283,6 +1283,15 @@ config NET_NS
endif # NAMESPACES
+config ROOTNS
+ bool "Root namespace descriptor support"
+ depends on NAMESPACES && USER_NS && PID_NS && UTS_NS && IPC_NS && NET_NS && CGROUPS
+ help
+ Allow user space to create and manage isolated namespace sets and
+ their init process lifecycle through an anonymous-inode control file
+ descriptor via rootns(), rootns ioctls, FSCONFIG_SET_ROOTNS, and
+ clone3() with CLONE_INTO_ROOTNS.
+
config CHECKPOINT_RESTORE
bool "Checkpoint/restore support"
depends on PROC_FS
diff --git a/kernel/Makefile b/kernel/Makefile
index 4ff92e24680c..7074d2664ce7 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_ROOTNS) += rootns.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/rootns.c b/kernel/rootns.c
new file mode 100644
index 000000000000..033e0aae386f
--- /dev/null
+++ b/kernel/rootns.c
@@ -0,0 +1,187 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.
+ * Copyright (C) 2026 Opinsys Oy
+ */
+
+/**
+ * DOC: Overview
+ *
+ * A ``rootns`` is an anonymous-inode control file descriptor (not an ``nsfs``
+ * namespace) that binds a full set of detached namespaces, an initially empty
+ * mount namespace, an owning user namespace, and an init process lifecycle:
+ *
+ * 1. ``rootns()`` allocates a detached ``rootns`` with a fresh user namespace
+ * and dedicated mount (``CLONE_EMPTY_MNTNS``), PID, UTS, IPC, network,
+ * cgroup, and time namespaces, returning its control fd.
+ *
+ * 2. Userspace optionally maps UIDs/GIDs via ``userns_set_idmap()`` on the
+ * ``CLONE_NEWUSER`` fd, configures superblocks via ``FSCONFIG_SET_ROOTNS``,
+ * retrieves the mount namespace fd via ``ioctl(rootnsfd, ROOTNS_GET_NSFD,
+ * CLONE_NEWNS)``, and installs ``"/"`` and relative or cloned
+ * (``MOVE_MOUNT_CLONE``) submounts via ``MOVE_MOUNT_T_MNTNS``.
+ *
+ * 3. ``clone3()`` with ``CLONE_INTO_ROOTNS`` spawns processes into the
+ * ``rootns``; the first call commits PID 1 while concurrent bootstrap
+ * callers wait killably.
+ *
+ * 4. ``ioctl(rootnsfd, ROOTNS_KILL, sig)`` signals all member thread groups.
+ * When PID 1 exits, the PID namespace zaps and reaps all remaining tasks,
+ * ``poll()`` reports ``EPOLLHUP``, and ``ioctl(rootnsfd, ROOTNS_WAIT,
+ * &args)`` returns init's exit status.
+ */
+
+#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/rootns.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/compat.h>
+#include <linux/idr.h>
+#include <uapi/linux/rootns.h>
+
+/*
+ * Get a reference to a rootns.
+ */
+struct rootns *get_rootns(struct rootns *c)
+{
+ refcount_inc(&c->usage);
+ return c;
+}
+
+/*
+ * Drop a reference on a rootns and clear it if it is no longer in use.
+ */
+void put_rootns(struct rootns *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);
+}
+
+/*
+ * Allow the user to poll for the rootns dying.
+ */
+static __poll_t rootns_poll(struct file *file, poll_table *wait)
+{
+ struct rootns *rootns = file->private_data;
+ __poll_t mask = 0;
+
+ poll_wait(file, &rootns->waitq, wait);
+
+ if (READ_ONCE(rootns->state) == ROOTNS_DEAD)
+ mask |= EPOLLHUP;
+
+ return mask;
+}
+
+static long rootns_get_nsfd(struct rootns *rootns, unsigned long nstype)
+{
+ if (nstype > UINT_MAX)
+ return -EINVAL;
+ if (!ns_capable(rootns->user_ns, CAP_SYS_ADMIN))
+ return -EPERM;
+
+ if (nstype == CLONE_NEWPID) {
+ if (!pidns_is_ancestor(rootns->ns->pid_ns_for_children,
+ task_active_pid_ns(current)))
+ return -EXDEV;
+ if (READ_ONCE(rootns->state) != ROOTNS_RUNNING)
+ return -ESRCH;
+ }
+
+ return nsproxy_open_namespace(rootns->ns, rootns->user_ns, nstype);
+}
+
+static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
+{
+ struct rootns *rootns = file->private_data;
+
+ switch (cmd) {
+ case ROOTNS_GET_NSFD:
+ return rootns_get_nsfd(rootns, arg);
+ default:
+ return -ENOIOCTLCMD;
+ }
+}
+
+#ifdef CONFIG_COMPAT
+static long rootns_compat_ioctl(struct file *file, unsigned int cmd,
+ unsigned long arg)
+{
+ switch (cmd) {
+ case ROOTNS_GET_NSFD:
+ return rootns_ioctl(file, cmd, arg);
+ default:
+ return -ENOIOCTLCMD;
+ }
+}
+#endif
+
+static int __rootns_kill(struct rootns *rootns, int sig, bool priv)
+{
+ struct pid *pid = NULL;
+ int ret;
+
+ scoped_guard(spinlock, &rootns->lock) {
+ if (rootns->state == ROOTNS_RUNNING)
+ pid = get_pid(rootns->init_pid);
+ }
+ if (!pid)
+ return -ESRCH;
+
+ ret = kill_pid(pid, sig, priv);
+ put_pid(pid);
+ return ret;
+}
+
+static int rootns_release(struct inode *inode, struct file *file)
+{
+ struct rootns *rootns = file->private_data;
+
+ if (rootns->flags & ROOTNS_KILL_ON_CLOSE)
+ __rootns_kill(rootns, SIGKILL, true);
+ put_rootns(rootns);
+ return 0;
+}
+
+static const struct file_operations rootns_fops = {
+ .poll = rootns_poll,
+ .unlocked_ioctl = rootns_ioctl,
+#ifdef CONFIG_COMPAT
+ .compat_ioctl = rootns_compat_ioctl,
+#endif
+ .release = rootns_release,
+};
+
+/*
+ * Returns true if the file is a rootns.
+ */
+bool is_rootns_file(struct file *file)
+{
+ return file->f_op == &rootns_fops;
+}
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 12/25] rootns: Track init lifecycle via copy_process() and pid_namespace
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (10 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 11/25] rootns: Add core infrastructure for root namespaces Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 1:32 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 13/25] rootns: Add rootns() system call Jarkko Sakkinen
` (12 subsequent siblings)
24 siblings, 1 reply; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
Zygmunt Krynicki
A root namespace needs to record its init thread group's PID when
bootstrapped and capture its exit status once all processes in the root
namespace have terminated, without serializing normal fork() and exit()
paths inside the container.
Commit the bootstrap child reaper and bind pid_ns->rootns in
copy_rootns() after attach_pid(PIDTYPE_PID), and invoke exit_rootns()
from zap_pid_ns_processes() after the root namespace's PID namespace has
killed and reaped all member tasks.
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/pid_namespace.h | 4 ++++
include/linux/rootns.h | 15 ++++++++++++++
kernel/fork.c | 3 +++
kernel/pid_namespace.c | 2 ++
kernel/rootns.c | 37 +++++++++++++++++++++++++++++++++++
5 files changed, 61 insertions(+)
diff --git a/include/linux/pid_namespace.h b/include/linux/pid_namespace.h
index b20baaa7e62b..6fd959f4d0d4 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 rootns;
#if defined(CONFIG_SYSCTL) && defined(CONFIG_MEMFD_CREATE)
/* modes for vm.memfd_noexec sysctl */
@@ -45,6 +46,9 @@ struct pid_namespace {
struct user_namespace *user_ns;
struct ucounts *ucounts;
int reboot; /* group exit code if this pidns was rebooted */
+#ifdef CONFIG_ROOTNS
+ struct rootns *rootns;
+#endif
struct ns_common ns;
struct work_struct work;
} __randomize_layout;
diff --git a/include/linux/rootns.h b/include/linux/rootns.h
index dcdba08cfaeb..6add4dd55550 100644
--- a/include/linux/rootns.h
+++ b/include/linux/rootns.h
@@ -14,6 +14,8 @@
struct file;
struct nsproxy;
struct pid;
+struct pid_namespace;
+struct task_struct;
struct user_namespace;
enum rootns_state {
@@ -42,6 +44,9 @@ struct rootns {
struct rootns *get_rootns(struct rootns *c);
void put_rootns(struct rootns *c);
bool is_rootns_file(struct file *file);
+void copy_rootns(struct task_struct *tsk, struct pid *pid,
+ struct rootns *rootns);
+void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk);
#else
static inline struct rootns *get_rootns(struct rootns *c)
{
@@ -56,6 +61,16 @@ static inline bool is_rootns_file(struct file *file)
{
return false;
}
+
+static inline void copy_rootns(struct task_struct *tsk, struct pid *pid,
+ struct rootns *rootns)
+{
+}
+
+static inline void exit_rootns(struct pid_namespace *pid_ns,
+ struct task_struct *tsk)
+{
+}
#endif /* CONFIG_ROOTNS */
#endif /* _LINUX_ROOTNS_H */
diff --git a/kernel/fork.c b/kernel/fork.c
index 5efceb8d58a7..08fc28ad1eed 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/rootns.h>
#include <linux/posix-timers.h>
#include <linux/user-return-notifier.h>
#include <linux/oom.h>
@@ -2576,6 +2577,8 @@ __latent_entropy struct task_struct *copy_process(
&p->signal->thread_head);
}
attach_pid(p, PIDTYPE_PID);
+ if (thread_group_leader(p))
+ copy_rootns(p, pid, NULL);
nr_threads++;
}
total_forks++;
diff --git a/kernel/pid_namespace.c b/kernel/pid_namespace.c
index 127a5fd23e70..081c27aa85bd 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/rootns.h>
#include <uapi/linux/wait.h>
#include "pid_sysctl.h"
@@ -280,6 +281,7 @@ void zap_pid_ns_processes(struct pid_namespace *pid_ns)
current->signal->group_exit_code = pid_ns->reboot;
acct_exit_ns(pid_ns);
+ exit_rootns(pid_ns, me);
return;
}
diff --git a/kernel/rootns.c b/kernel/rootns.c
index 033e0aae386f..fd8ce59de61a 100644
--- a/kernel/rootns.c
+++ b/kernel/rootns.c
@@ -185,3 +185,40 @@ bool is_rootns_file(struct file *file)
{
return file->f_op == &rootns_fops;
}
+
+void copy_rootns(struct task_struct *tsk, struct pid *pid, struct rootns *c)
+{
+ if (likely(!c || !is_child_reaper(pid)))
+ return;
+
+ scoped_guard(spinlock, &c->lock) {
+ if (c->state != ROOTNS_FORKING)
+ return;
+ ns_of_pid(pid)->rootns = get_rootns(c);
+ WRITE_ONCE(c->init_pid, get_pid(pid));
+ WRITE_ONCE(c->state, ROOTNS_RUNNING);
+ }
+}
+
+void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk)
+{
+ struct rootns *c = pid_ns->rootns;
+ struct task_struct *leader;
+ int status;
+
+ if (!c)
+ return;
+
+ leader = tsk->group_leader;
+ status = (tsk->signal->flags & SIGNAL_GROUP_EXIT) ?
+ tsk->signal->group_exit_code : leader->exit_code;
+
+ scoped_guard(spinlock, &c->lock) {
+ c->exit_code = status;
+ WRITE_ONCE(c->state, ROOTNS_DEAD);
+ }
+
+ pid_ns->rootns = NULL;
+ __wake_up(&c->waitq, TASK_NORMAL, 0, poll_to_key(EPOLLHUP));
+ put_rootns(c);
+}
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* Re: [RFC PATCH v5 12/25] rootns: Track init lifecycle via copy_process() and pid_namespace
2026-11-21 0:08 ` [RFC PATCH v5 12/25] rootns: Track init lifecycle via copy_process() and pid_namespace Jarkko Sakkinen
@ 2026-11-21 1:32 ` Jarkko Sakkinen
0 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 1:32 UTC (permalink / raw)
To: linux-fsdevel
Cc: linux-api, linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Alexander Mikhalitsyn, Alexander Viro,
Andy Lutomirski, Christian Brauner, David Howells, Jan Kara,
Jonathan Corbet, Josef Bacik, Kees Cook, Neal Gompa, Paul Moore,
Serge Hallyn, Zygmunt Krynicki
On Sat, Nov 21, 2026 at 02:08:31AM +0200, Jarkko Sakkinen wrote:
> A root namespace needs to record its init thread group's PID when
> bootstrapped and capture its exit status once all processes in the root
> namespace have terminated, without serializing normal fork() and exit()
> paths inside the container.
>
> Commit the bootstrap child reaper and bind pid_ns->rootns in
> copy_rootns() after attach_pid(PIDTYPE_PID), and invoke exit_rootns()
> from zap_pid_ns_processes() after the root namespace's PID namespace has
> killed and reaped all member tasks.
>
> Co-developed-by: David Howells <dhowells@redhat.com>
> Signed-off-by: David Howells <dhowells@redhat.com>
> Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
ROOTNS_GET_NSFD will be the only surviving ioctl, which make access
control wise sense.
This leaves room for ROOTNS_SHARE_NSFD, which would share a namespace
from host. This makes whole a lot more sense than unsharing security
wise as it is allow listing (instead of deny listing).
It can be post-clone3 disabled. This is what we do in SGX driver i.e.,
have build phase enabled ioctls.
Br, Jarkko
^ permalink raw reply [flat|nested] 33+ messages in thread
* [RFC PATCH v5 13/25] rootns: Add rootns() system call
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (11 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 12/25] rootns: Track init lifecycle via copy_process() and pid_namespace Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 14/25] rootns: Add ROOTNS_WAIT ioctl Jarkko Sakkinen
` (11 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
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 rootns() system call to allocate a detached rootns instance
owning a fresh user namespace alongside dedicated empty mount
(CLONE_EMPTY_MNTNS), PID, UTS, IPC, network, cgroup, and time
namespaces, and return its control file descriptor. Finalize the nsproxy
time namespace and pin active references for the lifetime of the rootns.
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 +
include/linux/time_namespace.h | 13 ++++
kernel/rootns.c | 106 +++++++++++++++++++++++++++++++++
kernel/sys_ni.c | 3 +
4 files changed, 123 insertions(+)
diff --git a/include/linux/syscalls.h b/include/linux/syscalls.h
index 72308cc11908..8284bce1c31e 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_rootns(unsigned int flags);
/*
* Architecture-specific system calls
diff --git a/include/linux/time_namespace.h b/include/linux/time_namespace.h
index 58bd9728df58..bdc185543893 100644
--- a/include/linux/time_namespace.h
+++ b/include/linux/time_namespace.h
@@ -60,6 +60,15 @@ static inline void put_time_ns(struct time_namespace *ns)
free_time_ns(ns);
}
+static inline void timens_activate_nsproxy(struct nsproxy *nsproxy)
+{
+ if (nsproxy->time_ns != nsproxy->time_ns_for_children) {
+ get_time_ns(nsproxy->time_ns_for_children);
+ put_time_ns(nsproxy->time_ns);
+ nsproxy->time_ns = nsproxy->time_ns_for_children;
+ }
+}
+
void proc_timens_show_offsets(struct task_struct *p, struct seq_file *m);
struct proc_timens_offset {
@@ -125,6 +134,10 @@ static inline void put_time_ns(struct time_namespace *ns)
{
}
+static inline void timens_activate_nsproxy(struct nsproxy *nsproxy)
+{
+}
+
static inline
struct time_namespace *copy_time_ns(u64 flags,
struct user_namespace *user_ns,
diff --git a/kernel/rootns.c b/kernel/rootns.c
index fd8ce59de61a..5d59fc9a591d 100644
--- a/kernel/rootns.c
+++ b/kernel/rootns.c
@@ -222,3 +222,109 @@ void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk)
__wake_up(&c->waitq, TASK_NORMAL, 0, poll_to_key(EPOLLHUP));
put_rootns(c);
}
+
+static struct user_namespace *create_rootns_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;
+}
+
+/*
+ * Create a new rootns.
+ */
+static struct rootns *create_rootns(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 rootns *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 = create_rootns_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->nsproxy, user_ns,
+ NULL);
+ if (IS_ERR(ns)) {
+ ret = PTR_ERR(ns);
+ goto err_put;
+ }
+
+ timens_activate_nsproxy(ns);
+ c->ns = ns;
+ nsproxy_ns_active_get(ns);
+
+ return c;
+
+err_put:
+ put_rootns(c);
+ return ERR_PTR(ret);
+}
+
+/**
+ * sys_rootns - Create a detached root namespace
+ * @flags: Combination of &enum rootns_flags values
+ *
+ * Allocate a detached root namespace owning a fresh user namespace and
+ * dedicated empty mount, PID, UTS, IPC, network, cgroup, and time namespaces.
+ *
+ * Return: Control file descriptor on success, negative error code on failure.
+ */
+SYSCALL_DEFINE1(rootns, unsigned int, flags)
+{
+ struct rootns *c;
+ int fd;
+
+ if (flags & ~ROOTNS_ALL_FLAGS)
+ return -EINVAL;
+ if (unlikely(!current->nsproxy))
+ return -EOPNOTSUPP;
+
+ c = create_rootns(flags);
+ if (IS_ERR(c))
+ return PTR_ERR(c);
+
+ fd = anon_inode_getfd("rootns", &rootns_fops, c,
+ O_RDWR | (flags & ROOTNS_CLOSE_ON_EXEC ? O_CLOEXEC : 0));
+ if (fd < 0)
+ put_rootns(c);
+
+ return fd;
+}
diff --git a/kernel/sys_ni.c b/kernel/sys_ni.c
index e3202e7cc2a1..f095401bed24 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/rootns.c */
+COND_SYSCALL(rootns);
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 14/25] rootns: Add ROOTNS_WAIT ioctl
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (12 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 13/25] rootns: Add rootns() system call Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:17 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 15/25] rootns: Add ROOTNS_KILL ioctl Jarkko Sakkinen
` (10 subsequent siblings)
24 siblings, 1 reply; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
Zygmunt Krynicki
wait4() and waitid() only allow a parent or subreaper to collect exit
status, so an external manager holding a rootns file descriptor cannot
wait on a rootns init process forked by another process or observe exit
status multiple times across observers.
Add the ROOTNS_WAIT ioctl and struct rootns_wait_args to wait freezably
and interruptibly on a rootns file descriptor until its init thread group
exits and report the recorded wait status. Return the init TGID
translated into the caller's active PID namespace, 0 for WNOHANG while
running, or -ECHILD if init was never started or is not visible to the
caller.
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/uapi/linux/rootns.h | 26 +++++++++++++++++++++
kernel/rootns.c | 46 +++++++++++++++++++++++++++++++++++++
2 files changed, 72 insertions(+)
diff --git a/include/uapi/linux/rootns.h b/include/uapi/linux/rootns.h
index bd643bdfb43c..3fd215185398 100644
--- a/include/uapi/linux/rootns.h
+++ b/include/uapi/linux/rootns.h
@@ -8,6 +8,7 @@
#define _UAPI_LINUX_ROOTNS_H
#include <linux/ioctl.h>
+#include <linux/types.h>
/**
* enum rootns_flags - Flags for rootns()
@@ -24,6 +25,16 @@ enum rootns_flags {
ROOTNS_ALL_FLAGS = 0x00000003,
};
+/**
+ * struct rootns_wait_args - Arguments for %ROOTNS_WAIT
+ * @flags: Wait options (0 or %WNOHANG).
+ * @status: Output wait status of rootns init in waitpid(2) format.
+ */
+struct rootns_wait_args {
+ __u32 flags;
+ __s32 status;
+};
+
#define ROOTNS_IOCTL_MAGIC 0xB9
/**
@@ -41,4 +52,19 @@ enum rootns_flags {
*/
#define ROOTNS_GET_NSFD _IO(ROOTNS_IOCTL_MAGIC, 0x01)
+/**
+ * DOC: ROOTNS_WAIT
+ *
+ * ``ioctl(rootnsfd, ROOTNS_WAIT, &args)`` waits interruptibly (unless
+ * ``WNOHANG`` is set in ``args.flags``) until ``rootnsfd`` reaches
+ * ``ROOTNS_DEAD``, then writes the recorded exit status of ``rootns`` init
+ * into ``args.status``.
+ *
+ * Returns the caller-visible TGID of ``rootns`` init on success, ``0`` if
+ * ``WNOHANG`` is set and the ``rootns`` has not terminated, or ``-1`` with
+ * ``errno`` set to ``ECHILD`` if init was never started or is not visible in
+ * the caller's active PID namespace.
+ */
+#define ROOTNS_WAIT _IOWR(ROOTNS_IOCTL_MAGIC, 0x02, struct rootns_wait_args)
+
#endif /* _UAPI_LINUX_ROOTNS_H */
diff --git a/kernel/rootns.c b/kernel/rootns.c
index 5d59fc9a591d..cb74ddc8363c 100644
--- a/kernel/rootns.c
+++ b/kernel/rootns.c
@@ -117,6 +117,47 @@ static long rootns_get_nsfd(struct rootns *rootns, unsigned long nstype)
return nsproxy_open_namespace(rootns->ns, rootns->user_ns, nstype);
}
+static long rootns_wait(struct rootns *rootns, void __user *uarg)
+{
+ struct pid_namespace *pid_ns = task_active_pid_ns(current);
+ struct rootns_wait_args args;
+ long ret;
+
+ if (!uarg)
+ return -EINVAL;
+ if (copy_from_user(&args, uarg, sizeof(args)))
+ return -EFAULT;
+ if (args.flags & ~WNOHANG)
+ return -EINVAL;
+ if (!pidns_is_ancestor(rootns->ns->pid_ns_for_children, pid_ns))
+ return -ECHILD;
+ if (READ_ONCE(rootns->state) == ROOTNS_INIT)
+ return -ECHILD;
+
+ if (!(args.flags & WNOHANG)) {
+ ret = wait_event_freezable(rootns->waitq,
+ READ_ONCE(rootns->state) == ROOTNS_DEAD ||
+ READ_ONCE(rootns->state) == ROOTNS_INIT);
+ if (ret)
+ return ret;
+ }
+
+ scoped_guard(spinlock, &rootns->lock) {
+ if (rootns->state == ROOTNS_INIT)
+ return -ECHILD;
+ if (rootns->state != ROOTNS_DEAD)
+ return 0;
+ ret = pid_nr_ns(rootns->init_pid, pid_ns);
+ if (ret <= 0)
+ return -ECHILD;
+ args.status = rootns->exit_code;
+ }
+
+ if (copy_to_user(uarg, &args, sizeof(args)))
+ return -EFAULT;
+ return ret;
+}
+
static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct rootns *rootns = file->private_data;
@@ -124,6 +165,8 @@ static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
switch (cmd) {
case ROOTNS_GET_NSFD:
return rootns_get_nsfd(rootns, arg);
+ case ROOTNS_WAIT:
+ return rootns_wait(rootns, (void __user *)arg);
default:
return -ENOIOCTLCMD;
}
@@ -134,6 +177,8 @@ static long rootns_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
switch (cmd) {
+ case ROOTNS_WAIT:
+ return rootns_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
case ROOTNS_GET_NSFD:
return rootns_ioctl(file, cmd, arg);
default:
@@ -328,3 +373,4 @@ SYSCALL_DEFINE1(rootns, unsigned int, flags)
return fd;
}
+
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* Re: [RFC PATCH v5 14/25] rootns: Add ROOTNS_WAIT ioctl
2026-11-21 0:08 ` [RFC PATCH v5 14/25] rootns: Add ROOTNS_WAIT ioctl Jarkko Sakkinen
@ 2026-11-21 0:17 ` Jarkko Sakkinen
2026-11-21 0:18 ` Jarkko Sakkinen
0 siblings, 1 reply; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:17 UTC (permalink / raw)
To: linux-fsdevel
Cc: linux-api, linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Alexander Mikhalitsyn, Alexander Viro,
Andy Lutomirski, Christian Brauner, David Howells, Jan Kara,
Jonathan Corbet, Josef Bacik, Kees Cook, Neal Gompa, Paul Moore,
Serge Hallyn, Zygmunt Krynicki
On Sat, Nov 21, 2026 at 02:08:33AM +0200, Jarkko Sakkinen wrote:
> wait4() and waitid() only allow a parent or subreaper to collect exit
> status, so an external manager holding a rootns file descriptor cannot
> wait on a rootns init process forked by another process or observe exit
> status multiple times across observers.
>
> Add the ROOTNS_WAIT ioctl and struct rootns_wait_args to wait freezably
> and interruptibly on a rootns file descriptor until its init thread group
> exits and report the recorded wait status. Return the init TGID
> translated into the caller's active PID namespace, 0 for WNOHANG while
> running, or -ECHILD if init was never started or is not visible to the
> caller.
>
> 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/uapi/linux/rootns.h | 26 +++++++++++++++++++++
> kernel/rootns.c | 46 +++++++++++++++++++++++++++++++++++++
> 2 files changed, 72 insertions(+)
>
> diff --git a/include/uapi/linux/rootns.h b/include/uapi/linux/rootns.h
> index bd643bdfb43c..3fd215185398 100644
> --- a/include/uapi/linux/rootns.h
> +++ b/include/uapi/linux/rootns.h
> @@ -8,6 +8,7 @@
> #define _UAPI_LINUX_ROOTNS_H
>
> #include <linux/ioctl.h>
> +#include <linux/types.h>
>
> /**
> * enum rootns_flags - Flags for rootns()
> @@ -24,6 +25,16 @@ enum rootns_flags {
> ROOTNS_ALL_FLAGS = 0x00000003,
> };
>
> +/**
> + * struct rootns_wait_args - Arguments for %ROOTNS_WAIT
> + * @flags: Wait options (0 or %WNOHANG).
> + * @status: Output wait status of rootns init in waitpid(2) format.
> + */
> +struct rootns_wait_args {
> + __u32 flags;
> + __s32 status;
> +};
> +
> #define ROOTNS_IOCTL_MAGIC 0xB9
>
> /**
> @@ -41,4 +52,19 @@ enum rootns_flags {
> */
> #define ROOTNS_GET_NSFD _IO(ROOTNS_IOCTL_MAGIC, 0x01)
>
> +/**
> + * DOC: ROOTNS_WAIT
> + *
> + * ``ioctl(rootnsfd, ROOTNS_WAIT, &args)`` waits interruptibly (unless
> + * ``WNOHANG`` is set in ``args.flags``) until ``rootnsfd`` reaches
> + * ``ROOTNS_DEAD``, then writes the recorded exit status of ``rootns`` init
> + * into ``args.status``.
> + *
> + * Returns the caller-visible TGID of ``rootns`` init on success, ``0`` if
> + * ``WNOHANG`` is set and the ``rootns`` has not terminated, or ``-1`` with
> + * ``errno`` set to ``ECHILD`` if init was never started or is not visible in
> + * the caller's active PID namespace.
> + */
> +#define ROOTNS_WAIT _IOWR(ROOTNS_IOCTL_MAGIC, 0x02, struct rootns_wait_args)
> +
> #endif /* _UAPI_LINUX_ROOTNS_H */
> diff --git a/kernel/rootns.c b/kernel/rootns.c
> index 5d59fc9a591d..cb74ddc8363c 100644
> --- a/kernel/rootns.c
> +++ b/kernel/rootns.c
> @@ -117,6 +117,47 @@ static long rootns_get_nsfd(struct rootns *rootns, unsigned long nstype)
> return nsproxy_open_namespace(rootns->ns, rootns->user_ns, nstype);
> }
>
> +static long rootns_wait(struct rootns *rootns, void __user *uarg)
> +{
> + struct pid_namespace *pid_ns = task_active_pid_ns(current);
> + struct rootns_wait_args args;
> + long ret;
> +
> + if (!uarg)
> + return -EINVAL;
> + if (copy_from_user(&args, uarg, sizeof(args)))
> + return -EFAULT;
> + if (args.flags & ~WNOHANG)
> + return -EINVAL;
> + if (!pidns_is_ancestor(rootns->ns->pid_ns_for_children, pid_ns))
> + return -ECHILD;
> + if (READ_ONCE(rootns->state) == ROOTNS_INIT)
> + return -ECHILD;
> +
> + if (!(args.flags & WNOHANG)) {
> + ret = wait_event_freezable(rootns->waitq,
> + READ_ONCE(rootns->state) == ROOTNS_DEAD ||
> + READ_ONCE(rootns->state) == ROOTNS_INIT);
> + if (ret)
> + return ret;
> + }
> +
> + scoped_guard(spinlock, &rootns->lock) {
> + if (rootns->state == ROOTNS_INIT)
> + return -ECHILD;
> + if (rootns->state != ROOTNS_DEAD)
> + return 0;
> + ret = pid_nr_ns(rootns->init_pid, pid_ns);
> + if (ret <= 0)
> + return -ECHILD;
> + args.status = rootns->exit_code;
> + }
> +
> + if (copy_to_user(uarg, &args, sizeof(args)))
> + return -EFAULT;
> + return ret;
> +}
> +
> static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
> {
> struct rootns *rootns = file->private_data;
> @@ -124,6 +165,8 @@ static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
> switch (cmd) {
> case ROOTNS_GET_NSFD:
> return rootns_get_nsfd(rootns, arg);
> + case ROOTNS_WAIT:
> + return rootns_wait(rootns, (void __user *)arg);
> default:
> return -ENOIOCTLCMD;
> }
> @@ -134,6 +177,8 @@ static long rootns_compat_ioctl(struct file *file, unsigned int cmd,
> unsigned long arg)
> {
> switch (cmd) {
> + case ROOTNS_WAIT:
> + return rootns_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
> case ROOTNS_GET_NSFD:
> return rootns_ioctl(file, cmd, arg);
> default:
> @@ -328,3 +373,4 @@ SYSCALL_DEFINE1(rootns, unsigned int, flags)
>
> return fd;
> }
> +
> --
> 2.47.3
>
Ought to be dropped but seemed too irrelevant detail for the time
being.
Br, Jarkko
^ permalink raw reply [flat|nested] 33+ messages in thread* Re: [RFC PATCH v5 14/25] rootns: Add ROOTNS_WAIT ioctl
2026-11-21 0:17 ` Jarkko Sakkinen
@ 2026-11-21 0:18 ` Jarkko Sakkinen
2026-11-21 1:09 ` Jarkko Sakkinen
0 siblings, 1 reply; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:18 UTC (permalink / raw)
To: linux-fsdevel
Cc: linux-api, linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Alexander Mikhalitsyn, Alexander Viro,
Andy Lutomirski, Christian Brauner, David Howells, Jan Kara,
Jonathan Corbet, Josef Bacik, Kees Cook, Neal Gompa, Paul Moore,
Serge Hallyn, Zygmunt Krynicki
On Sat, Nov 21, 2026 at 02:17:20AM +0200, Jarkko Sakkinen wrote:
> On Sat, Nov 21, 2026 at 02:08:33AM +0200, Jarkko Sakkinen wrote:
> > wait4() and waitid() only allow a parent or subreaper to collect exit
> > status, so an external manager holding a rootns file descriptor cannot
> > wait on a rootns init process forked by another process or observe exit
> > status multiple times across observers.
> >
> > Add the ROOTNS_WAIT ioctl and struct rootns_wait_args to wait freezably
> > and interruptibly on a rootns file descriptor until its init thread group
> > exits and report the recorded wait status. Return the init TGID
> > translated into the caller's active PID namespace, 0 for WNOHANG while
> > running, or -ECHILD if init was never started or is not visible to the
> > caller.
> >
> > 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/uapi/linux/rootns.h | 26 +++++++++++++++++++++
> > kernel/rootns.c | 46 +++++++++++++++++++++++++++++++++++++
> > 2 files changed, 72 insertions(+)
> >
> > diff --git a/include/uapi/linux/rootns.h b/include/uapi/linux/rootns.h
> > index bd643bdfb43c..3fd215185398 100644
> > --- a/include/uapi/linux/rootns.h
> > +++ b/include/uapi/linux/rootns.h
> > @@ -8,6 +8,7 @@
> > #define _UAPI_LINUX_ROOTNS_H
> >
> > #include <linux/ioctl.h>
> > +#include <linux/types.h>
> >
> > /**
> > * enum rootns_flags - Flags for rootns()
> > @@ -24,6 +25,16 @@ enum rootns_flags {
> > ROOTNS_ALL_FLAGS = 0x00000003,
> > };
> >
> > +/**
> > + * struct rootns_wait_args - Arguments for %ROOTNS_WAIT
> > + * @flags: Wait options (0 or %WNOHANG).
> > + * @status: Output wait status of rootns init in waitpid(2) format.
> > + */
> > +struct rootns_wait_args {
> > + __u32 flags;
> > + __s32 status;
> > +};
> > +
> > #define ROOTNS_IOCTL_MAGIC 0xB9
> >
> > /**
> > @@ -41,4 +52,19 @@ enum rootns_flags {
> > */
> > #define ROOTNS_GET_NSFD _IO(ROOTNS_IOCTL_MAGIC, 0x01)
> >
> > +/**
> > + * DOC: ROOTNS_WAIT
> > + *
> > + * ``ioctl(rootnsfd, ROOTNS_WAIT, &args)`` waits interruptibly (unless
> > + * ``WNOHANG`` is set in ``args.flags``) until ``rootnsfd`` reaches
> > + * ``ROOTNS_DEAD``, then writes the recorded exit status of ``rootns`` init
> > + * into ``args.status``.
> > + *
> > + * Returns the caller-visible TGID of ``rootns`` init on success, ``0`` if
> > + * ``WNOHANG`` is set and the ``rootns`` has not terminated, or ``-1`` with
> > + * ``errno`` set to ``ECHILD`` if init was never started or is not visible in
> > + * the caller's active PID namespace.
> > + */
> > +#define ROOTNS_WAIT _IOWR(ROOTNS_IOCTL_MAGIC, 0x02, struct rootns_wait_args)
> > +
> > #endif /* _UAPI_LINUX_ROOTNS_H */
> > diff --git a/kernel/rootns.c b/kernel/rootns.c
> > index 5d59fc9a591d..cb74ddc8363c 100644
> > --- a/kernel/rootns.c
> > +++ b/kernel/rootns.c
> > @@ -117,6 +117,47 @@ static long rootns_get_nsfd(struct rootns *rootns, unsigned long nstype)
> > return nsproxy_open_namespace(rootns->ns, rootns->user_ns, nstype);
> > }
> >
> > +static long rootns_wait(struct rootns *rootns, void __user *uarg)
> > +{
> > + struct pid_namespace *pid_ns = task_active_pid_ns(current);
> > + struct rootns_wait_args args;
> > + long ret;
> > +
> > + if (!uarg)
> > + return -EINVAL;
> > + if (copy_from_user(&args, uarg, sizeof(args)))
> > + return -EFAULT;
> > + if (args.flags & ~WNOHANG)
> > + return -EINVAL;
> > + if (!pidns_is_ancestor(rootns->ns->pid_ns_for_children, pid_ns))
> > + return -ECHILD;
> > + if (READ_ONCE(rootns->state) == ROOTNS_INIT)
> > + return -ECHILD;
> > +
> > + if (!(args.flags & WNOHANG)) {
> > + ret = wait_event_freezable(rootns->waitq,
> > + READ_ONCE(rootns->state) == ROOTNS_DEAD ||
> > + READ_ONCE(rootns->state) == ROOTNS_INIT);
> > + if (ret)
> > + return ret;
> > + }
> > +
> > + scoped_guard(spinlock, &rootns->lock) {
> > + if (rootns->state == ROOTNS_INIT)
> > + return -ECHILD;
> > + if (rootns->state != ROOTNS_DEAD)
> > + return 0;
> > + ret = pid_nr_ns(rootns->init_pid, pid_ns);
> > + if (ret <= 0)
> > + return -ECHILD;
> > + args.status = rootns->exit_code;
> > + }
> > +
> > + if (copy_to_user(uarg, &args, sizeof(args)))
> > + return -EFAULT;
> > + return ret;
> > +}
> > +
> > static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
> > {
> > struct rootns *rootns = file->private_data;
> > @@ -124,6 +165,8 @@ static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
> > switch (cmd) {
> > case ROOTNS_GET_NSFD:
> > return rootns_get_nsfd(rootns, arg);
> > + case ROOTNS_WAIT:
> > + return rootns_wait(rootns, (void __user *)arg);
> > default:
> > return -ENOIOCTLCMD;
> > }
> > @@ -134,6 +177,8 @@ static long rootns_compat_ioctl(struct file *file, unsigned int cmd,
> > unsigned long arg)
> > {
> > switch (cmd) {
> > + case ROOTNS_WAIT:
> > + return rootns_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
> > case ROOTNS_GET_NSFD:
> > return rootns_ioctl(file, cmd, arg);
> > default:
> > @@ -328,3 +373,4 @@ SYSCALL_DEFINE1(rootns, unsigned int, flags)
> >
> > return fd;
> > }
> > +
> > --
> > 2.47.3
> >
>
> Ought to be dropped but seemed too irrelevant detail for the time
> being.
I mean replaced with a syscall path.
Br, Jarkko
^ permalink raw reply [flat|nested] 33+ messages in thread* Re: [RFC PATCH v5 14/25] rootns: Add ROOTNS_WAIT ioctl
2026-11-21 0:18 ` Jarkko Sakkinen
@ 2026-11-21 1:09 ` Jarkko Sakkinen
0 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 1:09 UTC (permalink / raw)
To: linux-fsdevel
Cc: linux-api, linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Alexander Mikhalitsyn, Alexander Viro,
Andy Lutomirski, Christian Brauner, David Howells, Jan Kara,
Jonathan Corbet, Josef Bacik, Kees Cook, Neal Gompa, Paul Moore,
Serge Hallyn, Zygmunt Krynicki
On Sat, Nov 21, 2026 at 02:18:14AM +0200, Jarkko Sakkinen wrote:
> > Ought to be dropped but seemed too irrelevant detail for the time
> > being
>
> I mean replaced with a syscall path.
Yeah, a lot better overall (less fallible paths).
+long rootns_waitid(int upid, struct waitid_info *infop, int options,
+ struct rusage *ru)
{
- struct pid_namespace *pid_ns = task_active_pid_ns(current);
- struct rootns_wait_args args;
+ struct pid_namespace *pid_ns;
+ unsigned int f_flags;
+ struct rootns *rootns;
+ bool nonblock;
+ int status;
+ kuid_t uid;
long ret;
- if (!uarg)
+ if (upid < 0 || ru)
return -EINVAL;
- if (copy_from_user(&args, uarg, sizeof(args)))
- return -EFAULT;
- if (args.flags & ~WNOHANG)
+ if (options & ~(WEXITED | WNOHANG | WNOWAIT))
return -EINVAL;
+ if (!(options & WEXITED))
+ return -EINVAL;
+
+ CLASS(fd, f)(upid);
+ if (fd_empty(f) || !is_rootns_file(fd_file(f)))
+ return -EBADF;
+
+ f_flags = READ_ONCE(fd_file(f)->f_flags);
+ nonblock = (options & WNOHANG) || (f_flags & O_NONBLOCK);
+ rootns = fd_file(f)->private_data;
+ pid_ns = task_active_pid_ns(current);
+
if (!pidns_is_ancestor(rootns->ns->pid_ns_for_children, pid_ns))
return -ECHILD;
if (READ_ONCE(rootns->state) == ROOTNS_INIT)
return -ECHILD;
- if (!(args.flags & WNOHANG)) {
+ if (!nonblock) {
ret = wait_event_freezable(rootns->waitq,
READ_ONCE(rootns->state) == ROOTNS_DEAD ||
READ_ONCE(rootns->state) == ROOTNS_INIT);
@@ -154,15 +191,23 @@ static long rootns_wait(struct rootns *rootns, void __user *uarg)
if (rootns->state == ROOTNS_INIT)
return -ECHILD;
if (rootns->state != ROOTNS_DEAD)
- return 0;
+ return (options & WNOHANG) ? 0 : -EAGAIN;
ret = pid_nr_ns(rootns->init_pid, pid_ns);
if (ret <= 0)
return -ECHILD;
- args.status = rootns->exit_code;
+ status = rootns->exit_code;
+ uid = rootns->init_uid;
}
- if (copy_to_user(uarg, &args, sizeof(args)))
- return -EFAULT;
+ if ((status & 0x7f) == 0) {
+ infop->cause = CLD_EXITED;
+ infop->status = status >> 8;
+ } else {
+ infop->cause = (status & 0x80) ? CLD_DUMPED : CLD_KILLED;
+ infop->status = status & 0x7f;
+ }
+ infop->pid = ret;
+ infop->uid = from_kuid_munged(current_user_ns(), uid);
return ret;
}
Br, Jarkko
^ permalink raw reply [flat|nested] 33+ messages in thread
* [RFC PATCH v5 15/25] rootns: Add ROOTNS_KILL ioctl
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (13 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 14/25] rootns: Add ROOTNS_WAIT ioctl Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 1:19 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 16/25] fork: Support CLONE_INTO_ROOTNS in clone3() Jarkko Sakkinen
` (9 subsequent siblings)
24 siblings, 1 reply; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
Zygmunt Krynicki
Signaling every process inside a container from userspace via /proc is
racy against concurrent fork() calls.
Add the ROOTNS_KILL ioctl to require an ancestor active PID namespace,
walk the root namespace's PID namespace IDR under tasklist_lock, and
deliver a validated signal once to each thread group including in-flight
forks, aggregating per-process delivery results.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
include/uapi/linux/rootns.h | 13 ++++++++++
kernel/rootns.c | 52 +++++++++++++++++++++++++++++++++++++
2 files changed, 65 insertions(+)
diff --git a/include/uapi/linux/rootns.h b/include/uapi/linux/rootns.h
index 3fd215185398..acd91d895c63 100644
--- a/include/uapi/linux/rootns.h
+++ b/include/uapi/linux/rootns.h
@@ -67,4 +67,17 @@ struct rootns_wait_args {
*/
#define ROOTNS_WAIT _IOWR(ROOTNS_IOCTL_MAGIC, 0x02, struct rootns_wait_args)
+/**
+ * DOC: ROOTNS_KILL
+ *
+ * ``ioctl(rootnsfd, ROOTNS_KILL, sig)`` walks the target root namespace's PID
+ * namespace IDR under ``tasklist_lock`` and delivers ``sig`` (or ``0`` for a
+ * permission check) once to each member thread group.
+ *
+ * Returns ``0`` if at least one thread group was signaled, or ``-1`` with
+ * ``errno`` set to ``EXDEV`` if the caller's active PID namespace is not an
+ * ancestor or ``ESRCH`` if the ``rootns`` is not running or has no members.
+ */
+#define ROOTNS_KILL _IO(ROOTNS_IOCTL_MAGIC, 0x03)
+
#endif /* _UAPI_LINUX_ROOTNS_H */
diff --git a/kernel/rootns.c b/kernel/rootns.c
index cb74ddc8363c..5ae975604571 100644
--- a/kernel/rootns.c
+++ b/kernel/rootns.c
@@ -158,6 +158,53 @@ static long rootns_wait(struct rootns *rootns, void __user *uarg)
return ret;
}
+static int rootns_kill_members(struct rootns *rootns, int sig)
+{
+ struct pid_namespace *pid_ns = rootns->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 (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
+ return -EXDEV;
+ if (READ_ONCE(rootns->state) != ROOTNS_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 rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct rootns *rootns = file->private_data;
@@ -167,6 +214,10 @@ static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
return rootns_get_nsfd(rootns, arg);
case ROOTNS_WAIT:
return rootns_wait(rootns, (void __user *)arg);
+ case ROOTNS_KILL:
+ if (arg > INT_MAX || !valid_signal(arg))
+ return -EINVAL;
+ return rootns_kill_members(rootns, arg);
default:
return -ENOIOCTLCMD;
}
@@ -180,6 +231,7 @@ static long rootns_compat_ioctl(struct file *file, unsigned int cmd,
case ROOTNS_WAIT:
return rootns_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
case ROOTNS_GET_NSFD:
+ case ROOTNS_KILL:
return rootns_ioctl(file, cmd, arg);
default:
return -ENOIOCTLCMD;
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* Re: [RFC PATCH v5 15/25] rootns: Add ROOTNS_KILL ioctl
2026-11-21 0:08 ` [RFC PATCH v5 15/25] rootns: Add ROOTNS_KILL ioctl Jarkko Sakkinen
@ 2026-11-21 1:19 ` Jarkko Sakkinen
2026-11-21 11:24 ` Jarkko Sakkinen
0 siblings, 1 reply; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 1:19 UTC (permalink / raw)
To: linux-fsdevel
Cc: linux-api, linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Alexander Mikhalitsyn, Alexander Viro,
Andy Lutomirski, Christian Brauner, David Howells, Jan Kara,
Jonathan Corbet, Josef Bacik, Kees Cook, Neal Gompa, Paul Moore,
Serge Hallyn, Zygmunt Krynicki
On Sat, Nov 21, 2026 at 02:08:34AM +0200, Jarkko Sakkinen wrote:
> Signaling every process inside a container from userspace via /proc is
> racy against concurrent fork() calls.
>
> Add the ROOTNS_KILL ioctl to require an ancestor active PID namespace,
> walk the root namespace's PID namespace IDR under tasklist_lock, and
> deliver a validated signal once to each thread group including in-flight
> forks, aggregating per-process delivery results.
>
> Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
Will be gone i.e., can do also pidfd_send_signal(fd, signum, NULL, 0).
Br, Jarkko
^ permalink raw reply [flat|nested] 33+ messages in thread
* Re: [RFC PATCH v5 15/25] rootns: Add ROOTNS_KILL ioctl
2026-11-21 1:19 ` Jarkko Sakkinen
@ 2026-11-21 11:24 ` Jarkko Sakkinen
0 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 11:24 UTC (permalink / raw)
To: linux-fsdevel
Cc: linux-api, linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Alexander Mikhalitsyn, Alexander Viro,
Andy Lutomirski, Christian Brauner, David Howells, Jan Kara,
Jonathan Corbet, Josef Bacik, Kees Cook, Neal Gompa, Paul Moore,
Serge Hallyn, Zygmunt Krynicki
On Sat, Nov 21, 2026 at 03:19:38AM +0200, Jarkko Sakkinen wrote:
> On Sat, Nov 21, 2026 at 02:08:34AM +0200, Jarkko Sakkinen wrote:
> > Signaling every process inside a container from userspace via /proc is
> > racy against concurrent fork() calls.
> >
> > Add the ROOTNS_KILL ioctl to require an ancestor active PID namespace,
> > walk the root namespace's PID namespace IDR under tasklist_lock, and
> > deliver a validated signal once to each thread group including in-flight
> > forks, aggregating per-process delivery results.
> >
> > Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
>
> Will be gone i.e., can do also pidfd_send_signal(fd, signum, NULL, 0).
Wiring:
case PIDFD_SELF_THREAD_GROUP:
pid = get_task_pid(current, PIDTYPE_TGID);
type = PIDTYPE_TGID;
break;
default: {
CLASS(fd, f)(pidfd);
if (fd_empty(f))
return -EBADF;
if (is_rootns_file(fd_file(f)))
return rootns_send_signal(fd_file(f), sig, info, flags);
After this only ROONTS_GET_NSFD remains.
Br, Jarkko
^ permalink raw reply [flat|nested] 33+ messages in thread
* [RFC PATCH v5 16/25] fork: Support CLONE_INTO_ROOTNS in clone3()
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (14 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 15/25] rootns: Add ROOTNS_KILL ioctl Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 17/25] fs: Support FSCONFIG_SET_ROOTNS in fsconfig() Jarkko Sakkinen
` (8 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
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_ROOTNS and struct clone_args.rootns (CLONE_ARGS_SIZE_VER3)
to spawn a child process directly into a rootns whose root mount has
been installed. Transition the rootns from ROOTNS_INIT through
ROOTNS_FORKING to ROOTNS_RUNNING for the first process so it becomes
PID 1, serialize concurrent entrants on waitq until bootstrap resolves,
and admit subsequent callers into the running PID namespace until
teardown begins.
Derive child credentials from current, require CAP_SYS_ADMIN and
CAP_SYS_CHROOT in the target user namespace and an ancestor active PID
namespace, preserve caller umask, reset dumpability across user namespace
transitions, commit time namespace vvar mappings after copy_process()
succeeds, and look up the live mount namespace root. Restrict companion
flags to CLONE_VFORK, CLONE_PIDFD, CLONE_PIDFD_AUTOKILL, CLONE_AUTOREAP,
CLONE_CLEAR_SIGHAND, CLONE_INTO_CGROUP, and CLONE_NNP.
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/nsproxy.h | 4 +-
include/linux/rootns.h | 14 ++++
include/linux/sched/task.h | 8 +++
include/uapi/linux/sched.h | 5 ++
kernel/cred.c | 32 ++++++++-
kernel/fork.c | 94 ++++++++++++++++++++++---
kernel/nsproxy.c | 11 ++-
kernel/rootns.c | 140 +++++++++++++++++++++++++++++++++++++
9 files changed, 298 insertions(+), 14 deletions(-)
diff --git a/include/linux/cred.h b/include/linux/cred.h
index 49c26af37349..9849366fd44b 100644
--- a/include/linux/cred.h
+++ b/include/linux/cred.h
@@ -19,6 +19,7 @@
struct cred;
struct inode;
+struct rootns;
extern struct task_struct init_task;
@@ -152,7 +153,8 @@ struct cred {
extern void __put_cred(struct cred *);
extern void exit_creds(struct task_struct *);
-extern int copy_creds(struct task_struct *, u64);
+int copy_creds(struct task_struct *tsk, u64 clone_flags,
+ struct rootns *rootns);
extern const struct cred *get_task_cred(struct task_struct *);
extern struct cred *cred_alloc_blank(void);
extern struct cred *prepare_creds(void);
diff --git a/include/linux/nsproxy.h b/include/linux/nsproxy.h
index cacbbbe3f1ce..26b3b788cc90 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 rootns;
struct user_namespace;
/*
@@ -97,7 +98,8 @@ struct nsproxy *create_new_namespaces(u64 flags,
struct nsproxy *ns,
struct user_namespace *user_ns,
struct fs_struct *new_fs);
-int copy_namespaces(u64 flags, struct task_struct *tsk);
+int copy_namespaces(u64 flags, struct task_struct *tsk,
+ struct rootns *rootns);
void switch_cred_namespaces(const struct cred *old, const struct cred *new);
void exit_nsproxy_namespaces(struct task_struct *tsk);
void get_cred_namespaces(struct task_struct *tsk);
diff --git a/include/linux/rootns.h b/include/linux/rootns.h
index 6add4dd55550..68590b27e4ee 100644
--- a/include/linux/rootns.h
+++ b/include/linux/rootns.h
@@ -12,6 +12,7 @@
#include <linux/wait.h>
struct file;
+struct kernel_clone_args;
struct nsproxy;
struct pid;
struct pid_namespace;
@@ -47,6 +48,8 @@ bool is_rootns_file(struct file *file);
void copy_rootns(struct task_struct *tsk, struct pid *pid,
struct rootns *rootns);
void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk);
+int rootns_prepare_fork(struct kernel_clone_args *args);
+int rootns_finish_fork(struct kernel_clone_args *args, struct task_struct *p);
#else
static inline struct rootns *get_rootns(struct rootns *c)
{
@@ -71,6 +74,17 @@ static inline void exit_rootns(struct pid_namespace *pid_ns,
struct task_struct *tsk)
{
}
+
+static inline int rootns_prepare_fork(struct kernel_clone_args *args)
+{
+ return -EINVAL;
+}
+
+static inline int rootns_finish_fork(struct kernel_clone_args *args,
+ struct task_struct *p)
+{
+ return 0;
+}
#endif /* CONFIG_ROOTNS */
#endif /* _LINUX_ROOTNS_H */
diff --git a/include/linux/sched/task.h b/include/linux/sched/task.h
index 90ed5bc3c7af..e0c4e8ab02f1 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 rootns;
/* All the bits taken by the old clone syscall. */
#define CLONE_LEGACY_FLAGS 0xffffffffULL
@@ -39,11 +41,17 @@ struct kernel_clone_args {
/* Number of elements in *set_tid */
size_t set_tid_size;
int cgroup;
+ int rootns_fd;
int idle;
int (*fn)(void *);
void *fn_arg;
struct cgroup *cgrp;
struct css_set *cset;
+#ifdef CONFIG_ROOTNS
+ struct file *rootns_file;
+ struct rootns *rootns;
+ bool rootns_bootstrapping;
+#endif
unsigned int kill_seq;
};
diff --git a/include/uapi/linux/sched.h b/include/uapi/linux/sched.h
index 19ffeba89428..405cfc954ae1 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_ROOTNS (1ULL << 38) /* Clone into a specific root namespace. */
/*
* cloning flags intersect with CSIGNAL so can be used with unshare and clone3
@@ -94,6 +95,8 @@
* kernel's limit of nested PID namespaces.
* @cgroup: If CLONE_INTO_CGROUP is specified set this to
* a file descriptor for the cgroup.
+ * @rootns: If CLONE_INTO_ROOTNS is specified set this to
+ * a file descriptor for the root namespace.
*
* The structure is versioned by size and thus extensible.
* New struct members must go at the end of the struct and
@@ -111,12 +114,14 @@ struct clone_args {
__aligned_u64 set_tid;
__aligned_u64 set_tid_size;
__aligned_u64 cgroup;
+ __aligned_u64 rootns;
};
#endif
#define CLONE_ARGS_SIZE_VER0 64 /* sizeof first published struct */
#define CLONE_ARGS_SIZE_VER1 80 /* sizeof second published struct */
#define CLONE_ARGS_SIZE_VER2 88 /* sizeof third published struct */
+#define CLONE_ARGS_SIZE_VER3 96 /* sizeof fourth published struct */
/*
* Scheduling policies
diff --git a/kernel/cred.c b/kernel/cred.c
index d01df40a9a38..48a8852dab4a 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/rootns.h>
#include <linux/security.h>
#include <linux/binfmts.h>
#include <linux/cn_proc.h>
#include <linux/uidgid.h>
+#include <linux/user_namespace.h>
#if 0
#define kdebug(FMT, ...) \
@@ -251,6 +254,9 @@ struct cred *prepare_exec_creds(void)
return new;
}
+static bool cred_cap_issubset(const struct cred *set,
+ const struct cred *subset);
+
/*
* Copy credentials for the new process created by fork()
*
@@ -260,7 +266,8 @@ struct cred *prepare_exec_creds(void)
* The new process gets the current process's subjective credentials as its
* objective and subjective credentials
*/
-int copy_creds(struct task_struct *p, u64 clone_flags)
+int copy_creds(struct task_struct *p, u64 clone_flags,
+ struct rootns *rootns)
{
struct cred *new;
int ret;
@@ -287,6 +294,29 @@ int copy_creds(struct task_struct *p, u64 clone_flags)
if (!new)
return -ENOMEM;
+ if (rootns) {
+ const struct cred *old = current_cred();
+
+ if (!ns_capable(rootns->user_ns, CAP_SYS_ADMIN) ||
+ !ns_capable(rootns->user_ns, CAP_SYS_CHROOT)) {
+ ret = -EPERM;
+ goto error_put;
+ }
+ if (new->user_ns != rootns->user_ns) {
+ ret = install_user_ns_cred(new, rootns->user_ns);
+ if (ret < 0)
+ goto error_put;
+ }
+ if (!cred_cap_issubset(old, new) ||
+ old->user_ns != new->user_ns) {
+ struct task_exec_state *exec_state;
+
+ exec_state = rcu_dereference_protected(p->exec_state, true);
+ if (exec_state != &init_task_exec_state)
+ WRITE_ONCE(exec_state->dumpable, suid_dumpable);
+ }
+ }
+
if (clone_flags & CLONE_NEWUSER) {
ret = create_user_ns(new);
if (ret < 0)
diff --git a/kernel/fork.c b/kernel/fork.c
index 08fc28ad1eed..ac0497ff410c 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_ROOTNS)) == CLONE_VM) {
exec_state = rcu_dereference_protected(current->exec_state, true);
refcount_inc(&exec_state->count);
rcu_assign_pointer(tsk->exec_state, exec_state);
@@ -1632,8 +1633,30 @@ enum copy_fs_flags_t {
COPY_FS_IDLE = (1 << 1),
};
+#ifdef CONFIG_ROOTNS
+static inline struct rootns *clone_args_rootns(const struct kernel_clone_args *args)
+{
+ return args->rootns;
+}
+
+static inline bool clone_args_rootns_bootstrapping(const struct kernel_clone_args *args)
+{
+ return args->rootns_bootstrapping;
+}
+#else
+static inline struct rootns *clone_args_rootns(const struct kernel_clone_args *args)
+{
+ return NULL;
+}
+
+static inline bool clone_args_rootns_bootstrapping(const struct kernel_clone_args *args)
+{
+ return false;
+}
+#endif
+
static int copy_fs(u64 clone_flags, struct task_struct *tsk,
- enum copy_fs_flags_t flags)
+ enum copy_fs_flags_t flags, struct rootns *rootns)
{
struct fs_struct *fs;
@@ -1649,7 +1672,7 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk,
if (current->nsproxy->mnt_ns != &init_mnt_ns)
return -EINVAL;
fs = userspace_init_fs;
- } else if (flags & COPY_FS_IDLE) {
+ } else if (flags & COPY_FS_IDLE || rootns) {
fs = &init_fs;
} else {
fs = current->fs;
@@ -1671,6 +1694,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 (rootns) {
+ struct path root __free(path_put) = {};
+ int err;
+
+ err = mnt_ns_get_root(rootns->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;
}
@@ -2186,7 +2224,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, clone_args_rootns(args));
if (retval < 0)
goto bad_fork_free;
@@ -2317,7 +2355,8 @@ __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),
+ clone_args_rootns(args));
if (retval)
goto bad_fork_cleanup_semundo;
retval = copy_sighand(clone_flags, p);
@@ -2329,7 +2368,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, clone_args_rootns(args));
if (retval)
goto bad_fork_cleanup_mm;
retval = copy_io(clone_flags, p);
@@ -2510,6 +2549,12 @@ __latent_entropy struct task_struct *copy_process(
goto bad_fork_core_free;
}
+ if (unlikely(clone_args_rootns_bootstrapping(args) &&
+ !is_child_reaper(pid))) {
+ retval = -EBUSY;
+ goto bad_fork_core_free;
+ }
+
/* Let kill terminate clone/fork in the middle */
if (fatal_signal_pending(current)) {
retval = -EINTR;
@@ -2578,7 +2623,7 @@ __latent_entropy struct task_struct *copy_process(
}
attach_pid(p, PIDTYPE_PID);
if (thread_group_leader(p))
- copy_rootns(p, pid, NULL);
+ copy_rootns(p, pid, clone_args_rootns(args));
nr_threads++;
}
total_forks++;
@@ -2780,6 +2825,13 @@ pid_t kernel_clone(struct kernel_clone_args *args)
if (!valid_signal(args->exit_signal))
return -EINVAL;
+ if (unlikely(clone_flags & CLONE_INTO_ROOTNS)) {
+ int err = rootns_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
@@ -2801,6 +2853,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_ROOTNS)) {
+ int err = rootns_finish_fork(args, p);
+
+ if (err)
+ return err;
+ }
+
if (IS_ERR(p))
return PTR_ERR(p);
@@ -2958,7 +3017,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, rootns) !=
+ CLONE_ARGS_SIZE_VER3);
+ BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER3);
if (unlikely(usize > PAGE_SIZE))
return -E2BIG;
@@ -2988,6 +3049,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_ROOTNS) &&
+ (args.rootns > INT_MAX || usize < CLONE_ARGS_SIZE_VER3))
+ return -EINVAL;
+
*kargs = (struct kernel_clone_args){
.flags = args.flags,
.pidfd = u64_to_user_ptr(args.pidfd),
@@ -2999,6 +3064,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,
+ .rootns_fd = args.rootns,
};
if (args.set_tid &&
@@ -3039,13 +3105,19 @@ static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
return true;
}
+#define CLONE_INTO_ROOTNS_FLAGS \
+ (CLONE_INTO_ROOTNS | 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_ROOTNS))
return false;
/*
@@ -3063,6 +3135,10 @@ static bool clone3_args_valid(struct kernel_clone_args *kargs)
kargs->exit_signal)
return false;
+ if ((kargs->flags & CLONE_INTO_ROOTNS) &&
+ (kargs->flags & ~CLONE_INTO_ROOTNS_FLAGS))
+ return false;
+
if (!clone3_stack_valid(kargs))
return false;
diff --git a/kernel/nsproxy.c b/kernel/nsproxy.c
index 8a3c6d4e94e2..78a1e1fb2cfd 100644
--- a/kernel/nsproxy.c
+++ b/kernel/nsproxy.c
@@ -13,6 +13,7 @@
#include <linux/export.h>
#include <linux/nsproxy.h>
#include <linux/ns/ns_common_types.h>
+#include <linux/rootns.h>
#include <linux/init_task.h>
#include <linux/mnt_namespace.h>
#include <linux/utsname.h>
@@ -166,12 +167,18 @@ struct nsproxy *create_new_namespaces(u64 flags,
* called from clone. This now handles copy for nsproxy and all
* namespaces therein.
*/
-int copy_namespaces(u64 flags, struct task_struct *tsk)
+int copy_namespaces(u64 flags, struct task_struct *tsk,
+ struct rootns *rootns)
{
struct nsproxy *old_ns = tsk->nsproxy;
struct user_namespace *user_ns = task_cred_xxx(tsk, user_ns);
struct nsproxy *new_ns;
+ if (rootns) {
+ get_nsproxy(rootns->ns);
+ tsk->nsproxy = rootns->ns;
+ return 0;
+ }
if (likely(!(flags & (CLONE_NS_ALL & ~CLONE_NEWUSER)))) {
if ((flags & CLONE_VM) ||
likely(old_ns->time_ns_for_children == old_ns->time_ns)) {
@@ -192,7 +199,7 @@ int copy_namespaces(u64 flags, struct task_struct *tsk)
(CLONE_NEWIPC | CLONE_SYSVSEM))
return -EINVAL;
- new_ns = create_new_namespaces(flags, tsk->nsproxy, user_ns, tsk->fs);
+ new_ns = create_new_namespaces(flags, old_ns, user_ns, tsk->fs);
if (IS_ERR(new_ns))
return PTR_ERR(new_ns);
diff --git a/kernel/rootns.c b/kernel/rootns.c
index 5ae975604571..6fb49c20cc2d 100644
--- a/kernel/rootns.c
+++ b/kernel/rootns.c
@@ -36,6 +36,7 @@
#include <uapi/linux/wait.h>
#include <linux/file.h>
#include <linux/fs.h>
+#include <linux/fs_struct.h>
#include <linux/anon_inodes.h>
#include <linux/rootns.h>
#include <linux/sched/signal.h>
@@ -426,3 +427,142 @@ SYSCALL_DEFINE1(rootns, unsigned int, flags)
return fd;
}
+/**
+ * DOC: CLONE_INTO_ROOTNS
+ *
+ * Passing ``CLONE_INTO_ROOTNS`` in ``struct clone_args.flags`` (with
+ * ``size >= CLONE_ARGS_SIZE_VER3``) spawns the child process into the root
+ * namespace identified by ``struct clone_args.rootns``.
+ *
+ * Once ``"/"`` is mounted in the root namespace's mount namespace, the first
+ * caller transitions the ``rootns`` from ``ROOTNS_INIT`` through
+ * ``ROOTNS_FORKING`` to ``ROOTNS_RUNNING`` as PID 1 of its PID namespace
+ * while concurrent bootstrap callers wait killably. Subsequent callers join
+ * the running PID namespace until teardown begins.
+ *
+ * The caller must hold ``CAP_SYS_ADMIN`` and ``CAP_SYS_CHROOT`` in the target
+ * user namespace (and ``CAP_SYS_CHROOT`` in its current user namespace when
+ * chrooted) and run in an ancestor active PID namespace. The child inherits
+ * the caller's credentials and switches to the target user namespace.
+ *
+ * ``CLONE_INTO_ROOTNS`` may be combined with the following ``CLONE_*`` flags:
+ *
+ * - ``CLONE_VFORK``
+ * - ``CLONE_PIDFD``
+ * - ``CLONE_PIDFD_AUTOKILL``
+ * - ``CLONE_AUTOREAP``
+ * - ``CLONE_CLEAR_SIGHAND``
+ * - ``CLONE_INTO_CGROUP``
+ * - ``CLONE_NNP``
+ *
+ * Returns ``-EBADF`` if ``rootns`` is not an open file descriptor, ``-EINVAL``
+ * for unsupported flags, invalid argument size, or non-``rootns`` file
+ * descriptors, ``-ENOENT`` before ``"/"`` is installed, ``-EXDEV`` if the
+ * caller's active PID namespace is not an ancestor, ``-EPERM`` without
+ * required capabilities, ``-EBUSY`` if the PID
+ * namespace already has an external init process, and ``-ESRCH`` once teardown
+ * has started.
+ */
+int rootns_prepare_fork(struct kernel_clone_args *args)
+{
+ struct file *file __free(fput) = fget(args->rootns_fd);
+ struct path root __free(path_put) = {};
+ struct pid_namespace *pid_ns;
+ bool bootstrapping = false;
+ struct rootns *rootns;
+ int ret;
+
+ if (!file)
+ return -EBADF;
+ if (!is_rootns_file(file))
+ return -EINVAL;
+
+ rootns = file->private_data;
+ if (!ns_capable(rootns->user_ns, CAP_SYS_ADMIN) ||
+ !ns_capable(rootns->user_ns, CAP_SYS_CHROOT))
+ return -EPERM;
+ if (current_chrooted() && !ns_capable(current_user_ns(), CAP_SYS_CHROOT))
+ return -EPERM;
+
+ pid_ns = rootns->ns->pid_ns_for_children;
+ if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
+ return -EXDEV;
+
+ ret = mnt_ns_get_root(rootns->ns->mnt_ns, &root);
+ if (ret)
+ return ret;
+
+ for (;;) {
+ bool wait = false;
+
+ scoped_guard(spinlock, &rootns->lock) {
+ switch (rootns->state) {
+ case ROOTNS_INIT:
+ if (!(READ_ONCE(pid_ns->pid_allocated) & PIDNS_ADDING))
+ return -ESRCH;
+ if (READ_ONCE(pid_ns->child_reaper))
+ return -EBUSY;
+ WRITE_ONCE(rootns->state, ROOTNS_FORKING);
+ bootstrapping = true;
+ break;
+ case ROOTNS_FORKING:
+ wait = true;
+ break;
+ case ROOTNS_RUNNING:
+ if (!(READ_ONCE(pid_ns->pid_allocated) & PIDNS_ADDING))
+ return -ESRCH;
+ break;
+ case ROOTNS_DEAD:
+ return -ESRCH;
+ }
+ }
+ if (!wait)
+ break;
+
+ ret = wait_event_killable(rootns->waitq,
+ READ_ONCE(rootns->state) != ROOTNS_FORKING);
+ if (ret)
+ return ret;
+ }
+
+ args->rootns_file = no_free_ptr(file);
+ args->rootns = rootns;
+ args->rootns_bootstrapping = bootstrapping;
+ return 0;
+}
+
+int rootns_finish_fork(struct kernel_clone_args *args, struct task_struct *p)
+{
+ struct file *file __free(fput) = args->rootns_file;
+ struct rootns *rootns = args->rootns;
+ struct pid_namespace *pid_ns = rootns->ns->pid_ns_for_children;
+ int ret;
+
+ args->rootns_file = NULL;
+ args->rootns = NULL;
+ if (!IS_ERR(p)) {
+ if (args->rootns_bootstrapping)
+ wake_up_all(&rootns->waitq);
+ if (current->nsproxy->time_ns != rootns->ns->time_ns)
+ timens_commit(p, rootns->ns->time_ns);
+ return 0;
+ }
+
+ ret = PTR_ERR(p);
+ if (args->rootns_bootstrapping) {
+ scoped_guard(spinlock, &rootns->lock) {
+ if (rootns->state == ROOTNS_FORKING)
+ WRITE_ONCE(rootns->state, ROOTNS_INIT);
+ }
+ wake_up_all(&rootns->waitq);
+ if (ret == -EINVAL && !args->set_tid_size &&
+ (READ_ONCE(pid_ns->child_reaper) ||
+ (READ_ONCE(pid_ns->pid_allocated) & ~PIDNS_ADDING)))
+ ret = -EBUSY;
+ }
+ if ((ret == -ENOMEM || ret == -EBUSY) &&
+ !(READ_ONCE(pid_ns->pid_allocated) & PIDNS_ADDING))
+ return -ESRCH;
+
+ return ret;
+}
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 17/25] fs: Support FSCONFIG_SET_ROOTNS in fsconfig()
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (15 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 16/25] fork: Support CLONE_INTO_ROOTNS in clone3() Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 18/25] proc: Implement ->set_rootns() fs_context operation Jarkko Sakkinen
` (7 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
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 root namespace.
Add FSCONFIG_SET_ROOTNS and the ->set_rootns() fs_context operation so
callers holding CAP_SYS_ADMIN in the target rootns user namespace can
bind a newly opened fs_context to that rootns once before offering
parameters. Allow unprivileged callers to open FS_USERNS_MOUNT contexts
in FS_CONTEXT_AWAITING_NS without module autoloading until
FSCONFIG_SET_ROOTNS authorizes and initializes the context, and keep
devpts pty_reserve restricted to host mounts.
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/devpts/inode.c | 2 +
fs/filesystems.c | 15 ++++
fs/fs_context.c | 21 ++++--
fs/fsopen.c | 140 ++++++++++++++++++++++++++++++++++---
fs/internal.h | 6 ++
fs/namespace.c | 19 ++++-
include/linux/fs_context.h | 6 ++
include/uapi/linux/mount.h | 1 +
8 files changed, 196 insertions(+), 14 deletions(-)
diff --git a/fs/devpts/inode.c b/fs/devpts/inode.c
index bd1e8eb26edb..db5a5c7a07db 100644
--- a/fs/devpts/inode.c
+++ b/fs/devpts/inode.c
@@ -434,6 +434,8 @@ static int devpts_init_fs_context(struct fs_context *fc)
fsi->mount_opts.max = NR_UNIX98_PTY_MAX;
if (fc->purpose == FS_CONTEXT_FOR_MOUNT &&
+ !fc->rootns_bound &&
+ fc->user_ns == &init_user_ns &&
current->nsproxy->mnt_ns == init_task.nsproxy->mnt_ns)
fsi->mount_opts.reserve = true;
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..e0d65f6018a7 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/nsproxy.h>
+#include <linux/rootns.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,95 @@ static inline const char *fetch_message_locked(struct fc_log *log, size_t len,
return p;
}
+/**
+ * DOC: FSCONFIG_SET_ROOTNS
+ *
+ * ``fsconfig(fsfd, FSCONFIG_SET_ROOTNS, NULL, NULL, rootnsfd)`` binds a newly
+ * opened filesystem context to ``rootnsfd`` once before any parameters are
+ * supplied (subsequent calls fail with ``-EBUSY``).
+ *
+ * The caller must hold ``CAP_SYS_ADMIN`` in the target ``rootns`` user
+ * namespace, allowing unprivileged callers to configure ``FS_USERNS_MOUNT``
+ * filesystems without entering the user namespace first.
+ *
+ * The filesystem must support ``FS_USERNS_MOUNT`` or
+ * ``FS_USERNS_DELEGATABLE`` (failing with ``-EOPNOTSUPP`` otherwise). The
+ * context is initialized against the ``rootns`` network and user namespaces,
+ * and ``proc`` and ``mqueue`` contexts bind to the target ``rootns`` PID and
+ * IPC namespaces.
+ */
+static int fsconfig_set_rootns(struct fs_context *fc, struct fs_parameter *param)
+{
+ struct user_namespace *user_ns;
+ struct rootns *c;
+ int ret;
+
+ if (!is_rootns_file(param->file))
+ return -EINVAL;
+
+ c = param->file->private_data;
+ user_ns = c->user_ns;
+ if (!ns_capable(user_ns, CAP_SYS_ADMIN))
+ return -EPERM;
+ if (!(fc->fs_type->fs_flags &
+ (FS_USERNS_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);
+
+ if (fc->log.prefix && strcmp(fc->fs_type->name, fc->log.prefix)) {
+ struct file_system_type *orig;
+
+ orig = get_fs_type_noload(fc->log.prefix);
+ if (!orig) {
+ fc->phase = FS_CONTEXT_FAILED;
+ return -ENODEV;
+ }
+ put_filesystem(fc->fs_type);
+ fc->fs_type = orig;
+ }
+
+ put_net(fc->net_ns);
+ fc->net_ns = get_net(c->ns->net_ns);
+ put_user_ns(fc->user_ns);
+ fc->user_ns = get_user_ns(user_ns);
+
+ fc->rootns_bound = true;
+ fc->rootns_mnt_id = c->ns->mnt_ns->ns.ns_id;
+
+ ret = fc->fs_type->init_fs_context(fc);
+ if (ret < 0) {
+ fc->rootns_bound = false;
+ fc->phase = FS_CONTEXT_FAILED;
+ return ret;
+ }
+ fc->need_free = true;
+
+ if (fc->ops->set_rootns) {
+ ret = fc->ops->set_rootns(fc, c);
+ if (ret < 0) {
+ fc->rootns_bound = false;
+ fc->phase = FS_CONTEXT_FAILED;
+ return ret;
+ }
+ }
+ if (fc->user_ns != user_ns) {
+ fc->rootns_bound = false;
+ fc->phase = FS_CONTEXT_FAILED;
+ return -EOPNOTSUPP;
+ }
+ 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 +217,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_ROOTNS))
return -EPERM;
if (flags & ~FSOPEN_CLOEXEC)
@@ -137,17 +233,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;
+
+ if (!priv && !(fs_type->fs_flags & FS_USERNS_MOUNT)) {
+ put_filesystem(fs_type);
+ return -EPERM;
+ }
- fc = fs_context_for_mount(fs_type, 0);
+ 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 +324,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 +394,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_ROOTNS)
+ return -EPERM;
switch (cmd) {
case FSCONFIG_CMD_CREATE:
return vfs_cmd_create(fc, false);
@@ -298,9 +403,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_ROOTNS:
+ if (fc->phase != FS_CONTEXT_AWAITING_NS &&
+ fc->phase != FS_CONTEXT_CREATE_NS)
+ return -EBUSY;
+ return fsconfig_set_rootns(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 +503,10 @@ SYSCALL_DEFINE5(fsconfig,
if (!_key || _value || aux < 0)
return -EINVAL;
break;
+ case FSCONFIG_SET_ROOTNS:
+ if (_key || _value || aux < 0)
+ return -EINVAL;
+ break;
case FSCONFIG_CMD_CREATE:
case FSCONFIG_CMD_CREATE_EXCL:
case FSCONFIG_CMD_RECONFIGURE:
@@ -457,6 +574,12 @@ SYSCALL_DEFINE5(fsconfig,
goto out_key;
param.dirfd = aux;
break;
+ case FSCONFIG_SET_ROOTNS:
+ ret = -EBADF;
+ param.file = fget(aux);
+ if (!param.file)
+ goto out_key;
+ break;
default:
break;
}
@@ -482,6 +605,7 @@ SYSCALL_DEFINE5(fsconfig,
putname(param.name);
break;
case FSCONFIG_SET_FD:
+ case FSCONFIG_SET_ROOTNS:
if (param.file)
fput(param.file);
break;
diff --git a/fs/internal.h b/fs/internal.h
index 3f2fbac40f8e..d6815bf6ea9b 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 1e7d776c0966..162ecb52f6eb 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -4699,16 +4699,19 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
struct vfsmount *new_mnt;
struct mount *mnt;
unsigned int mnt_flags = 0;
+ bool priv;
long ret;
if ((flags & ~(FSMOUNT_CLOEXEC | FSMOUNT_NAMESPACE)) != 0)
return -EINVAL;
+ priv = may_mount();
if ((flags & FSMOUNT_NAMESPACE) &&
!ns_capable(current_user_ns(), CAP_SYS_ADMIN))
return -EPERM;
- if (!(flags & FSMOUNT_NAMESPACE) && !may_mount())
+ if (!(flags & FSMOUNT_NAMESPACE) && !IS_ENABLED(CONFIG_ROOTNS) &&
+ !priv)
return -EPERM;
if (attr_flags & ~FSMOUNT_VALID_FLAGS)
@@ -4743,6 +4746,15 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
if (ret)
return ret;
+ if (fc->rootns_bound) {
+ if (flags & FSMOUNT_NAMESPACE)
+ return -EINVAL;
+ if (!ns_capable(fc->user_ns, CAP_SYS_ADMIN))
+ return -EPERM;
+ } else if (!(flags & FSMOUNT_NAMESPACE) && !priv) {
+ return -EPERM;
+ }
+
/* There must be a valid superblock or we can't mount it */
ret = -EINVAL;
if (!fc->root)
@@ -4784,9 +4796,12 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
return FD_ADD((flags & FSMOUNT_CLOEXEC) ? O_CLOEXEC : 0,
open_new_namespace(&new_path, MOUNT_COPY_NEW));
- ns = alloc_mnt_ns(current->nsproxy->mnt_ns->user_ns, true);
+ ns = alloc_mnt_ns(fc->rootns_bound ? fc->user_ns :
+ current->nsproxy->mnt_ns->user_ns, true);
if (IS_ERR(ns))
return PTR_ERR(ns);
+ if (fc->rootns_bound)
+ ns->seq_origin = fc->rootns_mnt_id;
mnt = real_mount(new_path.mnt);
ns->root = mnt;
ns->nr_mounts = 1;
diff --git a/include/linux/fs_context.h b/include/linux/fs_context.h
index d1727dffecc5..42648bec5cfa 100644
--- a/include/linux/fs_context.h
+++ b/include/linux/fs_context.h
@@ -21,6 +21,7 @@ struct file_system_type;
struct mnt_namespace;
struct net;
struct pid_namespace;
+struct rootns;
struct super_block;
struct user_namespace;
struct vfsmount;
@@ -36,6 +37,8 @@ enum fs_context_purpose {
* Userspace usage phase for fsopen/fspick.
*/
enum fs_context_phase {
+ FS_CONTEXT_AWAITING_NS, /* Unprivileged context awaiting target ns */
+ FS_CONTEXT_CREATE_NS, /* Set namespaces for sb creation */
FS_CONTEXT_CREATE_PARAMS, /* Loading params for sb creation */
FS_CONTEXT_CREATING, /* A superblock is being created */
FS_CONTEXT_AWAITING_MOUNT, /* Superblock created, awaiting fsmount() */
@@ -101,6 +104,7 @@ struct fs_context {
const char *source; /* The source name (eg. dev path) */
void *security; /* LSM options */
void *s_fs_info; /* Proposed s_fs_info */
+ u64 rootns_mnt_id; /* Target rootns mnt_ns ID */
unsigned int sb_flags; /* Proposed superblock flags (SB_*) */
unsigned int sb_flags_mask; /* Superblock flags that were changed */
unsigned int s_iflags; /* OR'd with sb->s_iflags */
@@ -110,6 +114,7 @@ struct fs_context {
bool global:1; /* Goes into &init_user_ns */
bool oldapi:1; /* Coming from mount(2) */
bool exclusive:1; /* create new superblock, reject existing one */
+ bool rootns_bound:1; /* Bound via FSCONFIG_SET_ROOTNS */
};
struct fs_context_operations {
@@ -117,6 +122,7 @@ struct fs_context_operations {
int (*dup)(struct fs_context *fc, struct fs_context *src_fc);
int (*parse_param)(struct fs_context *fc, struct fs_parameter *param);
int (*parse_monolithic)(struct fs_context *fc, void *data);
+ int (*set_rootns)(struct fs_context *fc, struct rootns *rootns);
int (*get_tree)(struct fs_context *fc);
int (*reconfigure)(struct fs_context *fc);
};
diff --git a/include/uapi/linux/mount.h b/include/uapi/linux/mount.h
index cb4f7175db02..5d4d93edb9df 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_ROOTNS = 9, /* Set a rootns, supplied by fd */
};
/*
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 18/25] proc: Implement ->set_rootns() fs_context operation
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (16 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 17/25] fs: Support FSCONFIG_SET_ROOTNS in fsconfig() Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 19/25] ipc/mqueue: " Jarkko Sakkinen
` (6 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
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_ROOTNS and leaving the context
attached to the caller's PID namespace.
Wire up proc_set_rootns() to verify that the target root namespace's PID
namespace is a descendant of the caller's active PID namespace and
rebind ctx->pid_ns and fc->user_ns accordingly.
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 | 22 ++++++++++++++++++++++
1 file changed, 22 insertions(+)
diff --git a/fs/proc/root.c b/fs/proc/root.c
index 7fbbe92bf73a..8d2b9bbfa1c1 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/nsproxy.h>
+#include <linux/rootns.h>
#include <linux/user_namespace.h>
#include <linux/fs_context.h>
#include <linux/mount.h>
@@ -206,6 +208,10 @@ static int proc_parse_param(struct fs_context *fc, struct fs_parameter *param)
errorfc(fc, "cannot reconfigure pidns for existing procfs");
return -EBUSY;
}
+ if (fc->rootns_bound) {
+ errorfc(fc, "cannot override pidns on rootns-bound procfs");
+ return -EBUSY;
+ }
err = proc_parse_pidns_param(fc, param, &result);
if (err)
return err;
@@ -323,6 +329,21 @@ static int proc_get_tree(struct fs_context *fc)
return get_tree_nodev(fc, proc_fill_super);
}
+static int proc_set_rootns(struct fs_context *fc, struct rootns *rootns)
+{
+ struct proc_fs_context *ctx = fc->fs_private;
+ struct pid_namespace *target = rootns->ns->pid_ns_for_children;
+
+ if (!pidns_is_ancestor(target, task_active_pid_ns(current)))
+ return invalfc(fc, "cannot set pidns to non-descendant pidns");
+
+ put_pid_ns(ctx->pid_ns);
+ ctx->pid_ns = get_pid_ns(target);
+ put_user_ns(fc->user_ns);
+ fc->user_ns = get_user_ns(ctx->pid_ns->user_ns);
+ return 0;
+}
+
static void proc_fs_context_free(struct fs_context *fc)
{
struct proc_fs_context *ctx = fc->fs_private;
@@ -334,6 +355,7 @@ static void proc_fs_context_free(struct fs_context *fc)
static const struct fs_context_operations proc_fs_context_ops = {
.free = proc_fs_context_free,
.parse_param = proc_parse_param,
+ .set_rootns = proc_set_rootns,
.get_tree = proc_get_tree,
.reconfigure = proc_reconfigure,
};
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 19/25] ipc/mqueue: Implement ->set_rootns() fs_context operation
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (17 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 18/25] proc: Implement ->set_rootns() fs_context operation Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 20/25] security: Add rootns LSM hooks Jarkko Sakkinen
` (5 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
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_ROOTNS and leaving the context bound to the
caller's IPC namespace.
Wire up mqueue_set_rootns() to switch ctx->ipc_ns to the target root
namespace's IPC namespace and update fc->user_ns to match.
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 | 13 +++++++++++++
1 file changed, 13 insertions(+)
diff --git a/ipc/mqueue.c b/ipc/mqueue.c
index 322c3dd98c44..f94e9b566bd0 100644
--- a/ipc/mqueue.c
+++ b/ipc/mqueue.c
@@ -32,6 +32,7 @@
#include <linux/mutex.h>
#include <linux/nsproxy.h>
#include <linux/pid.h>
+#include <linux/rootns.h>
#include <linux/ipc_namespace.h>
#include <linux/user_namespace.h>
#include <linux/slab.h>
@@ -400,6 +401,17 @@ static struct inode *mqueue_get_inode(struct super_block *sb,
return ERR_PTR(ret);
}
+static int mqueue_set_rootns(struct fs_context *fc, struct rootns *rootns)
+{
+ struct mqueue_fs_context *ctx = fc->fs_private;
+
+ put_ipc_ns(ctx->ipc_ns);
+ ctx->ipc_ns = get_ipc_ns(rootns->ns->ipc_ns);
+ put_user_ns(fc->user_ns);
+ fc->user_ns = get_user_ns(ctx->ipc_ns->user_ns);
+ return 0;
+}
+
static int mqueue_fill_super(struct super_block *sb, struct fs_context *fc)
{
struct inode *inode;
@@ -1613,6 +1625,7 @@ static const struct super_operations mqueue_super_ops = {
static const struct fs_context_operations mqueue_fs_context_ops = {
.free = mqueue_fs_context_free,
+ .set_rootns = mqueue_set_rootns,
.get_tree = mqueue_get_tree,
};
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 20/25] security: Add rootns LSM hooks
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (18 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 19/25] ipc/mqueue: " Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 11:47 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 21/25] bpf: Register " Jarkko Sakkinen
` (4 subsequent siblings)
24 siblings, 1 reply; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
Zygmunt Krynicki
Security modules need visibility into root namespace creation, teardown,
process entry, and container-wide signal delivery so policies can attach
per-rootns security state and mediate operations on rootns file
descriptors.
Add lbs_rootns and rootns->security blob management alongside
security_rootns_alloc(), security_rootns_free(), security_rootns_clone(),
and security_rootns_kill().
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/lsm_hook_defs.h | 7 +++
include/linux/lsm_hooks.h | 3 ++
include/linux/rootns.h | 3 ++
include/linux/security.h | 30 ++++++++++++
kernel/rootns.c | 44 +++++++++++++-----
security/lsm_init.c | 6 +++
security/security.c | 86 +++++++++++++++++++++++++++++++++++
7 files changed, 167 insertions(+), 12 deletions(-)
diff --git a/include/linux/lsm_hook_defs.h b/include/linux/lsm_hook_defs.h
index 87d9d06710cb..2cb90ddedc14 100644
--- a/include/linux/lsm_hook_defs.h
+++ b/include/linux/lsm_hook_defs.h
@@ -480,3 +480,10 @@ LSM_HOOK(int, 0, bdev_alloc_security, struct block_device *bdev)
LSM_HOOK(void, LSM_RET_VOID, bdev_free_security, struct block_device *bdev)
LSM_HOOK(int, 0, bdev_setintegrity, struct block_device *bdev,
enum lsm_integrity_type type, const void *value, size_t size)
+
+#ifdef CONFIG_ROOTNS
+LSM_HOOK(int, 0, rootns_alloc, struct rootns *rootns, unsigned int flags)
+LSM_HOOK(void, LSM_RET_VOID, rootns_free, struct rootns *rootns)
+LSM_HOOK(int, 0, rootns_clone, struct rootns *rootns)
+LSM_HOOK(int, 0, rootns_kill, struct rootns *rootns, int sig)
+#endif /* CONFIG_ROOTNS */
diff --git a/include/linux/lsm_hooks.h b/include/linux/lsm_hooks.h
index 13621e9e233e..217a59d428b1 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_ROOTNS
+ unsigned int lbs_rootns;
+#endif
};
/*
diff --git a/include/linux/rootns.h b/include/linux/rootns.h
index 68590b27e4ee..1301bc6961f1 100644
--- a/include/linux/rootns.h
+++ b/include/linux/rootns.h
@@ -32,6 +32,9 @@ enum rootns_state {
struct rootns {
refcount_t usage;
int exit_code; /* The exit code of 'init' */
+#ifdef CONFIG_SECURITY
+ void *security; /* LSM security blob */
+#endif
struct user_namespace *user_ns; /* Owning user namespace */
struct nsproxy *ns; /* This rootns's namespaces */
struct pid *init_pid; /* The 'init' task's TGID (pid ref) */
diff --git a/include/linux/security.h b/include/linux/security.h
index 40831fab5470..995292f1c92e 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 rootns;
enum lsm_event {
LSM_POLICY_CHANGE,
@@ -2469,4 +2470,33 @@ static inline void security_initramfs_populated(void)
}
#endif /* CONFIG_SECURITY */
+#ifdef CONFIG_ROOTNS
+#ifdef CONFIG_SECURITY
+int security_rootns_alloc(struct rootns *rootns, unsigned int flags);
+void security_rootns_free(struct rootns *rootns);
+int security_rootns_clone(struct rootns *rootns);
+int security_rootns_kill(struct rootns *rootns, int sig);
+#else
+static inline int security_rootns_alloc(struct rootns *rootns,
+ unsigned int flags)
+{
+ return 0;
+}
+
+static inline void security_rootns_free(struct rootns *rootns)
+{
+}
+
+static inline int security_rootns_clone(struct rootns *rootns)
+{
+ return 0;
+}
+
+static inline int security_rootns_kill(struct rootns *rootns, int sig)
+{
+ return 0;
+}
+#endif /* CONFIG_SECURITY */
+#endif /* CONFIG_ROOTNS */
+
#endif /* ! __LINUX_SECURITY_H */
diff --git a/kernel/rootns.c b/kernel/rootns.c
index 6fb49c20cc2d..bf3174023d97 100644
--- a/kernel/rootns.c
+++ b/kernel/rootns.c
@@ -54,6 +54,7 @@
#include <linux/user_namespace.h>
#include <linux/compat.h>
#include <linux/idr.h>
+#include <linux/security.h>
#include <uapi/linux/rootns.h>
/*
@@ -65,14 +66,8 @@ struct rootns *get_rootns(struct rootns *c)
return c;
}
-/*
- * Drop a reference on a rootns and clear it if it is no longer in use.
- */
-void put_rootns(struct rootns *c)
+static void free_rootns(struct rootns *c)
{
- if (!c || !refcount_dec_and_test(&c->usage))
- return;
-
if (c->ns)
put_nsproxy(c->ns);
if (c->init_pid)
@@ -84,6 +79,18 @@ void put_rootns(struct rootns *c)
kfree(c);
}
+/*
+ * Drop a reference on a rootns and clear it if it is no longer in use.
+ */
+void put_rootns(struct rootns *c)
+{
+ if (!c || !refcount_dec_and_test(&c->usage))
+ return;
+
+ security_rootns_free(c);
+ free_rootns(c);
+}
+
/*
* Allow the user to poll for the rootns dying.
*/
@@ -167,6 +174,7 @@ static int rootns_kill_members(struct rootns *rootns, int sig)
bool any_perm = false;
int other_err = 0;
struct pid *pid;
+ int ret;
int nr;
if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
@@ -174,6 +182,10 @@ static int rootns_kill_members(struct rootns *rootns, int sig)
if (READ_ONCE(rootns->state) != ROOTNS_RUNNING)
return -ESRCH;
+ ret = security_rootns_kill(rootns, sig);
+ if (ret)
+ return ret;
+
scoped_guard(rcu) {
read_lock(&tasklist_lock);
idr_for_each_entry(&pid_ns->idr, pid, nr) {
@@ -368,31 +380,35 @@ static struct rootns *create_rootns(unsigned int flags)
user_ns = create_rootns_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->nsproxy, user_ns,
NULL);
if (IS_ERR(ns)) {
ret = PTR_ERR(ns);
- goto err_put;
+ goto err_free;
}
timens_activate_nsproxy(ns);
c->ns = ns;
nsproxy_ns_active_get(ns);
+ ret = security_rootns_alloc(c, flags);
+ if (ret < 0)
+ goto err_free;
+
return c;
-err_put:
- put_rootns(c);
+err_free:
+ free_rootns(c);
return ERR_PTR(ret);
}
@@ -488,6 +504,10 @@ int rootns_prepare_fork(struct kernel_clone_args *args)
if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
return -EXDEV;
+ ret = security_rootns_clone(rootns);
+ if (ret)
+ return ret;
+
ret = mnt_ns_get_root(rootns->ns->mnt_ns, &root);
if (ret)
return ret;
diff --git a/security/lsm_init.c b/security/lsm_init.c
index 8d5ecea99c46..56b515b20812 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_ROOTNS
+ lsm_blob_size_update(&blobs->lbs_rootns, &blob_sizes.lbs_rootns);
+#endif
}
/**
@@ -460,6 +463,9 @@ int __init security_init(void)
lsm_pr("blob(bpf_map) size %d\n", blob_sizes.lbs_bpf_map);
lsm_pr("blob(bpf_prog) size %d\n", blob_sizes.lbs_bpf_prog);
lsm_pr("blob(bpf_token) size %d\n", blob_sizes.lbs_bpf_token);
+#ifdef CONFIG_ROOTNS
+ lsm_pr("blob(rootns) size %d\n", blob_sizes.lbs_rootns);
+#endif
}
if (blob_sizes.lbs_file)
diff --git a/security/security.c b/security/security.c
index 4727b8347fc4..919d4bb63701 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/rootns.h>
#include <net/flow.h>
#include <net/sock.h>
@@ -395,6 +396,22 @@ static int lsm_ns_alloc(struct ns_common *ns)
return lsm_blob_alloc(&ns->ns_security, blob_sizes.lbs_ns, GFP_KERNEL);
}
+#ifdef CONFIG_ROOTNS
+/**
+ * lsm_rootns_alloc - allocate a composite rootns blob
+ * @rootns: the rootns that needs a blob
+ *
+ * Allocate the rootns blob for all the modules
+ *
+ * Return: Returns 0, or -ENOMEM if memory can't be allocated.
+ */
+static int lsm_rootns_alloc(struct rootns *rootns)
+{
+ return lsm_blob_alloc(&rootns->security, blob_sizes.lbs_rootns,
+ GFP_KERNEL);
+}
+#endif /* CONFIG_ROOTNS */
+
/**
* lsm_fill_user_ctx - Fill a user space lsm_ctx structure
* @uctx: a userspace LSM context to be filled
@@ -5795,3 +5812,72 @@ void security_initramfs_populated(void)
{
call_void_hook(initramfs_populated);
}
+
+#ifdef CONFIG_ROOTNS
+/**
+ * security_rootns_alloc() - Check creation of a new rootns and init LSM blob
+ * @rootns: the new rootns
+ * @flags: creation flags passed to rootns()
+ *
+ * Check whether a new rootns may be created and initialize its LSM security
+ * blob.
+ *
+ * Return: Returns 0 on success, negative error code on failure.
+ */
+int security_rootns_alloc(struct rootns *rootns, unsigned int flags)
+{
+ int rc;
+
+ rc = lsm_rootns_alloc(rootns);
+ if (unlikely(rc))
+ return rc;
+
+ rc = call_int_hook(rootns_alloc, rootns, flags);
+ if (unlikely(rc))
+ security_rootns_free(rootns);
+
+ return rc;
+}
+
+/**
+ * security_rootns_free() - Release LSM security data from a rootns
+ * @rootns: the rootns being freed
+ *
+ * Release security data attached to @rootns before the structure is freed.
+ */
+void security_rootns_free(struct rootns *rootns)
+{
+ call_void_hook(rootns_free, rootns);
+ kfree(rootns->security);
+ rootns->security = NULL;
+}
+
+/**
+ * security_rootns_clone() - Check permission to spawn a task into a rootns
+ * @rootns: the target rootns
+ *
+ * Check permission before spawning a child process into @rootns via
+ * clone3(CLONE_INTO_ROOTNS).
+ *
+ * Return: Returns 0 if permission is granted, negative error code on failure.
+ */
+int security_rootns_clone(struct rootns *rootns)
+{
+ return call_int_hook(rootns_clone, rootns);
+}
+
+/**
+ * security_rootns_kill() - Check permission to signal a rootns
+ * @rootns: the target rootns
+ * @sig: signal number to deliver (or 0 for permission check)
+ *
+ * Check permission before broadcasting @sig to member thread groups in @rootns
+ * via ioctl(ROOTNS_KILL).
+ *
+ * Return: Returns 0 if permission is granted, negative error code on failure.
+ */
+int security_rootns_kill(struct rootns *rootns, int sig)
+{
+ return call_int_hook(rootns_kill, rootns, sig);
+}
+#endif /* CONFIG_ROOTNS */
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* Re: [RFC PATCH v5 20/25] security: Add rootns LSM hooks
2026-11-21 0:08 ` [RFC PATCH v5 20/25] security: Add rootns LSM hooks Jarkko Sakkinen
@ 2026-11-21 11:47 ` Jarkko Sakkinen
0 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 11:47 UTC (permalink / raw)
To: linux-fsdevel
Cc: linux-api, linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Alexander Mikhalitsyn, Alexander Viro,
Andy Lutomirski, Christian Brauner, David Howells, Jan Kara,
Jonathan Corbet, Josef Bacik, Kees Cook, Neal Gompa, Paul Moore,
Serge Hallyn, Zygmunt Krynicki
On Sat, Nov 21, 2026 at 02:08:39AM +0200, Jarkko Sakkinen wrote:
> Security modules need visibility into root namespace creation, teardown,
> process entry, and container-wide signal delivery so policies can attach
> per-rootns security state and mediate operations on rootns file
> descriptors.
>
> Add lbs_rootns and rootns->security blob management alongside
> security_rootns_alloc(), security_rootns_free(), security_rootns_clone(),
> and security_rootns_kill().
>
> 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/lsm_hook_defs.h | 7 +++
> include/linux/lsm_hooks.h | 3 ++
> include/linux/rootns.h | 3 ++
> include/linux/security.h | 30 ++++++++++++
> kernel/rootns.c | 44 +++++++++++++-----
> security/lsm_init.c | 6 +++
> security/security.c | 86 +++++++++++++++++++++++++++++++++++
> 7 files changed, 167 insertions(+), 12 deletions(-)
>
> diff --git a/include/linux/lsm_hook_defs.h b/include/linux/lsm_hook_defs.h
> index 87d9d06710cb..2cb90ddedc14 100644
> --- a/include/linux/lsm_hook_defs.h
> +++ b/include/linux/lsm_hook_defs.h
> @@ -480,3 +480,10 @@ LSM_HOOK(int, 0, bdev_alloc_security, struct block_device *bdev)
> LSM_HOOK(void, LSM_RET_VOID, bdev_free_security, struct block_device *bdev)
> LSM_HOOK(int, 0, bdev_setintegrity, struct block_device *bdev,
> enum lsm_integrity_type type, const void *value, size_t size)
> +
> +#ifdef CONFIG_ROOTNS
> +LSM_HOOK(int, 0, rootns_alloc, struct rootns *rootns, unsigned int flags)
> +LSM_HOOK(void, LSM_RET_VOID, rootns_free, struct rootns *rootns)
> +LSM_HOOK(int, 0, rootns_clone, struct rootns *rootns)
> +LSM_HOOK(int, 0, rootns_kill, struct rootns *rootns, int sig)
Rootns objects have a security model:
1. No embryonic state by design. Especially staircase initialization
contributes to this property.
2. Unshare logic is inverted. Right now ROOTNS_SHARE ioctl does not
exist right now but it is (obviously) doable.
3. Dead obvious and transparent LSM hooks. Really hard to get them
wrong.
4. We already know by experience that opaque fd-bound objects with
two-phase state machine (build, live) works. It's what make this
secure and policy-free implementatiion.
The choices how to do things with closures used in SGX driver are
translatable and they are also pretty well reviewed choices, given all
those years... I would put some weight on this too.
Br, Jarkko
^ permalink raw reply [flat|nested] 33+ messages in thread
* [RFC PATCH v5 21/25] bpf: Register rootns LSM hooks
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (19 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 20/25] security: Add rootns LSM hooks Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 22/25] arch: Wire up rootns() system call Jarkko Sakkinen
` (3 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
Zygmunt Krynicki
BPF LSM programs need sleepable and untrusted hook classifications for
the new root namespace LSM hooks in order to attach policies to root
namespace allocation, cloning, signaling, and release.
Register bpf_lsm_rootns_alloc, bpf_lsm_rootns_clone, and
bpf_lsm_rootns_kill in sleepable_lsm_hooks, and bpf_lsm_rootns_alloc
and bpf_lsm_rootns_free in untrusted_lsm_hooks under CONFIG_ROOTNS.
Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
kernel/bpf/bpf_lsm.c | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/kernel/bpf/bpf_lsm.c b/kernel/bpf/bpf_lsm.c
index 468e63dbd922..bbcf1433fdc2 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/rootns.h>
/* For every LSM hook that allows attachment of BPF programs, declare a nop
* function where a BPF program can be attached. Notably, we qualify each with
@@ -404,6 +405,11 @@ BTF_ID(func, bpf_lsm_task_setscheduler)
BTF_ID(func, bpf_lsm_userns_create)
BTF_ID(func, bpf_lsm_bdev_alloc_security)
BTF_ID(func, bpf_lsm_bdev_setintegrity)
+#ifdef CONFIG_ROOTNS
+BTF_ID(func, bpf_lsm_rootns_alloc)
+BTF_ID(func, bpf_lsm_rootns_clone)
+BTF_ID(func, bpf_lsm_rootns_kill)
+#endif /* CONFIG_ROOTNS */
BTF_SET_END(sleepable_lsm_hooks)
BTF_SET_START(untrusted_lsm_hooks)
@@ -420,6 +426,10 @@ BTF_ID(func, bpf_lsm_sk_free_security)
BTF_ID(func, bpf_lsm_task_free)
BTF_ID(func, bpf_lsm_bdev_alloc_security)
BTF_ID(func, bpf_lsm_bdev_free_security)
+#ifdef CONFIG_ROOTNS
+BTF_ID(func, bpf_lsm_rootns_alloc)
+BTF_ID(func, bpf_lsm_rootns_free)
+#endif /* CONFIG_ROOTNS */
BTF_SET_END(untrusted_lsm_hooks)
bool bpf_lsm_is_sleepable_hook(u32 btf_id)
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 22/25] arch: Wire up rootns() system call
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (20 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 21/25] bpf: Register " Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 23/25] docs: Document root namespace uAPI Jarkko Sakkinen
` (2 subsequent siblings)
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
Zygmunt Krynicki
Now that the core root namespace lifecycle and VFS mount-tree
installation are in place, expose rootns() (474, 584 on Alpha) across
all architecture system call tables and asm-generic unistd.h.
Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
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 +
18 files changed, 22 insertions(+), 1 deletion(-)
diff --git a/arch/alpha/kernel/syscalls/syscall.tbl b/arch/alpha/kernel/syscalls/syscall.tbl
index 9384d59a44dc..2087b83d6d2c 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_sys_userns_set_idmap
+584 common rootns sys_sys_rootns
diff --git a/arch/arm/tools/syscall.tbl b/arch/arm/tools/syscall.tbl
index 6130366b7681..93e609de0bad 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_sys_userns_set_idmap
+474 common rootns sys_sys_rootns
diff --git a/arch/arm64/tools/syscall_32.tbl b/arch/arm64/tools/syscall_32.tbl
index 3fcc7899fd08..5dd5172b5118 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_sys_userns_set_idmap
+474 common rootns sys_sys_rootns
diff --git a/arch/m68k/kernel/syscalls/syscall.tbl b/arch/m68k/kernel/syscalls/syscall.tbl
index 5607635bd4bd..4fa5db7d1e62 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_sys_userns_set_idmap
+474 common rootns sys_sys_rootns
diff --git a/arch/microblaze/kernel/syscalls/syscall.tbl b/arch/microblaze/kernel/syscalls/syscall.tbl
index 97ee93f42fac..5bfe96f7ec5c 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_sys_userns_set_idmap
+474 common rootns sys_sys_rootns
diff --git a/arch/mips/kernel/syscalls/syscall_n32.tbl b/arch/mips/kernel/syscalls/syscall_n32.tbl
index da4ed57a91d3..e664ef0d1e56 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_sys_userns_set_idmap
+474 n32 rootns sys_sys_rootns
diff --git a/arch/mips/kernel/syscalls/syscall_n64.tbl b/arch/mips/kernel/syscalls/syscall_n64.tbl
index 5e9839b6b389..725c0e5a5ab8 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_sys_userns_set_idmap
+474 n64 rootns sys_sys_rootns
diff --git a/arch/mips/kernel/syscalls/syscall_o32.tbl b/arch/mips/kernel/syscalls/syscall_o32.tbl
index 290c1b61be47..2c8472b83d23 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_sys_userns_set_idmap
+474 o32 rootns sys_sys_rootns
diff --git a/arch/parisc/kernel/syscalls/syscall.tbl b/arch/parisc/kernel/syscalls/syscall.tbl
index fc0fa917eb92..0a32c40cfcbe 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_sys_userns_set_idmap
+474 common rootns sys_sys_rootns
diff --git a/arch/powerpc/kernel/syscalls/syscall.tbl b/arch/powerpc/kernel/syscalls/syscall.tbl
index d12e49022b23..d2fd229b8da8 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 common userns_set_idmap sys_sys_userns_set_idmap
+474 nospu rootns sys_sys_rootns
diff --git a/arch/s390/kernel/syscalls/syscall.tbl b/arch/s390/kernel/syscalls/syscall.tbl
index dc427811d30d..8251cad9530d 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_sys_userns_set_idmap
+474 common rootns sys_sys_rootns
diff --git a/arch/sh/kernel/syscalls/syscall.tbl b/arch/sh/kernel/syscalls/syscall.tbl
index e62ac9acc7ad..13105c503bf6 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_sys_userns_set_idmap
+474 common rootns sys_sys_rootns
diff --git a/arch/sparc/kernel/syscalls/syscall.tbl b/arch/sparc/kernel/syscalls/syscall.tbl
index df074bf322c4..7542448ab4eb 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_sys_userns_set_idmap
+474 common rootns sys_sys_rootns
diff --git a/arch/x86/entry/syscalls/syscall_32.tbl b/arch/x86/entry/syscalls/syscall_32.tbl
index 243a3f55834d..35cb517befbf 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_sys_userns_set_idmap
+474 i386 rootns sys_sys_rootns
diff --git a/arch/x86/entry/syscalls/syscall_64.tbl b/arch/x86/entry/syscalls/syscall_64.tbl
index f11700e3af65..387ca7628bae 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_sys_userns_set_idmap
+474 common rootns sys_sys_rootns
#
# 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 1d28de95915f..f9869ffeeed1 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_sys_userns_set_idmap
+474 common rootns sys_sys_rootns
diff --git a/include/uapi/asm-generic/unistd.h b/include/uapi/asm-generic/unistd.h
index 695eac2d356b..726b39b6b47c 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/rootns.c */
+#define __NR_rootns 474
+__SYSCALL(__NR_rootns, sys_rootns)
+
#undef __NR_syscalls
-#define __NR_syscalls 474
+#define __NR_syscalls 475
/*
* 32 bit systems traditionally used different
diff --git a/scripts/syscall.tbl b/scripts/syscall.tbl
index 0dddd465d1c5..1670f575d3e4 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_sys_userns_set_idmap
+474 common rootns sys_sys_rootns
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 23/25] docs: Document root namespace uAPI
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (21 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 22/25] arch: Wire up rootns() system call Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 24/25] selftests/rootns: Add root namespace test suite Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 25/25] MAINTAINERS: Add entry for ROOT NAMESPACE Jarkko Sakkinen
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
Zygmunt Krynicki
Userspace container managers need a clear specification of rootns state
transitions, control ioctls, mount-tree construction, user namespace ID
mapping, credential rules, and process creation semantics.
Add Documentation/userspace-api/rootns.rst to include the kernel-doc
sections, ioctl descriptions, and system call reference from
kernel/rootns.c, kernel/user_namespace.c, include/uapi/linux/rootns.h,
include/uapi/linux/nsfs.h, fs/fsopen.c, and fs/namespace.c, and register
the rootns ioctl magic in ioctl-number.rst.
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/userspace-api/index.rst | 1 +
.../userspace-api/ioctl/ioctl-number.rst | 1 +
Documentation/userspace-api/rootns.rst | 65 +++++++++++++++++++
3 files changed, 67 insertions(+)
create mode 100644 Documentation/userspace-api/rootns.rst
diff --git a/Documentation/userspace-api/index.rst b/Documentation/userspace-api/index.rst
index a68b1bea57a8..56d0ac4eb087 100644
--- a/Documentation/userspace-api/index.rst
+++ b/Documentation/userspace-api/index.rst
@@ -17,6 +17,7 @@ System calls
:maxdepth: 1
unshare
+ rootns
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..d8dc926ea283 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/rootns.h Root namespace 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/rootns.rst b/Documentation/userspace-api/rootns.rst
new file mode 100644
index 000000000000..ef18ed59ba4a
--- /dev/null
+++ b/Documentation/userspace-api/rootns.rst
@@ -0,0 +1,65 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+===================
+Root namespace uAPI
+===================
+
+Overview
+========
+
+.. kernel-doc:: kernel/rootns.c
+ :doc: Overview
+
+Flags
+=====
+
+.. kernel-doc:: include/uapi/linux/rootns.h
+ :identifiers: rootns_flags
+
+Ioctls
+======
+
+.. kernel-doc:: include/uapi/linux/rootns.h
+ :doc: ROOTNS_GET_NSFD
+
+.. kernel-doc:: include/uapi/linux/rootns.h
+ :identifiers: rootns_wait_args
+
+.. kernel-doc:: include/uapi/linux/rootns.h
+ :doc: ROOTNS_WAIT
+
+.. kernel-doc:: include/uapi/linux/rootns.h
+ :doc: ROOTNS_KILL
+
+System calls
+============
+
+.. kernel-doc:: kernel/rootns.c
+ :identifiers: sys_rootns
+
+Process creation
+================
+
+.. kernel-doc:: kernel/rootns.c
+ :doc: CLONE_INTO_ROOTNS
+
+Filesystem configuration
+========================
+
+.. kernel-doc:: fs/fsopen.c
+ :doc: FSCONFIG_SET_ROOTNS
+
+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_idmap_flags userns_idmap
+
+.. kernel-doc:: kernel/user_namespace.c
+ :identifiers: sys_userns_set_idmap
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 24/25] selftests/rootns: Add root namespace test suite
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (22 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 23/25] docs: Document root namespace uAPI Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
2026-11-21 0:08 ` [RFC PATCH v5 25/25] MAINTAINERS: Add entry for ROOT NAMESPACE Jarkko Sakkinen
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
Zygmunt Krynicki
Verify the root namespace, mount-namespace configuration, and
userns_set_idmap() uAPI and security invariants across privileged,
unprivileged, SCM_RIGHTS delegation, and edge-case scenarios.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
tools/testing/selftests/Makefile | 1 +
tools/testing/selftests/rootns/Makefile | 5 +
tools/testing/selftests/rootns/config | 10 +
.../testing/selftests/rootns/rootns_cells.py | 1400 ++++++++++++++
tools/testing/selftests/rootns/rootns_test.py | 1645 +++++++++++++++++
tools/testing/selftests/rootns/test_smoke.sh | 10 +
6 files changed, 3071 insertions(+)
create mode 100644 tools/testing/selftests/rootns/Makefile
create mode 100644 tools/testing/selftests/rootns/config
create mode 100755 tools/testing/selftests/rootns/rootns_cells.py
create mode 100755 tools/testing/selftests/rootns/rootns_test.py
create mode 100755 tools/testing/selftests/rootns/test_smoke.sh
diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile
index 07c3719f8b04..7c44f93e57a4 100644
--- a/tools/testing/selftests/Makefile
+++ b/tools/testing/selftests/Makefile
@@ -117,6 +117,7 @@ TARGETS += rdma
TARGETS += resctrl
TARGETS += riscv
TARGETS += rlimits
+TARGETS += rootns
TARGETS += rseq
TARGETS += rtc
TARGETS += rust
diff --git a/tools/testing/selftests/rootns/Makefile b/tools/testing/selftests/rootns/Makefile
new file mode 100644
index 000000000000..62629d112e12
--- /dev/null
+++ b/tools/testing/selftests/rootns/Makefile
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+include ../lib.mk
+
+TEST_PROGS := test_smoke.sh
+TEST_PROGS_EXTENDED := rootns_cells.py rootns_test.py
diff --git a/tools/testing/selftests/rootns/config b/tools/testing/selftests/rootns/config
new file mode 100644
index 000000000000..21b1aecc003b
--- /dev/null
+++ b/tools/testing/selftests/rootns/config
@@ -0,0 +1,10 @@
+CONFIG_CGROUPS=y
+CONFIG_IPC_NS=y
+CONFIG_NET_NS=y
+CONFIG_PID_NS=y
+CONFIG_PROC_FS=y
+CONFIG_ROOTNS=y
+CONFIG_TIME_NS=y
+CONFIG_TMPFS=y
+CONFIG_USER_NS=y
+CONFIG_UTS_NS=y
diff --git a/tools/testing/selftests/rootns/rootns_cells.py b/tools/testing/selftests/rootns/rootns_cells.py
new file mode 100755
index 000000000000..733e45b39a8a
--- /dev/null
+++ b/tools/testing/selftests/rootns/rootns_cells.py
@@ -0,0 +1,1400 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+#
+# Copyright (C) 2026 Opinsys Oy
+
+from __future__ import annotations
+
+import argparse
+from collections.abc import Callable, Mapping, Sequence
+from contextlib import suppress
+import ctypes
+from dataclasses import asdict, dataclass, field
+from enum import Enum, IntEnum, IntFlag
+import errno
+import json
+import os
+import platform
+import selectors
+import signal
+import socket
+import sys
+from types import TracebackType
+from typing import Any, ClassVar, Final, NoReturn
+
+HOST_RUNTIME_ENTRIES: Final[tuple[str, ...]] = (
+ "usr",
+ "bin",
+ "sbin",
+ "lib",
+ "lib32",
+ "lib64",
+ "libx32",
+ "etc",
+ "opt",
+ "nix",
+)
+
+
+class RootnsFlag(IntFlag):
+ NONE = 0
+ KILL_ON_CLOSE = 0x00000001
+ CLOSE_ON_EXEC = 0x00000002
+ DEFAULT = KILL_ON_CLOSE | CLOSE_ON_EXEC
+ ALL = KILL_ON_CLOSE | CLOSE_ON_EXEC
+
+
+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_ROOTNS = 1 << 38
+
+
+class AtFlag(IntFlag):
+ NONE = 0
+ EMPTY_PATH = 0x1000
+ RECURSIVE = 0x8000
+
+
+class OpenTreeFlag(IntFlag):
+ CLONE = 1 << 0
+ CLOEXEC = os.O_CLOEXEC
+ RECURSIVE = 0x8000
+
+
+class MoveMountFlag(IntFlag):
+ F_EMPTY_PATH = 0x00000004
+ T_EMPTY_PATH = 0x00000040
+ T_MNTNS = 0x00000080
+ SET_GROUP = 0x00000100
+ BENEATH = 0x00000200
+ CLONE = 0x00000400
+
+
+class UsernsIdmapFlag(IntFlag):
+ NONE = 0
+ UID = 1 << 0
+ GID = 1 << 1
+ PROJID = 1 << 2
+ SETGROUPS_DENY = 1 << 3
+ ALL = 0x0F
+
+
+class MountAttrFlag(IntFlag):
+ NONE = 0
+ RDONLY = 0x00000001
+ NOSUID = 0x00000002
+ NODEV = 0x00000004
+
+
+class MountFlag(IntFlag):
+ REC = 0x4000
+ PRIVATE = 1 << 18
+ SHARED = 1 << 20
+
+
+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
+ SET_ROOTNS = 9
+
+
+class PrctlOp(IntEnum):
+ GET_DUMPABLE = 3
+ SET_DUMPABLE = 4
+ SET_KEEPCAPS = 8
+ GET_NO_NEW_PRIVS = 39
+
+
+class RootnsWaitArgs(ctypes.Structure):
+ flags: int
+ status: int
+ _fields_ = [
+ ("flags", ctypes.c_uint32),
+ ("status", ctypes.c_int32),
+ ]
+
+
+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
+ rootns: 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),
+ ("rootns", 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 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),
+ ]
+
+
+class UsernsIdmap(ctypes.Structure):
+ SIZE_VER0: ClassVar[int] = 40
+
+ flags: int
+ nr_uid_extents: int
+ uid_extents: int
+ nr_gid_extents: int
+ nr_projid_extents: int
+ gid_extents: int
+ projid_extents: int
+ _fields_ = [
+ ("flags", ctypes.c_uint32),
+ ("nr_uid_extents", ctypes.c_uint32),
+ ("uid_extents", ctypes.c_uint64),
+ ("nr_gid_extents", ctypes.c_uint32),
+ ("nr_projid_extents", ctypes.c_uint32),
+ ("gid_extents", ctypes.c_uint64),
+ ("projid_extents", ctypes.c_uint64),
+ ]
+
+
+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_ARCHS: Final[tuple[str, ...]] = (
+ "ppc",
+ "ppc64",
+ "ppc64le",
+ "powerpc",
+ "sparc",
+ "sparc64",
+ "alpha",
+ )
+
+ @classmethod
+ def _is_wide_ioc_arch(cls) -> bool:
+ mach = platform.machine().lower()
+ return mach in cls._WIDE_IOC_ARCHS or mach.startswith("mips")
+
+ @classmethod
+ def ioc(cls, direction: int, magic: int, nr: int, size: int) -> int:
+ sizebits = 13 if cls._is_wide_ioc_arch() else 14
+ typeshift = 8
+ sizeshift = 16
+ dirshift = sizeshift + sizebits
+ return (
+ (direction << dirshift)
+ | (magic << typeshift)
+ | nr
+ | (size << sizeshift)
+ )
+
+ @classmethod
+ def io(cls, magic: int, nr: int) -> int:
+ none_dir = 1 if cls._is_wide_ioc_arch() else 0
+ return cls.ioc(none_dir, magic, nr, 0)
+
+ @classmethod
+ def iowr(cls, magic: int, nr: int, size: int) -> int:
+ rw = 6 if cls._is_wide_ioc_arch() else 3
+ return cls.ioc(rw, magic, nr, size)
+
+ @staticmethod
+ def _build_syscall_numbers() -> dict[str, int]:
+ mach = platform.machine().lower()
+ if mach == "alpha":
+ base = 110
+ elif mach.startswith("mips"):
+ base = 5000 if ctypes.sizeof(ctypes.c_void_p) == 8 else 4000
+ else:
+ base = 0
+
+ nums: dict[str, int] = {
+ "open_tree": base + 428,
+ "move_mount": base + 429,
+ "fsopen": base + 430,
+ "fsconfig": base + 431,
+ "fsmount": base + 432,
+ "clone3": base + 435,
+ "openat2": base + 437,
+ "userns_set_idmap": base + 473,
+ "rootns": base + 474,
+ }
+ legacy: dict[str, dict[str, int]] = {
+ "x86_64": {"pivot_root": 155, "umount2": 166, "execveat": 322},
+ "i386": {"pivot_root": 217, "umount2": 52, "execveat": 358},
+ "i686": {"pivot_root": 217, "umount2": 52, "execveat": 358},
+ "aarch64": {"pivot_root": 41, "umount2": 39, "execveat": 281},
+ "riscv64": {"pivot_root": 41, "umount2": 39, "execveat": 281},
+ "loongarch64": {
+ "pivot_root": 41,
+ "umount2": 39,
+ "execveat": 281,
+ },
+ "s390x": {"pivot_root": 217, "umount2": 52, "execveat": 354},
+ "ppc64le": {"pivot_root": 203, "umount2": 52, "execveat": 362},
+ "ppc64": {"pivot_root": 203, "umount2": 52, "execveat": 362},
+ "armv7l": {"pivot_root": 218, "umount2": 52, "execveat": 387},
+ }
+ nums.update(legacy.get(mach, legacy["x86_64"]))
+ return nums
+
+ _NR: ClassVar[dict[str, int]]
+ _LIBC: ClassVar[ctypes.CDLL]
+
+ @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 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 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 open_tree(
+ cls, dfd: int, path: str | bytes, flags: OpenTreeFlag
+ ) -> int:
+ return cls.syscall(
+ "open_tree",
+ ctypes.c_int(dfd),
+ ctypes.c_char_p(cls._cstr(path)),
+ ctypes.c_uint(int(flags)),
+ )
+
+ @classmethod
+ def move_mount(
+ cls,
+ from_dfd: int,
+ from_path: str | bytes,
+ to_dfd: int,
+ to_path: str | bytes,
+ flags: MoveMountFlag,
+ ) -> 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 set_mount_propagation(
+ cls,
+ target: str | bytes = "/",
+ flags: MountFlag = MountFlag.REC | MountFlag.PRIVATE,
+ ) -> None:
+ ret: int = cls._LIBC.mount(
+ ctypes.c_char_p(b"none"),
+ ctypes.c_char_p(cls._cstr(target)),
+ ctypes.c_void_p(0),
+ ctypes.c_ulong(int(flags)),
+ ctypes.c_void_p(0),
+ )
+ if ret < 0:
+ cls._os_err()
+
+ @classmethod
+ def setns(cls, fd: int, nstype: CloneFlag | int = 0) -> None:
+ if hasattr(os, "setns"):
+ os.setns(fd, int(nstype))
+ return
+ ret: int = cls._LIBC.setns(ctypes.c_int(fd), ctypes.c_int(int(nstype)))
+ if ret < 0:
+ cls._os_err()
+
+ @classmethod
+ def unshare(cls, flags: CloneFlag | int) -> None:
+ if hasattr(os, "unshare"):
+ os.unshare(int(flags))
+ return
+ ret: int = cls._LIBC.unshare(ctypes.c_int(int(flags)))
+ if ret < 0:
+ cls._os_err()
+
+ @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 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_size = 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_size)
+ )
+
+ @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 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]] = (),
+ *,
+ deny_setgroups: bool = False,
+ extra_flags: UsernsIdmapFlag | int = UsernsIdmapFlag.NONE,
+ size: int | None = None,
+ sys_flags: int = 0,
+ ) -> None:
+ flags = int(extra_flags)
+ u_arr = cls._extent_array(uid_extents)
+ g_arr = cls._extent_array(gid_extents)
+ p_arr = cls._extent_array(projid_extents)
+ if u_arr is not None:
+ flags |= int(UsernsIdmapFlag.UID)
+ if g_arr is not None:
+ flags |= int(UsernsIdmapFlag.GID)
+ if p_arr is not None:
+ flags |= int(UsernsIdmapFlag.PROJID)
+ if deny_setgroups:
+ flags |= int(UsernsIdmapFlag.SETGROUPS_DENY)
+ req = UsernsIdmap(
+ flags=flags,
+ nr_uid_extents=len(uid_extents),
+ uid_extents=ctypes.addressof(u_arr) if u_arr is not None else 0,
+ nr_gid_extents=len(gid_extents),
+ nr_projid_extents=len(projid_extents),
+ 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,
+ sys_flags,
+ )
+
+
+Sys._NR = Sys._build_syscall_numbers()
+Sys._LIBC = ctypes.CDLL(None, use_errno=True)
+Sys._LIBC.syscall.restype = ctypes.c_long
+
+
+class Ioctl(IntEnum):
+ ROOTNS_GET_NSFD = Sys.io(0xB9, 0x01)
+ ROOTNS_WAIT = Sys.iowr(0xB9, 0x02, ctypes.sizeof(RootnsWaitArgs))
+ ROOTNS_KILL = Sys.io(0xB9, 0x03)
+ NS_GET_USERNS = Sys.io(0xB7, 0x01)
+ NS_GET_PARENT = Sys.io(0xB7, 0x02)
+ NS_GET_NSTYPE = Sys.io(0xB7, 0x03)
+
+
+class CellState(str, Enum):
+ CREATED = "created"
+ RUNNING = "running"
+ EXITED = "exited"
+
+
+class CellMode(str, Enum):
+ HOST = "host"
+ TMPFS = "tmpfs"
+
+
+class RpcOp(str, Enum):
+ PING = "ping"
+ SHUTDOWN = "shutdown"
+ LIST = "list"
+ CREATE = "create"
+ SPAWN = "spawn"
+ MOUNT = "mount"
+ KILL = "kill"
+ WAIT = "wait"
+ DESTROY = "destroy"
+
+
+@dataclass(frozen=True)
+class WaitResult:
+ pid: int
+ status: int = 0
+
+ @property
+ def exit_code(self) -> int | None:
+ if self.pid <= 0:
+ return None
+ return os.waitstatus_to_exitcode(self.status)
+
+
+@dataclass(frozen=True)
+class CellInfo:
+ name: str
+ state: CellState
+ init_pid: int | None = None
+ exit_code: int | None = None
+
+
+@dataclass(frozen=True)
+class SpawnInfo:
+ pid: int
+ state: CellState
+
+
+class Rootns:
+ fd: int
+
+ def __init__(
+ self,
+ flags: RootnsFlag | int = RootnsFlag.DEFAULT,
+ *,
+ fd: int | None = None,
+ ) -> None:
+ if fd is not None:
+ self.fd = fd
+ else:
+ self.fd = Sys.syscall("rootns", ctypes.c_uint(int(flags)))
+
+ @classmethod
+ def from_fd(cls, fd: int) -> Rootns:
+ return cls(fd=fd)
+
+ def fileno(self) -> int:
+ return self.fd
+
+ def __enter__(self) -> Rootns:
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc: BaseException | None,
+ tb: TracebackType | None,
+ ) -> None:
+ self.close()
+
+ def close(self) -> None:
+ if self.fd >= 0:
+ try:
+ os.close(self.fd)
+ except OSError:
+ pass
+ self.fd = -1
+
+ def get_nsfd(self, nstype: CloneFlag | int) -> int:
+ return Sys.ioctl(self.fd, Ioctl.ROOTNS_GET_NSFD, int(nstype))
+
+ 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]] = (),
+ *,
+ deny_setgroups: bool = False,
+ ) -> None:
+ userns_fd = self.get_nsfd(CloneFlag.NEWUSER)
+ try:
+ Sys.set_userns_idmap(
+ userns_fd,
+ uid_extents=uid_extents,
+ gid_extents=gid_extents,
+ projid_extents=projid_extents,
+ deny_setgroups=deny_setgroups,
+ )
+ finally:
+ os.close(userns_fd)
+
+ def map_self_ugid(self) -> None:
+ self.set_idmap(
+ uid_extents=((0, os.geteuid(), 1),),
+ gid_extents=((0, os.getegid(), 1),),
+ deny_setgroups=True,
+ )
+
+ def wait(self, flags: int = 0) -> WaitResult:
+ args = RootnsWaitArgs(flags=flags, status=0)
+ pid = Sys.ioctl(self.fd, Ioctl.ROOTNS_WAIT, ctypes.addressof(args))
+ return WaitResult(pid=pid, status=int(args.status))
+
+ def kill(self, sig: signal.Signals | int) -> None:
+ mask = (1 << (ctypes.sizeof(ctypes.c_ulong) * 8)) - 1
+ Sys.ioctl(self.fd, Ioctl.ROOTNS_KILL, int(sig) & mask)
+
+ def clone_into(
+ self,
+ extra_flags: CloneFlag = CloneFlag.NONE,
+ exit_signal: int = int(signal.SIGCHLD),
+ ) -> tuple[int, int]:
+ pidfd_cell = ctypes.c_int(-1)
+ args = CloneArgs()
+ args.flags = int(CloneFlag.INTO_ROOTNS | extra_flags)
+ args.exit_signal = exit_signal
+ args.rootns = self.fd & 0xFFFFFFFFFFFFFFFF
+ if extra_flags & CloneFlag.PIDFD:
+ args.pidfd = ctypes.addressof(pidfd_cell)
+ pid = Sys.clone3(args)
+ return pid, int(pidfd_cell.value)
+
+ def run(
+ self,
+ fn: Callable[[], int | None],
+ extra_flags: CloneFlag = CloneFlag.NONE,
+ ) -> int:
+ pid, _ = self.clone_into(extra_flags=extra_flags)
+ 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
+
+ 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_ROOTNS, 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:
+ name: str
+ flags: RootnsFlag = RootnsFlag.DEFAULT
+ rns: Rootns = field(init=False)
+ mntns_fd: int = field(init=False, default=-1)
+ root_dfd: int = field(init=False, default=-1)
+ init_pid: int | None = field(init=False, default=None)
+ exit_status: int | None = field(init=False, default=None)
+
+ def __post_init__(self) -> None:
+ self.rns = Rootns(self.flags)
+ try:
+ self.mntns_fd = self.rns.get_nsfd(CloneFlag.NEWNS)
+ except Exception:
+ self.rns.close()
+ raise
+
+ def __enter__(self) -> Cell:
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc: BaseException | None,
+ tb: TracebackType | None,
+ ) -> None:
+ self.close()
+
+ @staticmethod
+ def _close_fd(fd: int) -> int:
+ if fd >= 0:
+ with suppress(OSError):
+ os.close(fd)
+ return -1
+
+ def _move_to_mntns(self, mfd: int, target: str) -> None:
+ Sys.move_mount(
+ mfd,
+ "",
+ self.mntns_fd,
+ target,
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+
+ def _consume_mount(self, mfd: int, target: str) -> None:
+ try:
+ self._move_to_mntns(mfd, target.lstrip("/"))
+ finally:
+ os.close(mfd)
+
+ def setup_rootfs(
+ self,
+ dirs: Sequence[str] = ("proc", "tmp", "mnt"),
+ mount_procfs: bool = True,
+ host_runtime: bool = False,
+ map_ugid: bool = True,
+ ) -> None:
+ if map_ugid:
+ self.rns.map_self_ugid()
+ rootfd = self.rns.make_mount("tmpfs")
+ bind_dirs: list[str] = []
+ try:
+ for d in dirs:
+ os.mkdir(d, 0o755, dir_fd=rootfd)
+ if host_runtime:
+ for entry in HOST_RUNTIME_ENTRIES:
+ host_path = f"/{entry}"
+ if os.path.islink(host_path):
+ os.symlink(
+ os.readlink(host_path), entry, dir_fd=rootfd
+ )
+ elif os.path.isdir(host_path):
+ os.mkdir(entry, 0o755, dir_fd=rootfd)
+ bind_dirs.append(entry)
+ self._move_to_mntns(rootfd, "/")
+ except Exception:
+ os.close(rootfd)
+ raise
+ self.root_dfd = rootfd
+ for entry in bind_dirs:
+ self.bind_mount(f"/{entry}", entry)
+ if mount_procfs and "proc" in dirs:
+ self.mount_fs("proc", "proc")
+
+ def mount_fs(
+ self,
+ fstype: str,
+ target: str,
+ attr_flags: MountAttrFlag = MountAttrFlag.NONE,
+ options: Mapping[str, str | None] | None = None,
+ ) -> None:
+ mfd = self.rns.make_mount(
+ fstype, attr_flags=attr_flags, options=options
+ )
+ self._consume_mount(mfd, target)
+
+ def bind_mount(self, host_src: str, target: str) -> None:
+ Sys.move_mount(
+ Sys.AT_FDCWD,
+ host_src,
+ self.mntns_fd,
+ target.lstrip("/"),
+ MoveMountFlag.T_MNTNS | MoveMountFlag.CLONE,
+ )
+
+ def spawn(
+ self,
+ argv: Sequence[str],
+ env: Mapping[str, str] | None = None,
+ resolve_in_root: bool = True,
+ ) -> int:
+ bin_fd = -1
+ if resolve_in_root and self.root_dfd >= 0:
+ bin_fd = Sys.openat2(
+ self.root_dfd,
+ argv[0],
+ os.O_RDONLY | os.O_CLOEXEC,
+ resolve=ResolveFlag.IN_ROOT,
+ )
+ try:
+ pid, _ = self.rns.clone_into(
+ extra_flags=CloneFlag.AUTOREAP, 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))
+ else:
+ os.execve(argv[0], list(argv), dict(env))
+ except BaseException:
+ os._exit(127)
+ if self.init_pid is None:
+ self.init_pid = pid
+ return pid
+ finally:
+ self._close_fd(bin_fd)
+
+ def kill(self, sig: signal.Signals | int = signal.SIGTERM) -> None:
+ self.rns.kill(sig)
+
+ def wait(self, nohang: bool = False) -> WaitResult:
+ res = self.rns.wait(os.WNOHANG if nohang else 0)
+ if res.pid > 0:
+ self.exit_status = res.status
+ return res
+
+ @property
+ def state(self) -> CellState:
+ if self.init_pid is None:
+ return CellState.CREATED
+ if self.exit_status is None:
+ return CellState.RUNNING
+ return CellState.EXITED
+
+ def info(self) -> CellInfo:
+ code = (
+ os.waitstatus_to_exitcode(self.exit_status)
+ if self.exit_status is not None
+ else None
+ )
+ return CellInfo(
+ name=self.name,
+ state=self.state,
+ init_pid=self.init_pid,
+ exit_code=code,
+ )
+
+ def close(self) -> None:
+ self.root_dfd = self._close_fd(self.root_dfd)
+ self.mntns_fd = self._close_fd(self.mntns_fd)
+ self.rns.close()
+
+
+class JsonLine:
+ @staticmethod
+ def send(sock: socket.socket, payload: Mapping[str, Any]) -> None:
+ sock.sendall((json.dumps(payload) + "\n").encode("utf-8"))
+
+ @staticmethod
+ def recv(sock: socket.socket) -> dict[str, Any] | None:
+ with sock.makefile("r", encoding="utf-8") as reader:
+ line = reader.readline()
+ if not line:
+ return None
+ data: dict[str, Any] = json.loads(line)
+ return data
+
+
+class CellService:
+ def __init__(self, sock_path: str) -> None:
+ self.sock_path = sock_path
+ self.sel = selectors.DefaultSelector()
+ self.cells: dict[str, Cell] = {}
+ self.running = True
+ with suppress(FileNotFoundError):
+ os.unlink(sock_path)
+ self.srv = socket.socket(
+ socket.AF_UNIX, socket.SOCK_STREAM | socket.SOCK_CLOEXEC
+ )
+ self.srv.bind(sock_path)
+ self.srv.listen(16)
+ self.srv.setblocking(False)
+ self.sel.register(self.srv, selectors.EVENT_READ, self._on_accept)
+
+ def __enter__(self) -> CellService:
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc: BaseException | None,
+ tb: TracebackType | None,
+ ) -> None:
+ self.close()
+
+ def _safe_unregister(self, fileobj: Any) -> None:
+ with suppress(KeyError, ValueError):
+ self.sel.unregister(fileobj)
+
+ def _reap_children(self) -> None:
+ while True:
+ try:
+ pid, _ = os.waitpid(-1, os.WNOHANG)
+ if pid == 0:
+ break
+ except ChildProcessError:
+ break
+
+ def _on_cell_event(self, cell: Cell) -> None:
+ with suppress(OSError):
+ res = cell.wait(nohang=True)
+ if res.pid > 0:
+ self._safe_unregister(cell.rns)
+ self._reap_children()
+
+ def _on_accept(self) -> None:
+ conn, _ = self.srv.accept()
+ with conn:
+ conn.setblocking(True)
+ try:
+ req = JsonLine.recv(conn)
+ if req is None:
+ return
+ resp: dict[str, Any] = {
+ "ok": True,
+ "result": self._dispatch(req),
+ }
+ except Exception as exc:
+ resp = {
+ "ok": False,
+ "error": str(exc),
+ "errno": getattr(exc, "errno", None),
+ }
+ JsonLine.send(conn, resp)
+
+ def _dispatch(self, req: Mapping[str, Any]) -> Any:
+ op = RpcOp(req["op"])
+ if op is RpcOp.PING:
+ return "pong"
+ if op is RpcOp.SHUTDOWN:
+ self.running = False
+ return "bye"
+ if op is RpcOp.LIST:
+ self._reap_children()
+ return [asdict(c.info()) for c in self.cells.values()]
+
+ name = str(req["name"])
+ if op is RpcOp.CREATE:
+ if name in self.cells:
+ raise OSError(errno.EEXIST, f"cell {name} already exists")
+ mode = CellMode(req.get("mode", CellMode.HOST))
+ cell = Cell(name, flags=RootnsFlag.DEFAULT)
+ try:
+ cell.setup_rootfs(
+ mount_procfs=bool(req.get("proc", True)),
+ host_runtime=mode is CellMode.HOST,
+ )
+ except Exception:
+ cell.close()
+ raise
+ self.cells[name] = cell
+ self.sel.register(
+ cell.rns,
+ selectors.EVENT_READ,
+ lambda c=cell: self._on_cell_event(c),
+ )
+ return asdict(cell.info())
+
+ if name not in self.cells:
+ raise OSError(errno.ENOENT, f"unknown cell {name}")
+ cell = self.cells[name]
+
+ if op is RpcOp.SPAWN:
+ pid = cell.spawn(
+ list(req["argv"]),
+ resolve_in_root=bool(req.get("resolve_in_root", True)),
+ )
+ return asdict(SpawnInfo(pid=pid, state=cell.state))
+ if op is RpcOp.MOUNT:
+ if req.get("bind"):
+ cell.bind_mount(str(req["source"]), str(req["target"]))
+ else:
+ cell.mount_fs(
+ str(req["source"]),
+ str(req["target"]),
+ options=req.get("options"),
+ )
+ return str(req["target"])
+ if op is RpcOp.KILL:
+ cell.kill(int(req.get("sig", int(signal.SIGTERM))))
+ return name
+ if op is RpcOp.WAIT:
+ res = cell.wait(nohang=bool(req.get("nohang", False)))
+ self._reap_children()
+ return asdict(res)
+ if op is RpcOp.DESTROY:
+ self._safe_unregister(cell.rns)
+ cell.close()
+ del self.cells[name]
+ self._reap_children()
+ return name
+ raise ValueError(f"unsupported op {op}")
+
+ def serve_forever(self) -> None:
+ try:
+ while self.running:
+ for key, _ in self.sel.select(timeout=0.2):
+ cb: Callable[[], None] = key.data
+ cb()
+ self._reap_children()
+ finally:
+ self.close()
+
+ def close(self) -> None:
+ for cell in list(self.cells.values()):
+ self._safe_unregister(cell.rns)
+ cell.close()
+ self.cells.clear()
+ self._safe_unregister(self.srv)
+ self.srv.close()
+ self.sel.close()
+ with suppress(FileNotFoundError):
+ os.unlink(self.sock_path)
+ self._reap_children()
+
+
+@dataclass(frozen=True)
+class CellClient:
+ sock_path: str
+
+ def call(self, op: RpcOp, **params: Any) -> Any:
+ with socket.socket(
+ socket.AF_UNIX, socket.SOCK_STREAM | socket.SOCK_CLOEXEC
+ ) as sock:
+ sock.connect(self.sock_path)
+ JsonLine.send(sock, {"op": op.value, **params})
+ resp = JsonLine.recv(sock)
+ if resp is None:
+ raise RuntimeError("empty RPC response")
+ if not resp["ok"]:
+ err = resp.get("errno")
+ if err is not None:
+ raise OSError(int(err), str(resp["error"]))
+ raise RuntimeError(str(resp["error"]))
+ return resp["result"]
+
+ @staticmethod
+ def _parse_cell_info(data: Mapping[str, Any]) -> CellInfo:
+ return CellInfo(
+ name=str(data["name"]),
+ state=CellState(data["state"]),
+ init_pid=data.get("init_pid"),
+ exit_code=data.get("exit_code"),
+ )
+
+ def ping(self) -> str:
+ return str(self.call(RpcOp.PING))
+
+ def shutdown(self) -> str:
+ return str(self.call(RpcOp.SHUTDOWN))
+
+ def list_cells(self) -> list[CellInfo]:
+ items: list[dict[str, Any]] = self.call(RpcOp.LIST)
+ return [self._parse_cell_info(item) for item in items]
+
+ def create(
+ self,
+ name: str,
+ mode: CellMode = CellMode.HOST,
+ proc: bool = True,
+ ) -> CellInfo:
+ data: dict[str, Any] = self.call(
+ RpcOp.CREATE,
+ name=name,
+ mode=mode.value,
+ proc=proc,
+ )
+ return self._parse_cell_info(data)
+
+ def spawn(
+ self,
+ name: str,
+ argv: Sequence[str],
+ resolve_in_root: bool = True,
+ ) -> SpawnInfo:
+ data: dict[str, Any] = self.call(
+ RpcOp.SPAWN,
+ name=name,
+ argv=list(argv),
+ resolve_in_root=resolve_in_root,
+ )
+ return SpawnInfo(pid=int(data["pid"]), state=CellState(data["state"]))
+
+ def mount(
+ self,
+ name: str,
+ source: str,
+ target: str,
+ bind: bool = False,
+ options: Mapping[str, str | None] | None = None,
+ ) -> str:
+ return str(
+ self.call(
+ RpcOp.MOUNT,
+ name=name,
+ source=source,
+ target=target,
+ bind=bind,
+ options=dict(options) if options is not None else None,
+ )
+ )
+
+ def kill(
+ self, name: str, sig: signal.Signals | int = signal.SIGTERM
+ ) -> str:
+ return str(self.call(RpcOp.KILL, name=name, sig=int(sig)))
+
+ def wait(self, name: str, nohang: bool = False) -> WaitResult:
+ data: dict[str, Any] = self.call(RpcOp.WAIT, name=name, nohang=nohang)
+ return WaitResult(pid=int(data["pid"]), status=int(data["status"]))
+
+ def destroy(self, name: str) -> str:
+ return str(self.call(RpcOp.DESTROY, name=name))
+
+
+class CellCli:
+ @staticmethod
+ def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--sock", default="/tmp/rootns-cells.sock")
+ sub = parser.add_subparsers(dest="cmd", required=True)
+ sub.add_parser("daemon")
+ sub.add_parser("ps")
+ sub.add_parser("shutdown")
+
+ p_create = sub.add_parser("create")
+ p_create.add_argument("name")
+ p_create.add_argument(
+ "--mode",
+ type=CellMode,
+ choices=tuple(CellMode),
+ default=CellMode.HOST,
+ )
+
+ for cname in ("start", "exec", "spawn"):
+ p_run = sub.add_parser(cname)
+ p_run.add_argument("name")
+ p_run.add_argument("argv", nargs=argparse.REMAINDER)
+
+ p_mnt = sub.add_parser("mount")
+ p_mnt.add_argument("name")
+ p_mnt.add_argument("source")
+ p_mnt.add_argument("target")
+ p_mnt.add_argument("--bind", action="store_true")
+
+ p_kill = sub.add_parser("kill")
+ p_kill.add_argument("name")
+ p_kill.add_argument(
+ "-s", "--sig", type=int, default=int(signal.SIGTERM)
+ )
+
+ p_wait = sub.add_parser("wait")
+ p_wait.add_argument("name")
+
+ p_rm = sub.add_parser("destroy")
+ p_rm.add_argument("name")
+ return parser
+
+ @classmethod
+ def main(cls, argv: Sequence[str] | None = None) -> None:
+ args = cls.build_parser().parse_args(argv)
+ if args.cmd == "daemon":
+ with CellService(args.sock) as srv:
+ srv.serve_forever()
+ return
+
+ client = CellClient(args.sock)
+ if args.cmd == "ps":
+ print(
+ json.dumps([asdict(c) for c in client.list_cells()], indent=2)
+ )
+ elif args.cmd == "shutdown":
+ print(json.dumps(client.shutdown()))
+ elif args.cmd == "create":
+ info = client.create(args.name, mode=args.mode)
+ print(json.dumps(asdict(info)))
+ elif args.cmd in ("start", "exec", "spawn"):
+ cmd_argv = (
+ args.argv[1:]
+ if args.argv and args.argv[0] == "--"
+ else list(args.argv)
+ )
+ print(json.dumps(asdict(client.spawn(args.name, cmd_argv))))
+ elif args.cmd == "mount":
+ print(
+ json.dumps(
+ client.mount(
+ args.name, args.source, args.target, bind=args.bind
+ )
+ )
+ )
+ elif args.cmd == "kill":
+ print(json.dumps(client.kill(args.name, args.sig)))
+ elif args.cmd == "wait":
+ res = client.wait(args.name)
+ print(json.dumps({"pid": res.pid, "exit_code": res.exit_code}))
+ elif args.cmd == "destroy":
+ print(json.dumps(client.destroy(args.name)))
+
+
+if __name__ == "__main__":
+ CellCli.main()
diff --git a/tools/testing/selftests/rootns/rootns_test.py b/tools/testing/selftests/rootns/rootns_test.py
new file mode 100755
index 000000000000..756bfe605f8e
--- /dev/null
+++ b/tools/testing/selftests/rootns/rootns_test.py
@@ -0,0 +1,1645 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+#
+# Copyright (C) 2026 Opinsys Oy
+
+from __future__ import annotations
+
+from collections.abc import Callable, Iterator, Sequence
+from contextlib import contextmanager, suppress
+from dataclasses import dataclass
+import errno
+import importlib
+import json
+import os
+from pathlib import Path
+import select
+import shutil
+import signal
+import socket
+import sys
+import tempfile
+import time
+import traceback
+from types import TracebackType
+from typing import Any, Final, NoReturn
+import unittest
+
+from rootns_cells import (
+ Cell,
+ CellClient,
+ CellInfo,
+ CellMode,
+ CellService,
+ CellState,
+ CloneArgs,
+ CloneFlag,
+ FsconfigCmd,
+ Ioctl,
+ MountFlag,
+ MoveMountFlag,
+ OpenTreeFlag,
+ PrctlOp,
+ Rootns,
+ RootnsFlag,
+ Sys,
+ UmountFlag,
+ UsernsIdmap,
+ UsernsIdmapFlag,
+ WaitResult,
+)
+
+PYTHON_BIN: Final[str] = os.path.realpath(sys.executable)
+SKIP_ERRNOS: Final[tuple[int, ...]] = (
+ errno.ENOSYS,
+ errno.EPERM,
+ errno.EACCES,
+ errno.EINVAL,
+ errno.ENOSPC,
+)
+
+
+@dataclass(frozen=True)
+class Payload:
+ code: str
+
+ def argv(self) -> list[str]:
+ return [PYTHON_BIN, "-S", "-c", self.code]
+
+
+WAIT_MOUNT_PAYLOAD: Final[Payload] = Payload(
+ """\
+import os
+import sys
+import time
+
+if os.getpid() != 1:
+ sys.exit(1)
+deadline = time.monotonic() + 5.0
+while time.monotonic() < deadline:
+ if os.path.ismount("/mnt") and os.path.exists("/mnt/done"):
+ with open("/mnt/done", "rb") as f:
+ sys.exit(0 if f.read() == b"ok\\n" else 2)
+ time.sleep(0.02)
+sys.exit(3)
+"""
+)
+
+WRITE_MOUNT_PAYLOAD: Final[Payload] = Payload(
+ """\
+import os
+import sys
+
+if not os.path.ismount("/mnt"):
+ sys.exit(1)
+with open("/mnt/done.tmp", "wb") as f:
+ f.write(b"ok\\n")
+os.replace("/mnt/done.tmp", "/mnt/done")
+"""
+)
+
+PAUSE_PAYLOAD: Final[Payload] = Payload(
+ """\
+import signal
+
+signal.pause()
+"""
+)
+
+
+@dataclass(frozen=True)
+class ProbeResult:
+ supported: bool
+ reason: str = ""
+
+
+@dataclass
+class SyncPipe:
+ r_fd: int
+ w_fd: int
+
+ @classmethod
+ def create(cls) -> SyncPipe:
+ r_fd, w_fd = os.pipe2(os.O_CLOEXEC)
+ return cls(r_fd=r_fd, w_fd=w_fd)
+
+ def __enter__(self) -> SyncPipe:
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc: BaseException | None,
+ tb: TracebackType | None,
+ ) -> None:
+ self.close()
+
+ def close_read(self) -> None:
+ if self.r_fd >= 0:
+ os.close(self.r_fd)
+ self.r_fd = -1
+
+ def close_write(self) -> None:
+ if self.w_fd >= 0:
+ os.close(self.w_fd)
+ self.w_fd = -1
+
+ def close(self) -> None:
+ self.close_read()
+ self.close_write()
+
+ def read_bytes(self, n: int = 1) -> bytes:
+ return os.read(self.r_fd, n)
+
+ def read_all(self) -> bytes:
+ chunks: list[bytes] = []
+ while True:
+ chunk = os.read(self.r_fd, 4096)
+ if not chunk:
+ break
+ chunks.append(chunk)
+ return b"".join(chunks)
+
+ def write_bytes(self, data: bytes = b"1") -> None:
+ os.write(self.w_fd, data)
+
+ def wait_in_child(self, exit_code: int = 0) -> int:
+ self.close_write()
+ self.read_bytes()
+ self.close_read()
+ return exit_code
+
+
+@dataclass(frozen=True)
+class NsTypeCase:
+ name: str
+ nstype: CloneFlag
+
+
+@dataclass(frozen=True)
+class BadCloneCase:
+ name: str
+ flags: CloneFlag
+ exit_signal: int = int(signal.SIGCHLD)
+ expected_errno: int = errno.EINVAL
+
+
+@dataclass(frozen=True)
+class SignalCase:
+ name: str
+ sig: int
+ expected_errno: int
+
+
+NS_TYPE_CASES: Final[tuple[NsTypeCase, ...]] = (
+ NsTypeCase("mnt", CloneFlag.NEWNS),
+ NsTypeCase("cgroup", CloneFlag.NEWCGROUP),
+ NsTypeCase("uts", CloneFlag.NEWUTS),
+ NsTypeCase("ipc", CloneFlag.NEWIPC),
+ NsTypeCase("user", CloneFlag.NEWUSER),
+ NsTypeCase("net", CloneFlag.NEWNET),
+ NsTypeCase("time", CloneFlag.NEWTIME),
+)
+
+BAD_CLONE_CASES: Final[tuple[BadCloneCase, ...]] = (
+ BadCloneCase("newns", CloneFlag.NEWNS),
+ BadCloneCase("newpid", CloneFlag.NEWPID),
+ BadCloneCase("newuser", CloneFlag.NEWUSER),
+ BadCloneCase("empty_mntns", CloneFlag.EMPTY_MNTNS),
+ BadCloneCase("fs", CloneFlag.FS),
+ BadCloneCase(
+ "thread",
+ CloneFlag.THREAD | CloneFlag.SIGHAND | CloneFlag.VM,
+ exit_signal=0,
+ ),
+ BadCloneCase("parent", CloneFlag.PARENT, exit_signal=0),
+ BadCloneCase("sysvsem", CloneFlag.SYSVSEM),
+ BadCloneCase("vm", CloneFlag.VM),
+ BadCloneCase("vm_vfork", CloneFlag.VM | CloneFlag.VFORK),
+)
+
+BAD_SIGNAL_CASES: Final[tuple[SignalCase, ...]] = (
+ SignalCase("negative", -1, errno.EINVAL),
+ SignalCase("out_of_range", 9999, errno.EINVAL),
+ SignalCase("empty_rootns", 0, errno.ESRCH),
+)
+
+
+class RootnsTestBase(unittest.TestCase):
+ @staticmethod
+ @contextmanager
+ def closing_fd(fd: int) -> Iterator[int]:
+ try:
+ yield fd
+ finally:
+ os.close(fd)
+
+ @staticmethod
+ def pause_forever() -> int:
+ signal.pause()
+ return 0
+
+ @staticmethod
+ def reap_exit_code(pid: int) -> int:
+ _, status = os.waitpid(pid, 0)
+ if os.WIFEXITED(status):
+ return os.WEXITSTATUS(status)
+ if os.WIFSIGNALED(status):
+ return 128 + os.WTERMSIG(status)
+ return 255
+
+ @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)
+
+ @classmethod
+ def make_plain_mount(cls, fstype: str) -> int:
+ with cls.closing_fd(Sys.fsopen(fstype)) as fsfd:
+ Sys.fsconfig(fsfd, FsconfigCmd.CMD_CREATE)
+ return Sys.fsmount(fsfd)
+
+ @classmethod
+ def probe_pre_idmap_mkdir(cls) -> ProbeResult:
+ try:
+ rns = Rootns()
+ except OSError as exc:
+ if exc.errno in SKIP_ERRNOS:
+ return ProbeResult(False, f"rootns() unavailable: {exc}")
+ raise
+ with rns:
+ try:
+ rns.map_self_ugid()
+ mfd = rns.make_mount("tmpfs")
+ except OSError as exc:
+ return ProbeResult(False, f"rootns setup unavailable: {exc}")
+ with cls.closing_fd(mfd):
+ os.mkdir("probe", 0o755, dir_fd=mfd)
+ return ProbeResult(True)
+
+ def run_forked(self, fn: Callable[[], None]) -> None:
+ with SyncPipe.create() as pipe:
+ sys.stdout.flush()
+ sys.stderr.flush()
+ pid = os.fork()
+ if pid == 0:
+ pipe.close_read()
+ try:
+ fn()
+ except unittest.SkipTest as exc:
+ payload = json.dumps({"kind": "skip", "msg": str(exc)})
+ pipe.write_bytes(payload.encode("utf-8"))
+ pipe.close_write()
+ os._exit(0)
+ except BaseException:
+ payload = json.dumps(
+ {"kind": "fail", "msg": traceback.format_exc()}
+ )
+ pipe.write_bytes(payload.encode("utf-8"))
+ pipe.close_write()
+ os._exit(1)
+ pipe.close_write()
+ os._exit(0)
+ pipe.close_write()
+ raw = pipe.read_all()
+ code = self.reap_exit_code(pid)
+ if raw:
+ info = json.loads(raw.decode("utf-8"))
+ if info["kind"] == "skip":
+ self.skipTest(str(info["msg"]))
+ self.fail(str(info["msg"]))
+ self.assertEqual(code, 0)
+
+ def create_rootns_as_uid(self, uid: int) -> Rootns | None:
+ s_parent, s_child = socket.socketpair(
+ socket.AF_UNIX, socket.SOCK_DGRAM
+ )
+ sys.stdout.flush()
+ sys.stderr.flush()
+ pid = os.fork()
+ if pid == 0:
+ s_parent.close()
+ try:
+ self.drop_to_uid(uid)
+ with Rootns() as rns:
+ socket.send_fds(s_child, [b"F"], [rns.fd])
+ os._exit(0)
+ except OSError as exc:
+ os._exit(0 if exc.errno in SKIP_ERRNOS else 1)
+ finally:
+ s_child.close()
+ s_child.close()
+ fds: list[int] = []
+ try:
+ rlist, _, _ = select.select([s_parent], [], [], 5.0)
+ if rlist:
+ _, fds, _, _ = socket.recv_fds(s_parent, 1, 1)
+ finally:
+ s_parent.close()
+ code = self.reap_exit_code(pid)
+ if code != 0:
+ for fd in fds:
+ os.close(fd)
+ self.fail(f"create_rootns_as_uid({uid}) failed with status {code}")
+ return Rootns.from_fd(fds[0]) if fds else None
+
+
+class CellServiceTest(RootnsTestBase):
+ tmpdir: str
+ sock_path: str
+ daemon_pid: int
+ client: CellClient
+
+ def setUp(self) -> None:
+ probe = self.probe_pre_idmap_mkdir()
+ if not probe.supported:
+ self.skipTest(probe.reason)
+ self.daemon_pid = 0
+ self.tmpdir = tempfile.mkdtemp(prefix="rootns-cells-")
+ try:
+ self.sock_path = os.path.join(self.tmpdir, "cells.sock")
+ self.daemon_pid = os.fork()
+ if self.daemon_pid == 0:
+ try:
+ with CellService(self.sock_path) as srv:
+ srv.serve_forever()
+ os._exit(0)
+ except BaseException:
+ os._exit(1)
+ self.client = CellClient(self.sock_path)
+ for _ in range(50):
+ if os.path.exists(self.sock_path):
+ try:
+ if self.client.ping() == "pong":
+ break
+ except OSError:
+ pass
+ time.sleep(0.05)
+ else:
+ self.fail("CellService daemon failed to start")
+ except BaseException:
+ self.tearDown()
+ raise
+
+ def tearDown(self) -> None:
+ daemon_pid = getattr(self, "daemon_pid", 0)
+ if daemon_pid > 0:
+ try:
+ self.client.shutdown()
+ except Exception:
+ os.kill(daemon_pid, signal.SIGKILL)
+ self.reap_exit_code(daemon_pid)
+ tmpdir = getattr(self, "tmpdir", "")
+ if tmpdir:
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+ def test_cell_lifecycle_exec_and_hot_mount(self) -> None:
+ info = self.client.create("alpha", mode=CellMode.HOST)
+ self.assertEqual(info.state, CellState.CREATED)
+ self.assertEqual(
+ self.client.list_cells(),
+ [CellInfo(name="alpha", state=CellState.CREATED)],
+ )
+
+ started = self.client.spawn("alpha", WAIT_MOUNT_PAYLOAD.argv())
+ self.assertEqual(started.state, CellState.RUNNING)
+
+ self.client.mount("alpha", "tmpfs", "/mnt")
+ self.client.spawn("alpha", WRITE_MOUNT_PAYLOAD.argv())
+
+ res = self.client.wait("alpha")
+ self.assertGreater(res.pid, 0)
+ self.assertEqual(res.exit_code, 0)
+
+ self.client.destroy("alpha")
+ self.assertEqual(self.client.list_cells(), [])
+
+ def test_cell_broadcast_kill(self) -> None:
+ self.client.create("killme", mode=CellMode.HOST)
+ self.client.spawn("killme", PAUSE_PAYLOAD.argv())
+ self.client.spawn("killme", PAUSE_PAYLOAD.argv())
+
+ self.client.kill("killme", signal.SIGKILL)
+ res = self.client.wait("killme")
+ self.assertEqual(res.exit_code, -int(signal.SIGKILL))
+ self.client.destroy("killme")
+
+
+class RootnsUapiTest(RootnsTestBase):
+ probe: ProbeResult
+ cell: Cell | None
+
+ def setUp(self) -> None:
+ self.probe = self.probe_pre_idmap_mkdir()
+ self.cell = None
+ if self.probe.supported:
+ cell = Cell("test")
+ try:
+ cell.setup_rootfs(
+ dirs=("proc", "tmp", "mnt"), mount_procfs=True
+ )
+ except BaseException:
+ cell.close()
+ raise
+ self.cell = cell
+
+ def tearDown(self) -> None:
+ if self.cell is not None:
+ self.cell.close()
+
+ def _require_cell(self) -> Cell:
+ if not self.probe.supported or self.cell is None:
+ self.skipTest(self.probe.reason)
+ return self.cell
+
+ def test_create_flags(self) -> None:
+ self._require_cell()
+ with Rootns(RootnsFlag.NONE):
+ pass
+ with Rootns(RootnsFlag.DEFAULT):
+ pass
+ with self.assertRaises(OSError) as cm:
+ Rootns((~int(RootnsFlag.ALL)) & 0xFFFFFFFF)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ def test_get_nsfd(self) -> None:
+ try:
+ rns = Rootns()
+ except OSError as exc:
+ if exc.errno in SKIP_ERRNOS:
+ self.skipTest(f"rootns() unavailable: {exc}")
+ raise
+ with rns:
+ for case in NS_TYPE_CASES:
+ with self.subTest(ns=case.name):
+ with self.closing_fd(rns.get_nsfd(case.nstype)) as nsfd:
+ self.assertEqual(
+ Sys.ioctl(nsfd, Ioctl.NS_GET_NSTYPE),
+ int(case.nstype),
+ )
+
+ with self.assertRaises(OSError) as cm:
+ rns.get_nsfd(CloneFlag.NEWPID)
+ self.assertEqual(cm.exception.errno, errno.ESRCH)
+
+ with self.assertRaises(OSError) as cm:
+ rns.get_nsfd(0)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with (
+ self.closing_fd(rns.get_nsfd(CloneFlag.NEWNS)) as mntns_fd,
+ self.closing_fd(rns.make_mount("tmpfs")) as rootfd,
+ ):
+ Sys.move_mount(
+ rootfd,
+ "",
+ mntns_fd,
+ "/",
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+
+ with SyncPipe.create() as hold:
+ pid = rns.run(hold.wait_in_child)
+ hold.close_read()
+ try:
+ with self.closing_fd(
+ rns.get_nsfd(CloneFlag.NEWPID)
+ ) as nsfd:
+ self.assertEqual(
+ Sys.ioctl(nsfd, Ioctl.NS_GET_NSTYPE),
+ int(CloneFlag.NEWPID),
+ )
+ finally:
+ hold.close_write()
+ self.assertEqual(self.reap_exit_code(pid), 0)
+
+ def test_wait_poll_and_clone_dead(self) -> None:
+ cell = self._require_cell()
+ rns = cell.rns
+
+ with self.assertRaises(OSError) as cm:
+ Sys.ioctl(rns.fd, Ioctl.ROOTNS_WAIT, 0)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.assertRaises(OSError) as cm:
+ rns.wait((~os.WNOHANG) & 0xFFFFFFFF)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ for wait_flags in (0, os.WNOHANG):
+ with self.assertRaises(OSError) as cm:
+ rns.wait(wait_flags)
+ self.assertEqual(cm.exception.errno, errno.ECHILD)
+
+ with SyncPipe.create() as hold:
+ pid = rns.run(lambda: hold.wait_in_child(42))
+ hold.close_read()
+
+ self.assertEqual(rns.wait(os.WNOHANG), WaitResult(0, 0))
+
+ def check_foreign_pidns_wait() -> None:
+ Sys.unshare(CloneFlag.NEWPID)
+
+ def check_inner_wait() -> None:
+ with self.assertRaises(OSError) as cm_w:
+ rns.wait(os.WNOHANG)
+ self.assertEqual(cm_w.exception.errno, errno.ECHILD)
+
+ self.run_forked(check_inner_wait)
+
+ self.run_forked(check_foreign_pidns_wait)
+ poller = select.poll()
+ poller.register(rns, select.POLLIN)
+ self.assertEqual(poller.poll(0), [])
+ with select.epoll() as ep1, select.epoll() as ep2:
+ ep1.register(rns, select.EPOLLIN | select.EPOLLEXCLUSIVE)
+ ep2.register(rns, select.EPOLLIN | select.EPOLLEXCLUSIVE)
+ self.assertEqual(ep1.poll(0), [])
+ self.assertEqual(ep2.poll(0), [])
+
+ hold.close_write()
+ events = poller.poll(5000)
+ self.assertTrue(any(ev & select.POLLHUP for _, ev in events))
+ ep1_ev = ep1.poll(5.0)
+ ep2_ev = ep2.poll(5.0)
+ self.assertTrue(any(ev & select.EPOLLHUP for _, ev in ep1_ev))
+ self.assertTrue(any(ev & select.EPOLLHUP for _, ev in ep2_ev))
+
+ res = rns.wait(os.WNOHANG)
+ self.assertEqual(res.pid, pid)
+ self.assertEqual(res.exit_code, 42)
+ self.assertEqual(self.reap_exit_code(pid), 42)
+
+ with self.assertRaises(OSError) as cm:
+ rns.clone_into()
+ self.assertEqual(cm.exception.errno, errno.ESRCH)
+
+ def test_kill_ioctl_and_kill_on_close(self) -> None:
+ cell = self._require_cell()
+ rns = cell.rns
+
+ for case in BAD_SIGNAL_CASES:
+ with self.subTest(sig=case.name):
+ with self.assertRaises(OSError) as cm:
+ rns.kill(case.sig)
+ self.assertEqual(cm.exception.errno, case.expected_errno)
+
+ with SyncPipe.create() as ready, SyncPipe.create() as hold:
+
+ def init_proc() -> int:
+ ready.close()
+ hold.close()
+ signal.pause()
+ return 0
+
+ def member_proc() -> int:
+ ready.close_read()
+ hold.close_read()
+ os.setsid()
+ gc = os.fork()
+ if gc == 0:
+ ready.write_bytes(b"r")
+ ready.close_write()
+ signal.pause()
+ os._exit(0)
+ ready.close_write()
+ signal.pause()
+ return 0
+
+ pid1 = rns.run(init_proc)
+ pid2 = rns.run(member_proc)
+ ready.close_write()
+ hold.close_write()
+
+ self.assertEqual(ready.read_bytes(), b"r")
+ ready.close_read()
+
+ rns.kill(0)
+ rns.kill(signal.SIGKILL)
+ self.assertEqual(hold.read_bytes(), b"")
+ hold.close_read()
+
+ self.assertEqual(
+ self.reap_exit_code(pid2), 128 + int(signal.SIGKILL)
+ )
+ self.assertEqual(
+ self.reap_exit_code(pid1), 128 + int(signal.SIGKILL)
+ )
+
+ with Cell("koc", flags=RootnsFlag.DEFAULT) as cell2:
+ cell2.setup_rootfs(mount_procfs=False)
+ pid_koc = cell2.rns.run(self.pause_forever)
+ self.assertEqual(
+ self.reap_exit_code(pid_koc), 128 + int(signal.SIGKILL)
+ )
+
+ def test_proc_submount_and_nested_namespaces(self) -> None:
+ cell = self._require_cell()
+ cell.mount_fs("tmpfs", "mnt")
+
+ def inside() -> int:
+ if os.getpid() != 1:
+ return 1
+ pids = [e for e in os.listdir("/proc") if e.isdigit()]
+ if pids != ["1"]:
+ return 2
+ with open("/mnt/hello", "wb") as f:
+ f.write(b"ok")
+ Sys.unshare(
+ CloneFlag.NEWUTS | CloneFlag.NEWIPC | CloneFlag.NEWNET
+ )
+ return 0
+
+ pid = cell.rns.run(inside)
+ res = cell.wait()
+ self.assertEqual(res.pid, pid)
+ self.assertEqual(res.exit_code, 0)
+ self.assertEqual(self.reap_exit_code(pid), 0)
+
+ def test_setns_owner_vs_foreign(self) -> None:
+ cell = self._require_cell()
+ with SyncPipe.create() as hold:
+ pid = cell.rns.run(hold.wait_in_child)
+ hold.close_read()
+ try:
+ with self.closing_fd(
+ os.open(f"/proc/{pid}/ns/uts", os.O_RDONLY | os.O_CLOEXEC)
+ ) as uts_fd:
+ self.run_forked(
+ lambda: Sys.setns(uts_fd, CloneFlag.NEWUTS)
+ )
+
+ if os.geteuid() == 0:
+
+ def check_foreign() -> None:
+ try:
+ self.drop_to_uid(1000)
+ except OSError:
+ return
+ with self.assertRaises(OSError) as cm_perm:
+ Sys.setns(uts_fd, CloneFlag.NEWUTS)
+ self.assertEqual(
+ cm_perm.exception.errno, errno.EPERM
+ )
+
+ self.run_forked(check_foreign)
+ finally:
+ hold.close_write()
+ self.reap_exit_code(pid)
+
+ def test_mount_and_fsconfig_validation(self) -> None:
+ self._require_cell()
+ with (
+ Rootns() as rns,
+ self.closing_fd(rns.get_nsfd(CloneFlag.NEWNS)) as mntns_fd,
+ ):
+ with self.assertRaises(OSError) as cm:
+ Sys.move_mount(
+ Sys.AT_FDCWD, "/", mntns_fd, "/", MoveMountFlag.T_MNTNS
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.assertRaises(OSError) as cm:
+ Sys.move_mount(
+ Sys.AT_FDCWD,
+ "/tmp",
+ Sys.AT_FDCWD,
+ "/tmp",
+ MoveMountFlag.CLONE,
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.assertRaises(OSError) as cm:
+ Sys.move_mount(
+ Sys.AT_FDCWD,
+ "/tmp",
+ mntns_fd,
+ "/",
+ MoveMountFlag.T_MNTNS
+ | MoveMountFlag.CLONE
+ | MoveMountFlag.SET_GROUP,
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.closing_fd(rns.make_mount("tmpfs")) as m1:
+ Sys.move_mount(
+ m1,
+ "",
+ mntns_fd,
+ "/",
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+
+ with self.closing_fd(rns.make_mount("tmpfs")) as m2:
+ for alias in ("/", "."):
+ with self.assertRaises(OSError) as cm:
+ Sys.move_mount(
+ m2,
+ "",
+ mntns_fd,
+ alias,
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+ self.assertEqual(cm.exception.errno, errno.EBUSY)
+ with self.assertRaises(OSError) as cm:
+ Sys.move_mount(
+ m2,
+ "",
+ mntns_fd,
+ ".",
+ MoveMountFlag.F_EMPTY_PATH
+ | MoveMountFlag.T_MNTNS
+ | MoveMountFlag.BENEATH,
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.closing_fd(Sys.fsopen("tmpfs")) as fsfd:
+ Sys.fsconfig(fsfd, FsconfigCmd.SET_ROOTNS, aux=rns.fd)
+ with self.assertRaises(OSError) as cm:
+ Sys.fsconfig(fsfd, FsconfigCmd.SET_ROOTNS, aux=rns.fd)
+ self.assertEqual(cm.exception.errno, errno.EBUSY)
+
+ with (
+ Rootns() as other_rns,
+ self.closing_fd(
+ other_rns.get_nsfd(CloneFlag.NEWNS)
+ ) as other_mntns,
+ self.closing_fd(rns.make_mount("tmpfs")) as bound_mfd,
+ ):
+ with self.assertRaises(OSError) as cm:
+ Sys.move_mount(
+ bound_mfd,
+ "",
+ other_mntns,
+ "/",
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.closing_fd(Sys.fsopen("proc")) as p_fsfd:
+ Sys.fsconfig(p_fsfd, FsconfigCmd.SET_ROOTNS, aux=rns.fd)
+ with self.assertRaises(OSError) as cm:
+ Sys.fsconfig(
+ p_fsfd,
+ FsconfigCmd.SET_STRING,
+ key="pidns",
+ value="/proc/self/ns/pid",
+ )
+ self.assertEqual(cm.exception.errno, errno.EBUSY)
+
+ with self.closing_fd(Sys.fsopen("proc")) as bad_proc:
+
+ def check_nonancestor_proc() -> None:
+ Sys.unshare(CloneFlag.NEWPID)
+
+ def check_inner() -> None:
+ with self.assertRaises(OSError) as cm_set:
+ Sys.fsconfig(
+ bad_proc, FsconfigCmd.SET_ROOTNS, aux=rns.fd
+ )
+ self.assertEqual(cm_set.exception.errno, errno.EINVAL)
+ with self.assertRaises(OSError) as cm_create:
+ Sys.fsconfig(bad_proc, FsconfigCmd.CMD_CREATE)
+ self.assertEqual(
+ cm_create.exception.errno, errno.EBUSY
+ )
+
+ self.run_forked(check_inner)
+
+ self.run_forked(check_nonancestor_proc)
+
+ with (
+ Rootns() as rns_lock,
+ self.closing_fd(
+ rns_lock.get_nsfd(CloneFlag.NEWNS)
+ ) as lock_mntns,
+ SyncPipe.create() as prop_ready,
+ SyncPipe.create() as prop_go,
+ ):
+ rns_lock.map_self_ugid()
+ with self.closing_fd(rns_lock.make_mount("tmpfs")) as rfd:
+ os.mkdir("host_sub", 0o755, dir_fd=rfd)
+ os.mkdir("prop_mnt", 0o755, dir_fd=rfd)
+ Sys.move_mount(
+ rfd,
+ "",
+ lock_mntns,
+ "/",
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+ Sys.move_mount(
+ Sys.AT_FDCWD,
+ "/tmp",
+ lock_mntns,
+ "host_sub",
+ MoveMountFlag.T_MNTNS | MoveMountFlag.CLONE,
+ )
+
+ def try_umount_locked() -> int:
+ prop_ready.close_read()
+ prop_go.close_write()
+ try:
+ Sys.umount2("/host_sub", UmountFlag.DETACH)
+ return 1
+ except OSError as exc:
+ if exc.errno != errno.EINVAL:
+ return 2
+ Sys.set_mount_propagation(
+ "/", MountFlag.REC | MountFlag.SHARED
+ )
+ peer = os.fork()
+ if peer == 0:
+ Sys.unshare(CloneFlag.NEWNS)
+ prop_ready.write_bytes(b"p")
+ prop_ready.close_write()
+ if prop_go.read_bytes() != b"g":
+ os._exit(3)
+ prop_go.close_read()
+ if not os.path.ismount("/prop_mnt"):
+ os._exit(4)
+ try:
+ Sys.umount2("/prop_mnt", UmountFlag.DETACH)
+ os._exit(5)
+ except OSError as exc:
+ os._exit(0 if exc.errno == errno.EINVAL else 6)
+ prop_ready.close_write()
+ prop_go.close_read()
+ return self.reap_exit_code(peer)
+
+ p_lock = rns_lock.run(try_umount_locked)
+ prop_ready.close_write()
+ prop_go.close_read()
+ self.assertEqual(prop_ready.read_bytes(), b"p")
+ Sys.move_mount(
+ Sys.AT_FDCWD,
+ "/tmp",
+ lock_mntns,
+ "prop_mnt",
+ MoveMountFlag.T_MNTNS | MoveMountFlag.CLONE,
+ )
+ prop_go.write_bytes(b"g")
+ prop_go.close_write()
+ self.assertEqual(self.reap_exit_code(p_lock), 0)
+
+ if os.geteuid() == 0:
+ u_rns = self.create_rootns_as_uid(1000)
+ if u_rns is not None:
+ with (
+ u_rns,
+ self.closing_fd(
+ u_rns.get_nsfd(CloneFlag.NEWNS)
+ ) as u_mntns,
+ ):
+ with self.closing_fd(
+ u_rns.make_mount("tmpfs")
+ ) as m_root:
+ Sys.move_mount(
+ m_root,
+ "",
+ u_mntns,
+ "/",
+ MoveMountFlag.F_EMPTY_PATH
+ | MoveMountFlag.T_MNTNS,
+ )
+
+ def check_attacker() -> None:
+ try:
+ self.drop_to_uid(2000)
+ except OSError:
+ return
+ with self.closing_fd(Sys.fsopen("tmpfs")) as fsfd2:
+ with self.assertRaises(OSError) as cm_fs:
+ Sys.fsconfig(
+ fsfd2,
+ FsconfigCmd.SET_ROOTNS,
+ aux=u_rns.fd,
+ )
+ self.assertEqual(
+ cm_fs.exception.errno, errno.EPERM
+ )
+ with self.assertRaises(OSError) as cm_clone:
+ u_rns.clone_into()
+ self.assertEqual(
+ cm_clone.exception.errno, errno.EPERM
+ )
+
+ self.run_forked(check_attacker)
+
+ def test_clone_flags_and_pidns_ancestry(self) -> None:
+ cell = self._require_cell()
+ rns = cell.rns
+
+ with Rootns() as empty_rns:
+ with self.assertRaises(OSError) as cm:
+ empty_rns.clone_into(CloneFlag.VFORK)
+ self.assertEqual(cm.exception.errno, errno.ENOENT)
+
+ with (
+ self.closing_fd(
+ empty_rns.get_nsfd(CloneFlag.NEWNS)
+ ) as e_mntns,
+ self.closing_fd(empty_rns.make_mount("tmpfs")) as e_root,
+ ):
+ Sys.move_mount(
+ e_root,
+ "",
+ e_mntns,
+ "/",
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+ with self.assertRaises(OSError) as cm:
+ empty_rns.clone_into(
+ CloneFlag.AUTOREAP, exit_signal=int(signal.SIGCHLD)
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ args = CloneArgs(
+ flags=int(CloneFlag.INTO_ROOTNS),
+ exit_signal=int(signal.SIGCHLD),
+ rootns=rns.fd,
+ )
+ with self.assertRaises(OSError) as cm:
+ Sys.clone3(args, size=CloneArgs.SIZE_VER2)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ for case in BAD_CLONE_CASES:
+ with self.subTest(flag=case.name):
+ with self.assertRaises(OSError) as cm:
+ rns.clone_into(
+ extra_flags=case.flags,
+ exit_signal=case.exit_signal,
+ )
+ self.assertEqual(cm.exception.errno, case.expected_errno)
+
+ allowed = (
+ CloneFlag.VFORK
+ | CloneFlag.PIDFD
+ | CloneFlag.CLEAR_SIGHAND
+ | CloneFlag.NNP
+ )
+ old_umask = os.umask(0o077)
+ try:
+ Sys.prctl(PrctlOp.SET_DUMPABLE, 1)
+ pid, pidfd = rns.clone_into(extra_flags=allowed)
+ if pid == 0:
+ cur_umask = os.umask(0o022)
+ dumpable = Sys.prctl(PrctlOp.GET_DUMPABLE)
+ ok = (
+ os.getpid() == 1
+ and Sys.prctl(PrctlOp.GET_NO_NEW_PRIVS) == 1
+ and cur_umask == 0o077
+ and dumpable != 1
+ )
+ os._exit(0 if ok else 1)
+ finally:
+ os.umask(old_umask)
+ self.assertGreaterEqual(pidfd, 0)
+ os.close(pidfd)
+ self.assertEqual(self.reap_exit_code(pid), 0)
+
+ with Cell("exdev") as cell2:
+ cell2.setup_rootfs(mount_procfs=False)
+
+ def check_exdev() -> None:
+ Sys.unshare(CloneFlag.NEWPID)
+
+ def check_inner() -> None:
+ with self.assertRaises(OSError) as cm_exdev:
+ cell2.rns.clone_into()
+ self.assertEqual(cm_exdev.exception.errno, errno.EXDEV)
+
+ self.run_forked(check_inner)
+
+ self.run_forked(check_exdev)
+
+ def test_concurrent_bootstrap(self) -> None:
+ cell = self._require_cell()
+ rns = cell.rns
+ with (
+ SyncPipe.create() as start,
+ SyncPipe.create() as ready,
+ SyncPipe.create() as init_gate,
+ SyncPipe.create() as peer_gate,
+ ):
+ workers: list[int] = []
+ for idx in range(4):
+ wpid = os.fork()
+ if wpid == 0:
+ start.close_write()
+ ready.close_read()
+ init_gate.close_write()
+ peer_gate.close_write()
+ start.read_bytes()
+ start.close_read()
+
+ def entrant(worker_idx: int = idx) -> int:
+ my_pid = os.getpid()
+ ready.write_bytes(bytes([worker_idx, my_pid]))
+ ready.close_write()
+ gate = init_gate if my_pid == 1 else peer_gate
+ gate.read_bytes()
+ init_gate.close_read()
+ peer_gate.close_read()
+ return 0
+
+ cpid = rns.run(entrant)
+ ready.close_write()
+ init_gate.close_read()
+ peer_gate.close_read()
+ os._exit(0 if self.reap_exit_code(cpid) == 0 else 1)
+ workers.append(wpid)
+
+ start.close_read()
+ ready.close_write()
+ init_gate.close_read()
+ peer_gate.close_read()
+ start.close_write()
+
+ seen_pids: set[int] = set()
+ init_idx = -1
+ for _ in range(4):
+ msg = ready.read_bytes(2)
+ self.assertEqual(len(msg), 2)
+ if msg[1] == 1:
+ init_idx = msg[0]
+ seen_pids.add(msg[1])
+ ready.close_read()
+
+ self.assertEqual(seen_pids, {1, 2, 3, 4})
+ self.assertGreaterEqual(init_idx, 0)
+
+ peer_gate.close_write()
+ for i, wpid in enumerate(workers):
+ if i != init_idx:
+ self.assertEqual(self.reap_exit_code(wpid), 0)
+ init_gate.close_write()
+ self.assertEqual(self.reap_exit_code(workers[init_idx]), 0)
+
+ res = cell.wait()
+ self.assertGreater(res.pid, 0)
+ self.assertEqual(res.exit_code, 0)
+
+ def test_pivot_root_and_standalone_mntns_hot_mount(self) -> None:
+ cell = self._require_cell()
+ with (
+ SyncPipe.create() as ready,
+ SyncPipe.create() as hold,
+ ):
+
+ def init_pivot() -> int:
+ ready.close_read()
+ hold.close_write()
+ with self.closing_fd(self.make_plain_mount("tmpfs")) as mfd:
+ os.mkdir("old_root", 0o755, dir_fd=mfd)
+ os.mkdir("sub", 0o755, dir_fd=mfd)
+ with self.closing_fd(
+ os.open(
+ "pivoted",
+ os.O_CREAT | os.O_WRONLY | os.O_CLOEXEC,
+ 0o644,
+ dir_fd=mfd,
+ )
+ ):
+ pass
+ Sys.move_mount(
+ mfd,
+ "",
+ Sys.AT_FDCWD,
+ "/mnt",
+ MoveMountFlag.F_EMPTY_PATH,
+ )
+ os.chdir("/mnt")
+ Sys.pivot_root(".", "old_root")
+ os.chdir("/")
+ Sys.umount2("/old_root", UmountFlag.DETACH)
+ ready.write_bytes(b"p")
+ ready.close_write()
+ hold.read_bytes()
+ hold.close_read()
+ return 0
+
+ pid1 = cell.rns.run(init_pivot)
+ ready.close_write()
+ hold.close_read()
+ try:
+ self.assertEqual(ready.read_bytes(), b"p")
+ ready.close_read()
+
+ cell.mount_fs("tmpfs", "sub")
+
+ pid2 = cell.rns.run(
+ lambda: (
+ 0
+ if os.path.exists("/pivoted")
+ and os.path.ismount("/sub")
+ else 1
+ ),
+ )
+ self.assertEqual(self.reap_exit_code(pid2), 0)
+ finally:
+ hold.close_write()
+ self.assertEqual(self.reap_exit_code(pid1), 0)
+
+ with SyncPipe.create() as ext_ready, SyncPipe.create() as ext_hold:
+ plain_pid = os.fork()
+ if plain_pid == 0:
+ ext_ready.close_read()
+ ext_hold.close_write()
+ try:
+ Sys.unshare(CloneFlag.NEWNS)
+ Sys.set_mount_propagation("/")
+ with self.closing_fd(
+ self.make_plain_mount("tmpfs")
+ ) as mfd:
+ Sys.move_mount(
+ mfd,
+ "",
+ Sys.AT_FDCWD,
+ "/tmp",
+ MoveMountFlag.F_EMPTY_PATH,
+ )
+ os.mkdir("/tmp/target", 0o755)
+ ext_ready.write_bytes(b"r")
+ ext_ready.close_write()
+ ext_hold.read_bytes()
+ ext_hold.close_read()
+ os._exit(0 if os.path.ismount("/tmp/target") else 2)
+ except BaseException:
+ os._exit(1)
+ ext_ready.close_write()
+ ext_hold.close_read()
+ try:
+ self.assertEqual(ext_ready.read_bytes(), b"r")
+ ext_ready.close_read()
+ with (
+ self.closing_fd(
+ os.open(
+ f"/proc/{plain_pid}/ns/mnt",
+ os.O_RDONLY | os.O_CLOEXEC,
+ )
+ ) as ext_mntns,
+ self.closing_fd(self.make_plain_mount("tmpfs")) as mfd,
+ ):
+ with self.assertRaises(OSError) as cm:
+ Sys.move_mount(
+ mfd,
+ "",
+ ext_mntns,
+ "tmp/..",
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+ self.assertEqual(cm.exception.errno, errno.EBUSY)
+ with self.assertRaises(OSError) as cm:
+ Sys.move_mount(
+ mfd,
+ "",
+ ext_mntns,
+ "tmp/..",
+ MoveMountFlag.F_EMPTY_PATH
+ | MoveMountFlag.T_MNTNS
+ | MoveMountFlag.BENEATH,
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+ Sys.move_mount(
+ mfd,
+ "",
+ ext_mntns,
+ "tmp/target",
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+ finally:
+ ext_hold.close_write()
+ self.assertEqual(self.reap_exit_code(plain_pid), 0)
+
+ def test_userns_set_idmap(self) -> None:
+ self._require_cell()
+ with (
+ Rootns() as rns,
+ self.closing_fd(rns.get_nsfd(CloneFlag.NEWUSER)) as userns_fd,
+ self.closing_fd(rns.get_nsfd(CloneFlag.NEWNS)) as mntns_fd,
+ ):
+ with self.assertRaises(OSError) as cm:
+ Sys.userns_set_idmap_raw(-1, 0)
+ self.assertEqual(cm.exception.errno, errno.EBADF)
+
+ with self.assertRaises(OSError) as cm:
+ Sys.userns_set_idmap_raw(userns_fd, 0)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.assertRaises(OSError) as cm:
+ Sys.set_userns_idmap(
+ userns_fd,
+ uid_extents=((0, os.geteuid(), 1),),
+ size=UsernsIdmap.SIZE_VER0 - 1,
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.assertRaises(OSError) as cm:
+ Sys.set_userns_idmap(
+ userns_fd,
+ uid_extents=((0, os.geteuid(), 1),),
+ sys_flags=1,
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.assertRaises(OSError) as cm:
+ Sys.set_userns_idmap(
+ rns.fd,
+ uid_extents=((0, os.geteuid(), 1),),
+ deny_setgroups=True,
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.assertRaises(OSError) as cm:
+ Sys.set_userns_idmap(
+ mntns_fd,
+ uid_extents=((0, os.geteuid(), 1),),
+ deny_setgroups=True,
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.assertRaises(OSError) as cm:
+ Sys.set_userns_idmap(userns_fd)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.assertRaises(OSError) as cm:
+ Sys.set_userns_idmap(
+ userns_fd,
+ extra_flags=(~int(UsernsIdmapFlag.ALL)) & 0xFFFFFFFF,
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.assertRaises(OSError) as cm:
+ Sys.set_userns_idmap(
+ userns_fd,
+ uid_extents=((0, os.geteuid(), 0),),
+ deny_setgroups=True,
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ rns.map_self_ugid()
+ with self.assertRaises(OSError) as cm:
+ rns.map_self_ugid()
+ self.assertEqual(cm.exception.errno, errno.EPERM)
+
+ with self.closing_fd(rns.make_mount("tmpfs")) as rootfd:
+ os.mkdir("proc", 0o755, dir_fd=rootfd)
+ Sys.move_mount(
+ rootfd,
+ "",
+ mntns_fd,
+ "/",
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+ with self.closing_fd(rns.make_mount("proc")) as pfd:
+ Sys.move_mount(
+ pfd,
+ "",
+ mntns_fd,
+ "proc",
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+
+ def verify_idmap() -> int:
+ if os.geteuid() != 0 or os.getegid() != 0:
+ return 1
+ with open("/proc/self/setgroups", "rb") as f:
+ if f.read() != b"deny\n":
+ return 2
+ return 0
+
+ pid = rns.run(verify_idmap)
+ res = rns.wait()
+ self.assertEqual(res.pid, pid)
+ self.assertEqual(res.exit_code, 0)
+ self.assertEqual(self.reap_exit_code(pid), 0)
+
+ def test_userns_set_idmap_delegation(self) -> None:
+ self._require_cell()
+ if os.geteuid() != 0:
+ self.skipTest("uidmapd delegation test requires root")
+
+ rns1 = self.create_rootns_as_uid(1000)
+ rns2 = self.create_rootns_as_uid(1000)
+ if rns1 is None or rns2 is None:
+ if rns1 is not None:
+ rns1.close()
+ if rns2 is not None:
+ rns2.close()
+ self.skipTest("unprivileged rootns creation unavailable")
+
+ with rns1, rns2:
+ s_main, s_alice = socket.socketpair(
+ socket.AF_UNIX, socket.SOCK_DGRAM
+ )
+ alice_pid = os.fork()
+ if alice_pid == 0:
+ s_main.close()
+ try:
+ self.drop_to_uid(1000)
+ with self.closing_fd(
+ rns1.get_nsfd(CloneFlag.NEWUSER)
+ ) as ufd1:
+ socket.send_fds(s_alice, [b"A"], [ufd1])
+ os._exit(0)
+ except BaseException:
+ os._exit(1)
+ finally:
+ s_alice.close()
+ s_alice.close()
+ _, alice_fds, _, _ = socket.recv_fds(s_main, 1, 1)
+ s_main.close()
+ self.assertEqual(self.reap_exit_code(alice_pid), 0)
+
+ with (
+ self.closing_fd(alice_fds[0]) as alice_ufd,
+ self.closing_fd(rns2.get_nsfd(CloneFlag.NEWUTS)) as uts2_fd,
+ ):
+ s_m1, s_m2 = socket.socketpair(
+ socket.AF_UNIX, socket.SOCK_DGRAM
+ )
+ mal_pid = os.fork()
+ if mal_pid == 0:
+ s_m1.close()
+ try:
+ self.drop_to_uid(2000)
+ with self.closing_fd(
+ Sys.ioctl(uts2_fd, Ioctl.NS_GET_USERNS)
+ ) as bad_ufd:
+ socket.send_fds(s_m2, [b"M"], [bad_ufd])
+ os._exit(0)
+ except BaseException:
+ os._exit(1)
+ finally:
+ s_m2.close()
+ s_m2.close()
+ _, mal_fds, _, _ = socket.recv_fds(s_m1, 1, 1)
+ s_m1.close()
+ self.assertEqual(self.reap_exit_code(mal_pid), 0)
+
+ with self.closing_fd(mal_fds[0]) as mallory_ufd:
+
+ def run_uidmapd() -> None:
+ try:
+ Sys.drop_to_setid_helper(990)
+ except OSError as exc:
+ if exc.errno in SKIP_ERRNOS:
+ self.skipTest(f"setid helper setup: {exc}")
+ raise
+
+ with self.assertRaises(OSError) as cm_bad:
+ Sys.set_userns_idmap(
+ mallory_ufd,
+ uid_extents=((0, 1000, 1),),
+ deny_setgroups=True,
+ )
+ self.assertEqual(cm_bad.exception.errno, errno.EPERM)
+
+ with self.assertRaises(OSError) as cm_root:
+ Sys.set_userns_idmap(
+ alice_ufd,
+ uid_extents=((0, 0, 1),),
+ deny_setgroups=True,
+ )
+ self.assertEqual(cm_root.exception.errno, errno.EPERM)
+
+ Sys.set_userns_idmap(
+ alice_ufd,
+ uid_extents=((0, 1000, 1), (1, 2000, 1)),
+ gid_extents=((0, 1000, 1), (1, 2000, 1)),
+ deny_setgroups=True,
+ )
+
+ self.run_forked(run_uidmapd)
+
+ def verify_as_alice() -> None:
+ self.drop_to_uid(1000)
+ with (
+ self.closing_fd(
+ rns1.get_nsfd(CloneFlag.NEWNS)
+ ) as mntns_fd,
+ self.closing_fd(rns1.make_mount("tmpfs")) as rootfd,
+ ):
+ Sys.move_mount(
+ rootfd,
+ "",
+ mntns_fd,
+ "/",
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+
+ def switch_subuid() -> int:
+ os.setresgid(1, 1, 1)
+ os.setresuid(1, 1, 1)
+ return 0 if os.geteuid() == 1 and os.getegid() == 1 else 1
+
+ pid = rns1.run(switch_subuid)
+ res = rns1.wait()
+ self.assertEqual(res.pid, pid)
+ self.assertEqual(res.exit_code, 0)
+ self.assertEqual(self.reap_exit_code(pid), 0)
+
+ self.run_forked(verify_as_alice)
+
+ def test_unprivileged_without_entering_userns(self) -> None:
+ def worker() -> None:
+ if os.geteuid() == 0:
+ try:
+ self.drop_to_uid(1000)
+ except OSError as exc:
+ if exc.errno == errno.EINVAL:
+ self.skipTest("uid 1000 unmapped in current userns")
+ raise
+
+ try:
+ tfd = Sys.fsopen("tmpfs")
+ except OSError as exc:
+ self.assertEqual(exc.errno, errno.EPERM)
+ else:
+ with self.closing_fd(tfd):
+ with self.assertRaises(OSError) as cm_create:
+ Sys.fsconfig(tfd, FsconfigCmd.CMD_CREATE)
+ self.assertEqual(cm_create.exception.errno, errno.EPERM)
+
+ with self.assertRaises(OSError) as cm_ot:
+ Sys.open_tree(
+ Sys.AT_FDCWD,
+ "/tmp",
+ OpenTreeFlag.CLONE | OpenTreeFlag.CLOEXEC,
+ )
+ self.assertEqual(cm_ot.exception.errno, errno.EPERM)
+
+ try:
+ cell = Cell("unpriv", flags=RootnsFlag.DEFAULT)
+ except OSError as exc:
+ if exc.errno in SKIP_ERRNOS:
+ self.skipTest("unprivileged rootns unavailable")
+ raise
+
+ with (
+ tempfile.TemporaryDirectory(prefix="rootns-unpriv-") as hdir,
+ cell,
+ ):
+ os.chmod(hdir, 0o755)
+ with open(os.path.join(hdir, "hello"), "wb") as f:
+ f.write(b"unpriv-ok\n")
+ cell.setup_rootfs(
+ dirs=("proc", "tmp", "mnt"), mount_procfs=True
+ )
+ cell.bind_mount(hdir, "mnt")
+
+ def unpriv_init() -> int:
+ if (
+ os.getpid() != 1
+ or os.geteuid() != 0
+ or os.getegid() != 0
+ ):
+ return 1
+ pids = [e for e in os.listdir("/proc") if e.isdigit()]
+ if pids != ["1"]:
+ return 2
+ with open("/mnt/hello", "rb") as hf:
+ if hf.read() != b"unpriv-ok\n":
+ return 3
+ try:
+ Sys.umount2("/mnt", UmountFlag.DETACH)
+ return 4
+ except OSError as exc:
+ return 0 if exc.errno == errno.EINVAL else 5
+
+ pid = cell.rns.run(unpriv_init)
+ res = cell.wait()
+ self.assertEqual(res.pid, pid)
+ self.assertEqual(res.exit_code, 0)
+ self.assertEqual(self.reap_exit_code(pid), 0)
+
+ self.run_forked(worker)
+
+class KtapTestResult(unittest.TestResult):
+ def __init__(self, ksft_mod: Any) -> None:
+ super().__init__()
+ self._ksft = ksft_mod
+ self._failed = False
+
+ @staticmethod
+ def _test_name(test: unittest.TestCase) -> str:
+ return f"{type(test).__name__}.{test._testMethodName}"
+
+ def _print_diag(self, text: str) -> None:
+ for line in text.rstrip().splitlines():
+ self._ksft.print_msg(line)
+
+ def _print_err(
+ self,
+ test: unittest.TestCase,
+ err: (
+ tuple[type[BaseException], BaseException, TracebackType]
+ | tuple[None, None, None]
+ ),
+ ) -> None:
+ formatted = "".join(traceback.format_exception(*err))
+ self._print_diag(f"{test.id()}:\n{formatted}")
+
+ def startTest(self, test: unittest.TestCase) -> None:
+ super().startTest(test)
+ self._failed = False
+
+ def stopTest(self, test: unittest.TestCase) -> None:
+ if self._failed:
+ self._ksft.test_result_fail(self._test_name(test))
+ super().stopTest(test)
+
+ def addSuccess(self, test: unittest.TestCase) -> None:
+ super().addSuccess(test)
+ self._ksft.test_result_pass(self._test_name(test))
+
+ def addSkip(self, test: unittest.TestCase, reason: str) -> None:
+ super().addSkip(test, reason)
+ name = self._test_name(test)
+ if reason:
+ self._print_diag(f"{name}: {reason}")
+ self._ksft.test_result_skip(name)
+
+ def addFailure(
+ self,
+ test: unittest.TestCase,
+ err: (
+ tuple[type[BaseException], BaseException, TracebackType]
+ | tuple[None, None, None]
+ ),
+ ) -> None:
+ super().addFailure(test, err)
+ self._print_err(test, err)
+ self._failed = True
+
+ def addError(
+ self,
+ test: unittest.TestCase,
+ err: (
+ tuple[type[BaseException], BaseException, TracebackType]
+ | tuple[None, None, None]
+ ),
+ ) -> None:
+ super().addError(test, err)
+ self._print_err(test, err)
+ self._failed = True
+
+ def addSubTest(
+ self,
+ test: unittest.TestCase,
+ subtest: unittest.TestCase,
+ err: (
+ tuple[type[BaseException], BaseException, TracebackType]
+ | tuple[None, None, None]
+ | None
+ ),
+ ) -> None:
+ super().addSubTest(test, subtest, err)
+ if err is not None:
+ self._print_err(subtest, err)
+ self._failed = True
+
+
+class KtapRunner:
+ @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")
+
+ @classmethod
+ def main(cls, argv: Sequence[str] | None = None) -> NoReturn:
+ args = list(sys.argv[1:] if argv is None else argv)
+ loader = unittest.TestLoader()
+ module = sys.modules[__name__]
+ suite = (
+ loader.loadTestsFromNames(args, module)
+ if args
+ else loader.loadTestsFromModule(module)
+ )
+ ksft = cls._load_ksft()
+ total = suite.countTestCases()
+ ksft.print_header()
+ ksft.set_plan(total)
+ result = KtapTestResult(ksft)
+ suite.run(result)
+ ksft.print_cnts()
+ sys.stdout.flush()
+ counts: dict[str, int] = ksft.ksft_cnt
+ if counts["fail"] > 0:
+ code = int(ksft.KSFT_FAIL)
+ elif total == 0 or (counts["pass"] == 0 and counts["skip"] > 0):
+ code = int(ksft.KSFT_SKIP)
+ else:
+ code = int(ksft.KSFT_PASS)
+ sys.exit(code)
+
+
+if __name__ == "__main__":
+ KtapRunner.main()
diff --git a/tools/testing/selftests/rootns/test_smoke.sh b/tools/testing/selftests/rootns/test_smoke.sh
new file mode 100755
index 000000000000..729e0c275602
--- /dev/null
+++ b/tools/testing/selftests/rootns/test_smoke.sh
@@ -0,0 +1,10 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0
+
+# Kselftest framework requirement - SKIP code is 4.
+ksft_skip=4
+
+command -v python3 >/dev/null 2>&1 || exit $ksft_skip
+
+DIR="$(dirname "$(readlink -f "$0")")"
+exec python3 "$DIR/rootns_test.py" "$@"
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread* [RFC PATCH v5 25/25] MAINTAINERS: Add entry for ROOT NAMESPACE
2026-11-21 0:08 [RFC PATCH v5 00/25] rootns: fd-bound process closures Jarkko Sakkinen
` (23 preceding siblings ...)
2026-11-21 0:08 ` [RFC PATCH v5 24/25] selftests/rootns: Add root namespace test suite Jarkko Sakkinen
@ 2026-11-21 0:08 ` Jarkko Sakkinen
24 siblings, 0 replies; 33+ messages in thread
From: Jarkko Sakkinen @ 2026-11-21 0:08 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, linux-api, linux-doc, linux-kernel,
linux-kselftest, linux-mm, linux-security-module,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Christian Brauner, David Howells, Jan Kara, Jonathan Corbet,
Josef Bacik, Kees Cook, Neal Gompa, Paul Moore, Serge Hallyn,
Zygmunt Krynicki
Record maintainership and mailing list routing for the root namespace
subsystem across its 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 7cbce21ba45a..072be5ec7fd8 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -24533,6 +24533,17 @@ F: include/linux/mfd/rohm-bd96802.h
F: include/linux/mfd/rohm-generic.h
F: include/linux/mfd/rohm-shared.h
+ROOT NAMESPACE
+M: David Howells <dhowells@redhat.com>
+M: Jarkko Sakkinen <jarkko@kernel.org>
+L: linux-fsdevel@vger.kernel.org
+S: Maintained
+F: Documentation/userspace-api/rootns.rst
+F: include/linux/rootns.h
+F: include/uapi/linux/rootns.h
+F: kernel/rootns.c
+F: tools/testing/selftests/rootns/
+
ROTATION DRIVER FOR ALLWINNER A83T
M: Jernej Skrabec <jernej.skrabec@gmail.com>
L: linux-media@vger.kernel.org
--
2.47.3
^ permalink raw reply [flat|nested] 33+ messages in thread