* [RFC PATCH v7 01/26] userns: Factor out idmap validation and commit helpers
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 02/26] userns: Add userns_set_idmap() system call Jarkko Sakkinen
` (24 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
map_write() and its permission helpers validate extent ranges, check
root and unprivileged self-mappings, translate parent ID ranges, sort
extents, and install the resulting map inline for procfs text writes,
preventing non-procfs callers from reusing the same validation and
commit path.
Extract idmap_maps_root(), unpriv_idmap_permitted(),
validate_and_insert_extent(), free_new_idmap(), resolve_new_idmap(), and
commit_new_idmap() with no functional change.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
kernel/user_namespace.c | 229 +++++++++++++++++++++-------------------
1 file changed, 122 insertions(+), 107 deletions(-)
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index cd748e1cbace..caba2ac33077 100644
--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -884,6 +884,22 @@ VISIBLE_IF_KUNIT int uid_gid_map_sort(struct uid_gid_map *map)
}
EXPORT_SYMBOL_IF_KUNIT(uid_gid_map_sort);
+static bool idmap_maps_root(const struct uid_gid_map *new_map)
+{
+ unsigned int idx;
+
+ for (idx = 0; idx < new_map->nr_extents; idx++) {
+ const struct uid_gid_extent *e;
+
+ if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
+ e = &new_map->extent[idx];
+ else
+ e = &new_map->forward[idx];
+ if (e->lower_first == 0)
+ return true;
+ }
+ return false;
+}
/**
* verify_root_map() - check the uid 0 mapping
* @file: idmapping file
@@ -900,22 +916,9 @@ static bool verify_root_map(const struct file *file,
struct user_namespace *map_ns,
struct uid_gid_map *new_map)
{
- int idx;
const struct user_namespace *file_ns = file->f_cred->user_ns;
- struct uid_gid_extent *extent0 = NULL;
-
- for (idx = 0; idx < new_map->nr_extents; idx++) {
- if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
- extent0 = &new_map->extent[idx];
- else
- extent0 = &new_map->forward[idx];
- if (extent0->lower_first == 0)
- break;
-
- extent0 = NULL;
- }
- if (!extent0)
+ if (!idmap_maps_root(new_map))
return true;
if (map_ns == file_ns) {
@@ -938,6 +941,103 @@ static bool verify_root_map(const struct file *file,
return true;
}
+static int validate_and_insert_extent(struct uid_gid_map *new_map,
+ struct uid_gid_extent *extent)
+{
+ if ((extent->first == (u32)-1) || (extent->lower_first == (u32)-1))
+ return -EINVAL;
+
+ if ((extent->first + extent->count) <= extent->first)
+ return -EINVAL;
+ if ((extent->lower_first + extent->count) <= extent->lower_first)
+ return -EINVAL;
+
+ if (mappings_overlap(new_map, extent))
+ return -EINVAL;
+
+ if (new_map->nr_extents >= UID_GID_MAP_MAX_EXTENTS)
+ return -EINVAL;
+
+ return uid_gid_map_insert_extent(new_map, extent);
+}
+
+static void free_new_idmap(struct uid_gid_map *new_map)
+{
+ if (new_map->nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
+ kfree(new_map->forward);
+ kfree(new_map->reverse);
+ }
+ memset(new_map, 0, sizeof(*new_map));
+}
+
+static int resolve_new_idmap(struct uid_gid_map *new_map,
+ struct uid_gid_map *parent_map)
+{
+ unsigned int idx;
+
+ if (new_map->nr_extents == 0)
+ return -EINVAL;
+
+ for (idx = 0; idx < new_map->nr_extents; idx++) {
+ struct uid_gid_extent *e;
+ u32 lower_first;
+
+ if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
+ e = &new_map->extent[idx];
+ else
+ e = &new_map->forward[idx];
+
+ lower_first = map_id_range_down(parent_map,
+ e->lower_first,
+ e->count);
+ if (lower_first == (u32)-1)
+ return -EPERM;
+
+ e->lower_first = lower_first;
+ }
+
+ return uid_gid_map_sort(new_map);
+}
+
+static void commit_new_idmap(struct uid_gid_map *map,
+ struct uid_gid_map *new_map)
+{
+ if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) {
+ memcpy(map->extent, new_map->extent,
+ new_map->nr_extents * sizeof(new_map->extent[0]));
+ } else {
+ map->forward = new_map->forward;
+ map->reverse = new_map->reverse;
+ }
+ /*
+ * Pairs with smp_rmb() in map_id_range_down(), map_id_range_up(),
+ * and m_start().
+ */
+ smp_wmb();
+ map->nr_extents = new_map->nr_extents;
+ memset(new_map, 0, sizeof(*new_map));
+}
+
+static bool unpriv_idmap_permitted(const struct user_namespace *ns,
+ const struct cred *cred, int cap_setid,
+ unsigned long ns_flags,
+ const struct uid_gid_map *new_map)
+{
+ u32 id;
+
+ if (new_map->nr_extents != 1 || new_map->extent[0].count != 1 ||
+ !uid_eq(ns->owner, cred->euid))
+ return false;
+
+ id = new_map->extent[0].lower_first;
+ if (cap_setid == CAP_SETUID)
+ return uid_eq(make_kuid(ns->parent, id), cred->euid);
+ if (cap_setid == CAP_SETGID)
+ return !(ns_flags & USERNS_SETGROUPS_ALLOWED) &&
+ gid_eq(make_kgid(ns->parent, id), cred->egid);
+ return false;
+}
+
/*
* Parse the decimal u32 at *pos, up to the next whitespace or NUL, and
* leave *pos pointing at that character.
@@ -966,8 +1066,7 @@ static ssize_t map_write(struct file *file, const char __user *buf,
{
struct seq_file *seq = file->private_data;
struct user_namespace *map_ns = seq->private;
- struct uid_gid_map new_map;
- unsigned idx;
+ struct uid_gid_map new_map = {};
struct uid_gid_extent extent;
char *kbuf, *pos, *next_line;
ssize_t ret;
@@ -1002,8 +1101,6 @@ static ssize_t map_write(struct file *file, const char __user *buf,
*/
mutex_lock(&userns_state_mutex);
- memset(&new_map, 0, sizeof(struct uid_gid_map));
-
ret = -EPERM;
/* Only allow one successful write to the map */
if (map->nr_extents != 0)
@@ -1052,98 +1149,28 @@ static ssize_t map_write(struct file *file, const char __user *buf,
if (*pos != '\0')
goto out;
- /* Verify we have been given valid starting values */
- if ((extent.first == (u32) -1) ||
- (extent.lower_first == (u32) -1))
- goto out;
-
- /* Verify count is not zero and does not cause the
- * extent to wrap
- */
- if ((extent.first + extent.count) <= extent.first)
- goto out;
- if ((extent.lower_first + extent.count) <=
- extent.lower_first)
- goto out;
-
- /* Do the ranges in extent overlap any previous extents? */
- if (mappings_overlap(&new_map, &extent))
- goto out;
-
- if ((new_map.nr_extents + 1) == UID_GID_MAP_MAX_EXTENTS &&
- (next_line != NULL))
- goto out;
-
- ret = uid_gid_map_insert_extent(&new_map, &extent);
+ ret = validate_and_insert_extent(&new_map, &extent);
if (ret < 0)
goto out;
ret = -EINVAL;
}
- /* Be very certain the new map actually exists */
+
if (new_map.nr_extents == 0)
goto out;
ret = -EPERM;
- /* Validate the user is allowed to use user id's mapped to. */
if (!new_idmap_permitted(file, map_ns, cap_setid, &new_map))
goto out;
- ret = -EPERM;
- /* Map the lower ids from the parent user namespace to the
- * kernel global id space.
- */
- for (idx = 0; idx < new_map.nr_extents; idx++) {
- struct uid_gid_extent *e;
- u32 lower_first;
-
- if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
- e = &new_map.extent[idx];
- else
- e = &new_map.forward[idx];
-
- lower_first = map_id_range_down(parent_map,
- e->lower_first,
- e->count);
-
- /* Fail if we can not map the specified extent to
- * the kernel global id space.
- */
- if (lower_first == (u32) -1)
- goto out;
-
- e->lower_first = lower_first;
- }
-
- /*
- * If we want to use binary search for lookup, this clones the extent
- * array and sorts both copies.
- */
- ret = uid_gid_map_sort(&new_map);
+ ret = resolve_new_idmap(&new_map, parent_map);
if (ret < 0)
goto out;
- /* Install the map */
- if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) {
- memcpy(map->extent, new_map.extent,
- new_map.nr_extents * sizeof(new_map.extent[0]));
- } else {
- map->forward = new_map.forward;
- map->reverse = new_map.reverse;
- }
- smp_wmb();
- map->nr_extents = new_map.nr_extents;
-
+ commit_new_idmap(map, &new_map);
*ppos = count;
ret = count;
out:
- if (ret < 0 && new_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
- kfree(new_map.forward);
- kfree(new_map.reverse);
- map->forward = NULL;
- map->reverse = NULL;
- map->nr_extents = 0;
- }
-
+ free_new_idmap(&new_map);
mutex_unlock(&userns_state_mutex);
kfree(kbuf);
return ret;
@@ -1213,20 +1240,8 @@ static bool new_idmap_permitted(const struct file *file,
/* Don't allow mappings that would allow anything that wouldn't
* be allowed without the establishment of unprivileged mappings.
*/
- if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1) &&
- uid_eq(ns->owner, cred->euid)) {
- u32 id = new_map->extent[0].lower_first;
- if (cap_setid == CAP_SETUID) {
- kuid_t uid = make_kuid(ns->parent, id);
- if (uid_eq(uid, cred->euid))
- return true;
- } else if (cap_setid == CAP_SETGID) {
- kgid_t gid = make_kgid(ns->parent, id);
- if (!(ns->flags & USERNS_SETGROUPS_ALLOWED) &&
- gid_eq(gid, cred->egid))
- return true;
- }
- }
+ if (unpriv_idmap_permitted(ns, cred, cap_setid, ns->flags, new_map))
+ return true;
/* Allow anyone to set a mapping that doesn't require privilege */
if (!cap_valid(cap_setid))
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 02/26] userns: Add userns_set_idmap() system call
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 01/26] userns: Factor out idmap validation and commit helpers Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 03/26] arch: Wire up " Jarkko Sakkinen
` (23 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
Configuring UID, GID, and project ID mappings currently requires writing
formatted text to /proc/<pid>/{uid_map,gid_map,projid_map,setgroups},
which depends on a live task in /proc and enforces write(2) file-opener
CAP_SETUID/CAP_SETGID checks that prevent passing an unprivileged userns
file descriptor over SCM_RIGHTS to a dedicated CAP_SETUID/CAP_SETGID
mapping helper.
Add userns_set_idmap() to atomically configure setgroups policy and UID,
GID, and project ID extents directly on a CLONE_NEWUSER nsfs file
descriptor. Expose USERNS_SETGROUPS_ALLOWED in uapi/linux/nsfs.h as the
flags bitmask when installing a GID mapping so setgroups(2) is disabled
by default unless explicitly preserved. Require CAP_SYS_ADMIN over the
target user namespace in either the caller's or the file opener's
credentials, and check parent ID-range capabilities strictly against the
caller's credentials.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
include/linux/syscalls.h | 4 +
include/linux/user_namespace.h | 2 -
include/uapi/linux/nsfs.h | 46 +++++++
kernel/sys_ni.c | 1 +
kernel/user_namespace.c | 226 +++++++++++++++++++++++++++++++++
5 files changed, 277 insertions(+), 2 deletions(-)
diff --git a/include/linux/syscalls.h b/include/linux/syscalls.h
index 552d9710a0d5..72308cc11908 100644
--- a/include/linux/syscalls.h
+++ b/include/linux/syscalls.h
@@ -77,6 +77,7 @@ struct cachestat;
struct statmount;
struct mnt_id_req;
struct ns_id_req;
+struct userns_idmap;
struct xattr_args;
struct file_attr;
@@ -909,6 +910,9 @@ asmlinkage long sys_clock_adjtime32(clockid_t which_clock,
struct old_timex32 __user *tx);
asmlinkage long sys_syncfs(int fd);
asmlinkage long sys_setns(int fd, int nstype);
+asmlinkage long sys_userns_set_idmap(int fd,
+ const struct userns_idmap __user *map,
+ size_t size, unsigned int flags);
asmlinkage long sys_pidfd_open(pid_t pid, unsigned int flags);
asmlinkage long sys_sendmmsg(int fd, struct mmsghdr __user *msg,
unsigned int vlen, unsigned flags);
diff --git a/include/linux/user_namespace.h b/include/linux/user_namespace.h
index 91232053775d..b4a50edfe003 100644
--- a/include/linux/user_namespace.h
+++ b/include/linux/user_namespace.h
@@ -35,8 +35,6 @@ struct uid_gid_map { /* 64 bytes -- 1 cache line */
};
};
-#define USERNS_SETGROUPS_ALLOWED 1UL
-
#define USERNS_INIT_FLAGS USERNS_SETGROUPS_ALLOWED
struct ucounts;
diff --git a/include/uapi/linux/nsfs.h b/include/uapi/linux/nsfs.h
index e5909266ec3f..f919b19a2c74 100644
--- a/include/uapi/linux/nsfs.h
+++ b/include/uapi/linux/nsfs.h
@@ -44,6 +44,52 @@ struct mnt_ns_info {
#define NS_GET_MNTNS_ID _IOR(NSIO, 5, __u64)
#define NS_GET_ID _IOR(NSIO, 13, __u64)
+/**
+ * struct userns_idmap_extent - Single ID mapping range for userns_set_idmap()
+ * @first: First ID inside the target user namespace.
+ * @lower_first: First ID inside the parent user namespace.
+ * @count: Number of consecutive IDs in the range.
+ * @reserved: Reserved for future use; must be zero.
+ */
+struct userns_idmap_extent {
+ __u32 first;
+ __u32 lower_first;
+ __u32 count;
+ __u32 reserved;
+};
+
+/**
+ * enum userns_flags - User namespace flags
+ * @USERNS_SETGROUPS_ALLOWED: Allow setgroups(2) inside the user namespace
+ * once its GID mapping is established.
+ */
+enum userns_flags {
+ USERNS_SETGROUPS_ALLOWED = (1 << 0),
+};
+
+/**
+ * struct userns_idmap - Arguments for userns_set_idmap()
+ * @nr_uid_extents: Number of entries in @uid_extents.
+ * @nr_gid_extents: Number of entries in @gid_extents.
+ * @nr_projid_extents: Number of entries in @projid_extents.
+ * @reserved: Reserved for future use; must be zero.
+ * @uid_extents: User pointer to array of &struct userns_idmap_extent for UIDs.
+ * @gid_extents: User pointer to array of &struct userns_idmap_extent for GIDs.
+ * @projid_extents: User pointer to array of &struct userns_idmap_extent for
+ * project IDs.
+ */
+struct userns_idmap {
+ __u32 nr_uid_extents;
+ __u32 nr_gid_extents;
+ __u32 nr_projid_extents;
+ __u32 reserved;
+ __aligned_u64 uid_extents;
+ __aligned_u64 gid_extents;
+ __aligned_u64 projid_extents;
+};
+
+#define USERNS_IDMAP_SIZE_VER0 40 /* sizeof first published struct */
+
enum init_ns_ino {
IPC_NS_INIT_INO = 0xEFFFFFFFU,
UTS_NS_INIT_INO = 0xEFFFFFFEU,
diff --git a/kernel/sys_ni.c b/kernel/sys_ni.c
index c8be0abaa407..e3202e7cc2a1 100644
--- a/kernel/sys_ni.c
+++ b/kernel/sys_ni.c
@@ -172,6 +172,7 @@ COND_SYSCALL_COMPAT(fadvise64_64);
COND_SYSCALL(lsm_get_self_attr);
COND_SYSCALL(lsm_set_self_attr);
COND_SYSCALL(lsm_list_modules);
+COND_SYSCALL(userns_set_idmap);
/* CONFIG_MMU only */
COND_SYSCALL(swapon);
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index caba2ac33077..61dcf2fab6f0 100644
--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -22,7 +22,11 @@
#include <linux/fs_struct.h>
#include <linux/bsearch.h>
#include <linux/sort.h>
+#include <linux/file.h>
#include <linux/nstree.h>
+#include <linux/proc_fs.h>
+#include <linux/syscalls.h>
+#include <uapi/linux/nsfs.h>
static struct kmem_cache *user_ns_cachep __ro_after_init;
static DEFINE_MUTEX(userns_state_mutex);
@@ -1176,6 +1180,228 @@ static ssize_t map_write(struct file *file, const char __user *buf,
return ret;
}
+static bool caller_idmap_permitted(struct user_namespace *ns, int cap_setid,
+ unsigned long ns_flags,
+ const struct uid_gid_map *new_map)
+{
+ const struct cred *cred = current_cred();
+
+ if (cap_setid == CAP_SETUID && idmap_maps_root(new_map)) {
+ if (cred->user_ns == ns) {
+ if (!ns->parent_could_setfcap)
+ return false;
+ } else {
+ if (!ns_capable(ns->parent, CAP_SETFCAP))
+ return false;
+ }
+ }
+
+ if (unpriv_idmap_permitted(ns, cred, cap_setid, ns_flags, new_map))
+ return true;
+
+ if (!cap_valid(cap_setid))
+ return ns_capable(ns, CAP_SYS_ADMIN) ||
+ ns_capable(ns->parent, CAP_SETUID);
+
+ return ns_capable(ns->parent, cap_setid);
+}
+
+static int prepare_caller_idmap(struct user_namespace *ns, int cap_setid,
+ unsigned long ns_flags,
+ struct uid_gid_map *new_map,
+ struct uid_gid_map *parent_map)
+{
+ if (!caller_idmap_permitted(ns, cap_setid, ns_flags, new_map))
+ return -EPERM;
+
+ return resolve_new_idmap(new_map, parent_map);
+}
+
+static int parse_user_idmap_extents(__u64 uptr, __u32 nr_extents,
+ struct uid_gid_map *new_map)
+{
+ const struct userns_idmap_extent __user *uext = u64_to_user_ptr(uptr);
+ unsigned int i;
+ int ret;
+
+ if (!nr_extents || nr_extents > UID_GID_MAP_MAX_EXTENTS || !uptr)
+ return -EINVAL;
+
+ for (i = 0; i < nr_extents; i++) {
+ struct userns_idmap_extent kext;
+ struct uid_gid_extent extent;
+
+ if (copy_from_user(&kext, &uext[i], sizeof(kext)))
+ return -EFAULT;
+ if (kext.reserved)
+ return -EINVAL;
+
+ extent.first = kext.first;
+ extent.lower_first = kext.lower_first;
+ extent.count = kext.count;
+
+ ret = validate_and_insert_extent(new_map, &extent);
+ if (ret < 0)
+ return ret;
+ }
+ return 0;
+}
+
+/**
+ * sys_userns_set_idmap - Configure ID mappings on a user namespace fd
+ * @fd: File descriptor referencing a %CLONE_NEWUSER ``nsfs`` namespace
+ * @map: User pointer to &struct userns_idmap configuration
+ * @size: Size of @map structure in bytes (%USERNS_IDMAP_SIZE_VER0..%PAGE_SIZE)
+ * @flags: Bitmask of &enum userns_flags values (%USERNS_SETGROUPS_ALLOWED)
+ *
+ * Atomically configure UID, GID, and project ID mappings (and, when
+ * @map->nr_gid_extents is non-zero, the %USERNS_SETGROUPS_ALLOWED policy) of
+ * @fd. Requires ``CAP_SYS_ADMIN`` over the target user namespace in the
+ * caller's or @fd opener's credentials, with parent ID ranges authorized
+ * against the caller's credentials.
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+SYSCALL_DEFINE4(userns_set_idmap, int, fd,
+ const struct userns_idmap __user *, map,
+ size_t, size, unsigned int, flags)
+{
+ struct uid_gid_map new_uid = {}, new_gid = {}, new_projid = {};
+ struct userns_idmap req = {};
+ struct ns_common *ns_common;
+ struct user_namespace *ns;
+ unsigned long new_flags;
+ struct file *filp;
+ bool file_ok;
+ int ret;
+
+ BUILD_BUG_ON(sizeof(struct userns_idmap) != USERNS_IDMAP_SIZE_VER0);
+
+ if (flags & ~USERNS_SETGROUPS_ALLOWED)
+ return -EINVAL;
+
+ CLASS(fd, f)(fd);
+ if (fd_empty(f))
+ return -EBADF;
+
+ filp = fd_file(f);
+ if (!proc_ns_file(filp))
+ return -EINVAL;
+
+ ns_common = get_proc_ns(file_inode(filp));
+ if (ns_common->ns_type != CLONE_NEWUSER)
+ return -EINVAL;
+ ns = to_user_ns(ns_common);
+
+ if (!map || size < USERNS_IDMAP_SIZE_VER0)
+ return -EINVAL;
+ if (unlikely(size > PAGE_SIZE))
+ return -E2BIG;
+ ret = copy_struct_from_user(&req, sizeof(req), map, size);
+ if (ret)
+ return ret;
+ if (req.reserved)
+ return -EINVAL;
+ if (!req.nr_uid_extents != !req.uid_extents ||
+ !req.nr_gid_extents != !req.gid_extents ||
+ !req.nr_projid_extents != !req.projid_extents)
+ return -EINVAL;
+ if (!req.nr_uid_extents && !req.nr_gid_extents &&
+ !req.nr_projid_extents)
+ return -EINVAL;
+ if ((flags & USERNS_SETGROUPS_ALLOWED) && !req.nr_gid_extents)
+ return -EINVAL;
+
+ if (!ns->parent)
+ return -EPERM;
+ if (current_user_ns() != ns && current_user_ns() != ns->parent)
+ return -EPERM;
+
+ file_ok = (filp->f_cred->user_ns == ns ||
+ filp->f_cred->user_ns == ns->parent) &&
+ file_ns_capable(filp, ns, CAP_SYS_ADMIN);
+ if (!ns_capable(ns, CAP_SYS_ADMIN) && !file_ok)
+ return -EPERM;
+
+ if (req.nr_uid_extents) {
+ ret = parse_user_idmap_extents(req.uid_extents,
+ req.nr_uid_extents, &new_uid);
+ if (ret < 0)
+ goto out_free;
+ }
+ if (req.nr_gid_extents) {
+ ret = parse_user_idmap_extents(req.gid_extents,
+ req.nr_gid_extents, &new_gid);
+ if (ret < 0)
+ goto out_free;
+ }
+ if (req.nr_projid_extents) {
+ ret = parse_user_idmap_extents(req.projid_extents,
+ req.nr_projid_extents,
+ &new_projid);
+ if (ret < 0)
+ goto out_free;
+ }
+
+ mutex_lock(&userns_state_mutex);
+ new_flags = ns->flags;
+ ret = -EPERM;
+
+ if (req.nr_uid_extents && ns->uid_map.nr_extents != 0)
+ goto out_unlock;
+ if (req.nr_gid_extents && ns->gid_map.nr_extents != 0)
+ goto out_unlock;
+ if (req.nr_projid_extents && ns->projid_map.nr_extents != 0)
+ goto out_unlock;
+
+ if (req.nr_gid_extents) {
+ if ((flags & USERNS_SETGROUPS_ALLOWED) &&
+ !(new_flags & USERNS_SETGROUPS_ALLOWED))
+ goto out_unlock;
+ if (!(flags & USERNS_SETGROUPS_ALLOWED))
+ new_flags &= ~USERNS_SETGROUPS_ALLOWED;
+ }
+
+ if (req.nr_uid_extents) {
+ ret = prepare_caller_idmap(ns, CAP_SETUID, new_flags, &new_uid,
+ &ns->parent->uid_map);
+ if (ret < 0)
+ goto out_unlock;
+ }
+ if (req.nr_gid_extents) {
+ ret = prepare_caller_idmap(ns, CAP_SETGID, new_flags, &new_gid,
+ &ns->parent->gid_map);
+ if (ret < 0)
+ goto out_unlock;
+ }
+ if (req.nr_projid_extents) {
+ ret = prepare_caller_idmap(ns, -1, new_flags, &new_projid,
+ &ns->parent->projid_map);
+ if (ret < 0)
+ goto out_unlock;
+ }
+
+ if (new_flags != ns->flags)
+ WRITE_ONCE(ns->flags, new_flags);
+ if (req.nr_uid_extents)
+ commit_new_idmap(&ns->uid_map, &new_uid);
+ if (req.nr_gid_extents)
+ commit_new_idmap(&ns->gid_map, &new_gid);
+ if (req.nr_projid_extents)
+ commit_new_idmap(&ns->projid_map, &new_projid);
+
+ mutex_unlock(&userns_state_mutex);
+ return 0;
+
+out_unlock:
+ mutex_unlock(&userns_state_mutex);
+out_free:
+ free_new_idmap(&new_uid);
+ free_new_idmap(&new_gid);
+ free_new_idmap(&new_projid);
+ return ret;
+}
+
ssize_t proc_uid_map_write(struct file *file, const char __user *buf,
size_t size, loff_t *ppos)
{
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 03/26] arch: Wire up userns_set_idmap() system call
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 01/26] userns: Factor out idmap validation and commit helpers Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 02/26] userns: Add userns_set_idmap() system call Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 04/26] mount: Add mnt_ns_get_root() Jarkko Sakkinen
` (22 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
Expose userns_set_idmap() (473, 583 on Alpha) across all architecture
system call tables, asm-generic unistd.h, and the mirrored copies under
tools/.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
arch/alpha/kernel/syscalls/syscall.tbl | 1 +
arch/arm/tools/syscall.tbl | 1 +
arch/arm64/tools/syscall_32.tbl | 1 +
arch/m68k/kernel/syscalls/syscall.tbl | 1 +
arch/microblaze/kernel/syscalls/syscall.tbl | 1 +
arch/mips/kernel/syscalls/syscall_n32.tbl | 1 +
arch/mips/kernel/syscalls/syscall_n64.tbl | 1 +
arch/mips/kernel/syscalls/syscall_o32.tbl | 1 +
arch/parisc/kernel/syscalls/syscall.tbl | 1 +
arch/powerpc/kernel/syscalls/syscall.tbl | 1 +
arch/s390/kernel/syscalls/syscall.tbl | 1 +
arch/sh/kernel/syscalls/syscall.tbl | 1 +
arch/sparc/kernel/syscalls/syscall.tbl | 1 +
arch/x86/entry/syscalls/syscall_32.tbl | 1 +
arch/x86/entry/syscalls/syscall_64.tbl | 1 +
arch/xtensa/kernel/syscalls/syscall.tbl | 1 +
include/uapi/asm-generic/unistd.h | 6 +++++-
scripts/syscall.tbl | 1 +
tools/include/uapi/asm-generic/unistd.h | 6 +++++-
tools/perf/arch/arm/entry/syscalls/syscall.tbl | 1 +
tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl | 1 +
tools/perf/arch/powerpc/entry/syscalls/syscall.tbl | 1 +
tools/perf/arch/s390/entry/syscalls/syscall.tbl | 1 +
tools/perf/arch/sh/entry/syscalls/syscall.tbl | 1 +
tools/perf/arch/sparc/entry/syscalls/syscall.tbl | 1 +
tools/perf/arch/x86/entry/syscalls/syscall_32.tbl | 1 +
tools/perf/arch/x86/entry/syscalls/syscall_64.tbl | 1 +
tools/perf/arch/xtensa/entry/syscalls/syscall.tbl | 1 +
tools/scripts/syscall.tbl | 1 +
29 files changed, 37 insertions(+), 2 deletions(-)
diff --git a/arch/alpha/kernel/syscalls/syscall.tbl b/arch/alpha/kernel/syscalls/syscall.tbl
index 52e3538cc7df..60d330a51476 100644
--- a/arch/alpha/kernel/syscalls/syscall.tbl
+++ b/arch/alpha/kernel/syscalls/syscall.tbl
@@ -512,3 +512,4 @@
580 common listns sys_listns
581 common rseq_slice_yield sys_rseq_slice_yield
582 common fchroot sys_fchroot
+583 common userns_set_idmap sys_userns_set_idmap
diff --git a/arch/arm/tools/syscall.tbl b/arch/arm/tools/syscall.tbl
index 55717ed32c27..d055515e98cd 100644
--- a/arch/arm/tools/syscall.tbl
+++ b/arch/arm/tools/syscall.tbl
@@ -487,3 +487,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/arch/arm64/tools/syscall_32.tbl b/arch/arm64/tools/syscall_32.tbl
index df2d1d82fb3c..a18982ead3bf 100644
--- a/arch/arm64/tools/syscall_32.tbl
+++ b/arch/arm64/tools/syscall_32.tbl
@@ -484,3 +484,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/arch/m68k/kernel/syscalls/syscall.tbl b/arch/m68k/kernel/syscalls/syscall.tbl
index ba7a4d8903d0..e89ec7d54b8c 100644
--- a/arch/m68k/kernel/syscalls/syscall.tbl
+++ b/arch/m68k/kernel/syscalls/syscall.tbl
@@ -472,3 +472,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/arch/microblaze/kernel/syscalls/syscall.tbl b/arch/microblaze/kernel/syscalls/syscall.tbl
index 76d7cbe2a133..0dfcd6f9e4e7 100644
--- a/arch/microblaze/kernel/syscalls/syscall.tbl
+++ b/arch/microblaze/kernel/syscalls/syscall.tbl
@@ -478,3 +478,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/arch/mips/kernel/syscalls/syscall_n32.tbl b/arch/mips/kernel/syscalls/syscall_n32.tbl
index 9ae88e4eac61..882ff15f3e6d 100644
--- a/arch/mips/kernel/syscalls/syscall_n32.tbl
+++ b/arch/mips/kernel/syscalls/syscall_n32.tbl
@@ -411,3 +411,4 @@
470 n32 listns sys_listns
471 n32 rseq_slice_yield sys_rseq_slice_yield
472 n32 fchroot sys_fchroot
+473 n32 userns_set_idmap sys_userns_set_idmap
diff --git a/arch/mips/kernel/syscalls/syscall_n64.tbl b/arch/mips/kernel/syscalls/syscall_n64.tbl
index 83dc93a0712f..daa95049baef 100644
--- a/arch/mips/kernel/syscalls/syscall_n64.tbl
+++ b/arch/mips/kernel/syscalls/syscall_n64.tbl
@@ -387,3 +387,4 @@
470 n64 listns sys_listns
471 n64 rseq_slice_yield sys_rseq_slice_yield
472 n64 fchroot sys_fchroot
+473 n64 userns_set_idmap sys_userns_set_idmap
diff --git a/arch/mips/kernel/syscalls/syscall_o32.tbl b/arch/mips/kernel/syscalls/syscall_o32.tbl
index 9c62429c9b7b..9e0040399fef 100644
--- a/arch/mips/kernel/syscalls/syscall_o32.tbl
+++ b/arch/mips/kernel/syscalls/syscall_o32.tbl
@@ -460,3 +460,4 @@
470 o32 listns sys_listns
471 o32 rseq_slice_yield sys_rseq_slice_yield
472 o32 fchroot sys_fchroot
+473 o32 userns_set_idmap sys_userns_set_idmap
diff --git a/arch/parisc/kernel/syscalls/syscall.tbl b/arch/parisc/kernel/syscalls/syscall.tbl
index 88adc4016cce..b77482e68d1a 100644
--- a/arch/parisc/kernel/syscalls/syscall.tbl
+++ b/arch/parisc/kernel/syscalls/syscall.tbl
@@ -471,3 +471,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/arch/powerpc/kernel/syscalls/syscall.tbl b/arch/powerpc/kernel/syscalls/syscall.tbl
index cfbb70039ff0..973562f20a94 100644
--- a/arch/powerpc/kernel/syscalls/syscall.tbl
+++ b/arch/powerpc/kernel/syscalls/syscall.tbl
@@ -563,3 +563,4 @@
470 common listns sys_listns
471 nospu rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 nospu userns_set_idmap sys_userns_set_idmap
diff --git a/arch/s390/kernel/syscalls/syscall.tbl b/arch/s390/kernel/syscalls/syscall.tbl
index 1b45e68a217b..19d7b234b31b 100644
--- a/arch/s390/kernel/syscalls/syscall.tbl
+++ b/arch/s390/kernel/syscalls/syscall.tbl
@@ -399,3 +399,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/arch/sh/kernel/syscalls/syscall.tbl b/arch/sh/kernel/syscalls/syscall.tbl
index ace068dff0de..252e6f9aa04c 100644
--- a/arch/sh/kernel/syscalls/syscall.tbl
+++ b/arch/sh/kernel/syscalls/syscall.tbl
@@ -476,3 +476,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/arch/sparc/kernel/syscalls/syscall.tbl b/arch/sparc/kernel/syscalls/syscall.tbl
index 5b9fe0e8140f..1263d0e825c1 100644
--- a/arch/sparc/kernel/syscalls/syscall.tbl
+++ b/arch/sparc/kernel/syscalls/syscall.tbl
@@ -518,3 +518,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/arch/x86/entry/syscalls/syscall_32.tbl b/arch/x86/entry/syscalls/syscall_32.tbl
index 2c172ef48dfd..0f8c81c584e0 100644
--- a/arch/x86/entry/syscalls/syscall_32.tbl
+++ b/arch/x86/entry/syscalls/syscall_32.tbl
@@ -478,3 +478,4 @@
470 i386 listns sys_listns
471 i386 rseq_slice_yield sys_rseq_slice_yield
472 i386 fchroot sys_fchroot
+473 i386 userns_set_idmap sys_userns_set_idmap
diff --git a/arch/x86/entry/syscalls/syscall_64.tbl b/arch/x86/entry/syscalls/syscall_64.tbl
index d5b6045b0090..5452b7567bf8 100644
--- a/arch/x86/entry/syscalls/syscall_64.tbl
+++ b/arch/x86/entry/syscalls/syscall_64.tbl
@@ -397,6 +397,7 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
#
# Due to a historical design error, certain syscalls are numbered differently
diff --git a/arch/xtensa/kernel/syscalls/syscall.tbl b/arch/xtensa/kernel/syscalls/syscall.tbl
index d354bb231796..f10b491c873c 100644
--- a/arch/xtensa/kernel/syscalls/syscall.tbl
+++ b/arch/xtensa/kernel/syscalls/syscall.tbl
@@ -443,3 +443,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/include/uapi/asm-generic/unistd.h b/include/uapi/asm-generic/unistd.h
index 5b7e77a7c736..695eac2d356b 100644
--- a/include/uapi/asm-generic/unistd.h
+++ b/include/uapi/asm-generic/unistd.h
@@ -867,8 +867,12 @@ __SYSCALL(__NR_rseq_slice_yield, sys_rseq_slice_yield)
#define __NR_fchroot 472
__SYSCALL(__NR_fchroot, sys_fchroot)
+/* kernel/user_namespace.c */
+#define __NR_userns_set_idmap 473
+__SYSCALL(__NR_userns_set_idmap, sys_userns_set_idmap)
+
#undef __NR_syscalls
-#define __NR_syscalls 473
+#define __NR_syscalls 474
/*
* 32 bit systems traditionally used different
diff --git a/scripts/syscall.tbl b/scripts/syscall.tbl
index 0ab531605120..7ba073cc0e80 100644
--- a/scripts/syscall.tbl
+++ b/scripts/syscall.tbl
@@ -413,3 +413,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/tools/include/uapi/asm-generic/unistd.h b/tools/include/uapi/asm-generic/unistd.h
index 5b7e77a7c736..695eac2d356b 100644
--- a/tools/include/uapi/asm-generic/unistd.h
+++ b/tools/include/uapi/asm-generic/unistd.h
@@ -867,8 +867,12 @@ __SYSCALL(__NR_rseq_slice_yield, sys_rseq_slice_yield)
#define __NR_fchroot 472
__SYSCALL(__NR_fchroot, sys_fchroot)
+/* kernel/user_namespace.c */
+#define __NR_userns_set_idmap 473
+__SYSCALL(__NR_userns_set_idmap, sys_userns_set_idmap)
+
#undef __NR_syscalls
-#define __NR_syscalls 473
+#define __NR_syscalls 474
/*
* 32 bit systems traditionally used different
diff --git a/tools/perf/arch/arm/entry/syscalls/syscall.tbl b/tools/perf/arch/arm/entry/syscalls/syscall.tbl
index 55717ed32c27..d055515e98cd 100644
--- a/tools/perf/arch/arm/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/arm/entry/syscalls/syscall.tbl
@@ -487,3 +487,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl b/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl
index 83dc93a0712f..daa95049baef 100644
--- a/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl
+++ b/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl
@@ -387,3 +387,4 @@
470 n64 listns sys_listns
471 n64 rseq_slice_yield sys_rseq_slice_yield
472 n64 fchroot sys_fchroot
+473 n64 userns_set_idmap sys_userns_set_idmap
diff --git a/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl b/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl
index cfbb70039ff0..973562f20a94 100644
--- a/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl
@@ -563,3 +563,4 @@
470 common listns sys_listns
471 nospu rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 nospu userns_set_idmap sys_userns_set_idmap
diff --git a/tools/perf/arch/s390/entry/syscalls/syscall.tbl b/tools/perf/arch/s390/entry/syscalls/syscall.tbl
index 1b45e68a217b..19d7b234b31b 100644
--- a/tools/perf/arch/s390/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/s390/entry/syscalls/syscall.tbl
@@ -399,3 +399,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/tools/perf/arch/sh/entry/syscalls/syscall.tbl b/tools/perf/arch/sh/entry/syscalls/syscall.tbl
index ace068dff0de..252e6f9aa04c 100644
--- a/tools/perf/arch/sh/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/sh/entry/syscalls/syscall.tbl
@@ -476,3 +476,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/tools/perf/arch/sparc/entry/syscalls/syscall.tbl b/tools/perf/arch/sparc/entry/syscalls/syscall.tbl
index 5b9fe0e8140f..1263d0e825c1 100644
--- a/tools/perf/arch/sparc/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/sparc/entry/syscalls/syscall.tbl
@@ -518,3 +518,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl b/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl
index 2c172ef48dfd..0f8c81c584e0 100644
--- a/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl
+++ b/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl
@@ -478,3 +478,4 @@
470 i386 listns sys_listns
471 i386 rseq_slice_yield sys_rseq_slice_yield
472 i386 fchroot sys_fchroot
+473 i386 userns_set_idmap sys_userns_set_idmap
diff --git a/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl b/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl
index d5b6045b0090..5452b7567bf8 100644
--- a/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl
+++ b/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl
@@ -397,6 +397,7 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
#
# Due to a historical design error, certain syscalls are numbered differently
diff --git a/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl b/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl
index d354bb231796..f10b491c873c 100644
--- a/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl
@@ -443,3 +443,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
diff --git a/tools/scripts/syscall.tbl b/tools/scripts/syscall.tbl
index 0ab531605120..7ba073cc0e80 100644
--- a/tools/scripts/syscall.tbl
+++ b/tools/scripts/syscall.tbl
@@ -413,3 +413,4 @@
470 common listns sys_listns
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
+473 common userns_set_idmap sys_userns_set_idmap
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 04/26] mount: Add mnt_ns_get_root()
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (2 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 03/26] arch: Wire up " Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 05/26] mount: Enforce mount_too_revealing() for foreign mntns Jarkko Sakkinen
` (21 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
Empty mount namespaces created with CLONE_EMPTY_MNTNS start with only an
internal nullfs root mount until a real root filesystem is mounted over
it, and external callers have no helper to resolve the live root path of
an unentered mount namespace.
Add mnt_ns_get_root() to look up "/" with LOOKUP_DOWN from the mount
namespace's base root mount and return -ENOENT if no filesystem has been
mounted over the initial nullfs root yet.
Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
fs/namespace.c | 16 ++++++++++++++++
include/linux/mnt_namespace.h | 2 ++
2 files changed, 18 insertions(+)
diff --git a/fs/namespace.c b/fs/namespace.c
index aecd05ac0170..781380945d78 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -6708,6 +6708,22 @@ static void mntns_put(struct ns_common *ns)
put_mnt_ns(to_mnt_ns(ns));
}
+int mnt_ns_get_root(struct mnt_namespace *mnt_ns, struct path *root)
+{
+ int err;
+
+ err = vfs_path_lookup(mnt_ns->root->mnt.mnt_root, &mnt_ns->root->mnt,
+ "/", LOOKUP_DOWN, root);
+ if (err)
+ return err;
+ if (root->mnt == &mnt_ns->root->mnt) {
+ path_put(root);
+ *root = (struct path){};
+ return -ENOENT;
+ }
+ return 0;
+}
+
static int mntns_install(struct nsset *nsset, struct ns_common *ns)
{
struct nsproxy *nsproxy = nsset->nsproxy;
diff --git a/include/linux/mnt_namespace.h b/include/linux/mnt_namespace.h
index 0acd1089d149..98188d1f7428 100644
--- a/include/linux/mnt_namespace.h
+++ b/include/linux/mnt_namespace.h
@@ -8,6 +8,7 @@
struct mnt_namespace;
struct fs_struct;
+struct path;
struct user_namespace;
struct ns_common;
@@ -15,6 +16,7 @@ extern struct mnt_namespace init_mnt_ns;
extern struct mnt_namespace *copy_mnt_ns(u64, struct mnt_namespace *,
struct user_namespace *, struct fs_struct *);
+int mnt_ns_get_root(struct mnt_namespace *mnt_ns, struct path *root);
extern void put_mnt_ns(struct mnt_namespace *ns);
DEFINE_FREE(put_mnt_ns, struct mnt_namespace *, if (!IS_ERR_OR_NULL(_T)) put_mnt_ns(_T))
extern struct ns_common *from_mnt_ns(struct mnt_namespace *);
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 05/26] mount: Enforce mount_too_revealing() for foreign mntns
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (3 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 04/26] mount: Add mnt_ns_get_root() Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 06/26] mount: Support MOVE_MOUNT_T_MNTNS in move_mount() Jarkko Sakkinen
` (20 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
mount_too_revealing() skips visibility checks whenever
current->nsproxy->mnt_ns belongs to init_user_ns, assuming the caller
holds CAP_SYS_ADMIN in its current mount namespace. That assumption does
not hold when an unprivileged caller creates mounts for a child user
namespace while running in init_mnt_ns or another foreign mount
namespace.
Require CAP_SYS_ADMIN in init_user_ns before bypassing
mount_too_revealing() for init_mnt_ns, reject chrooted callers lacking
CAP_SYS_ADMIN in their current mount namespace, and treat existing
mounts and child overmounts in a foreign mount namespace as locked
during mnt_already_visible() checks.
Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
fs/namespace.c | 24 +++++++++++++++++-------
1 file changed, 17 insertions(+), 7 deletions(-)
diff --git a/fs/namespace.c b/fs/namespace.c
index 781380945d78..1bb9f90a6523 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -6580,7 +6580,7 @@ bool current_chrooted(void)
static bool mnt_already_visible(struct mnt_namespace *ns,
const struct super_block *sb,
- int *new_mnt_flags)
+ int *new_mnt_flags, bool foreign_ns)
{
int new_flags = *new_mnt_flags;
struct mount *mnt;
@@ -6606,11 +6606,16 @@ static bool mnt_already_visible(struct mnt_namespace *ns,
continue;
/* A local view of the mount flags */
- mnt_flags = mnt->mnt.mnt_flags;
+ mnt_flags = READ_ONCE(mnt->mnt.mnt_flags);
/* Don't miss readonly hidden in the superblock flags */
if (sb_rdonly(mnt->mnt.mnt_sb))
mnt_flags |= MNT_LOCK_READONLY;
+ if (foreign_ns) {
+ if (mnt_flags & MNT_READONLY)
+ mnt_flags |= MNT_LOCK_READONLY;
+ mnt_flags |= MNT_LOCK_ATIME;
+ }
/* Verify the mount flags are equal to or more permissive
* than the proposed new mount.
@@ -6629,7 +6634,7 @@ static bool mnt_already_visible(struct mnt_namespace *ns,
list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) {
struct inode *inode = child->mnt_mountpoint->d_inode;
/* Only worry about locked mounts */
- if (!(child->mnt.mnt_flags & MNT_LOCKED))
+ if (!foreign_ns && !(READ_ONCE(child->mnt.mnt_flags) & MNT_LOCKED))
continue;
/* Is the directory permanently empty? */
if (!is_empty_dir_inode(inode))
@@ -6649,14 +6654,19 @@ static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flags
const unsigned long required_iflags = SB_I_NOEXEC | SB_I_NODEV;
struct mnt_namespace *ns = current->nsproxy->mnt_ns;
unsigned long s_iflags;
-
- if (ns->user_ns == &init_user_ns)
- return false;
+ bool foreign_ns;
/* Can this filesystem be too revealing? */
if (!(sb->s_type->fs_flags & FS_USERNS_MOUNT_RESTRICTED))
return false;
+ foreign_ns = !ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN);
+ if (ns->user_ns == &init_user_ns && !foreign_ns)
+ return false;
+
+ if (foreign_ns && current_chrooted())
+ return true;
+
s_iflags = sb->s_iflags;
if ((s_iflags & required_iflags) != required_iflags) {
WARN_ONCE(1, "Expected s_iflags to contain 0x%lx\n",
@@ -6671,7 +6681,7 @@ static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flags
if (s_iflags & SB_I_RESTRICTED_VARIANT)
return false;
- return !mnt_already_visible(ns, sb, new_mnt_flags);
+ return !mnt_already_visible(ns, sb, new_mnt_flags, foreign_ns);
}
bool mnt_may_suid(struct vfsmount *mnt)
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 06/26] mount: Support MOVE_MOUNT_T_MNTNS in move_mount()
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (4 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 05/26] mount: Enforce mount_too_revealing() for foreign mntns Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 07/26] mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS Jarkko Sakkinen
` (19 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
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 | 235 +++++++++++++++++++++++++++++++------
include/uapi/linux/mount.h | 3 +-
2 files changed, 199 insertions(+), 39 deletions(-)
diff --git a/fs/namespace.c b/fs/namespace.c
index 1bb9f90a6523..93dd11da7e73 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,16 @@ int count_mounts(struct mnt_namespace *ns, struct mount *mnt)
enum mnt_tree_flags_t {
MNT_TREE_BENEATH = BIT(0),
MNT_TREE_PROPAGATION = BIT(1),
+ MNT_TREE_MNTNS = BIT(2),
+ MNT_TREE_MNTNS_INIT = BIT(3),
};
/**
* attach_recursive_mnt - attach a source mount tree
* @source_mnt: mount tree to be attached
* @dest: the context for mounting at the place where the tree should go
+ * @src_user_ns: owning user namespace of @source_mnt for MOVE_MOUNT_T_MNTNS,
+ * or NULL
*
* NOTE: in the table below explains the semantics when a source mount
* of a given type is attached to a destination mount of a given type.
@@ -2632,13 +2643,15 @@ enum mnt_tree_flags_t {
* Otherwise a negative error code is returned.
*/
static int attach_recursive_mnt(struct mount *source_mnt,
- const struct pinned_mountpoint *dest)
+ const struct pinned_mountpoint *dest,
+ struct user_namespace *src_user_ns)
{
struct mount *dest_mnt = dest->parent;
struct mountpoint *dest_mp = dest->mp;
HLIST_HEAD(tree_list);
struct mnt_namespace *ns = dest_mnt->mnt_ns;
struct user_namespace *user_ns = ns->user_ns;
+ bool cross_src = src_user_ns && !in_userns(ns->user_ns, src_user_ns);
struct pinned_mountpoint root = {};
struct mountpoint *shorter = NULL;
struct mount *child, *p;
@@ -2725,11 +2738,22 @@ static int attach_recursive_mnt(struct mount *source_mnt,
hlist_add_head(&source_mnt->mnt_hash, &tree_list);
hlist_for_each_entry_safe(child, n, &tree_list, mnt_hash) {
+ struct user_namespace *child_user_ns =
+ child->mnt_parent->mnt_ns->user_ns;
+ bool cross_child_src = cross_src &&
+ !in_userns(child_user_ns, src_user_ns);
struct mount *q;
+
hlist_del_init(&child->mnt_hash);
- /* Notice when we are propagating across user namespaces */
- if (child->mnt_parent->mnt_ns->user_ns != user_ns)
+ /*
+ * Notice when we are propagating or attaching a foreign
+ * source tree across user namespaces.
+ */
+ if (child_user_ns != user_ns || cross_child_src) {
lock_mnt_tree(child);
+ if (cross_child_src && list_empty(&child->mnt_expire))
+ child->mnt.mnt_flags |= MNT_LOCKED;
+ }
q = __lookup_mnt(&child->mnt_parent->mnt,
child->mnt_mountpoint);
commit_tree(child);
@@ -2937,7 +2961,7 @@ static int graft_tree(struct mount *mnt, const struct pinned_mountpoint *mp)
d_is_dir(mnt->mnt.mnt_root))
return -ENOTDIR;
- return attach_recursive_mnt(mnt, mp);
+ return attach_recursive_mnt(mnt, mp, NULL);
}
static int may_change_propagation(const struct mount *m)
@@ -3131,7 +3155,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 +3800,12 @@ static inline bool may_use_mount(struct mount *mnt)
static int do_move_mount(const struct path *old_path,
const struct path *new_path,
- enum mnt_tree_flags_t flags)
+ enum mnt_tree_flags_t flags,
+ struct mnt_namespace *target_mnt_ns)
{
struct mount *old = real_mount(old_path->mnt);
+ struct user_namespace *src_user_ns = NULL;
+ struct mnt_namespace *dest_mnt_ns;
int err;
bool beneath = flags & MNT_TREE_BENEATH;
@@ -3792,7 +3819,30 @@ static int do_move_mount(const struct path *old_path,
if (IS_ERR(mp.parent))
return PTR_ERR(mp.parent);
- if (check_mnt(old)) {
+ if (flags & MNT_TREE_MNTNS) {
+ u64 seq;
+
+ if (!anon_ns_root(old) || old->mnt_ns == mp.parent->mnt_ns ||
+ mp.parent->mnt_ns != target_mnt_ns)
+ return -EINVAL;
+ seq = old->mnt_ns->seq_origin;
+ if (seq && seq != target_mnt_ns->ns.ns_id &&
+ seq != current->nsproxy->mnt_ns->ns.ns_id)
+ return -EINVAL;
+ src_user_ns = old->mnt_ns->user_ns;
+ if (flags & MNT_TREE_MNTNS_INIT) {
+ if (mp.parent != target_mnt_ns->root)
+ return -EBUSY;
+ } else if (mp.mp->m_dentry == mp.parent->mnt.mnt_root) {
+ const struct mount *m = mp.parent;
+
+ while (m != target_mnt_ns->root && mnt_has_parent(m) &&
+ m->mnt_mountpoint == m->mnt_parent->mnt.mnt_root)
+ m = m->mnt_parent;
+ if (m == target_mnt_ns->root)
+ return beneath ? -EINVAL : -EBUSY;
+ }
+ } else if (check_mnt(old)) {
/* if the source is in our namespace... */
/* ... it should be detachable from parent */
if (!mnt_has_parent(old) || IS_MNT_LOCKED(old))
@@ -3840,12 +3890,14 @@ static int do_move_mount(const struct path *old_path,
*/
if (IS_MNT_SHARED(mp.parent) && tree_contains_unbindable(old))
return -EINVAL;
- if (!check_for_nsfs_mounts(old))
+ dest_mnt_ns = is_anon_ns(mp.parent->mnt_ns) ?
+ current->nsproxy->mnt_ns : mp.parent->mnt_ns;
+ if (!check_for_nsfs_mounts(old, dest_mnt_ns))
return -ELOOP;
if (mount_is_ancestor(old, mp.parent))
return -ELOOP;
- return attach_recursive_mnt(old, &mp);
+ return attach_recursive_mnt(old, &mp, src_user_ns);
}
static int do_move_mount_old(const struct path *path, const char *old_name)
@@ -3860,7 +3912,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 +4777,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 +4789,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 +4927,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 +4940,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 +4970,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 related [flat|nested] 30+ messages in thread* [RFC PATCH v7 07/26] mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (5 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 06/26] mount: Support MOVE_MOUNT_T_MNTNS in move_mount() Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 08/26] userns: Factor out install_user_ns_cred() Jarkko Sakkinen
` (18 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
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 | 91 +++++++++++++++++++++++++++++---------
include/uapi/linux/mount.h | 3 +-
2 files changed, 73 insertions(+), 21 deletions(-)
diff --git a/fs/namespace.c b/fs/namespace.c
index 93dd11da7e73..b2c89ad2393e 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -2573,6 +2573,7 @@ enum mnt_tree_flags_t {
MNT_TREE_PROPAGATION = BIT(1),
MNT_TREE_MNTNS = BIT(2),
MNT_TREE_MNTNS_INIT = BIT(3),
+ MNT_TREE_CLONE = BIT(4),
};
/**
@@ -3805,31 +3806,28 @@ static int do_move_mount(const struct path *old_path,
{
struct mount *old = real_mount(old_path->mnt);
struct user_namespace *src_user_ns = NULL;
+ struct mount *cloned = NULL;
struct mnt_namespace *dest_mnt_ns;
int err;
bool beneath = flags & MNT_TREE_BENEATH;
- if (!path_mounted(old_path))
+ if (!(flags & MNT_TREE_CLONE) && !path_mounted(old_path))
return -EINVAL;
if (d_is_dir(new_path->dentry) != d_is_dir(old_path->dentry))
return -EINVAL;
+ if ((flags & MNT_TREE_CLONE) &&
+ mnt_ns_loop_target(old_path->dentry, target_mnt_ns))
+ return -EINVAL;
+
LOCK_MOUNT_MAYBE_BENEATH(mp, new_path, beneath);
if (IS_ERR(mp.parent))
return PTR_ERR(mp.parent);
if (flags & MNT_TREE_MNTNS) {
- u64 seq;
-
- if (!anon_ns_root(old) || old->mnt_ns == mp.parent->mnt_ns ||
- mp.parent->mnt_ns != target_mnt_ns)
- return -EINVAL;
- seq = old->mnt_ns->seq_origin;
- if (seq && seq != target_mnt_ns->ns.ns_id &&
- seq != current->nsproxy->mnt_ns->ns.ns_id)
+ if (mp.parent->mnt_ns != target_mnt_ns)
return -EINVAL;
- src_user_ns = old->mnt_ns->user_ns;
if (flags & MNT_TREE_MNTNS_INIT) {
if (mp.parent != target_mnt_ns->root)
return -EBUSY;
@@ -3842,6 +3840,36 @@ static int do_move_mount(const struct path *old_path,
if (m == target_mnt_ns->root)
return beneath ? -EINVAL : -EBUSY;
}
+ if (flags & MNT_TREE_CLONE) {
+ unsigned int copy_flags;
+
+ if (!check_mnt(old) || old->mnt_ns == target_mnt_ns ||
+ (old->mnt.mnt_sb->s_flags & SB_NOUSER))
+ return -EINVAL;
+ src_user_ns = old->mnt_ns->user_ns;
+ copy_flags = (target_mnt_ns->user_ns != src_user_ns) ?
+ (CL_SLAVE | CL_COPY_UNBINDABLE) :
+ CL_COPY_MNT_NS_FILE;
+ cloned = __do_loopback(old_path, true, copy_flags);
+ if (IS_ERR(cloned))
+ return PTR_ERR(cloned);
+ old = cloned;
+ if (d_is_symlink(old->mnt.mnt_root)) {
+ err = -EINVAL;
+ goto out_cloned;
+ }
+ } else {
+ u64 seq;
+
+ if (!anon_ns_root(old) ||
+ old->mnt_ns == mp.parent->mnt_ns)
+ return -EINVAL;
+ seq = old->mnt_ns->seq_origin;
+ if (seq && seq != target_mnt_ns->ns.ns_id &&
+ seq != current->nsproxy->mnt_ns->ns.ns_id)
+ return -EINVAL;
+ src_user_ns = old->mnt_ns->user_ns;
+ }
} else if (check_mnt(old)) {
/* if the source is in our namespace... */
/* ... it should be detachable from parent */
@@ -3881,23 +3909,36 @@ static int do_move_mount(const struct path *old_path,
over = mp.parent->overmount;
err = can_move_mount_beneath(old, over, &mp);
if (err)
- return err;
+ goto out_cloned;
}
/*
* Don't move a mount tree containing unbindable mounts to a destination
* mount which is shared.
*/
- if (IS_MNT_SHARED(mp.parent) && tree_contains_unbindable(old))
- return -EINVAL;
+ if (IS_MNT_SHARED(mp.parent) && tree_contains_unbindable(old)) {
+ err = -EINVAL;
+ goto out_cloned;
+ }
dest_mnt_ns = is_anon_ns(mp.parent->mnt_ns) ?
current->nsproxy->mnt_ns : mp.parent->mnt_ns;
- if (!check_for_nsfs_mounts(old, dest_mnt_ns))
- return -ELOOP;
- if (mount_is_ancestor(old, mp.parent))
- return -ELOOP;
+ if (!check_for_nsfs_mounts(old, dest_mnt_ns)) {
+ err = -ELOOP;
+ goto out_cloned;
+ }
+ if (mount_is_ancestor(old, mp.parent)) {
+ err = -ELOOP;
+ goto out_cloned;
+ }
- return attach_recursive_mnt(old, &mp, src_user_ns);
+ err = attach_recursive_mnt(old, &mp, src_user_ns);
+out_cloned:
+ if (err && cloned) {
+ lock_mount_hash();
+ umount_tree(cloned, UMOUNT_SYNC);
+ unlock_mount_hash();
+ }
+ return err;
}
static int do_move_mount_old(const struct path *path, const char *old_name)
@@ -4823,8 +4864,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.
@@ -4832,6 +4873,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.
@@ -4933,12 +4979,17 @@ SYSCALL_DEFINE5(move_mount,
if (flags & ~MOVE_MOUNT__MASK)
return -EINVAL;
+ if ((flags & MOVE_MOUNT_CLONE) && !(flags & MOVE_MOUNT_T_MNTNS))
+ return -EINVAL;
+
if ((flags & (MOVE_MOUNT_BENEATH | MOVE_MOUNT_SET_GROUP)) ==
(MOVE_MOUNT_BENEATH | MOVE_MOUNT_SET_GROUP))
return -EINVAL;
if (flags & MOVE_MOUNT_SET_GROUP) mflags |= MNT_TREE_PROPAGATION;
if (flags & MOVE_MOUNT_BENEATH) mflags |= MNT_TREE_BENEATH;
+ if (flags & MOVE_MOUNT_CLONE)
+ mflags |= MNT_TREE_CLONE;
if (unlikely(flags & MOVE_MOUNT_T_MNTNS)) {
if (flags & (MOVE_MOUNT_T_EMPTY_PATH | MOVE_MOUNT_SET_GROUP))
diff --git a/include/uapi/linux/mount.h b/include/uapi/linux/mount.h
index 7d413418426a..cb4f7175db02 100644
--- a/include/uapi/linux/mount.h
+++ b/include/uapi/linux/mount.h
@@ -78,7 +78,8 @@
#define MOVE_MOUNT_T_MNTNS 0x00000080 /* Resolve to_dfd as mntns fd */
#define MOVE_MOUNT_SET_GROUP 0x00000100 /* Set sharing group instead */
#define MOVE_MOUNT_BENEATH 0x00000200 /* Mount beneath top mount */
-#define MOVE_MOUNT__MASK 0x000003f7
+#define MOVE_MOUNT_CLONE 0x00000400 /* Recursively clone from path */
+#define MOVE_MOUNT__MASK 0x000007f7
/*
* fsopen() flags.
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 08/26] userns: Factor out install_user_ns_cred()
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (6 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 07/26] mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 09/26] nsproxy: Expose create_new_namespaces() Jarkko Sakkinen
` (17 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
userns_install() updates a credential's owning user namespace and
rebinds its ucounts inline, which cannot be reused by fork paths that
switch a newly allocated child credential into a target user namespace.
Factor this logic out into install_user_ns_cred() with a !CONFIG_USER_NS
stub so callers outside kernel/user_namespace.c can install a target
user namespace on a prepared struct cred.
Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
include/linux/user_namespace.h | 7 +++++++
kernel/user_namespace.c | 12 ++++++++----
2 files changed, 15 insertions(+), 4 deletions(-)
diff --git a/include/linux/user_namespace.h b/include/linux/user_namespace.h
index b4a50edfe003..ecee91aa2257 100644
--- a/include/linux/user_namespace.h
+++ b/include/linux/user_namespace.h
@@ -182,6 +182,7 @@ static inline struct user_namespace *get_user_ns(struct user_namespace *ns)
}
extern int create_user_ns(struct cred *new);
+int install_user_ns_cred(struct cred *cred, struct user_namespace *user_ns);
extern int unshare_userns(unsigned long unshare_flags, struct cred **new_cred);
extern void __put_user_ns(struct user_namespace *ns);
@@ -224,6 +225,12 @@ static inline int create_user_ns(struct cred *new)
return -EINVAL;
}
+static inline int install_user_ns_cred(struct cred *cred,
+ struct user_namespace *user_ns)
+{
+ return -EINVAL;
+}
+
static inline int unshare_userns(unsigned long unshare_flags,
struct cred **new_cred)
{
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index 61dcf2fab6f0..218ea4e73006 100644
--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -1613,6 +1613,13 @@ static void userns_put(struct ns_common *ns)
put_user_ns(to_user_ns(ns));
}
+int install_user_ns_cred(struct cred *cred, struct user_namespace *user_ns)
+{
+ put_user_ns(cred->user_ns);
+ set_cred_user_ns(cred, get_user_ns(user_ns));
+ return set_cred_ucounts(cred);
+}
+
static int userns_install(struct nsset *nsset, struct ns_common *ns)
{
struct user_namespace *user_ns = to_user_ns(ns);
@@ -1638,10 +1645,7 @@ static int userns_install(struct nsset *nsset, struct ns_common *ns)
if (!cred)
return -EINVAL;
- put_user_ns(cred->user_ns);
- set_cred_user_ns(cred, get_user_ns(user_ns));
-
- if (set_cred_ucounts(cred) < 0)
+ if (install_user_ns_cred(cred, user_ns) < 0)
return -EINVAL;
return 0;
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 09/26] nsproxy: Expose create_new_namespaces()
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (7 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 08/26] userns: Factor out install_user_ns_cred() Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 10/26] userland: Add core infrastructure Jarkko Sakkinen
` (16 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
create_new_namespaces() is currently static to kernel/nsproxy.c,
preventing callers outside kernel/nsproxy.c from constructing a child
nsproxy without mutating a task.
Expose create_new_namespaces() in <linux/nsproxy.h> so userland_open()
can allocate a detached namespace set from current.
Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
include/linux/nsproxy.h | 4 ++++
kernel/nsproxy.c | 6 +++---
2 files changed, 7 insertions(+), 3 deletions(-)
diff --git a/include/linux/nsproxy.h b/include/linux/nsproxy.h
index dc2447f5f092..d611c40cb4ce 100644
--- a/include/linux/nsproxy.h
+++ b/include/linux/nsproxy.h
@@ -12,6 +12,7 @@ struct ipc_namespace;
struct pid_namespace;
struct cgroup_namespace;
struct fs_struct;
+struct user_namespace;
/*
* A structure to contain pointers to all per-process
@@ -92,6 +93,9 @@ static inline struct cred *nsset_cred(struct nsset *set)
*
*/
+struct nsproxy *create_new_namespaces(u64 flags, struct task_struct *tsk,
+ struct user_namespace *user_ns,
+ struct fs_struct *new_fs);
int copy_namespaces(u64 flags, struct task_struct *tsk);
void switch_cred_namespaces(const struct cred *old, const struct cred *new);
void exit_nsproxy_namespaces(struct task_struct *tsk);
diff --git a/kernel/nsproxy.c b/kernel/nsproxy.c
index 2dcf105e8ee2..3c4161515c3c 100644
--- a/kernel/nsproxy.c
+++ b/kernel/nsproxy.c
@@ -85,9 +85,9 @@ void deactivate_nsproxy(struct nsproxy *ns)
* Return the newly created nsproxy. Do not attach this to the task,
* leave it to the caller to do proper locking and attach it to task.
*/
-static struct nsproxy *create_new_namespaces(u64 flags,
- struct task_struct *tsk, struct user_namespace *user_ns,
- struct fs_struct *new_fs)
+struct nsproxy *create_new_namespaces(u64 flags, struct task_struct *tsk,
+ struct user_namespace *user_ns,
+ struct fs_struct *new_fs)
{
struct nsproxy *new_nsp;
int err;
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 10/26] userland: Add core infrastructure
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (8 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 09/26] nsproxy: Expose create_new_namespaces() Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 11/26] userland: Track init lifecycle via copy_process() and pid_namespace Jarkko Sakkinen
` (15 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
Linux namespaces can be created and entered individually, but userspace
orchestrators lack a single control object that binds a full detached
namespace set and an init process lifecycle behind a pollable file
descriptor. Because this object manages process lifecycle, wait and
signal delivery, VFS mount delegation, and LSM state rather than
representing an nsfs namespace entity, model it as a distinct userland
abstraction.
Add struct userland, its lifecycle states, reference counting, uAPI
flags, and anonymous inode file operations under CONFIG_USERLAND. Drop
active and passive namespace references on final release, send SIGKILL
to the userland init thread group on close when USERLAND_KILL_ON_CLOSE
is set, and report EPOLLHUP from poll() once the userland reaches
USERLAND_DEAD.
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/userland.h | 80 +++++++++++++++++++++++++++++
include/uapi/linux/userland.h | 25 ++++++++++
init/Kconfig | 10 ++++
kernel/Makefile | 2 +
kernel/userland.c | 94 +++++++++++++++++++++++++++++++++++
5 files changed, 211 insertions(+)
create mode 100644 include/linux/userland.h
create mode 100644 include/uapi/linux/userland.h
create mode 100644 kernel/userland.c
diff --git a/include/linux/userland.h b/include/linux/userland.h
new file mode 100644
index 000000000000..9b9fefed63ac
--- /dev/null
+++ b/include/linux/userland.h
@@ -0,0 +1,80 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.
+ * Copyright (C) 2026 Opinsys Oy
+ */
+
+#ifndef _LINUX_USERLAND_H
+#define _LINUX_USERLAND_H
+
+#include <linux/refcount.h>
+#include <linux/spinlock.h>
+#include <linux/wait.h>
+
+struct file;
+struct nsproxy;
+struct pid;
+struct user_namespace;
+
+/**
+ * enum userland_state - Userland lifecycle states
+ * @USERLAND_INIT: Build phase after ``userland_open()`` before any
+ * process has entered. ``USERLAND_SHARE_NSFD`` is
+ * permitted, ID mappings may be configured on the owning
+ * user namespace, and ``"/"`` must be mounted in the
+ * mount namespace before entry.
+ * @USERLAND_FORKING: Bootstrap phase while the first
+ * ``clone3(CLONE_INTO_USERLAND)`` call creates PID 1.
+ * Concurrent callers wait killably; reverts to
+ * %USERLAND_INIT if ``copy_process()`` fails, or advances
+ * to %USERLAND_RUNNING once PID 1 is attached.
+ * @USERLAND_RUNNING: Live phase while PID 1 is attached. Subsequent
+ * ``clone3(CLONE_INTO_USERLAND)`` calls join the PID
+ * namespace until teardown begins,
+ * ``USERLAND_GET_NSFD(CLONE_NEWPID)`` and
+ * ``pidfd_send_signal()`` are enabled, and
+ * ``USERLAND_SHARE_NSFD`` returns ``-EBUSY``.
+ * @USERLAND_DEAD: Terminal phase entered after PID 1 exits and the PID
+ * namespace has killed and reaped all member processes.
+ * ``poll()`` reports ``EPOLLHUP`` and
+ * ``waitid(P_USERLAND, ...)`` reports PID 1's exit status
+ * without consuming it.
+ *
+ * State transitions advance from %USERLAND_INIT through %USERLAND_FORKING and
+ * %USERLAND_RUNNING to %USERLAND_DEAD, reverting from %USERLAND_FORKING to
+ * %USERLAND_INIT only if the initial bootstrap fork fails.
+ */
+enum userland_state {
+ USERLAND_INIT = 0,
+ USERLAND_FORKING = 1,
+ USERLAND_RUNNING = 2,
+ USERLAND_DEAD = 3,
+};
+
+struct userland {
+ refcount_t usage;
+ int exit_code;
+ struct user_namespace *user_ns;
+ struct nsproxy *ns;
+ struct pid *init_pid;
+ spinlock_t lock; /* Guards userland lifecycle state */
+ wait_queue_head_t waitq;
+ unsigned int flags;
+ enum userland_state state;
+};
+
+#ifdef CONFIG_USERLAND
+void userland_put(struct userland *c);
+bool userland_is_file(struct file *file);
+#else
+static inline void userland_put(struct userland *c)
+{
+}
+
+static inline bool userland_is_file(struct file *file)
+{
+ return false;
+}
+#endif /* CONFIG_USERLAND */
+
+#endif /* _LINUX_USERLAND_H */
diff --git a/include/uapi/linux/userland.h b/include/uapi/linux/userland.h
new file mode 100644
index 000000000000..4a9031f81dda
--- /dev/null
+++ b/include/uapi/linux/userland.h
@@ -0,0 +1,25 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+/*
+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.
+ * Copyright (C) 2026 Opinsys Oy
+ */
+
+#ifndef _UAPI_LINUX_USERLAND_H
+#define _UAPI_LINUX_USERLAND_H
+
+/**
+ * enum userland_flags - Flags for userland_open()
+ * @USERLAND_KILL_ON_CLOSE: Send %SIGKILL to userland init on final fd release.
+ * @USERLAND_CLOSE_ON_EXEC: Set %O_CLOEXEC on the returned control fd.
+ * @USERLAND_ALL_FLAGS: Mask of all valid flags accepted by userland_open().
+ *
+ * Every userland created by userland_open() allocates a full set of
+ * detached namespaces owned by a fresh user namespace.
+ */
+enum userland_flags {
+ USERLAND_KILL_ON_CLOSE = 0x00000001,
+ USERLAND_CLOSE_ON_EXEC = 0x00000002,
+ USERLAND_ALL_FLAGS = 0x00000003,
+};
+
+#endif /* _UAPI_LINUX_USERLAND_H */
diff --git a/init/Kconfig b/init/Kconfig
index c8a7cfa60a6e..0c5fada1ba88 100644
--- a/init/Kconfig
+++ b/init/Kconfig
@@ -1283,6 +1283,16 @@ config NET_NS
endif # NAMESPACES
+config USERLAND
+ bool "Userland support"
+ depends on NAMESPACES && USER_NS && PID_NS && UTS_NS && IPC_NS && NET_NS && CGROUPS
+ help
+ Allow user space to open and manage isolated userlands and their init
+ process lifecycle through an anonymous-inode control file descriptor
+ via userland_open(), waitid(P_USERLAND), pidfd_send_signal(),
+ USERLAND_GET_NSFD, USERLAND_SHARE_NSFD, FSCONFIG_SET_USERLAND, and
+ clone3() with CLONE_INTO_USERLAND.
+
config CHECKPOINT_RESTORE
bool "Checkpoint/restore support"
depends on PROC_FS
diff --git a/kernel/Makefile b/kernel/Makefile
index 4ff92e24680c..80eb26639776 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_USERLAND) += userland.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/userland.c b/kernel/userland.c
new file mode 100644
index 000000000000..7be0c4b5385b
--- /dev/null
+++ b/kernel/userland.c
@@ -0,0 +1,94 @@
+// 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 userland is an anonymous-inode control object opened by ``userland_open()``
+ * that binds a detached namespace set, an initially empty mount namespace, an
+ * owning user namespace, and an init process lifecycle.
+ */
+#include <linux/poll.h>
+#include <linux/wait.h>
+#include <uapi/linux/wait.h>
+#include <linux/file.h>
+#include <linux/fs.h>
+#include <linux/anon_inodes.h>
+#include <linux/userland.h>
+#include <linux/sched/signal.h>
+#include <linux/sched/task.h>
+#include <linux/slab.h>
+#include <linux/syscalls.h>
+#include <linux/uaccess.h>
+#include <linux/mnt_namespace.h>
+#include <linux/nsproxy.h>
+#include <linux/ns_common.h>
+#include <linux/nsfs.h>
+#include <linux/pid.h>
+#include <linux/pid_namespace.h>
+#include <linux/time_namespace.h>
+#include <linux/user_namespace.h>
+#include <linux/idr.h>
+#include <uapi/linux/userland.h>
+
+void userland_put(struct userland *c)
+{
+ if (!c || !refcount_dec_and_test(&c->usage))
+ return;
+
+ if (c->ns)
+ put_nsproxy(c->ns);
+ if (c->init_pid)
+ put_pid(c->init_pid);
+ if (c->user_ns) {
+ ns_ref_active_put(c->user_ns);
+ put_user_ns(c->user_ns);
+ }
+ kfree(c);
+}
+
+static __poll_t userland_poll(struct file *file, poll_table *wait)
+{
+ struct userland *userland = file->private_data;
+ __poll_t mask = 0;
+
+ poll_wait(file, &userland->waitq, wait);
+
+ if (READ_ONCE(userland->state) == USERLAND_DEAD)
+ mask |= EPOLLHUP;
+
+ return mask;
+}
+
+static int userland_release(struct inode *inode, struct file *file)
+{
+ struct userland *userland = file->private_data;
+
+ if (userland->flags & USERLAND_KILL_ON_CLOSE) {
+ struct pid *pid = NULL;
+
+ scoped_guard(spinlock, &userland->lock) {
+ if (userland->state == USERLAND_RUNNING)
+ pid = get_pid(userland->init_pid);
+ }
+ if (pid) {
+ kill_pid(pid, SIGKILL, true);
+ put_pid(pid);
+ }
+ }
+ userland_put(userland);
+ return 0;
+}
+
+static const struct file_operations userland_fops = {
+ .poll = userland_poll,
+ .release = userland_release,
+};
+
+bool userland_is_file(struct file *file)
+{
+ return file->f_op == &userland_fops;
+}
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 11/26] userland: Track init lifecycle via copy_process() and pid_namespace
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (9 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 10/26] userland: Add core infrastructure Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 12/26] userland: Add userland_open() system call Jarkko Sakkinen
` (14 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
A userland needs to record its init thread group's PID when bootstrapped
and capture its exit status and UID once all processes in the userland
have terminated, without serializing normal fork() and exit() paths
inside the userland.
Commit the bootstrap child reaper and bind pid_ns->userland in
userland_copy() after copy_process() attaches PIDs and drops
tasklist_lock, and invoke userland_exit() from zap_pid_ns_processes()
after the userland'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/userland.h | 17 ++++++++++++++
kernel/fork.c | 4 ++++
kernel/pid_namespace.c | 2 ++
kernel/userland.c | 43 +++++++++++++++++++++++++++++++++++
5 files changed, 70 insertions(+)
diff --git a/include/linux/pid_namespace.h b/include/linux/pid_namespace.h
index b20baaa7e62b..ef703a3b8ed5 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 userland;
#if defined(CONFIG_SYSCTL) && defined(CONFIG_MEMFD_CREATE)
/* modes for vm.memfd_noexec sysctl */
@@ -45,6 +46,9 @@ struct pid_namespace {
struct user_namespace *user_ns;
struct ucounts *ucounts;
int reboot; /* group exit code if this pidns was rebooted */
+#ifdef CONFIG_USERLAND
+ struct userland *userland;
+#endif
struct ns_common ns;
struct work_struct work;
} __randomize_layout;
diff --git a/include/linux/userland.h b/include/linux/userland.h
index 9b9fefed63ac..a92709957529 100644
--- a/include/linux/userland.h
+++ b/include/linux/userland.h
@@ -9,11 +9,14 @@
#include <linux/refcount.h>
#include <linux/spinlock.h>
+#include <linux/uidgid.h>
#include <linux/wait.h>
struct file;
struct nsproxy;
struct pid;
+struct pid_namespace;
+struct task_struct;
struct user_namespace;
/**
@@ -57,6 +60,7 @@ struct userland {
struct user_namespace *user_ns;
struct nsproxy *ns;
struct pid *init_pid;
+ kuid_t init_uid;
spinlock_t lock; /* Guards userland lifecycle state */
wait_queue_head_t waitq;
unsigned int flags;
@@ -66,6 +70,9 @@ struct userland {
#ifdef CONFIG_USERLAND
void userland_put(struct userland *c);
bool userland_is_file(struct file *file);
+void userland_copy(struct task_struct *tsk, struct pid *pid,
+ struct userland *userland);
+void userland_exit(struct pid_namespace *pid_ns, struct task_struct *tsk);
#else
static inline void userland_put(struct userland *c)
{
@@ -75,6 +82,16 @@ static inline bool userland_is_file(struct file *file)
{
return false;
}
+
+static inline void userland_copy(struct task_struct *tsk, struct pid *pid,
+ struct userland *userland)
+{
+}
+
+static inline void userland_exit(struct pid_namespace *pid_ns,
+ struct task_struct *tsk)
+{
+}
#endif /* CONFIG_USERLAND */
#endif /* _LINUX_USERLAND_H */
diff --git a/kernel/fork.c b/kernel/fork.c
index 5efceb8d58a7..d87ab7cbad5e 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/userland.h>
#include <linux/posix-timers.h>
#include <linux/user-return-notifier.h>
#include <linux/oom.h>
@@ -2584,6 +2585,9 @@ __latent_entropy struct task_struct *copy_process(
syscall_tracepoint_update(p);
write_unlock_irq(&tasklist_lock);
+ if (likely(p->pid) && thread_group_leader(p))
+ userland_copy(p, pid, NULL);
+
if (pidfile)
fd_install(pidfd, pidfile);
diff --git a/kernel/pid_namespace.c b/kernel/pid_namespace.c
index 127a5fd23e70..70606d9c5b52 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/userland.h>
#include <uapi/linux/wait.h>
#include "pid_sysctl.h"
@@ -280,6 +281,7 @@ void zap_pid_ns_processes(struct pid_namespace *pid_ns)
current->signal->group_exit_code = pid_ns->reboot;
acct_exit_ns(pid_ns);
+ userland_exit(pid_ns, me);
return;
}
diff --git a/kernel/userland.c b/kernel/userland.c
index 7be0c4b5385b..44a1976f97c2 100644
--- a/kernel/userland.c
+++ b/kernel/userland.c
@@ -92,3 +92,46 @@ bool userland_is_file(struct file *file)
{
return file->f_op == &userland_fops;
}
+
+void userland_copy(struct task_struct *tsk, struct pid *pid, struct userland *c)
+{
+ if (likely(!c || !is_child_reaper(pid)))
+ return;
+
+ scoped_guard(spinlock, &c->lock) {
+ if (c->state != USERLAND_FORKING)
+ return;
+ refcount_inc(&c->usage);
+ ns_of_pid(pid)->userland = c;
+ WRITE_ONCE(c->init_pid, get_pid(pid));
+ WRITE_ONCE(c->state, USERLAND_RUNNING);
+ }
+}
+
+void userland_exit(struct pid_namespace *pid_ns, struct task_struct *tsk)
+{
+ struct userland *c = pid_ns->userland;
+ struct task_struct *leader;
+ kuid_t uid;
+ int status;
+
+ if (!c)
+ return;
+
+ leader = tsk->group_leader;
+ rcu_read_lock();
+ uid = task_uid(leader);
+ rcu_read_unlock();
+ status = (tsk->signal->flags & SIGNAL_GROUP_EXIT) ?
+ tsk->signal->group_exit_code : leader->exit_code;
+
+ scoped_guard(spinlock, &c->lock) {
+ c->exit_code = status;
+ c->init_uid = uid;
+ WRITE_ONCE(c->state, USERLAND_DEAD);
+ }
+
+ pid_ns->userland = NULL;
+ __wake_up(&c->waitq, TASK_NORMAL, 0, poll_to_key(EPOLLHUP));
+ userland_put(c);
+}
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 12/26] userland: Add userland_open() system call
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (10 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 11/26] userland: Track init lifecycle via copy_process() and pid_namespace Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 13/26] userland: Add USERLAND_GET_NSFD ioctl Jarkko Sakkinen
` (13 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
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 userland_open() system call to allocate a userland owning a
fresh user namespace alongside dedicated empty mount
(CLONE_EMPTY_MNTNS), PID, UTS, IPC, network, cgroup, and time
namespaces, and return its anonymous-inode file descriptor. Because a
userland encapsulates process lifecycle and mount delegation rather than
an nsfs namespace entity, keep it separate from namespace creation APIs.
Finalize the nsproxy time namespace and pin active references for the
lifetime of the userland.
Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
include/linux/syscalls.h | 1 +
kernel/sys_ni.c | 3 ++
kernel/userland.c | 108 +++++++++++++++++++++++++++++++++++++++
3 files changed, 112 insertions(+)
diff --git a/include/linux/syscalls.h b/include/linux/syscalls.h
index 72308cc11908..2ea8ebd71743 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_userland_open(unsigned int flags);
/*
* Architecture-specific system calls
diff --git a/kernel/sys_ni.c b/kernel/sys_ni.c
index e3202e7cc2a1..fca9663d09b7 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/userland.c */
+COND_SYSCALL(userland_open);
diff --git a/kernel/userland.c b/kernel/userland.c
index 44a1976f97c2..472d75423b95 100644
--- a/kernel/userland.c
+++ b/kernel/userland.c
@@ -135,3 +135,111 @@ void userland_exit(struct pid_namespace *pid_ns, struct task_struct *tsk)
__wake_up(&c->waitq, TASK_NORMAL, 0, poll_to_key(EPOLLHUP));
userland_put(c);
}
+
+static struct user_namespace *userland_create_user_ns(void)
+{
+ struct user_namespace *user_ns;
+ struct cred *new;
+ int ret;
+
+ new = prepare_creds();
+ if (!new)
+ return ERR_PTR(-ENOMEM);
+
+ ret = create_user_ns(new);
+ if (ret < 0) {
+ abort_creds(new);
+ return ERR_PTR(ret);
+ }
+
+ user_ns = get_user_ns(new->user_ns);
+ abort_creds(new);
+ return user_ns;
+}
+
+static struct userland *userland_create(unsigned int flags)
+{
+ u64 clone_flags = CLONE_NEWNS | CLONE_EMPTY_MNTNS | CLONE_NEWPID |
+ CLONE_NEWCGROUP | CLONE_NEWUTS | CLONE_NEWIPC |
+ CLONE_NEWNET |
+ (IS_ENABLED(CONFIG_TIME_NS) ? CLONE_NEWTIME : 0);
+ struct user_namespace *user_ns;
+ struct nsproxy *ns;
+ struct userland *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 = userland_create_user_ns();
+ if (IS_ERR(user_ns)) {
+ ret = PTR_ERR(user_ns);
+ goto err_put;
+ }
+ c->user_ns = user_ns;
+ ns_ref_active_get(user_ns);
+
+ if (!ns_capable(user_ns, CAP_SYS_ADMIN)) {
+ ret = -EPERM;
+ goto err_put;
+ }
+
+ ns = create_new_namespaces(clone_flags, current, user_ns, NULL);
+ if (IS_ERR(ns)) {
+ ret = PTR_ERR(ns);
+ goto err_put;
+ }
+
+ if (ns->time_ns != ns->time_ns_for_children) {
+ get_time_ns(ns->time_ns_for_children);
+ put_time_ns(ns->time_ns);
+ ns->time_ns = ns->time_ns_for_children;
+ }
+ c->ns = ns;
+ nsproxy_ns_active_get(ns);
+
+ return c;
+
+err_put:
+ userland_put(c);
+ return ERR_PTR(ret);
+}
+
+/**
+ * sys_userland_open - Open a new userland
+ * @flags: Combination of &enum userland_flags values
+ *
+ * Allocate a userland owning a fresh child user namespace (with the caller's
+ * effective UID and GID as owner and initially empty ID mappings) and dedicated
+ * empty mount, PID, UTS, IPC, network, cgroup, and time namespaces. Control
+ * operations authorize against capabilities in the userland's owning user
+ * namespace.
+ *
+ * Return: Userland file descriptor on success, negative error code on failure.
+ */
+SYSCALL_DEFINE1(userland_open, unsigned int, flags)
+{
+ struct userland *c;
+ int fd;
+
+ if (flags & ~USERLAND_ALL_FLAGS)
+ return -EINVAL;
+
+ c = userland_create(flags);
+ if (IS_ERR(c))
+ return PTR_ERR(c);
+
+ fd = anon_inode_getfd("userland", &userland_fops, c,
+ O_RDWR |
+ (flags & USERLAND_CLOSE_ON_EXEC ? O_CLOEXEC : 0));
+ if (fd < 0)
+ userland_put(c);
+
+ return fd;
+}
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 13/26] userland: Add USERLAND_GET_NSFD ioctl
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (11 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 12/26] userland: Add userland_open() system call Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 14/26] userland: Add USERLAND_SHARE_NSFD ioctl Jarkko Sakkinen
` (12 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
Standalone namespace operations such as userns_set_idmap() and
move_mount(..., MOVE_MOUNT_T_MNTNS) operate on nsfs file descriptors,
requiring a way to obtain member namespace fds from a userland file
descriptor before any process has entered it.
Add the USERLAND_GET_NSFD ioctl to open an O_CLOEXEC nsfs file
descriptor for a requested member namespace when the caller holds
CAP_SYS_ADMIN in the userland's user namespace, additionally requiring
an ancestor active PID namespace and a running init process for
CLONE_NEWPID.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
fs/internal.h | 1 -
include/linux/nsfs.h | 1 +
include/uapi/linux/userland.h | 19 +++++++++
kernel/userland.c | 76 +++++++++++++++++++++++++++++++++++
4 files changed, 96 insertions(+), 1 deletion(-)
diff --git a/fs/internal.h b/fs/internal.h
index 3f2fbac40f8e..ee3f796241ac 100644
--- a/fs/internal.h
+++ b/fs/internal.h
@@ -250,7 +250,6 @@ extern void mnt_pin_kill(struct mount *m);
* fs/nsfs.c
*/
extern const struct dentry_operations ns_dentry_operations;
-int open_namespace(struct ns_common *ns);
struct file *open_namespace_file(struct ns_common *ns);
/*
diff --git a/include/linux/nsfs.h b/include/linux/nsfs.h
index 731b67fc2fec..40912c1eb5ff 100644
--- a/include/linux/nsfs.h
+++ b/include/linux/nsfs.h
@@ -23,6 +23,7 @@ bool ns_match(const struct ns_common *ns, dev_t dev, ino_t ino);
int ns_get_name(char *buf, size_t size, struct task_struct *task,
const struct proc_ns_operations *ns_ops);
void nsfs_init(void);
+int open_namespace(struct ns_common *ns);
#define __current_namespace_from_type(__ns) \
_Generic((__ns), \
diff --git a/include/uapi/linux/userland.h b/include/uapi/linux/userland.h
index 4a9031f81dda..e81a06d6e9eb 100644
--- a/include/uapi/linux/userland.h
+++ b/include/uapi/linux/userland.h
@@ -7,6 +7,8 @@
#ifndef _UAPI_LINUX_USERLAND_H
#define _UAPI_LINUX_USERLAND_H
+#include <linux/ioctl.h>
+
/**
* enum userland_flags - Flags for userland_open()
* @USERLAND_KILL_ON_CLOSE: Send %SIGKILL to userland init on final fd release.
@@ -22,4 +24,21 @@ enum userland_flags {
USERLAND_ALL_FLAGS = 0x00000003,
};
+#define USERLAND_IOCTL_MAGIC 0xB9
+
+/**
+ * DOC: USERLAND_GET_NSFD
+ *
+ * ``ioctl(userland_fd, USERLAND_GET_NSFD, nstype)`` opens an ``nsfs`` file
+ * descriptor (with ``O_CLOEXEC``) for the member namespace identified by
+ * ``nstype`` (one of ``CLONE_NEWNS``, ``CLONE_NEWCGROUP``,
+ * ``CLONE_NEWUTS``, ``CLONE_NEWIPC``, ``CLONE_NEWUSER``, ``CLONE_NEWPID``,
+ * ``CLONE_NEWNET``, or ``CLONE_NEWTIME``).
+ *
+ * Requires ``CAP_SYS_ADMIN`` in the userland's user namespace.
+ * Opening ``CLONE_NEWPID`` additionally requires running in an ancestor
+ * active PID namespace and that userland init is running.
+ */
+#define USERLAND_GET_NSFD _IO(USERLAND_IOCTL_MAGIC, 0x01)
+
#endif /* _UAPI_LINUX_USERLAND_H */
diff --git a/kernel/userland.c b/kernel/userland.c
index 472d75423b95..fd5f67c0245e 100644
--- a/kernel/userland.c
+++ b/kernel/userland.c
@@ -23,6 +23,8 @@
#include <linux/slab.h>
#include <linux/syscalls.h>
#include <linux/uaccess.h>
+#include <linux/cgroup_namespace.h>
+#include <linux/ipc_namespace.h>
#include <linux/mnt_namespace.h>
#include <linux/nsproxy.h>
#include <linux/ns_common.h>
@@ -31,6 +33,8 @@
#include <linux/pid_namespace.h>
#include <linux/time_namespace.h>
#include <linux/user_namespace.h>
+#include <linux/uts_namespace.h>
+#include <net/net_namespace.h>
#include <linux/idr.h>
#include <uapi/linux/userland.h>
@@ -63,6 +67,76 @@ static __poll_t userland_poll(struct file *file, poll_table *wait)
return mask;
}
+static long userland_get_nsfd(struct userland *userland, unsigned long nstype)
+{
+ struct ns_common *ns = NULL;
+
+ if (nstype > UINT_MAX)
+ return -EINVAL;
+ if (!ns_capable(userland->user_ns, CAP_SYS_ADMIN))
+ return -EPERM;
+
+ if (nstype == CLONE_NEWPID) {
+ if (!pidns_is_ancestor(userland->ns->pid_ns_for_children,
+ task_active_pid_ns(current)))
+ return -EXDEV;
+ if (READ_ONCE(userland->state) != USERLAND_RUNNING)
+ return -ESRCH;
+ }
+
+ scoped_guard(spinlock, &userland->lock) {
+ switch (nstype) {
+ case CLONE_NEWNS:
+ ns = from_mnt_ns(userland->ns->mnt_ns);
+ break;
+ case CLONE_NEWCGROUP:
+ ns = to_ns_common(userland->ns->cgroup_ns);
+ break;
+ case CLONE_NEWUTS:
+ ns = to_ns_common(userland->ns->uts_ns);
+ break;
+ case CLONE_NEWIPC:
+ ns = to_ns_common(userland->ns->ipc_ns);
+ break;
+ case CLONE_NEWUSER:
+ ns = to_ns_common(userland->user_ns);
+ break;
+ case CLONE_NEWPID:
+ ns = to_ns_common(userland->ns->pid_ns_for_children);
+ break;
+ case CLONE_NEWNET:
+ ns = to_ns_common(userland->ns->net_ns);
+ break;
+ case CLONE_NEWTIME:
+#ifdef CONFIG_TIME_NS
+ ns = to_ns_common(userland->ns->time_ns);
+ break;
+#else
+ return -EOPNOTSUPP;
+#endif
+ default:
+ return -EINVAL;
+ }
+
+ if (!__ns_ref_get(ns))
+ return -ESRCH;
+ }
+
+ return open_namespace(ns);
+}
+
+static long userland_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
+{
+ struct userland *userland = file->private_data;
+
+ switch (cmd) {
+ case USERLAND_GET_NSFD:
+ return userland_get_nsfd(userland, arg);
+ default:
+ return -ENOIOCTLCMD;
+ }
+}
+
static int userland_release(struct inode *inode, struct file *file)
{
struct userland *userland = file->private_data;
@@ -85,6 +159,8 @@ static int userland_release(struct inode *inode, struct file *file)
static const struct file_operations userland_fops = {
.poll = userland_poll,
+ .unlocked_ioctl = userland_ioctl,
+ .compat_ioctl = userland_ioctl,
.release = userland_release,
};
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 14/26] userland: Add USERLAND_SHARE_NSFD ioctl
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (12 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 13/26] userland: Add USERLAND_GET_NSFD ioctl Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 15/26] exit: Support P_USERLAND in waitid() Jarkko Sakkinen
` (11 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
userland_open() isolates every namespace by default rather than relying
on unshare() deny-listing, which prevents workloads such as
host-networked sandboxes or sidecars sharing a network or IPC namespace
from opting into specific existing namespaces.
Add the build-phase USERLAND_SHARE_NSFD ioctl to replace the userland's
cgroup, IPC, UTS, network, or time namespace with a supplied nsfs file
descriptor in-place under userland->lock while the userland is still in
USERLAND_INIT, rejecting calls with -EBUSY once CLONE_INTO_USERLAND
begins. Require CAP_SYS_ADMIN in the userland's user namespace, and
require CAP_SYS_ADMIN in the target namespace's owning user namespace
when the caller is not already a member of that namespace.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
include/uapi/linux/userland.h | 14 ++++++
kernel/userland.c | 90 +++++++++++++++++++++++++++++++++++
2 files changed, 104 insertions(+)
diff --git a/include/uapi/linux/userland.h b/include/uapi/linux/userland.h
index e81a06d6e9eb..addb84e996f5 100644
--- a/include/uapi/linux/userland.h
+++ b/include/uapi/linux/userland.h
@@ -41,4 +41,18 @@ enum userland_flags {
*/
#define USERLAND_GET_NSFD _IO(USERLAND_IOCTL_MAGIC, 0x01)
+/**
+ * DOC: USERLAND_SHARE_NSFD
+ *
+ * ``ioctl(userland_fd, USERLAND_SHARE_NSFD, ns_fd)`` replaces the corresponding
+ * member namespace of ``userland_fd`` with ``ns_fd`` (``CLONE_NEWCGROUP``,
+ * ``CLONE_NEWIPC``, ``CLONE_NEWUTS``, ``CLONE_NEWNET``, or ``CLONE_NEWTIME``)
+ * while ``userland_fd`` is in ``USERLAND_INIT``.
+ *
+ * Requires ``CAP_SYS_ADMIN`` in the userland's user namespace, plus
+ * ``CAP_SYS_ADMIN`` in ``ns_fd``'s owning user namespace when the caller is
+ * not already a member of ``ns_fd``.
+ */
+#define USERLAND_SHARE_NSFD _IO(USERLAND_IOCTL_MAGIC, 0x02)
+
#endif /* _UAPI_LINUX_USERLAND_H */
diff --git a/kernel/userland.c b/kernel/userland.c
index fd5f67c0245e..279b92e7b7f8 100644
--- a/kernel/userland.c
+++ b/kernel/userland.c
@@ -31,6 +31,8 @@
#include <linux/nsfs.h>
#include <linux/pid.h>
#include <linux/pid_namespace.h>
+#include <linux/proc_fs.h>
+#include <linux/proc_ns.h>
#include <linux/time_namespace.h>
#include <linux/user_namespace.h>
#include <linux/uts_namespace.h>
@@ -125,6 +127,92 @@ static long userland_get_nsfd(struct userland *userland, unsigned long nstype)
return open_namespace(ns);
}
+static long userland_share_nsfd(struct userland *c, unsigned long arg)
+{
+ struct ns_common *old_time_children = NULL;
+ struct ns_common *old_ns = NULL;
+ struct ns_common *ns;
+
+ if (arg > INT_MAX)
+ return -EBADF;
+
+ CLASS(fd, f)((int)arg);
+ if (fd_empty(f))
+ return -EBADF;
+ if (!proc_ns_file(fd_file(f)))
+ return -EINVAL;
+
+ ns = get_proc_ns(file_inode(fd_file(f)));
+ switch (ns->ns_type) {
+ case CLONE_NEWCGROUP:
+ case CLONE_NEWIPC:
+ case CLONE_NEWUTS:
+ case CLONE_NEWNET:
+ break;
+ case CLONE_NEWTIME:
+ if (!IS_ENABLED(CONFIG_TIME_NS))
+ return -EOPNOTSUPP;
+ break;
+ default:
+ return -EINVAL;
+ }
+
+ if (!ns_capable(c->user_ns, CAP_SYS_ADMIN))
+ return -EPERM;
+ if (!is_current_namespace(ns) &&
+ !ns_capable(ns->ops->owner(ns), CAP_SYS_ADMIN))
+ return -EPERM;
+
+ scoped_guard(spinlock, &c->lock) {
+ if (c->state != USERLAND_INIT)
+ return -EBUSY;
+
+ __ns_ref_inc(ns);
+ __ns_ref_active_get(ns);
+
+ switch (ns->ns_type) {
+ case CLONE_NEWCGROUP:
+ old_ns = to_ns_common(c->ns->cgroup_ns);
+ c->ns->cgroup_ns = to_cg_ns(ns);
+ break;
+ case CLONE_NEWIPC:
+ old_ns = to_ns_common(c->ns->ipc_ns);
+ c->ns->ipc_ns = to_ipc_ns(ns);
+ break;
+ case CLONE_NEWUTS:
+ old_ns = to_ns_common(c->ns->uts_ns);
+ c->ns->uts_ns = to_uts_ns(ns);
+ break;
+ case CLONE_NEWNET:
+ old_ns = to_ns_common(c->ns->net_ns);
+ c->ns->net_ns = to_net_ns(ns);
+ break;
+#ifdef CONFIG_TIME_NS
+ case CLONE_NEWTIME:
+ __ns_ref_inc(ns);
+ __ns_ref_active_get(ns);
+ old_ns = to_ns_common(c->ns->time_ns);
+ old_time_children =
+ to_ns_common(c->ns->time_ns_for_children);
+ c->ns->time_ns = to_time_ns(ns);
+ c->ns->time_ns_for_children = to_time_ns(ns);
+ break;
+#endif
+ default:
+ WARN_ON_ONCE(1);
+ break;
+ }
+ }
+
+ __ns_ref_active_put(old_ns);
+ old_ns->ops->put(old_ns);
+ if (old_time_children) {
+ __ns_ref_active_put(old_time_children);
+ old_time_children->ops->put(old_time_children);
+ }
+ return 0;
+}
+
static long userland_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct userland *userland = file->private_data;
@@ -132,6 +220,8 @@ static long userland_ioctl(struct file *file, unsigned int cmd, unsigned long ar
switch (cmd) {
case USERLAND_GET_NSFD:
return userland_get_nsfd(userland, arg);
+ case USERLAND_SHARE_NSFD:
+ return userland_share_nsfd(userland, arg);
default:
return -ENOIOCTLCMD;
}
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 15/26] exit: Support P_USERLAND in waitid()
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (13 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 14/26] userland: Add USERLAND_SHARE_NSFD ioctl Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 16/26] signal: Support userland fds in pidfd_send_signal() Jarkko Sakkinen
` (10 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
wait4() and waitid() only allow a parent or subreaper to collect exit
status, so an external manager holding a userland file descriptor cannot
wait on a userland init process forked by another process or observe
exit status multiple times across observers.
Add P_USERLAND to waitid() and wire kernel_waitid() to userland_waitid()
to wait freezably and interruptibly on a userland file descriptor until
the userland reaches USERLAND_DEAD and populate siginfo_t with init's
caller-visible TGID, munged UID, and exit status without consuming it.
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/userland.h | 10 +++++
include/uapi/linux/wait.h | 1 +
kernel/exit.c | 4 ++
kernel/userland.c | 83 +++++++++++++++++++++++++++++++++++++++
4 files changed, 98 insertions(+)
diff --git a/include/linux/userland.h b/include/linux/userland.h
index a92709957529..16988e10f623 100644
--- a/include/linux/userland.h
+++ b/include/linux/userland.h
@@ -16,8 +16,10 @@ struct file;
struct nsproxy;
struct pid;
struct pid_namespace;
+struct rusage;
struct task_struct;
struct user_namespace;
+struct waitid_info;
/**
* enum userland_state - Userland lifecycle states
@@ -73,6 +75,8 @@ bool userland_is_file(struct file *file);
void userland_copy(struct task_struct *tsk, struct pid *pid,
struct userland *userland);
void userland_exit(struct pid_namespace *pid_ns, struct task_struct *tsk);
+long userland_waitid(int upid, struct waitid_info *infop, int options,
+ struct rusage *ru);
#else
static inline void userland_put(struct userland *c)
{
@@ -92,6 +96,12 @@ static inline void userland_exit(struct pid_namespace *pid_ns,
struct task_struct *tsk)
{
}
+
+static inline long userland_waitid(int upid, struct waitid_info *infop,
+ int options, struct rusage *ru)
+{
+ return -EINVAL;
+}
#endif /* CONFIG_USERLAND */
#endif /* _LINUX_USERLAND_H */
diff --git a/include/uapi/linux/wait.h b/include/uapi/linux/wait.h
index 85b809fc9f11..edd39c2cab96 100644
--- a/include/uapi/linux/wait.h
+++ b/include/uapi/linux/wait.h
@@ -18,6 +18,7 @@
#define P_PID 1
#define P_PGID 2
#define P_PIDFD 3
+#define P_USERLAND 4
#endif /* _UAPI_LINUX_WAIT_H */
diff --git a/kernel/exit.c b/kernel/exit.c
index d5e7bc2af804..5b0bd3a9187c 100644
--- a/kernel/exit.c
+++ b/kernel/exit.c
@@ -71,6 +71,7 @@
#include <linux/unwind_deferred.h>
#include <linux/uaccess.h>
#include <linux/pidfs.h>
+#include <linux/userland.h>
#include <uapi/linux/wait.h>
@@ -1803,6 +1804,9 @@ static long kernel_waitid(int which, pid_t upid, struct waitid_info *infop,
struct wait_opts wo;
long ret;
+ if (which == P_USERLAND)
+ return userland_waitid(upid, infop, options, ru);
+
ret = kernel_waitid_prepare(&wo, which, upid, infop, options, ru);
if (ret)
return ret;
diff --git a/kernel/userland.c b/kernel/userland.c
index 279b92e7b7f8..3ded663b71af 100644
--- a/kernel/userland.c
+++ b/kernel/userland.c
@@ -15,6 +15,7 @@
#include <linux/wait.h>
#include <uapi/linux/wait.h>
#include <linux/file.h>
+#include <linux/freezer.h>
#include <linux/fs.h>
#include <linux/anon_inodes.h>
#include <linux/userland.h>
@@ -40,6 +41,8 @@
#include <linux/idr.h>
#include <uapi/linux/userland.h>
+#include "exit.h"
+
void userland_put(struct userland *c)
{
if (!c || !refcount_dec_and_test(&c->usage))
@@ -213,6 +216,86 @@ static long userland_share_nsfd(struct userland *c, unsigned long arg)
return 0;
}
+/**
+ * DOC: P_USERLAND
+ *
+ * ``waitid(P_USERLAND, userland_fd, infop, options, NULL)`` waits freezably until
+ * ``userland_fd`` reaches ``USERLAND_DEAD`` (unless ``WNOHANG`` or ``O_NONBLOCK`` is
+ * set) and writes init's exit information into ``infop`` without consuming it.
+ * ``options`` must include ``WEXITED`` and may include ``WNOHANG`` and
+ * ``WNOWAIT``; ``rusage`` must be ``NULL``, and the caller must run in an
+ * ancestor active PID namespace.
+ */
+long userland_waitid(int upid, struct waitid_info *infop, int options,
+ struct rusage *ru)
+{
+ struct pid_namespace *pid_ns;
+ unsigned int f_flags;
+ struct userland *userland;
+ bool nonblock;
+ int status;
+ kuid_t uid;
+ long ret;
+
+ if (upid < 0 || ru)
+ return -EINVAL;
+ if (options & ~(WEXITED | WNOHANG | WNOWAIT))
+ return -EINVAL;
+ if (!(options & WEXITED))
+ return -EINVAL;
+
+ CLASS(fd, f)(upid);
+ if (fd_empty(f) || !userland_is_file(fd_file(f)))
+ return -EBADF;
+
+ f_flags = READ_ONCE(fd_file(f)->f_flags);
+ nonblock = (options & WNOHANG) || (f_flags & O_NONBLOCK);
+ userland = fd_file(f)->private_data;
+ pid_ns = task_active_pid_ns(current);
+
+ if (!pidns_is_ancestor(userland->ns->pid_ns_for_children, pid_ns))
+ return -ECHILD;
+ for (;;) {
+ enum userland_state state;
+
+ scoped_guard(spinlock, &userland->lock) {
+ state = userland->state;
+ if (state == USERLAND_INIT)
+ return -ECHILD;
+ if (state == USERLAND_DEAD) {
+ ret = pid_nr_ns(userland->init_pid, pid_ns);
+ if (ret <= 0)
+ return -ECHILD;
+ status = userland->exit_code;
+ uid = userland->init_uid;
+ }
+ }
+ if (state == USERLAND_DEAD)
+ break;
+ if (nonblock)
+ return (options & WNOHANG) ? 0 : -EAGAIN;
+
+ ret = wait_event_freezable(userland->waitq,
+ READ_ONCE(userland->state) ==
+ USERLAND_DEAD ||
+ READ_ONCE(userland->state) ==
+ USERLAND_INIT);
+ if (ret)
+ return ret;
+ }
+
+ if ((status & 0x7f) == 0) {
+ infop->cause = CLD_EXITED;
+ infop->status = status >> 8;
+ } else {
+ infop->cause = (status & 0x80) ? CLD_DUMPED : CLD_KILLED;
+ infop->status = status & 0x7f;
+ }
+ infop->pid = ret;
+ infop->uid = from_kuid_munged(current_user_ns(), uid);
+ return ret;
+}
+
static long userland_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct userland *userland = file->private_data;
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 16/26] signal: Support userland fds in pidfd_send_signal()
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (14 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 15/26] exit: Support P_USERLAND in waitid() Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 17/26] fork: Support CLONE_INTO_USERLAND in clone3() Jarkko Sakkinen
` (9 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
Signaling every process inside a userland from userspace via /proc is
racy against concurrent fork() calls.
Teach pidfd_send_signal() to dispatch userland file descriptors to
userland_send_signal() when info is NULL and flags is 0. Require an
ancestor active PID namespace, walk the userland's PID namespace IDR
under tasklist_lock, and deliver a validated signal once to each thread
group including in-flight forks by member processes, aggregating
per-process delivery results.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
include/linux/userland.h | 10 +++++++
kernel/signal.c | 4 +++
kernel/userland.c | 59 ++++++++++++++++++++++++++++++++++++++++
3 files changed, 73 insertions(+)
diff --git a/include/linux/userland.h b/include/linux/userland.h
index 16988e10f623..da0978db54dd 100644
--- a/include/linux/userland.h
+++ b/include/linux/userland.h
@@ -17,6 +17,7 @@ struct nsproxy;
struct pid;
struct pid_namespace;
struct rusage;
+struct siginfo;
struct task_struct;
struct user_namespace;
struct waitid_info;
@@ -77,6 +78,8 @@ void userland_copy(struct task_struct *tsk, struct pid *pid,
void userland_exit(struct pid_namespace *pid_ns, struct task_struct *tsk);
long userland_waitid(int upid, struct waitid_info *infop, int options,
struct rusage *ru);
+int userland_send_signal(struct file *file, int sig,
+ struct siginfo __user *info, unsigned int flags);
#else
static inline void userland_put(struct userland *c)
{
@@ -102,6 +105,13 @@ static inline long userland_waitid(int upid, struct waitid_info *infop,
{
return -EINVAL;
}
+
+static inline int userland_send_signal(struct file *file, int sig,
+ struct siginfo __user *info,
+ unsigned int flags)
+{
+ return -EBADF;
+}
#endif /* CONFIG_USERLAND */
#endif /* _LINUX_USERLAND_H */
diff --git a/kernel/signal.c b/kernel/signal.c
index dd770e68faee..5b11e67dc98a 100644
--- a/kernel/signal.c
+++ b/kernel/signal.c
@@ -37,6 +37,7 @@
#include <linux/capability.h>
#include <linux/freezer.h>
#include <linux/pid_namespace.h>
+#include <linux/userland.h>
#include <linux/nsproxy.h>
#include <linux/user_namespace.h>
#include <linux/uprobes.h>
@@ -4181,6 +4182,9 @@ SYSCALL_DEFINE4(pidfd_send_signal, int, pidfd, int, sig,
if (fd_empty(f))
return -EBADF;
+ if (userland_is_file(fd_file(f)))
+ return userland_send_signal(fd_file(f), sig, info, flags);
+
/* Is this a pidfd? */
pid = pidfd_to_pid(fd_file(f));
if (IS_ERR(pid))
diff --git a/kernel/userland.c b/kernel/userland.c
index 3ded663b71af..f449e2ff9152 100644
--- a/kernel/userland.c
+++ b/kernel/userland.c
@@ -296,6 +296,65 @@ long userland_waitid(int upid, struct waitid_info *infop, int options,
return ret;
}
+/**
+ * DOC: pidfd_send_signal
+ *
+ * ``pidfd_send_signal(userland_fd, sig, NULL, 0)`` delivers ``sig`` (or ``0`` for
+ * a permission and existence probe) once to each member thread group in a
+ * running userland. ``info`` must be ``NULL``, ``flags`` must be ``0``, and the
+ * caller must run in an ancestor active PID namespace.
+ */
+int userland_send_signal(struct file *file, int sig,
+ struct siginfo __user *info, unsigned int flags)
+{
+ struct userland *userland = file->private_data;
+ struct pid_namespace *pid_ns = userland->ns->pid_ns_for_children;
+ bool any_success = false;
+ bool any_other = false;
+ bool any_perm = false;
+ int other_err = 0;
+ struct pid *pid;
+ int nr;
+
+ if (info || flags || sig < 0 || !valid_signal(sig))
+ return -EINVAL;
+ if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
+ return -EXDEV;
+ if (READ_ONCE(userland->state) != USERLAND_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 userland_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct userland *userland = file->private_data;
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 17/26] fork: Support CLONE_INTO_USERLAND in clone3()
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (15 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 16/26] signal: Support userland fds in pidfd_send_signal() Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 20:01 ` sashiko-bot
2026-11-22 19:35 ` [RFC PATCH v7 18/26] fs: Support FSCONFIG_SET_USERLAND in fsconfig() Jarkko Sakkinen
` (8 subsequent siblings)
25 siblings, 1 reply; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
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_USERLAND and struct clone_args.userland
(CLONE_ARGS_SIZE_VER3) to spawn a child process directly into a userland
whose root mount has been installed. Transition the userland from
USERLAND_INIT through USERLAND_FORKING to USERLAND_RUNNING for the first
process so it becomes PID 1, serialize concurrent entrants on waitq
until bootstrap resolves, and admit subsequent callers into the running
PID namespace until teardown begins.
Derive child credentials from current, require CAP_SYS_ADMIN and
CAP_SYS_CHROOT in the target user namespace and an ancestor active PID
namespace, preserve caller umask, reset dumpability across user
namespace transitions, commit time namespace vvar mappings after
copy_process() succeeds, and look up the live mount namespace root.
Restrict companion flags to CLONE_VFORK, CLONE_PIDFD,
CLONE_PIDFD_AUTOKILL, CLONE_AUTOREAP, CLONE_CLEAR_SIGHAND,
CLONE_INTO_CGROUP, and CLONE_NNP.
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/sched/task.h | 6 ++
include/linux/userland.h | 15 ++++
include/uapi/linux/sched.h | 5 ++
kernel/cred.c | 27 ++++++-
kernel/fork.c | 70 ++++++++++++++++---
kernel/nsproxy.c | 9 ++-
kernel/userland.c | 139 +++++++++++++++++++++++++++++++++++++
9 files changed, 266 insertions(+), 13 deletions(-)
diff --git a/include/linux/cred.h b/include/linux/cred.h
index 49c26af37349..e0bb4d3eab17 100644
--- a/include/linux/cred.h
+++ b/include/linux/cred.h
@@ -19,6 +19,7 @@
struct cred;
struct inode;
+struct userland;
extern struct task_struct init_task;
@@ -152,7 +153,8 @@ struct cred {
extern void __put_cred(struct cred *);
extern void exit_creds(struct task_struct *);
-extern int copy_creds(struct task_struct *, u64);
+int copy_creds(struct task_struct *tsk, u64 clone_flags,
+ struct userland *userland);
extern const struct cred *get_task_cred(struct task_struct *);
extern struct cred *cred_alloc_blank(void);
extern struct cred *prepare_creds(void);
diff --git a/include/linux/nsproxy.h b/include/linux/nsproxy.h
index d611c40cb4ce..17bd48433bba 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 userland;
struct user_namespace;
/*
@@ -96,7 +97,8 @@ static inline struct cred *nsset_cred(struct nsset *set)
struct nsproxy *create_new_namespaces(u64 flags, struct task_struct *tsk,
struct user_namespace *user_ns,
struct fs_struct *new_fs);
-int copy_namespaces(u64 flags, struct task_struct *tsk);
+int copy_namespaces(u64 flags, struct task_struct *tsk,
+ struct userland *userland);
void switch_cred_namespaces(const struct cred *old, const struct cred *new);
void exit_nsproxy_namespaces(struct task_struct *tsk);
void get_cred_namespaces(struct task_struct *tsk);
diff --git a/include/linux/sched/task.h b/include/linux/sched/task.h
index 90ed5bc3c7af..c21ac74d7b72 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 userland;
/* All the bits taken by the old clone syscall. */
#define CLONE_LEGACY_FLAGS 0xffffffffULL
@@ -39,11 +41,15 @@ struct kernel_clone_args {
/* Number of elements in *set_tid */
size_t set_tid_size;
int cgroup;
+ int userland_fd;
int idle;
int (*fn)(void *);
void *fn_arg;
struct cgroup *cgrp;
struct css_set *cset;
+ struct file *userland_file;
+ struct userland *userland;
+ bool userland_bootstrapping;
unsigned int kill_seq;
};
diff --git a/include/linux/userland.h b/include/linux/userland.h
index da0978db54dd..a9b99642c46e 100644
--- a/include/linux/userland.h
+++ b/include/linux/userland.h
@@ -13,6 +13,7 @@
#include <linux/wait.h>
struct file;
+struct kernel_clone_args;
struct nsproxy;
struct pid;
struct pid_namespace;
@@ -80,6 +81,9 @@ long userland_waitid(int upid, struct waitid_info *infop, int options,
struct rusage *ru);
int userland_send_signal(struct file *file, int sig,
struct siginfo __user *info, unsigned int flags);
+int userland_prepare_fork(struct kernel_clone_args *args);
+int userland_finish_fork(struct kernel_clone_args *args,
+ struct task_struct *p);
#else
static inline void userland_put(struct userland *c)
{
@@ -112,6 +116,17 @@ static inline int userland_send_signal(struct file *file, int sig,
{
return -EBADF;
}
+
+static inline int userland_prepare_fork(struct kernel_clone_args *args)
+{
+ return -EINVAL;
+}
+
+static inline int userland_finish_fork(struct kernel_clone_args *args,
+ struct task_struct *p)
+{
+ return 0;
+}
#endif /* CONFIG_USERLAND */
#endif /* _LINUX_USERLAND_H */
diff --git a/include/uapi/linux/sched.h b/include/uapi/linux/sched.h
index 19ffeba89428..30551f4cdedb 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_USERLAND (1ULL << 38) /* Clone into a userland. */
/*
* cloning flags intersect with CSIGNAL so can be used with unshare and clone3
@@ -94,6 +95,8 @@
* kernel's limit of nested PID namespaces.
* @cgroup: If CLONE_INTO_CGROUP is specified set this to
* a file descriptor for the cgroup.
+ * @userland: If CLONE_INTO_USERLAND is specified set this to
+ * a file descriptor for the userland.
*
* The structure is versioned by size and thus extensible.
* New struct members must go at the end of the struct and
@@ -111,12 +114,14 @@ struct clone_args {
__aligned_u64 set_tid;
__aligned_u64 set_tid_size;
__aligned_u64 cgroup;
+ __aligned_u64 userland;
};
#endif
#define CLONE_ARGS_SIZE_VER0 64 /* sizeof first published struct */
#define CLONE_ARGS_SIZE_VER1 80 /* sizeof second published struct */
#define CLONE_ARGS_SIZE_VER2 88 /* sizeof third published struct */
+#define CLONE_ARGS_SIZE_VER3 96 /* sizeof fourth published struct */
/*
* Scheduling policies
diff --git a/kernel/cred.c b/kernel/cred.c
index d01df40a9a38..6bb83edd22b5 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/userland.h>
#include <linux/security.h>
#include <linux/binfmts.h>
#include <linux/cn_proc.h>
#include <linux/uidgid.h>
+#include <linux/user_namespace.h>
#if 0
#define kdebug(FMT, ...) \
@@ -251,6 +254,9 @@ struct cred *prepare_exec_creds(void)
return new;
}
+static bool cred_cap_issubset(const struct cred *set,
+ const struct cred *subset);
+
/*
* Copy credentials for the new process created by fork()
*
@@ -260,7 +266,8 @@ struct cred *prepare_exec_creds(void)
* The new process gets the current process's subjective credentials as its
* objective and subjective credentials
*/
-int copy_creds(struct task_struct *p, u64 clone_flags)
+int copy_creds(struct task_struct *p, u64 clone_flags,
+ struct userland *userland)
{
struct cred *new;
int ret;
@@ -287,6 +294,24 @@ int copy_creds(struct task_struct *p, u64 clone_flags)
if (!new)
return -ENOMEM;
+ if (userland) {
+ const struct cred *old = current_cred();
+
+ if (new->user_ns != userland->user_ns) {
+ ret = install_user_ns_cred(new, userland->user_ns);
+ if (ret < 0)
+ goto error_put;
+ }
+ if (!cred_cap_issubset(old, new) ||
+ old->user_ns != new->user_ns) {
+ struct task_exec_state *exec_state;
+
+ exec_state = rcu_dereference_protected(p->exec_state, true);
+ if (exec_state != &init_task_exec_state)
+ WRITE_ONCE(exec_state->dumpable, suid_dumpable);
+ }
+ }
+
if (clone_flags & CLONE_NEWUSER) {
ret = create_user_ns(new);
if (ret < 0)
diff --git a/kernel/fork.c b/kernel/fork.c
index d87ab7cbad5e..d8fc18a9af22 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_USERLAND)) == CLONE_VM) {
exec_state = rcu_dereference_protected(current->exec_state, true);
refcount_inc(&exec_state->count);
rcu_assign_pointer(tsk->exec_state, exec_state);
@@ -1633,7 +1634,7 @@ enum copy_fs_flags_t {
};
static int copy_fs(u64 clone_flags, struct task_struct *tsk,
- enum copy_fs_flags_t flags)
+ enum copy_fs_flags_t flags, struct userland *userland)
{
struct fs_struct *fs;
@@ -1649,7 +1650,7 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk,
if (current->nsproxy->mnt_ns != &init_mnt_ns)
return -EINVAL;
fs = userspace_init_fs;
- } else if (flags & COPY_FS_IDLE) {
+ } else if (flags & COPY_FS_IDLE || userland) {
fs = &init_fs;
} else {
fs = current->fs;
@@ -1671,6 +1672,21 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk,
tsk->real_fs = tsk->fs = copy_fs_struct(fs);
if (!tsk->fs)
return -ENOMEM;
+ if (userland) {
+ struct path root __free(path_put) = {};
+ int err;
+
+ err = mnt_ns_get_root(userland->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 +2202,7 @@ __latent_entropy struct task_struct *copy_process(
#ifdef CONFIG_PROVE_LOCKING
DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
#endif
- retval = copy_creds(p, clone_flags);
+ retval = copy_creds(p, clone_flags, args->userland);
if (retval < 0)
goto bad_fork_free;
@@ -2317,7 +2333,7 @@ __latent_entropy struct task_struct *copy_process(
goto bad_fork_cleanup_semundo;
retval = copy_fs(clone_flags, p,
(args->umh ? COPY_FS_UMH : 0) |
- (args->idle ? COPY_FS_IDLE : 0));
+ (args->idle ? COPY_FS_IDLE : 0), args->userland);
if (retval)
goto bad_fork_cleanup_semundo;
retval = copy_sighand(clone_flags, p);
@@ -2329,7 +2345,7 @@ __latent_entropy struct task_struct *copy_process(
retval = copy_mm(clone_flags, p);
if (retval)
goto bad_fork_cleanup_signal;
- retval = copy_namespaces(clone_flags, p);
+ retval = copy_namespaces(clone_flags, p, args->userland);
if (retval)
goto bad_fork_cleanup_mm;
retval = copy_io(clone_flags, p);
@@ -2510,6 +2526,11 @@ __latent_entropy struct task_struct *copy_process(
goto bad_fork_core_free;
}
+ if (unlikely(args->userland_bootstrapping && !is_child_reaper(pid))) {
+ retval = -EBUSY;
+ goto bad_fork_core_free;
+ }
+
/* Let kill terminate clone/fork in the middle */
if (fatal_signal_pending(current)) {
retval = -EINTR;
@@ -2586,7 +2607,7 @@ __latent_entropy struct task_struct *copy_process(
write_unlock_irq(&tasklist_lock);
if (likely(p->pid) && thread_group_leader(p))
- userland_copy(p, pid, NULL);
+ userland_copy(p, pid, args->userland);
if (pidfile)
fd_install(pidfd, pidfile);
@@ -2781,6 +2802,13 @@ pid_t kernel_clone(struct kernel_clone_args *args)
if (!valid_signal(args->exit_signal))
return -EINVAL;
+ if (unlikely(clone_flags & CLONE_INTO_USERLAND)) {
+ int err = userland_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
@@ -2802,6 +2830,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_USERLAND)) {
+ int err = userland_finish_fork(args, p);
+
+ if (err)
+ return err;
+ }
+
if (IS_ERR(p))
return PTR_ERR(p);
@@ -2959,7 +2994,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, userland) !=
+ CLONE_ARGS_SIZE_VER3);
+ BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER3);
if (unlikely(usize > PAGE_SIZE))
return -E2BIG;
@@ -2989,6 +3026,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_USERLAND) &&
+ (args.userland > INT_MAX || usize < CLONE_ARGS_SIZE_VER3))
+ return -EINVAL;
+
*kargs = (struct kernel_clone_args){
.flags = args.flags,
.pidfd = u64_to_user_ptr(args.pidfd),
@@ -3000,6 +3041,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,
+ .userland_fd = args.userland,
};
if (args.set_tid &&
@@ -3040,13 +3082,19 @@ static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
return true;
}
+#define CLONE_INTO_USERLAND_FLAGS \
+ (CLONE_INTO_USERLAND | 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_USERLAND))
return false;
/*
@@ -3064,6 +3112,10 @@ static bool clone3_args_valid(struct kernel_clone_args *kargs)
kargs->exit_signal)
return false;
+ if ((kargs->flags & CLONE_INTO_USERLAND) &&
+ (kargs->flags & ~CLONE_INTO_USERLAND_FLAGS))
+ return false;
+
if (!clone3_stack_valid(kargs))
return false;
diff --git a/kernel/nsproxy.c b/kernel/nsproxy.c
index 3c4161515c3c..90cf3c799152 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/userland.h>
#include <linux/init_task.h>
#include <linux/mnt_namespace.h>
#include <linux/utsname.h>
@@ -166,12 +167,18 @@ struct nsproxy *create_new_namespaces(u64 flags, struct task_struct *tsk,
* called from clone. This now handles copy for nsproxy and all
* namespaces therein.
*/
-int copy_namespaces(u64 flags, struct task_struct *tsk)
+int copy_namespaces(u64 flags, struct task_struct *tsk,
+ struct userland *userland)
{
struct nsproxy *old_ns = tsk->nsproxy;
struct user_namespace *user_ns = task_cred_xxx(tsk, user_ns);
struct nsproxy *new_ns;
+ if (userland) {
+ get_nsproxy(userland->ns);
+ tsk->nsproxy = userland->ns;
+ return 0;
+ }
if (likely(!(flags & (CLONE_NS_ALL & ~CLONE_NEWUSER)))) {
if ((flags & CLONE_VM) ||
likely(old_ns->time_ns_for_children == old_ns->time_ns)) {
diff --git a/kernel/userland.c b/kernel/userland.c
index f449e2ff9152..2375442733b6 100644
--- a/kernel/userland.c
+++ b/kernel/userland.c
@@ -17,6 +17,7 @@
#include <linux/file.h>
#include <linux/freezer.h>
#include <linux/fs.h>
+#include <linux/fs_struct.h>
#include <linux/anon_inodes.h>
#include <linux/userland.h>
#include <linux/sched/signal.h>
@@ -551,3 +552,141 @@ SYSCALL_DEFINE1(userland_open, unsigned int, flags)
return fd;
}
+
+/**
+ * DOC: CLONE_INTO_USERLAND
+ *
+ * Passing ``CLONE_INTO_USERLAND`` in ``struct clone_args.flags`` (with
+ * ``size >= CLONE_ARGS_SIZE_VER3``) spawns the child into the userland identified
+ * by ``struct clone_args.userland`` once ``"/"`` is mounted in its mount
+ * namespace. The first caller bootstraps PID 1 while concurrent bootstrap
+ * callers wait killably; subsequent callers join the running PID namespace
+ * until teardown begins.
+ *
+ * Requires ``CAP_SYS_ADMIN`` and ``CAP_SYS_CHROOT`` in the target user
+ * namespace (plus ``CAP_SYS_CHROOT`` in the caller's user namespace when
+ * chrooted) and an ancestor active PID namespace. May be combined with
+ * ``CLONE_VFORK``, ``CLONE_PIDFD``, ``CLONE_PIDFD_AUTOKILL``,
+ * ``CLONE_AUTOREAP``, ``CLONE_CLEAR_SIGHAND``, ``CLONE_INTO_CGROUP``, and
+ * ``CLONE_NNP``.
+ *
+ * When spawning from outside the userland's user namespace, the child's
+ * credentials are copied from ``current`` and installed into the userland's
+ * user namespace with capabilities recomputed as in ``setns(CLONE_NEWUSER)``
+ * and dumpability reset to ``suid_dumpable``, retaining ``current``'s kernel
+ * UID, GID, and supplementary groups as mapped there.
+ */
+static bool userland_pidns_alive(struct pid_namespace *pid_ns)
+{
+ for (; pid_ns != &init_pid_ns; pid_ns = pid_ns->parent) {
+ if (!(READ_ONCE(pid_ns->pid_allocated) & PIDNS_ADDING))
+ return false;
+ }
+ return true;
+}
+
+int userland_prepare_fork(struct kernel_clone_args *args)
+{
+ struct file *file __free(fput) = fget(args->userland_fd);
+ struct path root __free(path_put) = {};
+ struct pid_namespace *pid_ns;
+ bool bootstrapping = false;
+ struct userland *userland;
+ int ret;
+
+ if (!file)
+ return -EBADF;
+ if (!userland_is_file(file))
+ return -EINVAL;
+
+ userland = file->private_data;
+ if (!ns_capable(userland->user_ns, CAP_SYS_ADMIN) ||
+ !ns_capable(userland->user_ns, CAP_SYS_CHROOT))
+ return -EPERM;
+ if (current_chrooted() && !ns_capable(current_user_ns(), CAP_SYS_CHROOT))
+ return -EPERM;
+
+ pid_ns = userland->ns->pid_ns_for_children;
+ if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
+ return -EXDEV;
+
+ ret = mnt_ns_get_root(userland->ns->mnt_ns, &root);
+ if (ret)
+ return ret;
+
+ for (;;) {
+ bool wait = false;
+
+ scoped_guard(spinlock, &userland->lock) {
+ switch (userland->state) {
+ case USERLAND_INIT:
+ if (!userland_pidns_alive(pid_ns))
+ return -ESRCH;
+ if (READ_ONCE(pid_ns->child_reaper))
+ return -EBUSY;
+ WRITE_ONCE(userland->state, USERLAND_FORKING);
+ bootstrapping = true;
+ break;
+ case USERLAND_FORKING:
+ wait = true;
+ break;
+ case USERLAND_RUNNING:
+ if (!userland_pidns_alive(pid_ns))
+ return -ESRCH;
+ break;
+ case USERLAND_DEAD:
+ return -ESRCH;
+ }
+ }
+ if (!wait)
+ break;
+
+ ret = wait_event_killable(userland->waitq,
+ READ_ONCE(userland->state) !=
+ USERLAND_FORKING);
+ if (ret)
+ return ret;
+ }
+
+ args->userland_file = no_free_ptr(file);
+ args->userland = userland;
+ args->userland_bootstrapping = bootstrapping;
+ return 0;
+}
+
+int userland_finish_fork(struct kernel_clone_args *args,
+ struct task_struct *p)
+{
+ struct file *file __free(fput) = args->userland_file;
+ struct userland *userland = args->userland;
+ struct pid_namespace *pid_ns = userland->ns->pid_ns_for_children;
+ int ret;
+
+ args->userland_file = NULL;
+ args->userland = NULL;
+ if (!IS_ERR(p)) {
+ if (args->userland_bootstrapping)
+ wake_up_all(&userland->waitq);
+ if (current->nsproxy->time_ns != userland->ns->time_ns)
+ timens_commit(p, userland->ns->time_ns);
+ return 0;
+ }
+
+ ret = PTR_ERR(p);
+ if (args->userland_bootstrapping) {
+ scoped_guard(spinlock, &userland->lock) {
+ if (userland->state == USERLAND_FORKING)
+ WRITE_ONCE(userland->state, USERLAND_INIT);
+ }
+ wake_up_all(&userland->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) &&
+ !userland_pidns_alive(pid_ns))
+ return -ESRCH;
+
+ return ret;
+}
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* Re: [RFC PATCH v7 17/26] fork: Support CLONE_INTO_USERLAND in clone3()
2026-11-22 19:35 ` [RFC PATCH v7 17/26] fork: Support CLONE_INTO_USERLAND in clone3() Jarkko Sakkinen
@ 2026-11-22 20:01 ` sashiko-bot
0 siblings, 0 replies; 30+ messages in thread
From: sashiko-bot @ 2026-11-22 20:01 UTC (permalink / raw)
To: Jarkko Sakkinen
Cc: bpf, linux-mm, linux-security-module, Aleksa Sarai,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Arnd Bergmann, Christian Brauner, David Howells, Eric Biggers,
Giuseppe Scrivano, Hugh Dickins, Jan Kara, Jeff Layton,
Jonathan Corbet, Josef Bacik, Kees Cook, KP Singh,
Lennart Poettering, Neal Gompa, Oleg Nesterov, Paul Moore,
Pavel Tikhomirov, Serge Hallyn, Shuah Khan, Zygmunt Krynicki
Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [High] userland: missing namespace owner permission check in
userland_prepare_fork()
- [Medium] fork: missing ancestor PID namespace liveness check in
copy_process()
- [Medium] userland: missing Landlock namespace-use check in
userland_prepare_fork()
--
commit ae368fbd705dc27859acdfc3d94bc11f009bc3b0
Author: Jarkko Sakkinen <jarkko@kernel.org>
fork: Support CLONE_INTO_USERLAND in clone3()
This patch adds CLONE_INTO_USERLAND and struct clone_args.userland to
allow clone3() to spawn a child process directly into an initialized
userland's namespaces and root mount.
[ ... ]
> diff --git a/kernel/fork.c b/kernel/fork.c
> index d87ab7cbad5e9..d8fc18a9af220 100644
> --- a/kernel/fork.c
> +++ b/kernel/fork.c
[ ... ]
> @@ -2510,6 +2526,11 @@ __latent_entropy struct task_struct *copy_process(
> goto bad_fork_core_free;
> }
>
> + if (unlikely(args->userland_bootstrapping && !is_child_reaper(pid))) {
> + retval = -EBUSY;
> + goto bad_fork_core_free;
> + }
> +
> /* Let kill terminate clone/fork in the middle */
> if (fatal_signal_pending(current)) {
> retval = -EINTR;
[Severity: Medium]
Can copy_process() attach a child into a dying ancestor PID namespace when
cloning into a nested userland?
Immediately above this check, copy_process() only tests PIDNS_ADDING on
the leaf ns_of_pid(pid). When current is in an outer PID namespace A and
spawns into a nested userland C whose parent PID namespace is B, B can
enter zap_pid_ns_processes() after alloc_pid() succeeds:
CPU0 (in pid_ns A) CPU1 (init of pid_ns B)
copy_process()
alloc_pid(C)
zap_pid_ns_processes(B)
disable_pid_allocation(B)
read_lock(&tasklist_lock)
/* sends SIGKILL to tasks in B */
read_unlock(&tasklist_lock)
write_lock_irq(&tasklist_lock)
!(C->pid_allocated & PIDNS_ADDING)
-> false (C still has PIDNS_ADDING)
attach_pid(p, PIDTYPE_PID) <-- attached into dying B after SIGKILL
Because current is in A, fatal_signal_pending(current) does not trigger,
and if C is bootstrapping it has no tasks in B->idr to trigger C's
teardown. The new child (with SIGNAL_UNKILLABLE if PID 1 in C) then runs
inside dying namespace B, blocking B's child_reaper in
zap_pid_ns_processes() until the child exits.
[ ... ]
> diff --git a/kernel/userland.c b/kernel/userland.c
> index f449e2ff91522..2375442733b66 100644
> --- a/kernel/userland.c
> +++ b/kernel/userland.c
[ ... ]
> +int userland_prepare_fork(struct kernel_clone_args *args)
> +{
> + struct file *file __free(fput) = fget(args->userland_fd);
> + struct path root __free(path_put) = {};
> + struct pid_namespace *pid_ns;
> + bool bootstrapping = false;
> + struct userland *userland;
> + int ret;
> +
> + if (!file)
> + return -EBADF;
> + if (!userland_is_file(file))
> + return -EINVAL;
> +
> + userland = file->private_data;
> + if (!ns_capable(userland->user_ns, CAP_SYS_ADMIN) ||
> + !ns_capable(userland->user_ns, CAP_SYS_CHROOT))
> + return -EPERM;
> + if (current_chrooted() && !ns_capable(current_user_ns(), CAP_SYS_CHROOT))
> + return -EPERM;
[Severity: High]
Does userland_prepare_fork() allow a process to join shared namespaces in
userland->ns without being a member of those namespaces or holding
CAP_SYS_ADMIN in their owning user namespaces?
userland_share_nsfd() allows binding a cgroup, IPC, UTS, network, or time
namespace owned by a more privileged user namespace (such as init_user_ns)
into userland->ns without CAP_SYS_ADMIN in ns->ops->owner(ns) whenever
is_current_namespace(ns) is true at ioctl time:
kernel/userland.c:userland_share_nsfd() {
...
if (!ns_capable(c->user_ns, CAP_SYS_ADMIN))
return -EPERM;
if (!is_current_namespace(ns) &&
!ns_capable(ns->ops->owner(ns), CAP_SYS_ADMIN))
return -EPERM;
...
}
If the caller (or another process holding the userland fd) later enters a
separate network, IPC, UTS, cgroup, or time namespace,
clone3(CLONE_INTO_USERLAND) only checks capabilities in userland->user_ns
and installs userland->ns directly in copy_namespaces(), letting the
caller escape its namespace isolation into the previously bound namespace.
[Severity: Medium]
Does spawning into a userland also bypass Landlock's
LANDLOCK_PERMISSION_NAMESPACE_USE check?
Landlock mediates entering existing namespaces through the
namespace_install LSM hook (called from validate_ns() during setns()), and
does not implement a userland_clone hook in commit "security: Add userland
LSM hooks". Because userland_prepare_fork(), copy_creds(), and
copy_namespaces() install userland->user_ns and userland->ns without
calling security_namespace_install(), a Landlock-sandboxed task holding a
pre-opened userland fd can enter its namespaces even when
LANDLOCK_PERMISSION_NAMESPACE_USE denies them.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261122193539.3334213-1-jarkko@kernel.org?part=17
^ permalink raw reply [flat|nested] 30+ messages in thread
* [RFC PATCH v7 18/26] fs: Support FSCONFIG_SET_USERLAND in fsconfig()
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (16 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 17/26] fork: Support CLONE_INTO_USERLAND in clone3() Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:58 ` sashiko-bot
2026-11-22 19:35 ` [RFC PATCH v7 19/26] proc: Implement ->set_userland() fs_context operation Jarkko Sakkinen
` (7 subsequent siblings)
25 siblings, 1 reply; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
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 userland.
Add FSCONFIG_SET_USERLAND and the ->set_userland() fs_context operation
so callers holding CAP_SYS_ADMIN in the target userland's user namespace
can bind a newly opened fs_context to that userland once before offering
parameters. Gate userland context binding on explicit FS_USERLAND_MOUNT
opt-in (or FS_USERNS_DELEGATABLE), mark tmpfs, ramfs, and devpts with
FS_USERLAND_MOUNT, refresh fc->cred when FSCONFIG_SET_USERLAND
authorizes and initializes the context, and keep devpts pty_reserve
restricted to host mounts.
Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
Documentation/filesystems/mount_api.rst | 32 +++++-
fs/devpts/inode.c | 4 +-
fs/filesystems.c | 15 +++
fs/fs_context.c | 21 +++-
fs/fsopen.c | 137 ++++++++++++++++++++++--
fs/internal.h | 6 ++
fs/namespace.c | 18 +++-
fs/ramfs/inode.c | 2 +-
include/linux/fs.h | 1 +
include/linux/fs_context.h | 6 ++
include/uapi/linux/mount.h | 1 +
mm/shmem.c | 5 +-
12 files changed, 229 insertions(+), 19 deletions(-)
diff --git a/Documentation/filesystems/mount_api.rst b/Documentation/filesystems/mount_api.rst
index e8b94357b4df..55edc9fdd6fd 100644
--- a/Documentation/filesystems/mount_api.rst
+++ b/Documentation/filesystems/mount_api.rst
@@ -80,6 +80,7 @@ context. This is represented by the fs_context structure::
unsigned int sb_flags_mask;
unsigned int s_iflags;
enum fs_context_purpose purpose:8;
+ bool userland_bound:1;
...
};
@@ -123,7 +124,8 @@ The fs_context fields are as follows:
There are a subset of the namespaces in use by the invoking process. They
retain references on each namespace. The subscribed namespaces may be
replaced by the filesystem to reflect other sources, such as the parent
- mount superblock on an automount.
+ mount superblock on an automount, or to the target userland's
+ namespaces when bound via FSCONFIG_SET_USERLAND.
* ::
@@ -186,6 +188,15 @@ The fs_context fields are as follows:
FS_CONTEXT_FOR_RECONFIGURE Change an existing mount
========================== ======================================
+ * ::
+
+ bool userland_bound:1
+
+ Set when the filesystem context has been bound to a target userland via
+ FSCONFIG_SET_USERLAND. Filesystems may inspect this flag (for example in
+ ->init_fs_context() or ->parse_param()) to distinguish userland-delegated
+ mounts from host mounts.
+
The mount context is created by calling vfs_new_fs_context() or
vfs_dup_fs_context() and is destroyed with put_fs_context(). Note that the
structure is not refcounted.
@@ -214,6 +225,8 @@ The filesystem context points to a table of operations::
int (*parse_param)(struct fs_context *fc,
struct fs_parameter *param);
int (*parse_monolithic)(struct fs_context *fc, void *data);
+ int (*set_userland)(struct fs_context *fc,
+ struct userland *userland);
int (*get_tree)(struct fs_context *fc);
int (*reconfigure)(struct fs_context *fc);
};
@@ -272,6 +285,23 @@ manage the filesystem context. They are as follows:
finds it's the standard key-val list then it may pass it off to
generic_parse_monolithic().
+ * ::
+
+ int (*set_userland)(struct fs_context *fc,
+ struct userland *userland);
+
+ Called by FSCONFIG_SET_USERLAND after updating fc->user_ns, fc->net_ns,
+ and fc->cred, setting fc->userland_bound, and re-running
+ ->init_fs_context(). Filesystems opting into FS_USERLAND_MOUNT (or
+ FS_USERNS_DELEGATABLE) that capture additional namespaces from current in
+ ->init_fs_context() (such as PID or IPC namespaces) can implement this
+ operation to rebind their private context to the target userland's
+ namespaces. It may update fc->user_ns, which must equal userland->user_ns
+ on return or the bind fails with -EOPNOTSUPP.
+
+ On success it should return 0. In the case of an error, it should return
+ a negative error code and the context transitions to FS_CONTEXT_FAILED.
+
* ::
int (*get_tree)(struct fs_context *fc);
diff --git a/fs/devpts/inode.c b/fs/devpts/inode.c
index bd1e8eb26edb..921b67d18fa2 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->userland_bound &&
+ fc->user_ns == &init_user_ns &&
current->nsproxy->mnt_ns == init_task.nsproxy->mnt_ns)
fsi->mount_opts.reserve = true;
@@ -457,7 +459,7 @@ static struct file_system_type devpts_fs_type = {
.init_fs_context = devpts_init_fs_context,
.parameters = devpts_param_specs,
.kill_sb = devpts_kill_sb,
- .fs_flags = FS_USERNS_MOUNT,
+ .fs_flags = FS_USERNS_MOUNT | FS_USERLAND_MOUNT,
};
/*
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..33cc9163c670 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/userland.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,92 @@ static inline const char *fetch_message_locked(struct fc_log *log, size_t len,
return p;
}
+/**
+ * DOC: FSCONFIG_SET_USERLAND
+ *
+ * ``fsconfig(fsfd, FSCONFIG_SET_USERLAND, NULL, NULL, userland_fd)`` binds a newly
+ * opened ``FS_USERLAND_MOUNT`` or ``FS_USERNS_DELEGATABLE`` filesystem context
+ * to ``userland_fd`` once before parameters are supplied. Requires
+ * ``CAP_SYS_ADMIN`` in the userland's user namespace and binds the context to the
+ * userland's user, network, PID (``proc``), and IPC (``mqueue``) namespaces.
+ */
+static int fsconfig_set_userland(struct fs_context *fc, struct fs_parameter *param)
+{
+ struct user_namespace *user_ns;
+ struct net *net;
+ struct userland *c;
+ int ret;
+
+ if (!userland_is_file(param->file))
+ return -EINVAL;
+
+ c = param->file->private_data;
+ user_ns = c->user_ns;
+ if (!ns_capable(user_ns, CAP_SYS_ADMIN))
+ return -EPERM;
+ if (!(fc->fs_type->fs_flags &
+ (FS_USERLAND_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;
+ }
+
+ scoped_guard(spinlock, &c->lock)
+ net = get_net(c->ns->net_ns);
+ put_cred(fc->cred);
+ fc->cred = get_current_cred();
+ put_net(fc->net_ns);
+ fc->net_ns = net;
+ put_user_ns(fc->user_ns);
+ fc->user_ns = get_user_ns(user_ns);
+
+ fc->userland_bound = true;
+ fc->userland_mnt_id = c->ns->mnt_ns->ns.ns_id;
+
+ ret = fc->fs_type->init_fs_context(fc);
+ if (ret < 0) {
+ fc->userland_bound = false;
+ fc->phase = FS_CONTEXT_FAILED;
+ return ret;
+ }
+ fc->need_free = true;
+
+ if (fc->ops->set_userland) {
+ ret = fc->ops->set_userland(fc, c);
+ if (ret < 0) {
+ fc->userland_bound = false;
+ fc->phase = FS_CONTEXT_FAILED;
+ return ret;
+ }
+ }
+ if (fc->user_ns != user_ns) {
+ fc->userland_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 +214,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_USERLAND))
return -EPERM;
if (flags & ~FSOPEN_CLOEXEC)
@@ -137,17 +230,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_USERLAND_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 +321,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 +391,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_USERLAND)
+ return -EPERM;
switch (cmd) {
case FSCONFIG_CMD_CREATE:
return vfs_cmd_create(fc, false);
@@ -298,9 +400,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_USERLAND:
+ if (fc->phase != FS_CONTEXT_AWAITING_NS &&
+ fc->phase != FS_CONTEXT_CREATE_NS)
+ return -EBUSY;
+ return fsconfig_set_userland(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 +500,10 @@ SYSCALL_DEFINE5(fsconfig,
if (!_key || _value || aux < 0)
return -EINVAL;
break;
+ case FSCONFIG_SET_USERLAND:
+ if (_key || _value || aux < 0)
+ return -EINVAL;
+ break;
case FSCONFIG_CMD_CREATE:
case FSCONFIG_CMD_CREATE_EXCL:
case FSCONFIG_CMD_RECONFIGURE:
@@ -457,6 +571,12 @@ SYSCALL_DEFINE5(fsconfig,
goto out_key;
param.dirfd = aux;
break;
+ case FSCONFIG_SET_USERLAND:
+ ret = -EBADF;
+ param.file = fget(aux);
+ if (!param.file)
+ goto out_key;
+ break;
default:
break;
}
@@ -482,6 +602,7 @@ SYSCALL_DEFINE5(fsconfig,
putname(param.name);
break;
case FSCONFIG_SET_FD:
+ case FSCONFIG_SET_USERLAND:
if (param.file)
fput(param.file);
break;
diff --git a/fs/internal.h b/fs/internal.h
index ee3f796241ac..c7b57263ac83 100644
--- a/fs/internal.h
+++ b/fs/internal.h
@@ -40,12 +40,18 @@ int __block_write_begin_int(struct folio *folio, loff_t pos, unsigned len,
*/
extern void __init chrdev_init(void);
+/*
+ * filesystems.c
+ */
+struct file_system_type *get_fs_type_noload(const char *name);
+
/*
* fs_context.c
*/
extern int parse_monolithic_mount_data(struct fs_context *, void *);
extern void vfs_clean_context(struct fs_context *fc);
extern int finish_clean_context(struct fs_context *fc);
+struct fs_context *fs_context_for_unpriv_mount(struct file_system_type *fs_type);
/*
* namei.c
diff --git a/fs/namespace.c b/fs/namespace.c
index b2c89ad2393e..18534cd2d601 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -4716,7 +4716,8 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
!ns_capable(current_user_ns(), CAP_SYS_ADMIN))
return -EPERM;
- if (!(flags & FSMOUNT_NAMESPACE) && !may_mount())
+ if (!(flags & FSMOUNT_NAMESPACE) && !IS_ENABLED(CONFIG_USERLAND) &&
+ !may_mount())
return -EPERM;
if (attr_flags & ~FSMOUNT_VALID_FLAGS)
@@ -4751,6 +4752,16 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
if (ret)
return ret;
+ if (fc->userland_bound) {
+ if (flags & FSMOUNT_NAMESPACE)
+ return -EINVAL;
+ if (!ns_capable(fc->user_ns, CAP_SYS_ADMIN))
+ return -EPERM;
+ } else if (!(flags & FSMOUNT_NAMESPACE) &&
+ IS_ENABLED(CONFIG_USERLAND) && !may_mount()) {
+ return -EPERM;
+ }
+
/* There must be a valid superblock or we can't mount it */
ret = -EINVAL;
if (!fc->root)
@@ -4792,9 +4803,12 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
return FD_ADD((flags & FSMOUNT_CLOEXEC) ? O_CLOEXEC : 0,
open_new_namespace(&new_path, MOUNT_COPY_NEW));
- ns = alloc_mnt_ns(current->nsproxy->mnt_ns->user_ns, true);
+ ns = alloc_mnt_ns(fc->userland_bound ? fc->user_ns :
+ current->nsproxy->mnt_ns->user_ns, true);
if (IS_ERR(ns))
return PTR_ERR(ns);
+ if (fc->userland_bound)
+ ns->seq_origin = fc->userland_mnt_id;
mnt = real_mount(new_path.mnt);
ns->root = mnt;
ns->nr_mounts = 1;
diff --git a/fs/ramfs/inode.c b/fs/ramfs/inode.c
index ef91b933d4e6..d15542145704 100644
--- a/fs/ramfs/inode.c
+++ b/fs/ramfs/inode.c
@@ -319,7 +319,7 @@ static struct file_system_type ramfs_fs_type = {
.init_fs_context = ramfs_init_fs_context,
.parameters = ramfs_fs_parameters,
.kill_sb = ramfs_kill_sb,
- .fs_flags = FS_USERNS_MOUNT,
+ .fs_flags = FS_USERNS_MOUNT | FS_USERLAND_MOUNT,
};
static int __init init_ramfs_fs(void)
diff --git a/include/linux/fs.h b/include/linux/fs.h
index 5b3a100aba77..afb514600372 100644
--- a/include/linux/fs.h
+++ b/include/linux/fs.h
@@ -2306,6 +2306,7 @@ struct file_system_type {
#define FS_USERNS_MOUNT_RESTRICTED 512 /* Restrict mount in userns if not already visible */
#define FS_USERNS_DELEGATABLE 1024 /* Can be mounted inside userns from outside */
#define FS_DISALLOW_NOTIFY 2048 /* No fsnotify marks on its objects */
+#define FS_USERLAND_MOUNT 4096 /* Supports FSCONFIG_SET_USERLAND */
#define FS_RENAME_DOES_D_MOVE 32768 /* FS will handle d_move() during rename() internally. */
int (*init_fs_context)(struct fs_context *);
const struct fs_parameter_spec *parameters;
diff --git a/include/linux/fs_context.h b/include/linux/fs_context.h
index d1727dffecc5..a98e5a40d54c 100644
--- a/include/linux/fs_context.h
+++ b/include/linux/fs_context.h
@@ -23,6 +23,7 @@ struct net;
struct pid_namespace;
struct super_block;
struct user_namespace;
+struct userland;
struct vfsmount;
struct path;
@@ -36,6 +37,8 @@ enum fs_context_purpose {
* Userspace usage phase for fsopen/fspick.
*/
enum fs_context_phase {
+ FS_CONTEXT_AWAITING_NS, /* Unprivileged context awaiting target ns */
+ FS_CONTEXT_CREATE_NS, /* Set namespaces for sb creation */
FS_CONTEXT_CREATE_PARAMS, /* Loading params for sb creation */
FS_CONTEXT_CREATING, /* A superblock is being created */
FS_CONTEXT_AWAITING_MOUNT, /* Superblock created, awaiting fsmount() */
@@ -101,6 +104,7 @@ struct fs_context {
const char *source; /* The source name (eg. dev path) */
void *security; /* LSM options */
void *s_fs_info; /* Proposed s_fs_info */
+ u64 userland_mnt_id; /* Target userland mnt_ns ID */
unsigned int sb_flags; /* Proposed superblock flags (SB_*) */
unsigned int sb_flags_mask; /* Superblock flags that were changed */
unsigned int s_iflags; /* OR'd with sb->s_iflags */
@@ -110,6 +114,7 @@ struct fs_context {
bool global:1; /* Goes into &init_user_ns */
bool oldapi:1; /* Coming from mount(2) */
bool exclusive:1; /* create new superblock, reject existing one */
+ bool userland_bound:1; /* Bound via FSCONFIG_SET_USERLAND */
};
struct fs_context_operations {
@@ -117,6 +122,7 @@ struct fs_context_operations {
int (*dup)(struct fs_context *fc, struct fs_context *src_fc);
int (*parse_param)(struct fs_context *fc, struct fs_parameter *param);
int (*parse_monolithic)(struct fs_context *fc, void *data);
+ int (*set_userland)(struct fs_context *fc, struct userland *userland);
int (*get_tree)(struct fs_context *fc);
int (*reconfigure)(struct fs_context *fc);
};
diff --git a/include/uapi/linux/mount.h b/include/uapi/linux/mount.h
index cb4f7175db02..4c70c0183f5e 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_USERLAND = 9, /* Set target userland, supplied by fd */
};
/*
diff --git a/mm/shmem.c b/mm/shmem.c
index 10cef89b00b0..61503304be6b 100644
--- a/mm/shmem.c
+++ b/mm/shmem.c
@@ -5592,7 +5592,8 @@ static struct file_system_type shmem_fs_type = {
.parameters = shmem_fs_parameters,
#endif
.kill_sb = kill_anon_super,
- .fs_flags = FS_USERNS_MOUNT | FS_ALLOW_IDMAP | FS_MGTIME,
+ .fs_flags = FS_USERNS_MOUNT | FS_USERLAND_MOUNT |
+ FS_ALLOW_IDMAP | FS_MGTIME,
};
#if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS)
@@ -6021,7 +6022,7 @@ static struct file_system_type shmem_fs_type = {
.init_fs_context = ramfs_init_fs_context,
.parameters = ramfs_fs_parameters,
.kill_sb = ramfs_kill_sb,
- .fs_flags = FS_USERNS_MOUNT,
+ .fs_flags = FS_USERNS_MOUNT | FS_USERLAND_MOUNT,
};
void __init shmem_init(void)
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* Re: [RFC PATCH v7 18/26] fs: Support FSCONFIG_SET_USERLAND in fsconfig()
2026-11-22 19:35 ` [RFC PATCH v7 18/26] fs: Support FSCONFIG_SET_USERLAND in fsconfig() Jarkko Sakkinen
@ 2026-11-22 19:58 ` sashiko-bot
0 siblings, 0 replies; 30+ messages in thread
From: sashiko-bot @ 2026-11-22 19:58 UTC (permalink / raw)
To: Jarkko Sakkinen
Cc: bpf, linux-mm, linux-security-module, Aleksa Sarai,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Arnd Bergmann, Christian Brauner, David Howells, Eric Biggers,
Giuseppe Scrivano, Hugh Dickins, Jan Kara, Jeff Layton,
Jonathan Corbet, Josef Bacik, Kees Cook, KP Singh,
Lennart Poettering, Neal Gompa, Oleg Nesterov, Paul Moore,
Pavel Tikhomirov, Serge Hallyn, Shuah Khan, Zygmunt Krynicki
Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [High] devpts: missing fc->user_ns uid and gid mapping check in
devpts_parse_param()
--
commit 5f6b9ba4a78b24bfe4f6ba168eb1ea41dd809f38
Author: Jarkko Sakkinen <jarkko@kernel.org>
fs: Support FSCONFIG_SET_USERLAND in fsconfig()
This commit adds FSCONFIG_SET_USERLAND and the ->set_userland() fs_context
operation so callers with CAP_SYS_ADMIN in a target userland's user
namespace can bind a newly opened fs_context to that userland, and marks
tmpfs, ramfs, and devpts with FS_USERLAND_MOUNT.
> diff --git a/fs/devpts/inode.c b/fs/devpts/inode.c
> index bd1e8eb26edb7..921b67d18fa2e 100644
> --- a/fs/devpts/inode.c
> +++ b/fs/devpts/inode.c
[ ... ]
> @@ -457,7 +459,7 @@ static struct file_system_type devpts_fs_type = {
> .init_fs_context = devpts_init_fs_context,
> .parameters = devpts_param_specs,
> .kill_sb = devpts_kill_sb,
> - .fs_flags = FS_USERNS_MOUNT,
> + .fs_flags = FS_USERNS_MOUNT | FS_USERLAND_MOUNT,
> };
[Severity: High]
Can opting devpts into FS_USERLAND_MOUNT allow an unprivileged user in an
outer user namespace to configure opts->uid and opts->gid to host UIDs and
GIDs that have no mapping in fc->user_ns?
When a caller binds a devpts context to a target userland via
FSCONFIG_SET_USERLAND and passes uid or gid options, fs_parse() resolves
fsparam_uid and fsparam_gid against current_user_ns() rather than
fc->user_ns. Unlike shmem_parse_one(), devpts_parse_param() does not
verify that the resulting IDs are mapped in fc->user_ns:
fs/devpts/inode.c:devpts_parse_param() {
...
case Opt_uid:
opts->uid = result.uid;
opts->setuid = 1;
break;
case Opt_gid:
opts->gid = result.gid;
opts->setgid = 1;
break;
...
}
devpts_pty_new() then assigns opts->uid and opts->gid directly to newly
allocated slave PTY device inodes on a superblock where SB_I_NODEV is
cleared, creating character device nodes owned by arbitrary unmapped host
UIDs and GIDs inside the userns-mounted devpts instance.
Should devpts_parse_param() check kuid_has_mapping(fc->user_ns, result.uid)
and kgid_has_mapping(fc->user_ns, result.gid) before accepting Opt_uid and
Opt_gid?
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261122193539.3334213-1-jarkko@kernel.org?part=18
^ permalink raw reply [flat|nested] 30+ messages in thread
* [RFC PATCH v7 19/26] proc: Implement ->set_userland() fs_context operation
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (17 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 18/26] fs: Support FSCONFIG_SET_USERLAND in fsconfig() Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 20/26] ipc/mqueue: " Jarkko Sakkinen
` (6 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
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_USERLAND and leaving the context
attached to the caller's PID namespace.
Wire up proc_set_userland() to verify that the target userland's PID
namespace is a descendant of the caller's active PID namespace and
rebind ctx->pid_ns and fc->user_ns accordingly, and mark proc with
FS_USERLAND_MOUNT.
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 | 26 +++++++++++++++++++++++++-
1 file changed, 25 insertions(+), 1 deletion(-)
diff --git a/fs/proc/root.c b/fs/proc/root.c
index 7fbbe92bf73a..e61b1a559172 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/userland.h>
#include <linux/user_namespace.h>
#include <linux/fs_context.h>
#include <linux/mount.h>
@@ -206,6 +208,10 @@ static int proc_parse_param(struct fs_context *fc, struct fs_parameter *param)
errorfc(fc, "cannot reconfigure pidns for existing procfs");
return -EBUSY;
}
+ if (fc->userland_bound) {
+ errorfc(fc, "cannot override pidns on userland-bound procfs");
+ return -EBUSY;
+ }
err = proc_parse_pidns_param(fc, param, &result);
if (err)
return err;
@@ -323,6 +329,21 @@ static int proc_get_tree(struct fs_context *fc)
return get_tree_nodev(fc, proc_fill_super);
}
+static int proc_set_userland(struct fs_context *fc, struct userland *userland)
+{
+ struct proc_fs_context *ctx = fc->fs_private;
+ struct pid_namespace *target = userland->ns->pid_ns_for_children;
+
+ if (!pidns_is_ancestor(target, task_active_pid_ns(current)))
+ return invalfc(fc, "cannot set pidns to non-descendant pidns");
+
+ put_pid_ns(ctx->pid_ns);
+ ctx->pid_ns = get_pid_ns(target);
+ put_user_ns(fc->user_ns);
+ fc->user_ns = get_user_ns(ctx->pid_ns->user_ns);
+ return 0;
+}
+
static void proc_fs_context_free(struct fs_context *fc)
{
struct proc_fs_context *ctx = fc->fs_private;
@@ -334,6 +355,7 @@ static void proc_fs_context_free(struct fs_context *fc)
static const struct fs_context_operations proc_fs_context_ops = {
.free = proc_fs_context_free,
.parse_param = proc_parse_param,
+ .set_userland = proc_set_userland,
.get_tree = proc_get_tree,
.reconfigure = proc_reconfigure,
};
@@ -371,7 +393,9 @@ static struct file_system_type proc_fs_type = {
.init_fs_context = proc_init_fs_context,
.parameters = proc_fs_parameters,
.kill_sb = proc_kill_sb,
- .fs_flags = FS_USERNS_MOUNT | FS_USERNS_MOUNT_RESTRICTED | FS_DISALLOW_NOTIFY_PERM,
+ .fs_flags = FS_USERNS_MOUNT | FS_USERLAND_MOUNT |
+ FS_USERNS_MOUNT_RESTRICTED |
+ FS_DISALLOW_NOTIFY_PERM,
};
void __init proc_root_init(void)
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 20/26] ipc/mqueue: Implement ->set_userland() fs_context operation
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (18 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 19/26] proc: Implement ->set_userland() fs_context operation Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 21/26] security: Add userland LSM hooks Jarkko Sakkinen
` (5 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
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_USERLAND and leaving the context bound to the
caller's IPC namespace.
Wire up mqueue_set_userland() to switch ctx->ipc_ns to the target
userland's IPC namespace, update fc->user_ns to match, and mark mqueue
with FS_USERLAND_MOUNT.
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 | 18 +++++++++++++++++-
1 file changed, 17 insertions(+), 1 deletion(-)
diff --git a/ipc/mqueue.c b/ipc/mqueue.c
index 322c3dd98c44..f3079f7d888b 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/userland.h>
#include <linux/ipc_namespace.h>
#include <linux/user_namespace.h>
#include <linux/slab.h>
@@ -400,6 +401,20 @@ static struct inode *mqueue_get_inode(struct super_block *sb,
return ERR_PTR(ret);
}
+static int mqueue_set_userland(struct fs_context *fc, struct userland *userland)
+{
+ struct mqueue_fs_context *ctx = fc->fs_private;
+ struct ipc_namespace *ipc_ns;
+
+ scoped_guard(spinlock, &userland->lock)
+ ipc_ns = get_ipc_ns(userland->ns->ipc_ns);
+ put_ipc_ns(ctx->ipc_ns);
+ ctx->ipc_ns = ipc_ns;
+ put_user_ns(fc->user_ns);
+ fc->user_ns = get_user_ns(ipc_ns->user_ns);
+ return 0;
+}
+
static int mqueue_fill_super(struct super_block *sb, struct fs_context *fc)
{
struct inode *inode;
@@ -1613,6 +1628,7 @@ static const struct super_operations mqueue_super_ops = {
static const struct fs_context_operations mqueue_fs_context_ops = {
.free = mqueue_fs_context_free,
+ .set_userland = mqueue_set_userland,
.get_tree = mqueue_get_tree,
};
@@ -1620,7 +1636,7 @@ static struct file_system_type mqueue_fs_type = {
.name = "mqueue",
.init_fs_context = mqueue_init_fs_context,
.kill_sb = kill_anon_super,
- .fs_flags = FS_USERNS_MOUNT,
+ .fs_flags = FS_USERNS_MOUNT | FS_USERLAND_MOUNT,
};
int mq_init_ns(struct ipc_namespace *ns)
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 21/26] security: Add userland LSM hooks
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (19 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 20/26] ipc/mqueue: " Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 22/26] bpf: Register " Jarkko Sakkinen
` (4 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
Security modules need visibility into userland creation, teardown,
namespace sharing, process entry, and userland-wide signal delivery so
policies can attach per-userland security state and mediate operations
on userland file descriptors.
Add lbs_userland and userland->security blob management alongside
security_userland_alloc(), security_userland_free(),
security_userland_share(), security_userland_clone(), and
security_userland_kill().
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
include/linux/lsm_hook_defs.h | 8 ++++
include/linux/lsm_hooks.h | 3 ++
include/linux/security.h | 37 ++++++++++++++++++
include/linux/userland.h | 3 ++
kernel/userland.c | 43 ++++++++++++++++-----
security/lsm_init.c | 6 +++
security/security.c | 72 +++++++++++++++++++++++++++++++++++
7 files changed, 163 insertions(+), 9 deletions(-)
diff --git a/include/linux/lsm_hook_defs.h b/include/linux/lsm_hook_defs.h
index 87d9d06710cb..be858bfdc534 100644
--- a/include/linux/lsm_hook_defs.h
+++ b/include/linux/lsm_hook_defs.h
@@ -480,3 +480,11 @@ LSM_HOOK(int, 0, bdev_alloc_security, struct block_device *bdev)
LSM_HOOK(void, LSM_RET_VOID, bdev_free_security, struct block_device *bdev)
LSM_HOOK(int, 0, bdev_setintegrity, struct block_device *bdev,
enum lsm_integrity_type type, const void *value, size_t size)
+
+#ifdef CONFIG_USERLAND
+LSM_HOOK(int, 0, userland_alloc, struct userland *userland, unsigned int flags)
+LSM_HOOK(void, LSM_RET_VOID, userland_free, struct userland *userland)
+LSM_HOOK(int, 0, userland_share, struct userland *userland, struct ns_common *ns)
+LSM_HOOK(int, 0, userland_clone, struct userland *userland)
+LSM_HOOK(int, 0, userland_kill, struct userland *userland, int sig)
+#endif /* CONFIG_USERLAND */
diff --git a/include/linux/lsm_hooks.h b/include/linux/lsm_hooks.h
index 13621e9e233e..7c18370ac427 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_USERLAND
+ unsigned int lbs_userland;
+#endif
};
/*
diff --git a/include/linux/security.h b/include/linux/security.h
index 40831fab5470..2638ee1aa397 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 userland;
enum lsm_event {
LSM_POLICY_CHANGE,
@@ -2469,4 +2470,40 @@ static inline void security_initramfs_populated(void)
}
#endif /* CONFIG_SECURITY */
+#ifdef CONFIG_USERLAND
+#ifdef CONFIG_SECURITY
+int security_userland_alloc(struct userland *userland, unsigned int flags);
+void security_userland_free(struct userland *userland);
+int security_userland_share(struct userland *userland, struct ns_common *ns);
+int security_userland_clone(struct userland *userland);
+int security_userland_kill(struct userland *userland, int sig);
+#else
+static inline int security_userland_alloc(struct userland *userland,
+ unsigned int flags)
+{
+ return 0;
+}
+
+static inline void security_userland_free(struct userland *userland)
+{
+}
+
+static inline int security_userland_share(struct userland *userland,
+ struct ns_common *ns)
+{
+ return 0;
+}
+
+static inline int security_userland_clone(struct userland *userland)
+{
+ return 0;
+}
+
+static inline int security_userland_kill(struct userland *userland, int sig)
+{
+ return 0;
+}
+#endif /* CONFIG_SECURITY */
+#endif /* CONFIG_USERLAND */
+
#endif /* ! __LINUX_SECURITY_H */
diff --git a/include/linux/userland.h b/include/linux/userland.h
index a9b99642c46e..eecee199fad7 100644
--- a/include/linux/userland.h
+++ b/include/linux/userland.h
@@ -61,6 +61,9 @@ enum userland_state {
struct userland {
refcount_t usage;
int exit_code;
+#ifdef CONFIG_SECURITY
+ void *security;
+#endif
struct user_namespace *user_ns;
struct nsproxy *ns;
struct pid *init_pid;
diff --git a/kernel/userland.c b/kernel/userland.c
index 2375442733b6..0a6c6179f629 100644
--- a/kernel/userland.c
+++ b/kernel/userland.c
@@ -40,15 +40,13 @@
#include <linux/uts_namespace.h>
#include <net/net_namespace.h>
#include <linux/idr.h>
+#include <linux/security.h>
#include <uapi/linux/userland.h>
#include "exit.h"
-void userland_put(struct userland *c)
+static void userland_free(struct userland *c)
{
- if (!c || !refcount_dec_and_test(&c->usage))
- return;
-
if (c->ns)
put_nsproxy(c->ns);
if (c->init_pid)
@@ -60,6 +58,15 @@ void userland_put(struct userland *c)
kfree(c);
}
+void userland_put(struct userland *c)
+{
+ if (!c || !refcount_dec_and_test(&c->usage))
+ return;
+
+ security_userland_free(c);
+ userland_free(c);
+}
+
static __poll_t userland_poll(struct file *file, poll_table *wait)
{
struct userland *userland = file->private_data;
@@ -136,6 +143,7 @@ static long userland_share_nsfd(struct userland *c, unsigned long arg)
struct ns_common *old_time_children = NULL;
struct ns_common *old_ns = NULL;
struct ns_common *ns;
+ int ret;
if (arg > INT_MAX)
return -EBADF;
@@ -167,6 +175,10 @@ static long userland_share_nsfd(struct userland *c, unsigned long arg)
!ns_capable(ns->ops->owner(ns), CAP_SYS_ADMIN))
return -EPERM;
+ ret = security_userland_share(c, ns);
+ if (ret)
+ return ret;
+
scoped_guard(spinlock, &c->lock) {
if (c->state != USERLAND_INIT)
return -EBUSY;
@@ -315,6 +327,7 @@ int userland_send_signal(struct file *file, int sig,
bool any_perm = false;
int other_err = 0;
struct pid *pid;
+ int ret;
int nr;
if (info || flags || sig < 0 || !valid_signal(sig))
@@ -324,6 +337,10 @@ int userland_send_signal(struct file *file, int sig,
if (READ_ONCE(userland->state) != USERLAND_RUNNING)
return -ESRCH;
+ ret = security_userland_kill(userland, sig);
+ if (ret)
+ return ret;
+
scoped_guard(rcu) {
read_lock(&tasklist_lock);
idr_for_each_entry(&pid_ns->idr, pid, nr) {
@@ -489,20 +506,20 @@ static struct userland *userland_create(unsigned int flags)
user_ns = userland_create_user_ns();
if (IS_ERR(user_ns)) {
ret = PTR_ERR(user_ns);
- goto err_put;
+ goto err_free;
}
c->user_ns = user_ns;
ns_ref_active_get(user_ns);
if (!ns_capable(user_ns, CAP_SYS_ADMIN)) {
ret = -EPERM;
- goto err_put;
+ goto err_free;
}
ns = create_new_namespaces(clone_flags, current, user_ns, NULL);
if (IS_ERR(ns)) {
ret = PTR_ERR(ns);
- goto err_put;
+ goto err_free;
}
if (ns->time_ns != ns->time_ns_for_children) {
@@ -513,10 +530,14 @@ static struct userland *userland_create(unsigned int flags)
c->ns = ns;
nsproxy_ns_active_get(ns);
+ ret = security_userland_alloc(c, flags);
+ if (ret < 0)
+ goto err_free;
+
return c;
-err_put:
- userland_put(c);
+err_free:
+ userland_free(c);
return ERR_PTR(ret);
}
@@ -610,6 +631,10 @@ int userland_prepare_fork(struct kernel_clone_args *args)
if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
return -EXDEV;
+ ret = security_userland_clone(userland);
+ if (ret)
+ return ret;
+
ret = mnt_ns_get_root(userland->ns->mnt_ns, &root);
if (ret)
return ret;
diff --git a/security/lsm_init.c b/security/lsm_init.c
index 8d5ecea99c46..b1af1d922c58 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_USERLAND
+ lsm_blob_size_update(&blobs->lbs_userland, &blob_sizes.lbs_userland);
+#endif
}
/**
@@ -460,6 +463,9 @@ int __init security_init(void)
lsm_pr("blob(bpf_map) size %d\n", blob_sizes.lbs_bpf_map);
lsm_pr("blob(bpf_prog) size %d\n", blob_sizes.lbs_bpf_prog);
lsm_pr("blob(bpf_token) size %d\n", blob_sizes.lbs_bpf_token);
+#ifdef CONFIG_USERLAND
+ lsm_pr("blob(userland) size %d\n", blob_sizes.lbs_userland);
+#endif
}
if (blob_sizes.lbs_file)
diff --git a/security/security.c b/security/security.c
index 4727b8347fc4..8c3a5df21938 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/userland.h>
#include <net/flow.h>
#include <net/sock.h>
@@ -5795,3 +5796,74 @@ void security_initramfs_populated(void)
{
call_void_hook(initramfs_populated);
}
+
+#ifdef CONFIG_USERLAND
+/**
+ * security_userland_alloc() - Allocate LSM blob and check userland creation
+ * @userland: the new userland
+ * @flags: creation flags passed to userland_open()
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int security_userland_alloc(struct userland *userland, unsigned int flags)
+{
+ int rc;
+
+ rc = lsm_blob_alloc(&userland->security, blob_sizes.lbs_userland,
+ GFP_KERNEL);
+ if (unlikely(rc))
+ return rc;
+
+ rc = call_int_hook(userland_alloc, userland, flags);
+ if (unlikely(rc))
+ security_userland_free(userland);
+
+ return rc;
+}
+
+/**
+ * security_userland_free() - Release LSM blob from @userland
+ * @userland: the userland being freed
+ */
+void security_userland_free(struct userland *userland)
+{
+ call_void_hook(userland_free, userland);
+ kfree(userland->security);
+ userland->security = NULL;
+}
+
+/**
+ * security_userland_share() - Check permission to share @ns into @userland
+ * @userland: the target userland
+ * @ns: the namespace being shared
+ *
+ * Return: 0 if permission is granted, negative error code on failure.
+ */
+int security_userland_share(struct userland *userland, struct ns_common *ns)
+{
+ return call_int_hook(userland_share, userland, ns);
+}
+
+/**
+ * security_userland_clone() - Check permission to spawn into @userland
+ * @userland: the target userland
+ *
+ * Return: 0 if permission is granted, negative error code on failure.
+ */
+int security_userland_clone(struct userland *userland)
+{
+ return call_int_hook(userland_clone, userland);
+}
+
+/**
+ * security_userland_kill() - Check permission to signal @userland
+ * @userland: the target userland
+ * @sig: signal number (or 0 for permission probe)
+ *
+ * Return: 0 if permission is granted, negative error code on failure.
+ */
+int security_userland_kill(struct userland *userland, int sig)
+{
+ return call_int_hook(userland_kill, userland, sig);
+}
+#endif /* CONFIG_USERLAND */
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 22/26] bpf: Register userland LSM hooks
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (20 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 21/26] security: Add userland LSM hooks Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 23/26] arch: Wire up userland_open() system call Jarkko Sakkinen
` (3 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
BPF LSM programs need sleepable and untrusted hook classifications for
the userland LSM hooks in order to attach policies to userland
allocation, namespace sharing, cloning, signaling, and release.
Register bpf_lsm_userland_alloc, bpf_lsm_userland_share,
bpf_lsm_userland_clone, and bpf_lsm_userland_kill in
sleepable_lsm_hooks, and bpf_lsm_userland_alloc and
bpf_lsm_userland_free in untrusted_lsm_hooks under CONFIG_USERLAND.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
kernel/bpf/bpf_lsm.c | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/kernel/bpf/bpf_lsm.c b/kernel/bpf/bpf_lsm.c
index 468e63dbd922..ac8508a6b242 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/userland.h>
/* For every LSM hook that allows attachment of BPF programs, declare a nop
* function where a BPF program can be attached. Notably, we qualify each with
@@ -404,6 +405,12 @@ BTF_ID(func, bpf_lsm_task_setscheduler)
BTF_ID(func, bpf_lsm_userns_create)
BTF_ID(func, bpf_lsm_bdev_alloc_security)
BTF_ID(func, bpf_lsm_bdev_setintegrity)
+#ifdef CONFIG_USERLAND
+BTF_ID(func, bpf_lsm_userland_alloc)
+BTF_ID(func, bpf_lsm_userland_share)
+BTF_ID(func, bpf_lsm_userland_clone)
+BTF_ID(func, bpf_lsm_userland_kill)
+#endif /* CONFIG_USERLAND */
BTF_SET_END(sleepable_lsm_hooks)
BTF_SET_START(untrusted_lsm_hooks)
@@ -420,6 +427,10 @@ BTF_ID(func, bpf_lsm_sk_free_security)
BTF_ID(func, bpf_lsm_task_free)
BTF_ID(func, bpf_lsm_bdev_alloc_security)
BTF_ID(func, bpf_lsm_bdev_free_security)
+#ifdef CONFIG_USERLAND
+BTF_ID(func, bpf_lsm_userland_alloc)
+BTF_ID(func, bpf_lsm_userland_free)
+#endif /* CONFIG_USERLAND */
BTF_SET_END(untrusted_lsm_hooks)
bool bpf_lsm_is_sleepable_hook(u32 btf_id)
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 23/26] arch: Wire up userland_open() system call
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (21 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 22/26] bpf: Register " Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 24/26] docs: Document userland uAPI Jarkko Sakkinen
` (2 subsequent siblings)
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
Now that userland lifecycle and VFS mount-tree installation are in
place, expose userland_open() (474, 584 on Alpha) across all
architecture system call tables, asm-generic unistd.h, and the mirrored
copies under tools/.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
arch/alpha/kernel/syscalls/syscall.tbl | 1 +
arch/arm/tools/syscall.tbl | 1 +
arch/arm64/tools/syscall_32.tbl | 1 +
arch/m68k/kernel/syscalls/syscall.tbl | 1 +
arch/microblaze/kernel/syscalls/syscall.tbl | 1 +
arch/mips/kernel/syscalls/syscall_n32.tbl | 1 +
arch/mips/kernel/syscalls/syscall_n64.tbl | 1 +
arch/mips/kernel/syscalls/syscall_o32.tbl | 1 +
arch/parisc/kernel/syscalls/syscall.tbl | 1 +
arch/powerpc/kernel/syscalls/syscall.tbl | 1 +
arch/s390/kernel/syscalls/syscall.tbl | 1 +
arch/sh/kernel/syscalls/syscall.tbl | 1 +
arch/sparc/kernel/syscalls/syscall.tbl | 1 +
arch/x86/entry/syscalls/syscall_32.tbl | 1 +
arch/x86/entry/syscalls/syscall_64.tbl | 1 +
arch/xtensa/kernel/syscalls/syscall.tbl | 1 +
include/uapi/asm-generic/unistd.h | 6 +++++-
scripts/syscall.tbl | 1 +
tools/include/uapi/asm-generic/unistd.h | 6 +++++-
tools/perf/arch/arm/entry/syscalls/syscall.tbl | 1 +
tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl | 1 +
tools/perf/arch/powerpc/entry/syscalls/syscall.tbl | 1 +
tools/perf/arch/s390/entry/syscalls/syscall.tbl | 1 +
tools/perf/arch/sh/entry/syscalls/syscall.tbl | 1 +
tools/perf/arch/sparc/entry/syscalls/syscall.tbl | 1 +
tools/perf/arch/x86/entry/syscalls/syscall_32.tbl | 1 +
tools/perf/arch/x86/entry/syscalls/syscall_64.tbl | 1 +
tools/perf/arch/xtensa/entry/syscalls/syscall.tbl | 1 +
tools/scripts/syscall.tbl | 1 +
29 files changed, 37 insertions(+), 2 deletions(-)
diff --git a/arch/alpha/kernel/syscalls/syscall.tbl b/arch/alpha/kernel/syscalls/syscall.tbl
index 60d330a51476..2d66a28b610d 100644
--- a/arch/alpha/kernel/syscalls/syscall.tbl
+++ b/arch/alpha/kernel/syscalls/syscall.tbl
@@ -513,3 +513,4 @@
581 common rseq_slice_yield sys_rseq_slice_yield
582 common fchroot sys_fchroot
583 common userns_set_idmap sys_userns_set_idmap
+584 common userland_open sys_userland_open
diff --git a/arch/arm/tools/syscall.tbl b/arch/arm/tools/syscall.tbl
index d055515e98cd..4d2608f907de 100644
--- a/arch/arm/tools/syscall.tbl
+++ b/arch/arm/tools/syscall.tbl
@@ -488,3 +488,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/arch/arm64/tools/syscall_32.tbl b/arch/arm64/tools/syscall_32.tbl
index a18982ead3bf..2f3e7a4686bf 100644
--- a/arch/arm64/tools/syscall_32.tbl
+++ b/arch/arm64/tools/syscall_32.tbl
@@ -485,3 +485,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/arch/m68k/kernel/syscalls/syscall.tbl b/arch/m68k/kernel/syscalls/syscall.tbl
index e89ec7d54b8c..ad1b3326c478 100644
--- a/arch/m68k/kernel/syscalls/syscall.tbl
+++ b/arch/m68k/kernel/syscalls/syscall.tbl
@@ -473,3 +473,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/arch/microblaze/kernel/syscalls/syscall.tbl b/arch/microblaze/kernel/syscalls/syscall.tbl
index 0dfcd6f9e4e7..4a9f4e1e7e31 100644
--- a/arch/microblaze/kernel/syscalls/syscall.tbl
+++ b/arch/microblaze/kernel/syscalls/syscall.tbl
@@ -479,3 +479,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/arch/mips/kernel/syscalls/syscall_n32.tbl b/arch/mips/kernel/syscalls/syscall_n32.tbl
index 882ff15f3e6d..7483d569dcb0 100644
--- a/arch/mips/kernel/syscalls/syscall_n32.tbl
+++ b/arch/mips/kernel/syscalls/syscall_n32.tbl
@@ -412,3 +412,4 @@
471 n32 rseq_slice_yield sys_rseq_slice_yield
472 n32 fchroot sys_fchroot
473 n32 userns_set_idmap sys_userns_set_idmap
+474 n32 userland_open sys_userland_open
diff --git a/arch/mips/kernel/syscalls/syscall_n64.tbl b/arch/mips/kernel/syscalls/syscall_n64.tbl
index daa95049baef..fe5c3ab9ffa7 100644
--- a/arch/mips/kernel/syscalls/syscall_n64.tbl
+++ b/arch/mips/kernel/syscalls/syscall_n64.tbl
@@ -388,3 +388,4 @@
471 n64 rseq_slice_yield sys_rseq_slice_yield
472 n64 fchroot sys_fchroot
473 n64 userns_set_idmap sys_userns_set_idmap
+474 n64 userland_open sys_userland_open
diff --git a/arch/mips/kernel/syscalls/syscall_o32.tbl b/arch/mips/kernel/syscalls/syscall_o32.tbl
index 9e0040399fef..233e0b6850ae 100644
--- a/arch/mips/kernel/syscalls/syscall_o32.tbl
+++ b/arch/mips/kernel/syscalls/syscall_o32.tbl
@@ -461,3 +461,4 @@
471 o32 rseq_slice_yield sys_rseq_slice_yield
472 o32 fchroot sys_fchroot
473 o32 userns_set_idmap sys_userns_set_idmap
+474 o32 userland_open sys_userland_open
diff --git a/arch/parisc/kernel/syscalls/syscall.tbl b/arch/parisc/kernel/syscalls/syscall.tbl
index b77482e68d1a..7c251ea35d4c 100644
--- a/arch/parisc/kernel/syscalls/syscall.tbl
+++ b/arch/parisc/kernel/syscalls/syscall.tbl
@@ -472,3 +472,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/arch/powerpc/kernel/syscalls/syscall.tbl b/arch/powerpc/kernel/syscalls/syscall.tbl
index 973562f20a94..b07ab66144b5 100644
--- a/arch/powerpc/kernel/syscalls/syscall.tbl
+++ b/arch/powerpc/kernel/syscalls/syscall.tbl
@@ -564,3 +564,4 @@
471 nospu rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 nospu userns_set_idmap sys_userns_set_idmap
+474 nospu userland_open sys_userland_open
diff --git a/arch/s390/kernel/syscalls/syscall.tbl b/arch/s390/kernel/syscalls/syscall.tbl
index 19d7b234b31b..4daa1f92e171 100644
--- a/arch/s390/kernel/syscalls/syscall.tbl
+++ b/arch/s390/kernel/syscalls/syscall.tbl
@@ -400,3 +400,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/arch/sh/kernel/syscalls/syscall.tbl b/arch/sh/kernel/syscalls/syscall.tbl
index 252e6f9aa04c..df51ac4faaf4 100644
--- a/arch/sh/kernel/syscalls/syscall.tbl
+++ b/arch/sh/kernel/syscalls/syscall.tbl
@@ -477,3 +477,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/arch/sparc/kernel/syscalls/syscall.tbl b/arch/sparc/kernel/syscalls/syscall.tbl
index 1263d0e825c1..3db2b5a99b1f 100644
--- a/arch/sparc/kernel/syscalls/syscall.tbl
+++ b/arch/sparc/kernel/syscalls/syscall.tbl
@@ -519,3 +519,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/arch/x86/entry/syscalls/syscall_32.tbl b/arch/x86/entry/syscalls/syscall_32.tbl
index 0f8c81c584e0..68e3e01c8751 100644
--- a/arch/x86/entry/syscalls/syscall_32.tbl
+++ b/arch/x86/entry/syscalls/syscall_32.tbl
@@ -479,3 +479,4 @@
471 i386 rseq_slice_yield sys_rseq_slice_yield
472 i386 fchroot sys_fchroot
473 i386 userns_set_idmap sys_userns_set_idmap
+474 i386 userland_open sys_userland_open
diff --git a/arch/x86/entry/syscalls/syscall_64.tbl b/arch/x86/entry/syscalls/syscall_64.tbl
index 5452b7567bf8..f8ad4c72a86e 100644
--- a/arch/x86/entry/syscalls/syscall_64.tbl
+++ b/arch/x86/entry/syscalls/syscall_64.tbl
@@ -398,6 +398,7 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
#
# Due to a historical design error, certain syscalls are numbered differently
diff --git a/arch/xtensa/kernel/syscalls/syscall.tbl b/arch/xtensa/kernel/syscalls/syscall.tbl
index f10b491c873c..b87586ff006c 100644
--- a/arch/xtensa/kernel/syscalls/syscall.tbl
+++ b/arch/xtensa/kernel/syscalls/syscall.tbl
@@ -444,3 +444,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/include/uapi/asm-generic/unistd.h b/include/uapi/asm-generic/unistd.h
index 695eac2d356b..201335a08837 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/userland.c */
+#define __NR_userland_open 474
+__SYSCALL(__NR_userland_open, sys_userland_open)
+
#undef __NR_syscalls
-#define __NR_syscalls 474
+#define __NR_syscalls 475
/*
* 32 bit systems traditionally used different
diff --git a/scripts/syscall.tbl b/scripts/syscall.tbl
index 7ba073cc0e80..c3d07ff911a7 100644
--- a/scripts/syscall.tbl
+++ b/scripts/syscall.tbl
@@ -414,3 +414,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/tools/include/uapi/asm-generic/unistd.h b/tools/include/uapi/asm-generic/unistd.h
index 695eac2d356b..201335a08837 100644
--- a/tools/include/uapi/asm-generic/unistd.h
+++ b/tools/include/uapi/asm-generic/unistd.h
@@ -871,8 +871,12 @@ __SYSCALL(__NR_fchroot, sys_fchroot)
#define __NR_userns_set_idmap 473
__SYSCALL(__NR_userns_set_idmap, sys_userns_set_idmap)
+/* kernel/userland.c */
+#define __NR_userland_open 474
+__SYSCALL(__NR_userland_open, sys_userland_open)
+
#undef __NR_syscalls
-#define __NR_syscalls 474
+#define __NR_syscalls 475
/*
* 32 bit systems traditionally used different
diff --git a/tools/perf/arch/arm/entry/syscalls/syscall.tbl b/tools/perf/arch/arm/entry/syscalls/syscall.tbl
index d055515e98cd..4d2608f907de 100644
--- a/tools/perf/arch/arm/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/arm/entry/syscalls/syscall.tbl
@@ -488,3 +488,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl b/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl
index daa95049baef..fe5c3ab9ffa7 100644
--- a/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl
+++ b/tools/perf/arch/mips/entry/syscalls/syscall_n64.tbl
@@ -388,3 +388,4 @@
471 n64 rseq_slice_yield sys_rseq_slice_yield
472 n64 fchroot sys_fchroot
473 n64 userns_set_idmap sys_userns_set_idmap
+474 n64 userland_open sys_userland_open
diff --git a/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl b/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl
index 973562f20a94..b07ab66144b5 100644
--- a/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/powerpc/entry/syscalls/syscall.tbl
@@ -564,3 +564,4 @@
471 nospu rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 nospu userns_set_idmap sys_userns_set_idmap
+474 nospu userland_open sys_userland_open
diff --git a/tools/perf/arch/s390/entry/syscalls/syscall.tbl b/tools/perf/arch/s390/entry/syscalls/syscall.tbl
index 19d7b234b31b..4daa1f92e171 100644
--- a/tools/perf/arch/s390/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/s390/entry/syscalls/syscall.tbl
@@ -400,3 +400,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/tools/perf/arch/sh/entry/syscalls/syscall.tbl b/tools/perf/arch/sh/entry/syscalls/syscall.tbl
index 252e6f9aa04c..df51ac4faaf4 100644
--- a/tools/perf/arch/sh/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/sh/entry/syscalls/syscall.tbl
@@ -477,3 +477,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/tools/perf/arch/sparc/entry/syscalls/syscall.tbl b/tools/perf/arch/sparc/entry/syscalls/syscall.tbl
index 1263d0e825c1..3db2b5a99b1f 100644
--- a/tools/perf/arch/sparc/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/sparc/entry/syscalls/syscall.tbl
@@ -519,3 +519,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl b/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl
index 0f8c81c584e0..68e3e01c8751 100644
--- a/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl
+++ b/tools/perf/arch/x86/entry/syscalls/syscall_32.tbl
@@ -479,3 +479,4 @@
471 i386 rseq_slice_yield sys_rseq_slice_yield
472 i386 fchroot sys_fchroot
473 i386 userns_set_idmap sys_userns_set_idmap
+474 i386 userland_open sys_userland_open
diff --git a/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl b/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl
index 5452b7567bf8..f8ad4c72a86e 100644
--- a/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl
+++ b/tools/perf/arch/x86/entry/syscalls/syscall_64.tbl
@@ -398,6 +398,7 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
#
# Due to a historical design error, certain syscalls are numbered differently
diff --git a/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl b/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl
index f10b491c873c..b87586ff006c 100644
--- a/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl
+++ b/tools/perf/arch/xtensa/entry/syscalls/syscall.tbl
@@ -444,3 +444,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
diff --git a/tools/scripts/syscall.tbl b/tools/scripts/syscall.tbl
index 7ba073cc0e80..c3d07ff911a7 100644
--- a/tools/scripts/syscall.tbl
+++ b/tools/scripts/syscall.tbl
@@ -414,3 +414,4 @@
471 common rseq_slice_yield sys_rseq_slice_yield
472 common fchroot sys_fchroot
473 common userns_set_idmap sys_userns_set_idmap
+474 common userland_open sys_userland_open
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 24/26] docs: Document userland uAPI
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (22 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 23/26] arch: Wire up userland_open() system call Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 25/26] selftests/userland: Add userland test suite Jarkko Sakkinen
2026-11-22 19:35 ` [RFC PATCH v7 26/26] MAINTAINERS: Add entry for USERLAND Jarkko Sakkinen
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
Userspace orchestrators need a clear specification of what a userland
is, its build and live state transitions, USERLAND_GET_NSFD,
USERLAND_SHARE_NSFD, waitid(P_USERLAND), pidfd_send_signal(), mount-tree
construction, user namespace ID mapping, credential rules, and process
creation semantics.
Add Documentation/userspace-api/userland.rst including the kernel-doc
sections, type definitions, ioctl descriptions, and system call
reference from include/linux/userland.h, include/uapi/linux/userland.h,
include/uapi/linux/nsfs.h, kernel/userland.c, kernel/user_namespace.c,
fs/fsopen.c, and fs/namespace.c, and register the userland ioctl magic
in ioctl-number.rst.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
Documentation/userspace-api/index.rst | 1 +
.../userspace-api/ioctl/ioctl-number.rst | 1 +
Documentation/userspace-api/userland.rst | 77 +++++++++++++++++++
3 files changed, 79 insertions(+)
create mode 100644 Documentation/userspace-api/userland.rst
diff --git a/Documentation/userspace-api/index.rst b/Documentation/userspace-api/index.rst
index a68b1bea57a8..ac665b8fea72 100644
--- a/Documentation/userspace-api/index.rst
+++ b/Documentation/userspace-api/index.rst
@@ -17,6 +17,7 @@ System calls
:maxdepth: 1
unshare
+ userland
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..4cf194e7b648 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/userland.h userland 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/userland.rst b/Documentation/userspace-api/userland.rst
new file mode 100644
index 000000000000..e32ea3501472
--- /dev/null
+++ b/Documentation/userspace-api/userland.rst
@@ -0,0 +1,77 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=============
+userland uAPI
+=============
+
+Overview
+========
+
+.. kernel-doc:: kernel/userland.c
+ :doc: Overview
+
+Lifecycle
+=========
+
+.. kernel-doc:: include/linux/userland.h
+ :identifiers: userland_state
+
+Flags
+=====
+
+.. kernel-doc:: include/uapi/linux/userland.h
+ :identifiers: userland_flags
+
+Ioctls
+======
+
+.. kernel-doc:: include/uapi/linux/userland.h
+ :doc: USERLAND_GET_NSFD
+
+.. kernel-doc:: include/uapi/linux/userland.h
+ :doc: USERLAND_SHARE_NSFD
+
+System calls
+============
+
+.. kernel-doc:: kernel/userland.c
+ :identifiers: sys_userland_open
+
+Process creation
+================
+
+.. kernel-doc:: kernel/userland.c
+ :doc: CLONE_INTO_USERLAND
+
+Process waiting
+===============
+
+.. kernel-doc:: kernel/userland.c
+ :doc: P_USERLAND
+
+Signal delivery
+===============
+
+.. kernel-doc:: kernel/userland.c
+ :doc: pidfd_send_signal
+
+Filesystem configuration
+========================
+
+.. kernel-doc:: fs/fsopen.c
+ :doc: FSCONFIG_SET_USERLAND
+
+Mount tree installation
+=======================
+
+.. kernel-doc:: fs/namespace.c
+ :doc: MOVE_MOUNT_T_MNTNS
+
+User namespace ID mapping
+=========================
+
+.. kernel-doc:: include/uapi/linux/nsfs.h
+ :identifiers: userns_idmap_extent userns_flags userns_idmap
+
+.. kernel-doc:: kernel/user_namespace.c
+ :identifiers: sys_userns_set_idmap
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* [RFC PATCH v7 25/26] selftests/userland: Add userland test suite
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (23 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 24/26] docs: Document userland uAPI Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
2026-11-22 19:52 ` sashiko-bot
2026-11-22 19:35 ` [RFC PATCH v7 26/26] MAINTAINERS: Add entry for USERLAND Jarkko Sakkinen
25 siblings, 1 reply; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
Verify the userland_open() control object, namespace sharing,
mount-namespace configuration, waitid(P_USERLAND), pidfd_send_signal(),
and userns_set_idmap() uAPI and security invariants across privileged,
unprivileged, SCM_RIGHTS delegation, and edge-case scenarios.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
tools/testing/selftests/Makefile | 1 +
tools/testing/selftests/userland/Makefile | 6 +
tools/testing/selftests/userland/config | 10 +
.../testing/selftests/userland/test_smoke.sh | 10 +
.../selftests/userland/userland_cells.py | 1088 ++++++++
.../selftests/userland/userland_test.py | 2330 +++++++++++++++++
6 files changed, 3445 insertions(+)
create mode 100644 tools/testing/selftests/userland/Makefile
create mode 100644 tools/testing/selftests/userland/config
create mode 100755 tools/testing/selftests/userland/test_smoke.sh
create mode 100644 tools/testing/selftests/userland/userland_cells.py
create mode 100755 tools/testing/selftests/userland/userland_test.py
diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile
index 07c3719f8b04..4bf12d0cfd1e 100644
--- a/tools/testing/selftests/Makefile
+++ b/tools/testing/selftests/Makefile
@@ -145,6 +145,7 @@ TARGETS += tty
TARGETS += ublk
TARGETS += uevent
TARGETS += user_events
+TARGETS += userland
TARGETS += vDSO
TARGETS += mm
TARGETS += vfio
diff --git a/tools/testing/selftests/userland/Makefile b/tools/testing/selftests/userland/Makefile
new file mode 100644
index 000000000000..566ecb6f7f19
--- /dev/null
+++ b/tools/testing/selftests/userland/Makefile
@@ -0,0 +1,6 @@
+# SPDX-License-Identifier: GPL-2.0
+include ../lib.mk
+
+TEST_PROGS := test_smoke.sh
+TEST_FILES := userland_cells.py userland_test.py
+TEST_INCLUDES := ../kselftest/ksft.py
diff --git a/tools/testing/selftests/userland/config b/tools/testing/selftests/userland/config
new file mode 100644
index 000000000000..c144ef706856
--- /dev/null
+++ b/tools/testing/selftests/userland/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_TIME_NS=y
+CONFIG_TMPFS=y
+CONFIG_USER_NS=y
+CONFIG_UTS_NS=y
+CONFIG_USERLAND=y
diff --git a/tools/testing/selftests/userland/test_smoke.sh b/tools/testing/selftests/userland/test_smoke.sh
new file mode 100755
index 000000000000..fdd4aaa01804
--- /dev/null
+++ b/tools/testing/selftests/userland/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/userland_test.py" "$@"
diff --git a/tools/testing/selftests/userland/userland_cells.py b/tools/testing/selftests/userland/userland_cells.py
new file mode 100644
index 000000000000..586cb5f09ddf
--- /dev/null
+++ b/tools/testing/selftests/userland/userland_cells.py
@@ -0,0 +1,1088 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Copyright (C) 2026 Opinsys Oy
+
+from __future__ import annotations
+
+from collections.abc import Callable, Mapping, Sequence
+from contextlib import suppress
+import ctypes
+from dataclasses import dataclass, field
+from enum import IntEnum, IntFlag
+import errno
+import os
+import platform
+import signal
+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 UserlandFlag(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_USERLAND = 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 UsernsFlag(IntFlag):
+ NONE = 0
+ SETGROUPS_ALLOWED = 1 << 0
+
+
+class MountAttrFlag(IntFlag):
+ NONE = 0
+ RDONLY = 0x00000001
+ NOSUID = 0x00000002
+ NODEV = 0x00000004
+
+
+class MountFlag(IntFlag):
+ REC = 0x4000
+ PRIVATE = 1 << 18
+ SLAVE = 1 << 19
+ 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_USERLAND = 9
+
+
+class PrctlOp(IntEnum):
+ GET_DUMPABLE = 3
+ SET_DUMPABLE = 4
+ SET_KEEPCAPS = 8
+ GET_NO_NEW_PRIVS = 39
+
+
+class WaitIdType(IntEnum):
+ ALL = 0
+ PID = 1
+ PGID = 2
+ PIDFD = 3
+ USERLAND = 4
+
+
+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
+ userland: 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),
+ ("userland", 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
+
+ nr_uid_extents: int
+ nr_gid_extents: int
+ nr_projid_extents: int
+ reserved: int
+ uid_extents: int
+ gid_extents: int
+ projid_extents: int
+ _fields_ = [
+ ("nr_uid_extents", ctypes.c_uint32),
+ ("nr_gid_extents", ctypes.c_uint32),
+ ("nr_projid_extents", ctypes.c_uint32),
+ ("reserved", ctypes.c_uint32),
+ ("uid_extents", ctypes.c_uint64),
+ ("gid_extents", ctypes.c_uint64),
+ ("projid_extents", ctypes.c_uint64),
+ ]
+
+
+class 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_PREFIXES: Final[tuple[str, ...]] = (
+ "alpha",
+ "mips",
+ "powerpc",
+ "ppc",
+ "sparc",
+ )
+
+ @classmethod
+ def _is_wide_ioc_arch(cls) -> bool:
+ return platform.machine().lower().startswith(cls._WIDE_IOC_PREFIXES)
+
+ @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)
+
+ @staticmethod
+ def _build_syscall_numbers() -> dict[str, int]:
+ mach = platform.machine().lower()
+ ptr_size = ctypes.sizeof(ctypes.c_void_p)
+ multiarch = getattr(sys.implementation, "_multiarch", "")
+ arch_legacy: dict[str, int]
+
+ if mach.startswith("alpha"):
+ base = 110
+ arch_legacy = {
+ "pivot_root": 374,
+ "umount2": 22,
+ "waitid": 438,
+ "execveat": 513,
+ }
+ elif mach.startswith("mips"):
+ if ptr_size == 8:
+ base = 5000
+ arch_legacy = {
+ "pivot_root": 5151,
+ "umount2": 5161,
+ "waitid": 5237,
+ "execveat": 5316,
+ }
+ elif "abin32" in multiarch:
+ base = 6000
+ arch_legacy = {
+ "pivot_root": 6151,
+ "umount2": 6161,
+ "waitid": 6241,
+ "execveat": 6320,
+ }
+ else:
+ base = 4000
+ arch_legacy = {
+ "pivot_root": 4216,
+ "umount2": 4052,
+ "waitid": 4278,
+ "execveat": 4356,
+ }
+ elif mach == "x86_64" and ptr_size == 4 and "x32" in multiarch:
+ base = 0x40000000
+ arch_legacy = {
+ "pivot_root": base + 155,
+ "umount2": base + 166,
+ "waitid": base + 529,
+ "execveat": base + 545,
+ }
+ else:
+ base = 0
+ asm_generic = {
+ "pivot_root": 41,
+ "umount2": 39,
+ "waitid": 95,
+ "execveat": 281,
+ }
+ if mach == "x86_64" and ptr_size == 8:
+ arch_legacy = {
+ "pivot_root": 155,
+ "umount2": 166,
+ "waitid": 247,
+ "execveat": 322,
+ }
+ elif mach in ("i386", "i486", "i586", "i686", "x86_64"):
+ arch_legacy = {
+ "pivot_root": 217,
+ "umount2": 52,
+ "waitid": 284,
+ "execveat": 358,
+ }
+ elif mach in ("aarch64", "arm64") and ptr_size == 8:
+ arch_legacy = asm_generic
+ elif mach.startswith(("arm", "aarch64")):
+ arch_legacy = {
+ "pivot_root": 218,
+ "umount2": 52,
+ "waitid": 280,
+ "execveat": 387,
+ }
+ elif mach.startswith(("ppc", "powerpc")):
+ arch_legacy = {
+ "pivot_root": 203,
+ "umount2": 52,
+ "waitid": 272,
+ "execveat": 362,
+ }
+ elif mach.startswith("s390"):
+ arch_legacy = {
+ "pivot_root": 217,
+ "umount2": 52,
+ "waitid": 281,
+ "execveat": 354,
+ }
+ elif mach.startswith("sparc"):
+ arch_legacy = {
+ "pivot_root": 146,
+ "umount2": 45,
+ "waitid": 279,
+ "execveat": 350,
+ }
+ elif mach.startswith(("parisc", "hppa")):
+ arch_legacy = {
+ "pivot_root": 67,
+ "umount2": 52,
+ "waitid": 235,
+ "execveat": 342,
+ }
+ elif mach == "m68k":
+ arch_legacy = {
+ "pivot_root": 217,
+ "umount2": 52,
+ "waitid": 277,
+ "execveat": 355,
+ }
+ elif mach.startswith("microblaze"):
+ arch_legacy = {
+ "pivot_root": 217,
+ "umount2": 52,
+ "waitid": 284,
+ "execveat": 388,
+ }
+ elif mach.startswith("sh"):
+ arch_legacy = {
+ "pivot_root": 217,
+ "umount2": 52,
+ "waitid": 284,
+ "execveat": 376,
+ }
+ elif mach == "xtensa":
+ arch_legacy = {
+ "pivot_root": 175,
+ "umount2": 171,
+ "waitid": 122,
+ "execveat": 341,
+ }
+ else:
+ arch_legacy = asm_generic
+
+ nums: dict[str, int] = {
+ "pidfd_send_signal": base + 424,
+ "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,
+ "userland_open": base + 474,
+ }
+ nums.update(arch_legacy)
+ 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 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 pidfd_send_signal(
+ cls,
+ pidfd: int,
+ sig: int,
+ info_addr: int = 0,
+ flags: int = 0,
+ ) -> None:
+ cls.syscall(
+ "pidfd_send_signal",
+ ctypes.c_int(pidfd),
+ ctypes.c_int(sig),
+ ctypes.c_void_p(info_addr),
+ ctypes.c_uint(flags),
+ )
+
+ @classmethod
+ def waitid_raw(
+ cls,
+ which: int,
+ upid: int,
+ infop_addr: int,
+ options: int,
+ ru_addr: int = 0,
+ ) -> None:
+ cls.syscall(
+ "waitid",
+ ctypes.c_int(which),
+ ctypes.c_int(upid),
+ ctypes.c_void_p(infop_addr),
+ ctypes.c_int(options),
+ ctypes.c_void_p(ru_addr),
+ )
+
+ @classmethod
+ def userns_set_idmap_raw(
+ cls,
+ userns_fd: int,
+ map_addr: int,
+ size: int = UsernsIdmap.SIZE_VER0,
+ flags: int = 0,
+ ) -> None:
+ cls.syscall(
+ "userns_set_idmap",
+ ctypes.c_int(userns_fd),
+ ctypes.c_void_p(map_addr),
+ ctypes.c_size_t(size),
+ ctypes.c_uint(flags),
+ )
+
+ @classmethod
+ def set_userns_idmap(
+ cls,
+ userns_fd: int,
+ uid_extents: Sequence[tuple[int, int, int]] = (),
+ gid_extents: Sequence[tuple[int, int, int]] = (),
+ projid_extents: Sequence[tuple[int, int, int]] = (),
+ *,
+ reserved: int = 0,
+ size: int | None = None,
+ flags: UsernsFlag | int = UsernsFlag.NONE,
+ ) -> None:
+ u_arr = cls._extent_array(uid_extents)
+ g_arr = cls._extent_array(gid_extents)
+ p_arr = cls._extent_array(projid_extents)
+ req = UsernsIdmap(
+ nr_uid_extents=len(uid_extents),
+ nr_gid_extents=len(gid_extents),
+ nr_projid_extents=len(projid_extents),
+ reserved=reserved,
+ uid_extents=ctypes.addressof(u_arr) if u_arr is not None else 0,
+ gid_extents=ctypes.addressof(g_arr) if g_arr is not None else 0,
+ projid_extents=ctypes.addressof(p_arr) if p_arr is not None else 0,
+ )
+ cls.userns_set_idmap_raw(
+ userns_fd,
+ ctypes.addressof(req),
+ ctypes.sizeof(req) if size is None else size,
+ int(flags),
+ )
+
+
+Sys._NR = Sys._build_syscall_numbers()
+Sys._LIBC = ctypes.CDLL(None, use_errno=True)
+Sys._LIBC.syscall.restype = ctypes.c_long
+
+
+class Ioctl(IntEnum):
+ USERLAND_GET_NSFD = Sys.io(0xB9, 0x01)
+ USERLAND_SHARE_NSFD = Sys.io(0xB9, 0x02)
+ NS_GET_USERNS = Sys.io(0xB7, 0x01)
+ NS_GET_PARENT = Sys.io(0xB7, 0x02)
+ NS_GET_NSTYPE = Sys.io(0xB7, 0x03)
+
+
+@dataclass(frozen=True)
+class WaitResult:
+ pid: int
+ status: int = 0
+ code: int = 0
+ uid: int = 0
+
+ @property
+ def exit_code(self) -> int | None:
+ if self.pid <= 0:
+ return None
+ if self.code == os.CLD_EXITED:
+ return self.status
+ if self.code in (os.CLD_KILLED, os.CLD_DUMPED):
+ return -self.status
+ return os.waitstatus_to_exitcode(self.status)
+
+
+class Userland:
+ fd: int
+
+ def __init__(
+ self,
+ flags: UserlandFlag | int = UserlandFlag.DEFAULT,
+ *,
+ fd: int | None = None,
+ ) -> None:
+ if fd is not None:
+ self.fd = fd
+ else:
+ self.fd = Sys.syscall("userland_open", ctypes.c_uint(int(flags)))
+
+ @classmethod
+ def from_fd(cls, fd: int) -> Userland:
+ return cls(fd=fd)
+
+ def fileno(self) -> int:
+ return self.fd
+
+ def __enter__(self) -> Userland:
+ 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.USERLAND_GET_NSFD, int(nstype))
+
+ def share_nsfd(self, nsfd: int) -> None:
+ Sys.ioctl(self.fd, Ioctl.USERLAND_SHARE_NSFD, nsfd)
+
+ def set_idmap(
+ self,
+ uid_extents: Sequence[tuple[int, int, int]] = (),
+ gid_extents: Sequence[tuple[int, int, int]] = (),
+ projid_extents: Sequence[tuple[int, int, int]] = (),
+ *,
+ flags: UsernsFlag | int = UsernsFlag.NONE,
+ ) -> None:
+ 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,
+ flags=flags,
+ )
+ 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),),
+ )
+
+ def wait(self, flags: int = 0) -> WaitResult:
+ res = os.waitid(int(WaitIdType.USERLAND), self.fd, os.WEXITED | flags)
+ if res is None:
+ return WaitResult(pid=0)
+ return WaitResult(
+ pid=int(res.si_pid),
+ status=int(res.si_status),
+ code=int(res.si_code),
+ uid=int(res.si_uid),
+ )
+
+ def kill(self, sig: signal.Signals | int) -> None:
+ Sys.pidfd_send_signal(self.fd, int(sig))
+
+ 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_USERLAND | extra_flags)
+ args.exit_signal = exit_signal
+ args.userland = 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_USERLAND, 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: UserlandFlag = UserlandFlag.DEFAULT
+ rns: Userland = field(init=False)
+ mntns_fd: int = field(init=False, default=-1)
+ root_dfd: int = field(init=False, default=-1)
+
+ def __post_init__(self) -> None:
+ self.rns = Userland(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)
+ 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:
+ return self.rns.wait(os.WNOHANG if nohang else 0)
+
+ 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()
diff --git a/tools/testing/selftests/userland/userland_test.py b/tools/testing/selftests/userland/userland_test.py
new file mode 100755
index 000000000000..2b43adbbb429
--- /dev/null
+++ b/tools/testing/selftests/userland/userland_test.py
@@ -0,0 +1,2330 @@
+#!/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
+import ctypes
+from dataclasses import dataclass
+import errno
+import importlib
+import json
+import os
+from pathlib import Path
+import select
+import signal
+import socket
+import sys
+import tempfile
+import threading
+import traceback
+from types import TracebackType
+from typing import Any, Final, NoReturn
+import unittest
+
+from userland_cells import (
+ AtFlag,
+ Cell,
+ CloneArgs,
+ CloneFlag,
+ FsconfigCmd,
+ Ioctl,
+ MountFlag,
+ MoveMountFlag,
+ OpenTreeFlag,
+ PrctlOp,
+ Sys,
+ UmountFlag,
+ Userland,
+ UserlandFlag,
+ UsernsFlag,
+ UsernsIdmap,
+ WaitIdType,
+ 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_userland", 0, errno.ESRCH),
+)
+
+
+class UserlandTestBase(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 enter_userns_if_unpriv(cls) -> None:
+ if os.geteuid() == 0:
+ return
+ uid = os.geteuid()
+ gid = os.getegid()
+ os.unshare(CloneFlag.NEWUSER | CloneFlag.NEWNS)
+ Path("/proc/self/setgroups").write_bytes(b"deny\n")
+ Path("/proc/self/uid_map").write_bytes(f"0 {uid} 1\n".encode())
+ Path("/proc/self/gid_map").write_bytes(f"0 {gid} 1\n".encode())
+
+ @classmethod
+ def enter_foreign_pidns(cls, rns: Userland) -> None:
+ with cls.closing_fd(rns.get_nsfd(CloneFlag.NEWUSER)) as ufd:
+ os.setns(ufd, CloneFlag.NEWUSER)
+ os.unshare(CloneFlag.NEWPID)
+
+ @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 = Userland()
+ except OSError as exc:
+ if exc.errno in SKIP_ERRNOS:
+ return ProbeResult(
+ False, f"userland_open() unavailable: {exc}"
+ )
+ raise
+ with rns:
+ try:
+ rns.map_self_ugid()
+ mfd = rns.make_mount("tmpfs")
+ except OSError as exc:
+ return ProbeResult(False, f"userland 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_userland_as_uid(self, uid: int) -> Userland | None:
+ s_parent, s_child = socket.socketpair(
+ socket.AF_UNIX, socket.SOCK_SEQPACKET
+ )
+ sys.stdout.flush()
+ sys.stderr.flush()
+ pid = os.fork()
+ if pid == 0:
+ s_parent.close()
+ try:
+ self.drop_to_uid(uid)
+ with Userland() 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_userland_as_uid({uid}) failed with status {code}"
+ )
+ return Userland.from_fd(fds[0]) if fds else None
+
+
+class UserlandUapiTest(UserlandTestBase):
+ 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_cell_lifecycle_exec_and_hot_mount(self) -> None:
+ self._require_cell()
+ with Cell("alpha") as cell:
+ cell.setup_rootfs(mount_procfs=True, host_runtime=True)
+ pid = cell.spawn(WAIT_MOUNT_PAYLOAD.argv())
+ self.assertGreater(pid, 0)
+ cell.mount_fs("tmpfs", "/mnt")
+ cell.spawn(WRITE_MOUNT_PAYLOAD.argv())
+ res = cell.wait()
+ self.assertEqual(res.pid, pid)
+ self.assertEqual(res.exit_code, 0)
+
+ def test_cell_broadcast_kill(self) -> None:
+ self._require_cell()
+ with Cell("killme") as cell:
+ cell.setup_rootfs(mount_procfs=True, host_runtime=True)
+ cell.spawn(PAUSE_PAYLOAD.argv())
+ cell.spawn(PAUSE_PAYLOAD.argv())
+ cell.kill(signal.SIGKILL)
+ res = cell.wait()
+ self.assertEqual(res.exit_code, -int(signal.SIGKILL))
+
+ def test_create_flags(self) -> None:
+ self._require_cell()
+ with Userland(UserlandFlag.NONE):
+ pass
+ with Userland(UserlandFlag.DEFAULT):
+ pass
+ with self.assertRaises(OSError) as cm:
+ Userland((~int(UserlandFlag.ALL)) & 0xFFFFFFFF)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ def test_get_nsfd(self) -> None:
+ try:
+ rns = Userland()
+ except OSError as exc:
+ if exc.errno in SKIP_ERRNOS:
+ self.skipTest(f"userland_open() unavailable: {exc}")
+ raise
+ with rns:
+ for case in NS_TYPE_CASES:
+ with self.subTest(ns=case.name):
+ try:
+ nsfd = rns.get_nsfd(case.nstype)
+ except OSError as exc:
+ if (
+ case.nstype == CloneFlag.NEWTIME
+ and exc.errno == errno.EOPNOTSUPP
+ and not os.path.exists("/proc/self/ns/time")
+ ):
+ continue
+ raise
+ with self.closing_fd(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_share_nsfd(self) -> None:
+ self._require_cell()
+ with Userland() as rns:
+ with self.assertRaises(OSError) as cm:
+ Sys.ioctl(rns.fd, Ioctl.USERLAND_SHARE_NSFD, 99999)
+ self.assertEqual(cm.exception.errno, errno.EBADF)
+
+ with self.assertRaises(OSError) as cm:
+ rns.share_nsfd(rns.fd)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ for bad_type in (CloneFlag.NEWUSER, CloneFlag.NEWNS):
+ with self.closing_fd(rns.get_nsfd(bad_type)) as bad_fd:
+ with self.assertRaises(OSError) as cm:
+ rns.share_nsfd(bad_fd)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.closing_fd(
+ os.open("/proc/self/ns/pid", os.O_RDONLY | os.O_CLOEXEC)
+ ) as pid_fd:
+ with self.assertRaises(OSError) as cm:
+ rns.share_nsfd(pid_fd)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ shareable = (
+ NsTypeCase("cgroup", CloneFlag.NEWCGROUP),
+ NsTypeCase("uts", CloneFlag.NEWUTS),
+ NsTypeCase("ipc", CloneFlag.NEWIPC),
+ NsTypeCase("net", CloneFlag.NEWNET),
+ NsTypeCase("time", CloneFlag.NEWTIME),
+ )
+ for case in shareable:
+ ns_path = f"/proc/self/ns/{case.name}"
+ if not os.path.exists(ns_path):
+ continue
+ with self.subTest(ns=case.name):
+ with (
+ self.closing_fd(
+ os.open(ns_path, os.O_RDONLY | os.O_CLOEXEC)
+ ) as host_fd,
+ self.closing_fd(
+ rns.get_nsfd(case.nstype)
+ ) as orig_fd,
+ ):
+ host_st = os.fstat(host_fd)
+ orig_st = os.fstat(orig_fd)
+ self.assertNotEqual(
+ (orig_st.st_dev, orig_st.st_ino),
+ (host_st.st_dev, host_st.st_ino),
+ )
+ rns.share_nsfd(host_fd)
+ with self.closing_fd(
+ rns.get_nsfd(case.nstype)
+ ) as new_fd:
+ new_st = os.fstat(new_fd)
+ self.assertEqual(
+ (new_st.st_dev, new_st.st_ino),
+ (host_st.st_dev, host_st.st_ino),
+ )
+
+ rns.map_self_ugid()
+ with (
+ self.closing_fd(rns.get_nsfd(CloneFlag.NEWNS)) as mntns_fd,
+ 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,
+ )
+
+ host_net_st = os.stat("/proc/self/ns/net")
+ with (
+ SyncPipe.create() as hold,
+ self.closing_fd(
+ os.open("/proc/self/ns/net", os.O_RDONLY | os.O_CLOEXEC)
+ ) as host_net_fd,
+ ):
+
+ def check_inside_shared() -> int:
+ hold.close_write()
+ st = os.stat("/proc/self/ns/net")
+ ok = (st.st_dev, st.st_ino) == (
+ host_net_st.st_dev,
+ host_net_st.st_ino,
+ )
+ hold.read_bytes()
+ hold.close_read()
+ return 0 if ok else 1
+
+ pid = rns.run(check_inside_shared)
+ hold.close_read()
+ try:
+ with self.assertRaises(OSError) as cm:
+ rns.share_nsfd(host_net_fd)
+ self.assertEqual(cm.exception.errno, errno.EBUSY)
+ finally:
+ hold.close_write()
+ self.assertEqual(rns.wait().exit_code, 0)
+ self.assertEqual(self.reap_exit_code(pid), 0)
+
+ with self.assertRaises(OSError) as cm:
+ rns.share_nsfd(host_net_fd)
+ self.assertEqual(cm.exception.errno, errno.EBUSY)
+
+ with (
+ Userland() as race_rns,
+ self.closing_fd(race_rns.get_nsfd(CloneFlag.NEWNET)) as v_net,
+ self.closing_fd(
+ os.open("/proc/self/ns/net", os.O_RDONLY | os.O_CLOEXEC)
+ ) as h_net,
+ ):
+ errs: list[BaseException] = []
+
+ def share_worker() -> None:
+ try:
+ for _ in range(100):
+ race_rns.share_nsfd(h_net)
+ race_rns.share_nsfd(v_net)
+ except BaseException as exc:
+ errs.append(exc)
+
+ def reader_worker() -> None:
+ try:
+ for _ in range(100):
+ with self.closing_fd(Sys.fsopen("proc")) as fsfd:
+ Sys.fsconfig(
+ fsfd, FsconfigCmd.SET_USERLAND, aux=race_rns.fd
+ )
+ with self.closing_fd(
+ race_rns.get_nsfd(CloneFlag.NEWNET)
+ ):
+ pass
+ try:
+ race_rns.wait(os.WNOHANG)
+ except OSError as exc:
+ if exc.errno != errno.ECHILD:
+ raise
+ try:
+ race_rns.kill(0)
+ except OSError as exc:
+ if exc.errno != errno.ESRCH:
+ raise
+ except BaseException as exc:
+ errs.append(exc)
+
+ t1 = threading.Thread(target=share_worker)
+ t2 = threading.Thread(target=reader_worker)
+ t1.start()
+ t2.start()
+ t1.join()
+ t2.join()
+ self.assertEqual(errs, [])
+
+ if os.geteuid() == 0:
+ with (
+ Userland() as foreign_rns,
+ self.closing_fd(
+ foreign_rns.get_nsfd(CloneFlag.NEWNET)
+ ) as foreign_net,
+ ):
+
+ def check_foreign_share() -> None:
+ try:
+ self.drop_to_uid(1000)
+ except OSError:
+ return
+ try:
+ alice_rns = Userland()
+ except OSError as exc:
+ if exc.errno in SKIP_ERRNOS:
+ return
+ raise
+ with alice_rns:
+ with self.assertRaises(OSError) as cm_f:
+ alice_rns.share_nsfd(foreign_net)
+ self.assertEqual(cm_f.exception.errno, errno.EPERM)
+ with self.closing_fd(
+ os.open(
+ "/proc/self/ns/net",
+ os.O_RDONLY | os.O_CLOEXEC,
+ )
+ ) as own_net:
+ alice_rns.share_nsfd(own_net)
+
+ self.run_forked(check_foreign_share)
+
+ def test_wait_poll_and_clone_dead(self) -> None:
+ cell = self._require_cell()
+ rns = cell.rns
+
+ with self.assertRaises(OSError) as cm:
+ os.waitid(int(WaitIdType.USERLAND), -1, os.WEXITED)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.assertRaises(OSError) as cm:
+ os.waitid(int(WaitIdType.USERLAND), 99999, os.WEXITED)
+ self.assertEqual(cm.exception.errno, errno.EBADF)
+
+ with self.assertRaises(OSError) as cm:
+ os.waitid(int(WaitIdType.USERLAND), cell.mntns_fd, os.WEXITED)
+ self.assertEqual(cm.exception.errno, errno.EBADF)
+
+ with self.assertRaises(OSError) as cm:
+ os.waitid(int(WaitIdType.USERLAND), rns.fd, os.WNOHANG)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.assertRaises(OSError) as cm:
+ rns.wait(os.WSTOPPED)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ ru_buf = ctypes.create_string_buffer(256)
+ with self.assertRaises(OSError) as cm:
+ Sys.waitid_raw(
+ int(WaitIdType.USERLAND),
+ rns.fd,
+ 0,
+ os.WEXITED | os.WNOHANG,
+ ctypes.addressof(ru_buf),
+ )
+ 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))
+
+ os.set_blocking(rns.fd, False)
+ try:
+ with self.assertRaises(OSError) as cm:
+ rns.wait(0)
+ self.assertEqual(cm.exception.errno, errno.EAGAIN)
+ finally:
+ os.set_blocking(rns.fd, True)
+
+ def check_foreign_pidns_wait() -> None:
+ self.enter_foreign_pidns(rns)
+
+ 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 | os.WNOWAIT)
+ self.assertEqual(res.pid, pid)
+ self.assertEqual(res.code, os.CLD_EXITED)
+ self.assertEqual(res.status, 42)
+ self.assertEqual(res.exit_code, 42)
+ self.assertEqual(res.uid, os.geteuid())
+ Sys.waitid_raw(int(WaitIdType.USERLAND), rns.fd, 0, os.WEXITED, 0)
+ self.assertEqual(rns.wait(), res)
+ 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_send_signal_and_kill_on_close(self) -> None:
+ cell = self._require_cell()
+ rns = cell.rns
+
+ with self.assertRaises(OSError) as cm:
+ Sys.pidfd_send_signal(99999, 0)
+ self.assertEqual(cm.exception.errno, errno.EBADF)
+
+ with self.assertRaises(OSError) as cm:
+ Sys.pidfd_send_signal(cell.mntns_fd, 0)
+ self.assertEqual(cm.exception.errno, errno.EBADF)
+
+ with self.assertRaises(OSError) as cm:
+ Sys.pidfd_send_signal(rns.fd, 0, flags=1)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ siginfo_buf = ctypes.create_string_buffer(128)
+ with self.assertRaises(OSError) as cm:
+ Sys.pidfd_send_signal(
+ rns.fd, int(signal.SIGKILL), ctypes.addressof(siginfo_buf)
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ 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()
+
+ def check_foreign_pidns_kill() -> None:
+ self.enter_foreign_pidns(rns)
+
+ def check_inner_kill() -> None:
+ with self.assertRaises(OSError) as cm_k:
+ rns.kill(0)
+ self.assertEqual(cm_k.exception.errno, errno.EXDEV)
+
+ self.run_forked(check_inner_kill)
+
+ self.run_forked(check_foreign_pidns_kill)
+
+ 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=UserlandFlag.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")
+ os.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 ready, SyncPipe.create() as hold:
+
+ def dumpable_child() -> int:
+ ready.close_read()
+ Sys.prctl(PrctlOp.SET_DUMPABLE, 1)
+ ready.write_bytes(b"r")
+ ready.close_write()
+ return hold.wait_in_child()
+
+ pid = cell.rns.run(dumpable_child)
+ ready.close_write()
+ hold.close_read()
+ try:
+ self.assertEqual(ready.read_bytes(), b"r")
+ ready.close_read()
+ with (
+ self.closing_fd(
+ os.open(
+ f"/proc/{pid}/ns/uts", os.O_RDONLY | os.O_CLOEXEC
+ )
+ ) as uts_fd,
+ self.closing_fd(
+ cell.rns.get_nsfd(CloneFlag.NEWUSER)
+ ) as ufd,
+ ):
+
+ def check_owner() -> None:
+ os.setns(ufd, CloneFlag.NEWUSER)
+ os.setns(uts_fd, CloneFlag.NEWUTS)
+
+ self.run_forked(check_owner)
+
+ if os.geteuid() == 0:
+
+ def check_foreign() -> None:
+ try:
+ self.drop_to_uid(1000)
+ except OSError:
+ return
+ self.enter_userns_if_unpriv()
+ with self.assertRaises(OSError) as cm_perm:
+ os.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 (
+ Userland() 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)
+
+ def check_clone_without_mntns() -> None:
+ self.enter_userns_if_unpriv()
+ with self.assertRaises(OSError) as cm_c:
+ Sys.move_mount(
+ Sys.AT_FDCWD,
+ "/tmp",
+ Sys.AT_FDCWD,
+ "/tmp",
+ MoveMountFlag.CLONE,
+ )
+ self.assertEqual(cm_c.exception.errno, errno.EINVAL)
+
+ self.run_forked(check_clone_without_mntns)
+
+ 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_USERLAND, aux=rns.fd)
+ with self.assertRaises(OSError) as cm:
+ Sys.fsconfig(fsfd, FsconfigCmd.SET_USERLAND, aux=rns.fd)
+ self.assertEqual(cm.exception.errno, errno.EBUSY)
+
+ if os.geteuid() == 0:
+ with self.closing_fd(Sys.fsopen("cgroup2")) as cg_fsfd:
+ with self.assertRaises(OSError) as cm:
+ Sys.fsconfig(
+ cg_fsfd, FsconfigCmd.SET_USERLAND, aux=rns.fd
+ )
+ self.assertEqual(cm.exception.errno, errno.EOPNOTSUPP)
+
+ def check_sb_nouser_clone() -> None:
+ self.enter_userns_if_unpriv()
+ with (
+ Userland() as empty_u,
+ self.closing_fd(
+ empty_u.get_nsfd(CloneFlag.NEWUSER)
+ ) as e_ufd,
+ self.closing_fd(
+ empty_u.get_nsfd(CloneFlag.NEWNS)
+ ) as e_mfd,
+ ):
+ empty_u.map_self_ugid()
+ os.setns(e_ufd, int(CloneFlag.NEWUSER))
+ os.setns(e_mfd, int(CloneFlag.NEWNS))
+ with (
+ Userland() as dest_u,
+ self.closing_fd(
+ dest_u.get_nsfd(CloneFlag.NEWNS)
+ ) as d_mfd,
+ ):
+ with self.assertRaises(OSError) as cm_nu:
+ Sys.move_mount(
+ Sys.AT_FDCWD,
+ "/",
+ d_mfd,
+ "/",
+ MoveMountFlag.T_MNTNS | MoveMountFlag.CLONE,
+ )
+ self.assertEqual(cm_nu.exception.errno, errno.EINVAL)
+
+ self.run_forked(check_sb_nouser_clone)
+
+ def check_child_src_slave_locking() -> None:
+ self.enter_userns_if_unpriv()
+ os.unshare(CloneFlag.NEWNS)
+ with self.closing_fd(self.make_plain_mount("tmpfs")) as tfd:
+ os.mkdir("sub", 0o755, dir_fd=tfd)
+ Sys.move_mount(
+ tfd,
+ "",
+ Sys.AT_FDCWD,
+ "/tmp",
+ MoveMountFlag.F_EMPTY_PATH,
+ )
+ Sys.set_mount_propagation(
+ "/tmp", MountFlag.REC | MountFlag.SHARED
+ )
+ s_p, s_c = socket.socketpair(
+ socket.AF_UNIX, socket.SOCK_SEQPACKET
+ )
+ with (
+ Userland() as u2,
+ self.closing_fd(u2.get_nsfd(CloneFlag.NEWUSER)) as u2_ufd,
+ self.closing_fd(
+ os.open(
+ "/proc/self/ns/mnt", os.O_RDONLY | os.O_CLOEXEC
+ )
+ ) as u1_mfd,
+ SyncPipe.create() as s_go,
+ ):
+ u2.map_self_ugid()
+ spid = os.fork()
+ if spid == 0:
+ s_p.close()
+ s_go.close_write()
+ try:
+ os.setns(u2_ufd, int(CloneFlag.NEWUSER))
+ os.unshare(CloneFlag.NEWNS)
+ Sys.set_mount_propagation(
+ "/tmp", MountFlag.REC | MountFlag.SLAVE
+ )
+ with (
+ self.closing_fd(
+ self.make_plain_mount("tmpfs")
+ ) as m_top,
+ self.closing_fd(
+ self.make_plain_mount("tmpfs")
+ ) as m_inner,
+ ):
+ os.mkdir("inner", 0o755, dir_fd=m_top)
+ Sys.move_mount(
+ m_inner,
+ "",
+ m_top,
+ "inner",
+ MoveMountFlag.F_EMPTY_PATH,
+ )
+ socket.send_fds(s_c, [b"M"], [m_top])
+ if s_go.read_bytes() != b"g":
+ os._exit(1)
+ s_go.close_read()
+ if not os.path.ismount("/tmp/sub/inner"):
+ os._exit(2)
+ try:
+ Sys.umount2(
+ "/tmp/sub/inner", UmountFlag.DETACH
+ )
+ os._exit(3)
+ except OSError as exc:
+ if exc.errno != errno.EINVAL:
+ os._exit(4)
+ Sys.umount2("/tmp/sub", UmountFlag.DETACH)
+ os._exit(0)
+ finally:
+ s_c.close()
+ s_c.close()
+ s_go.close_read()
+ try:
+ _, m_fds, _, _ = socket.recv_fds(s_p, 1, 1)
+ finally:
+ s_p.close()
+ if not m_fds:
+ s_go.close_write()
+ self.assertEqual(self.reap_exit_code(spid), 0)
+ self.fail("did not receive mount fd")
+ with self.closing_fd(m_fds[0]) as m_top:
+ Sys.move_mount(
+ m_top,
+ "",
+ u1_mfd,
+ "tmp/sub",
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+ s_go.write_bytes(b"g")
+ s_go.close_write()
+ self.assertEqual(self.reap_exit_code(spid), 0)
+ Sys.umount2("/tmp/sub", UmountFlag.DETACH)
+
+ self.run_forked(check_child_src_slave_locking)
+
+ with (
+ Userland() 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_USERLAND, 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)
+
+ rns.map_self_ugid()
+ with self.closing_fd(Sys.fsopen("proc")) as bad_proc:
+
+ def check_nonancestor_proc() -> None:
+ self.enter_foreign_pidns(rns)
+
+ def check_inner() -> None:
+ with self.assertRaises(OSError) as cm_set:
+ Sys.fsconfig(
+ bad_proc, FsconfigCmd.SET_USERLAND, 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 (
+ Userland() 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:
+ os.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)
+
+ def check_clone_mntns_loop() -> None:
+ with (
+ Userland() as host_v,
+ SyncPipe.create() as ready,
+ SyncPipe.create() as hold,
+ ):
+ host_v.map_self_ugid()
+ with self.closing_fd(
+ host_v.get_nsfd(CloneFlag.NEWUSER)
+ ) as ufd:
+ os.setns(ufd, int(CloneFlag.NEWUSER))
+ os.unshare(CloneFlag.NEWNS)
+ Sys.prctl(PrctlOp.SET_DUMPABLE, 1)
+ with self.closing_fd(
+ self.make_plain_mount("tmpfs")
+ ) as tfd:
+ for fname in ("src_m1", "src_m2", "loop_ns", "ok_ns"):
+ os.close(
+ os.open(
+ fname,
+ os.O_CREAT | os.O_WRONLY | os.O_CLOEXEC,
+ 0o600,
+ dir_fd=tfd,
+ )
+ )
+ Sys.move_mount(
+ tfd,
+ "",
+ Sys.AT_FDCWD,
+ "/tmp",
+ MoveMountFlag.F_EMPTY_PATH,
+ )
+ cpid = os.fork()
+ if cpid == 0:
+ ready.close_read()
+ hold.close_write()
+ os.unshare(CloneFlag.NEWNS)
+ ready.write_bytes(b"1")
+ ready.close_write()
+ hold.read_bytes()
+ hold.close_read()
+ os._exit(0)
+ ready.close_write()
+ hold.close_read()
+ self.assertEqual(ready.read_bytes(), b"1")
+ try:
+ with (
+ Userland() as v2,
+ self.closing_fd(
+ os.open(
+ f"/proc/{cpid}/ns/mnt",
+ os.O_RDONLY | os.O_CLOEXEC,
+ )
+ ) as m1_fd,
+ self.closing_fd(
+ v2.get_nsfd(CloneFlag.NEWNS)
+ ) as m2_fd,
+ ):
+ ot_flags = OpenTreeFlag(
+ int(OpenTreeFlag.CLONE)
+ | int(OpenTreeFlag.CLOEXEC)
+ | int(AtFlag.EMPTY_PATH)
+ )
+ with self.closing_fd(
+ Sys.open_tree(m1_fd, "", ot_flags)
+ ) as c1:
+ Sys.move_mount(
+ c1,
+ "",
+ Sys.AT_FDCWD,
+ "/tmp/src_m1",
+ MoveMountFlag.F_EMPTY_PATH,
+ )
+ with self.closing_fd(
+ Sys.open_tree(m2_fd, "", ot_flags)
+ ) as c2:
+ Sys.move_mount(
+ c2,
+ "",
+ Sys.AT_FDCWD,
+ "/tmp/src_m2",
+ MoveMountFlag.F_EMPTY_PATH,
+ )
+ with self.assertRaises(OSError) as cm_loop:
+ Sys.move_mount(
+ Sys.AT_FDCWD,
+ "/tmp/src_m1",
+ m1_fd,
+ "tmp/loop_ns",
+ MoveMountFlag.T_MNTNS
+ | MoveMountFlag.CLONE,
+ )
+ self.assertEqual(
+ cm_loop.exception.errno, errno.EINVAL
+ )
+ Sys.move_mount(
+ Sys.AT_FDCWD,
+ "/tmp/src_m2",
+ m1_fd,
+ "tmp/ok_ns",
+ MoveMountFlag.T_MNTNS | MoveMountFlag.CLONE,
+ )
+ finally:
+ hold.close_write()
+ self.assertEqual(self.reap_exit_code(cpid), 0)
+
+ self.run_forked(check_clone_mntns_loop)
+
+ if os.geteuid() == 0:
+ u_rns = self.create_userland_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_USERLAND,
+ 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 Userland() 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_USERLAND),
+ exit_signal=int(signal.SIGCHLD),
+ userland=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:
+ self.enter_foreign_pidns(cell2.rns)
+
+ 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 check_dead_ancestor_pidns() -> None:
+ self.enter_userns_if_unpriv()
+ s_p, s_c = socket.socketpair(
+ socket.AF_UNIX, socket.SOCK_SEQPACKET
+ )
+ p1 = os.fork()
+ if p1 == 0:
+ s_p.close()
+ try:
+ os.unshare(CloneFlag.NEWPID)
+ p2 = os.fork()
+ if p2 == 0:
+ with Userland() as nested_u:
+ socket.send_fds(s_c, [b"U"], [nested_u.fd])
+ os._exit(0)
+ os._exit(self.reap_exit_code(p2))
+ finally:
+ s_c.close()
+ s_c.close()
+ try:
+ _, recv_u, _, _ = socket.recv_fds(s_p, 1, 1)
+ finally:
+ s_p.close()
+ self.assertEqual(self.reap_exit_code(p1), 0)
+ self.assertEqual(len(recv_u), 1)
+ with Userland.from_fd(recv_u[0]) as dead_u:
+ with (
+ self.closing_fd(dead_u.get_nsfd(CloneFlag.NEWNS)) as mfd,
+ self.closing_fd(dead_u.make_mount("tmpfs")) as rfd,
+ ):
+ Sys.move_mount(
+ rfd,
+ "",
+ mfd,
+ "/",
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+ with self.assertRaises(OSError) as cm_dead:
+ dead_u.clone_into()
+ self.assertEqual(cm_dead.exception.errno, errno.ESRCH)
+
+ self.run_forked(check_dead_ancestor_pidns)
+
+ 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)
+
+ def check_standalone_mntns() -> None:
+ self.enter_userns_if_unpriv()
+ 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:
+ os.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)
+
+ self.run_forked(check_standalone_mntns)
+
+ def test_userns_set_idmap(self) -> None:
+ self._require_cell()
+ with (
+ Userland() 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, size=0, flags=0)
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ with self.assertRaises(OSError) as cm:
+ Sys.userns_set_idmap_raw(
+ userns_fd, 0, size=UsernsIdmap.SIZE_VER0, flags=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)
+
+ big_buf = ctypes.create_string_buffer(65536)
+ with self.assertRaises(OSError) as cm:
+ Sys.userns_set_idmap_raw(
+ userns_fd, ctypes.addressof(big_buf), size=65536
+ )
+ self.assertEqual(cm.exception.errno, errno.E2BIG)
+
+ with self.assertRaises(OSError) as cm:
+ Sys.set_userns_idmap(
+ userns_fd,
+ uid_extents=((0, os.geteuid(), 1),),
+ flags=(~int(UsernsFlag.SETGROUPS_ALLOWED)) & 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(), 1),),
+ flags=UsernsFlag.SETGROUPS_ALLOWED,
+ )
+ 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),),
+ reserved=1,
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ bad_req = UsernsIdmap(nr_uid_extents=1, uid_extents=0)
+ with self.assertRaises(OSError) as cm:
+ Sys.userns_set_idmap_raw(
+ userns_fd, ctypes.addressof(bad_req)
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ bad_req2 = UsernsIdmap(nr_uid_extents=0, uid_extents=1)
+ with self.assertRaises(OSError) as cm:
+ Sys.userns_set_idmap_raw(
+ userns_fd, ctypes.addressof(bad_req2)
+ )
+ 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),),
+ )
+ 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),),
+ )
+ 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,
+ uid_extents=((0, os.geteuid(), 0),),
+ )
+ self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+ can_allow_setgroups = (
+ os.geteuid() == 0
+ and Path("/proc/self/setgroups").read_bytes() == b"allow\n"
+ )
+ if can_allow_setgroups:
+ with (
+ Userland() as rns_sg,
+ self.closing_fd(
+ rns_sg.get_nsfd(CloneFlag.NEWNS)
+ ) as sg_mntns,
+ ):
+ rns_sg.set_idmap(
+ uid_extents=((0, 0, 1),),
+ gid_extents=((0, 0, 1),),
+ flags=UsernsFlag.SETGROUPS_ALLOWED,
+ )
+ with self.closing_fd(rns_sg.make_mount("tmpfs")) as sgr:
+ os.mkdir("proc", 0o755, dir_fd=sgr)
+ Sys.move_mount(
+ sgr,
+ "",
+ sg_mntns,
+ "/",
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+ with self.closing_fd(rns_sg.make_mount("proc")) as sgp:
+ Sys.move_mount(
+ sgp,
+ "",
+ sg_mntns,
+ "proc",
+ MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS,
+ )
+
+ def verify_allow() -> int:
+ with open("/proc/self/setgroups", "rb") as f:
+ return 0 if f.read() == b"allow\n" else 1
+
+ sg_pid = rns_sg.run(verify_allow)
+ self.assertEqual(rns_sg.wait().exit_code, 0)
+ self.assertEqual(self.reap_exit_code(sg_pid), 0)
+ else:
+ with self.assertRaises(OSError) as cm:
+ Sys.set_userns_idmap(
+ userns_fd,
+ gid_extents=((0, os.getegid(), 1),),
+ flags=UsernsFlag.SETGROUPS_ALLOWED,
+ )
+ self.assertEqual(cm.exception.errno, errno.EPERM)
+
+ rns.map_self_ugid()
+ if Path("/proc/self/projid_map").read_bytes():
+ rns.set_idmap(projid_extents=((0, 0, 1),))
+ with self.assertRaises(OSError) as cm:
+ rns.set_idmap(projid_extents=((0, 0, 1),))
+ self.assertEqual(cm.exception.errno, errno.EPERM)
+ else:
+ with self.assertRaises(OSError) as cm:
+ rns.set_idmap(projid_extents=((0, 0, 1),))
+ self.assertEqual(cm.exception.errno, errno.EPERM)
+ 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_userland_as_uid(1000)
+ rns2 = self.create_userland_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 userland creation unavailable")
+
+ with rns1, rns2:
+ s_main, s_alice = socket.socketpair(
+ socket.AF_UNIX, socket.SOCK_SEQPACKET
+ )
+ 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()
+ try:
+ _, alice_fds, _, _ = socket.recv_fds(s_main, 1, 1)
+ finally:
+ s_main.close()
+ self.assertEqual(self.reap_exit_code(alice_pid), 0)
+ self.assertEqual(len(alice_fds), 1)
+
+ 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_SEQPACKET
+ )
+ mal_pid = os.fork()
+ if mal_pid == 0:
+ s_m1.close()
+ try:
+ self.drop_to_uid(2000)
+ try:
+ Sys.set_userns_idmap(
+ alice_ufd, projid_extents=((0, 2000, 1),)
+ )
+ os._exit(2)
+ except OSError as exc:
+ if exc.errno != errno.EPERM:
+ os._exit(3)
+ with self.closing_fd(
+ Sys.ioctl(uts2_fd, Ioctl.NS_GET_USERNS)
+ ) as bad_ufd:
+ try:
+ Sys.set_userns_idmap(
+ bad_ufd, projid_extents=((0, 2000, 1),)
+ )
+ os._exit(4)
+ except OSError as exc:
+ if exc.errno != errno.EPERM:
+ os._exit(5)
+ socket.send_fds(s_m2, [b"M"], [bad_ufd])
+ os._exit(0)
+ except BaseException:
+ os._exit(1)
+ finally:
+ s_m2.close()
+ s_m2.close()
+ try:
+ _, mal_fds, _, _ = socket.recv_fds(s_m1, 1, 1)
+ finally:
+ s_m1.close()
+ self.assertEqual(self.reap_exit_code(mal_pid), 0)
+ self.assertEqual(len(mal_fds), 1)
+
+ 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),),
+ )
+ 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),),
+ )
+ self.assertEqual(cm_root.exception.errno, errno.EPERM)
+
+ with self.assertRaises(OSError) as cm_mal_p:
+ Sys.set_userns_idmap(
+ mallory_ufd, projid_extents=((0, 1000, 1),)
+ )
+ self.assertEqual(cm_mal_p.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)),
+ projid_extents=((0, 1000, 1),),
+ flags=UsernsFlag.SETGROUPS_ALLOWED,
+ )
+
+ 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:
+ Sys.setgroups_empty()
+ 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
+
+ with self.assertRaises(OSError) as cm_sys:
+ Sys.fsopen("sysfs")
+ self.assertEqual(cm_sys.exception.errno, errno.EPERM)
+
+ 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=UserlandFlag.DEFAULT)
+ except OSError as exc:
+ if exc.errno in SKIP_ERRNOS:
+ self.skipTest("unprivileged userland unavailable")
+ raise
+
+ with (
+ tempfile.TemporaryDirectory(prefix="userland-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()
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread* Re: [RFC PATCH v7 25/26] selftests/userland: Add userland test suite
2026-11-22 19:35 ` [RFC PATCH v7 25/26] selftests/userland: Add userland test suite Jarkko Sakkinen
@ 2026-11-22 19:52 ` sashiko-bot
0 siblings, 0 replies; 30+ messages in thread
From: sashiko-bot @ 2026-11-22 19:52 UTC (permalink / raw)
To: Jarkko Sakkinen
Cc: bpf, linux-mm, linux-security-module, Aleksa Sarai,
Alexander Mikhalitsyn, Alexander Viro, Andy Lutomirski,
Arnd Bergmann, Christian Brauner, David Howells, Eric Biggers,
Giuseppe Scrivano, Hugh Dickins, Jan Kara, Jeff Layton,
Jonathan Corbet, Josef Bacik, Kees Cook, KP Singh,
Lennart Poettering, Neal Gompa, Oleg Nesterov, Paul Moore,
Pavel Tikhomirov, Serge Hallyn, Shuah Khan, Zygmunt Krynicki
Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [Medium] selftests/userland: host /tmp mount leak in
check_child_src_slave_locking()
- [Medium] selftests/userland: 64K-page E2BIG failure in
test_userns_set_idmap()
- [Low] selftests/userland: Python 3.10+ parenthesized with-statements
in test
--
commit cd1410a72fb4e8338db290b21743ad1e3c5bf460
Author: Jarkko Sakkinen <jarkko@kernel.org>
selftests/userland: Add userland test suite
This commit adds a kselftest suite for the userland control object,
namespace sharing, mount-namespace configuration, waitid(P_USERLAND),
pidfd_send_signal(), and userns_set_idmap().
> diff --git a/tools/testing/selftests/userland/userland_test.py b/tools/testing/selftests/userland/userland_test.py
> new file mode 100755
> index 0000000000000..2b43adbbb4291
> --- /dev/null
> +++ b/tools/testing/selftests/userland/userland_test.py
[ ... ]
> + with (
> + self.closing_fd(rns.get_nsfd(CloneFlag.NEWNS)) as mntns_fd,
> + self.closing_fd(rns.make_mount("tmpfs")) as rootfd,
> + ):
[Severity: Low]
Will these parenthesized multi-item with-statements fail with a SyntaxError
on Python 3.9? Parenthesized context managers across multiple clauses
require Python 3.10+, whereas Documentation/process/changes.rst specifies
Python 3.9.x as the minimum supported version.
[ ... ]
> + def check_child_src_slave_locking() -> None:
> + self.enter_userns_if_unpriv()
> + os.unshare(CloneFlag.NEWNS)
> + with self.closing_fd(self.make_plain_mount("tmpfs")) as tfd:
> + os.mkdir("sub", 0o755, dir_fd=tfd)
> + Sys.move_mount(
> + tfd,
> + "",
> + Sys.AT_FDCWD,
> + "/tmp",
> + MoveMountFlag.F_EMPTY_PATH,
> + )
[Severity: Medium]
Does check_child_src_slave_locking() leak a tmpfs mount over the host /tmp
when the test runs as root?
When os.geteuid() == 0, enter_userns_if_unpriv() returns without unsharing
CLONE_NEWUSER, so os.unshare(CloneFlag.NEWNS) keeps shared mount peer
groups with the host mount namespace. Mounting tfd onto /tmp before
making mount propagation private propagates the tmpfs mount into the host
mount namespace, and cleanup only detaches /tmp/sub, leaving the host /tmp
masked after the test exits. Calling Sys.set_mount_propagation("/") right
after os.unshare(CloneFlag.NEWNS), as check_standalone_mntns() does, would
prevent the mount from propagating to the host.
[ ... ]
> + big_buf = ctypes.create_string_buffer(65536)
> + with self.assertRaises(OSError) as cm:
> + Sys.userns_set_idmap_raw(
> + userns_fd, ctypes.addressof(big_buf), size=65536
> + )
> + self.assertEqual(cm.exception.errno, errno.E2BIG)
[Severity: Medium]
Does this E2BIG check fail on kernels configured with 64 KiB (or 256 KiB)
base pages?
userns_set_idmap() returns -E2BIG only when size > PAGE_SIZE. When
PAGE_SIZE >= 65536, size=65536 passes the PAGE_SIZE check and fails later
with EINVAL because the zeroed buffer has no extents. Sizing the buffer
with os.sysconf("SC_PAGE_SIZE") + 1 would exceed PAGE_SIZE on all page
sizes.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261122193539.3334213-1-jarkko@kernel.org?part=25
^ permalink raw reply [flat|nested] 30+ messages in thread
* [RFC PATCH v7 26/26] MAINTAINERS: Add entry for USERLAND
2026-11-22 19:35 [RFC PATCH v7 00/26] userland: Userland containers Jarkko Sakkinen
` (24 preceding siblings ...)
2026-11-22 19:35 ` [RFC PATCH v7 25/26] selftests/userland: Add userland test suite Jarkko Sakkinen
@ 2026-11-22 19:35 ` Jarkko Sakkinen
25 siblings, 0 replies; 30+ messages in thread
From: Jarkko Sakkinen @ 2026-11-22 19:35 UTC (permalink / raw)
To: linux-fsdevel
Cc: Jarkko Sakkinen, bpf, containers, linux-api, linux-arch,
linux-doc, linux-kernel, linux-kselftest, linux-mm,
linux-security-module, Aleksa Sarai, Alexander Mikhalitsyn,
Alexander Viro, Andy Lutomirski, Arnd Bergmann, Christian Brauner,
David Howells, Eric Biggers, Giuseppe Scrivano, Hugh Dickins,
Jan Kara, Jeff Layton, Jonathan Corbet, Josef Bacik, Kees Cook,
KP Singh, Lennart Poettering, Neal Gompa, Oleg Nesterov,
Paul Moore, Pavel Tikhomirov, Serge Hallyn, Shuah Khan,
Zygmunt Krynicki
Record maintainership and mailing list routing for userlands across
their uAPI headers, core implementation, documentation, and selftests.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
MAINTAINERS | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/MAINTAINERS b/MAINTAINERS
index 7cbce21ba45a..54d8f628cb87 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -29285,6 +29285,17 @@ F: arch/um/
F: arch/x86/um/
F: fs/hostfs/
+USERLAND
+M: David Howells <dhowells@redhat.com>
+M: Jarkko Sakkinen <jarkko@kernel.org>
+L: linux-fsdevel@vger.kernel.org
+S: Maintained
+F: Documentation/userspace-api/userland.rst
+F: include/linux/userland.h
+F: include/uapi/linux/userland.h
+F: kernel/userland.c
+F: tools/testing/selftests/userland/
+
USERSPACE COPYIN/COPYOUT (UIOVEC)
M: Alexander Viro <viro@zeniv.linux.org.uk>
L: linux-block@vger.kernel.org
--
2.47.3
^ permalink raw reply related [flat|nested] 30+ messages in thread