[RFC PATCH v5 08/25] userns: Factor out install_user_ns_cred()

From: Jarkko Sakkinen

Date: Fri Nov 20 2026 - 19:10:12 EST


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

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

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

diff --git a/include/linux/user_namespace.h b/include/linux/user_namespace.h
index 91232053775d..3600a903442e 100644
--- a/include/linux/user_namespace.h
+++ b/include/linux/user_namespace.h
@@ -184,6 +184,7 @@ static inline struct user_namespace *get_user_ns(struct user_namespace *ns)
}

extern int create_user_ns(struct cred *new);
+int install_user_ns_cred(struct cred *cred, struct user_namespace *user_ns);
extern int unshare_userns(unsigned long unshare_flags, struct cred **new_cred);
extern void __put_user_ns(struct user_namespace *ns);

@@ -226,6 +227,12 @@ static inline int create_user_ns(struct cred *new)
return -EINVAL;
}

+static inline int install_user_ns_cred(struct cred *cred,
+ struct user_namespace *user_ns)
+{
+ return -EINVAL;
+}
+
static inline int unshare_userns(unsigned long unshare_flags,
struct cred **new_cred)
{
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index d7f2cad388c8..4cf5d802032c 100644
--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -1632,6 +1632,13 @@ static void userns_put(struct ns_common *ns)
put_user_ns(to_user_ns(ns));
}

+int install_user_ns_cred(struct cred *cred, struct user_namespace *user_ns)
+{
+ put_user_ns(cred->user_ns);
+ set_cred_user_ns(cred, get_user_ns(user_ns));
+ return set_cred_ucounts(cred);
+}
+
static int userns_install(struct nsset *nsset, struct ns_common *ns)
{
struct user_namespace *user_ns = to_user_ns(ns);
@@ -1657,10 +1664,7 @@ static int userns_install(struct nsset *nsset, struct ns_common *ns)
if (!cred)
return -EINVAL;

- put_user_ns(cred->user_ns);
- set_cred_user_ns(cred, get_user_ns(user_ns));
-
- if (set_cred_ucounts(cred) < 0)
+ if (install_user_ns_cred(cred, user_ns) < 0)
return -EINVAL;

return 0;
--
2.47.3