From nobody Tue Nov 24 14:20:09 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376161; b=I/m/WknjkepquTHZzeigYfg3TxX3yHJGFeZfWf1fPwQLWNhCKsKr+E32Oo7UGqq4QW/T a1F8fBZzwQnt/2Dfk+1mqjZXN8xadmAlIkhqLicWOm4/pNTAnXDwNoOFuHewaGTVYgWjR tEMhkALAOzYh+RqGu9qR1msJyyoubRXP8sVr7CuKPPuNslN08qayV1z5BTRlUn/OOuMVh Ipbx9lxEDBPF+0NOzjRv+dalwwHXdka3MBi2r+tC9cm35y3J/R0rajarHqWtGhpHscULz x3yPOzXECz779wsn+Shs5CWicnWaDfcWHKGEjBU46yN/UwpiVrCgN5kKs4qfprSoAng== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376161; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=PxWsspzEioIIwUqnuiIeYKp1fTe5D8PzGx83Wd5XdHY=; b=uN4bDiJt4K/gBOp0Yn3/NndacLmnAE+IyoCelvck80qqMIZGAvvmyjvI8X88GN6rcruG GRu2l5J0+29shwyprW+y2jRfMq83R80fA1GAQABpqRyC5EYBSCKenzGNOM8E+1MjsgALo mdgmnk49UzvCAGa3JtAzCqzPkxOkuhReDQEpjgjiqfVddGOtZ82osQX3kVEVk1ylsz19M MSkv/FXYiN30KJsLXbOfQaAqTu2EtgFnCPDWgUBHAe5Gnd2q8ImBS3zCjHQF3Hjto00dm buovwfa83f7qkSZAhsBlb1ouPDfeGEAj/kkPU7Ia8zgByPmobEcXMcYcclxgmj3CcMA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=DFiqTxJB; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id 46200606A32C; Sun, 22 Nov 2026 19:36:01 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=DFiqTxJB Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id C697E1F000C0; Sun, 22 Nov 2026 19:35:59 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376160; bh=PxWsspzEioIIwUqnuiIeYKp1fTe5D8PzGx83Wd5XdHY=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=DFiqTxJBeq3OOH2VDJJY2sRb16klNa8m8RHt5Abh/YsPImOZ5nu0uM/UuMH+1ycLe S+SXiQ9ZdkEJGKkPN8frshQVWuicTWsoG5qYiFtE16U0SbJ6N0d/pprgRSmcbMWB0L 0fc+vdB1MX5xOtwmvvCKQVbCxtNDWEr972W+bhnrLZB08bFuYj96P+xs8sX24UVzV5 vR6e0SgrDbPp5c3KER4nWHsM3H80dhGu3haKOn8CZtqET9eS+adDfRk0TJeYI2DcSh DNDD/KxSNtFTnTtbxIpVpUpwPU2Jqbe3L0B6Jmlu7Ie34V9iCvX0vbkLcG4h/jk/TN FUckdOsdfl/JQ== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 01/26] userns: Factor out idmap validation and commit helpers Date: Sun, 22 Nov 2026 21:35:14 +0200 Message-ID: <20261122193539.3334213-2-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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_m= ap *map) } EXPORT_SYMBOL_IF_KUNIT(uid_gid_map_sort); =20 +static bool idmap_maps_root(const struct uid_gid_map *new_map) +{ + unsigned int idx; + + for (idx =3D 0; idx < new_map->nr_extents; idx++) { + const struct uid_gid_extent *e; + + if (new_map->nr_extents <=3D UID_GID_MAP_MAX_BASE_EXTENTS) + e =3D &new_map->extent[idx]; + else + e =3D &new_map->forward[idx]; + if (e->lower_first =3D=3D 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 =3D file->f_cred->user_ns; - struct uid_gid_extent *extent0 =3D NULL; - - for (idx =3D 0; idx < new_map->nr_extents; idx++) { - if (new_map->nr_extents <=3D UID_GID_MAP_MAX_BASE_EXTENTS) - extent0 =3D &new_map->extent[idx]; - else - extent0 =3D &new_map->forward[idx]; - if (extent0->lower_first =3D=3D 0) - break; - - extent0 =3D NULL; - } =20 - if (!extent0) + if (!idmap_maps_root(new_map)) return true; =20 if (map_ns =3D=3D file_ns) { @@ -938,6 +941,103 @@ static bool verify_root_map(const struct file *file, return true; } =20 +static int validate_and_insert_extent(struct uid_gid_map *new_map, + struct uid_gid_extent *extent) +{ + if ((extent->first =3D=3D (u32)-1) || (extent->lower_first =3D=3D (u32)-1= )) + return -EINVAL; + + if ((extent->first + extent->count) <=3D extent->first) + return -EINVAL; + if ((extent->lower_first + extent->count) <=3D extent->lower_first) + return -EINVAL; + + if (mappings_overlap(new_map, extent)) + return -EINVAL; + + if (new_map->nr_extents >=3D 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 =3D=3D 0) + return -EINVAL; + + for (idx =3D 0; idx < new_map->nr_extents; idx++) { + struct uid_gid_extent *e; + u32 lower_first; + + if (new_map->nr_extents <=3D UID_GID_MAP_MAX_BASE_EXTENTS) + e =3D &new_map->extent[idx]; + else + e =3D &new_map->forward[idx]; + + lower_first =3D map_id_range_down(parent_map, + e->lower_first, + e->count); + if (lower_first =3D=3D (u32)-1) + return -EPERM; + + e->lower_first =3D 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 <=3D UID_GID_MAP_MAX_BASE_EXTENTS) { + memcpy(map->extent, new_map->extent, + new_map->nr_extents * sizeof(new_map->extent[0])); + } else { + map->forward =3D new_map->forward; + map->reverse =3D new_map->reverse; + } + /* + * Pairs with smp_rmb() in map_id_range_down(), map_id_range_up(), + * and m_start(). + */ + smp_wmb(); + map->nr_extents =3D 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 !=3D 1 || new_map->extent[0].count !=3D 1 || + !uid_eq(ns->owner, cred->euid)) + return false; + + id =3D new_map->extent[0].lower_first; + if (cap_setid =3D=3D CAP_SETUID) + return uid_eq(make_kuid(ns->parent, id), cred->euid); + if (cap_setid =3D=3D 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 =3D file->private_data; struct user_namespace *map_ns =3D seq->private; - struct uid_gid_map new_map; - unsigned idx; + struct uid_gid_map new_map =3D {}; 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 cha= r __user *buf, */ mutex_lock(&userns_state_mutex); =20 - memset(&new_map, 0, sizeof(struct uid_gid_map)); - ret =3D -EPERM; /* Only allow one successful write to the map */ if (map->nr_extents !=3D 0) @@ -1052,98 +1149,28 @@ static ssize_t map_write(struct file *file, const c= har __user *buf, if (*pos !=3D '\0') goto out; =20 - /* Verify we have been given valid starting values */ - if ((extent.first =3D=3D (u32) -1) || - (extent.lower_first =3D=3D (u32) -1)) - goto out; - - /* Verify count is not zero and does not cause the - * extent to wrap - */ - if ((extent.first + extent.count) <=3D extent.first) - goto out; - if ((extent.lower_first + extent.count) <=3D - 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) =3D=3D UID_GID_MAP_MAX_EXTENTS && - (next_line !=3D NULL)) - goto out; - - ret =3D uid_gid_map_insert_extent(&new_map, &extent); + ret =3D validate_and_insert_extent(&new_map, &extent); if (ret < 0) goto out; ret =3D -EINVAL; } - /* Be very certain the new map actually exists */ + if (new_map.nr_extents =3D=3D 0) goto out; =20 ret =3D -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; =20 - ret =3D -EPERM; - /* Map the lower ids from the parent user namespace to the - * kernel global id space. - */ - for (idx =3D 0; idx < new_map.nr_extents; idx++) { - struct uid_gid_extent *e; - u32 lower_first; - - if (new_map.nr_extents <=3D UID_GID_MAP_MAX_BASE_EXTENTS) - e =3D &new_map.extent[idx]; - else - e =3D &new_map.forward[idx]; - - lower_first =3D 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 =3D=3D (u32) -1) - goto out; - - e->lower_first =3D lower_first; - } - - /* - * If we want to use binary search for lookup, this clones the extent - * array and sorts both copies. - */ - ret =3D uid_gid_map_sort(&new_map); + ret =3D resolve_new_idmap(&new_map, parent_map); if (ret < 0) goto out; =20 - /* Install the map */ - if (new_map.nr_extents <=3D UID_GID_MAP_MAX_BASE_EXTENTS) { - memcpy(map->extent, new_map.extent, - new_map.nr_extents * sizeof(new_map.extent[0])); - } else { - map->forward =3D new_map.forward; - map->reverse =3D new_map.reverse; - } - smp_wmb(); - map->nr_extents =3D new_map.nr_extents; - + commit_new_idmap(map, &new_map); *ppos =3D count; ret =3D 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 =3D NULL; - map->reverse =3D NULL; - map->nr_extents =3D 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 *f= ile, /* Don't allow mappings that would allow anything that wouldn't * be allowed without the establishment of unprivileged mappings. */ - if ((new_map->nr_extents =3D=3D 1) && (new_map->extent[0].count =3D=3D 1)= && - uid_eq(ns->owner, cred->euid)) { - u32 id =3D new_map->extent[0].lower_first; - if (cap_setid =3D=3D CAP_SETUID) { - kuid_t uid =3D make_kuid(ns->parent, id); - if (uid_eq(uid, cred->euid)) - return true; - } else if (cap_setid =3D=3D CAP_SETGID) { - kgid_t gid =3D 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; =20 /* Allow anyone to set a mapping that doesn't require privilege */ if (!cap_valid(cap_setid)) --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376165; b=pEJ/EpFl10PBPOv/NiXZLQKKXZkEKRADy32M2MdvbRvBLmDelAFXmThWtZ4qN0y+ZllY LwoG45QHbn3t8njCnAlQYlvYyo/TqI5M0dQuuGKv87DEaK637O0/2eopa8ZMYQkKCwvuy Yqn8pJJSLJotSy5U5BmLE6Cq3+7vBeDW0T4X4cZX5c6iGBh8VNjjTG9u7zmWQ+osJ704o yufs3WhSRnfO2zjJNuWDhpRY+IVJgajggreNdEqyiU89/s1+Ge+YmT4z8X8G81yv48dKG 3rnGZG3EeZG/jhJTBUIUdI6Y8pOlctpyRBqhw1Xo0x0xtpnWuKWSyaZSFBWAp0YFaGA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376165; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=bwYR0fybAzWaJ/ixuaYty0PvLt1G3qb2IvCSTFt/BhY=; b=pzV+QMXCw6p1EggrjTldVpTFXB41Wuyuzmg9xNWdad6ZU/Tp3U+WKXx6+ejw0l2fZ8I4 DTAZPxYWxYkvJnYeX0Pj+oYEowHS3Yk9FTT06lem09kBEbRAAtiMMBQiYTBXGiOVMkFsZ hgRsaVcF+LVDkZiBAYEQg7bbz4BhzltF9v822ag8VecVocl+pZon6kuCq+1cTYzkm81/L hfIrldD5olq8pSwqkULS20dRM74g8TefMm7tMLk0TarvYWNlVYShuD2pZp3VpKAfA9y4U Pzifx0hR+tJTDosjFbhKQP2Jw89KdaCJg72AKoS9L5PR2RBT1a8maTt2W3f0wi/fxZQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=FEw+TPoF; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id 5BED5606A31D; Sun, 22 Nov 2026 19:36:05 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=FEw+TPoF Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 1032F1F00A3D; Sun, 22 Nov 2026 19:36:04 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376164; bh=bwYR0fybAzWaJ/ixuaYty0PvLt1G3qb2IvCSTFt/BhY=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=FEw+TPoFZg72kU6HD8uTdPZhlBZWrNQof5Vz2hIUIyspTmWwA4eckU6xoFQQkUkz5 j5k/lqIBBdLDHpZLHsJOSjlIIQlj+ra1Q8Gq5MsYctOMl56038vXeYIg8ZUyv9Ktn6 LmM2fGeUPpuIzzuEdmeSVkPgk9c3oJCSD9YgAm2FRfxb93c1MzvVvI1Xj9v9FilaXq saCFvGkwscsH4vLizA+s3i+flOB2Y6YMkuzGjXaxc6EFU4HiKfrk3xluz0dG0F2oLE J71t5FQ5AWPRB61vS52N2QsruIRPKzgNN+ygiMNGCO0tblD9iA+veXmPtGLY3zZQEc ggs6eGH4uYShA== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 02/26] userns: Add userns_set_idmap() system call Date: Sun, 22 Nov 2026 21:35:15 +0200 Message-ID: <20261122193539.3334213-3-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Configuring UID, GID, and project ID mappings currently requires writing formatted text to /proc//{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 --- 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; =20 @@ -909,6 +910,9 @@ asmlinkage long sys_clock_adjtime32(clockid_t which_clo= ck, 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 */ }; }; =20 -#define USERNS_SETGROUPS_ALLOWED 1UL - #define USERNS_INIT_FLAGS USERNS_SETGROUPS_ALLOWED =20 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) =20 +/** + * struct userns_idmap_extent - Single ID mapping range for userns_set_idm= ap() + * @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 =3D (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 f= or + * 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 =3D 0xEFFFFFFFU, UTS_NS_INIT_INO =3D 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); =20 /* 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 #include #include +#include #include +#include +#include +#include =20 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 c= har __user *buf, return ret; } =20 +static bool caller_idmap_permitted(struct user_namespace *ns, int cap_seti= d, + unsigned long ns_flags, + const struct uid_gid_map *new_map) +{ + const struct cred *cred =3D current_cred(); + + if (cap_setid =3D=3D CAP_SETUID && idmap_maps_root(new_map)) { + if (cred->user_ns =3D=3D 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 =3D 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 =3D 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 =3D kext.first; + extent.lower_first =3D kext.lower_first; + extent.count =3D kext.count; + + ret =3D 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 =3D {}, new_gid =3D {}, new_projid =3D {}; + struct userns_idmap req =3D {}; + 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) !=3D USERNS_IDMAP_SIZE_VER0); + + if (flags & ~USERNS_SETGROUPS_ALLOWED) + return -EINVAL; + + CLASS(fd, f)(fd); + if (fd_empty(f)) + return -EBADF; + + filp =3D fd_file(f); + if (!proc_ns_file(filp)) + return -EINVAL; + + ns_common =3D get_proc_ns(file_inode(filp)); + if (ns_common->ns_type !=3D CLONE_NEWUSER) + return -EINVAL; + ns =3D to_user_ns(ns_common); + + if (!map || size < USERNS_IDMAP_SIZE_VER0) + return -EINVAL; + if (unlikely(size > PAGE_SIZE)) + return -E2BIG; + ret =3D copy_struct_from_user(&req, sizeof(req), map, size); + if (ret) + return ret; + if (req.reserved) + return -EINVAL; + if (!req.nr_uid_extents !=3D !req.uid_extents || + !req.nr_gid_extents !=3D !req.gid_extents || + !req.nr_projid_extents !=3D !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() !=3D ns && current_user_ns() !=3D ns->parent) + return -EPERM; + + file_ok =3D (filp->f_cred->user_ns =3D=3D ns || + filp->f_cred->user_ns =3D=3D 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 =3D 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 =3D 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 =3D 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 =3D ns->flags; + ret =3D -EPERM; + + if (req.nr_uid_extents && ns->uid_map.nr_extents !=3D 0) + goto out_unlock; + if (req.nr_gid_extents && ns->gid_map.nr_extents !=3D 0) + goto out_unlock; + if (req.nr_projid_extents && ns->projid_map.nr_extents !=3D 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 &=3D ~USERNS_SETGROUPS_ALLOWED; + } + + if (req.nr_uid_extents) { + ret =3D 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 =3D 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 =3D prepare_caller_idmap(ns, -1, new_flags, &new_projid, + &ns->parent->projid_map); + if (ret < 0) + goto out_unlock; + } + + if (new_flags !=3D 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) { --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376169; b=KBc4d0WKaiojPjH3+HtJqLYHKeJRRVFJUv9i52PRFywaZZ/xCYz188IEZsVbqX6oRNnP kcFwIbw5qrmqkCB2oG1DCApHwCUnA8H3rF/M3gSBoEtvqv7oqAm0Za/vfTPbpZIXyxs1L r/7QB8J+oi6jraLYCBGWCxATMI3Pi8jrVCf2lzHbjmALah/ljFKi8ixKdfMXwoxsxo0WM Ml5vjzYMOa/0QyoyE3gqCrsTDdDUWdW20QJxywAaeC3W6/UuK3A6Ju7gTHZWdjtkRLZTg utobAAh30Nbw1LW0UJ5vwpMOuSyAW0qQvX14SEsDru4Ng27/+P7VYkN3IWngDis9/Zg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376169; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=M0Jcf1onBvCVtufFcrdOL5QCVPkyz3xxS4zQsg/IEp0=; b=AMv99aiDJKtzxjfMqvKSoqpCbvKV15CMKrC3RZagqFEk9tVm8g6PnwKbEjgZV+MUcl+5 SA7JbAeA2X1no8N6URpcBnDZLJZQAe3w7ZfdKqtp/UehQhsavW/nKDSLz8jM0oQEPcQyv snFSb8QrEJboeePJkkhCiJ/iAN6jgzn7QTi05pfy1/4hAsKVXZmRnEtK4PUl+nFuPuXQL gYhNwrRPDxZjRLf8SDR1l6XtUNFcXArf8qbfc+2wepbBXsLUwq6CbpIvtNNFUvaxonNIk w2j9VnCwdixW0fP1vJifvAJbrmBl0PbTRfg4i7hDeBXd77nZFXMcO+Uh4qwKpLzw40w== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=h7ZUfA60; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id AB002606A32C; Sun, 22 Nov 2026 19:36:09 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=h7ZUfA60 Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 6FAB41F000CF; Sun, 22 Nov 2026 19:36:08 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376169; bh=M0Jcf1onBvCVtufFcrdOL5QCVPkyz3xxS4zQsg/IEp0=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=h7ZUfA60FNui4/mwZs0pyabViCDUQIR+fYWNycoi6GbJsfLe2FuTN4GllES9A0mug cCSnigmbXRghrHGxmtPpXl7Ww5NfPcKOkOVc73nCm0wcXFTj2tOgepZYihqFxh9kMS BqzFUUiYuO4gNnZWQKEd8fyg6Kh+JaljazXuaiUye3WO1zsFfVvp0JgNCsImDkMbDK TTDWr0AIR3JN92B6TawmACviMCQ7B9CYKgw49caks4b8n/jgHBAic52aecEHL6+73p qTvGpn0MhhEoPvsuHI46SLFiDhE0oOjmJX4KyTleuHYGNrth5ZifYZEI/K4zSSIUpI g2y0Cvd2Q4v5A== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 03/26] arch: Wire up userns_set_idmap() system call Date: Sun, 22 Nov 2026 21:35:16 +0200 Message-ID: <20261122193539.3334213-4-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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/sys= calls/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/sysca= lls/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/s= yscalls/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/s= yscalls/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/s= yscalls/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/s= yscalls/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/sysca= lls/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/sys= calls/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/syscal= ls/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/syscal= ls/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 =20 # # Due to a historical design error, certain syscalls are numbered differen= tly diff --git a/arch/xtensa/kernel/syscalls/syscall.tbl b/arch/xtensa/kernel/s= yscalls/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/u= nistd.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) =20 +/* 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 =20 /* * 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/a= sm-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) =20 +/* 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 =20 /* * 32 bit systems traditionally used different diff --git a/tools/perf/arch/arm/entry/syscalls/syscall.tbl b/tools/perf/ar= ch/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/pe= rf/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/per= f/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/a= rch/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/arc= h/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 =20 # # Due to a historical design error, certain syscalls are numbered differen= tly 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 --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376173; b=uBOddxOuhj8vMUDTmGV0ZDiPfIoRM04Uz7CZOmCkfTXXncH3jZMHx7lmwQhdZ0Az2Suf xWvxI7Alt6iQLeDr0ZfxdAb6rdsWmUddbWNxWtvbGJSdtw4jkI/NncMDApx5bqtyBWhBk XcZI8rBcHeixVBsUWd9uKuiq3Y+hCI3TErjSOQMbWQuFZgEibrGI3P61ja68Ogq4pj1WN esMcoCUMes6zA9mMe34kmoA4UOxVx5RkpYX3sCVwwh2zzVnMeGb5/uukmCEc20PCwbN0n BQBFykZWm+OpID9rHhIRIRTIohsAqGf0Z7+FDnkkl8n7nyHQ94vZdHnTOck8Ekpe6zA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376173; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=vM1mKrQLSyzANBNyG1aKfJTP501fkwwz9TXQLi7bGuQ=; b=s0H3D5pU8VAOPt5p+syq3G1EZIdKU6N/y4Xzbab9FM6qGnrV5sYgsiNx6RU4krsJJ/NB Aa1f3SGdZ5C/QGUHOt58M7ohuYVDrtqCXG1IPTrYHOJYwaw4RRu4lTxdJ3glmu5VPACWS fZPuzQ0ORo877BbiPtQcmqK8c8daK5DFXRk+V4nTc47YOnVE9eubKT5QOz5f1Rc+WhLgj /LuunyAnNfw3PWI3arJMCgvJb3HlGHDNDiYRVkr7TGhUQsxbwqeD6Ql/6278bu0RT9jyR 2k1l18KBIGeEKwMgHJP3t9RtT9FpLX5icI8oPszAud5/YM6SjxObsDHzKVX0TnifFUw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=ML3xN9f1; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id 9C669606A32D; Sun, 22 Nov 2026 19:36:13 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=ML3xN9f1 Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id AD8231F0093E; Sun, 22 Nov 2026 19:36:12 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376173; bh=vM1mKrQLSyzANBNyG1aKfJTP501fkwwz9TXQLi7bGuQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=ML3xN9f1NmOT9C4XtO9B3G/pEraSCkk+fGaUGxmfXkMSy6TKIXwr5mJ/3Vb0BQdJx bc4Zgm5HzTPW7ytnpBWX+mvGnJJToKTeHouV6VOQ4K0ixbrEDJTitMQrGpBFHfl/YQ Uupc2uCAxIGiBsYzn50mAhzkLjT7HECBIIA83ovrkQSr1W0+ZEjB4dtS+3WxjZm+DD WUEB8tzZ2u5Ytdu9lYsERqyGEtHbrar1iun2ztFzU6sHSkfUhgdjFFouEhwNv/3QaK mjpaCN5iKa1Kot+n2y5Rwu+az720n6eoCHJuGinUAhRjNbLRwVb6KGTnrvVjvRx6Kj 1lk1dgq8Y6CjA== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 04/26] mount: Add mnt_ns_get_root() Date: Sun, 22 Nov 2026 21:35:17 +0200 Message-ID: <20261122193539.3334213-5-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 Signed-off-by: David Howells Signed-off-by: Jarkko Sakkinen --- 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)); } =20 +int mnt_ns_get_root(struct mnt_namespace *mnt_ns, struct path *root) +{ + int err; + + err =3D vfs_path_lookup(mnt_ns->root->mnt.mnt_root, &mnt_ns->root->mnt, + "/", LOOKUP_DOWN, root); + if (err) + return err; + if (root->mnt =3D=3D &mnt_ns->root->mnt) { + path_put(root); + *root =3D (struct path){}; + return -ENOENT; + } + return 0; +} + static int mntns_install(struct nsset *nsset, struct ns_common *ns) { struct nsproxy *nsproxy =3D 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 @@ =20 struct mnt_namespace; struct fs_struct; +struct path; struct user_namespace; struct ns_common; =20 @@ -15,6 +16,7 @@ extern struct mnt_namespace init_mnt_ns; =20 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)) p= ut_mnt_ns(_T)) extern struct ns_common *from_mnt_ns(struct mnt_namespace *); --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376178; b=cfZ5VP5YrDl5rvD7i1OnKCmrAzK2ElSvta4uR8TkAlo74jFT736GBEJlMaDLtcIDSNe7 V91GF+L6YCMu270p2qYWeSa02auv4W/gfBQ5oSgXWN1eWcCm5wA5mVkslaPY5WQNo19pZ 8+sKG3NKkzCYo6YADFueMDZb5g7qBDnxB/YULTckAatXfSOge1mIoTEr9sVM2Ry50zqI2 aLYXJADbPb4HHehMgo1LRWr742p0fE+QS3QJ8CPx4ZY1PFnNCC8RMHu6qXdgoEHg46CPU lgNa9TiK45eLxB92jbWM31rLSMf1lktqlgkc+RhJihxTsWZ+XJj/vPSOj6KuKe+DvJg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376178; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=l3BxF7eKc8H9WX2SeKI00rPkbSvVT1UJBee/DhqmTQQ=; b=vmDTZwG+RhcSQKOw8TIXiezwWtR7qcjeWdVLqcFxx4IX6zHW/hUqiJJh/n09m7Ar1f0l LnZDwzfHiaS1O+t7KFXr6cInCHZ4Z7cfygy5202px2RvBmzobwFTCHTOTymK1M57RAxb2 x8AIKO6kWvfrebzx4MR2Zfg6KmxMsr1kXpkqo//zVNykhSdK+NcamVjAisr3UjWf6tGZ6 fLv1/WNyDhxhQmS8Tv3JOoF8Vrggp7sgOnLAmKxc0iB6ep0sIRW4BE/vNbpMU8tnRUFCD VeyhlvPYkiudhsTxSFKkCLXhVCP9v5scLSBN/nD3HQxTJQlvvd5MWfSy/3OapS2x9JA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b="T28tb/dn"; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id 2C522606A320; Sun, 22 Nov 2026 19:36:17 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=T28tb/dn Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 09FC71F000EB; Sun, 22 Nov 2026 19:36:17 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376177; bh=l3BxF7eKc8H9WX2SeKI00rPkbSvVT1UJBee/DhqmTQQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=T28tb/dnYShrqpGI2ZILYjzh72RVEHrrezyrm54oR6Obd86v3PTs376d9kZmGiJB+ MUaqau3YQxX+z/GWr+9RG0JDb6bK1vqUMm9l/H8m/RqGDXDxO5ShNJ6WPrcOKQFN72 Lp2v8MzuVi6Nq52IkFkGidmWcugTYAZverSueVjAgR2lsfg4eHz5f+C9qJscWQmP91 UvSv7pZiNTWpbNmSdj6YKT2dG8l982i7je4+oLgBuBdSEu85qs20Ob4lOnj9/OCG2z aSfS6cai0B+r+urHqmyerKvW0s6us7upbOBQhpzjuP6094eRFGxT0XybG4NqwQpfnw 74hvHOnQ9kYMw== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 05/26] mount: Enforce mount_too_revealing() for foreign mntns Date: Sun, 22 Nov 2026 21:35:18 +0200 Message-ID: <20261122193539.3334213-6-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 Signed-off-by: David Howells Signed-off-by: Jarkko Sakkinen --- 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) =20 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 =3D *new_mnt_flags; struct mount *mnt; @@ -6606,11 +6606,16 @@ static bool mnt_already_visible(struct mnt_namespac= e *ns, continue; =20 /* A local view of the mount flags */ - mnt_flags =3D mnt->mnt.mnt_flags; + mnt_flags =3D READ_ONCE(mnt->mnt.mnt_flags); =20 /* Don't miss readonly hidden in the superblock flags */ if (sb_rdonly(mnt->mnt.mnt_sb)) mnt_flags |=3D MNT_LOCK_READONLY; + if (foreign_ns) { + if (mnt_flags & MNT_READONLY) + mnt_flags |=3D MNT_LOCK_READONLY; + mnt_flags |=3D MNT_LOCK_ATIME; + } =20 /* 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 =3D 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 =3D SB_I_NOEXEC | SB_I_NODEV; struct mnt_namespace *ns =3D current->nsproxy->mnt_ns; unsigned long s_iflags; - - if (ns->user_ns =3D=3D &init_user_ns) - return false; + bool foreign_ns; =20 /* Can this filesystem be too revealing? */ if (!(sb->s_type->fs_flags & FS_USERNS_MOUNT_RESTRICTED)) return false; =20 + foreign_ns =3D !ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN); + if (ns->user_ns =3D=3D &init_user_ns && !foreign_ns) + return false; + + if (foreign_ns && current_chrooted()) + return true; + s_iflags =3D sb->s_iflags; if ((s_iflags & required_iflags) !=3D 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_bl= ock *sb, int *new_mnt_flags if (s_iflags & SB_I_RESTRICTED_VARIANT) return false; =20 - return !mnt_already_visible(ns, sb, new_mnt_flags); + return !mnt_already_visible(ns, sb, new_mnt_flags, foreign_ns); } =20 bool mnt_may_suid(struct vfsmount *mnt) --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376183; b=za2UcAQlp1rZSwMgUPsGXASwNhbAhw68VxWQ4yuuefIy54eqfZw8dVPQ5XmzLg0RvNfu m9fWAcRprmXLP6nUVbo50T8DvF8vEs3R+LQ1kW7Ft8oSDpP/hDmffh3yFuV+VidnUvXVU lqBNo9zn5wRIm2g6RMHqnoV5gsgAQlIoT+S+kX1wDSz6oWHAWEcPnQCZa6/qn0cqD47Zv WxqHZ57BGko9f12NeEiz/9tWnFXuPzTUta+Q57erLVu9SXRkirrLvAZZ00AqS0bo2MG8P l3aUp1aCuGZ23IOWg76g44SZbbycSgrDuDtVgDJnvImNnztiDUAfv448WcadIzp5MhA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376183; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=5jrAX1PmfNtv6uOvZGmkwX1H7UPYJH6p5kmtKInrUTc=; b=ajTwh8xG5SvYY9ejK09+2U2yeaBnenmOpSH1UJUaqpkJGB1GosSW75mJd4APUTEzqhQT osSHmRVN6mV1UxQ5ieqpeyMZOpUAkGHuT2ph86gVQAbTmrVItkUNdW462EtfCEttVwhhD 1QlaRSXRPhJNy4JwAL4C/iqKJV3DF5W78nD0lte4gHbWaUwqDPRQojSzY4nHZWpZsDhsL oA2UvjvotPQwwJGJ9qvHdglIFL5Jzhm3OToHm/onUprbQ9m6lRV80xA5Xj9KGV440GbSl O207t2qRZ4uYHv++7cTxOt53t1SffJqFSqjnjW4ENM5HWOVcfkquyf9jaqoJfJFjiVA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=Br9beAXp; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id 03DB0606A332; Sun, 22 Nov 2026 19:36:22 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=Br9beAXp Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 421061F000C0; Sun, 22 Nov 2026 19:36:21 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376182; bh=5jrAX1PmfNtv6uOvZGmkwX1H7UPYJH6p5kmtKInrUTc=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=Br9beAXprFGij/+40/DsIWOg+MKu+1rmUGEdQmx2e1C6wg/wAYxaxU9+E5PcqnIXH d5gerPs13OrDyCLG301s/dqW/l79pgAw2umYn3k9dTUSJnecT0POE1ZAbSb9jIEiGn c7n+0MZH54bUU195vbobf1ECTDJ2dftZizqLY5avzGNyJGbCYRSwM+B05QpmUxh2T/ opf800SdJ7o1TyszlbvFiTkIkYmlPBjsj/61bvm3BJlRFEHVNvFfVNUtSdxXhtCJFJ HCfxakC4I9L14bYYvur262S9TF5Gww9UDY5q2iS+0nzmExopckW8sR/fSeJwowbMOH 1XaXpF6P5Zfdg== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 06/26] mount: Support MOVE_MOUNT_T_MNTNS in move_mount() Date: Sun, 22 Nov 2026 21:35:19 +0200 Message-ID: <20261122193539.3334213-7-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 Signed-off-by: David Howells Signed-off-by: Jarkko Sakkinen --- 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 dentr= y *dentry) return to_mnt_ns(get_proc_ns(dentry->d_inode)); } =20 -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; =20 - return current->nsproxy->mnt_ns->ns.ns_id >=3D mnt_ns->ns.ns_id; + return target_mnt_ns->ns.ns_id >=3D mnt_ns->ns.ns_id; +} + +static bool mnt_ns_loop(struct dentry *dentry) +{ + return mnt_ns_loop_target(dentry, current->nsproxy->mnt_ns); } =20 struct mount *copy_tree(struct mount *src_root, struct dentry *dentry, @@ -2423,10 +2429,11 @@ static bool __has_children(struct mount *mnt, struc= t 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 =3D subtree; p; p =3D 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 pat= h *path) if (!anon_ns_root(old_mnt)) return ERR_PTR(-EINVAL); =20 - if (!check_for_nsfs_mounts(old_mnt)) + if (!check_for_nsfs_mounts(old_mnt, current->nsproxy->mnt_ns)) return ERR_PTR(-EINVAL); } =20 @@ -2564,12 +2571,16 @@ int count_mounts(struct mnt_namespace *ns, struct m= ount *mnt) enum mnt_tree_flags_t { MNT_TREE_BENEATH =3D BIT(0), MNT_TREE_PROPAGATION =3D BIT(1), + MNT_TREE_MNTNS =3D BIT(2), + MNT_TREE_MNTNS_INIT =3D BIT(3), }; =20 /** * 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_MNT= NS, + * 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 =3D dest->parent; struct mountpoint *dest_mp =3D dest->mp; HLIST_HEAD(tree_list); struct mnt_namespace *ns =3D dest_mnt->mnt_ns; struct user_namespace *user_ns =3D ns->user_ns; + bool cross_src =3D src_user_ns && !in_userns(ns->user_ns, src_user_ns); struct pinned_mountpoint root =3D {}; struct mountpoint *shorter =3D NULL; struct mount *child, *p; @@ -2725,11 +2738,22 @@ static int attach_recursive_mnt(struct mount *sourc= e_mnt, hlist_add_head(&source_mnt->mnt_hash, &tree_list); =20 hlist_for_each_entry_safe(child, n, &tree_list, mnt_hash) { + struct user_namespace *child_user_ns =3D + child->mnt_parent->mnt_ns->user_ns; + bool cross_child_src =3D 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 !=3D user_ns) + /* + * Notice when we are propagating or attaching a foreign + * source tree across user namespaces. + */ + if (child_user_ns !=3D user_ns || cross_child_src) { lock_mnt_tree(child); + if (cross_child_src && list_empty(&child->mnt_expire)) + child->mnt.mnt_flags |=3D MNT_LOCKED; + } q =3D __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; =20 - return attach_recursive_mnt(mnt, mp); + return attach_recursive_mnt(mnt, mp, NULL); } =20 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); =20 /* 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 =3D -EINVAL; else err =3D graft_tree(mnt, &mp); @@ -3776,9 +3800,12 @@ static inline bool may_use_mount(struct mount *mnt) =20 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 =3D real_mount(old_path->mnt); + struct user_namespace *src_user_ns =3D NULL; + struct mnt_namespace *dest_mnt_ns; int err; bool beneath =3D flags & MNT_TREE_BENEATH; =20 @@ -3792,7 +3819,30 @@ static int do_move_mount(const struct path *old_path, if (IS_ERR(mp.parent)) return PTR_ERR(mp.parent); =20 - if (check_mnt(old)) { + if (flags & MNT_TREE_MNTNS) { + u64 seq; + + if (!anon_ns_root(old) || old->mnt_ns =3D=3D mp.parent->mnt_ns || + mp.parent->mnt_ns !=3D target_mnt_ns) + return -EINVAL; + seq =3D old->mnt_ns->seq_origin; + if (seq && seq !=3D target_mnt_ns->ns.ns_id && + seq !=3D current->nsproxy->mnt_ns->ns.ns_id) + return -EINVAL; + src_user_ns =3D old->mnt_ns->user_ns; + if (flags & MNT_TREE_MNTNS_INIT) { + if (mp.parent !=3D target_mnt_ns->root) + return -EBUSY; + } else if (mp.mp->m_dentry =3D=3D mp.parent->mnt.mnt_root) { + const struct mount *m =3D mp.parent; + + while (m !=3D target_mnt_ns->root && mnt_has_parent(m) && + m->mnt_mountpoint =3D=3D m->mnt_parent->mnt.mnt_root) + m =3D m->mnt_parent; + if (m =3D=3D 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_pat= h, */ if (IS_MNT_SHARED(mp.parent) && tree_contains_unbindable(old)) return -EINVAL; - if (!check_for_nsfs_mounts(old)) + dest_mnt_ns =3D 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; =20 - return attach_recursive_mnt(old, &mp); + return attach_recursive_mnt(old, &mp, src_user_ns); } =20 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; =20 - return do_move_mount(&old_path, path, 0); + return do_move_mount(&old_path, path, 0, NULL); } =20 /* @@ -4725,7 +4777,8 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, fl= ags, =20 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; =20 @@ -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); =20 - 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 =3D 0; + unsigned int lflags =3D 0; + + if (flags & MOVE_MOUNT_F_EMPTY_PATH) + uflags =3D AT_EMPTY_PATH; + + CLASS(filename_maybe_null, from_name)(from_pathname, uflags); + if (!from_name && from_dfd >=3D 0) { + CLASS(fd_raw, f_from)(from_dfd); + if (fd_empty(f_from)) + return -EBADF; + + *from_path =3D fd_file(f_from)->f_path; + path_get(from_path); + return 0; + } + + if (flags & MOVE_MOUNT_F_SYMLINKS) + lflags |=3D LOOKUP_FOLLOW; + if (flags & MOVE_MOUNT_F_AUTOMOUNTS) + lflags |=3D 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 t= arget + * 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 names= pace + * 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) =3D {}; + struct path to_path __free(path_put) =3D {}; + 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 =3D get_proc_ns(file_inode(fd_file(f_mntns))); + if (ns->ns_type !=3D CLONE_NEWNS) + return -EINVAL; + + target_mnt_ns =3D 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 =3D to_name->name[0] =3D=3D '/' && to_name->name[1] =3D=3D '\0'; + if (is_root) { + if (flags & MOVE_MOUNT_BENEATH) + return -EINVAL; + + to_path.mnt =3D mntget(&target_mnt_ns->root->mnt); + to_path.dentry =3D dget(target_mnt_ns->root->mnt.mnt_root); + mflags |=3D MNT_TREE_MNTNS_INIT; + } else { + struct path mntns_root __free(path_put) =3D {}; + + if (to_name->name[0] =3D=3D '/') + return -EINVAL; + + ret =3D mnt_ns_get_root(target_mnt_ns, &mntns_root); + if (ret) + return ret; + + lflags =3D LOOKUP_IN_ROOT; + if (flags & MOVE_MOUNT_T_SYMLINKS) + lflags |=3D LOOKUP_FOLLOW; + if (flags & MOVE_MOUNT_T_AUTOMOUNTS) + lflags |=3D LOOKUP_AUTOMOUNT; + ret =3D filename_lookup(AT_FDCWD, to_name, lflags, &to_path, + &mntns_root); + if (ret) + return ret; + } + + ret =3D 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); } =20 /* @@ -4758,7 +4927,7 @@ SYSCALL_DEFINE5(move_mount, enum mnt_tree_flags_t mflags =3D 0; int ret =3D 0; =20 - if (!may_mount()) + if (!(flags & MOVE_MOUNT_T_MNTNS) && !may_mount()) return -EPERM; =20 if (flags & ~MOVE_MOUNT__MASK) @@ -4771,6 +4940,13 @@ SYSCALL_DEFINE5(move_mount, if (flags & MOVE_MOUNT_SET_GROUP) mflags |=3D MNT_TREE_PROPAGATION; if (flags & MOVE_MOUNT_BENEATH) mflags |=3D MNT_TREE_BENEATH; =20 + 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 =3D 0; if (flags & MOVE_MOUNT_T_EMPTY_PATH) uflags =3D AT_EMPTY_PATH; @@ -4794,29 +4970,12 @@ SYSCALL_DEFINE5(move_mount, return ret; } =20 - uflags =3D 0; - if (flags & MOVE_MOUNT_F_EMPTY_PATH) - uflags =3D AT_EMPTY_PATH; - - CLASS(filename_maybe_null,from_name)(from_pathname, uflags); - if (!from_name && from_dfd >=3D 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 =3D 0; - if (flags & MOVE_MOUNT_F_SYMLINKS) - lflags |=3D LOOKUP_FOLLOW; - if (flags & MOVE_MOUNT_F_AUTOMOUNTS) - lflags |=3D LOOKUP_AUTOMOUNT; - ret =3D filename_lookup(from_dfd, from_name, lflags, &from_path, NULL); + ret =3D lookup_move_mount_from(from_dfd, from_pathname, flags, + &from_path); if (ret) return ret; =20 - return vfs_move_mount(&from_path, &to_path, mflags); + return vfs_move_mount(&from_path, &to_path, mflags, NULL); } =20 /* 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 pat= h */ #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 =20 /* * fsopen() flags. --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376186; b=wmA3VIcBckCuCHj4fOJOoQwYhruyYCv3WWGk7BkJ/z4lXqBw70b251k0yAVWVnxrzYIg ROg7x/TPfAb4yELUdPuctC04T9tPml1yfYjoR7aMr/r8HuofMZd8cOw2bgd9z/5a+AbHg cTFdTaoR92kpUwE/UVb/eGTcbdhQNllpdeaozfOI9wu6eTgHnGzHNyVELrB/P6jKEISZA a1hETkQgHVLWCIZvonJs1WPocKRatpDZNoY98UiGXv4HwbyrOcn0YoAkSLYaHYhBwPXf2 AdMxVJJPSv9hMb+M38q1s1F74y0p2MXiogetPgdpQGo2zGFbhewrxbxURDl9gkc9a7w== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376186; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=0eNIDEAoRmujXA6Ky0SIP9NpYpxjc1cr18CdGUMXyVQ=; b=Q3WJYxetxwILlyd0jg1IvqvVLAhcTrPHjIOhp0LjBp/0GK/IY7nygdw6r/aD2aTOy0HX 94hj5za9jPWLbLnAk8Y9EAljIeIaxdxxtaep47E97+H4xC8tW1SGMuHPdzwLKvndOXaUv NU0eecIK0vRhRw8lcLgn2uVdF6JbIKqaiYV66Jk0FdmWGFftkfbwrTuBU6RE0dd00iRmA +2KORYl9fESdxFqX+Yd341mopxpkDpo5+kdr8TDKyM8h7gJ0y/9RLyIdH6oqKdOy4Cj+u iahst2HXJwcC0h1Z/z4qcfkCqtf1Csk9vW8NVh44VybDf+sUxERGJVhFIFyLOsHBGoA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=TLFFyAyi; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id B74F0606A336; Sun, 22 Nov 2026 19:36:26 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=TLFFyAyi Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id A05D51F000D8; Sun, 22 Nov 2026 19:36:25 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376186; bh=0eNIDEAoRmujXA6Ky0SIP9NpYpxjc1cr18CdGUMXyVQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=TLFFyAyiMhK9+SAYJuBfJZEQtt1h6fQt9grxzJAP4rpI7obSf62cNKQZAYTyL0HB9 WnZKPuysbmFsbZdrAi0HCcEiJTOHTn9/3diENvg9DThAEXCv9O0YxoJPZTOxR/rFzA JgPHvjFAV+em3yt5633CMfEMJp2ZDdsjP0EGo5+FIuwrnoqIxGM7iNlM0FXfBLWsai GIk7KAamRhim5UvhKQJcs00/KagMUt8t3KJei22Llu3GK0UvsD/ojToL/meIiw3s/S NLcrLcfad3jY5fLiLZRUaibhLbHQLck+9QX8PepsyP25w6vInK+Pb2C9ylTrIPVqDP XCeD8oj9N9j+A== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 07/26] mount: Support MOVE_MOUNT_CLONE with MOVE_MOUNT_T_MNTNS Date: Sun, 22 Nov 2026 21:35:20 +0200 Message-ID: <20261122193539.3334213-8-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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 =3D BIT(1), MNT_TREE_MNTNS =3D BIT(2), MNT_TREE_MNTNS_INIT =3D BIT(3), + MNT_TREE_CLONE =3D BIT(4), }; =20 /** @@ -3805,31 +3806,28 @@ static int do_move_mount(const struct path *old_pat= h, { struct mount *old =3D real_mount(old_path->mnt); struct user_namespace *src_user_ns =3D NULL; + struct mount *cloned =3D NULL; struct mnt_namespace *dest_mnt_ns; int err; bool beneath =3D flags & MNT_TREE_BENEATH; =20 - if (!path_mounted(old_path)) + if (!(flags & MNT_TREE_CLONE) && !path_mounted(old_path)) return -EINVAL; =20 if (d_is_dir(new_path->dentry) !=3D d_is_dir(old_path->dentry)) return -EINVAL; =20 + 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); =20 if (flags & MNT_TREE_MNTNS) { - u64 seq; - - if (!anon_ns_root(old) || old->mnt_ns =3D=3D mp.parent->mnt_ns || - mp.parent->mnt_ns !=3D target_mnt_ns) - return -EINVAL; - seq =3D old->mnt_ns->seq_origin; - if (seq && seq !=3D target_mnt_ns->ns.ns_id && - seq !=3D current->nsproxy->mnt_ns->ns.ns_id) + if (mp.parent->mnt_ns !=3D target_mnt_ns) return -EINVAL; - src_user_ns =3D old->mnt_ns->user_ns; if (flags & MNT_TREE_MNTNS_INIT) { if (mp.parent !=3D target_mnt_ns->root) return -EBUSY; @@ -3842,6 +3840,36 @@ static int do_move_mount(const struct path *old_path, if (m =3D=3D target_mnt_ns->root) return beneath ? -EINVAL : -EBUSY; } + if (flags & MNT_TREE_CLONE) { + unsigned int copy_flags; + + if (!check_mnt(old) || old->mnt_ns =3D=3D target_mnt_ns || + (old->mnt.mnt_sb->s_flags & SB_NOUSER)) + return -EINVAL; + src_user_ns =3D old->mnt_ns->user_ns; + copy_flags =3D (target_mnt_ns->user_ns !=3D src_user_ns) ? + (CL_SLAVE | CL_COPY_UNBINDABLE) : + CL_COPY_MNT_NS_FILE; + cloned =3D __do_loopback(old_path, true, copy_flags); + if (IS_ERR(cloned)) + return PTR_ERR(cloned); + old =3D cloned; + if (d_is_symlink(old->mnt.mnt_root)) { + err =3D -EINVAL; + goto out_cloned; + } + } else { + u64 seq; + + if (!anon_ns_root(old) || + old->mnt_ns =3D=3D mp.parent->mnt_ns) + return -EINVAL; + seq =3D old->mnt_ns->seq_origin; + if (seq && seq !=3D target_mnt_ns->ns.ns_id && + seq !=3D current->nsproxy->mnt_ns->ns.ns_id) + return -EINVAL; + src_user_ns =3D 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_pat= h, over =3D mp.parent->overmount; err =3D can_move_mount_beneath(old, over, &mp); if (err) - return err; + goto out_cloned; } =20 /* * 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 =3D -EINVAL; + goto out_cloned; + } dest_mnt_ns =3D 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 =3D -ELOOP; + goto out_cloned; + } + if (mount_is_ancestor(old, mp.parent)) { + err =3D -ELOOP; + goto out_cloned; + } =20 - return attach_recursive_mnt(old, &mp, src_user_ns); + err =3D 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; } =20 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 t= arget - * mount namespace ``nsfs`` file descriptor supplied as ``to_dfd``: + * ``MOVE_MOUNT_T_MNTNS`` installs mount trees into a target mount namespa= ce + * ``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`` recursive= ly + * 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 names= pace * 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; =20 + if ((flags & MOVE_MOUNT_CLONE) && !(flags & MOVE_MOUNT_T_MNTNS)) + return -EINVAL; + if ((flags & (MOVE_MOUNT_BENEATH | MOVE_MOUNT_SET_GROUP)) =3D=3D (MOVE_MOUNT_BENEATH | MOVE_MOUNT_SET_GROUP)) return -EINVAL; =20 if (flags & MOVE_MOUNT_SET_GROUP) mflags |=3D MNT_TREE_PROPAGATION; if (flags & MOVE_MOUNT_BENEATH) mflags |=3D MNT_TREE_BENEATH; + if (flags & MOVE_MOUNT_CLONE) + mflags |=3D MNT_TREE_CLONE; =20 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 =20 /* * fsopen() flags. --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376191; b=F+DuJWRAMpFfSHbXJS+YprQCxkVaekpjaO0NB5EOIfzrOrH14DYuY0Wfur3x+y2fY2uw aE/qQRFK86mDEpm+r4ILY6uafJf6qZuf3OY8IHlzdUJqMEBhzwYNkoRkT3frjToqp7Ter wDflqDQ0hVzCEBmFKOQAVIHBv1odHm4EhEBy52qOBBenFLC6f0uE9R8fUezmr7jdRyIx9 G5/8kQ5v8eXbqg/u0XvZbKzfv82DXaclBohKqqgZJy75g++EjfpUJuHZ5WTZopHHB8C1X igMEn1Se2Phh2Mk3NkRlXZsX+daEDGh64IPGDtcHfm+U/pWqBh4q7WgVaxGYyfK/Prw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376191; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=43MsiEFgIrWkQNcNF+GYEjx93qeN3UcnPDjH27vMBMY=; b=NjgPFAuP7VX9v/ecV2jOcO6voJMyU921r26ucFJNu+mIo3pZIN8kIhuMfnLGaPqTwE84 RkF9Nuk1FwYmer+1dITbirD7DquoKAjqY4s10em8GrUyxQcQvWViZDmfKS0JRbGoe0Xcu 1Az4bPwg+RGPBR5v2ZPCQ2VIEzsy42SwTJ7IWduePirdp0GNunmWPUQJ9LGHIKcM7mYI7 UbcMBsyddPJvOh0QlBha0/Q12hBQg+8AnJ6k/fr4cmjIoZjxBt7rkDR32DSlZlD5dwFKP PvtABPomWvreciMV3jISxF00iry6ucnH22TmbAq5tohuM3wE2a+k/k3shc63GkQCW2w== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=Jx9MYo4v; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id 383A9606A338; Sun, 22 Nov 2026 19:36:31 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=Jx9MYo4v Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 1E7691F000D4; Sun, 22 Nov 2026 19:36:30 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376190; bh=43MsiEFgIrWkQNcNF+GYEjx93qeN3UcnPDjH27vMBMY=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=Jx9MYo4v5dG6TuiLqqMpwfnCLNp1dU3fsjM0rs7NeUiQpqvCbQkc6zfNZfQn1ceCg dkL6lAYTT/XApYv1EnrG/3bDLes3Ar8rT3NVk6CyizxCjxJOWQr/BQgKMnE4DozfXc 6MaZrPMCQKrw6XbZAf3J55qgj9MKKx8nvfOUvGoHcJ7/8yOdGVy1JssCARbZmF8vek 6kxEG95kGAihkM4HDqZ8n1mTcg/lmo4gtW2J8GayVKr+sLDzrsuUuDCALp/vF2d+2v BPUR0GZ3wJ2zZz8SvSCUOuV/4ea/j5aB9DkmJvEGCqfWbjjKoyCZJsHY54JfZejPWu dmVhu9cXx73XQ== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 08/26] userns: Factor out install_user_ns_cred() Date: Sun, 22 Nov 2026 21:35:21 +0200 Message-ID: <20261122193539.3334213-9-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 Signed-off-by: David Howells Signed-off-by: Jarkko Sakkinen --- 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) } =20 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_c= red); extern void __put_user_ns(struct user_namespace *ns); =20 @@ -224,6 +225,12 @@ static inline int create_user_ns(struct cred *new) return -EINVAL; } =20 +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)); } =20 +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 =3D to_user_ns(ns); @@ -1638,10 +1645,7 @@ static int userns_install(struct nsset *nsset, struc= t ns_common *ns) if (!cred) return -EINVAL; =20 - 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; =20 return 0; --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376195; b=EwPUx7GJayRNT1uUI2+/Ofvg4o+ubykL9fXewcITgNNoKxN5rNbXBUESm31eHFmg1cLg nFGYMh2xYG/NGOh8ZKzskxPSjYgo+KpyJVK2XTsm9yE7Y0u83RX8jGv+OwiLMmIqmFS9q ViZkjE55GHNBzBjGiVYzebKdP4rgpT/3lbnoV3f0+8WUH3sNuYtnbTA/GkjLJ8spCJoDB DerNaDX2xIEhSo8nEyC8I36Tx5xYaEpYxP6EFTBJS2UHs9djsL9G0iMKrTMJTc82uygPO 9Fq//4zvAgctEPmn9B/NpdkDJK/o9DwvxEoGDjje5vivcVagr/sAlvA4XLrfbReD6AQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376195; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=ujYt3pxK39YV6xgrJ9ycAzI8XphJxsY1pHf5v0/Q8cY=; b=nZNyeNrA8oBoKz1d0iHxBLn+muH/LbgxiZe25vyyVbd7V+91wW8Mtw7GO6RliZyb5OEl Ej2lxkc2KYlAhGqXjuVZbh+rVWzJA07P9ElBOUTdzrXRbACabEHIYnCi2X1n6u5LarW3p 6uCKX3T5JlUTBGDkyOwtvv2xXyQDAugBuQ1Q79LME/2uPfAtzzxGzKJqdjlVXS91ZrTgS 7PDPQ4aNwRKkVSb9bE73O8iMsHRj8UOX4DDy7NdxGcDTTMkwbZjMOsEOB8j9rV3KbhT5/ DZJRmWvjxy0tSKDR8EXWtTrV2d6QL4vA4nWQGtt+WyDZwRV+mSm5E2M3eFqSH3e9bGw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=OoGSfxYg; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id 3D54A606A32D; Sun, 22 Nov 2026 19:36:34 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=OoGSfxYg Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 275C91F000E1; Sun, 22 Nov 2026 19:36:34 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376194; bh=ujYt3pxK39YV6xgrJ9ycAzI8XphJxsY1pHf5v0/Q8cY=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=OoGSfxYgsZcZJElXw84v9gsSeSMwok9hzGq6rqX9ynWRDXqq3zx71CzuuYvvw2g/R 1UpEgjqxgsRgThvgJblfJjMiuNX4mqqhqHoyFnm0J7hEkd5/8FlUQcVS3mkMU4mMYX iF91SZzxOwMNMH2crVXxL7rch4XakMfXwpVbdpSN68at4yxvJhdrFGtdqimiqw52tC d1j+4sNCZtrz2PP53RcNgvvbAnU4dUe5TRSV/ZC+XXhMOQA24qIq01hpvWa3QXVrBH aYxsxae0fedmvv9+V6SNnLaGfcB9iN+D8NEneNdjl2luzlR75sAG8Cl8K/pyTCNbLe u82rSzLk5TrlQ== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 09/26] nsproxy: Expose create_new_namespaces() Date: Sun, 22 Nov 2026 21:35:22 +0200 Message-ID: <20261122193539.3334213-10-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 so userland_open() can allocate a detached namespace set from current. Co-developed-by: David Howells Signed-off-by: David Howells Signed-off-by: Jarkko Sakkinen --- 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; =20 /* * A structure to contain pointers to all per-process @@ -92,6 +93,9 @@ static inline struct cred *nsset_cred(struct nsset *set) * */ =20 +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; --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376199; b=IN9dVxTrqmPddojmmaFSBORIi2vPsxaEKUuNKtWJbZXX6MgVsp6oMHqpSOnBGwbjKx84 4en4n/wPx9TcGuwR+HeIBZdDAMTrSJtbs3sf9+l6pQwLJuvISHx5qfKgSz0Gt34M7KCnK 2yujx7yIyu/FJEfnhFaF4ahO8Dj18WheajhjpIbb0V6tXJuyh5MNRoqSlQNLEOUFImpKz Q8Mn4kzBDILOuugFxQxrfFtpIkCyp7AduaY3FhRlCc6UkObDoQN+Dw0Tnm2SYBhozywDD AYgeeB9Uk+0AnviU9FFBQ2ViJuy0nHWkmO1MAx5khBiW2M44fpo37+OrmLJi6vJpwAw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376199; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=YbRTDchIsz6xcCBmI8LhY6NC9NG/SzViBPWKNz/ygpo=; b=bZUW4RGxd3yVRWlya2Hgv14RvRW7LJFfOAz5bJPTDKSEfXFFs/SPoX9/od6VE8KLDWqO 0+ctRu994L+k3PEtNJAccwTDXTWhjXUuLQtuBaDJAHlExwliDYYYh1ybSLdBPc94y42GQ Zfzi4Pw0HkU/b+G+oIKcoFcnMDJPWhGchs18o9FGjxPqE1YQZNsFAc3TuNY1qtswBFd+a EA/QGHcZF9IKquO5l2G+Q1kd4sefW7WzqDgt/KEP2ByseeQqha38OX5GB4Pd8tfnwrMm5 JvKQf1L2K15/d24a/K6Xrtz0aodOrYng9Rs4HdQw05mviG7mvjgiAsd4Pceubz/V3AA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=CG6CfgoO; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id B8B89606A6B5; Sun, 22 Nov 2026 19:36:39 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=CG6CfgoO Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 790321F00A01; Sun, 22 Nov 2026 19:36:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376199; bh=YbRTDchIsz6xcCBmI8LhY6NC9NG/SzViBPWKNz/ygpo=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=CG6CfgoOYB1ykMnFVIQA0eyNbZL7c4vTkkFjT9pExp0M3QXg7D4zdq3w1sclLPgVq v6GwXd0nxYHutNTZB6HGmpV/+OX73AimUAxExG7MjtuOCGoUXB9N3zjmzMRwpdFDdx dCdEROaBeimYhLAOA1YltC41CjAlimHm/dakNnZRdrEWBPFmtPW4AkIF+zJfIjIHGG EGs++cNh42bvFH9IC59uuOPQ33drP6C5iAv5LMllE97DfQwhpVMbtaPngkZXJoHrkz TdX6U7kwnoRm40yTMUhPbV1gJs6Kq3aLa/e1x5MQ8CAA+fj6p3lm5F9OnZf3ZRlYGE l0cyVa5uM5glg== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 10/26] userland: Add core infrastructure Date: Sun, 22 Nov 2026 21:35:23 +0200 Message-ID: <20261122193539.3334213-11-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 Signed-off-by: David Howells Signed-off-by: Jarkko Sakkinen --- 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 +#include +#include + +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 =3D 0, + USERLAND_FORKING =3D 1, + USERLAND_RUNNING =3D 2, + USERLAND_DEAD =3D 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 rel= ease. + * @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 =3D 0x00000001, + USERLAND_CLOSE_ON_EXEC =3D 0x00000002, + USERLAND_ALL_FLAGS =3D 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 =20 endif # NAMESPACES =20 +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 :=3D n =20 obj-$(CONFIG_SCF_TORTURE_TEST) +=3D scftorture.o =20 +obj-$(CONFIG_USERLAND) +=3D userland.o + $(obj)/configs.o: $(obj)/config_data.gz =20 # .config is small, so it is compressed with gzip rather than the image co= mpressor. 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_op= en()`` + * that binds a detached namespace set, an initially empty mount namespace= , an + * owning user namespace, and an init process lifecycle. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 =3D file->private_data; + __poll_t mask =3D 0; + + poll_wait(file, &userland->waitq, wait); + + if (READ_ONCE(userland->state) =3D=3D USERLAND_DEAD) + mask |=3D EPOLLHUP; + + return mask; +} + +static int userland_release(struct inode *inode, struct file *file) +{ + struct userland *userland =3D file->private_data; + + if (userland->flags & USERLAND_KILL_ON_CLOSE) { + struct pid *pid =3D NULL; + + scoped_guard(spinlock, &userland->lock) { + if (userland->state =3D=3D USERLAND_RUNNING) + pid =3D 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 =3D { + .poll =3D userland_poll, + .release =3D userland_release, +}; + +bool userland_is_file(struct file *file) +{ + return file->f_op =3D=3D &userland_fops; +} --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376203; b=jcUAd/lRQigHorTLsdkigNL6xr89phZdxuBXoE8pkGD2iGg1i5bNqsEbggHGR9ubl1Xp DMJx21+F8urMLX7RhVedK2hcGw+lCyyb2J+7rhjOAtyP2nD5Eyqg1gGsVZnYu3ScAthxv PRte7VEzo7RGgntdkVRm4y+OgsOMdfLmyIYoI+E+NnFbNp+mcRhtDjFdXXXjhJcGhcou7 zcmqGiLVLT/UY4LPgffK6oAHA0KaFHqE8MHputN7w0GFFptZw7U+huS61v9EuV0VgMZey K2yC9lN303JQdRt9ToJpEwPRBt4kCzzoHKjESDk8HXA0kXDrJXD7+BnVxMs1BLvvWUA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376203; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=IjAX6Mgusa/02dTL9k5B5iNWMUDytzyYEuLarDCWpNc=; b=LGb4Dvhc01NhMeG1VVtaILAe1ddO4ez9iGcWDMLjP5YbKVSYanA9EtykAk2pb9Bx4tmy HqtUXea84Tvnou7+rDXz03w0NR3tNFSySP8/2F3CL7E4ivF+rNfEywNz8pE1BlDDwCWq1 cXK3jyzRC8wf2wLZ3Cj+vg1UetwcJpWMJ+P7+Wncc+zfg/NjVYIKIGlW4FezCNt6PAEeC 6Tem6FKooT4FTLLcfneCdN11G0ysG6vm/MX3e05ew1QadGsZEB0K8+Y4Y7oyvk7pF7A7W WpsZWYMj4VcCUEDwLvO2ZrZabKgY8eDhNFoJTzSn8Z04HTAwJZFaATg0wJoSfRgVPbQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=czFAln2I; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id A3F7A606A333; Sun, 22 Nov 2026 19:36:43 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=czFAln2I Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 8C2F81F000D4; Sun, 22 Nov 2026 19:36:42 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376203; bh=IjAX6Mgusa/02dTL9k5B5iNWMUDytzyYEuLarDCWpNc=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=czFAln2I6+sZq5DeFOwio4VktCbvoePYK6YNR+jqX5L7t1kVE1E6i4UOoC/+6YODO As9Q2tdND2gTuJbgeUqygX+MOX158TyJEEyEO9tX6+1iLSif2X8rebKCba0J2MRXkA hyV2Lp/6hTGUgmVrRz6OhP36LXJKHLFLd33LCxox+NfXtTjjBI2BBq1JERLBLnFhE+ B0V0aS/b1TK8XaRsnTnugpynFGEewuW9jXjC3mCfE+JYajLi93UElxeRhmK7auNl44 AyWflxSKkh4/Fqv+9i1D17R6n0QfmX+jFtO+uNeGSvJnVNXeM+YBDHEFBtAFoB05G9 eRtvVy4l0DpeQ== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 11/26] userland: Track init lifecycle via copy_process() and pid_namespace Date: Sun, 22 Nov 2026 21:35:24 +0200 Message-ID: <20261122193539.3334213-12-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 Signed-off-by: David Howells Signed-off-by: Jarkko Sakkinen --- 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 =20 struct fs_pin; +struct userland; =20 #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 @@ =20 #include #include +#include #include =20 struct file; struct nsproxy; struct pid; +struct pid_namespace; +struct task_struct; struct user_namespace; =20 /** @@ -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 */ =20 #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 #include #include +#include #include #include #include @@ -2584,6 +2585,9 @@ __latent_entropy struct task_struct *copy_process( syscall_tracepoint_update(p); write_unlock_irq(&tasklist_lock); =20 + if (likely(p->pid) && thread_group_leader(p)) + userland_copy(p, pid, NULL); + if (pidfile) fd_install(pidfd, pidfile); =20 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 #include #include +#include #include #include "pid_sysctl.h" =20 @@ -280,6 +281,7 @@ void zap_pid_ns_processes(struct pid_namespace *pid_ns) current->signal->group_exit_code =3D pid_ns->reboot; =20 acct_exit_ns(pid_ns); + userland_exit(pid_ns, me); return; } =20 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 =3D=3D &userland_fops; } + +void userland_copy(struct task_struct *tsk, struct pid *pid, struct userla= nd *c) +{ + if (likely(!c || !is_child_reaper(pid))) + return; + + scoped_guard(spinlock, &c->lock) { + if (c->state !=3D USERLAND_FORKING) + return; + refcount_inc(&c->usage); + ns_of_pid(pid)->userland =3D 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 =3D pid_ns->userland; + struct task_struct *leader; + kuid_t uid; + int status; + + if (!c) + return; + + leader =3D tsk->group_leader; + rcu_read_lock(); + uid =3D task_uid(leader); + rcu_read_unlock(); + status =3D (tsk->signal->flags & SIGNAL_GROUP_EXIT) ? + tsk->signal->group_exit_code : leader->exit_code; + + scoped_guard(spinlock, &c->lock) { + c->exit_code =3D status; + c->init_uid =3D uid; + WRITE_ONCE(c->state, USERLAND_DEAD); + } + + pid_ns->userland =3D NULL; + __wake_up(&c->waitq, TASK_NORMAL, 0, poll_to_key(EPOLLHUP)); + userland_put(c); +} --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376208; b=pGnVyVZ8gKzthKw2uTVOwokMxYC8hBPO4yjTxzEqhjAMtOf/jG8heAZoQofZMtbFAR2T tqbgIdfGdkzFIkcnsCsAjyZYRVe5FptALcroHnKEkDzuI+lAKhZn5r30rCbiIdKXwvcYL 82DcxAVmfj73vQm0DxS4zSqLBaqXlWiByxe8orCyo69pcG6GKIAvFRmHQa8LtXd/TFWuI 5kvz7EawAYB5WX5OkZOsYqZiwvIfihCB7xiw1ppYmHUJZ4Z+YXipUOqh2hiPpdcXA5OOh YoTzHioWqz17XLMa0SAXF0EALKQz+1qlBKS568j4j8WURFZDlR9mscwc/JvrkNIYQbw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376208; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=HhStIPKcjxn5feiVQQthiDAsaf5QXO2X/we9bRZ2ovc=; b=GMPDfJd0IuAeTSMaeyhILRR+tAmUMHoJAh8BNTodtunOWhK9bCpk43Z0c54oN/lw0e3W j0Yr28R0AWUoNGCUzMkVUNs8UqUq0pFC5an+w9wEJz4NKI05NVWM3RB9967YzElzcMXnf yVBwDh/IjaR7GJDvHCAjOY/XZsOUwpb7fzaqIjZEx5t8roBrt9xsFAqoSc9ZznuduRbnf VnbPmMNNy4mot1ArjCzWN+da2q2FU/TJDfwHllVlcu6+BdRR532OC9yCEHW128B1DiYwa YEleQ1kufl4hLECRhGK1XGCihqHuplpX9kHKbR+jJ+S/89aCTm6UUVAOE5ofHPYcy3g== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=J2p8Uw3t; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id 13FA0606A684; Sun, 22 Nov 2026 19:36:48 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=J2p8Uw3t Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 161B71F000E1; Sun, 22 Nov 2026 19:36:47 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376207; bh=HhStIPKcjxn5feiVQQthiDAsaf5QXO2X/we9bRZ2ovc=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=J2p8Uw3tToGSVpLPHI/ucHupSZdB5Yj8etAJN6ZvUe1N9Mfhwn7WkGmPNajjpa+m2 XmWcivurVwUJqhvH+l4bD3esY8AfbvSE1E62GLu3HGDZ1I4jLEhFRTN/vBymzmzbVO NwmsSJ+oEMZUwBatE38HrA9XAAxW9Fo88Nv8oIpEvXGN9A1qOeTkInVESes6jCWnc1 zGU63Agrse/TuqwIUSvYPWXMrUY/Eq8E5aj9/XIhcJ6h5p+ck0XMAo28A/7h5huKGu MzkQLSyxnzBgAlct+yDcHRcYYJoqBROIMPeSd2Yhjk29Dw/vwX3SCsM95T4U7PwTUp BszEjcK2Fa9rQ== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 12/26] userland: Add userland_open() system call Date: Sun, 22 Nov 2026 21:35:25 +0200 Message-ID: <20261122193539.3334213-13-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 Signed-off-by: David Howells Signed-off-by: Jarkko Sakkinen --- 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 at= tr, 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, u3= 2 flags); +asmlinkage long sys_userland_open(unsigned int flags); =20 /* * 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); =20 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, stru= ct 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 =3D prepare_creds(); + if (!new) + return ERR_PTR(-ENOMEM); + + ret =3D create_user_ns(new); + if (ret < 0) { + abort_creds(new); + return ERR_PTR(ret); + } + + user_ns =3D get_user_ns(new->user_ns); + abort_creds(new); + return user_ns; +} + +static struct userland *userland_create(unsigned int flags) +{ + u64 clone_flags =3D 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 =3D 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 =3D flags; + + user_ns =3D userland_create_user_ns(); + if (IS_ERR(user_ns)) { + ret =3D PTR_ERR(user_ns); + goto err_put; + } + c->user_ns =3D user_ns; + ns_ref_active_get(user_ns); + + if (!ns_capable(user_ns, CAP_SYS_ADMIN)) { + ret =3D -EPERM; + goto err_put; + } + + ns =3D create_new_namespaces(clone_flags, current, user_ns, NULL); + if (IS_ERR(ns)) { + ret =3D PTR_ERR(ns); + goto err_put; + } + + if (ns->time_ns !=3D ns->time_ns_for_children) { + get_time_ns(ns->time_ns_for_children); + put_time_ns(ns->time_ns); + ns->time_ns =3D ns->time_ns_for_children; + } + c->ns =3D 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 calle= r's + * effective UID and GID as owner and initially empty ID mappings) and ded= icated + * empty mount, PID, UTS, IPC, network, cgroup, and time namespaces. Contr= ol + * operations authorize against capabilities in the userland's owning user + * namespace. + * + * Return: Userland file descriptor on success, negative error code on fai= lure. + */ +SYSCALL_DEFINE1(userland_open, unsigned int, flags) +{ + struct userland *c; + int fd; + + if (flags & ~USERLAND_ALL_FLAGS) + return -EINVAL; + + c =3D userland_create(flags); + if (IS_ERR(c)) + return PTR_ERR(c); + + fd =3D 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; +} --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376212; b=IUFmoby1ny62tSWX4FtpXbk0Vrir+nIYGsVypAJ/Zvka5mXqriNwTksJP9BNj5uM73/m AeTTdrAtX0gLCC5VprPBND8xIQwWXhqc7AW2hNFseoiv6H9bCP71LDV3pFJNrZW+qDJZY wrZ9NTfwCpvNRQcZ5QwCeamYbKlfpoxiLq7qR+i0huWYzu45mXnrnfY8Ql+tfpT7QzEFi VNsOfQ1WNPyZUn/uMxi9RR1iOU/3E51NcVLKZRg41m9HASD54LCTw1mmYFweFadM/L719 /TAOw87r19UgwXFdB0SxX2p5eNjzF1PRb17xDSsaQIssIzqnkVMaLwYK/fwGlxrzwjQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376212; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=QgUTYSoeBbicoM/Ctv8wuw6txQmYFirn0xuo3QUM9bE=; b=GEXCoSzFyjdjKJfPpitb6QYx//nh2cTG5pslTcce+8Zh0S2WJoYxSsGc7ZkfE2oGYQku jr8nMNh0V8mZeHp/6Y4UXhY7ttQCqNKdP4S65TeA8h7mPlbbmJXO33mXUKoGowgGEr3c1 5fVu+JDc1+Tw4aV1h4CJTwl5wianwW3PpSOeMIAFPaNrxHaSqgRsemyzN2j5DC0VBDqrw w+5VOoUKF2zso0AyQqgrwqxJ/7UWX10yPnkrvaBUQnUasiS3g17y/5kdNVB8m2jZPz6Hr PRVbIhJlNd9vJhU45SyeOiWH9YkdCSPTQrivznMd1aKN1HVeTQwG07KCJXmX76HLFvQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=h++5CFR1; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id BC3B9606A690; Sun, 22 Nov 2026 19:36:52 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=h++5CFR1 Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 96DEE1F000E6; Sun, 22 Nov 2026 19:36:51 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376212; bh=QgUTYSoeBbicoM/Ctv8wuw6txQmYFirn0xuo3QUM9bE=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=h++5CFR1P60aN6bCiiNMePpNEGsSZ4HlKZo8lWB6f4wdhTNz6/tSkMTg8xEpHbRxI GlwySIf772FfNejL8QOE7DS9Aizp0uVQ7OkmwxoH40uYofSQqCzfMJ58pVkImG6RIZ K4AMH4F5lVhyQeJnnZn7QVG98lo9L40YECd9yjtIprIs1WGapBRgEZTAUwpA1D/vse 9AnVSn/pA6MDVVk9wdaaUy3HQ3N4ZDFectxotNoTvOE88ZsWBmeAVyX1TQJ6xY8ovy Svslni2eYDTNSN8Tttx+qsHPiF94D8NrmsIIFhHGYdKRWN+DSQF0ejgfAakQavvOKS d7uWpKN6e7POQ== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 13/26] userland: Add USERLAND_GET_NSFD ioctl Date: Sun, 22 Nov 2026 21:35:26 +0200 Message-ID: <20261122193539.3334213-14-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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); =20 /* 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); =20 #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 =20 +#include + /** * enum userland_flags - Flags for userland_open() * @USERLAND_KILL_ON_CLOSE: Send %SIGKILL to userland init on final fd rel= ease. @@ -22,4 +24,21 @@ enum userland_flags { USERLAND_ALL_FLAGS =3D 0x00000003, }; =20 +#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 #include #include +#include +#include #include #include #include @@ -31,6 +33,8 @@ #include #include #include +#include +#include #include #include =20 @@ -63,6 +67,76 @@ static __poll_t userland_poll(struct file *file, poll_ta= ble *wait) return mask; } =20 +static long userland_get_nsfd(struct userland *userland, unsigned long nst= ype) +{ + struct ns_common *ns =3D NULL; + + if (nstype > UINT_MAX) + return -EINVAL; + if (!ns_capable(userland->user_ns, CAP_SYS_ADMIN)) + return -EPERM; + + if (nstype =3D=3D CLONE_NEWPID) { + if (!pidns_is_ancestor(userland->ns->pid_ns_for_children, + task_active_pid_ns(current))) + return -EXDEV; + if (READ_ONCE(userland->state) !=3D USERLAND_RUNNING) + return -ESRCH; + } + + scoped_guard(spinlock, &userland->lock) { + switch (nstype) { + case CLONE_NEWNS: + ns =3D from_mnt_ns(userland->ns->mnt_ns); + break; + case CLONE_NEWCGROUP: + ns =3D to_ns_common(userland->ns->cgroup_ns); + break; + case CLONE_NEWUTS: + ns =3D to_ns_common(userland->ns->uts_ns); + break; + case CLONE_NEWIPC: + ns =3D to_ns_common(userland->ns->ipc_ns); + break; + case CLONE_NEWUSER: + ns =3D to_ns_common(userland->user_ns); + break; + case CLONE_NEWPID: + ns =3D to_ns_common(userland->ns->pid_ns_for_children); + break; + case CLONE_NEWNET: + ns =3D to_ns_common(userland->ns->net_ns); + break; + case CLONE_NEWTIME: +#ifdef CONFIG_TIME_NS + ns =3D 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 l= ong arg) +{ + struct userland *userland =3D 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 =3D file->private_data; @@ -85,6 +159,8 @@ static int userland_release(struct inode *inode, struct = file *file) =20 static const struct file_operations userland_fops =3D { .poll =3D userland_poll, + .unlocked_ioctl =3D userland_ioctl, + .compat_ioctl =3D userland_ioctl, .release =3D userland_release, }; =20 --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376216; b=39yfll7evyfxc3YPkXVEJziW0QAlsf2+vF7x0GeINOeSr+SF0kLiNhrsVU4icXye29yv FPXPcQdW+aGAjNhe+larNzf3JRwDiPEdGTGwU0xH6ijmtAv0Y93LH95S6w2QbzabNBSm3 ledpipdFURWN1tOxB1kOwV4ZNPheZJtTSwDVOTso35vfi5adYCk2PdNqVbI1VFeQ5Xw0l PRBjnNn7bicTSI2Lw7SQpWOjlCzLkirH4egSwZO8a5U9xAZy6bh6XtQYwruEV4rI5/wu5 lC6dO/Se341hIuEcW+t5ojOS5kJcgV0NcSmw5vntD5Tse21Ca22e8XJOEp+vY6S+ulw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376216; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=M3T9ruqYmyUMm2PturUvOibjyAbGjGhILSaT845gaFc=; b=QhjLdOACkCzlojV1Cv/1Eqbs8z2yezPoS08jGLf1L7xl1kbfjDORZYosdufkJZDaleWt fJIBwJ7DEVei1wPZTFrjO4etpmEtwA+K9Jxn83R6nCrdJGAsNwMEpgTVSf5oyc8CnOyPy qgYZu/GySD8pvfugCfnAwwWxStHwU8gLVGxNaYpTXmo7Z2QZJDCBFZB1mwK3LYNvDs1gt wd1C6GmN3h46YjeACPbbclibzYNmzNY3qhcNgTjDPoaITZZac5g1FN8NjSyfsdIEoZxHX e55G9chqHwcLP6yG8UiM2DH9X/oURFsHLmT8D3Hgts6HqcdPZ0MAoDqBZRfRRajXJAg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=hLXGB7rR; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id C979D606A31E; Sun, 22 Nov 2026 19:36:56 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=hLXGB7rR Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id C66B41F000D3; Sun, 22 Nov 2026 19:36:55 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376216; bh=M3T9ruqYmyUMm2PturUvOibjyAbGjGhILSaT845gaFc=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=hLXGB7rRUoPcsnXokx7eTA9UTxhJink/6OLXJGpNkEFY2vQ5ps/e+pGglAWeRcaZy D69TpTHUFZDEOPfMLaTzDAccup185NJA00nIa8btD/j/K/zihji2qj/Vqjt2BQKDi9 FYCn+JcNcPp3veWxbC/LRh3llVICiuCsHqaWjqx19tfPo+rGSqglic/fcJ9MQdqKCF FF4p0vGPssWSmi+bP5G6CU0qfVbppBr8xd1T9UblfWxxS24gRoKkiK1tirJ+HWETmh 8sF7LOOQkYd4jwAWNIzSKz7TKlJ+RbYJWtKR2bRLtgyX8zh3eaEwpQx5q0u0aHO/vr FiH7u4+X8bHMw== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 14/26] userland: Add USERLAND_SHARE_NSFD ioctl Date: Sun, 22 Nov 2026 21:35:27 +0200 Message-ID: <20261122193539.3334213-15-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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) =20 +/** + * DOC: USERLAND_SHARE_NSFD + * + * ``ioctl(userland_fd, USERLAND_SHARE_NSFD, ns_fd)`` replaces the corresp= onding + * member namespace of ``userland_fd`` with ``ns_fd`` (``CLONE_NEWCGROUP``, + * ``CLONE_NEWIPC``, ``CLONE_NEWUTS``, ``CLONE_NEWNET``, or ``CLONE_NEWTIM= E``) + * 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 #include #include +#include +#include #include #include #include @@ -125,6 +127,92 @@ static long userland_get_nsfd(struct userland *userlan= d, unsigned long nstype) return open_namespace(ns); } =20 +static long userland_share_nsfd(struct userland *c, unsigned long arg) +{ + struct ns_common *old_time_children =3D NULL; + struct ns_common *old_ns =3D 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 =3D 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 !=3D USERLAND_INIT) + return -EBUSY; + + __ns_ref_inc(ns); + __ns_ref_active_get(ns); + + switch (ns->ns_type) { + case CLONE_NEWCGROUP: + old_ns =3D to_ns_common(c->ns->cgroup_ns); + c->ns->cgroup_ns =3D to_cg_ns(ns); + break; + case CLONE_NEWIPC: + old_ns =3D to_ns_common(c->ns->ipc_ns); + c->ns->ipc_ns =3D to_ipc_ns(ns); + break; + case CLONE_NEWUTS: + old_ns =3D to_ns_common(c->ns->uts_ns); + c->ns->uts_ns =3D to_uts_ns(ns); + break; + case CLONE_NEWNET: + old_ns =3D to_ns_common(c->ns->net_ns); + c->ns->net_ns =3D to_net_ns(ns); + break; +#ifdef CONFIG_TIME_NS + case CLONE_NEWTIME: + __ns_ref_inc(ns); + __ns_ref_active_get(ns); + old_ns =3D to_ns_common(c->ns->time_ns); + old_time_children =3D + to_ns_common(c->ns->time_ns_for_children); + c->ns->time_ns =3D to_time_ns(ns); + c->ns->time_ns_for_children =3D 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 l= ong arg) { struct userland *userland =3D 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; } --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376221; b=JSf1EtqC1e0eVe7Rw3wB++6gR/brTlCacyb587X1CYF+lsHXZ98UxPdKxqVT7PA0skJa /d7y2k9UEECSHaBQZSTd9yGR9JR2OMrt3BXBQGWGHvMQNAAe0mmMKT4tFJVTloBC1Po2T +H4yHKIbB8R6TpcW4odNdWohf69CqYX15pVsTTu64kpNEW+PH0DohbTOqI+T976e+YgGo W/PRpKEnjR9u3UFwTZ+gum+MTaUUNxylo6Kwf5EmSzfifKthZ5E1DK24cMYsL/jLQIfFn La4GuFVVVUsC1yu7RgFaXNHOrkn6zyZitvNWLr/xd5tMCQeCP2K3VY5IRsd44n7D2+Q== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376221; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=XwK0kBI5FPDe2Km5ydmIo1Yx+Gsu/7X07W9R+yp2Gk4=; b=Il3g8V65l3DEhUgckY3b+m/pul35xzFKiIuNEG5DnO/fAkpW71fkKux+i5No3J81+B26 74KqM9SQGBnthvu7rgp9MqYJ09s+4DYxkqIQ65mHFLhJIvFtFkTbfCMM3V720pYkuMOrX zhy33gC+75gPAVnFJEpv2Fx+i+E2tbI/h3YiuoE79KzfOf4i4MEkM3xAFCIYkHzVrtQKi dzVXDgjqrFzS5V6Bdv1IaIoCKDnp80wqTgbUAYkURnhix7yLsZIZ44Yy5Ik6UIu7kJ0Gk 7y1SOhOkAEcYTc4buC2RXGLPWvKDYS++c1AZ0pCmSmvOCNnVQoNVtmr43ndHpkdEpCQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=gF2J+16U; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id 8F21D606A684; Sun, 22 Nov 2026 19:37:01 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=gF2J+16U Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 6000C1F000EE; Sun, 22 Nov 2026 19:37:00 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376221; bh=XwK0kBI5FPDe2Km5ydmIo1Yx+Gsu/7X07W9R+yp2Gk4=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=gF2J+16USDEJ/HoS3CxmYfyZ3+XohOPn6KBqcnalnjfeoKgwCJ0mdeSq4XUpsqVQv JHJwDi2vYYOZYXQ5K35Vg+mX/dPk8YwKeYtIHxhHJuVr23qNc45t5yuSN/jf8R98j7 Uv3upEuEiMrvoHiXxYP0BeSk2uk3iKHBclKHFP6mXU74k7521tf1lt9AogXlnGnRmz +U+krMJNlW4DxTf2DQq/R3PR6NLvMwealjlxKekHwWMIr7Wew4cPJEPxHYUgEZSsAH 29wXcNeZl25oN/k1s/8woNjUV4AyajyX/1wY5j7GaaYiEwrZGSxzwE29Oj634xjyak thRb7amQqFHBw== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 15/26] exit: Support P_USERLAND in waitid() Date: Sun, 22 Nov 2026 21:35:28 +0200 Message-ID: <20261122193539.3334213-16-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 Signed-off-by: David Howells Signed-off-by: Jarkko Sakkinen --- 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; =20 /** * 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 *p= id_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 */ =20 #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 =20 =20 #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 #include #include +#include =20 #include =20 @@ -1803,6 +1804,9 @@ static long kernel_waitid(int which, pid_t upid, stru= ct waitid_info *infop, struct wait_opts wo; long ret; =20 + if (which =3D=3D P_USERLAND) + return userland_waitid(upid, infop, options, ru); + ret =3D 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 #include #include +#include #include #include #include @@ -40,6 +41,8 @@ #include #include =20 +#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, un= signed long arg) return 0; } =20 +/** + * DOC: P_USERLAND + * + * ``waitid(P_USERLAND, userland_fd, infop, options, NULL)`` waits freezab= ly until + * ``userland_fd`` reaches ``USERLAND_DEAD`` (unless ``WNOHANG`` or ``O_NO= NBLOCK`` is + * set) and writes init's exit information into ``infop`` without consumin= g 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 =3D READ_ONCE(fd_file(f)->f_flags); + nonblock =3D (options & WNOHANG) || (f_flags & O_NONBLOCK); + userland =3D fd_file(f)->private_data; + pid_ns =3D 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 =3D userland->state; + if (state =3D=3D USERLAND_INIT) + return -ECHILD; + if (state =3D=3D USERLAND_DEAD) { + ret =3D pid_nr_ns(userland->init_pid, pid_ns); + if (ret <=3D 0) + return -ECHILD; + status =3D userland->exit_code; + uid =3D userland->init_uid; + } + } + if (state =3D=3D USERLAND_DEAD) + break; + if (nonblock) + return (options & WNOHANG) ? 0 : -EAGAIN; + + ret =3D wait_event_freezable(userland->waitq, + READ_ONCE(userland->state) =3D=3D + USERLAND_DEAD || + READ_ONCE(userland->state) =3D=3D + USERLAND_INIT); + if (ret) + return ret; + } + + if ((status & 0x7f) =3D=3D 0) { + infop->cause =3D CLD_EXITED; + infop->status =3D status >> 8; + } else { + infop->cause =3D (status & 0x80) ? CLD_DUMPED : CLD_KILLED; + infop->status =3D status & 0x7f; + } + infop->pid =3D ret; + infop->uid =3D from_kuid_munged(current_user_ns(), uid); + return ret; +} + static long userland_ioctl(struct file *file, unsigned int cmd, unsigned l= ong arg) { struct userland *userland =3D file->private_data; --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376225; b=ke3/25PRNRG7b9KDfHdudwdWsGWnr51R4bXbSb0lNLSsYUhu5IqSGlRh/e2uS5w+TYX6 YwgQf3uvgP6ijtLmYuRXHzAjTUDelCnZHbrCf4ZkUq6dpAubYtYN9YVmbLvYWIQq9q/n9 q4Alv8T8vtmWT41arG1VWc085M4sklDJTvtCpICGHPrN1xgxqtvdsnbzZ+R/HhhH1i4K4 GTPFack3FdFSuGognzWrDJYp6PNmH5y6OVN/0FZ7eABQWZ81dcGmb/N/JMwjEMF7oxwpY gZH+egptmNnEI2fwbDUxP3/jDbiuS3HQjgEy26ILoj0FloSbGahZjIlNiHiYbT9PeoQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376225; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=aVGgI7D53IZyEOdiIQgJZT0cYrc34vgpwt54f5ogQLw=; b=onzSBtNyrh+fZmFSYClCNd0GaFNlopQLIYH4KCR3dASre+D2KhLNgzv7yrgqsV/vjLFu SrGrE9fKRVp1r3vhXML/G2G5L1TvU9qsbf1cfarJhykr5iuO3mG8E8HRmBz/LcoNt9Flb MuISUCNh7gOVXQme2DdKyydqocKHlPurkOSFmQLWI0OmiDkSXdInsuUtmxF2Gx7HrIpKO P0nCV9vyHQEWJ6GVK1yJC0peUhTkXYFi3q5Q4o+4h+MLtzfEgeMEtVcTC7q8mnDdo9bAr KRR8n9Sqxdt12Reh6ZPWWFeXooZkCnffw+XfsGJLN0lysuxnEnJsqtdHXOFXA1eo3dg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=TxeiH5mi; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id CD76A606A31D; Sun, 22 Nov 2026 19:37:05 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=TxeiH5mi Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id A5F861F000E0; Sun, 22 Nov 2026 19:37:04 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376225; bh=aVGgI7D53IZyEOdiIQgJZT0cYrc34vgpwt54f5ogQLw=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=TxeiH5migMxtxLZVPutyjQ6/J7QKqoSFH/e1HcOJIJSoDF1AA8CxhtTITwMigbaeb I9yS9g21CpCn5IIvX186gax7JrXaTQBSO3ytBizEP9b1mmNiOvd6LF7PXsEu+Pc1b8 HUjIkMPk0nbBRdDYSnLBo07GsUKETFbxFuQLsLkf9MvtM04bWUSk8OXqQVBjxoBPds ncy7NCV3vxBxbV21mOz7yth9bNwCBbMdoXiISOaGDkM/Dj+IxpDGfzNucXbWlBzCHT jJAjknZhWjnuCc2ZXFoM2hJr9/b8Jpm0XKBGdFCBO9W5/nM4ALcdEReyW3sCbliMy6 L0ZYYKufVT4QA== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 16/26] signal: Support userland fds in pidfd_send_signal() Date: Sun, 22 Nov 2026 21:35:29 +0200 Message-ID: <20261122193539.3334213-17-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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 *p= id, 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 wa= itid_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 */ =20 #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 #include #include +#include #include #include #include @@ -4181,6 +4182,9 @@ SYSCALL_DEFINE4(pidfd_send_signal, int, pidfd, int, s= ig, if (fd_empty(f)) return -EBADF; =20 + if (userland_is_file(fd_file(f))) + return userland_send_signal(fd_file(f), sig, info, flags); + /* Is this a pidfd? */ pid =3D 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 *inf= op, int options, return ret; } =20 +/** + * 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``, a= nd 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 =3D file->private_data; + struct pid_namespace *pid_ns =3D userland->ns->pid_ns_for_children; + bool any_success =3D false; + bool any_other =3D false; + bool any_perm =3D false; + int other_err =3D 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) !=3D USERLAND_RUNNING) + return -ESRCH; + + scoped_guard(rcu) { + read_lock(&tasklist_lock); + idr_for_each_entry(&pid_ns->idr, pid, nr) { + struct task_struct *task =3D pid_task(pid, PIDTYPE_TGID); + int err; + + if (!task) + continue; + + err =3D group_send_sig_info(sig, SEND_SIG_NOINFO, task, + PIDTYPE_MAX); + if (!err) { + any_success =3D true; + } else if (err =3D=3D -EPERM) { + any_perm =3D true; + } else if (err !=3D -ESRCH && !any_other) { + any_other =3D true; + other_err =3D 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 l= ong arg) { struct userland *userland =3D file->private_data; --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376229; b=uNeGMhi3sfKgVpgSQOtEYH/bHGJIaz8woboDt327Ctt3mMXVeddxSzezoDonIxautgBS xqJP8E7cm5LOvJ201USPgs1pYGVM6aBxIkjgKpdFCtiyKMxe6nAfJ3WOcS25GqJZKuAcn p4VxFKF10+gc3iMBi/kLo+BQ/Gmlqa/2pw+V0rRHpP0BvQo1AQFuuMF/cqJVyU0lZtzko m8DQ0QTD26BYT6yPVlZ4syKcDnp64BHibr6CwYuaWFnsBeHbj8tb8YO3Fskj6W2UvCVxg ZNaKhgMfTdvZZqWczYQ8nH1EIhH1bX94P9uZozxnWMQ0SM0AzpkiJZ/LHzao9yWhFEA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376229; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=WbpDZaHnnjHuv0gV/3ertHEHpnm2j+Wl1rDtPX9sAVE=; b=RRjeB61CC/y26o8bU3HgezfoTbLiY5xoGjzCj7cF/BuPf2VBEXqmhqzPDPb+k6TFHG9K gOAUUyyIoAdq3HzRCqDY+jVOMcz/n6LyBeUvfew/yzckMgLVYhvYJ1QeNYeXVnKjHd+b/ EErdi13SUuvVKqLVFlswTyTCdaFY6deWj5M+yunXJBOXpZ0rcLfXQGykMx7vB5YLbTaPO EzOWksoxrfHCVbiEe6RcXt0DGfAkuMmeRgZ22BMQt3GXfcOkcJ+apyK6O3jUcP8JlbIMe sBFMM6RgXlgYeoq1CzO541GP+WGS9xusPugkygJYqAe1ThVSQHBsYZOz6szntqG2ZMw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=WqYJWrMV; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id CAA8160A262F; Sun, 22 Nov 2026 19:37:09 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=WqYJWrMV Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id C9A461F000E1; Sun, 22 Nov 2026 19:37:08 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376229; bh=WbpDZaHnnjHuv0gV/3ertHEHpnm2j+Wl1rDtPX9sAVE=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=WqYJWrMVyfrrFpHYDBIeYbZTdkThiLeA0h7xG6SorN1P38Pb/Vo5Nm2CC0UQ/+jYt juNebkrwS3APCUe0n9MntHRtNGbt8BTkyOp62dBAoNcCBJphyTEIrBtBSU0WxHxC2x w6Su1GLrqSMhHXiBrRQhk1lPlC406bGjnNR8Dhe9pxAMdwdySto3SbNqtXlIGZYazB uMIaYgPHC5yx/iw1U5fuHJoOqjcUnBHQQPE40trffiGzDb5/a0D1CVMHPV/oCgBPZZ /Kr1aM1M/5UfhyUgni55gJgOvY0yK6icr25E7+pu2VSBHuINay5oqoCPMofHi/uDuV NS/qdUT6d/0dA== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 17/26] fork: Support CLONE_INTO_USERLAND in clone3() Date: Sun, 22 Nov 2026 21:35:30 +0200 Message-ID: <20261122193539.3334213-18-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 Signed-off-by: David Howells Signed-off-by: Jarkko Sakkinen --- 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 @@ =20 struct cred; struct inode; +struct userland; =20 extern struct task_struct init_task; =20 @@ -152,7 +153,8 @@ struct cred { =20 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; =20 /* @@ -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; =20 /* 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; }; =20 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 =20 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 *fi= le, 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 */ =20 #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 c= loses. */ #define CLONE_EMPTY_MNTNS (1ULL << 37) /* Create an empty mount namespace.= */ +#define CLONE_INTO_USERLAND (1ULL << 38) /* Clone into a userland. */ =20 /* * cloning flags intersect with CSIGNAL so can be used with unshare and cl= one3 @@ -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 =20 #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 */ =20 /* * 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 #include #include +#include #include #include #include +#include #include #include #include #include +#include =20 #if 0 #define kdebug(FMT, ...) \ @@ -251,6 +254,9 @@ struct cred *prepare_exec_creds(void) return new; } =20 +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; =20 + if (userland) { + const struct cred *old =3D current_cred(); + + if (new->user_ns !=3D userland->user_ns) { + ret =3D install_user_ns_cred(new, userland->user_ns); + if (ret < 0) + goto error_put; + } + if (!cred_cap_issubset(old, new) || + old->user_ns !=3D new->user_ns) { + struct task_exec_state *exec_state; + + exec_state =3D rcu_dereference_protected(p->exec_state, true); + if (exec_state !=3D &init_task_exec_state) + WRITE_ONCE(exec_state->dumpable, suid_dumpable); + } + } + if (clone_flags & CLONE_NEWUSER) { ret =3D 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 #include #include +#include #include #include #include @@ -1616,7 +1617,7 @@ static int copy_exec_state(u64 clone_flags, struct ta= sk_struct *tsk) struct task_exec_state *exec_state; =20 /* CLONE_VM siblings refcount-share the parent's exec_state. */ - if (clone_flags & CLONE_VM) { + if ((clone_flags & (CLONE_VM | CLONE_INTO_USERLAND)) =3D=3D CLONE_VM) { exec_state =3D 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 { }; =20 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; =20 @@ -1649,7 +1650,7 @@ static int copy_fs(u64 clone_flags, struct task_struc= t *tsk, if (current->nsproxy->mnt_ns !=3D &init_mnt_ns) return -EINVAL; fs =3D userspace_init_fs; - } else if (flags & COPY_FS_IDLE) { + } else if (flags & COPY_FS_IDLE || userland) { fs =3D &init_fs; } else { fs =3D current->fs; @@ -1671,6 +1672,21 @@ static int copy_fs(u64 clone_flags, struct task_stru= ct *tsk, tsk->real_fs =3D tsk->fs =3D copy_fs_struct(fs); if (!tsk->fs) return -ENOMEM; + if (userland) { + struct path root __free(path_put) =3D {}; + int err; + + err =3D mnt_ns_get_root(userland->ns->mnt_ns, &root); + if (err) { + free_fs_struct(tsk->fs); + tsk->real_fs =3D NULL; + tsk->fs =3D NULL; + return err; + } + tsk->fs->umask =3D READ_ONCE(current->fs->umask); + set_fs_root(tsk->fs, &root); + set_fs_pwd(tsk->fs, &root); + } return 0; } =20 @@ -2186,7 +2202,7 @@ __latent_entropy struct task_struct *copy_process( #ifdef CONFIG_PROVE_LOCKING DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled); #endif - retval =3D copy_creds(p, clone_flags); + retval =3D copy_creds(p, clone_flags, args->userland); if (retval < 0) goto bad_fork_free; =20 @@ -2317,7 +2333,7 @@ __latent_entropy struct task_struct *copy_process( goto bad_fork_cleanup_semundo; retval =3D 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 =3D copy_sighand(clone_flags, p); @@ -2329,7 +2345,7 @@ __latent_entropy struct task_struct *copy_process( retval =3D copy_mm(clone_flags, p); if (retval) goto bad_fork_cleanup_signal; - retval =3D copy_namespaces(clone_flags, p); + retval =3D copy_namespaces(clone_flags, p, args->userland); if (retval) goto bad_fork_cleanup_mm; retval =3D copy_io(clone_flags, p); @@ -2510,6 +2526,11 @@ __latent_entropy struct task_struct *copy_process( goto bad_fork_core_free; } =20 + if (unlikely(args->userland_bootstrapping && !is_child_reaper(pid))) { + retval =3D -EBUSY; + goto bad_fork_core_free; + } + /* Let kill terminate clone/fork in the middle */ if (fatal_signal_pending(current)) { retval =3D -EINTR; @@ -2586,7 +2607,7 @@ __latent_entropy struct task_struct *copy_process( write_unlock_irq(&tasklist_lock); =20 if (likely(p->pid) && thread_group_leader(p)) - userland_copy(p, pid, NULL); + userland_copy(p, pid, args->userland); =20 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; =20 + if (unlikely(clone_flags & CLONE_INTO_USERLAND)) { + int err =3D 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 =3D copy_process(NULL, trace, NUMA_NO_NODE, args); add_latent_entropy(); =20 + if (unlikely(clone_flags & CLONE_INTO_USERLAND)) { + int err =3D userland_finish_fork(args, p); + + if (err) + return err; + } + if (IS_ERR(p)) return PTR_ERR(p); =20 @@ -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) !=3D CLONE_ARGS_SIZE_VER2); - BUILD_BUG_ON(sizeof(struct clone_args) !=3D CLONE_ARGS_SIZE_VER2); + BUILD_BUG_ON(offsetofend(struct clone_args, userland) !=3D + CLONE_ARGS_SIZE_VER3); + BUILD_BUG_ON(sizeof(struct clone_args) !=3D CLONE_ARGS_SIZE_VER3); =20 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; =20 + if ((args.flags & CLONE_INTO_USERLAND) && + (args.userland > INT_MAX || usize < CLONE_ARGS_SIZE_VER3)) + return -EINVAL; + *kargs =3D (struct kernel_clone_args){ .flags =3D args.flags, .pidfd =3D u64_to_user_ptr(args.pidfd), @@ -3000,6 +3041,7 @@ static noinline int copy_clone_args_from_user(struct = kernel_clone_args *kargs, .tls =3D args.tls, .set_tid_size =3D args.set_tid_size, .cgroup =3D args.cgroup, + .userland_fd =3D args.userland, }; =20 if (args.set_tid && @@ -3040,13 +3082,19 @@ static inline bool clone3_stack_valid(struct kernel= _clone_args *kargs) return true; } =20 +#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; =20 /* @@ -3064,6 +3112,10 @@ static bool clone3_args_valid(struct kernel_clone_ar= gs *kargs) kargs->exit_signal) return false; =20 + if ((kargs->flags & CLONE_INTO_USERLAND) && + (kargs->flags & ~CLONE_INTO_USERLAND_FLAGS)) + return false; + if (!clone3_stack_valid(kargs)) return false; =20 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 #include #include +#include #include #include #include @@ -166,12 +167,18 @@ struct nsproxy *create_new_namespaces(u64 flags, stru= ct 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 =3D tsk->nsproxy; struct user_namespace *user_ns =3D task_cred_xxx(tsk, user_ns); struct nsproxy *new_ns; =20 + if (userland) { + get_nsproxy(userland->ns); + tsk->nsproxy =3D userland->ns; + return 0; + } if (likely(!(flags & (CLONE_NS_ALL & ~CLONE_NEWUSER)))) { if ((flags & CLONE_VM) || likely(old_ns->time_ns_for_children =3D=3D 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 #include #include +#include #include #include #include @@ -551,3 +552,141 @@ SYSCALL_DEFINE1(userland_open, unsigned int, flags) =20 return fd; } + +/** + * DOC: CLONE_INTO_USERLAND + * + * Passing ``CLONE_INTO_USERLAND`` in ``struct clone_args.flags`` (with + * ``size >=3D 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 ker= nel + * UID, GID, and supplementary groups as mapped there. + */ +static bool userland_pidns_alive(struct pid_namespace *pid_ns) +{ + for (; pid_ns !=3D &init_pid_ns; pid_ns =3D 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) =3D fget(args->userland_fd); + struct path root __free(path_put) =3D {}; + struct pid_namespace *pid_ns; + bool bootstrapping =3D false; + struct userland *userland; + int ret; + + if (!file) + return -EBADF; + if (!userland_is_file(file)) + return -EINVAL; + + userland =3D 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 =3D userland->ns->pid_ns_for_children; + if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current))) + return -EXDEV; + + ret =3D mnt_ns_get_root(userland->ns->mnt_ns, &root); + if (ret) + return ret; + + for (;;) { + bool wait =3D 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 =3D true; + break; + case USERLAND_FORKING: + wait =3D true; + break; + case USERLAND_RUNNING: + if (!userland_pidns_alive(pid_ns)) + return -ESRCH; + break; + case USERLAND_DEAD: + return -ESRCH; + } + } + if (!wait) + break; + + ret =3D wait_event_killable(userland->waitq, + READ_ONCE(userland->state) !=3D + USERLAND_FORKING); + if (ret) + return ret; + } + + args->userland_file =3D no_free_ptr(file); + args->userland =3D userland; + args->userland_bootstrapping =3D bootstrapping; + return 0; +} + +int userland_finish_fork(struct kernel_clone_args *args, + struct task_struct *p) +{ + struct file *file __free(fput) =3D args->userland_file; + struct userland *userland =3D args->userland; + struct pid_namespace *pid_ns =3D userland->ns->pid_ns_for_children; + int ret; + + args->userland_file =3D NULL; + args->userland =3D NULL; + if (!IS_ERR(p)) { + if (args->userland_bootstrapping) + wake_up_all(&userland->waitq); + if (current->nsproxy->time_ns !=3D userland->ns->time_ns) + timens_commit(p, userland->ns->time_ns); + return 0; + } + + ret =3D PTR_ERR(p); + if (args->userland_bootstrapping) { + scoped_guard(spinlock, &userland->lock) { + if (userland->state =3D=3D USERLAND_FORKING) + WRITE_ONCE(userland->state, USERLAND_INIT); + } + wake_up_all(&userland->waitq); + if (ret =3D=3D -EINVAL && !args->set_tid_size && + (READ_ONCE(pid_ns->child_reaper) || + (READ_ONCE(pid_ns->pid_allocated) & ~PIDNS_ADDING))) + ret =3D -EBUSY; + } + if ((ret =3D=3D -ENOMEM || ret =3D=3D -EBUSY) && + !userland_pidns_alive(pid_ns)) + return -ESRCH; + + return ret; +} --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376233; b=VLp7k7LC9HfbsMyKOPzTMnkt5SFhRXqUjkzC+7tpfUpewQF5uapSVQvVXKya7Vn6aKIe biTiiWbUb5tj6FeWvBECjlVvHCz0a2mesQ9bJpXWKe6VWGdbO/ycUOdXzDovHgDSGIqrO sYWW2s9WcmGnRZFGthtxi/fi1de9P+60C5+igHgmHnvYbSGvjsc0YnNdAs1U9TCRJFL1C 0RwLb/jsxjGUlE/PS2zTPVuq75eEHseqT2qhIT9AkNGYj6iTySIyqCuLD981tUj/Dlm6f hMtksKom3DBxTiYwT+9IJKzCWEhe5JpnlfW/MFHjT1fG3PZplGyG56PfKPwqaUKJ/dg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376233; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=khxvpcGeTbqQJJSuGbnlbIcol0rjjybMBYSoawPmV50=; b=N9ntUEPrVGEaiR3Pa72nHOW2FO1GjIyb7kLYKuymkIHnQwWLC4R9YzqJJNRqxh7DPI/I NnSwzwVM5SFTI6s9QPXbU8MhzIpH6hh+4Ll4xrJsSGwuyz8Tub48U5R65nKO6eqVXFf+g YNYT4yqeq0m8BxqQyNaj7Uakj3KHagwa9wUH7dzzmwnyYjoUPCdXvgtGi+TxvBFpqemFJ 5pImakzHH9HP+S0URiu18y9jquylpR1tBON1HfmvwDsfWDZVthHcT/iElFvSmnnEKA9fM YOSAzY9CR+RsO7kGW5cXsTZDHXxmHkoan3KDcGpvOisF4342flaF8kGFilR+/Rgeb5w== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=HQQjMQcH; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id B87C5606A333; Sun, 22 Nov 2026 19:37:13 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=HQQjMQcH Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id A59BA1F000ED; Sun, 22 Nov 2026 19:37:12 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376233; bh=khxvpcGeTbqQJJSuGbnlbIcol0rjjybMBYSoawPmV50=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=HQQjMQcHancZxRSEXTnnNfnmTv7tzCkRXR8gIRGuI6Kc1UeH+LaHw4TYQ003/ayOU gDqP6tUK/r+t1pBzNsi1MyGF8MUCz2vYR8XvkldC8IJmfod6XSWPp8hEVUDYWDCcbL mH4yheFxBNmBFok98NZeorlOW9Mj1DWCEk5c6KKXkVCpPQBIcUwZkJkMwYQVZHu63w wYY1klB0TTGXd6wN8TZ6YId+Ca0GtXKxzxdMI8tN6PEQgaw82keC4o9Col5QNmEi4j eoDB7f8gDENj95Pb8o/SB+pF6BLcwQQUmKWHcCvXcGAQekK97LLL91HwXFzy1J++SG kMHn0ByvVy4gg== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 18/26] fs: Support FSCONFIG_SET_USERLAND in fsconfig() Date: Sun, 22 Nov 2026 21:35:31 +0200 Message-ID: <20261122193539.3334213-19-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 Signed-off-by: David Howells Signed-off-by: Jarkko Sakkinen --- 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/filesy= stems/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; ... }; =20 @@ -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 pare= nt - mount superblock on an automount. + mount superblock on an automount, or to the target userland's + namespaces when bound via FSCONFIG_SET_USERLAND. =20 * :: =20 @@ -186,6 +188,15 @@ The fs_context fields are as follows: FS_CONTEXT_FOR_RECONFIGURE Change an existing mount =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D =20 + * :: + + bool userland_bound:1 + + Set when the filesystem context has been bound to a target userland v= ia + FSCONFIG_SET_USERLAND. Filesystems may inspect this flag (for exampl= e in + ->init_fs_context() or ->parse_param()) to distinguish userland-deleg= ated + 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(). =20 + * :: + + int (*set_userland)(struct fs_context *fc, + struct userland *userland); + + Called by FSCONFIG_SET_USERLAND after updating fc->user_ns, fc->net_n= s, + 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 curren= t 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->us= er_ns + on return or the bind fails with -EOPNOTSUPP. + + On success it should return 0. In the case of an error, it should re= turn + a negative error code and the context transitions to FS_CONTEXT_FAILE= D. + * :: =20 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 =3D NR_UNIX98_PTY_MAX; =20 if (fc->purpose =3D=3D FS_CONTEXT_FOR_MOUNT && + !fc->userland_bound && + fc->user_ns =3D=3D &init_user_ns && current->nsproxy->mnt_ns =3D=3D init_task.nsproxy->mnt_ns) fsi->mount_opts.reserve =3D true; =20 @@ -457,7 +459,7 @@ static struct file_system_type devpts_fs_type =3D { .init_fs_context =3D devpts_init_fs_context, .parameters =3D devpts_param_specs, .kill_sb =3D devpts_kill_sb, - .fs_flags =3D FS_USERNS_MOUNT, + .fs_flags =3D FS_USERNS_MOUNT | FS_USERLAND_MOUNT, }; =20 /* 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 #include #include +#include "internal.h" =20 /* * Read-mostly filesystem drivers list. @@ -390,6 +391,20 @@ static struct file_system_type *__get_fs_type(const ch= ar *name, int len) return fs; } =20 +struct file_system_type *get_fs_type_noload(const char *name) +{ + struct file_system_type *fs; + const char *dot =3D strchr(name, '.'); + int len =3D dot ? dot - name : strlen(name); + + fs =3D __get_fs_type(name, len); + if (dot && fs && !(fs->fs_flags & FS_HAS_SUBTYPE)) { + put_filesystem(fs); + fs =3D 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 =3D -ENOMEM; @@ -292,6 +294,9 @@ static struct fs_context *alloc_fs_context(struct file_= system_type *fs_type, break; } =20 + if (!init) + return fc; + ret =3D 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_s= ystem_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); =20 +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 de= ntry *dentry, return ERR_PTR(-EINVAL); =20 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); } =20 /** @@ -337,7 +349,8 @@ struct fs_context *fs_context_for_submount(struct file_= system_type *type, struct fs_context *fc; int ret; =20 - fc =3D alloc_fs_context(type, reference, 0, 0, FS_CONTEXT_FOR_SUBMOUNT); + fc =3D alloc_fs_context(type, reference, 0, 0, FS_CONTEXT_FOR_SUBMOUNT, + true); if (IS_ERR(fc)) return fc; =20 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 #include #include +#include +#include +#include +#include #include #include #include +#include #include "internal.h" #include "mount.h" =20 @@ -41,6 +46,92 @@ static inline const char *fetch_message_locked(struct fc= _log *log, size_t len, return p; } =20 +/** + * DOC: FSCONFIG_SET_USERLAND + * + * ``fsconfig(fsfd, FSCONFIG_SET_USERLAND, NULL, NULL, userland_fd)`` bind= s a newly + * opened ``FS_USERLAND_MOUNT`` or ``FS_USERNS_DELEGATABLE`` filesystem co= ntext + * to ``userland_fd`` once before parameters are supplied. Requires + * ``CAP_SYS_ADMIN`` in the userland's user namespace and binds the contex= t to the + * userland's user, network, PID (``proc``), and IPC (``mqueue``) namespac= es. + */ +static int fsconfig_set_userland(struct fs_context *fc, struct fs_paramete= r *param) +{ + struct user_namespace *user_ns; + struct net *net; + struct userland *c; + int ret; + + if (!userland_is_file(param->file)) + return -EINVAL; + + c =3D param->file->private_data; + user_ns =3D 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 =3D false; + fc->fs_private =3D NULL; + fc->s_fs_info =3D NULL; + fc->ops =3D NULL; + fc->sb_flags =3D 0; + fc->global =3D 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 =3D get_fs_type_noload(fc->log.prefix); + if (!orig) { + fc->phase =3D FS_CONTEXT_FAILED; + return -ENODEV; + } + put_filesystem(fc->fs_type); + fc->fs_type =3D orig; + } + + scoped_guard(spinlock, &c->lock) + net =3D get_net(c->ns->net_ns); + put_cred(fc->cred); + fc->cred =3D get_current_cred(); + put_net(fc->net_ns); + fc->net_ns =3D net; + put_user_ns(fc->user_ns); + fc->user_ns =3D get_user_ns(user_ns); + + fc->userland_bound =3D true; + fc->userland_mnt_id =3D c->ns->mnt_ns->ns.ns_id; + + ret =3D fc->fs_type->init_fs_context(fc); + if (ret < 0) { + fc->userland_bound =3D false; + fc->phase =3D FS_CONTEXT_FAILED; + return ret; + } + fc->need_free =3D true; + + if (fc->ops->set_userland) { + ret =3D fc->ops->set_userland(fc, c); + if (ret < 0) { + fc->userland_bound =3D false; + fc->phase =3D FS_CONTEXT_FAILED; + return ret; + } + } + if (fc->user_ns !=3D user_ns) { + fc->userland_bound =3D false; + fc->phase =3D FS_CONTEXT_FAILED; + return -EOPNOTSUPP; + } + fc->phase =3D FS_CONTEXT_CREATE_PARAMS; + return 0; +} + /* * Allow the user to read back any error, warning or informational message= s. * 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; =20 - if (!may_mount()) + priv =3D may_mount(); + if (!priv && !IS_ENABLED(CONFIG_USERLAND)) return -EPERM; =20 if (flags & ~FSOPEN_CLOEXEC) @@ -137,17 +230,23 @@ SYSCALL_DEFINE2(fsopen, const char __user *, _fs_name= , unsigned int, flags) =20 audit_log_fsopen(fs_name); =20 - fs_type =3D get_fs_type(fs_name); + fs_type =3D 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; + } =20 - fc =3D fs_context_for_mount(fs_type, 0); + fc =3D 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); =20 - fc->phase =3D FS_CONTEXT_CREATE_PARAMS; + fc->phase =3D priv ? FS_CONTEXT_CREATE_NS : FS_CONTEXT_AWAITING_NS; =20 ret =3D fscontext_alloc_log(fc); if (ret < 0) @@ -222,7 +321,8 @@ static int vfs_cmd_create(struct fs_context *fc, bool e= xclusive) struct super_block *sb; int ret; =20 - if (fc->phase !=3D FS_CONTEXT_CREATE_PARAMS) + if (fc->phase !=3D FS_CONTEXT_CREATE_NS && + fc->phase !=3D FS_CONTEXT_CREATE_PARAMS) return -EBUSY; =20 if (!mount_capable(fc)) @@ -291,6 +391,8 @@ static int vfs_fsconfig_locked(struct fs_context *fc, i= nt cmd, ret =3D finish_clean_context(fc); if (ret) return ret; + if (fc->phase =3D=3D FS_CONTEXT_AWAITING_NS && cmd !=3D FSCONFIG_SET_USER= LAND) + 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 !=3D FS_CONTEXT_AWAITING_NS && + fc->phase !=3D FS_CONTEXT_CREATE_NS) + return -EBUSY; + return fsconfig_set_userland(fc, param); + default: - if (fc->phase !=3D FS_CONTEXT_CREATE_PARAMS && - fc->phase !=3D FS_CONTEXT_RECONF_PARAMS) + if (fc->phase =3D=3D FS_CONTEXT_CREATE_NS) + fc->phase =3D FS_CONTEXT_CREATE_PARAMS; + else if (fc->phase !=3D FS_CONTEXT_CREATE_PARAMS && + fc->phase !=3D FS_CONTEXT_RECONF_PARAMS) return -EBUSY; =20 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 =3D aux; break; + case FSCONFIG_SET_USERLAND: + ret =3D -EBADF; + param.file =3D 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); =20 +/* + * 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); =20 /* * 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, fl= ags, !ns_capable(current_user_ns(), CAP_SYS_ADMIN)) return -EPERM; =20 - if (!(flags & FSMOUNT_NAMESPACE) && !may_mount()) + if (!(flags & FSMOUNT_NAMESPACE) && !IS_ENABLED(CONFIG_USERLAND) && + !may_mount()) return -EPERM; =20 if (attr_flags & ~FSMOUNT_VALID_FLAGS) @@ -4751,6 +4752,16 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, f= lags, if (ret) return ret; =20 + 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 =3D -EINVAL; if (!fc->root) @@ -4792,9 +4803,12 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, f= lags, return FD_ADD((flags & FSMOUNT_CLOEXEC) ? O_CLOEXEC : 0, open_new_namespace(&new_path, MOUNT_COPY_NEW)); =20 - ns =3D alloc_mnt_ns(current->nsproxy->mnt_ns->user_ns, true); + ns =3D 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 =3D fc->userland_mnt_id; mnt =3D real_mount(new_path.mnt); ns->root =3D mnt; ns->nr_mounts =3D 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 =3D { .init_fs_context =3D ramfs_init_fs_context, .parameters =3D ramfs_fs_parameters, .kill_sb =3D ramfs_kill_sb, - .fs_flags =3D FS_USERNS_MOUNT, + .fs_flags =3D FS_USERNS_MOUNT | FS_USERLAND_MOUNT, }; =20 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 ou= tside */ #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 rena= me() 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; =20 @@ -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 */ }; =20 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 =3D 6, /* Create new or reuse existing superblock */ FSCONFIG_CMD_RECONFIGURE =3D 7, /* Invoke superblock reconfiguration */ FSCONFIG_CMD_CREATE_EXCL =3D 8, /* Create new superblock, fail if reusing= existing superblock */ + FSCONFIG_SET_USERLAND =3D 9, /* Set target userland, supplied by fd */ }; =20 /* 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 =3D { .parameters =3D shmem_fs_parameters, #endif .kill_sb =3D kill_anon_super, - .fs_flags =3D FS_USERNS_MOUNT | FS_ALLOW_IDMAP | FS_MGTIME, + .fs_flags =3D FS_USERNS_MOUNT | FS_USERLAND_MOUNT | + FS_ALLOW_IDMAP | FS_MGTIME, }; =20 #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS) @@ -6021,7 +6022,7 @@ static struct file_system_type shmem_fs_type =3D { .init_fs_context =3D ramfs_init_fs_context, .parameters =3D ramfs_fs_parameters, .kill_sb =3D ramfs_kill_sb, - .fs_flags =3D FS_USERNS_MOUNT, + .fs_flags =3D FS_USERNS_MOUNT | FS_USERLAND_MOUNT, }; =20 void __init shmem_init(void) --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376238; b=H/bSjUP7RChTTFsQ4dyCVdWm/qoIRfHoiVbWpLAjjbLGT8UH77w1kOvjqAN1iWOOLBIG n60o6cZ/FH5KCtzuW2KalAuf4GM29NMO/5/Gr8wrGSWPis0Pvk42OEs1oepFTNcIn5SDa YSx+2IfMQuEuZp1Is7yUaXAT0a2gyyO79ncpVFHOOySQeeZx0ReZ2NXlhWa0eGU4iBjbr rW9C48+O7USRMbde5NTc8mQXfxLpAg1lh3NDsdnyKWXpW0tX+Y9aWlbhmpxmvUX1TypMV xsd+OVtuLuYiU/SvhcKWxd+2SW+qo0vj7xdyi5QnyBPrvG7plQtf0brkXBOV5NXJQ0A== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376238; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=Jfv3MMg/O7UN8A+W1NHYimNXqqAkPIDpKwh6yDT3Yps=; b=yRdUsR0vN9GZjbuivVic5mOgvNQ0BkLOqUOXrs+uhChp7iEfP7Ugu5bcda1fhXME7xuI tV8eCsDl3S9j08rk/EvmkrRBUU1j+DoMKKAFdAw9pwLt9kY09XpErwNsM4s8MNiiduzGZ tOzSaIuN8Oy/DlwPBTPq4ohQALCg5zS1hEeiqXQV+1oo7QVoFnfSvcVRPYx5tLk3fIyWm cFNZCtgnTCCHxXAdbSdIGgV15usrROPTKEh/9wuHALSX45+tUCrqv1BmTtRZexUDcyFQJ kJ8X9glXefY5zulAh8RLovCfiNc2u+78EBgAoYLVTUO92X3Avq0hJvRLoVDKHa6S/Gw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=n5gU4g52; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id 20DD260A2638; Sun, 22 Nov 2026 19:37:18 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=n5gU4g52 Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id DB0961F000EF; Sun, 22 Nov 2026 19:37:16 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376237; bh=Jfv3MMg/O7UN8A+W1NHYimNXqqAkPIDpKwh6yDT3Yps=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=n5gU4g52v76arg2qLN1/ypN62ZK2xci1H49qauQnRD1ZQ4gQRiaGYjG+lO9PfDqlW JaNR9IvTfBSu/9qDydT2bch63eLvpP4T1EDPgHW8Mzoto0p3nO+szhaHzKbf0skjP8 /oEkzdVR1WlrXz4CBqyZipi3lB4p4mouk96KgWm56giD5yEchAfUB5dWsIpwvq5/SO eFtzo8KxT3hJ5NmYppp9kdPQ1v715sI0tizcf/CAez1gsnUTR9o9L7Xqzl9uV6h2dk aX+ZhnyZudMcQlmfslgweTo5EdDIU4iAKk/S4ZSGZENNEbQqlJTvaN0c/FeqdYoMKS vZPBDfzIqGCmw== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 19/26] proc: Implement ->set_userland() fs_context operation Date: Sun, 22 Nov 2026 21:35:32 +0200 Message-ID: <20261122193539.3334213-20-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 Signed-off-by: David Howells Signed-off-by: Jarkko Sakkinen --- 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 #include #include +#include +#include #include #include #include @@ -206,6 +208,10 @@ static int proc_parse_param(struct fs_context *fc, str= uct 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 =3D 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); } =20 +static int proc_set_userland(struct fs_context *fc, struct userland *userl= and) +{ + struct proc_fs_context *ctx =3D fc->fs_private; + struct pid_namespace *target =3D 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 =3D get_pid_ns(target); + put_user_ns(fc->user_ns); + fc->user_ns =3D 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 =3D 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 =3D { .free =3D proc_fs_context_free, .parse_param =3D proc_parse_param, + .set_userland =3D proc_set_userland, .get_tree =3D proc_get_tree, .reconfigure =3D proc_reconfigure, }; @@ -371,7 +393,9 @@ static struct file_system_type proc_fs_type =3D { .init_fs_context =3D proc_init_fs_context, .parameters =3D proc_fs_parameters, .kill_sb =3D proc_kill_sb, - .fs_flags =3D FS_USERNS_MOUNT | FS_USERNS_MOUNT_RESTRICTED | FS_DISALLOW= _NOTIFY_PERM, + .fs_flags =3D FS_USERNS_MOUNT | FS_USERLAND_MOUNT | + FS_USERNS_MOUNT_RESTRICTED | + FS_DISALLOW_NOTIFY_PERM, }; =20 void __init proc_root_init(void) --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376242; b=Qdvr/EgPPIHlltZ4UMDqiqPNkn90g/S+Kf1hVGUuJs9URV0VTbLM6Zhozm9mHrrbIlXB OR0igX7cMxQic1w5EfZ0Z6DEySYtJ6GiItdrz7CPzgWl+E/y52XRLRDK4vGHUKukJWeF7 4DMkDBwZx3f/4gCssOy6jy5CFkGBt1B+RoKoGTC1gKL1UMvlj1D7QrM/qdQuqI9vBKS/B iLsEt/favmB6urf2AtlHfbUj6oAeZFtwqfAAFieDY+fX8RY4g3idBf3XtT4Q5qypEMCNg NOI4coU4dtGcGi4KSDWOGvyQN9bKhRG11Gn1c1F/jN9IYG3cuZQHxFXZZv9zjLF6lPA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376242; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=cgy8beB6sSd/m8AunHL+Exu9SqwXUH4jGUnQFpHNC2g=; b=zrV2bFvG9jt4qZM5j71SgPeubQ1druz6s8IGjvIjMmosq1cGbceDmLHnmZlsoTQVzQrC C4sg5VIEGhAFv/G4MMZA3Eww4ro15NGedUAZLncZjds5dYEJ6U3YKnCcRkEOxXai8ouGb zU69XDkzeFCOoUwU6OA++Honsjqg5ivAwz1tH9hrc/+k/cFNCse4/v1GprfMU5mHp5HLa dlK7RKUl3dmELFv8pOzdzmLf4bcLJExdbfuu9muvJhotGF9vd5740ECAYMjFfrkpUqSMq eSIVDs7mYVA4xmBb7zKYu7a3SAuPMESCR9997g9a0h3bQj11QD9eYFPsPIEZ/8E2XOA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=MFbZVX98; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id C0E5F606A32C; Sun, 22 Nov 2026 19:37:22 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=MFbZVX98 Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 5680E1F000F0; Sun, 22 Nov 2026 19:37:21 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376242; bh=cgy8beB6sSd/m8AunHL+Exu9SqwXUH4jGUnQFpHNC2g=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=MFbZVX98oz4AbJTw3EE+xuDLG3zdzugZzGHmoYc6hW7eDec0Blnfzxt5edluonBsu e0Ei3/23NPNyGX5cyvRmcFvoeLu1mEnHe0QrQdxIt9XFnxpQeXlfHbYCLtlnjnYWBz Nbcb3MXIwfKxt7e7V4rLH7H0AIyobdyn+16rXrNSmV7u5hbKxwQBPTXwAOWKS4xmiF H7qCkd/Gt3lIwdBEvC2huYCEAP63fMN+dpNDjqiAJDdVcF4aAkl4mObzlIXk8T0o8H ayCiozSV6G0LHbRgmoiRS5toCHJx8Wl+Cu6RyA4Z2dEfujWJDRWtHSGWP8nbnF4Pmx r2J26+nsXFzqg== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 20/26] ipc/mqueue: Implement ->set_userland() fs_context operation Date: Sun, 22 Nov 2026 21:35:33 +0200 Message-ID: <20261122193539.3334213-21-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 Signed-off-by: David Howells Signed-off-by: Jarkko Sakkinen --- 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 #include #include +#include #include #include #include @@ -400,6 +401,20 @@ static struct inode *mqueue_get_inode(struct super_blo= ck *sb, return ERR_PTR(ret); } =20 +static int mqueue_set_userland(struct fs_context *fc, struct userland *use= rland) +{ + struct mqueue_fs_context *ctx =3D fc->fs_private; + struct ipc_namespace *ipc_ns; + + scoped_guard(spinlock, &userland->lock) + ipc_ns =3D get_ipc_ns(userland->ns->ipc_ns); + put_ipc_ns(ctx->ipc_ns); + ctx->ipc_ns =3D ipc_ns; + put_user_ns(fc->user_ns); + fc->user_ns =3D 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= =3D { =20 static const struct fs_context_operations mqueue_fs_context_ops =3D { .free =3D mqueue_fs_context_free, + .set_userland =3D mqueue_set_userland, .get_tree =3D mqueue_get_tree, }; =20 @@ -1620,7 +1636,7 @@ static struct file_system_type mqueue_fs_type =3D { .name =3D "mqueue", .init_fs_context =3D mqueue_init_fs_context, .kill_sb =3D kill_anon_super, - .fs_flags =3D FS_USERNS_MOUNT, + .fs_flags =3D FS_USERNS_MOUNT | FS_USERLAND_MOUNT, }; =20 int mq_init_ns(struct ipc_namespace *ns) --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376246; b=3txEcWvRObOdNfJlhGzUttxomADIez0MTvlkM52qIEQye5pHgsEElxhQ+nHTWNLhBizx M1W31F6QU+gDMs+JrQmI46bRtfl0/FyXmwscPyB+N8IfKZc1l299F8x1fhgA+dThoyUzo o0LWCRRhSrdTPMjteyrrIpJj62Zjs4GmykqLehuCFyRbgI6RkYFErCfFFskDcfv/rAT1l fLNZjSGH0mtGpk/o+RZkFzK0XmYxh068vG8WdynwDZwrjFapAqLb+Ez4Fjgw7jN4pE776 LwMXV8mWyIasliaZamSthu21cqtTiYyiYOfTGWyGRi3VFMoKwTGJJ5qEsqct/asSLTw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376246; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=0Po0UTofwVcN49w2TPBs2Sh5Xkkd18b3WmLdf69QyzI=; b=FQ9rrt/7QBeUqg6imaAVkZi7lwFmsZMPKrDVSKNjv7UXxJ1ZQiOGt5VKaiEcBEek9C/h DU9QrkvOElEultv2F080gNEUhxV/XtjKjvqI5Sj2vacg7nP4vJ8UaoiM+1gpbmemXKmxL peAzfoFAKpeBVEQSN6mk3JP+x7rGp9a1cJMX02RT1GSe6bEZc9yOVr7EQ6P8REyH7Tep0 oTkPIOlO0+3W0VCK09qCwGXsT9MJyBLdCikxzqJFIJtajINoxcuzg59gBaXUYIDSibMzr nYH9/zCsqdVVhV7BjAo/GyAh+/x4uc0A+Cipzz84ZVkIoldL796KzL94IzBmb+TwkJA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=Xq3b6n8w; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id D860C606A69D; Sun, 22 Nov 2026 19:37:26 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=Xq3b6n8w Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id A21051F000EB; Sun, 22 Nov 2026 19:37:25 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376246; bh=0Po0UTofwVcN49w2TPBs2Sh5Xkkd18b3WmLdf69QyzI=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=Xq3b6n8wczeX6bcEtdN8cCH7JhZ4EhymQVumjmGdh4f2hgTvNu4fOMm72bXXy3uj9 x9hE7lkWcwKsMamJC5/qm9QmNnW5m26AOYjo+582xRDqvIG8usSeMoAcaZdPHUHkW5 gE1gnioj/EdzfWXcDb+RIOxrDe3QFzjnzIa15tD4hK4WOTVxlglCcLJsSUrOjbo4Fw HSFZg6g3q0z5c7MAhlLjvO/Ezhuz1ZCo5I/30A0z97/OiK2bYbziT+mpWyb05PyBZR T33JJzXlIo8muXhyC4gjJuT0YvasYqIYnby2cjWNMaH6ZHKlODA/qEiXxy+6jw6B08 3rNnOKjquS4Dw== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 21/26] security: Add userland LSM hooks Date: Sun, 22 Nov 2026 21:35:34 +0200 Message-ID: <20261122193539.3334213-22-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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_dev= ice *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 f= lags) +LSM_HOOK(void, LSM_RET_VOID, userland_free, struct userland *userland) +LSM_HOOK(int, 0, userland_share, struct userland *userland, struct ns_comm= on *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 }; =20 /* 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; =20 enum lsm_event { LSM_POLICY_CHANGE, @@ -2469,4 +2470,40 @@ static inline void security_initramfs_populated(void) } #endif /* CONFIG_SECURITY */ =20 +#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 *n= s); +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 si= g) +{ + 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 #include #include +#include #include =20 #include "exit.h" =20 -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); } =20 +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 =3D file->private_data; @@ -136,6 +143,7 @@ static long userland_share_nsfd(struct userland *c, uns= igned long arg) struct ns_common *old_time_children =3D NULL; struct ns_common *old_ns =3D NULL; struct ns_common *ns; + int ret; =20 if (arg > INT_MAX) return -EBADF; @@ -167,6 +175,10 @@ static long userland_share_nsfd(struct userland *c, un= signed long arg) !ns_capable(ns->ops->owner(ns), CAP_SYS_ADMIN)) return -EPERM; =20 + ret =3D security_userland_share(c, ns); + if (ret) + return ret; + scoped_guard(spinlock, &c->lock) { if (c->state !=3D USERLAND_INIT) return -EBUSY; @@ -315,6 +327,7 @@ int userland_send_signal(struct file *file, int sig, bool any_perm =3D false; int other_err =3D 0; struct pid *pid; + int ret; int nr; =20 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) !=3D USERLAND_RUNNING) return -ESRCH; =20 + ret =3D 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 =3D userland_create_user_ns(); if (IS_ERR(user_ns)) { ret =3D PTR_ERR(user_ns); - goto err_put; + goto err_free; } c->user_ns =3D user_ns; ns_ref_active_get(user_ns); =20 if (!ns_capable(user_ns, CAP_SYS_ADMIN)) { ret =3D -EPERM; - goto err_put; + goto err_free; } =20 ns =3D create_new_namespaces(clone_flags, current, user_ns, NULL); if (IS_ERR(ns)) { ret =3D PTR_ERR(ns); - goto err_put; + goto err_free; } =20 if (ns->time_ns !=3D ns->time_ns_for_children) { @@ -513,10 +530,14 @@ static struct userland *userland_create(unsigned int = flags) c->ns =3D ns; nsproxy_ns_active_get(ns); =20 + ret =3D security_userland_alloc(c, flags); + if (ret < 0) + goto err_free; + return c; =20 -err_put: - userland_put(c); +err_free: + userland_free(c); return ERR_PTR(ret); } =20 @@ -610,6 +631,10 @@ int userland_prepare_fork(struct kernel_clone_args *ar= gs) if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current))) return -EXDEV; =20 + ret =3D security_userland_clone(userland); + if (ret) + return ret; + ret =3D 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 } =20 /** @@ -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 } =20 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 #include #include +#include #include #include =20 @@ -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 creati= on + * @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 =3D lsm_blob_alloc(&userland->security, blob_sizes.lbs_userland, + GFP_KERNEL); + if (unlikely(rc)) + return rc; + + rc =3D 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 =3D 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 *n= s) +{ + 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 */ --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376251; b=1KarJaDuhjPeTn49ZGEKlTwIKjr8XzSCKHh0peoo3NOXaIy3vEwF1rL6LXloYk8v51ZZ RlX1JlZ72qV4Amv0QVI/8XwDrN3sdVxqfkrZR2q9NVfugoZ1iXB555CVrmYfOoNkjodRC o1u0YhUjmp67RmbcdgPwdLWpN904b9N3eC5r0dhDttT/JbF4ZsLH8admpZd9+1YkAxP1S VsHXy12YMqYgaOt2PM802RuGtuVwLNd161z8ciJoaZZzUpuuv8QvxobPJIBBGWAZZGPhb cg8Tas63IPIyedpkGPO6qmuMWmZwCJRlTxoRe/YedPS2AVHD6rOARcm1eKHEoLCwX2w== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376251; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=zs4d8Qildq2fNc6PLk+GUR8ZjIlQZmHZPkOwBRx3+1A=; b=Pu14LMi6C0MVv0oYIfo4K0I0/bq8AEjm6iw9e2cG7G+3C9SK6JIo9z8L7GaGyYaMVlM7 +cWvZfJLrNuvBx2Z3fML1/7ngla2VJU4XMw7s2qZ11m99uW1cvZD3Fu1PWsFtHMrO3A2N wSbW+xfw4DDGtboAiQjHJkw1C3ogSxHQPBHtBcgmgxexA68Sl9VzyqeSG16hcuTrRt8hs GIvTN6/SAMq7RBCvlZ6vSxMsaNPN6MjARkTxmECJkzMkcQ1JdoMmwOeFIZx8sun8Pl9cA thdy7BulebM0baxX9QtSKy5kZr7rxTSXmXf8p5FKVsN9/hG5Ix+ja3V57yiE9sNK9Lw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=W8nWhqyY; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id 67B84606A6AD; Sun, 22 Nov 2026 19:37:31 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=W8nWhqyY Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 193F91F000C0; Sun, 22 Nov 2026 19:37:30 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376250; bh=zs4d8Qildq2fNc6PLk+GUR8ZjIlQZmHZPkOwBRx3+1A=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=W8nWhqyY1l/5oIhxo9AusbNPDS7pNe2c7jdlfibiK9O4J7YFbmrpPsuK6dub2ROAe rn9773eP+vZgMLsdrGpMNtNwUR97O+i7Ymi7QxvdMtYxyu/B5vZtW0/SSzz9CikZZG zz2so70cW+rNG9k2mcDrKZFtWEFpUpG1MUttpQAI7FZabGlKL8TGb/tF7vF0ZmWO80 Hm87LXNBNvD3YulVza7xOlYl39k1q+U50EdgVJtvNyOJtHreMMEnqffEYjwpr841I8 Iu4gBtD2Cfw8Lt+5t4n478r/phiivzEwhQSTNlPRapp8t/upmoP72EBoqdD5BcfafY ZTCS4Or2D4EEA== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 22/26] bpf: Register userland LSM hooks Date: Sun, 22 Nov 2026 21:35:35 +0200 Message-ID: <20261122193539.3334213-23-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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 #include #include +#include =20 /* 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) =20 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) =20 bool bpf_lsm_is_sleepable_hook(u32 btf_id) --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376255; b=RJanLf4dyMBsXoxjzHRT0eLQislLCDunU/30YbkuRMogoPxI7ZQNfrQizjOmVZofjHTb V7mE5wZI70W18IM8nUqu1/d9lmnJFiGI42VBTotEJr8RSHbDf4yhepa6KyY8tqvsaT3GS CcbwrYf4tCH1vjAbHSGRl75qSJvip8UdkKfSt4MQJyIGLj+6AQtr5tbGsLePwzRkKE3AN n9HMVloYrWUUVizjQWh6QrdsDCmyCzeTcgoDJtMqzuxaLSDV4XJVOjzR58X6s9FXX4tDQ /cO5LN/wqNp8myzPcYdRaN6Fdw6ChlpPjSOLNirpO3K/asnwtpWppM9tjE9b+faa8gQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376255; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=PRa/Z4N97Xs3mX/qNh7M9bbsE39tiqxbHLlAZExaAw8=; b=QVhtvoaSU2rcZwNJChgkDWfMR/9JMHo+HKH8W3ZEHOTwWx01AyCWWlEE2wsPcF0EUzwm VnLLzkEB7zKYA6wNfjI0vNhjVRmSy8kuItrucHrN0lXAXPs4OBUESHuJwuB1fbrV1xG/V XCxDARwzcNhetGUkPUgLg1IczATp39pd4YxEdPEFsJms04xlGlulem9mXl0Agm6K58Ms1 mEqmwaA8k7ncWFz93+DsmvFYbk9F2LpPG2foTjM7sd0nv4I4EstaupsZPtWga0ATvcgEr FX/A8c82vaENar3b3nCoxUnv2ArXmDgedF/XcfgwbfzTcnCTmo+w4wy4vNhZpDykgiw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=JZ45Dbnh; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id 98089606A690; Sun, 22 Nov 2026 19:37:35 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=JZ45Dbnh Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 652FA1F000C0; Sun, 22 Nov 2026 19:37:34 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376255; bh=PRa/Z4N97Xs3mX/qNh7M9bbsE39tiqxbHLlAZExaAw8=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=JZ45DbnhnjG22sXXrfi8OAsPk0tnpcu80M8TaUaBIU/vh3zjbCyKi3YDS5KNOZMVP P7P+wXeAqZy5QBwP1fJ14MNwzvO4qos+6KconVuWPKf0Tt9+bQwmUfJZADyxZeHuAw 6QUQEi/vtXrWBCDm6FxhM4nyELMBqRj1cXtjFmdZVmLoNGMKEV6OGTdhIlRfYwECbq rdnnwEH/iS50DHXkjmv1XaCvVN3q3rvxPsMRj2tjD2gsw3+oLrN0AXeJ+PqxD4WX0q TYLVzeu8J7I9IrNZP+HXFbEGXlhw0ytDoqTxt4hP00gc5J8gDWQzv1G/3SBxOwvtyi 8SsYj1tD2FLaw== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 23/26] arch: Wire up userland_open() system call Date: Sun, 22 Nov 2026 21:35:36 +0200 Message-ID: <20261122193539.3334213-24-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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/sys= calls/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/sysca= lls/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/s= yscalls/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/s= yscalls/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/s= yscalls/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/s= yscalls/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/sysca= lls/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/sys= calls/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/syscal= ls/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/syscal= ls/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 =20 # # Due to a historical design error, certain syscalls are numbered differen= tly diff --git a/arch/xtensa/kernel/syscalls/syscall.tbl b/arch/xtensa/kernel/s= yscalls/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/u= nistd.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) =20 +/* 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 =20 /* * 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/a= sm-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) =20 +/* 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 =20 /* * 32 bit systems traditionally used different diff --git a/tools/perf/arch/arm/entry/syscalls/syscall.tbl b/tools/perf/ar= ch/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/pe= rf/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/per= f/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/a= rch/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/arc= h/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 =20 # # Due to a historical design error, certain syscalls are numbered differen= tly 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 --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376259; b=MMZhef/T629x52jtCpAuqz1fa2VOnTRE98+CfYSLsRZ9ztthkWSnx0SH0WLISuoxDvc9 Fj+eR271g4ppLA7FGuLuYzZe23TcukBST+UlQM+xOYfYYAs2MGmN8xdUC0uB1qSNJXvLG Mh158cQDCQRBHq9JA1bNooiOUqX0PB+9wt85VXu+UyaS80OLbFcr7b4HGDNDo8OWr3ZMq cefkC95IBmEU5oivQSoD8kw2oCeJNoqhFOQj2NOIqi+OcYnuap+UApwlVHF2+XcG92D0p e4OFyv5SRAUWsWmCYug4AW9UckutUrX5wYwZ9gZibbHW50WZmU1OUzidFGccY08XIkQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376259; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=lKuvDTI6FKXAAEbVhrzFDmxnTT5Wc4CNv/2+sIEwHRc=; b=kNT5Pbm94mW7Y+OmsJw+eGQUuDHnL2GURY7ckUXGETkICavsBm34f+S/y/xMGJhCJ3Qd htbJXaN2IhpA9yNHZmFXe/yCmJNnnLkGyjXS5NKSLRR1AG18w3LKYQyOW7bLaO8EDRFB0 E0suIbZVCbkF/UecvKtjB2G1mF/xJr+aCb+pfXa3wSHMvDiFyx9COkEBsGvluxJfm2R+H 5Qy/4EozjR/blMHD4J6ESup4En+wMoQE3gbIeakFabsfShNVMIaa/xqeiclbaT2LPEoQU ELXUX7KVIjF+Jr2zqUWNuqFgBesfdgdc1SyCxwliD9x6i+y57vZsDqKrz2EsFALfEsw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=JrRw2VD2; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id B0926606A6AA; Sun, 22 Nov 2026 19:37:39 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=JrRw2VD2 Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id B91A51F000C0; Sun, 22 Nov 2026 19:37:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376259; bh=lKuvDTI6FKXAAEbVhrzFDmxnTT5Wc4CNv/2+sIEwHRc=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=JrRw2VD2LDlpWWnJ443LaoyqYPi4WgdTpxgCBEg8S1X4e6IoUvfRHh2uCryPfjSrB k49cshsGh1pQGyu8+ruFN5d5UZ84WoFrEgLMgZL33GuKh7Brduf4ZFFAMf8oJ5YeVe P5+logxlr1Mggk49m8VIlSPaAsMgwtpUd84l2GYBXS4JQzhRmyU1kB+6TwZ/FwxxFP TpBUzs/TXlv3gs+UJ16Cf0VGW6o7otugSJjLKPf51TNLQRNCN0a4c4ZxiL5bmTIcJA 2hkuAJmkIf2j7Bq11dWJG+6VxJu6M2HyIMMaJTql4BEoanz/MSQ6sg6sqBmAtBU/UV E0hG4WNw5gekA== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 24/26] docs: Document userland uAPI Date: Sun, 22 Nov 2026 21:35:37 +0200 Message-ID: <20261122193539.3334213-25-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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/userspac= e-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 =20 unshare + userland futex2 ebpf/index ioctl/index diff --git a/Documentation/userspace-api/ioctl/ioctl-number.rst b/Documenta= tion/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 Mar= vell CN10K DPI driver 0xB8 all uapi/linux/mshv.h Mic= rosoft Hyper-V /dev/mshv driver +0xB9 00-0F uapi/linux/userland.h use= rland uAPI 0xBA 00-0F uapi/linux/liveupdate.h Pas= ha Tatashin 0xC0 00-0F linux/usb/iowarrior.h diff --git a/Documentation/userspace-api/userland.rst b/Documentation/users= pace-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 + +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D +userland uAPI +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +Overview +=3D=3D=3D=3D=3D=3D=3D=3D + +.. kernel-doc:: kernel/userland.c + :doc: Overview + +Lifecycle +=3D=3D=3D=3D=3D=3D=3D=3D=3D + +.. kernel-doc:: include/linux/userland.h + :identifiers: userland_state + +Flags +=3D=3D=3D=3D=3D + +.. kernel-doc:: include/uapi/linux/userland.h + :identifiers: userland_flags + +Ioctls +=3D=3D=3D=3D=3D=3D + +.. kernel-doc:: include/uapi/linux/userland.h + :doc: USERLAND_GET_NSFD + +.. kernel-doc:: include/uapi/linux/userland.h + :doc: USERLAND_SHARE_NSFD + +System calls +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +.. kernel-doc:: kernel/userland.c + :identifiers: sys_userland_open + +Process creation +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +.. kernel-doc:: kernel/userland.c + :doc: CLONE_INTO_USERLAND + +Process waiting +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +.. kernel-doc:: kernel/userland.c + :doc: P_USERLAND + +Signal delivery +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +.. kernel-doc:: kernel/userland.c + :doc: pidfd_send_signal + +Filesystem configuration +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +.. kernel-doc:: fs/fsopen.c + :doc: FSCONFIG_SET_USERLAND + +Mount tree installation +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +.. kernel-doc:: fs/namespace.c + :doc: MOVE_MOUNT_T_MNTNS + +User namespace ID mapping +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D + +.. 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 --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376265; b=SsRr8cPV/RVT2+HMJjvZ74L0cqfpJeY7QWM9Gcsc3z9dQItSxUi00old8UR5VcoYPL32 NEXQdtWorrqH0825OJqukosoz3DTW5f2ccaoiTlRnKmOHNP9DZPqynLKY/6CBb0tfLYpS 8x5Jf5oIfVDw/QRwzhwUKhkdL3Iap9V2Nz3SnNXV79zwGnzPo7nFYyL77BCkqLGooi9vx tbTqEFNHBlQpJt+ZmrNFJHmwUudGvEYF8nLuyAIQoE/cQ06yTbnNjIZCMgu5o0nkJz4hi O8pveXALcCsqrhONUOMs4VlErQfwvJl59r2S4nGfUmTVtCA/AM8j760qmulI9GG+6mg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376265; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=vANxA5ylHQa5g4ZWjG01gH6865VjWSuiXPIRsM92opE=; b=3zHVpqMteZHom5oBYp4Vn86HH+8BStEpoh7e1FhJ/CK8btRNuKVrprGxQIYaoWwP1B3P nzv+NGMwG35IsfPUoMkR6DiKQqhENEYsu7qBLIM4R3ZhCSzsU5AjdgAUNxulZLQQV9sp9 XWjFWk2JgfJdBzlUlEXqY/ianNhTsxcfkbx/jhw4Z60/9LJ3nVE24as0GJeZMK+ZeYdWi 4lkxnbDMRDb5At3mVXWcUFvj7cv+y+3PXyY5bzxW7iAcdQ/y4W8t0c9+PhK03yaigzBl5 C2AB7jl8c2FnWXRNYOatPdNAJnvbbgkQhL+THhSOL7pBQ8bN6sLvOJD2E30eLa0cTrg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b="R+YxN/OT"; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id ECEB2606A336; Sun, 22 Nov 2026 19:37:44 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=R+YxN/OT Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id C5A081F000ED; Sun, 22 Nov 2026 19:37:42 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376264; bh=vANxA5ylHQa5g4ZWjG01gH6865VjWSuiXPIRsM92opE=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=R+YxN/OThW8G5UrNgRMxTVnKJ8n+lgKDzQX27XCDUPKS4BLiTm550tgGekJI7pkzE g/rbfU3l8RNVV2ConttGPdI6vMvdyfGgEGPEq/7ZbkvHs4tCf4IGoQ8fqW3P8KlyJL ctal7+XfKwqY++WZjhSd2bMV5RXZ8eSgj725aPji1p2s0vRf3/ZL3izrK0p/GJ1s3a QQOKOk1Li+8U1uFAZuHxd1wIpcDizgTiTrv8rGxGYHpcVmgW0CYjL0+yYPUjUnJQkP d5G9C7d8KPP1YlKMyWcpQkXPBg7bugotPC5JUfRW8IMCUl/R986Ek/FYVBbo296uJc IWDIPsADbFx7g== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 25/26] selftests/userland: Add userland test suite Date: Sun, 22 Nov 2026 21:35:38 +0200 Message-ID: <20261122193539.3334213-26-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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/Mak= efile index 07c3719f8b04..4bf12d0cfd1e 100644 --- a/tools/testing/selftests/Makefile +++ b/tools/testing/selftests/Makefile @@ -145,6 +145,7 @@ TARGETS +=3D tty TARGETS +=3D ublk TARGETS +=3D uevent TARGETS +=3D user_events +TARGETS +=3D userland TARGETS +=3D vDSO TARGETS +=3D mm TARGETS +=3D vfio diff --git a/tools/testing/selftests/userland/Makefile b/tools/testing/self= tests/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 :=3D test_smoke.sh +TEST_FILES :=3D userland_cells.py userland_test.py +TEST_INCLUDES :=3D ../kselftest/ksft.py diff --git a/tools/testing/selftests/userland/config b/tools/testing/selfte= sts/userland/config new file mode 100644 index 000000000000..c144ef706856 --- /dev/null +++ b/tools/testing/selftests/userland/config @@ -0,0 +1,10 @@ +CONFIG_CGROUPS=3Dy +CONFIG_IPC_NS=3Dy +CONFIG_NET_NS=3Dy +CONFIG_PID_NS=3Dy +CONFIG_PROC_FS=3Dy +CONFIG_TIME_NS=3Dy +CONFIG_TMPFS=3Dy +CONFIG_USER_NS=3Dy +CONFIG_UTS_NS=3Dy +CONFIG_USERLAND=3Dy 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=3D4 + +command -v python3 >/dev/null 2>&1 || exit $ksft_skip + +DIR=3D"$(dirname "$(readlink -f "$0")")" +exec python3 "$DIR/userland_test.py" "$@" diff --git a/tools/testing/selftests/userland/userland_cells.py b/tools/tes= ting/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, ...]] =3D ( + "usr", + "bin", + "sbin", + "lib", + "lib32", + "lib64", + "libx32", + "etc", + "opt", + "nix", +) + + +class UserlandFlag(IntFlag): + NONE =3D 0 + KILL_ON_CLOSE =3D 0x00000001 + CLOSE_ON_EXEC =3D 0x00000002 + DEFAULT =3D KILL_ON_CLOSE | CLOSE_ON_EXEC + ALL =3D KILL_ON_CLOSE | CLOSE_ON_EXEC + + +class CloneFlag(IntFlag): + NONE =3D 0 + NEWTIME =3D 0x00000080 + VM =3D 0x00000100 + FS =3D 0x00000200 + FILES =3D 0x00000400 + SIGHAND =3D 0x00000800 + PIDFD =3D 0x00001000 + VFORK =3D 0x00004000 + PARENT =3D 0x00008000 + THREAD =3D 0x00010000 + NEWNS =3D 0x00020000 + SYSVSEM =3D 0x00040000 + NEWCGROUP =3D 0x02000000 + NEWUTS =3D 0x04000000 + NEWIPC =3D 0x08000000 + NEWUSER =3D 0x10000000 + NEWPID =3D 0x20000000 + NEWNET =3D 0x40000000 + CLEAR_SIGHAND =3D 1 << 32 + INTO_CGROUP =3D 1 << 33 + AUTOREAP =3D 1 << 34 + NNP =3D 1 << 35 + PIDFD_AUTOKILL =3D 1 << 36 + EMPTY_MNTNS =3D 1 << 37 + INTO_USERLAND =3D 1 << 38 + + +class AtFlag(IntFlag): + NONE =3D 0 + EMPTY_PATH =3D 0x1000 + RECURSIVE =3D 0x8000 + + +class OpenTreeFlag(IntFlag): + CLONE =3D 1 << 0 + CLOEXEC =3D os.O_CLOEXEC + RECURSIVE =3D 0x8000 + + +class MoveMountFlag(IntFlag): + F_EMPTY_PATH =3D 0x00000004 + T_EMPTY_PATH =3D 0x00000040 + T_MNTNS =3D 0x00000080 + SET_GROUP =3D 0x00000100 + BENEATH =3D 0x00000200 + CLONE =3D 0x00000400 + + +class UsernsFlag(IntFlag): + NONE =3D 0 + SETGROUPS_ALLOWED =3D 1 << 0 + + +class MountAttrFlag(IntFlag): + NONE =3D 0 + RDONLY =3D 0x00000001 + NOSUID =3D 0x00000002 + NODEV =3D 0x00000004 + + +class MountFlag(IntFlag): + REC =3D 0x4000 + PRIVATE =3D 1 << 18 + SLAVE =3D 1 << 19 + SHARED =3D 1 << 20 + + +class UmountFlag(IntFlag): + NONE =3D 0 + DETACH =3D 2 + + +class ResolveFlag(IntFlag): + NONE =3D 0 + IN_ROOT =3D 0x10 + + +class FsconfigCmd(IntEnum): + SET_FLAG =3D 0 + SET_STRING =3D 1 + CMD_CREATE =3D 6 + SET_USERLAND =3D 9 + + +class PrctlOp(IntEnum): + GET_DUMPABLE =3D 3 + SET_DUMPABLE =3D 4 + SET_KEEPCAPS =3D 8 + GET_NO_NEW_PRIVS =3D 39 + + +class WaitIdType(IntEnum): + ALL =3D 0 + PID =3D 1 + PGID =3D 2 + PIDFD =3D 3 + USERLAND =3D 4 + + +class CloneArgs(ctypes.Structure): + SIZE_VER2: ClassVar[int] =3D 88 + SIZE_VER3: ClassVar[int] =3D 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_ =3D [ + ("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_ =3D [ + ("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_ =3D [ + ("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] =3D 0x20080522 + + version: int + pid: int + _fields_ =3D [ + ("version", ctypes.c_uint32), + ("pid", ctypes.c_int32), + ] + + +class CapData(ctypes.Structure): + effective: int + permitted: int + inheritable: int + _fields_ =3D [ + ("effective", ctypes.c_uint32), + ("permitted", ctypes.c_uint32), + ("inheritable", ctypes.c_uint32), + ] + + +class UsernsIdmap(ctypes.Structure): + SIZE_VER0: ClassVar[int] =3D 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_ =3D [ + ("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] =3D -100 + FSOPEN_CLOEXEC: Final[int] =3D 0x00000001 + FSMOUNT_CLOEXEC: Final[int] =3D 0x00000001 + CAP_SETGID: Final[int] =3D 6 + CAP_SETUID: Final[int] =3D 7 + _WIDE_IOC_PREFIXES: Final[tuple[str, ...]] =3D ( + "alpha", + "mips", + "powerpc", + "ppc", + "sparc", + ) + + @classmethod + def _is_wide_ioc_arch(cls) -> bool: + return platform.machine().lower().startswith(cls._WIDE_IOC_PREFIXE= S) + + @classmethod + def ioc(cls, direction: int, magic: int, nr: int, size: int) -> int: + sizebits =3D 13 if cls._is_wide_ioc_arch() else 14 + typeshift =3D 8 + sizeshift =3D 16 + dirshift =3D sizeshift + sizebits + return ( + (direction << dirshift) + | (magic << typeshift) + | nr + | (size << sizeshift) + ) + + @classmethod + def io(cls, magic: int, nr: int) -> int: + none_dir =3D 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 =3D platform.machine().lower() + ptr_size =3D ctypes.sizeof(ctypes.c_void_p) + multiarch =3D getattr(sys.implementation, "_multiarch", "") + arch_legacy: dict[str, int] + + if mach.startswith("alpha"): + base =3D 110 + arch_legacy =3D { + "pivot_root": 374, + "umount2": 22, + "waitid": 438, + "execveat": 513, + } + elif mach.startswith("mips"): + if ptr_size =3D=3D 8: + base =3D 5000 + arch_legacy =3D { + "pivot_root": 5151, + "umount2": 5161, + "waitid": 5237, + "execveat": 5316, + } + elif "abin32" in multiarch: + base =3D 6000 + arch_legacy =3D { + "pivot_root": 6151, + "umount2": 6161, + "waitid": 6241, + "execveat": 6320, + } + else: + base =3D 4000 + arch_legacy =3D { + "pivot_root": 4216, + "umount2": 4052, + "waitid": 4278, + "execveat": 4356, + } + elif mach =3D=3D "x86_64" and ptr_size =3D=3D 4 and "x32" in multi= arch: + base =3D 0x40000000 + arch_legacy =3D { + "pivot_root": base + 155, + "umount2": base + 166, + "waitid": base + 529, + "execveat": base + 545, + } + else: + base =3D 0 + asm_generic =3D { + "pivot_root": 41, + "umount2": 39, + "waitid": 95, + "execveat": 281, + } + if mach =3D=3D "x86_64" and ptr_size =3D=3D 8: + arch_legacy =3D { + "pivot_root": 155, + "umount2": 166, + "waitid": 247, + "execveat": 322, + } + elif mach in ("i386", "i486", "i586", "i686", "x86_64"): + arch_legacy =3D { + "pivot_root": 217, + "umount2": 52, + "waitid": 284, + "execveat": 358, + } + elif mach in ("aarch64", "arm64") and ptr_size =3D=3D 8: + arch_legacy =3D asm_generic + elif mach.startswith(("arm", "aarch64")): + arch_legacy =3D { + "pivot_root": 218, + "umount2": 52, + "waitid": 280, + "execveat": 387, + } + elif mach.startswith(("ppc", "powerpc")): + arch_legacy =3D { + "pivot_root": 203, + "umount2": 52, + "waitid": 272, + "execveat": 362, + } + elif mach.startswith("s390"): + arch_legacy =3D { + "pivot_root": 217, + "umount2": 52, + "waitid": 281, + "execveat": 354, + } + elif mach.startswith("sparc"): + arch_legacy =3D { + "pivot_root": 146, + "umount2": 45, + "waitid": 279, + "execveat": 350, + } + elif mach.startswith(("parisc", "hppa")): + arch_legacy =3D { + "pivot_root": 67, + "umount2": 52, + "waitid": 235, + "execveat": 342, + } + elif mach =3D=3D "m68k": + arch_legacy =3D { + "pivot_root": 217, + "umount2": 52, + "waitid": 277, + "execveat": 355, + } + elif mach.startswith("microblaze"): + arch_legacy =3D { + "pivot_root": 217, + "umount2": 52, + "waitid": 284, + "execveat": 388, + } + elif mach.startswith("sh"): + arch_legacy =3D { + "pivot_root": 217, + "umount2": 52, + "waitid": 284, + "execveat": 376, + } + elif mach =3D=3D "xtensa": + arch_legacy =3D { + "pivot_root": 175, + "umount2": 171, + "waitid": 122, + "execveat": 341, + } + else: + arch_legacy =3D asm_generic + + nums: dict[str, int] =3D { + "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 =3D 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 =3D 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 =3D 0) -> int: + ret: int =3D 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 =3D FSOPEN_CLOEXEC) ->= int: + return cls.syscall( + "fsopen", ctypes.c_char_p(cls._cstr(fsname)), ctypes.c_uint(fl= ags) + ) + + @classmethod + def fsconfig( + cls, + fsfd: int, + cmd: FsconfigCmd, + key: str | bytes | None =3D None, + value: str | bytes | None =3D None, + aux: int =3D 0, + ) -> None: + k_ptr =3D ( + ctypes.c_char_p(cls._cstr(key)) + if key is not None + else ctypes.c_void_p(0) + ) + v_ptr =3D ( + 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 =3D FSMOUNT_CLOEXEC, + attr_flags: MountAttrFlag =3D 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 =3D 0, + resolve: ResolveFlag =3D ResolveFlag.NONE, + ) -> int: + how =3D OpenHow(flags=3Dflags, mode=3Dmode, resolve=3Dint(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 =3D None, + flags: AtFlag =3D AtFlag.NONE, + ) -> NoReturn: + c_argv =3D (ctypes.c_char_p * (len(argv) + 1))( + *[cls._cstr(a) for a in argv], None + ) + if envp is None: + env_items =3D [f"{k}=3D{v}" for k, v in os.environ.items()] + elif isinstance(envp, Mapping): + env_items =3D [f"{k}=3D{v}" for k, v in envp.items()] + else: + env_items =3D list(envp) + c_envp =3D (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) -> No= ne: + 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 =3D 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 =3D "/", + flags: MountFlag =3D MountFlag.REC | MountFlag.PRIVATE, + ) -> None: + ret: int =3D 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 =3D 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 !=3D errno.EPERM: + raise + os.setresgid(uid, uid, uid) + os.setresuid(uid, uid, uid) + hdr =3D CapHeader(version=3DCapHeader.VERSION_3, pid=3D0) + mask =3D (1 << cls.CAP_SETGID) | (1 << cls.CAP_SETUID) + data =3D (CapData * 2)( + CapData(effective=3Dmask, permitted=3Dmask, inheritable=3D0), + CapData(effective=3D0, permitted=3D0, inheritable=3D0), + ) + ret: int =3D 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 =3D 0, + arg3: int =3D 0, + arg4: int =3D 0, + arg5: int =3D 0, + ) -> int: + ret: int =3D 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 =3D None) -> int: + actual_size =3D 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 =3D UsernsIdmapExtent * len(extents) + return arr_t( + *[ + UsernsIdmapExtent( + first=3Dfirst, lower_first=3Dlower, count=3Dcount, res= erved=3D0 + ) + for first, lower, count in extents + ] + ) + + @classmethod + def pidfd_send_signal( + cls, + pidfd: int, + sig: int, + info_addr: int =3D 0, + flags: int =3D 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 =3D 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 =3D UsernsIdmap.SIZE_VER0, + flags: int =3D 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]] =3D (), + gid_extents: Sequence[tuple[int, int, int]] =3D (), + projid_extents: Sequence[tuple[int, int, int]] =3D (), + *, + reserved: int =3D 0, + size: int | None =3D None, + flags: UsernsFlag | int =3D UsernsFlag.NONE, + ) -> None: + u_arr =3D cls._extent_array(uid_extents) + g_arr =3D cls._extent_array(gid_extents) + p_arr =3D cls._extent_array(projid_extents) + req =3D UsernsIdmap( + nr_uid_extents=3Dlen(uid_extents), + nr_gid_extents=3Dlen(gid_extents), + nr_projid_extents=3Dlen(projid_extents), + reserved=3Dreserved, + uid_extents=3Dctypes.addressof(u_arr) if u_arr is not None els= e 0, + gid_extents=3Dctypes.addressof(g_arr) if g_arr is not None els= e 0, + projid_extents=3Dctypes.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 =3D Sys._build_syscall_numbers() +Sys._LIBC =3D ctypes.CDLL(None, use_errno=3DTrue) +Sys._LIBC.syscall.restype =3D ctypes.c_long + + +class Ioctl(IntEnum): + USERLAND_GET_NSFD =3D Sys.io(0xB9, 0x01) + USERLAND_SHARE_NSFD =3D Sys.io(0xB9, 0x02) + NS_GET_USERNS =3D Sys.io(0xB7, 0x01) + NS_GET_PARENT =3D Sys.io(0xB7, 0x02) + NS_GET_NSTYPE =3D Sys.io(0xB7, 0x03) + + +@dataclass(frozen=3DTrue) +class WaitResult: + pid: int + status: int =3D 0 + code: int =3D 0 + uid: int =3D 0 + + @property + def exit_code(self) -> int | None: + if self.pid <=3D 0: + return None + if self.code =3D=3D 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 =3D UserlandFlag.DEFAULT, + *, + fd: int | None =3D None, + ) -> None: + if fd is not None: + self.fd =3D fd + else: + self.fd =3D Sys.syscall("userland_open", ctypes.c_uint(int(fla= gs))) + + @classmethod + def from_fd(cls, fd: int) -> Userland: + return cls(fd=3Dfd) + + 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 >=3D 0: + try: + os.close(self.fd) + except OSError: + pass + self.fd =3D -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]] =3D (), + gid_extents: Sequence[tuple[int, int, int]] =3D (), + projid_extents: Sequence[tuple[int, int, int]] =3D (), + *, + flags: UsernsFlag | int =3D UsernsFlag.NONE, + ) -> None: + userns_fd =3D self.get_nsfd(CloneFlag.NEWUSER) + try: + Sys.set_userns_idmap( + userns_fd, + uid_extents=3Duid_extents, + gid_extents=3Dgid_extents, + projid_extents=3Dprojid_extents, + flags=3Dflags, + ) + finally: + os.close(userns_fd) + + def map_self_ugid(self) -> None: + self.set_idmap( + uid_extents=3D((0, os.geteuid(), 1),), + gid_extents=3D((0, os.getegid(), 1),), + ) + + def wait(self, flags: int =3D 0) -> WaitResult: + res =3D os.waitid(int(WaitIdType.USERLAND), self.fd, os.WEXITED | = flags) + if res is None: + return WaitResult(pid=3D0) + return WaitResult( + pid=3Dint(res.si_pid), + status=3Dint(res.si_status), + code=3Dint(res.si_code), + uid=3Dint(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 =3D CloneFlag.NONE, + exit_signal: int =3D int(signal.SIGCHLD), + ) -> tuple[int, int]: + pidfd_cell =3D ctypes.c_int(-1) + args =3D CloneArgs() + args.flags =3D int(CloneFlag.INTO_USERLAND | extra_flags) + args.exit_signal =3D exit_signal + args.userland =3D self.fd & 0xFFFFFFFFFFFFFFFF + if extra_flags & CloneFlag.PIDFD: + args.pidfd =3D ctypes.addressof(pidfd_cell) + pid =3D Sys.clone3(args) + return pid, int(pidfd_cell.value) + + def run( + self, + fn: Callable[[], int | None], + extra_flags: CloneFlag =3D CloneFlag.NONE, + ) -> int: + pid, _ =3D self.clone_into(extra_flags=3Dextra_flags) + if pid =3D=3D 0: + try: + self.close() + rc =3D 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 =3D MountAttrFlag.NONE, + options: Mapping[str, str | None] | None =3D None, + ) -> int: + fsfd =3D Sys.fsopen(fstype) + try: + Sys.fsconfig(fsfd, FsconfigCmd.SET_USERLAND, aux=3Dself.fd) + if options: + for k, v in options.items(): + if v is None: + Sys.fsconfig(fsfd, FsconfigCmd.SET_FLAG, key=3Dk) + else: + Sys.fsconfig( + fsfd, FsconfigCmd.SET_STRING, key=3Dk, value= =3Dstr(v) + ) + Sys.fsconfig(fsfd, FsconfigCmd.CMD_CREATE) + return Sys.fsmount(fsfd, attr_flags=3Dattr_flags) + finally: + os.close(fsfd) + + +@dataclass +class Cell: + name: str + flags: UserlandFlag =3D UserlandFlag.DEFAULT + rns: Userland =3D field(init=3DFalse) + mntns_fd: int =3D field(init=3DFalse, default=3D-1) + root_dfd: int =3D field(init=3DFalse, default=3D-1) + + def __post_init__(self) -> None: + self.rns =3D Userland(self.flags) + try: + self.mntns_fd =3D 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 >=3D 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] =3D ("proc", "tmp", "mnt"), + mount_procfs: bool =3D True, + host_runtime: bool =3D False, + map_ugid: bool =3D True, + ) -> None: + if map_ugid: + self.rns.map_self_ugid() + rootfd =3D self.rns.make_mount("tmpfs") + bind_dirs: list[str] =3D [] + try: + for d in dirs: + os.mkdir(d, 0o755, dir_fd=3Drootfd) + if host_runtime: + for entry in HOST_RUNTIME_ENTRIES: + host_path =3D f"/{entry}" + if os.path.islink(host_path): + os.symlink( + os.readlink(host_path), entry, dir_fd=3Drootfd + ) + elif os.path.isdir(host_path): + os.mkdir(entry, 0o755, dir_fd=3Drootfd) + bind_dirs.append(entry) + self._move_to_mntns(rootfd, "/") + except Exception: + os.close(rootfd) + raise + self.root_dfd =3D 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 =3D MountAttrFlag.NONE, + options: Mapping[str, str | None] | None =3D None, + ) -> None: + mfd =3D self.rns.make_mount( + fstype, attr_flags=3Dattr_flags, options=3Doptions + ) + 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 =3D None, + resolve_in_root: bool =3D True, + ) -> int: + bin_fd =3D -1 + if resolve_in_root and self.root_dfd >=3D 0: + bin_fd =3D Sys.openat2( + self.root_dfd, + argv[0], + os.O_RDONLY | os.O_CLOEXEC, + resolve=3DResolveFlag.IN_ROOT, + ) + try: + pid, _ =3D self.rns.clone_into( + extra_flags=3DCloneFlag.AUTOREAP, exit_signal=3D0 + ) + if pid =3D=3D 0: + try: + self.close() + if bin_fd >=3D 0: + Sys.execveat(bin_fd, "", argv, env, AtFlag.EMPTY_P= ATH) + 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 =3D signal.SIGTERM) -> None: + self.rns.kill(sig) + + def wait(self, nohang: bool =3D False) -> WaitResult: + return self.rns.wait(os.WNOHANG if nohang else 0) + + def close(self) -> None: + self.root_dfd =3D self._close_fd(self.root_dfd) + self.mntns_fd =3D self._close_fd(self.mntns_fd) + self.rns.close() diff --git a/tools/testing/selftests/userland/userland_test.py b/tools/test= ing/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] =3D os.path.realpath(sys.executable) +SKIP_ERRNOS: Final[tuple[int, ...]] =3D ( + errno.ENOSYS, + errno.EPERM, + errno.EACCES, + errno.EINVAL, + errno.ENOSPC, +) + + +@dataclass(frozen=3DTrue) +class Payload: + code: str + + def argv(self) -> list[str]: + return [PYTHON_BIN, "-S", "-c", self.code] + + +WAIT_MOUNT_PAYLOAD: Final[Payload] =3D Payload( + """\ +import os +import sys +import time + +if os.getpid() !=3D 1: + sys.exit(1) +deadline =3D 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() =3D=3D b"ok\\n" else 2) + time.sleep(0.02) +sys.exit(3) +""" +) + +WRITE_MOUNT_PAYLOAD: Final[Payload] =3D 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] =3D Payload( + """\ +import signal + +signal.pause() +""" +) + + +@dataclass(frozen=3DTrue) +class ProbeResult: + supported: bool + reason: str =3D "" + + +@dataclass +class SyncPipe: + r_fd: int + w_fd: int + + @classmethod + def create(cls) -> SyncPipe: + r_fd, w_fd =3D os.pipe2(os.O_CLOEXEC) + return cls(r_fd=3Dr_fd, w_fd=3Dw_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 >=3D 0: + os.close(self.r_fd) + self.r_fd =3D -1 + + def close_write(self) -> None: + if self.w_fd >=3D 0: + os.close(self.w_fd) + self.w_fd =3D -1 + + def close(self) -> None: + self.close_read() + self.close_write() + + def read_bytes(self, n: int =3D 1) -> bytes: + return os.read(self.r_fd, n) + + def read_all(self) -> bytes: + chunks: list[bytes] =3D [] + while True: + chunk =3D os.read(self.r_fd, 4096) + if not chunk: + break + chunks.append(chunk) + return b"".join(chunks) + + def write_bytes(self, data: bytes =3D b"1") -> None: + os.write(self.w_fd, data) + + def wait_in_child(self, exit_code: int =3D 0) -> int: + self.close_write() + self.read_bytes() + self.close_read() + return exit_code + + +@dataclass(frozen=3DTrue) +class NsTypeCase: + name: str + nstype: CloneFlag + + +@dataclass(frozen=3DTrue) +class BadCloneCase: + name: str + flags: CloneFlag + exit_signal: int =3D int(signal.SIGCHLD) + expected_errno: int =3D errno.EINVAL + + +@dataclass(frozen=3DTrue) +class SignalCase: + name: str + sig: int + expected_errno: int + + +NS_TYPE_CASES: Final[tuple[NsTypeCase, ...]] =3D ( + 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, ...]] =3D ( + 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=3D0, + ), + BadCloneCase("parent", CloneFlag.PARENT, exit_signal=3D0), + BadCloneCase("sysvsem", CloneFlag.SYSVSEM), + BadCloneCase("vm", CloneFlag.VM), + BadCloneCase("vm_vfork", CloneFlag.VM | CloneFlag.VFORK), +) + +BAD_SIGNAL_CASES: Final[tuple[SignalCase, ...]] =3D ( + 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 =3D 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 !=3D 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() =3D=3D 0: + return + uid =3D os.geteuid() + gid =3D 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 =3D 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 =3D rns.make_mount("tmpfs") + except OSError as exc: + return ProbeResult(False, f"userland setup unavailable: {e= xc}") + with cls.closing_fd(mfd): + os.mkdir("probe", 0o755, dir_fd=3Dmfd) + return ProbeResult(True) + + def run_forked(self, fn: Callable[[], None]) -> None: + with SyncPipe.create() as pipe: + sys.stdout.flush() + sys.stderr.flush() + pid =3D os.fork() + if pid =3D=3D 0: + pipe.close_read() + try: + fn() + except unittest.SkipTest as exc: + payload =3D json.dumps({"kind": "skip", "msg": str(exc= )}) + pipe.write_bytes(payload.encode("utf-8")) + pipe.close_write() + os._exit(0) + except BaseException: + payload =3D 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 =3D pipe.read_all() + code =3D self.reap_exit_code(pid) + if raw: + info =3D json.loads(raw.decode("utf-8")) + if info["kind"] =3D=3D "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 =3D socket.socketpair( + socket.AF_UNIX, socket.SOCK_SEQPACKET + ) + sys.stdout.flush() + sys.stderr.flush() + pid =3D os.fork() + if pid =3D=3D 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] =3D [] + try: + rlist, _, _ =3D select.select([s_parent], [], [], 5.0) + if rlist: + _, fds, _, _ =3D socket.recv_fds(s_parent, 1, 1) + finally: + s_parent.close() + code =3D self.reap_exit_code(pid) + if code !=3D 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 =3D self.probe_pre_idmap_mkdir() + self.cell =3D None + if self.probe.supported: + cell =3D Cell("test") + try: + cell.setup_rootfs( + dirs=3D("proc", "tmp", "mnt"), mount_procfs=3DTrue + ) + except BaseException: + cell.close() + raise + self.cell =3D 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=3DTrue, host_runtime=3DTrue) + pid =3D cell.spawn(WAIT_MOUNT_PAYLOAD.argv()) + self.assertGreater(pid, 0) + cell.mount_fs("tmpfs", "/mnt") + cell.spawn(WRITE_MOUNT_PAYLOAD.argv()) + res =3D 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=3DTrue, host_runtime=3DTrue) + cell.spawn(PAUSE_PAYLOAD.argv()) + cell.spawn(PAUSE_PAYLOAD.argv()) + cell.kill(signal.SIGKILL) + res =3D 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 =3D 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=3Dcase.name): + try: + nsfd =3D rns.get_nsfd(case.nstype) + except OSError as exc: + if ( + case.nstype =3D=3D CloneFlag.NEWTIME + and exc.errno =3D=3D 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 =3D 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 =3D ( + 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 =3D f"/proc/self/ns/{case.name}" + if not os.path.exists(ns_path): + continue + with self.subTest(ns=3Dcase.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 =3D os.fstat(host_fd) + orig_st =3D 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 =3D 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=3Drootfd) + 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 =3D 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_CLOEXE= C) + ) as host_net_fd, + ): + + def check_inside_shared() -> int: + hold.close_write() + st =3D os.stat("/proc/self/ns/net") + ok =3D (st.st_dev, st.st_ino) =3D=3D ( + host_net_st.st_dev, + host_net_st.st_ino, + ) + hold.read_bytes() + hold.close_read() + return 0 if ok else 1 + + pid =3D 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] =3D [] + + 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=3Drace= _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 !=3D errno.ECHILD: + raise + try: + race_rns.kill(0) + except OSError as exc: + if exc.errno !=3D errno.ESRCH: + raise + except BaseException as exc: + errs.append(exc) + + t1 =3D threading.Thread(target=3Dshare_worker) + t2 =3D threading.Thread(target=3Dreader_worker) + t1.start() + t2.start() + t1.join() + t2.join() + self.assertEqual(errs, []) + + if os.geteuid() =3D=3D 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 =3D 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 =3D self._require_cell() + rns =3D 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 =3D 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 =3D 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 =3D 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 =3D poller.poll(5000) + self.assertTrue(any(ev & select.POLLHUP for _, ev in event= s)) + ep1_ev =3D ep1.poll(5.0) + ep2_ev =3D 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 =3D 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 =3D self._require_cell() + rns =3D 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=3D1) + self.assertEqual(cm.exception.errno, errno.EINVAL) + + siginfo_buf =3D 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=3Dcase.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 =3D os.fork() + if gc =3D=3D 0: + ready.write_bytes(b"r") + ready.close_write() + signal.pause() + os._exit(0) + ready.close_write() + signal.pause() + return 0 + + pid1 =3D rns.run(init_proc) + pid2 =3D 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=3DUserlandFlag.DEFAULT) as cell2: + cell2.setup_rootfs(mount_procfs=3DFalse) + pid_koc =3D 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 =3D self._require_cell() + cell.mount_fs("tmpfs", "mnt") + + def inside() -> int: + if os.getpid() !=3D 1: + return 1 + pids =3D [e for e in os.listdir("/proc") if e.isdigit()] + if pids !=3D ["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 =3D cell.rns.run(inside) + res =3D 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 =3D 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 =3D 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_CLOE= XEC + ) + ) 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() =3D=3D 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_M= NTNS, + ) + 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=3Drns.fd) + with self.assertRaises(OSError) as cm: + Sys.fsconfig(fsfd, FsconfigCmd.SET_USERLAND, aux=3Drns= .fd) + self.assertEqual(cm.exception.errno, errno.EBUSY) + + if os.geteuid() =3D=3D 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=3Drns.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.CLON= E, + ) + self.assertEqual(cm_nu.exception.errno, errno.EINV= AL) + + 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 tf= d: + os.mkdir("sub", 0o755, dir_fd=3Dtfd) + 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 =3D 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 =3D os.fork() + if spid =3D=3D 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=3Dm_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() !=3D 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 !=3D 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, _, _ =3D 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_M= NTNS, + ) + 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=3Drns.f= d) + with self.assertRaises(OSError) as cm: + Sys.fsconfig( + p_fsfd, + FsconfigCmd.SET_STRING, + key=3D"pidns", + value=3D"/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=3D= rns.fd + ) + self.assertEqual(cm_set.exception.errno, errno.EIN= VAL) + 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=3Drfd) + os.mkdir("prop_mnt", 0o755, dir_fd=3Drfd) + 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 !=3D errno.EINVAL: + return 2 + Sys.set_mount_propagation( + "/", MountFlag.REC | MountFlag.SHARED + ) + peer =3D os.fork() + if peer =3D=3D 0: + os.unshare(CloneFlag.NEWNS) + prop_ready.write_bytes(b"p") + prop_ready.close_write() + if prop_go.read_bytes() !=3D 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 =3D=3D errno.EINVAL el= se 6) + prop_ready.close_write() + prop_go.close_read() + return self.reap_exit_code(peer) + + p_lock =3D 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_n= s"): + os.close( + os.open( + fname, + os.O_CREAT | os.O_WRONLY | os.O_CLOEXE= C, + 0o600, + dir_fd=3Dtfd, + ) + ) + Sys.move_mount( + tfd, + "", + Sys.AT_FDCWD, + "/tmp", + MoveMountFlag.F_EMPTY_PATH, + ) + cpid =3D os.fork() + if cpid =3D=3D 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 =3D 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.CLON= E, + ) + finally: + hold.close_write() + self.assertEqual(self.reap_exit_code(cpid), 0) + + self.run_forked(check_clone_mntns_loop) + + if os.geteuid() =3D=3D 0: + u_rns =3D 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 f= sfd2: + with self.assertRaises(OSError) as cm_fs: + Sys.fsconfig( + fsfd2, + FsconfigCmd.SET_USERLAND, + aux=3Du_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 =3D self._require_cell() + rns =3D 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=3Dint(signal.SIGCHLD) + ) + self.assertEqual(cm.exception.errno, errno.EINVAL) + + args =3D CloneArgs( + flags=3Dint(CloneFlag.INTO_USERLAND), + exit_signal=3Dint(signal.SIGCHLD), + userland=3Drns.fd, + ) + with self.assertRaises(OSError) as cm: + Sys.clone3(args, size=3DCloneArgs.SIZE_VER2) + self.assertEqual(cm.exception.errno, errno.EINVAL) + + for case in BAD_CLONE_CASES: + with self.subTest(flag=3Dcase.name): + with self.assertRaises(OSError) as cm: + rns.clone_into( + extra_flags=3Dcase.flags, + exit_signal=3Dcase.exit_signal, + ) + self.assertEqual(cm.exception.errno, case.expected_errno) + + allowed =3D ( + CloneFlag.VFORK + | CloneFlag.PIDFD + | CloneFlag.CLEAR_SIGHAND + | CloneFlag.NNP + ) + old_umask =3D os.umask(0o077) + try: + Sys.prctl(PrctlOp.SET_DUMPABLE, 1) + pid, pidfd =3D rns.clone_into(extra_flags=3Dallowed) + if pid =3D=3D 0: + cur_umask =3D os.umask(0o022) + dumpable =3D Sys.prctl(PrctlOp.GET_DUMPABLE) + ok =3D ( + os.getpid() =3D=3D 1 + and Sys.prctl(PrctlOp.GET_NO_NEW_PRIVS) =3D=3D 1 + and cur_umask =3D=3D 0o077 + and dumpable !=3D 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=3DFalse) + + 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 =3D socket.socketpair( + socket.AF_UNIX, socket.SOCK_SEQPACKET + ) + p1 =3D os.fork() + if p1 =3D=3D 0: + s_p.close() + try: + os.unshare(CloneFlag.NEWPID) + p2 =3D os.fork() + if p2 =3D=3D 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, _, _ =3D 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 m= fd, + 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 =3D self._require_cell() + rns =3D cell.rns + with ( + SyncPipe.create() as start, + SyncPipe.create() as ready, + SyncPipe.create() as init_gate, + SyncPipe.create() as peer_gate, + ): + workers: list[int] =3D [] + for idx in range(4): + wpid =3D os.fork() + if wpid =3D=3D 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 =3D idx) -> int: + my_pid =3D os.getpid() + ready.write_bytes(bytes([worker_idx, my_pid])) + ready.close_write() + gate =3D init_gate if my_pid =3D=3D 1 else peer_ga= te + gate.read_bytes() + init_gate.close_read() + peer_gate.close_read() + return 0 + + cpid =3D rns.run(entrant) + ready.close_write() + init_gate.close_read() + peer_gate.close_read() + os._exit(0 if self.reap_exit_code(cpid) =3D=3D 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] =3D set() + init_idx =3D -1 + for _ in range(4): + msg =3D ready.read_bytes(2) + self.assertEqual(len(msg), 2) + if msg[1] =3D=3D 1: + init_idx =3D 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 !=3D 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 =3D 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 =3D 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 mf= d: + os.mkdir("old_root", 0o755, dir_fd=3Dmfd) + os.mkdir("sub", 0o755, dir_fd=3Dmfd) + with self.closing_fd( + os.open( + "pivoted", + os.O_CREAT | os.O_WRONLY | os.O_CLOEXEC, + 0o644, + dir_fd=3Dmfd, + ) + ): + 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 =3D 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 =3D 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 =3D os.fork() + if plain_pid =3D=3D 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_M= NTNS, + ) + 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=3D0, flags=3D0) + self.assertEqual(cm.exception.errno, errno.EINVAL) + + with self.assertRaises(OSError) as cm: + Sys.userns_set_idmap_raw( + userns_fd, 0, size=3DUsernsIdmap.SIZE_VER0, flags=3D0 + ) + self.assertEqual(cm.exception.errno, errno.EINVAL) + + with self.assertRaises(OSError) as cm: + Sys.set_userns_idmap( + userns_fd, + uid_extents=3D((0, os.geteuid(), 1),), + size=3DUsernsIdmap.SIZE_VER0 - 1, + ) + self.assertEqual(cm.exception.errno, errno.EINVAL) + + big_buf =3D ctypes.create_string_buffer(65536) + with self.assertRaises(OSError) as cm: + Sys.userns_set_idmap_raw( + userns_fd, ctypes.addressof(big_buf), size=3D65536 + ) + self.assertEqual(cm.exception.errno, errno.E2BIG) + + with self.assertRaises(OSError) as cm: + Sys.set_userns_idmap( + userns_fd, + uid_extents=3D((0, os.geteuid(), 1),), + flags=3D(~int(UsernsFlag.SETGROUPS_ALLOWED)) & 0xFFFFF= FFF, + ) + self.assertEqual(cm.exception.errno, errno.EINVAL) + + with self.assertRaises(OSError) as cm: + Sys.set_userns_idmap( + userns_fd, + uid_extents=3D((0, os.geteuid(), 1),), + flags=3DUsernsFlag.SETGROUPS_ALLOWED, + ) + self.assertEqual(cm.exception.errno, errno.EINVAL) + + with self.assertRaises(OSError) as cm: + Sys.set_userns_idmap( + userns_fd, + uid_extents=3D((0, os.geteuid(), 1),), + reserved=3D1, + ) + self.assertEqual(cm.exception.errno, errno.EINVAL) + + bad_req =3D UsernsIdmap(nr_uid_extents=3D1, uid_extents=3D0) + 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 =3D UsernsIdmap(nr_uid_extents=3D0, uid_extents=3D1) + 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=3D((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=3D((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=3D((0, os.geteuid(), 0),), + ) + self.assertEqual(cm.exception.errno, errno.EINVAL) + + can_allow_setgroups =3D ( + os.geteuid() =3D=3D 0 + and Path("/proc/self/setgroups").read_bytes() =3D=3D b"all= ow\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=3D((0, 0, 1),), + gid_extents=3D((0, 0, 1),), + flags=3DUsernsFlag.SETGROUPS_ALLOWED, + ) + with self.closing_fd(rns_sg.make_mount("tmpfs")) as sg= r: + os.mkdir("proc", 0o755, dir_fd=3Dsgr) + Sys.move_mount( + sgr, + "", + sg_mntns, + "/", + MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_M= NTNS, + ) + with self.closing_fd(rns_sg.make_mount("proc")) as sgp: + Sys.move_mount( + sgp, + "", + sg_mntns, + "proc", + MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_M= NTNS, + ) + + def verify_allow() -> int: + with open("/proc/self/setgroups", "rb") as f: + return 0 if f.read() =3D=3D b"allow\n" else 1 + + sg_pid =3D 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=3D((0, os.getegid(), 1),), + flags=3DUsernsFlag.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=3D((0, 0, 1),)) + with self.assertRaises(OSError) as cm: + rns.set_idmap(projid_extents=3D((0, 0, 1),)) + self.assertEqual(cm.exception.errno, errno.EPERM) + else: + with self.assertRaises(OSError) as cm: + rns.set_idmap(projid_extents=3D((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=3Drootfd) + 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() !=3D 0 or os.getegid() !=3D 0: + return 1 + with open("/proc/self/setgroups", "rb") as f: + if f.read() !=3D b"deny\n": + return 2 + return 0 + + pid =3D rns.run(verify_idmap) + res =3D 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() !=3D 0: + self.skipTest("uidmapd delegation test requires root") + + rns1 =3D self.create_userland_as_uid(1000) + rns2 =3D 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 =3D socket.socketpair( + socket.AF_UNIX, socket.SOCK_SEQPACKET + ) + alice_pid =3D os.fork() + if alice_pid =3D=3D 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, _, _ =3D 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_f= d, + ): + s_m1, s_m2 =3D socket.socketpair( + socket.AF_UNIX, socket.SOCK_SEQPACKET + ) + mal_pid =3D os.fork() + if mal_pid =3D=3D 0: + s_m1.close() + try: + self.drop_to_uid(2000) + try: + Sys.set_userns_idmap( + alice_ufd, projid_extents=3D((0, 2000, 1),) + ) + os._exit(2) + except OSError as exc: + if exc.errno !=3D 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=3D((0, 2000, 1= ),) + ) + os._exit(4) + except OSError as exc: + if exc.errno !=3D 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, _, _ =3D 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=3D((0, 1000, 1),), + ) + self.assertEqual(cm_bad.exception.errno, errno.EPE= RM) + + with self.assertRaises(OSError) as cm_root: + Sys.set_userns_idmap( + alice_ufd, + uid_extents=3D((0, 0, 1),), + ) + self.assertEqual(cm_root.exception.errno, errno.EP= ERM) + + with self.assertRaises(OSError) as cm_mal_p: + Sys.set_userns_idmap( + mallory_ufd, projid_extents=3D((0, 1000, 1= ),) + ) + self.assertEqual(cm_mal_p.exception.errno, errno.E= PERM) + + Sys.set_userns_idmap( + alice_ufd, + uid_extents=3D((0, 1000, 1), (1, 2000, 1)), + gid_extents=3D((0, 1000, 1), (1, 2000, 1)), + projid_extents=3D((0, 1000, 1),), + flags=3DUsernsFlag.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() =3D=3D 1 and os.getegid() =3D= =3D 1 else 1 + + pid =3D rns1.run(switch_subuid) + res =3D 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() =3D=3D 0: + try: + self.drop_to_uid(1000) + except OSError as exc: + if exc.errno =3D=3D 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 =3D 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.EPER= M) + + 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 =3D Cell("unpriv", flags=3DUserlandFlag.DEFAULT) + except OSError as exc: + if exc.errno in SKIP_ERRNOS: + self.skipTest("unprivileged userland unavailable") + raise + + with ( + tempfile.TemporaryDirectory(prefix=3D"userland-unpriv-") a= s 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=3D("proc", "tmp", "mnt"), mount_procfs=3DTrue + ) + cell.bind_mount(hdir, "mnt") + + def unpriv_init() -> int: + if ( + os.getpid() !=3D 1 + or os.geteuid() !=3D 0 + or os.getegid() !=3D 0 + ): + return 1 + pids =3D [e for e in os.listdir("/proc") if e.isdigit(= )] + if pids !=3D ["1"]: + return 2 + with open("/mnt/hello", "rb") as hf: + if hf.read() !=3D b"unpriv-ok\n": + return 3 + try: + Sys.umount2("/mnt", UmountFlag.DETACH) + return 4 + except OSError as exc: + return 0 if exc.errno =3D=3D errno.EINVAL else 5 + + pid =3D cell.rns.run(unpriv_init) + res =3D 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 =3D ksft_mod + self._failed =3D 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 =3D "".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 =3D 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 =3D 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 =3D 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 =3D 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 =3D True + + +class KtapRunner: + @staticmethod + def _load_ksft() -> Any: + ksft_dir =3D 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 =3D None) -> NoReturn: + args =3D list(sys.argv[1:] if argv is None else argv) + loader =3D unittest.TestLoader() + module =3D sys.modules[__name__] + suite =3D ( + loader.loadTestsFromNames(args, module) + if args + else loader.loadTestsFromModule(module) + ) + ksft =3D cls._load_ksft() + total =3D suite.countTestCases() + ksft.print_header() + ksft.set_plan(total) + result =3D KtapTestResult(ksft) + suite.run(result) + ksft.print_cnts() + sys.stdout.flush() + counts: dict[str, int] =3D ksft.ksft_cnt + if counts["fail"] > 0: + code =3D int(ksft.KSFT_FAIL) + elif total =3D=3D 0 or (counts["pass"] =3D=3D 0 and counts["skip"]= > 0): + code =3D int(ksft.KSFT_SKIP) + else: + code =3D int(ksft.KSFT_PASS) + sys.exit(code) + + +if __name__ =3D=3D "__main__": + KtapRunner.main() --=20 2.47.3 From nobody Tue Nov 24 14:20:10 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376269; b=GnAIQjjOaur02wXZaElJigfRlUV5dJshy2HTaIgI+JUhLsen6RkIPtY9+OiCffMEaDoV /xLAvO1X6DG1okGnAPTy/viWZVo0kv6avvNbymC0Y58jXftdaRr54y0bNhoPNt1sy32mm DtWs/KO5I8w/JP06HLhIa0uHgvRBS4IYDk83IPRYPUSh33803ovMfoX2jaUm+7nBfio/k fjwUWLqfGvk+60mqUL4DagBlH3g/b+bUjw8jDnk1iWi9glMkeUSBWGcGDG7F1hTrvZOSH 6S8dRaKNXw+itfMtY+kgSzO9QTbjpPxRbwRYiBT6W8VVIKQaCjIM/Fky2o1D4n7/hZg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376269; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=c/grzABhgrBQ8/IrA5G6GcEKHy2OSZTwhNr0CPP3+U4=; b=n7Aafw7dtvjp/NZMfdX9RLQK1QCayVqAxwbOzf4+eLa3Uv+7G1UxX60dilhkHJh0NjDN 0ADqbyDwK3O0wrRpMk8rTdAdz27KYYCYWAQvgLXq5S78mxyeFjG/ePktGRiPx24dCqJyV nww4ZsW9VOQ4nWf/dO+zX8rFdVBQNM57lh6nOmPVKGjLw7SoDcq/6fLC7KcxHdh2aE95M 6fQGRmzhGltUr2IE0KZp6Br4q2pn9hk+nz5ON6E946Ue2vx75yN+vX73ZZgCqLS/oJSva 2LqHk3Fw2ySBB9LXuxHFfTjwF/CAFEgJrjxETloI0YtJ8Hiftu95QKHL2B+zm7KTtkg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=If6Azv7y; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id 3BAFC606A684; Sun, 22 Nov 2026 19:37:48 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=If6Azv7y Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id E59221F000D1; Sun, 22 Nov 2026 19:37:47 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1795376268; bh=c/grzABhgrBQ8/IrA5G6GcEKHy2OSZTwhNr0CPP3+U4=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=If6Azv7y7srTCn6OR0qdqZQAwa1W7Gt05tNg4TPPtNZ0kqbU7S/HJIrOaVSbu5He2 UcQYGZyFJswbruL02XotkP5Qo0sAiLgKUKGIQ8Gi8yiHFaR9w9q4Wx7olOPpVQs/Ky A9rTDmfwXa5kKjKsqhuSfUcv8eeNDe3A2PZuK0tdgw2gon96AVqaD6syspi5fkJ3Wo ScgOoGL5gTQFoAfLmxdcLAxxx/Ypx7zjqXVJyKlTiTYDeVpD48x/RK33TjzOrp5rLO ANINvuVSa4Z5EmpoCFu4ML34znZVg9/tvfMwXoQWObjGP9ozyW5Vp36n4R0Za6rYTG k9ENPgWMMUgug== From: Jarkko Sakkinen To: linux-fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, 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 Subject: [RFC PATCH v7 26/26] MAINTAINERS: Add entry for USERLAND Date: Sun, 22 Nov 2026 21:35:39 +0200 Message-ID: <20261122193539.3334213-27-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261122193539.3334213-1-jarkko@kernel.org> References: <20261122193539.3334213-1-jarkko@kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Record maintainership and mailing list routing for userlands across their uAPI headers, core implementation, documentation, and selftests. Signed-off-by: Jarkko Sakkinen --- 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/ =20 +USERLAND +M: David Howells +M: Jarkko Sakkinen +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 L: linux-block@vger.kernel.org --=20 2.47.3