userns: per-namespace capability bounding set and opt-in netns loopback
Subsystems (13)
cover userns: per-namespace capability bounding set and opt-in netns loopback
When an unprivileged process creates a new user namespace, it is granted a full set of capabilities (CAP_FULL_SET) scoped to that namespace. While these capabilities are isolated to the namespace, they allow unprivileged local users to reach deep kernel subsystems (most notably networking configuration and raw sockets via CAP_NET_ADMIN and CAP_NET_RAW) that historically assumed a trusted caller and have accounted for a large share of local privilege escalation vulnerabilities.
Many workloads and sandboxes use unprivileged user namespaces strictly for basic UID/GID, mount, PID, or network isolation and never need high-risk capabilities like CAP_NET_ADMIN or CAP_NET_RAW. Likewise, system administrators often want a host-wide policy ceiling restricting which capabilities unprivileged user namespaces may acquire, without disabling unprivileged user namespaces altogether.
Prior work by Jonathan Calmels [1] proposed addressing this via a sixth per-thread capability set (cap_userns) alongside a global sysctl mask. During that discussion [1, 2], feedback (e.g. from Casey Schaufler) suggested that rather than adding another per-thread capability set and prctl() interface, capability restrictions could be integrated directly into struct user_namespace and configured via clone3(). At the same time, as noted in [1], a clone3() flag alone is not sufficient for administrators who need to enforce a host-wide ceiling on unprivileged user namespaces without modifying every userspace callsite.
This series combines both pieces of feedback: it embeds a capability bounding set (cap_bset) directly into struct user_namespace, reusing the existing task cap_bset, cap_permitted, and cap_effective sets on namespace entry, and provides both a system-wide sysctl ceiling for unprivileged user namespaces and a CLONE_NEWUSER_BSET flag for voluntary per-namespace restriction via clone3().
In addition, because restricting CAP_NET_ADMIN at user namespace creation time prevents userspace from bringing up the loopback interface in new network namespaces, the series first introduces an opt-in flag to automatically enable loopback on network namespace creation:
1. Opt-in loopback activation on netns creation (Patch 1)
New network namespaces start with the loopback interface (lo) DOWN by default, requiring CAP_NET_ADMIN over the owning user namespace to bring it up. To block external network access while preserving localhost networking, sandboxes commonly create an isolated network namespace with only the loopback interface enabled.
However, requiring a sandbox to hold CAP_NET_ADMIN in a new user namespace solely to bring loopback up conflicts with reducing the CAP_NET_ADMIN attack surface. Today, an unprivileged sandbox must start with CAP_NET_ADMIN to bring loopback up, drop it, and then block CAP_NET_ADMIN from being regained in nested user namespaces (e.g. via seccomp or max_user_namespaces limits). Conversely, when CAP_NET_ADMIN is restricted at user namespace creation time (via the sysctl ceiling or CLONE_NEWUSER_BSET introduced in Patches 2-3, or via LSMs such as Landlock), tasks inside the new namespace never acquire CAP_NET_ADMIN and cannot bring loopback up from userspace, breaking localhost networking for unprivileged sandboxes.
Introduce the CLONE_NEWNET_LOOPBACK flag for clone3() and the corresponding UNSHARE_NEWNET_LOOPBACK flag for unshare(), which imply CLONE_NEWNET and automatically bring the loopback device up in copy_net_ns() before returning the new network namespace. Making this an explicit opt-in preserves default network namespace semantics while allowing unprivileged sandboxes to create an isolated network namespace with functional localhost networking without ever holding CAP_NET_ADMIN.
2. Per-user-namespace capability bounding set & sysctl ceiling (Patch 2)
Add cap_bset to struct user_namespace (initialized to CAP_FULL_SET in init_user_ns) and introduce a system-wide sysctl ceiling for unprivileged users at:
/proc/sys/kernel/unprivileged_userns_caps_allowed
(defaulting to CAP_FULL_SET).
When a new user namespace is created:
- Privileged creators (holding CAP_SYS_ADMIN in the parent user namespace) inherit cap_bset from the parent user namespace.
- Unprivileged creators (lacking CAP_SYS_ADMIN in the parent user namespace) have the child namespace's bounding set constrained by the sysctl ceiling combined with any effective capabilities the creator already holds in the parent namespace:
child_bset = parent_bset & (sysctl_ceiling | creator_effective)
Allowing the creator to retain capabilities it already holds in the parent namespace ensures that a process granted a specific capability (e.g. CAP_NET_ADMIN) does not lose it when creating a nested user namespace.
When a task enters a user namespace via clone()/unshare() or setns(), its cap_bset, cap_permitted, and cap_effective sets are clamped to user_ns->cap_bset. In addition, cap_capable_helper() is updated so that implicit capabilities granted to the parent-namespace owner of a user namespace are likewise bounded by the owned namespace's cap_bset.
3. Per-namespace restriction via clone3() (Patch 3)
Introduce CLONE_NEWUSER_BSET and add cap_bset to struct clone_args. When specified alongside CLONE_NEWUSER, the new user namespace's bounding set is further intersected with the requested cap_bset mask, allowing container runtimes and sandboxes to drop unneeded capabilities from a user namespace at creation time even when permitted by the global sysctl.
4. Introspection via NS_USER_GET_INFO (Patch 4)
While tasks inside a user namespace see their initial ceiling in /proc/<pid>/status (CapBnd), threads may subsequently drop individual capabilities from their per-thread bounding set. Add an extensible NS_USER_GET_INFO ioctl on userns file descriptors to allow userspace to directly query a user namespace's cap_bset.
5. Selftests (Patches 5-8)
Add kselftest suites covering CLONE_NEWNET_LOOPBACK, the sysctl ceiling, creator capability retention, nested monotonicity, parent-owner bounding, CLONE_NEWUSER_BSET and NS_USER_GET_INFO.
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lwn.net/Articles/978846/
Note on tree routing:
While Patch 1 (CLONE_NEWNET_LOOPBACK) touches net/core/net_namespace.c, most of its changes add clone3()/unshare() flag plumbing in include/uapi/linux/sched.h, kernel/fork.c, and kernel/nsproxy.c, which Patch 3 (CLONE_NEWUSER_BSET) builds directly on top of. To avoid merge conflicts in kernel/fork.c and include/uapi/linux/sched.h, it may be simplest to route the entire series through a single tree, e.g. a namespace branch in vfs.git with Acked-by from the netdev and capabilities/credentials maintainers, or whichever tree the maintainers prefer.
Hallgrimur H. Gunnarsson (8):
net: introduce CLONE_NEWNET_LOOPBACK to auto-enable loopback
userns: introduce capability bounding set for user namespaces
userns: allow restricting capability bounding set via clone3()
nsfs: add NS_USER_GET_INFO ioctl to inspect user namespace
capabilities
selftests/net: add test suite for CLONE_NEWNET_LOOPBACK selftests/capabilities: tests for user namespace capability bounding
set
selftests/capabilities: add clone3() tests for CLONE_NEWUSER_BSET selftests/nsfs: add tests for NS_USER_GET_INFO ioctl
Documentation/admin-guide/sysctl/kernel.rst | 37 ++ fs/nsfs.c | 29 + include/linux/cred.h | 3 +- include/linux/sched/task.h | 1 + include/linux/user_namespace.h | 20 +- include/uapi/linux/nsfs.h | 17 + include/uapi/linux/sched.h | 9 + kernel/cred.c | 10 +- kernel/fork.c | 38 +- kernel/nsproxy.c | 9 + kernel/user.c | 1 + kernel/user_namespace.c | 100 +++- net/core/net_namespace.c | 11 + security/commoncap.c | 8 +- .../testing/selftests/capabilities/.gitignore | 1 + tools/testing/selftests/capabilities/Makefile | 2 +- .../capabilities/userns_bounding_set_test.c | 566 ++++++++++++++++++ .../selftests/clone3/clone3_selftests.h | 1 + .../selftests/filesystems/nsfs/.gitignore | 1 + .../selftests/filesystems/nsfs/Makefile | 4 +- .../selftests/filesystems/nsfs/userns.c | 120 ++++ tools/testing/selftests/net/.gitignore | 1 + tools/testing/selftests/net/Makefile | 1 + tools/testing/selftests/net/loopback_netns.c | 103 ++++ 24 files changed, 1069 insertions(+), 24 deletions(-) create mode 100644 tools/testing/selftests/capabilities/userns_bounding_set_test.c create mode 100644 tools/testing/selftests/filesystems/nsfs/userns.c create mode 100644 tools/testing/selftests/net/loopback_netns.c
base-commit: cee9395acd8043be0644b25c34bfa86623f2b935
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH 1/8 net: introduce CLONE_NEWNET_LOOPBACK to auto-enable loopback
New network namespaces start with the loopback interface DOWN by default, requiring CAP_NET_ADMIN over the owning user namespace to bring it up.
To block external network access while preserving the localhost networking that many applications expect, sandboxes (such as bwrap, nsjail and minijail) commonly create an isolated network namespace with only the loopback interface enabled.
However, requiring a sandbox to hold CAP_NET_ADMIN in a new user namespace solely to bring loopback up conflicts with reducing the CAP_NET_ADMIN attack surface.
Today, an unprivileged sandbox or sandbox manager must start with CAP_NET_ADMIN in its user namespace to be able to bring up loopback, drop it, and then take precautions to block CAP_NET_ADMIN from being regained in nested user namespaces (e.g. via seccomp or max_user_namespaces limits). This adds considerable complexity just to bring up loopback.
Conversely, if CAP_NET_ADMIN is restricted at user namespace creation time, tasks inside the new namespace never acquire CAP_NET_ADMIN. While this removes the CAP_NET_ADMIN attack surface down the namespace hierarchy, it also prevents userspace from bringing loopback up, breaking localhost networking for unprivileged sandboxes.
Introduce the CLONE_NEWNET_LOOPBACK flag for clone3() and the corresponding UNSHARE_NEWNET_LOOPBACK flag for unshare(). When specified, each flag implies CLONE_NEWNET and automatically brings the loopback device up in copy_net_ns() before returning the new network namespace.
Making this an explicit opt-in preserves default network namespace semantics while allowing unprivileged sandboxes to create an isolated network namespace with functional localhost networking without ever holding CAP_NET_ADMIN.
--- include/uapi/linux/sched.h | 2 ++ kernel/fork.c | 22 ++++++++++++++++++---- kernel/nsproxy.c | 9 +++++++++ net/core/net_namespace.c | 11 +++++++++++ 4 files changed, 40 insertions(+), 4 deletions(-)
include/uapi/linux/sched.h +2 -0
@@ -40,6 +40,7 @@#define CLONE_NNP (1ULL << 35)/* Set no_new_privs on child. */ #define CLONE_PIDFD_AUTOKILL (1ULL << 36)/* Kill child when clone pidfd closes. */ #define CLONE_EMPTY_MNTNS (1ULL << 37)/* Create an empty mount namespace. */ +#define CLONE_NEWNET_LOOPBACK (1ULL << 38)/* Create network namespace with loopback UP. */ /* * cloning flags intersect with CSIGNAL so can be used with unshare and clone3
@@ -52,6 +53,7 @@* unshare syscall: */ #define UNSHARE_EMPTY_MNTNS 0x00100000/* Unshare an empty mount namespace. */ +#define UNSHARE_NEWNET_LOOPBACK 0x00200000/* Unshare network namespace with loopback UP. */ #ifndef __ASSEMBLY__/**
kernel/fork.c +18 -4
@@ -2728,6 +2728,15 @@ pid_t kernel_clone(struct kernel_clone_args *args) args->flags = clone_flags; } +/* +* Set implied CLONE_NEWNET before copy_process() so that +* security_task_alloc() and other clone_flags checks see it. +*/ +if (clone_flags &CLONE_NEWNET_LOOPBACK ) { + clone_flags |=CLONE_NEWNET ; + args->flags = clone_flags; + } +/* * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
@@ -3010,7 +3019,8 @@ static bool clone3_args_valid(struct kernel_clone_args *kargs)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_NEWNET_LOOPBACK ))return false;/*
@@ -3160,9 +3170,10 @@ void __init proc_caches_init(void)*/ static int check_unshare_flags (unsigned long unshare_flags) { -if (unshare_flags & ~(CLONE_THREAD |CLONE_FS |CLONE_SIGHAND | -CLONE_VM |CLONE_FILES |CLONE_SYSVSEM | -CLONE_NS_ALL |UNSHARE_EMPTY_MNTNS )) +if (unshare_flags & ~(CLONE_THREAD |CLONE_FS |CLONE_SIGHAND | +CLONE_VM |CLONE_FILES |CLONE_SYSVSEM | +CLONE_NS_ALL |UNSHARE_EMPTY_MNTNS | +UNSHARE_NEWNET_LOOPBACK ))return -EINVAL ;/* * Not implemented, but pretend it works if there is nothing
@@ -3266,6 +3277,9 @@ int ksys_unshare(unsigned long unshare_flags)if (unshare_flags &CLONE_NEWNS ) unshare_flags |=CLONE_FS ; +if (unshare_flags &UNSHARE_NEWNET_LOOPBACK ) + unshare_flags |=CLONE_NEWNET ; +/* No unsharing with overriden fs state */ VFS_WARN_ON_ONCE (unshare_flags & (CLONE_NEWNS |CLONE_FS ) && current->fs != current->real_fs);
kernel/nsproxy.c +9 -0
@@ -231,6 +231,15 @@ int unshare_nsproxy_namespaces(unsigned long unshare_flags, flags |=CLONE_EMPTY_MNTNS ; } +/* +* Convert the 32-bit UNSHARE_NEWNET_LOOPBACK (which aliases +* CLONE_CHILD_CLEARTID) to the unique 64-bit CLONE_NEWNET_LOOPBACK. +*/ +if (flags &UNSHARE_NEWNET_LOOPBACK ) { + flags &= ~(u64 )UNSHARE_NEWNET_LOOPBACK ; + flags |=CLONE_NEWNET_LOOPBACK ; + } + *new_nsp =create_new_namespaces (flags, current, user_ns, new_fs ? new_fs : current->fs);if (IS_ERR (*new_nsp)) {
net/core/net_namespace.c +11 -0
@@ -596,6 +596,17 @@ struct net *copy_net_ns(u64 flags,dec_net_namespaces (ucounts);return ERR_PTR (rv); } + +if (flags &CLONE_NEWNET_LOOPBACK ) { +rtnl_net_lock (net); + rv =dev_open (net->loopback_dev,NULL ); +rtnl_net_unlock (net); +if (rv <0 ) { +put_net (net); +return ERR_PTR (rv); + } + } +return net; }
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH 2/8 userns: introduce capability bounding set for user namespaces
In reply to Hallgrimur H. GunnarssonWhen an unprivileged process creates a new user namespace, it receives a full set of capabilities scoped to that new namespace.
While these capabilities are isolated to the namespace, they allow unprivileged tasks to interact with deep kernel code (like networking logic) that historically assumed only a fully trusted root user could access them. Depending on the workload, administrators may not always want or need to grant every capability to unprivileged namespaces.
To provide administrators with flexible policy control over what privileges are permitted by default, introduce a per-user-namespace capability bounding set (cap_bset) and a global sysctl ceiling knob at:
/proc/sys/kernel/unprivileged_userns_caps_allowed
When a new user namespace is created, it inherits the capability bounding set of its parent namespace. For an unprivileged creator (i.e. a task lacking CAP_SYS_ADMIN in the parent namespace), the child namespace's bounding set is constrained by intersecting the parent's bounding set with the sysctl ceiling combined with any effective capabilities the creator already holds:
child_bset = parent_bset & (sysctl_ceiling | creator_effective)
Capability bounding sets decrease monotonically down the namespace hierarchy, ensuring child namespaces can never exceed the capabilities of their ancestors.
Upon entering a user namespace during creation or via setns, the task's permitted, effective, and bounding capability sets are clamped to the namespace's bounding set. Furthermore, cap_capable_helper() is updated so that implicit capabilities granted to parent-namespace owners over child namespaces are strictly bounded by the owned namespace's cap_bset.
The sysctl defaults to CAP_FULL_SET, preserving baseline backwards compatibility and existing behavior unless an administrator explicitly configures a restricted ceiling.
--- Documentation/admin-guide/sysctl/kernel.rst | 32 +++++++ include/linux/user_namespace.h | 16 ++++ kernel/user.c | 1 + kernel/user_namespace.c | 93 +++++++++++++++++++-- security/commoncap.c | 8 +- 5 files changed, 142 insertions(+), 8 deletions(-)
Documentation/admin-guide/sysctl/kernel.rst +32 -0
@@ -1690,6 +1690,38 @@ entry will default to 2 instead of 0. = ============================================================= +unprivileged_userns_caps_allowed +================================ + +This file contains a hexadecimal bitmask representing the capability bounding +ceiling enforced on unprivileged user namespace creation. Instead of granting +full capabilities upon namespace creation, this ceiling can be used to +configure which capabilities are permitted. + +When an unprivileged task (a task lacking ``CAP_SYS_ADMIN`` in its parent user +namespace) creates a new user namespace, the capability bounding set of the +new namespace is intersected with the union of this mask and the creator's +effective capabilities in the parent namespace: + + child_bset = parent_bset & (sysctl_ceiling | creator_effective) + +Privileged creators (holding ``CAP_SYS_ADMIN`` in the parent namespace) are +unaffected by this ceiling and inherit the parent namespace's bounding set +unmodified. + +Upon entering a user namespace during creation or via ``setns(2)``, +the task's permitted, effective, and bounding capability sets are clamped +to the namespace's bounding set. Tasks inside the namespace cannot exceed +this ceiling, even when executing setuid binaries or binaries with file +capabilities. + +Unknown capability bits (above ``CAP_LAST_CAP``) are ignored and masked +off when writing to this file. + +* Default: ``CAP_FULL_SET`` (all capabilities permitted) +* Privilege required to modify: ``CAP_SETPCAP`` in the initial user namespace. + + warn_limit ==========
include/linux/user_namespace.h +16 -0
@@ -3,6 +3,7 @@#define _LINUX_USER_NAMESPACE_H#include <linux/kref.h> +#include <linux/capability.h> #include <linux/nsproxy.h> #include <linux/ns_common.h> #include <linux/rculist_nulls.h>
@@ -89,6 +90,11 @@ struct user_namespace {/* parent_could_setfcap: true if the creator if this ns had CAP_SETFCAP * in its effective capability set at the child ns creation time. */ bool parent_could_setfcap; +/* +* Capability bounding set for tasks inside the namespace and for owner +* tasks in the parent namespace. +*/ +kernel_cap_t cap_bset;#ifdef CONFIG_KEYS /* List of joinable keyrings in this namespace. Modification access of
@@ -183,6 +189,11 @@ static inline struct user_namespace *get_user_ns(struct user_namespace *ns)return ns; } +static inline bool userns_has_cap (const struct user_namespace *ns,int cap) +{ +return cap_raised (ns->cap_bset, cap); +} +extern int create_user_ns (struct cred *new);extern int unshare_userns (unsigned long unshare_flags,struct cred **new_cred);extern void __put_user_ns (struct user_namespace *ns);
@@ -214,6 +225,11 @@ static inline struct user_namespace *get_user_ns(struct user_namespace *ns)return &init_user_ns; } +static inline bool userns_has_cap (const struct user_namespace *ns,int cap) +{ +return true; +} +static inline int create_user_ns (struct cred *new) {return -EINVAL ;
kernel/user.c +1 -0
@@ -69,6 +69,7 @@ struct user_namespace init_user_ns = { .owner = GLOBAL_ROOT_UID, .group = GLOBAL_ROOT_GID, .flags = USERNS_INIT_FLAGS, + .cap_bset =CAP_FULL_SET , #ifdef CONFIG_KEYS .keyring_name_list =LIST_HEAD_INIT (init_user_ns.keyring_name_list), .keyring_sem = __RWSEM_INITIALIZER(init_user_ns.keyring_sem),
kernel/user_namespace.c +88 -5
129 lines not on this page · raw message
security/commoncap.c +5 -3
@@ -88,11 +88,13 @@ static inline int cap_capable_helper(const struct cred *cred,if (ns->level <= cred_ns->level)return -EPERM ; -/* +/* * The owner of the user namespace in the parent of the -* user namespace has all caps. +* user namespace has all caps, subject to the bounding +* set of the owned user namespace. */ -if ((ns->parent == cred_ns) &&uid_eq (ns->owner, cred->euid)) +if (ns->parent == cred_ns &&uid_eq (ns->owner, cred->euid) && +userns_has_cap (ns, cap))return 0 ;/*
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH 3/8 userns: allow restricting capability bounding set via clone3()
In reply to Hallgrimur H. GunnarssonWhile the unprivileged_userns_caps_allowed sysctl enforces a system-wide capability ceiling for unprivileged users, the clone3() support allows sandboxes and container runtimes to voluntarily restrict the capability bounding set of a new user namespace on a per-namespace basis.
Introduce the CLONE_NEWUSER_BSET flag and add a cap_bset field to struct clone_args (CLONE_ARGS_SIZE_VER3). When specified alongside CLONE_NEWUSER, the new user namespace's capability bounding set is intersected with cap_bset in addition to the parent namespace's bounding set and any applicable unprivileged sysctl ceiling.
--- Documentation/admin-guide/sysctl/kernel.rst | 5 +++++ include/linux/cred.h | 3 ++- include/linux/sched/task.h | 1 + include/linux/user_namespace.h | 4 ++-- include/uapi/linux/sched.h | 7 +++++++ kernel/cred.c | 10 ++++++++-- kernel/fork.c | 18 +++++++++++++++--- kernel/user_namespace.c | 11 +++++++---- 8 files changed, 47 insertions(+), 12 deletions(-)
Documentation/admin-guide/sysctl/kernel.rst +5 -0
@@ -1709,6 +1709,11 @@ Privileged creators (holding ``CAP_SYS_ADMIN`` in the parent namespace) are unaffected by this ceiling and inherit the parent namespace's bounding set unmodified. +Regardless of privilege level, a creator using ``clone3(2)`` with the +``CLONE_NEWUSER_BSET`` flag can further restrict the new namespace's +bounding set by specifying a ``cap_bset`` mask in ``struct clone_args``, +which is intersected with the resulting bounding set. + Upon entering a user namespace during creation or via ``setns(2)``, the task's permitted, effective, and bounding capability sets are clamped to the namespace's bounding set. Tasks inside the namespace cannot exceed
include/linux/cred.h +2 -1
@@ -19,6 +19,7 @@struct cred ;struct inode ; +struct kernel_clone_args ;extern struct task_struct init_task;
@@ -150,9 +151,9 @@ struct cred { }; } __randomize_layout; +int copy_creds (struct task_struct *p,const struct kernel_clone_args *kargs);extern void __put_cred (struct cred *);extern void exit_creds (struct task_struct *); -extern int copy_creds (struct task_struct *,u64 );extern const struct cred *get_task_cred (struct task_struct *);extern struct cred *cred_alloc_blank (void );extern struct cred *prepare_creds (void );
include/linux/sched/task.h +1 -0
@@ -45,6 +45,7 @@ struct kernel_clone_args {struct cgroup *cgrp;struct css_set *cset;unsigned int kill_seq; +u64 cap_bset; };/*
include/linux/user_namespace.h +2 -2
@@ -194,7 +194,7 @@ static inline bool userns_has_cap(const struct user_namespace *ns, int cap)return cap_raised (ns->cap_bset, cap); } -extern int create_user_ns (struct cred *new); +int create_user_ns (struct cred *new,kernel_cap_t req_bset);extern int unshare_userns (unsigned long unshare_flags,struct cred **new_cred);extern void __put_user_ns (struct user_namespace *ns);
@@ -230,7 +230,7 @@ static inline bool userns_has_cap(const struct user_namespace *ns, int cap)return true; } -static inline int create_user_ns (struct cred *new) +static inline int create_user_ns (struct cred *new,kernel_cap_t req_bset) {return -EINVAL ; }
include/uapi/linux/sched.h +7 -0
@@ -41,6 +41,7 @@#define CLONE_PIDFD_AUTOKILL (1ULL << 36)/* Kill child when clone pidfd closes. */ #define CLONE_EMPTY_MNTNS (1ULL << 37)/* Create an empty mount namespace. */ #define CLONE_NEWNET_LOOPBACK (1ULL << 38)/* Create network namespace with loopback UP. */ +#define CLONE_NEWUSER_BSET (1ULL << 39)/* Set userns capability bounding set. */ /* * cloning flags intersect with CSIGNAL so can be used with unshare and clone3
@@ -96,6 +97,10 @@* kernel's limit of nested PID namespaces. * @cgroup: If CLONE_INTO_CGROUP is specified set this to * a file descriptor for the cgroup. +* @cap_bset: If CLONE_NEWUSER_BSET is specified, this +* specifies the capability bounding set mask to +* apply to the new user namespace. Unknown +* capability bits (> CAP_LAST_CAP) are ignored. * * The structure is versioned by size and thus extensible. * New struct members must go at the end of the struct and
@@ -113,12 +118,14 @@ struct clone_args {__aligned_u64 set_tid;__aligned_u64 set_tid_size;__aligned_u64 cgroup; + __aligned_u64 cap_bset; };#endif #define CLONE_ARGS_SIZE_VER0 64/* sizeof first published struct */ #define CLONE_ARGS_SIZE_VER1 80/* sizeof second published struct */ #define CLONE_ARGS_SIZE_VER2 88/* sizeof third published struct */ +#define CLONE_ARGS_SIZE_VER3 96/* sizeof fourth published struct */ /* * Scheduling policies
kernel/cred.c +8 -2
@@ -260,8 +260,9 @@ 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,const struct kernel_clone_args *kargs) { +u64 clone_flags = kargs->flags;struct cred *new;int ret;
@@ -288,7 +289,12 @@ int copy_creds(struct task_struct *p, u64 clone_flags)return -ENOMEM ;if (clone_flags &CLONE_NEWUSER ) { - ret =create_user_ns (new); +kernel_cap_t cap_bset =CAP_FULL_SET ; + +if (clone_flags &CLONE_NEWUSER_BSET ) + cap_bset = (kernel_cap_t ){ .val = kargs->cap_bset }; + + ret =create_user_ns (new, cap_bset);if (ret <0 ) goto error_put; ret =set_cred_ucounts (new);
kernel/fork.c +15 -3
@@ -2168,7 +2168,7 @@ __latent_entropy struct task_struct *copy_process(#ifdef CONFIG_PROVE_LOCKING DEBUG_LOCKS_WARN_ON (!p->softirqs_enabled);#endif - retval =copy_creds (p, clone_flags); + retval =copy_creds (p, args);if (retval <0 ) goto bad_fork_free;
@@ -2932,7 +2932,9 @@ static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs, CLONE_ARGS_SIZE_VER1); BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=CLONE_ARGS_SIZE_VER2 ); -BUILD_BUG_ON (sizeof (struct clone_args ) !=CLONE_ARGS_SIZE_VER2 ); + BUILD_BUG_ON(offsetofend(struct clone_args, cap_bset) != +CLONE_ARGS_SIZE_VER3 ); +BUILD_BUG_ON (sizeof (struct clone_args ) !=CLONE_ARGS_SIZE_VER3 );if (unlikely (usize >PAGE_SIZE ))return -E2BIG ;
@@ -2962,6 +2964,11 @@ static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs, (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))return -EINVAL ; +if ((args.flags &CLONE_NEWUSER_BSET ) && usize <CLONE_ARGS_SIZE_VER3 ) +return -EINVAL ; +if (!(args.flags &CLONE_NEWUSER_BSET ) && args.cap_bset) +return -EINVAL ; + *kargs = (struct kernel_clone_args ){ .flags = args.flags, .pidfd =u64_to_user_ptr (args.pidfd),
@@ -2973,6 +2980,7 @@ static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs, .tls = args.tls, .set_tid_size = args.set_tid_size, .cgroup = args.cgroup, + .cap_bset = args.cap_bset & CAP_VALID_MASK, }; if (args.set_tid &&
@@ -3020,7 +3028,7 @@ static bool clone3_args_valid(struct kernel_clone_args *kargs) ~(CLONE_LEGACY_FLAGS |CLONE_CLEAR_SIGHAND |CLONE_INTO_CGROUP |CLONE_AUTOREAP |CLONE_NNP |CLONE_PIDFD_AUTOKILL |CLONE_EMPTY_MNTNS | - CLONE_NEWNET_LOOPBACK)) + CLONE_NEWNET_LOOPBACK | CLONE_NEWUSER_BSET)) return false;/*
@@ -3038,6 +3046,10 @@ static bool clone3_args_valid(struct kernel_clone_args *kargs) kargs->exit_signal)return false; +if ((kargs->flags &CLONE_NEWUSER_BSET ) && + !(kargs->flags &CLONE_NEWUSER )) +return false; +if (!clone3_stack_valid (kargs))return false;
kernel/user_namespace.c +7 -4
@@ -143,7 +143,7 @@ static unsigned long enforced_nproc_rlimit(void)* This is called by copy_creds(), which will finish setting the target task's * credentials. */ -int create_user_ns (struct cred *new) +int create_user_ns (struct cred *new,kernel_cap_t req_bset) {struct user_namespace *ns, *parent_ns = new->user_ns;kuid_t owner = new->euid;
@@ -184,15 +184,18 @@ int create_user_ns(struct cred *new) goto fail_dec;/* +* Intersect the parent's bounding set with any voluntary +* restrictions requested via clone3(). +* * If the caller has CAP_SYS_ADMIN in the parent namespace, -* they are a privileged creator and inherit the parent's +* they are a privileged creator and inherit this resulting * bounding set directly. * * Otherwise, enforce the unprivileged bounding ceiling, but * allow the child namespace to retain any capabilities the * creator already holds. */ - cap_bset = parent_ns->cap_bset; + cap_bset =cap_intersect (parent_ns->cap_bset, req_bset);if (!ns_capable_noaudit (parent_ns,CAP_SYS_ADMIN )) {kernel_cap_t unpriv_bset =READ_ONCE (sysctl_unpriv_userns_bset); kernel_cap_t allowed = cap_combine(unpriv_bset,
@@ -267,7 +270,7 @@ int unshare_userns(unsigned long unshare_flags, struct cred **new_cred) cred =prepare_creds ();if (cred) { - err =create_user_ns (cred); + err =create_user_ns (cred,CAP_FULL_SET );if (err)put_cred (cred);else
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH 4/8 nsfs: add NS_USER_GET_INFO ioctl to inspect user namespace capabilities
In reply to Hallgrimur H. GunnarssonWith the introduction of a capability bounding set for user namespaces, userspace needs a way to inspect the capability ceiling enforced on a given user namespace.
Introduce the NS_USER_GET_INFO ioctl on nsfs file descriptors to query user namespace metadata, mirroring the extensible structure pattern used by NS_MNT_GET_INFO.
--- fs/nsfs.c | 29 +++++++++++++++++++++++++++++ include/uapi/linux/nsfs.h | 17 +++++++++++++++++ 2 files changed, 46 insertions(+)
fs/nsfs.c +29 -0
@@ -170,6 +170,17 @@ static int copy_ns_info_to_user(const struct mnt_namespace *mnt_ns,return 0 ; } +static int copy_user_ns_info_to_user (const struct user_namespace *user_ns, +struct user_ns_info __user *uinfo, +size_t usize,struct user_ns_info *kinfo) +{ + kinfo->size =min (usize,sizeof (*kinfo)); + kinfo->spare =0 ; + kinfo->cap_bset = user_ns->cap_bset.val; + +return copy_struct_to_user (uinfo, usize, kinfo,sizeof (*kinfo),NULL ); +} +static bool nsfs_ioctl_valid (unsigned int cmd) {switch (cmd) {
@@ -194,6 +205,8 @@ static bool nsfs_ioctl_valid(unsigned int cmd)return extensible_ioctl_valid (cmd,NS_MNT_GET_NEXT ,MNT_NS_INFO_SIZE_VER0 );case _IOC_NR (NS_MNT_GET_PREV ):return extensible_ioctl_valid (cmd,NS_MNT_GET_PREV ,MNT_NS_INFO_SIZE_VER0 ); +case _IOC_NR (NS_USER_GET_INFO ): +return extensible_ioctl_valid (cmd,NS_USER_GET_INFO ,USER_NS_INFO_SIZE_VER0 ); }return false;
@@ -360,6 +373,22 @@ static long ns_ioctl(struct file *filp, unsigned int ioctl, ret =fd_publish (fdf);break ; } +case _IOC_NR (NS_USER_GET_INFO ): { +struct user_ns_info __user *uinfo = (struct user_ns_info __user *)arg; +struct user_ns_info kinfo = {}; +size_t usize =_IOC_SIZE (ioctl); + +if (ns->ns_type !=CLONE_NEWUSER ) +return -EINVAL ; + +if (!uinfo) +return -EINVAL ; + +if (usize <USER_NS_INFO_SIZE_VER0 ) +return -EINVAL ; + +return copy_user_ns_info_to_user (to_user_ns (ns), uinfo, usize, &kinfo); + }default : ret = -ENOTTY ; }
include/uapi/linux/nsfs.h +17 -0
@@ -44,6 +44,23 @@ struct mnt_ns_info {#define NS_GET_MNTNS_ID _IOR(NSIO, 5, __u64)#define NS_GET_ID _IOR(NSIO, 13, __u64) +/** +* struct user_ns_info - information about a user namespace +* @size: size of this structure +* @spare: reserved for future use +* @cap_bset: capability bounding set of the user namespace +*/ +struct user_ns_info { +__u32 size; +__u32 spare; +__u64 cap_bset; +}; + +#define USER_NS_INFO_SIZE_VER0 16/* sizeof first published struct */ + +/* Get information about user namespace. */ +#define NS_USER_GET_INFO _IOR(NSIO, 14, struct user_ns_info) +enum init_ns_ino {IPC_NS_INIT_INO =0xEFFFFFFFU ,UTS_NS_INIT_INO =0xEFFFFFFEU ,
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH 5/8 selftests/net: add test suite for CLONE_NEWNET_LOOPBACK
In reply to Hallgrimur H. GunnarssonAdd tests in tools/testing/selftests/net to validate CLONE_NEWNET_LOOPBACK and UNSHARE_NEWNET_LOOPBACK behavior.
--- tools/testing/selftests/net/.gitignore | 1 + tools/testing/selftests/net/Makefile | 1 + tools/testing/selftests/net/loopback_netns.c | 103 +++++++++++++++++++ 3 files changed, 105 insertions(+) create mode 100644 tools/testing/selftests/net/loopback_netns.c
tools/testing/selftests/net/.gitignore +1 -0
@@ -18,6 +18,7 @@ ipv6_flowlabel ipv6_flowlabel_mgr ipv6_fragmentation log.txt +loopback_netns msg_zerocopy netlink-dumps nettest
tools/testing/selftests/net/Makefile +1 -0
@@ -184,6 +184,7 @@ TEST_GEN_PROGS := \ icmp_rfc4884 \ ipv6_flowlabel_mgr \ ipv6_fragmentation \ + loopback_netns \ proc_net_pktgen \ reuseaddr_conflict \ reuseport_bpf \
tools/testing/selftests/net/loopback_netns.c new file +103 -0
103 lines not on this page · raw message
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH 6/8 selftests/capabilities: tests for user namespace capability bounding set
In reply to Hallgrimur H. GunnarssonAdd tests in tools/testing/selftests/capabilities for the user namespace capability bounding set feature:
- Verify default full capabilities and sysctl capability restriction for unprivileged user namespaces.
- Verify that unprivileged creators retain their existing effective capabilities despite the sysctl ceiling.
- Verify that privileged creators bypass the sysctl ceiling.
- Verify monotonic capability restriction across nested namespaces.
- Verify parent-ownership capability bounding.
--- .../testing/selftests/capabilities/.gitignore | 1 + tools/testing/selftests/capabilities/Makefile | 2 +- .../capabilities/userns_bounding_set_test.c | 420 ++++++++++++++++++ 3 files changed, 422 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/capabilities/userns_bounding_set_test.c
tools/testing/selftests/capabilities/.gitignore +1 -0
@@ -1,3 +1,4 @@ # SPDX-License-Identifier: GPL-2.0-only test_execve +userns_bounding_set_test validate_cap
tools/testing/selftests/capabilities/Makefile +1 -1
@@ -1,6 +1,6 @@ # SPDX-License-Identifier: GPL-2.0 TEST_GEN_FILES := validate_cap -TEST_GEN_PROGS := test_execve +TEST_GEN_PROGS := test_execve userns_bounding_set_test CFLAGS += -O2 -g -std=gnu99 -Wall $(KHDR_INCLUDES) LDLIBS += -lcap-ng -lrt -ldl
tools/testing/selftests/capabilities/userns_bounding_set_test.c new file +420 -0
420 lines not on this page · raw message
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH 7/8 selftests/capabilities: add clone3() tests for CLONE_NEWUSER_BSET
In reply to Hallgrimur H. GunnarssonAdd tests to userns_bounding_set_test to verify per-namespace capability bounding via CLONE_NEWUSER_BSET.
--- .../capabilities/userns_bounding_set_test.c | 146 ++++++++++++++++++ .../selftests/clone3/clone3_selftests.h | 1 + 2 files changed, 147 insertions(+)
tools/testing/selftests/capabilities/userns_bounding_set_test.c +146 -0
@@ -417,4 +417,150 @@ TEST_F(userns_bset, parent_owner_cap_restricted)EXPECT_EQ (EPERM ,run_parent_owner_setns (restricted_mask)); } +/* +* Verify that CLONE_NEWUSER_BSET restricts capabilities in the child user +* namespace even when the global sysctl allows all capabilities. +*/ +TEST_F(userns_bset, clone3_bset_restriction) +{ +struct __clone_args args = { + .flags =CLONE_NEWUSER |CLONE_NEWUSER_BSET , + .exit_signal =SIGCHLD , + .cap_bset = cap_full_set & ~(1ULL <<CAP_NET_ADMIN ), + }; +pid_t pid; +int status; + +ASSERT_EQ (0 ,write_sysctl_caps (cap_full_set)); + + pid =sys_clone3 (&args,sizeof (args)); +ASSERT_GE (pid,0 ); + +if (pid ==0 ) { +if (!cap_raised (CAP_SYS_ADMIN )) +_exit (1 ); +if (!cap_dropped (CAP_NET_ADMIN )) +_exit (2 ); +_exit (0 ); + } + +ASSERT_EQ (pid,waitpid (pid, &status,0 )); +ASSERT_TRUE (WIFEXITED (status)); +EXPECT_EQ (0 ,WEXITSTATUS (status)); +} + +/* +* Verify that passing cap_bset = 0 with CLONE_NEWUSER_BSET drops all +* capabilities in the new user namespace. +*/ +TEST_F(userns_bset, clone3_bset_empty) +{ +struct __clone_args args = { + .flags =CLONE_NEWUSER |CLONE_NEWUSER_BSET , + .exit_signal =SIGCHLD , + .cap_bset =0 , + }; +pid_t pid; +int status; + +ASSERT_EQ (0 ,write_sysctl_caps (cap_full_set)); + + pid =sys_clone3 (&args,sizeof (args)); +ASSERT_GE (pid,0 ); + +if (pid ==0 ) { +if (!cap_dropped (CAP_SYS_ADMIN )) +_exit (1 ); +if (!cap_dropped (CAP_NET_ADMIN )) +_exit (2 ); +_exit (0 ); + } + +ASSERT_EQ (pid,waitpid (pid, &status,0 )); +ASSERT_TRUE (WIFEXITED (status)); +EXPECT_EQ (0 ,WEXITSTATUS (status)); +} + +/* +* Verify that an unprivileged caller cannot use CLONE_NEWUSER_BSET to bypass +* the global sysctl ceiling. +*/ +TEST_F(userns_bset, clone3_bset_cannot_bypass_sysctl) +{ +uint64_t restricted_mask = cap_full_set & ~(1ULL <<CAP_NET_ADMIN ); +pid_t pid; +int status; + +ASSERT_EQ (0 ,write_sysctl_caps (restricted_mask)); + + pid =fork (); +ASSERT_GE (pid,0 ); + +if (pid ==0 ) { +struct __clone_args args = { + .flags =CLONE_NEWUSER |CLONE_NEWUSER_BSET , + .exit_signal =SIGCHLD , + .cap_bset = cap_full_set, + }; +int child_status; +pid_t child; + +if (drop_privileges () !=0 ) +_exit (1 ); + + child =sys_clone3 (&args,sizeof (args)); +if (child <0 ) +_exit (2 ); + +if (child ==0 ) { +if (!cap_raised (CAP_SYS_ADMIN )) +_exit (3 ); +if (!cap_dropped (CAP_NET_ADMIN )) +_exit (4 ); +_exit (0 ); + } + +if (waitpid (child, &child_status,0 ) != child || + !WIFEXITED (child_status) ||WEXITSTATUS (child_status) !=0 ) +_exit (5 ); + +_exit (0 ); + } + +ASSERT_EQ (pid,waitpid (pid, &status,0 )); +ASSERT_TRUE (WIFEXITED (status)); +EXPECT_EQ (0 ,WEXITSTATUS (status)); +} + +/* +* Verify clone3() argument validation for CLONE_NEWUSER_BSET. +*/ +TEST_F(userns_bset, clone3_bset_invalid_args) +{ +struct __clone_args args; + +/* CLONE_NEWUSER_BSET without CLONE_NEWUSER must fail */ +memset (&args,0 ,sizeof (args)); + args.flags =CLONE_NEWUSER_BSET ; + args.exit_signal =SIGCHLD ; + args.cap_bset = cap_full_set; +EXPECT_EQ (-1 ,sys_clone3 (&args,sizeof (args))); +EXPECT_EQ (EINVAL , errno); + +/* Non-zero cap_bset without CLONE_NEWUSER_BSET must fail */ +memset (&args,0 ,sizeof (args)); + args.flags =CLONE_NEWUSER ; + args.exit_signal =SIGCHLD ; + args.cap_bset = cap_full_set; +EXPECT_EQ (-1 ,sys_clone3 (&args,sizeof (args))); +EXPECT_EQ (EINVAL , errno); + +/* CLONE_NEWUSER_BSET with struct size < VER3 must fail */ +memset (&args,0 ,sizeof (args)); + args.flags =CLONE_NEWUSER |CLONE_NEWUSER_BSET ; + args.exit_signal =SIGCHLD ; +EXPECT_EQ (-1 ,sys_clone3 (&args,CLONE_ARGS_SIZE_VER2 )); +EXPECT_EQ (EINVAL , errno); +} +TEST_HARNESS_MAIN
tools/testing/selftests/clone3/clone3_selftests.h +1 -0
@@ -31,6 +31,7 @@ struct __clone_args {__aligned_u64 set_tid;__aligned_u64 set_tid_size;__aligned_u64 cgroup; +__aligned_u64 cap_bset; };static pid_t sys_clone3 (struct __clone_args *args,size_t size)
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH 8/8 selftests/nsfs: add tests for NS_USER_GET_INFO ioctl
In reply to Hallgrimur H. GunnarssonAdd tests for the NS_USER_GET_INFO ioctl to verify user namespace capability bounding set inspection and validate error paths.
--- .../selftests/filesystems/nsfs/.gitignore | 1 + .../selftests/filesystems/nsfs/Makefile | 4 +- .../selftests/filesystems/nsfs/userns.c | 120 ++++++++++++++++++ 3 files changed, 123 insertions(+), 2 deletions(-) create mode 100644 tools/testing/selftests/filesystems/nsfs/userns.c
tools/testing/selftests/filesystems/nsfs/.gitignore +1 -0
@@ -1,4 +1,5 @@ # SPDX-License-Identifier: GPL-2.0-only owner pidns +userns iterate_mntns
tools/testing/selftests/filesystems/nsfs/Makefile +2 -2
@@ -1,6 +1,6 @@ # SPDX-License-Identifier: GPL-2.0-only -TEST_GEN_PROGS := owner pidns iterate_mntns +TEST_GEN_PROGS := owner pidns iterate_mntns userns -CFLAGS := -Wall -Werror +CFLAGS += -Wall -Werror $(KHDR_INCLUDES) include ../../lib.mk
tools/testing/selftests/filesystems/nsfs/userns.c new file +120 -0
120 lines not on this page · raw message
Signature · 1 line
2.56.0.313.g2479322e68-goog
Quoted 27 lines · Hallgrimur H. Gunnarsson
When an unprivileged process creates a new user namespace, it is granted a full set of capabilities (
CAP_FULL_SET) scoped to that namespace. While these capabilities are isolated to the namespace, they allow unprivileged local users to reach deep kernel subsystems (most notably networking configuration and raw sockets viaCAP_NET_ADMINandCAP_NET_RAW) that historically assumed a trusted caller and have accounted for a large share of local privilege escalation vulnerabilities.Many workloads and sandboxes use unprivileged user namespaces strictly for basic UID/GID, mount, PID, or network isolation and never need high-risk capabilities like
CAP_NET_ADMINorCAP_NET_RAW. Likewise, system administrators often want a host-wide policy ceiling restricting which capabilities unprivileged user namespaces may acquire, without disabling unprivileged user namespaces altogether.Prior work by Jonathan Calmels [1] proposed addressing this via a sixth per-thread capability set (
cap_userns) alongside a global sysctl mask. During that discussion [1, 2], feedback (e.g. from Casey Schaufler) suggested that rather than adding another per-thread capability set andprctl()interface, capability restrictions could be integrated directly into structuser_namespaceand configured viaclone3(). At the same time, as noted in [1], aclone3()flag alone is not sufficient for administrators who need to enforce a host-wide ceiling on unprivileged user namespaces without modifying every userspace callsite.
Quoted 6 lines
This series combines both pieces of feedback: it embeds a capability bounding set (
cap_bset) directly into structuser_namespace, reusing the existing taskcap_bset,cap_permitted, andcap_effectivesets on namespace entry, and provides both a system-wide sysctl ceiling for unprivileged user namespaces and aCLONE_NEWUSER_BSETflag for voluntary per-namespace restriction viaclone3().
Why should the task's cap masks affect this? *Maybe* cap_bset makes sense, but I'm struggling a bit to see why cap_permitted and cap_effective should matter.
Also, I think that Docker in non-userns mode restricts cap_bset, and the purpose of that restriction is rather at odds with interpreting it as a restriction on newly created user namespaces for purposes of vulnerability mitigation.
Quoted 7 lines
In addition, because restricting
CAP_NET_ADMINat user namespace creation time prevents userspace from bringing up the loopback interface in new network namespaces, the series first introduces an opt-in flag to automatically enable loopback on network namespace creation:
Quoted 8 lines
1. Opt-in loopback activation on netns creation (Patch 1)
New network namespaces start with the loopback interface (lo) DOWN by default, requiring
CAP_NET_ADMINover the owning user namespace to bring it up. To block external network access while preserving localhost networking, sandboxes commonly create an isolated network namespace with only the loopback interface enabled.
The whole unshare/clone flag situation is getting out of hand, IMO. And this new thing makes logical sense but is really about reducing exposure.
Perhaps we should instead have a small list associated with a userns (extensible in the future) of things that the ns's admin (i.e. whoever has CAP_SYS_ADMIN relative to the ns) may do. That list could include:
- Create loopback with sensible defaults for ipv4 and/or ipv6 (i see no obvious reason to separate them)
- Create tun/tap interfaces in that ns (and attach them, etc)
And add a very simple new API to do these things. Actually, the tun/tap could just use the normal mechanism.
Thoughts?
Signature · 2 lines
Andy Lutomirski AMA Capital Management, LLC
Quoted 70 lines · Andy Lutomirski
Quoted 27 lines · Hallgrimur H. Gunnarsson
When an unprivileged process creates a new user namespace, it is granted a full set of capabilities (
CAP_FULL_SET) scoped to that namespace. While these capabilities are isolated to the namespace, they allow unprivileged local users to reach deep kernel subsystems (most notably networking configuration and raw sockets viaCAP_NET_ADMINandCAP_NET_RAW) that historically assumed a trusted caller and have accounted for a large share of local privilege escalation vulnerabilities.Many workloads and sandboxes use unprivileged user namespaces strictly for basic UID/GID, mount, PID, or network isolation and never need high-risk capabilities like
CAP_NET_ADMINorCAP_NET_RAW. Likewise, system administrators often want a host-wide policy ceiling restricting which capabilities unprivileged user namespaces may acquire, without disabling unprivileged user namespaces altogether.Prior work by Jonathan Calmels [1] proposed addressing this via a sixth per-thread capability set (
cap_userns) alongside a global sysctl mask. During that discussion [1, 2], feedback (e.g. from Casey Schaufler) suggested that rather than adding another per-thread capability set andprctl()interface, capability restrictions could be integrated directly into structuser_namespaceand configured viaclone3(). At the same time, as noted in [1], aclone3()flag alone is not sufficient for administrators who need to enforce a host-wide ceiling on unprivileged user namespaces without modifying every userspace callsite.Quoted 6 lines
This series combines both pieces of feedback: it embeds a capability bounding set (
cap_bset) directly into structuser_namespace, reusing the existing taskcap_bset,cap_permitted, andcap_effectivesets on namespace entry, and provides both a system-wide sysctl ceiling for unprivileged user namespaces and aCLONE_NEWUSER_BSETflag for voluntary per-namespace restriction viaclone3().Why should the task's cap masks affect this? *Maybe*
cap_bsetmakes sense, but I'm struggling a bit to see whycap_permittedandcap_effectiveshould matter.Also, I think that Docker in non-userns mode restricts
cap_bset, and the purpose of that restriction is rather at odds with interpreting it as a restriction on newly created user namespaces for purposes of vulnerability mitigation.Quoted 7 lines
In addition, because restricting
CAP_NET_ADMINat user namespace creation time prevents userspace from bringing up the loopback interface in new network namespaces, the series first introduces an opt-in flag to automatically enable loopback on network namespace creation:Quoted 8 lines
1. Opt-in loopback activation on netns creation (Patch 1)
New network namespaces start with the loopback interface (lo) DOWN by default, requiring
CAP_NET_ADMINover the owning user namespace to bring it up. To block external network access while preserving localhost networking, sandboxes commonly create an isolated network namespace with only the loopback interface enabled.The whole unshare/clone flag situation is getting out of hand, IMO. And this new thing makes logical sense but is really about reducing exposure.
Perhaps we should instead have a small list associated with a userns (extensible in the future) of things that the ns's admin (i.e. whoever has
CAP_SYS_ADMINrelative to the ns) may do. That list could include:
Quoted 8 lines
- Create loopback with sensible defaults for ipv4 and/or ipv6 (i see no obvious reason to separate them)
- Create tun/tap interfaces in that ns (and attach them, etc)And add a very simple new API to do these things. Actually, the tun/tap could just use the normal mechanism.
Thoughts?
I think that's an interesting idea. I also think the whole flag issue is moving in the wrong direction.
Are you thinking of something like struct open_how in openat2, or something else?
Signature · 1 line
Rgrds, legion
Quoted 36 lines · Andy Lutomirski
Quoted 27 lines · Hallgrimur H. Gunnarsson
When an unprivileged process creates a new user namespace, it is granted a full set of capabilities (
CAP_FULL_SET) scoped to that namespace. While these capabilities are isolated to the namespace, they allow unprivileged local users to reach deep kernel subsystems (most notably networking configuration and raw sockets viaCAP_NET_ADMINandCAP_NET_RAW) that historically assumed a trusted caller and have accounted for a large share of local privilege escalation vulnerabilities.Many workloads and sandboxes use unprivileged user namespaces strictly for basic UID/GID, mount, PID, or network isolation and never need high-risk capabilities like
CAP_NET_ADMINorCAP_NET_RAW. Likewise, system administrators often want a host-wide policy ceiling restricting which capabilities unprivileged user namespaces may acquire, without disabling unprivileged user namespaces altogether.Prior work by Jonathan Calmels [1] proposed addressing this via a sixth per-thread capability set (
cap_userns) alongside a global sysctl mask. During that discussion [1, 2], feedback (e.g. from Casey Schaufler) suggested that rather than adding another per-thread capability set andprctl()interface, capability restrictions could be integrated directly into structuser_namespaceand configured viaclone3(). At the same time, as noted in [1], aclone3()flag alone is not sufficient for administrators who need to enforce a host-wide ceiling on unprivileged user namespaces without modifying every userspace callsite.Quoted 6 lines
This series combines both pieces of feedback: it embeds a capability bounding set (
cap_bset) directly into structuser_namespace, reusing the existing taskcap_bset,cap_permitted, andcap_effectivesets on namespace entry, and provides both a system-wide sysctl ceiling for unprivileged user namespaces and aCLONE_NEWUSER_BSETflag for voluntary per-namespace restriction viaclone3().
Quoted 3 lines
Why should the task's cap masks affect this? *Maybe*
cap_bsetmakes sense, but I'm struggling a bit to see whycap_permittedandcap_effectiveshould matter.
Sorry, the phrasing here may have been misleading. Just to clarify:
none of the creating task's capability sets (cap_bset, cap_permitted or cap_effective) are used to restrict the new user namespace.
When I wrote "reusing the existing task cap_bset, cap_permitted and cap_effective sets on namespace entry", I was contrasting this with the prior series from 2024 [1], which proposed adding a 6th per-thread capability set to struct cred.
In this series, when a task creates or enters a user namespace, we simply initialize its new cred->cap_{bset,permitted,effective} in that namespace to user_ns->cap_bset instead of CAP_FULL_SET.
Quoted 4 lines
Also, I think that Docker in non-userns mode restricts
cap_bset, and the purpose of that restriction is rather at odds with interpreting it as a restriction on newly created user namespaces for purposes of vulnerability mitigation.
When computing the new user namespace's user_ns->cap_bset in create_user_ns():
1. The creating task's cred->cap_bset and cred->cap_permitted are not consulted at all. The base ceiling is inherited from parent_ns->cap_bset (which is CAP_FULL_SET in init_user_ns), not from the task's cred->cap_bset. So a non-userns Docker container that drops bits from its task cap_bset does not restrict newly created user namespaces.
2. The creating task's cred->cap_effective never restricts the new user namespace, but it is used as an additive exception to the unprivileged sysctl ceiling.
The rationale is that if an admin restricts e.g. CAP_NET_ADMIN in the unprivileged sysctl, an unprivileged daemon that already holds effective CAP_NET_ADMIN in the parent namespace is allowed to keep it when creating a new user namespace. There is no added attack surface if the user already had the capability in the parent ns.
Quoted 24 lines
Quoted 6 lines
In addition, because restricting
CAP_NET_ADMINat user namespace creation time prevents userspace from bringing up the loopback interface in new network namespaces, the series first introduces an opt-in flag to automatically enable loopback on network namespace creation:Quoted 8 lines
1. Opt-in loopback activation on netns creation (Patch 1)
New network namespaces start with the loopback interface (lo) DOWN by default, requiring
CAP_NET_ADMINover the owning user namespace to bring it up. To block external network access while preserving localhost networking, sandboxes commonly create an isolated network namespace with only the loopback interface enabled.The whole unshare/clone flag situation is getting out of hand, IMO. And this new thing makes logical sense but is really about reducing exposure.
Perhaps we should instead have a small list associated with a userns (extensible in the future) of things that the ns's admin (i.e. whoever has
CAP_SYS_ADMINrelative to the ns) may do. That list could include:
Quoted 8 lines
- Create loopback with sensible defaults for ipv4 and/or ipv6 (i see no obvious reason to separate them)
- Create tun/tap interfaces in that ns (and attach them, etc)And add a very simple new API to do these things. Actually, the tun/tap could just use the normal mechanism.
Thoughts?
I'm not particularly attached to CLONE_NEWNET_LOOPBACK. I'd be happy with whatever mechanism allows bringing up loopback in a new netns without granting all of CAP_NET_ADMIN.
The main reason I went for a creation-time flag is that it avoids needing a separate userspace API call after namespace creation and makes it simple to get working loopback for sandboxes that want to drop all capabilities in the new userns from the start, e.g. CLONE_NEWUSER_BSET with cap_bset = 0.
That said, if maintainers prefer not to spend clone/unshare flags on this, I'm completely open to an alternative mechanism.
Also worth noting that Patch 1 is orthogonal to the rest of the series. The capability bounding set changes in Patches 2-4 stand on their own and Patch 1 just makes restricting CAP_NET_ADMIN more practical for common sandboxing use cases that rely on localhost networking.
[email protected]
AI reviewRe: [PATCH 1/8] net: introduce CLONE_NEWNET_LOOPBACK to auto-enable loopback
In reply to Hallgrimur H. GunnarssonSashiko has reviewed this patch and found no issues.
Quoted 13 lines
New network namespaces start with the loopback interface DOWN by default, requiring
CAP_NET_ADMINover the owning user namespace to bring it up.To block external network access while preserving the localhost networking that many applications expect, sandboxes (such as bwrap, nsjail and minijail) commonly create an isolated network namespace with only the loopback interface enabled.
However, requiring a sandbox to hold
CAP_NET_ADMINin a new user namespace solely to bring loopback up conflicts with reducing theCAP_NET_ADMINattack surface.
Quoted 8 lines
Today, an unprivileged sandbox or sandbox manager must start with
CAP_NET_ADMINin its user namespace to be able to bring up loopback, [ ... ]
semantics while allowing unprivileged sandboxes to create an isolated network namespace with functional localhost networking without ever holdingCAP_NET_ADMIN.Signed-off-by Hallgrimur H. Gunnarsson <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
[email protected]
AI reviewRe: [PATCH 2/8] userns: introduce capability bounding set for user namespaces
In reply to Hallgrimur H. GunnarssonThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] userns: cap_ptrace_access_check() denies owner access without CAP_SYS_PTRACE --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] userns: cap_ptrace_access_check() denies owner access without CAP_SYS_PTRACE --
commit 16037e714ad5686658566ccf9fa3273e7c4c0615
Author: Hallgrimur H. Gunnarsson <[email protected]>
userns: introduce capability bounding set for user namespaces
This commit introduces a per-user-namespace capability bounding set (cap_bset) and a global sysctl ceiling knob (kernel.unprivileged_userns_caps_allowed) to restrict the capabilities granted when unprivileged tasks create user namespaces. It also bounds the implicit capabilities granted to a parent-namespace owner over an owned child user namespace by the child namespace's cap_bset.
Quoted 9 lines
security/commoncap.c +0
-1@@ -88,11 +88,13 @@ static inline int cap_capable_helper(const struct cred *cred,if (ns->level <= cred_ns->level)return -EPERM ; -/*
security/commoncap.c static inline int cap_capable_helper(const struct cred *cred, · line 98
Quoted 10 lines
security/commoncap.c +5
-2+/* * The owner of the user namespace in the parent of the -* user namespace has all caps. +* user namespace has all caps, subject to the bounding +* set of the owned user namespace. */ -if ((ns->parent == cred_ns) &&uid_eq (ns->owner, cred->euid)) +if (ns->parent == cred_ns &&uid_eq (ns->owner, cred->euid) && +userns_has_cap (ns, cap))return 0 ;
[Severity: Medium]
When CAP_SYS_PTRACE is excluded from a child user namespace's cap_bset (either via the unprivileged_userns_caps_allowed sysctl or via CLONE_NEWUSER_BSET in "userns: allow restricting capability bounding set via clone3()"), does this break ptrace_may_access() and PTRACE_TRACEME for the parent-namespace owner inspecting its own child processes in that namespace?
In __ptrace_may_access(), a caller with the same UID/GID as a dumpable target passes the UID/GID and dumpability checks without needing CAP_SYS_PTRACE, and then calls security_ptrace_access_check() -> cap_ptrace_access_check():
security/commoncap.c:cap_ptrace_access_check() {
...
if (cred->user_ns == child_cred->user_ns &&
cap_issubset(child_cred->cap_permitted, *caller_caps))
goto out;
if (ns_capable(child_cred->user_ns, CAP_SYS_PTRACE))
goto out;
ret = -EPERM;
}And similarly in cap_ptrace_traceme():
security/commoncap.c:cap_ptrace_traceme() {
...
if (cred->user_ns == child_cred->user_ns &&
cap_issubset(child_cred->cap_permitted, cred->cap_permitted))
goto out;
if (has_ns_capability(parent, child_cred->user_ns, CAP_SYS_PTRACE))
goto out;
ret = -EPERM;
}Although the kernel-doc comments on both functions state that access is allowed if the caller is in the same or an ancestor user_ns and holds all of the target task's capabilities (matching cred_cap_issubset() in kernel/cred.c), both functions only check cap_issubset() when cred->user_ns == child_cred->user_ns. For an ancestor user_ns, they rely entirely on ns_capable(child_cred->user_ns, CAP_SYS_PTRACE) or has_ns_capability(parent, child_cred->user_ns, CAP_SYS_PTRACE).
Because cap_capable_helper() now requires userns_has_cap(ns, cap) for the owner in the parent namespace, ns_capable(child_cred->user_ns, CAP_SYS_PTRACE) returns false whenever CAP_SYS_PTRACE is not in child_ns->cap_bset. As a result, an unprivileged parent task that spawns a sandboxed child in a new user namespace without CAP_SYS_PTRACE is denied access to its own child even when the child has no capabilities beyond the owned namespace (or cap_permitted == CAP_EMPTY_SET).
This causes parent-side operations gated on ptrace_may_access() to fail with -EPERM, -EACCES, or -ENOENT, including opening /proc/<child>/ns/*, setns(pidfd, ...) via validate_nsset() (even when CAP_SYS_ADMIN is set in child_ns->cap_bset), pidfd_getfd(), reading /proc/<child>/maps or /proc/<child>/fd/*, ptrace attach / PTRACE_TRACEME, and accessing /proc/<child>/uid_map when procfs is mounted with hidepid.
Should cap_ptrace_access_check() and cap_ptrace_traceme() permit access when the caller is the owner of an ancestor user namespace (similar to cred_cap_issubset(), where all capabilities in the child namespace are a subset of the owner's privileges over that namespace), rather than requiring CAP_SYS_PTRACE to be present in the child namespace's cap_bset?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
[email protected]
AI reviewRe: [PATCH 3/8] userns: allow restricting capability bounding set via clone3()
In reply to Hallgrimur H. GunnarssonThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] fork: copy_clone_args_from_user() validates cap_bset outside flag gate --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] fork: copy_clone_args_from_user() validates cap_bset outside flag gate --
commit ad8aaabe65c03fa30d8b9e523721be228b373956
Author: Hallgrimur H. Gunnarsson <[email protected]>
userns: allow restricting capability bounding set via clone3()
This commit introduces the CLONE_NEWUSER_BSET flag and adds a cap_bset field to struct clone_args (CLONE_ARGS_SIZE_VER3). When specified with CLONE_NEWUSER during clone3(), the new user namespace's capability bounding set is intersected with cap_bset.
Quoted 4 lines
kernel/fork.c +0
-0
[ ... ]
kernel/fork.c static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs, · line 2970
Quoted 8 lines
kernel/fork.c +4
-0@@ -2962,6 +2964,11 @@ static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs, (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))return -EINVAL ; +if ((args.flags &CLONE_NEWUSER_BSET ) && usize <CLONE_ARGS_SIZE_VER3 ) +return -EINVAL ; +if (!(args.flags &CLONE_NEWUSER_BSET ) && args.cap_bset) +return -EINVAL ;
[Severity: Medium]
Should copy_clone_args_from_user() in kernel/fork.c really reject a non-zero args.cap_bset when CLONE_NEWUSER_BSET is not set in args.flags?
In include/uapi/linux/sched.h, cap_bset in struct clone_args is documented as a flag-gated field:
* @cap_bset: If CLONE_NEWUSER_BSET is specified, this * specifies the capability bounding set mask to * apply to the new user namespace. Unknown * capability bits (> CAP_LAST_CAP) are ignored.
Other flag-gated fields in struct clone_args (such as cgroup gated by CLONE_INTO_CGROUP right above, or pidfd, child_tid, parent_tid, and tls) are only validated and consumed when their corresponding flag is set, and copy_creds() in kernel/cred.c only reads kargs->cap_bset when CLONE_NEWUSER_BSET is present:
if (clone_flags & CLONE_NEWUSER) {
kernel_cap_t cap_bset = CAP_FULL_SET;
if (clone_flags & CLONE_NEWUSER_BSET)
cap_bset = (kernel_cap_t){ .val = kargs->cap_bset };If userspace invokes sys_clone3() -> copy_clone_args_from_user() with usize >= CLONE_ARGS_SIZE_VER3 and without CLONE_NEWUSER_BSET set, while args.cap_bset is non-zero (for instance, when reusing a struct clone_args buffer after clearing CLONE_NEWUSER_BSET or only initializing fields for the flags being passed), won't this check cause the syscall to fail spuriously with -EINVAL?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
[email protected]
AI reviewRe: [PATCH 4/8] nsfs: add NS_USER_GET_INFO ioctl to inspect user namespace capabilities
In reply to Hallgrimur H. GunnarssonSashiko has reviewed this patch and found no issues.
Quoted 9 lines
With the introduction of a capability bounding set for user namespaces, userspace needs a way to inspect the capability ceiling enforced on a given user namespace.
Introduce the
NS_USER_GET_INFOioctl on nsfs file descriptors to query user namespace metadata, mirroring the extensible structure pattern used byNS_MNT_GET_INFO.Signed-off-by Hallgrimur H. Gunnarsson <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
[email protected]
AI reviewRe: [PATCH 5/8] selftests/net: add test suite for CLONE_NEWNET_LOOPBACK
In reply to Hallgrimur H. GunnarssonSashiko has reviewed this patch and found no issues.
Quoted 4 lines
Add tests in
tools/testing/selftests/netto validateCLONE_NEWNET_LOOPBACKandUNSHARE_NEWNET_LOOPBACKbehavior.Signed-off-by Hallgrimur H. Gunnarsson <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
[email protected]
AI reviewRe: [PATCH 6/8] selftests/capabilities: tests for user namespace capability bounding set
In reply to Hallgrimur H. GunnarssonSashiko has reviewed this patch and found no issues.
Quoted 11 lines
Add tests in
tools/testing/selftests/capabilitiesfor the user namespace capability bounding set feature:- Verify default full capabilities and sysctl capability restriction for unprivileged user namespaces.
- Verify that unprivileged creators retain their existing effective capabilities despite the sysctl ceiling.
- Verify that privileged creators bypass the sysctl ceiling.
- Verify monotonic capability restriction across nested namespaces.
- Verify parent-ownership capability bounding.
Quoted 1 line
Signed-off-by Hallgrimur H. Gunnarsson <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
[email protected]
AI reviewRe: [PATCH 7/8] selftests/capabilities: add clone3() tests for CLONE_NEWUSER_BSET
In reply to Hallgrimur H. GunnarssonSashiko has reviewed this patch and found no issues.
Quoted 4 lines
Add tests to
userns_bounding_set_testto verify per-namespace capability bounding viaCLONE_NEWUSER_BSET.Signed-off-by Hallgrimur H. Gunnarsson <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
[email protected]
AI reviewRe: [PATCH 8/8] selftests/nsfs: add tests for NS_USER_GET_INFO ioctl
In reply to Hallgrimur H. GunnarssonSashiko has reviewed this patch and found no issues.
Quoted 4 lines
Add tests for the
NS_USER_GET_INFOioctl to verify user namespace capability bounding set inspection and validate error paths.Signed-off-by Hallgrimur H. Gunnarsson <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
Serge E. Hallyn
maintainerQuoted 26 lines · Hallgrimur H. Gunnarsson
When an unprivileged process creates a new user namespace, it is granted a full set of capabilities (
CAP_FULL_SET) scoped to that namespace. While these capabilities are isolated to the namespace, they allow unprivileged local users to reach deep kernel subsystems (most notably networking configuration and raw sockets viaCAP_NET_ADMINandCAP_NET_RAW) that historically assumed a trusted caller and have accounted for a large share of local privilege escalation vulnerabilities.Many workloads and sandboxes use unprivileged user namespaces strictly for basic UID/GID, mount, PID, or network isolation and never need high-risk capabilities like
CAP_NET_ADMINorCAP_NET_RAW. Likewise, system administrators often want a host-wide policy ceiling restricting which capabilities unprivileged user namespaces may acquire, without disabling unprivileged user namespaces altogether.Prior work by Jonathan Calmels [1] proposed addressing this via a sixth per-thread capability set (
cap_userns) alongside a global sysctl mask. During that discussion [1, 2], feedback (e.g. from Casey Schaufler) suggested that rather than adding another per-thread capability set andprctl()interface, capability restrictions could be integrated directly into structuser_namespaceand configured viaclone3(). At the same time, as noted in [1], aclone3()flag alone is not sufficient for administrators who need to enforce a host-wide ceiling on unprivileged user namespaces without modifying every userspace callsite.
Quoted 6 lines
This series combines both pieces of feedback: it embeds a capability bounding set (
cap_bset) directly into structuser_namespace, reusing the existing taskcap_bset,cap_permitted, andcap_effectivesets on namespace entry, and provides both a system-wide sysctl ceiling for unprivileged user namespaces and aCLONE_NEWUSER_BSETflag for voluntary per-namespace restriction viaclone3().
Hi. Thanks for sending this, and continuing to think about this problem.
A few weeks back I had a somewhat different idea for such controls. I've been meaning to start a wider discussion about it, but was traveling for a bit. What I wrote then:
Generally, if I, or some users I support, need to use unprivileged containers or user namespaces, then when an 0day comes along, I can hopefully trust them not to exploit it. The biggest danger comes from the fact that, right now, if they can use them, anyone can. So if someone can trigger some other code running as user nginx or something, that can become a root vector.
So what if we had a built-in feature or LSM which implemented a credential based whitelist, entered at firstboot? Something like
``` # Default deny uid == 1000 # approved 1005 < uid < 1010 # approved gid == 1005 security_label = lxc_user_t # Not sure how far we want to go with this tty # must have a session ```
Now, if you want to use user namespaces for generic sandboxes for all users, e.g. to confine browser activity or nginx modules, then this model may not fit. Or rather, it might need a few tweaks.
Kees whipped up a proof of concept BPF lsm that implemented this. A copy from his email (and let's call it GPLv2 unless he wants to change it to something like MIT) follows:
Needs:
CONFIG_BPF_LSM=yCONFIG_DEBUG_INFO_BTF=y
FUNCTION_TRACER=y
DYNAMIC_FTRACE=y
#!/bin/bash
# Manage the userns allowlist policy.
#
# policy.sh load load, attach and pin (policy still writable) # policy.sh allow-uid UID add a uid # policy.sh allow-gid GID add a gid # policy.sh deny-uid UID remove a uid (only before "lock") # policy.sh show dump the policy # policy.sh failures who has been denied, and how often # policy.sh lock freeze the policy maps, one way # policy.sh unload detach and unpin everything # # bpftool takes keys and values as raw bytes in target byte order, so a u32 # uid has to be written little-endian on x86: uid 1000 is "e8 03 00 00", not # "00 00 03 e8". Getting that backwards silently writes a policy for uid # 3892510720 instead, which is why this script exists. set -eu
BPFFS=${BPFFS:-/sys/fs/bpf}
DIR=$BPFFS/userns # pinned maps (a directory)
LINK=$BPFFS/userns_link # pinned lsm link (a file)
OBJ=${OBJ:-$(dirname "$0")/userns_allowlist.bpf.o} BPFTOOL=${BPFTOOL:-bpftool}
u32_le() { # 1000 -> "hex e8 03 00 00"
printf 'hex %02x %02x %02x %02x' \ $(( $1 & 0xff)) $(( ($1 >> 8) & 0xff)) \ $(( ($1 >> 16) & 0xff)) $(( ($1 >> 24) & 0xff)) }
# bpftool prints map contents as integers when the object carries BTF and as
# arrays of hex byte strings when it does not. Handle both.
decode() {
python3 -c '
import json, sys
rows = json.load(sys.stdin)
if not rows:
sys.exit("(empty)")
def val(v):
if isinstance(v, list):
return int.from_bytes(bytes(int(x, 16) for x in v), "little")
return int(v)
for r in sorted(rows, key=lambda r: -val(r["value"])):
print("uid %-8d denied %d time(s)" % (val(r["key"]), val(r["value"])))
'
}case ${1:-} in
load)
mountpoint -q "$BPFFS" 2>/dev/null || mount -t bpf bpf "$BPFFS"
# bpftool creates both pin paths itself and fails if either exists, so # do not mkdir them. For a single-program object the program path is a # file (the pinned link); pinmaps is a directory.
$BPFTOOL prog load "$OBJ" "$LINK" pinmaps "$DIR" autoattach
# "prog load" exits 0 even when the LSM attach failed and it silently # fell back to pinning the program, which leaves the policy loaded but # inert. The only reliable check is that an lsm link now exists. if ! $BPFTOOL link show | grep -q lsm; then
echo "ERROR: no lsm link: the program is loaded but NOT enforcing." >&2 echo "Needs CONFIG_BPF_LSM=y, CONFIG_DEBUG_INFO_BTF=y and" >&2 echo "CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS=y (the last one" >&2 echo "requires CONFIG_FUNCTION_TRACER=y), plus bpf in CONFIG_LSM." >&2 exit 1
fi
echo "loaded and enforcing; policy maps under $DIR (not yet frozen)" ;;
allow-uid)
$BPFTOOL map update pinned "$DIR/allowed_uids" key $(u32_le "$2") value hex 01
;;
allow-gid)
$BPFTOOL map update pinned "$DIR/allowed_gids" key $(u32_le "$2") value hex 01
;;
deny-uid)
$BPFTOOL map delete pinned "$DIR/allowed_uids" key $(u32_le "$2")
;;
show)
echo "== allowed uids"; $BPFTOOL map dump pinned "$DIR/allowed_uids"
echo "== allowed gids"; $BPFTOOL map dump pinned "$DIR/allowed_gids"
;;
failures)
# key is the euid that was denied, value is a count
$BPFTOOL -j map dump pinned "$DIR/denied_uids" | decode
;;
lock)
# Only the policy maps. denied_uids is written by the program, and
# program writes bypass the frozen check, so freezing it would lock out
# this script without stopping anything.
$BPFTOOL map freeze pinned "$DIR/allowed_uids"
$BPFTOOL map freeze pinned "$DIR/allowed_gids"
echo "policy frozen; allow-uid/allow-gid/deny-uid will now fail with EPERM"
echo "even as root. Changing it means 'unload' and 'load' again."
;;
unload)
rm -f "$LINK" "$DIR"/allowed_uids "$DIR"/allowed_gids "$DIR"/denied_uids
rmdir "$DIR" 2>/dev/null || true
echo "unpinned; enforcement stops when the last reference goes away"
;;
*)
# the header comment block, however long it grows
awk 'NR > 1 && /^#/ { print; next } NR > 1 { exit }' "$0"
exit 1
;;
esac# There is no "digest" command, though a frozen policy looks like it should
# have one. The kernel will hash a frozen map and return it through # BPF_OBJ_GET_INFO_BY_FD in info.hash (syscall.c:5433, -EPERM unless # map->frozen), but only array maps implement ->map_get_hash(); for a # BPF_MAP_TYPE_HASH it fails with -EINVAL however frozen it is. bpftool does # not expose info.hash either way. Attesting to this policy would mean # reshaping it as arrays -- e.g. a bitmap indexed by uid -- and calling # BPF_OBJ_GET_INFO_BY_FD directly.
exit 0
// SPDX-License-Identifier: GPL-2.0
/*
* Credential allowlist for unprivileged user namespace creation. *
* Default deny. A caller is allowed to create a user namespace if any of:
* - its euid is in allowed_uids * - its egid is in allowed_gids * - any of its supplementary groups is in allowed_gids
*
* The maps are populated once (at first boot, from a config file) and then
* frozen with BPF_MAP_FREEZE, after which the kernel refuses further updates
* through the syscall interface even from root. Pin the program and the maps
* under bpffs so they survive the loader exiting.
*/
#include "vmlinux.h"
#include <errno.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>
char _license[] SEC("license") = "GPL";
/*
* Supplementary groups are walked with a fixed bound so the verifier can
* see termination. A caller in more than this many groups falls back to the
* euid/egid checks. Raise it, or switch to bpf_loop(), if that matters. */
#define MAX_SUPP_GROUPS 64
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 1024);
__type(key, __u32); /* uid */
__type(value, __u8);
} allowed_uids SEC(".maps");struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 1024);
__type(key, __u32); /* gid */
__type(value, __u8);
} allowed_gids SEC(".maps");/* Denials, so you can see what a policy would break before enforcing it. */
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 4096);
__type(key, __u32); /* uid */
__type(value, __u64); /* count */
} denied_uids SEC(".maps");static __always_inline int gid_allowed(__u32 gid)
{
return bpf_map_lookup_elem(&allowed_gids, &gid) != NULL;
}SEC("lsm/userns_create")
int BPF_PROG(userns_allowlist, const struct cred *cred, int ret)
{
struct group_info *gi;
__u32 uid, gid;
int i, ngroups;
__u64 init = 1, *count;
/* Someone before us already objected; do not launder their denial. */
if (ret)
return ret;
uid = BPF_CORE_READ(cred, euid.val);
if (bpf_map_lookup_elem(&allowed_uids, &uid))
return 0;
gid = BPF_CORE_READ(cred, egid.val);
if (gid_allowed(gid))
return 0;
/*
* The common deployment is one group that everyone permitted is a
* member of, which for most users is a supplementary group rather
* than their primary one, so egid alone is not enough.
*/
gi = BPF_CORE_READ(cred, group_info);
if (gi) {
ngroups = BPF_CORE_READ(gi, ngroups);
if (ngroups > MAX_SUPP_GROUPS)
ngroups = MAX_SUPP_GROUPS;
for (i = 0; i < MAX_SUPP_GROUPS; i++) {
if (i >= ngroups)
break;
/*
* struct group_info is __randomize_layout and gid[] is
* a flexible array, so this has to go through CO-RE
* rather than any assumed offset.
*/
if (bpf_core_read(&gid, sizeof(gid), &gi->gid[i].val))
break;
if (gid_allowed(gid))
return 0;
}
}
count = bpf_map_lookup_elem(&denied_uids, &uid);
if (count)
__sync_fetch_and_add(count, 1);
else
bpf_map_update_elem(&denied_uids, &uid, &init, BPF_NOEXIST);
return -EPERM;
}Quoted 12 lines · Hallgrimur H. Gunnarsson
Quoted 4 lines · Andy Lutomirski
Why should the task's cap masks affect this? *Maybe*
cap_bsetmakes sense, but I'm struggling a bit to see whycap_permittedandcap_effectiveshould matter.Sorry, the phrasing here may have been misleading. Just to clarify:
none of the creating task's capability sets (cap_bset,cap_permittedorcap_effective) are used to restrict the new user namespace.
Quoted 9 lines
When I wrote "reusing the existing task
cap_bset,cap_permittedandcap_effectivesets on namespace entry", I was contrasting this with the prior series from 2024 [1], which proposed adding a 6th per-thread capability set to struct cred.In this series, when a task creates or enters a user namespace, we simply initialize its new cred->cap_{bset,permitted,effective} in that namespace to
user_ns->cap_bsetinstead ofCAP_FULL_SET.
Okay, this makes *more* sense, but I think it's too weak.
I have a sort-of goal of having the creation of unprivileged namespaces be allowed in most contexts by default, *even in Docker* (which would involve the Docker team changing their default seccomp rules, but that bridge can be crossed later). (In furtherance of this goal, I fixed an ancient bug in newuidmap that gets us quite a bit closer a couple weeks ago.)
But tying this mitigation to a parent userns means that it's completely unusable in the single-deep case.
I do have a question about this whole scheme, though: are we talking *just* about CAP_NET_ADMIN? That is, is there any other bit that has anywhere near enough security relevance to make this kind of thing worthwhile? Because if it's really just a single bit control, maybe we can come up with a nicer scheme.
Signature · 2 lines
Andy Lutomirski AMA Capital Management, LLC
Quoted 33 lines · Andy Lutomirski
Quoted 12 lines · Hallgrimur H. Gunnarsson
Quoted 4 lines · Andy Lutomirski
Why should the task's cap masks affect this? *Maybe*
cap_bsetmakes sense, but I'm struggling a bit to see whycap_permittedandcap_effectiveshould matter.Sorry, the phrasing here may have been misleading. Just to clarify:
none of the creating task's capability sets (cap_bset,cap_permittedorcap_effective) are used to restrict the new user namespace.Quoted 9 lines
When I wrote "reusing the existing task
cap_bset,cap_permittedandcap_effectivesets on namespace entry", I was contrasting this with the prior series from 2024 [1], which proposed adding a 6th per-thread capability set to struct cred.In this series, when a task creates or enters a user namespace, we simply initialize its new cred->cap_{bset,permitted,effective} in that namespace to
user_ns->cap_bsetinstead ofCAP_FULL_SET.Okay, this makes *more* sense, but I think it's too weak.
I have a sort-of goal of having the creation of unprivileged namespaces be allowed in most contexts by default, *even in Docker* (which would involve the Docker team changing their default seccomp rules, but that bridge can be crossed later). (In furtherance of this goal, I fixed an ancient bug in newuidmap that gets us quite a bit closer a couple weeks ago.)
Quoted 2 lines
But tying this mitigation to a parent userns means that it's completely unusable in the single-deep case.
To clarify, this mitigation isn't exclusively tied to the parent userns. If a system administrator wants a host-wide policy, like trimming CAP_NET_ADMIN for all unprivileged user namespaces, including single-deep Docker containers, then the host-wide sysctl handles this seamlessly. Any unprivileged process in init_user_ns calling CLONE_NEWUSER is subjected to the sysctl ceiling, effectively stripping CAP_NET_ADMIN upon creation.
Where the single-deep case falls short in this series is per-container granularity. For flexible configuration on a per-container basis, this patch series assumes that containers run in their own user namespace, allowing the runtime to bound capabilities at creation time via clone3() and have that bound persist down the namespace hierarchy across any nested userns creation.
If a container runs in init_user_ns (as in standard Docker) and we want to restrict userns capabilities for that specific container without relying on a host-wide sysctl, then you are exactly right. We would need some kind of cred-based mechanism to pre-configure a restriction for any future CLONE_NEWUSER calls within that container.
Quoted 5 lines
I do have a question about this whole scheme, though: are we talking *just* about
CAP_NET_ADMIN? That is, is there any other bit that has anywhere near enough security relevance to make this kind of thing worthwhile? Because if it's really just a single bit control, maybe we can come up with a nicer scheme.
Yes, primarily CAP_NET_ADMIN, and to a lesser extent CAP_NET_RAW.
If we look at submissions to Google's kernelCTF VRP [1], 90% of the exploit submissions in 2026 require CAP_NET_ADMIN (and about 70% across all submissions since the program started in 2023).
Restricting these network capabilities when they are not strictly needed (e.g. for sandboxing) is the primary motivation behind the series. However, I wrote the userns capability bounding as a generic mask so it could restrict arbitrary capabilities down the hierarchy, but if the preference is to narrow the scope more specifically to trimming CAP_NET_ADMIN and CAP_NET_RAW, that's completely fine by me.
If we go that route and want to support the single-deep Docker case, a per-task inheritable securebit might be one way to do it, e.g. SECBIT_NO_USERNS_NET and SECBIT_NO_USERNS_NET_LOCKED. Docker could then set and lock that bit on a container in init_user_ns without needing a parent userns.
On userns creation, create_user_ns() could record this restriction on struct user_namespace. That could either feed into the userns capability bounding set proposed in this series (clearing CAP_NET_ADMIN and CAP_NET_RAW from user_ns->cap_bset when the bit is set on the creator), or be stored as a single boolean in struct user_namespace if we want to keep the mechanism minimal and drop the generic capability mask UAPI. In the latter case, we would still need to replicate some of the userns capability bounding functionality, e.g. strip CAP_NET_ADMIN and CAP_NET_RAW in set_cred_user_ns() on namespace entry, and bound the parent-owner check in cap_capable_helper().
[1] https://github.com/google/security-research/tree/master/pocs/linux/kernelctf
Quoted 113 lines · Hallgrimur H. Gunnarsson
When an unprivileged process creates a new user namespace, it is granted a full set of capabilities (
CAP_FULL_SET) scoped to that namespace. While these capabilities are isolated to the namespace, they allow unprivileged local users to reach deep kernel subsystems (most notably networking configuration and raw sockets viaCAP_NET_ADMINandCAP_NET_RAW) that historically assumed a trusted caller and have accounted for a large share of local privilege escalation vulnerabilities.Many workloads and sandboxes use unprivileged user namespaces strictly for basic UID/GID, mount, PID, or network isolation and never need high-risk capabilities like
CAP_NET_ADMINorCAP_NET_RAW. Likewise, system administrators often want a host-wide policy ceiling restricting which capabilities unprivileged user namespaces may acquire, without disabling unprivileged user namespaces altogether.Prior work by Jonathan Calmels [1] proposed addressing this via a sixth per-thread capability set (
cap_userns) alongside a global sysctl mask. During that discussion [1, 2], feedback (e.g. from Casey Schaufler) suggested that rather than adding another per-thread capability set andprctl()interface, capability restrictions could be integrated directly into structuser_namespaceand configured viaclone3(). At the same time, as noted in [1], aclone3()flag alone is not sufficient for administrators who need to enforce a host-wide ceiling on unprivileged user namespaces without modifying every userspace callsite.This series combines both pieces of feedback: it embeds a capability bounding set (
cap_bset) directly into structuser_namespace, reusing the existing taskcap_bset,cap_permitted, andcap_effectivesets on namespace entry, and provides both a system-wide sysctl ceiling for unprivileged user namespaces and aCLONE_NEWUSER_BSETflag for voluntary per-namespace restriction viaclone3().In addition, because restricting
CAP_NET_ADMINat user namespace creation time prevents userspace from bringing up the loopback interface in new network namespaces, the series first introduces an opt-in flag to automatically enable loopback on network namespace creation:1. Opt-in loopback activation on netns creation (Patch 1)
New network namespaces start with the loopback interface (lo) DOWN by default, requiring
CAP_NET_ADMINover the owning user namespace to bring it up. To block external network access while preserving localhost networking, sandboxes commonly create an isolated network namespace with only the loopback interface enabled.However, requiring a sandbox to hold
CAP_NET_ADMINin a new user namespace solely to bring loopback up conflicts with reducing theCAP_NET_ADMINattack surface. Today, an unprivileged sandbox must start withCAP_NET_ADMINto bring loopback up, drop it, and then blockCAP_NET_ADMINfrom being regained in nested user namespaces (e.g. via seccomp ormax_user_namespaceslimits). Conversely, whenCAP_NET_ADMINis restricted at user namespace creation time (via the sysctl ceiling orCLONE_NEWUSER_BSETintroduced in Patches 2-3, or via LSMs such as Landlock), tasks inside the new namespace never acquireCAP_NET_ADMINand cannot bring loopback up from userspace, breaking localhost networking for unprivileged sandboxes.Introduce the
CLONE_NEWNET_LOOPBACKflag forclone3()and the correspondingUNSHARE_NEWNET_LOOPBACKflag forunshare(), which implyCLONE_NEWNETand automatically bring the loopback device up incopy_net_ns()before returning the new network namespace. Making this an explicit opt-in preserves default network namespace semantics while allowing unprivileged sandboxes to create an isolated network namespace with functional localhost networking without ever holdingCAP_NET_ADMIN.2. Per-user-namespace capability bounding set & sysctl ceiling (Patch 2)
Add
cap_bsetto structuser_namespace(initialized toCAP_FULL_SETininit_user_ns) and introduce a system-wide sysctl ceiling for unprivileged users at:
/proc/sys/kernel/unprivileged_userns_caps_allowed
(defaulting toCAP_FULL_SET).When a new user namespace is created:
- Privileged creators (holdingCAP_SYS_ADMINin the parent user namespace) inheritcap_bsetfrom the parent user namespace.
- Unprivileged creators (lackingCAP_SYS_ADMINin the parent user namespace) have the child namespace's bounding set constrained by the sysctl ceiling combined with any effective capabilities the creator already holds in the parent namespace:
child_bset=parent_bset& (sysctl_ceiling|creator_effective)
Allowing the creator to retain capabilities it already holds in the parent namespace ensures that a process granted a specific capability (e.g.CAP_NET_ADMIN) does not lose it when creating a nested user namespace.When a task enters a user namespace via clone()/unshare() or
setns(), itscap_bset,cap_permitted, andcap_effectivesets are clamped touser_ns->cap_bset. In addition,cap_capable_helper()is updated so that implicit capabilities granted to the parent-namespace owner of a user namespace are likewise bounded by the owned namespace'scap_bset.3. Per-namespace restriction via
clone3()(Patch 3)Introduce
CLONE_NEWUSER_BSETand addcap_bsetto structclone_args. When specified alongsideCLONE_NEWUSER, the new user namespace's bounding set is further intersected with the requestedcap_bsetmask, allowing container runtimes and sandboxes to drop unneeded capabilities from a user namespace at creation time even when permitted by the global sysctl.4. Introspection via
NS_USER_GET_INFO(Patch 4)While tasks inside a user namespace see their initial ceiling in /proc/<pid>/status (CapBnd), threads may subsequently drop individual capabilities from their per-thread bounding set. Add an extensible
NS_USER_GET_INFOioctl on userns file descriptors to allow userspace to directly query a user namespace'scap_bset.
Quoted 6 lines
5. Selftests (Patches 5-8)
Add kselftest suites covering
CLONE_NEWNET_LOOPBACK, the sysctl ceiling, creator capability retention, nested monotonicity, parent-owner bounding,CLONE_NEWUSER_BSETandNS_USER_GET_INFO.
FYI I'm doing something similar with cells
(https://github.com/josefbacik/linux/tree/cells) that gives the same sort of discrete control over the different parts of the network.
I super dislike this mapping of user to capabilities, as you said it creates this hodgepodge of areas that need to be updated and just creates more possibility of escapes where we get it wrong.
Extending userns makes sense in the current landscape, but I'd rather get away from using arbitrary user ids + a capability set as a control for what a task can do. Thanks,
Josef
Quoted 18 lines · Serge E. Hallyn
Generally, if I, or some users I support, need to use unprivileged containers or user namespaces, then when an 0day comes along, I can hopefully trust them not to exploit it. The biggest danger comes from the fact that, right now, if they can use them, anyone can. So if someone can trigger some other code running as user nginx or something, that can become a root vector.
So what if we had a built-in feature or LSM which implemented a credential based whitelist, entered at firstboot? Something like
``` # Default deny uid == 1000 # approved 1005 < uid < 1010 # approved gid == 1005 security_label = lxc_user_t # Not sure how far we want to go with this tty # must have a session ```
Quoted 3 lines
Now, if you want to use user namespaces for generic sandboxes for all users, e.g. to confine browser activity or nginx modules, then this model may not fit. Or rather, it might need a few tweaks.
Thanks for taking a look and sharing the credential-based allowlist.
The latter scenario (generic sandboxes for all users) is actually the primary use case that I'm targeting. I want to allow unprivileged users to create user namespaces, e.g. for sandboxing, but without granting them security-sensitive network capabilities (CAP_NET_ADMIN/CAP_NET_RAW) when they are not strictly needed, given the historically high risk of local privilege escalation associated with them.
The two approaches target complementary layers of the problem. A credential allowlist at creation time controls who can create a user namespace, while this patch series controls what capabilities are available inside that namespace (and its descendants) once it is created.
Gating creation works well when there is a clear boundary between trusted and untrusted users. However, in a multi-tenant environment (like a large container fleet), we generally treat workloads as untrusted by default. Because we still want to allow these untrusted workloads to use unprivileged user namespaces for sandboxing, it is essential to keep the attack surface small and follow the principle of least privilege whenever possible.
More specifically, this patch series enables that model of safe sandboxing across three key use cases:
1. Configurable capability stripping: Administrators can enable unprivileged user namespaces for all users to support sandboxing, but configure the system to strip CAP_NET_ADMIN and CAP_NET_RAW by default in new user namespaces created by unprivileged users. Basic sandboxing rarely needs these (except to bring up loopback, which Patch 1 addresses via CLONE_NEWNET_LOOPBACK).
The per-namespace bounding set can enforce this either globally via the sysctl, or explicitly via clone3() at the container manager level. This restriction is monotonic and persists down the namespace hierarchy.
2. Selectively granting CAP_NET_ADMIN: Some containerized workloads legitimately need CAP_NET_ADMIN to configure advanced networking for sub-containers. Because an unprivileged creator's child namespace is bounded by:
parent_bset & (sysctl_ceiling | creator_effective)
a container that is explicitly granted CAP_NET_ADMIN in its own user namespace automatically propagates that capability into the bounding set of any child namespace it creates (unless it is explicitly dropped).
3. Dropping capabilities for nested namespaces: If a container with CAP_NET_ADMIN needs to spawn an inner user namespace to run untrusted code in a nested sandbox, it can use CLONE_NEWUSER_BSET to voluntarily drop CAP_NET_ADMIN from the inner namespace's bounding set. This guarantees the nested sandbox cannot access the capability and the restriction persists for all further descendants.
As a quick clarification on how this interacts with the hierarchy: the bounding set restricts tasks inside the namespace and parent tasks relying purely on the parent-ownership check. It does not restrict tasks in an ancestor userns that inherently hold the capability. Therefore, in the nested sandbox scenario above (#3), the parent container with CAP_NET_ADMIN can still configure the sandbox's network from the outside (by using setns() to enter the nested netns directly) even though CAP_NET_ADMIN is stripped inside the sandbox userns.
Quoted 38 lines · Hallgrimur H. Gunnarsson
Quoted 33 lines · Andy Lutomirski
Quoted 12 lines · Hallgrimur H. Gunnarsson
Quoted 4 lines · Andy Lutomirski
Why should the task's cap masks affect this? *Maybe*
cap_bsetmakes sense, but I'm struggling a bit to see whycap_permittedandcap_effectiveshould matter.Sorry, the phrasing here may have been misleading. Just to clarify:
none of the creating task's capability sets (cap_bset,cap_permittedorcap_effective) are used to restrict the new user namespace.Quoted 9 lines
When I wrote "reusing the existing task
cap_bset,cap_permittedandcap_effectivesets on namespace entry", I was contrasting this with the prior series from 2024 [1], which proposed adding a 6th per-thread capability set to struct cred.In this series, when a task creates or enters a user namespace, we simply initialize its new cred->cap_{bset,permitted,effective} in that namespace to
user_ns->cap_bsetinstead ofCAP_FULL_SET.Okay, this makes *more* sense, but I think it's too weak.
I have a sort-of goal of having the creation of unprivileged namespaces be allowed in most contexts by default, *even in Docker* (which would involve the Docker team changing their default seccomp rules, but that bridge can be crossed later). (In furtherance of this goal, I fixed an ancient bug in newuidmap that gets us quite a bit closer a couple weeks ago.)
Quoted 2 lines
But tying this mitigation to a parent userns means that it's completely unusable in the single-deep case.
Quoted 7 lines
To clarify, this mitigation isn't exclusively tied to the parent userns. If a system administrator wants a host-wide policy, like trimming
CAP_NET_ADMINfor all unprivileged user namespaces, including single-deep Docker containers, then the host-wide sysctl handles this seamlessly. Any unprivileged process ininit_user_nscallingCLONE_NEWUSERis subjected to the sysctl ceiling, effectively strippingCAP_NET_ADMINupon creation.
Seems reasonable, but see below.
Quoted 7 lines
Where the single-deep case falls short in this series is per-container granularity. For flexible configuration on a per-container basis, this patch series assumes that containers run in their own user namespace, allowing the runtime to bound capabilities at creation time via
clone3()and have that bound persist down the namespace hierarchy across any nested userns creation.
There are plenty of cases of *privileged* user namespaces (i.e. created by privileged users) that would nonetheless want this. Or unprivileged user namespaces on systems that will not have this restriction set that still want to apply it in their own container.
Quoted 26 lines
If a container runs in
init_user_ns(as in standard Docker) and we want to restrict userns capabilities for that specific container without relying on a host-wide sysctl, then you are exactly right. We would need some kind of cred-based mechanism to pre-configure a restriction for any futureCLONE_NEWUSERcalls within that container.Quoted 5 lines
I do have a question about this whole scheme, though: are we talking *just* about
CAP_NET_ADMIN? That is, is there any other bit that has anywhere near enough security relevance to make this kind of thing worthwhile? Because if it's really just a single bit control, maybe we can come up with a nicer scheme.Yes, primarily
CAP_NET_ADMIN, and to a lesser extentCAP_NET_RAW.If we look at submissions to Google's kernelCTF VRP [1], 90% of the exploit submissions in 2026 require
CAP_NET_ADMIN(and about 70% across all submissions since the program started in 2023).Restricting these network capabilities when they are not strictly needed (e.g. for sandboxing) is the primary motivation behind the series. However, I wrote the userns capability bounding as a generic mask so it could restrict arbitrary capabilities down the hierarchy, but if the preference is to narrow the scope more specifically to trimming
CAP_NET_ADMINandCAP_NET_RAW, that's completely fine by me.
Quoted 5 lines
If we go that route and want to support the single-deep Docker case, a per-task inheritable securebit might be one way to do it, e.g.
SECBIT_NO_USERNS_NETandSECBIT_NO_USERNS_NET_LOCKED. Docker could then set and lock that bit on a container ininit_user_nswithout needing a parent userns.
This seems perhaps better. But maybe a bit that applies the restriction to a userns created by someone who doesn't have CAP_NET_ADMIN in their own userns?
IMO what we really want is a generic mechanism for sysctl-like settings that are scoped to a userns. And we would want the API not to be filesystem-based (or at least not require *mounting* a filesystem) because then we would just make everything messier. This would solve many problems.
Quoted 13 lines
On userns creation,
create_user_ns()could record this restriction on structuser_namespace. That could either feed into the userns capability bounding set proposed in this series (clearingCAP_NET_ADMINandCAP_NET_RAWfromuser_ns->cap_bsetwhen the bit is set on the creator), or be stored as a single boolean in structuser_namespaceif we want to keep the mechanism minimal and drop the generic capability mask UAPI. In the latter case, we would still need to replicate some of the userns capability bounding functionality, e.g. stripCAP_NET_ADMINandCAP_NET_RAWinset_cred_user_ns()on namespace entry, and bound the parent-owner check incap_capable_helper().[1] https://github.com/google/security-research/tree/master/pocs/linux/kernelctf
Quoted 59 lines · Hallgrimur H. Gunnarsson
Quoted 18 lines · Serge E. Hallyn
Generally, if I, or some users I support, need to use unprivileged containers or user namespaces, then when an 0day comes along, I can hopefully trust them not to exploit it. The biggest danger comes from the fact that, right now, if they can use them, anyone can. So if someone can trigger some other code running as user nginx or something, that can become a root vector.
So what if we had a built-in feature or LSM which implemented a credential based whitelist, entered at firstboot? Something like
``` # Default deny uid == 1000 # approved 1005 < uid < 1010 # approved gid == 1005 security_label = lxc_user_t # Not sure how far we want to go with this tty # must have a session ```Quoted 3 lines
Now, if you want to use user namespaces for generic sandboxes for all users, e.g. to confine browser activity or nginx modules, then this model may not fit. Or rather, it might need a few tweaks.
Thanks for taking a look and sharing the credential-based allowlist.
The latter scenario (generic sandboxes for all users) is actually the primary use case that I'm targeting. I want to allow unprivileged users to create user namespaces, e.g. for sandboxing, but without granting them security-sensitive network capabilities (CAP_NET_ADMIN/CAP_NET_RAW) when they are not strictly needed, given the historically high risk of local privilege escalation associated with them.
The two approaches target complementary layers of the problem. A credential allowlist at creation time controls who can create a user namespace, while this patch series controls what capabilities are available inside that namespace (and its descendants) once it is created.
Gating creation works well when there is a clear boundary between trusted and untrusted users. However, in a multi-tenant environment (like a large container fleet), we generally treat workloads as untrusted by default. Because we still want to allow these untrusted workloads to use unprivileged user namespaces for sandboxing, it is essential to keep the attack surface small and follow the principle of least privilege whenever possible.
More specifically, this patch series enables that model of safe sandboxing across three key use cases:
1. Configurable capability stripping: Administrators can enable unprivileged user namespaces for all users to support sandboxing, but configure the system to strip
CAP_NET_ADMINandCAP_NET_RAWby default in new user namespaces created by unprivileged users. Basic sandboxing rarely needs these (except to bring up loopback, which Patch 1 addresses viaCLONE_NEWNET_LOOPBACK).The per-namespace bounding set can enforce this either globally via the sysctl, or explicitly via
clone3()at the container manager level. This restriction is monotonic and persists down the namespace hierarchy.
Quoted 6 lines
2. Selectively granting
CAP_NET_ADMIN: Some containerized workloads legitimately needCAP_NET_ADMINto configure advanced networking for sub-containers. Because an unprivileged creator's child namespace is bounded by:
parent_bset& (sysctl_ceiling|creator_effective)
Right after sending my last email, I had the following thought of a variant of the model. Permission to gain CAP_NET_ADMIN via creating a userns is kind of like a capability itself, right? We could get pretty close to nice semantics if we allocated a capability bit for this (CAP_USERNS_NET_ADMIN perhaps?) and, by default, giving it to all users. Unfortunately, the latter part is tricky because even sticking it in the ambient set won't keep it from being dropped by setuid.
Perhaps we could have an extra capability mask that is for default-on capabilities.
The intuition for this is that permission to gain capabilities in a userns is a mess if it's a sysctl (as sysctls are global and there is no clean way to say that a particular unprivileged task may nonetheless create namespaces with CAP_NET_ADMIN) and it's a mess if it's a securebit (still has the latter problem), but it's much tidier if it's tied to a task.
Christian Brauner
maintainerQuoted 3 lines · Serge E. Hallyn
Kees whipped up a proof of concept BPF lsm that implemented this. A copy from his email (and let's call it GPLv2 unless he wants to change it to something like MIT) follows:
There's no need to special-case user namespaces for this anymore. I've added generic namespace LSM hooks for v7.4-rc1:
* namespace_init()
* namespace_install() (setns())
* namespace_free()
called from the common namespace code I added and for every namespace type.
So a policy like this can cover creation and setns() of all namespaces and follow a namespace by its id until it's gone.
The catch is that what got merged doesn't work with the bpf LSM right now.
namespace_free() is never called unless an LSM allocated a namespace blob, namespace_init() sees a namespace id of zero because the id is allocated after the hook has run, and the bpf LSM marks the namespace arguments of both hooks as trusted although the namespace can be freed right after.
I sent fixes for all of that (cf. [1], [2]) (cf. [3]).
[1]: https://lore.kernel.org/all/20261026-work-security-namespace_free-v1-0-ffa3ebbf71bd@kernel.org
[2]: https://lore.kernel.org/all/20261029-work-security-namespace_free-v2-0-65591dbba7b3@kernel.org
[3]: https://lore.kernel.org/all/CAHC9VhRwD1c1qKK4=Uc8cbMy27iF722C0DZeXy4WGtH-kOBOcQ@mail.gmail.com
Christian Brauner
maintainerQuoted 9 lines · Andy Lutomirski
The whole unshare/clone flag situation is getting out of hand, IMO. And this new thing makes logical sense but is really about reducing exposure.
Perhaps we should instead have a small list associated with a userns (extensible in the future) of things that the ns's admin (i.e. whoever has
CAP_SYS_ADMINrelative to the ns) may do. That list could include:
Quoted 5 lines
- Create loopback with sensible defaults for ipv4 and/or ipv6 (i see no obvious reason to separate them)
- Create tun/tap interfaces in that ns (and attach them, etc)And add a very simple new API to do these things. Actually, the
We've had this idea in the past and I think it is reasonable. I had always thought that we should expose a system call to create empty namespaces ot any type. Usually I'd be excited about that but I think that point is a bit moot and I'd really like see whether we can turn cells (or whatever other name) into a first class api.
The problem I have with the patchset as written is that adds a lot of moving parts. And yes, I find the CLONE_* and UNSHARE_* flags plus sysctl to be suboptimal as well.
So the TL;DR is that CAP_NET_ADMIN + userns = CAP_NET_PRIVILEGE_ESCALATION 10+ years later. And this patchset wants to put it back on a leash.
So why isn't an aggressively stupid solution to this problem to split a new capability out of CAP_NET_ADMIN so it covers the absolute minimal set of things that should be allowed instead of doing effectively the same thing but split over multiple apis?
Anything that is reasonably advanced should not be the kernel's responsibility to delegate. I really think the old privilege model where the kernel grants control over a whole subsystem is inherently flawed and is much better replaced if you have the means to let userspace services grant and delegate resources.
Hi,
I think this is mostly solved with Landlock (kernel v7.4), see
https://docs.kernel.org/userspace-api/landlock.html#capability-and-namespace-restrictions
and
https://lore.kernel.org/all/[email protected]/
This approach is agnostic to UID, cgroups, or other ways to identify processes, so it should fit any use case.
What is missing is a split of capabilities (e.g. CAP_NET_ADMIN) that makes sense from a security and (user) namespace point of view.
Regards,
Mickaël
Quoted 181 lines · Hallgrimur H. Gunnarsson
When an unprivileged process creates a new user namespace, it is granted a full set of capabilities (
CAP_FULL_SET) scoped to that namespace. While these capabilities are isolated to the namespace, they allow unprivileged local users to reach deep kernel subsystems (most notably networking configuration and raw sockets viaCAP_NET_ADMINandCAP_NET_RAW) that historically assumed a trusted caller and have accounted for a large share of local privilege escalation vulnerabilities.Many workloads and sandboxes use unprivileged user namespaces strictly for basic UID/GID, mount, PID, or network isolation and never need high-risk capabilities like
CAP_NET_ADMINorCAP_NET_RAW. Likewise, system administrators often want a host-wide policy ceiling restricting which capabilities unprivileged user namespaces may acquire, without disabling unprivileged user namespaces altogether.Prior work by Jonathan Calmels [1] proposed addressing this via a sixth per-thread capability set (
cap_userns) alongside a global sysctl mask. During that discussion [1, 2], feedback (e.g. from Casey Schaufler) suggested that rather than adding another per-thread capability set andprctl()interface, capability restrictions could be integrated directly into structuser_namespaceand configured viaclone3(). At the same time, as noted in [1], aclone3()flag alone is not sufficient for administrators who need to enforce a host-wide ceiling on unprivileged user namespaces without modifying every userspace callsite.This series combines both pieces of feedback: it embeds a capability bounding set (
cap_bset) directly into structuser_namespace, reusing the existing taskcap_bset,cap_permitted, andcap_effectivesets on namespace entry, and provides both a system-wide sysctl ceiling for unprivileged user namespaces and aCLONE_NEWUSER_BSETflag for voluntary per-namespace restriction viaclone3().In addition, because restricting
CAP_NET_ADMINat user namespace creation time prevents userspace from bringing up the loopback interface in new network namespaces, the series first introduces an opt-in flag to automatically enable loopback on network namespace creation:1. Opt-in loopback activation on netns creation (Patch 1)
New network namespaces start with the loopback interface (lo) DOWN by default, requiring
CAP_NET_ADMINover the owning user namespace to bring it up. To block external network access while preserving localhost networking, sandboxes commonly create an isolated network namespace with only the loopback interface enabled.However, requiring a sandbox to hold
CAP_NET_ADMINin a new user namespace solely to bring loopback up conflicts with reducing theCAP_NET_ADMINattack surface. Today, an unprivileged sandbox must start withCAP_NET_ADMINto bring loopback up, drop it, and then blockCAP_NET_ADMINfrom being regained in nested user namespaces (e.g. via seccomp ormax_user_namespaceslimits). Conversely, whenCAP_NET_ADMINis restricted at user namespace creation time (via the sysctl ceiling orCLONE_NEWUSER_BSETintroduced in Patches 2-3, or via LSMs such as Landlock), tasks inside the new namespace never acquireCAP_NET_ADMINand cannot bring loopback up from userspace, breaking localhost networking for unprivileged sandboxes.Introduce the
CLONE_NEWNET_LOOPBACKflag forclone3()and the correspondingUNSHARE_NEWNET_LOOPBACKflag forunshare(), which implyCLONE_NEWNETand automatically bring the loopback device up incopy_net_ns()before returning the new network namespace. Making this an explicit opt-in preserves default network namespace semantics while allowing unprivileged sandboxes to create an isolated network namespace with functional localhost networking without ever holdingCAP_NET_ADMIN.2. Per-user-namespace capability bounding set & sysctl ceiling (Patch 2)
Add
cap_bsetto structuser_namespace(initialized toCAP_FULL_SETininit_user_ns) and introduce a system-wide sysctl ceiling for unprivileged users at:
/proc/sys/kernel/unprivileged_userns_caps_allowed
(defaulting toCAP_FULL_SET).When a new user namespace is created:
- Privileged creators (holdingCAP_SYS_ADMINin the parent user namespace) inheritcap_bsetfrom the parent user namespace.
- Unprivileged creators (lackingCAP_SYS_ADMINin the parent user namespace) have the child namespace's bounding set constrained by the sysctl ceiling combined with any effective capabilities the creator already holds in the parent namespace:
child_bset=parent_bset& (sysctl_ceiling|creator_effective)
Allowing the creator to retain capabilities it already holds in the parent namespace ensures that a process granted a specific capability (e.g.CAP_NET_ADMIN) does not lose it when creating a nested user namespace.When a task enters a user namespace via clone()/unshare() or
setns(), itscap_bset,cap_permitted, andcap_effectivesets are clamped touser_ns->cap_bset. In addition,cap_capable_helper()is updated so that implicit capabilities granted to the parent-namespace owner of a user namespace are likewise bounded by the owned namespace'scap_bset.3. Per-namespace restriction via
clone3()(Patch 3)Introduce
CLONE_NEWUSER_BSETand addcap_bsetto structclone_args. When specified alongsideCLONE_NEWUSER, the new user namespace's bounding set is further intersected with the requestedcap_bsetmask, allowing container runtimes and sandboxes to drop unneeded capabilities from a user namespace at creation time even when permitted by the global sysctl.4. Introspection via
NS_USER_GET_INFO(Patch 4)While tasks inside a user namespace see their initial ceiling in /proc/<pid>/status (CapBnd), threads may subsequently drop individual capabilities from their per-thread bounding set. Add an extensible
NS_USER_GET_INFOioctl on userns file descriptors to allow userspace to directly query a user namespace'scap_bset.5. Selftests (Patches 5-8)
Add kselftest suites covering
CLONE_NEWNET_LOOPBACK, the sysctl ceiling, creator capability retention, nested monotonicity, parent-owner bounding,CLONE_NEWUSER_BSETandNS_USER_GET_INFO.[1] https://lore.kernel.org/all/[email protected]/
[2] https://lwn.net/Articles/978846/Note on tree routing:
While Patch 1 (
CLONE_NEWNET_LOOPBACK) touchesnet/core/net_namespace.c, most of its changes add clone3()/unshare() flag plumbing ininclude/uapi/linux/sched.h,kernel/fork.c, andkernel/nsproxy.c, which Patch 3 (CLONE_NEWUSER_BSET) builds directly on top of. To avoid merge conflicts inkernel/fork.candinclude/uapi/linux/sched.h, it may be simplest to route the entire series through a single tree, e.g. a namespace branch in vfs.git with Acked-by from the netdev and capabilities/credentials maintainers, or whichever tree the maintainers prefer.Hallgrimur H. Gunnarsson (8):
net: introduceCLONE_NEWNET_LOOPBACKto auto-enable loopback
userns: introduce capability bounding set for user namespaces
userns: allow restricting capability bounding set viaclone3()
nsfs: addNS_USER_GET_INFOioctl to inspect user namespace
capabilities
selftests/net: add test suite forCLONE_NEWNET_LOOPBACKselftests/capabilities: tests for user namespace capability bounding
set
selftests/capabilities: addclone3()tests forCLONE_NEWUSER_BSETselftests/nsfs: add tests forNS_USER_GET_INFOioctlDocumentation/admin-guide/sysctl/kernel.rst | 37 ++ fs/nsfs.c | 29 + include/linux/cred.h | 3 +- include/linux/sched/task.h | 1 + include/linux/user_namespace.h | 20 +- include/uapi/linux/nsfs.h | 17 + include/uapi/linux/sched.h | 9 + kernel/cred.c | 10 +- kernel/fork.c | 38 +- kernel/nsproxy.c | 9 + kernel/user.c | 1 + kernel/user_namespace.c | 100 +++- net/core/net_namespace.c | 11 + security/commoncap.c | 8 +- .../testing/selftests/capabilities/.gitignore | 1 + tools/testing/selftests/capabilities/Makefile | 2 +- .../capabilities/userns_bounding_set_test.c | 566 ++++++++++++++++++ .../selftests/clone3/clone3_selftests.h | 1 + .../selftests/filesystems/nsfs/.gitignore | 1 + .../selftests/filesystems/nsfs/Makefile | 4 +- .../selftests/filesystems/nsfs/userns.c | 120 ++++ tools/testing/selftests/net/.gitignore | 1 + tools/testing/selftests/net/Makefile | 1 + tools/testing/selftests/net/loopback_netns.c | 103 ++++ 24 files changed, 1069 insertions(+), 24 deletions(-) create mode 100644 tools/testing/selftests/capabilities/userns_bounding_set_test.c create mode 100644 tools/testing/selftests/filesystems/nsfs/userns.c create mode 100644 tools/testing/selftests/net/loopback_netns.cbase-commit:
cee9395acd8043be0644b25c34bfa86623f2b935Signature · 1 line
2.56.0.313.g2479322e68-goog
Quoted 27 lines · Christian Brauner
Quoted 9 lines · Andy Lutomirski
The whole unshare/clone flag situation is getting out of hand, IMO. And this new thing makes logical sense but is really about reducing exposure.
Perhaps we should instead have a small list associated with a userns (extensible in the future) of things that the ns's admin (i.e. whoever has
CAP_SYS_ADMINrelative to the ns) may do. That list could include:Quoted 5 lines
- Create loopback with sensible defaults for ipv4 and/or ipv6 (i see no obvious reason to separate them)
- Create tun/tap interfaces in that ns (and attach them, etc)And add a very simple new API to do these things. Actually, the
We've had this idea in the past and I think it is reasonable. I had always thought that we should expose a system call to create empty namespaces ot any type. Usually I'd be excited about that but I think that point is a bit moot and I'd really like see whether we can turn cells (or whatever other name) into a first class api.
The problem I have with the patchset as written is that adds a lot of moving parts. And yes, I find the CLONE_* and UNSHARE_* flags plus sysctl to be suboptimal as well.
Quoted 8 lines
So the TL;DR is that
CAP_NET_ADMIN+ userns =CAP_NET_PRIVILEGE_ESCALATION10+ years later. And this patchset wants to put it back on a leash.So why isn't an aggressively stupid solution to this problem to split a new capability out of
CAP_NET_ADMINso it covers the absolute minimal set of things that should be allowed instead of doing effectively the same thing but split over multiple apis?
Because we don't actually have a clean way to make a list of privileges that are, in theory, harmless but are hazardous from an attack surface perspective and assign them only to tasks that ought to have them.
But maybe we should invent such a thing. It would be very, very nice.
Other than that, I agree with you.
Quoted 6 lines
Anything that is reasonably advanced should not be the kernel's responsibility to delegate. I really think the old privilege model where the kernel grants control over a whole subsystem is inherently flawed and is much better replaced if you have the means to let userspace services grant and delegate resources.
Signature · 2 lines
Andy Lutomirski AMA Capital Management, LLC
Quoted 37 lines · Andy Lutomirski
Quoted 27 lines · Christian Brauner
Quoted 9 lines · Andy Lutomirski
The whole unshare/clone flag situation is getting out of hand, IMO. And this new thing makes logical sense but is really about reducing exposure.
Perhaps we should instead have a small list associated with a userns (extensible in the future) of things that the ns's admin (i.e. whoever has
CAP_SYS_ADMINrelative to the ns) may do. That list could include:Quoted 5 lines
- Create loopback with sensible defaults for ipv4 and/or ipv6 (i see no obvious reason to separate them)
- Create tun/tap interfaces in that ns (and attach them, etc)And add a very simple new API to do these things. Actually, the
We've had this idea in the past and I think it is reasonable. I had always thought that we should expose a system call to create empty namespaces ot any type. Usually I'd be excited about that but I think that point is a bit moot and I'd really like see whether we can turn cells (or whatever other name) into a first class api.
The problem I have with the patchset as written is that adds a lot of moving parts. And yes, I find the CLONE_* and UNSHARE_* flags plus sysctl to be suboptimal as well.
Quoted 8 lines
So the TL;DR is that
CAP_NET_ADMIN+ userns =CAP_NET_PRIVILEGE_ESCALATION10+ years later. And this patchset wants to put it back on a leash.So why isn't an aggressively stupid solution to this problem to split a new capability out of
CAP_NET_ADMINso it covers the absolute minimal set of things that should be allowed instead of doing effectively the same thing but split over multiple apis?
Quoted 4 lines
Because we don't actually have a clean way to make a list of privileges that are, in theory, harmless but are hazardous from an attack surface perspective and assign them only to tasks that ought to have them.
Exactly. Furthermore, even if we split a minimal capability out of CAP_NET_ADMIN, create_user_ns() still grants CAP_FULL_SET to new unprivileged user namespaces by default. Without a mechanism to withhold capabilities that are namespaced in scope but carry high attack surface risk (like CAP_NET_ADMIN and CAP_NET_RAW) and only selectively grant them to tasks that really need them, an unprivileged userns would still receive the full set of capabilities.
Providing that mechanism is the core goal of the per-userns capability bounding set in this series. Even on its own, without any loopback changes, it can be configured to prevent unprivileged users from acquiring CAP_NET_ADMIN and CAP_NET_RAW when creating a new userns + netns, while still supporting sandboxes that use a completely disconnected netns or containers whose networking is configured externally.
Finding a solution for loopback simply makes this bounding set more practical, as it allows us to also support sandboxes that rely on localhost networking without forcing them to retain full CAP_NET_ADMIN.
With a way to withhold CAP_NET_ADMIN from unprivileged userns, splitting out a minimal capability (as Christian suggests) is a very appealing way to handle the allowed subset for loopback, though the main challenge is defining a scope that justifies a capability bit without re-introducing LPE risk.
Looking at the CAP_NET_ADMIN LPEs from Google's kernelCTF, most are concentrated in netfilter and tc, with a smaller number in virtual interfaces and routing. Simply bringing up loopback at netns init shouldn't carry any LPE risk, but something like CAP_NET_LOOPBACK_UP is obviously too specific to warrant a capability bit. Conversely, broadening it into something like CAP_NET_IFCONFIG (allowing link state, L3 address and basic route configuration on existing interfaces) might justify a bit, but even such a basic subset would still re-introduce some LPE risk (see e.g. CVE-2026-53259 / commit f723ccaff2fb), although it would drastically reduce the risk by excluding the most high-risk components.
Furthermore, I think splitting out a smaller CAP_NET_ADMIN would also run into some practical difficulties when it comes to clean enforcement in rtnetlink. Currently, rtnetlink_rcv_msg() relies on a coarse CAP_NET_ADMIN check at the beginning before any complex message parsing occurs. To support more fine-grained capabilities, we would have to push these checks much deeper into the stack, spreading security checks across many locations, which could easily lead to mistakes.
Given this, I was hoping to have a minimal mechanism to just allow bringing up loopback without going for a new capability bit. Ultimately, it's a pragmatic judgment call. Maybe something like CAP_NET_IFCONFIG offers enough value and risk reduction to be worth the trade-off.
Otherwise, if we want to avoid consuming a capability bit just for loopback, we could also consider other alternatives, e.g. a small nsfs ioctl on the netns fd (e.g. NS_NET_LOOPBACK_UP). This would align with Andy's earlier suggestion of adding a "very simple new API" dedicated to these safely scoped operations.
If we drop CLONE_NEWNET_LOOPBACK / UNSHARE_NEWNET_LOOPBACK from this series and handle loopback separately, do you think the per-userns bounding set is a reasonable approach for withholding capabilities (e.g. CAP_NET_ADMIN and CAP_NET_RAW) from unprivileged userns, or would you prefer a different mechanism?
I think the single-deep case we were discussing on the other thread could also be cleanly built on top of this. The per-userns bounding set provides the underlying enforcement mechanism. How we configure and trigger that bounding, whether via sysctl and clone3() as proposed in this series, or via a per-task securebit to handle single-deep containers in init_user_ns as discussed on the other thread, is a policy control interface decision that can feed directly into the same mechanism.
To address the concern about the number of moving parts, I am also happy to simplify the control interfaces. If we decide a per-task securebit is the cleanest way to drive this configuration for both single-deep and nested cases, we could focus on that and drop the clone3() and sysctl from this series entirely, or only expose whatever subset you prefer.
Thanks!
Christian Brauner
maintainerQuoted 5 lines · Hallgrimur H. Gunnarsson
If we drop
CLONE_NEWNET_LOOPBACK/UNSHARE_NEWNET_LOOPBACKfrom this series and handle loopback separately, do you think the per-userns bounding set is a reasonable approach for withholding capabilities (e.g.CAP_NET_ADMINandCAP_NET_RAW) from unprivileged userns, or would you prefer a different mechanism?
Seems ok to me.
Quoted 6 lines
To address the concern about the number of moving parts, I am also happy to simplify the control interfaces. If we decide a per-task securebit is the cleanest way to drive this configuration for both single-deep and nested cases, we could focus on that and drop the
clone3()and sysctl from this series entirely, or only expose whatever subset you prefer.
Just a note on the essay I cut off. I really object to any arguments that amount to "it's too much work" propped up by a few thin arguments sprinkled in such as rtnetlink.
I also reject any arguments that amount to underscoping and overscoping of the new capability. The scope is clear: empty netns with brought up loop device.
I'm 180 patches deep into fixing procfs and 41 patches deep into preventing loop devices from abuse. Either we do the work and get something better or we do the same thing we've always done and hope we end up happily ever after.
But again, I'm more focussed on cells so here's what I find acceptable:
I'd rather go back to what Jonathan proposed in 2024 (cf. [1]). A per-task userns capability mask. Serge acked the core of it back then. It's at least generic and not just the single securebit capability thing. And we'd burn a new bit for every capability that turns out to be a problem later.
Jonathan's version had holes though. The restriction only lived in the task's creds so the owner rule and setns() blew this up. So it needs to be combined with your per-namespace set. Roughly:
* every task carries a mask, cred->cap_userns, full by default fork, exec, setuid and entering a namespace never change it
* a new user namespace records
ns->cap_bset = parent->cap_bset &
(cred->cap_userns | cred->cap_permitted); once at creation and never changes it again => it's monotonic downwards
* the creator gets ns->cap_bset instead of CAP_FULL_SET
* a task that setns()es in later gets
ns->cap_bset & (cred->cap_userns | cred->cap_permitted)
* the owner rule in cap_capable_helper() grants exactly what entering would and otherwise falls through to what the owner has
So caps a task actually has always count as allowed => should check Andy's "only restrict creators that don't have
CAP_NET_ADMIN themselves" per capability.
This amounts to a host-wide default without a sysctl. PID 1 drops CAP_NET_ADMIN and CAP_NET_RAW from its own mask at boot and everything inherits that.
Root, sudo and setuid-root binaries have those capabilities so nothing changes for them. A regular user doesn't and so their user namespaces come without CAP_NET_ADMIN and CAP_NET_RAW.
This also covers newgrp, su and sudo -u shells which is where resetting the mask on setuid exec (Which was raised by Serge in the other thread.).
* Root in a container has caps as well so for containers the exemption would be wrong.
So here we need a a lockable SECURE_NO_USERNS_CAP_RAISE bit thingy. This turns off the exemption and prevents raising the mask.
Docker lowers the mask, sets and locks the bit, and unshare(CLONE_NEWUSER) in the container doesn't hand out CAP_NET_ADMIN anymore.
=> no parent user namespace needed for the single-nesting case.
So a container with CAP_NET_ADMIN lowers its mask before it spawns the nested container => should cover your (3) case.
uAPI is a prctl modeled on the ambient capset:
* PR_CAP_USERNS with IS_SET, RAISE, LOWER and CLEAR_ALL
* lowering needs no_new_privs or CAP_SETPCAP
=> handles sendmail-style problem Serge raised on Jonathan's series.
* a new CapUns: line in /proc/<pid>/status
* new audit mask in AUDIT_CAPSET record
Raising needs the capability in the permitted set.
Fwiw, neither series handles ptrace. A task with a restricted mask can attach a less restricted task of the same uid and then make it create the namespace.
cap_ptrace_access_check() only compares permitted sets so far. So for PTRACE_MODE_ATTACH the tracer must be able to get whatever the tracee could get through user namespaces. A tracer that has CAP_SYS_PTRACE in its own creds can still attach to anything. But the CAP_SYS_PTRACE the caller gets over a user namespace just because it owns it must not count. Otherwise a restricted task could attach to a less restricted task inside a namespace it owns.
That gets rid of the sysctl, the clone3() field and the clone flags, doesn't need a new capability bit, and nothing changes for anyone who doesn't opt in, I think.
And that loopback thing should be its own series. Not as an nsfs ioctl though. All nsfs ioctls only report namespace state and I'd like to keep it that way.
Pipe this through an LLM and make sure it makes sense and covers all holes.
Thoughts?
Quoted 7 lines · Christian Brauner
Just a note on the essay I cut off. I really object to any arguments that amount to "it's too much work" propped up by a few thin arguments sprinkled in such as rtnetlink.
I also reject any arguments that amount to underscoping and overscoping of the new capability. The scope is clear: empty netns with brought up loop device.
Understood, thanks. I'll split the loopback work out into its own standalone series and handle it separately, keeping the scope strictly defined as you described.
Quoted 1 line
But again, I'm more focussed on cells so here's what I find acceptable:
[snip]
Quoted 2 lines
* a new CapUns: line in /proc/<pid>/status
* new audit mask inAUDIT_CAPSETrecord
Quick question on AUDIT_CAPSET: today it's only emitted on capset() and only logs capability sets that capset() can modify (explicitly or implicitly like cap_ambient). It does not include cap_bset which is modified via prctl(). Since capset() never modifies cap_userns either, does it make sense to treat it like cap_bset and leave it out of AUDIT_CAPSET, relying on prctl auditing instead?
[snip]
Quoted 4 lines
That gets rid of the sysctl, the
clone3()field and the clone flags, doesn't need a new capability bit, and nothing changes for anyone who doesn't opt in, I think.
Quoted 8 lines
And that loopback thing should be its own series. Not as an nsfs ioctl though. All nsfs ioctls only report namespace state and I'd like to keep it that way.
Pipe this through an LLM and make sure it makes sense and covers all holes.
Thoughts?
Thanks for the feedback and the detailed proposal. It looks good to me and nicely ties everything together. I'll prepare a V2 for review based on this hybrid design.
Quoted 46 lines · Christian Brauner
Quoted 5 lines · Hallgrimur H. Gunnarsson
If we drop
CLONE_NEWNET_LOOPBACK/UNSHARE_NEWNET_LOOPBACKfrom this series and handle loopback separately, do you think the per-userns bounding set is a reasonable approach for withholding capabilities (e.g.CAP_NET_ADMINandCAP_NET_RAW) from unprivileged userns, or would you prefer a different mechanism?Seems ok to me.
Quoted 6 lines
To address the concern about the number of moving parts, I am also happy to simplify the control interfaces. If we decide a per-task securebit is the cleanest way to drive this configuration for both single-deep and nested cases, we could focus on that and drop the
clone3()and sysctl from this series entirely, or only expose whatever subset you prefer.Just a note on the essay I cut off. I really object to any arguments that amount to "it's too much work" propped up by a few thin arguments sprinkled in such as rtnetlink.
I also reject any arguments that amount to underscoping and overscoping of the new capability. The scope is clear: empty netns with brought up loop device.
I'm 180 patches deep into fixing procfs and 41 patches deep into preventing loop devices from abuse. Either we do the work and get something better or we do the same thing we've always done and hope we end up happily ever after.
But again, I'm more focussed on cells so here's what I find acceptable:
I'd rather go back to what Jonathan proposed in 2024 (cf. [1]). A per-task userns capability mask. Serge acked the core of it back then. It's at least generic and not just the single securebit capability thing. And we'd burn a new bit for every capability that turns out to be a problem later.
Jonathan's version had holes though. The restriction only lived in the task's creds so the owner rule and
setns()blew this up. So it needs to be combined with your per-namespace set. Roughly:* every task carries a mask,
cred->cap_userns, full by default fork, exec, setuid and entering a namespace never change it
* a new user namespace records
Quoted 7 lines
ns->cap_bset = parent->cap_bset & (cred->cap_userns | cred->cap_permitted);once at creation and never changes it again => it's monotonic downwards
* the creator getsns->cap_bsetinstead ofCAP_FULL_SET
* a task that setns()es in later gets
ns->cap_bset& (cred->cap_userns|cred->cap_permitted)
I'm not sure this is ideal. If a task has cap_userns & CAP_NET_ADMIN, then there is no attack surface issue with allowing it to enter a namespace and be NET_ADMIN there even if the namespace itself has CAP_NET_ADMIN cleared from cap_bset. But any exemption here would need to be a new API so that it isn't used by accident.
I'm mostly saying this because container managers might want to restrict cap_userns within their containers but still have it themselves for management. But maybe there isn't any need to enter the userns for this purpose.
Quoted 22 lines
* the owner rule in
cap_capable_helper()grants exactly what entering would and otherwise falls through to what the owner hasSo caps a task actually has always count as allowed => should check Andy's "only restrict creators that don't have
CAP_NET_ADMINthemselves" per capability.This amounts to a host-wide default without a sysctl. PID 1 drops
CAP_NET_ADMINandCAP_NET_RAWfrom its own mask at boot and everything inherits that.Root, sudo and setuid-root binaries have those capabilities so nothing changes for them. A regular user doesn't and so their user namespaces come without
CAP_NET_ADMINandCAP_NET_RAW.This also covers newgrp, su and sudo -u shells which is where resetting the mask on setuid exec (Which was raised by Serge in the other thread.).
* Root in a container has caps as well so for containers the exemption would be wrong.
Quoted 6 lines
So here we need a a lockable
SECURE_NO_USERNS_CAP_RAISEbit thingy. This turns off the exemption and prevents raising the mask.Docker lowers the mask, sets and locks the bit, and
unshare(CLONE_NEWUSER)in the container doesn't hand outCAP_NET_ADMINanymore.
Can you clarify this part a bit? I'm not seeing why Docker should be special. Shouldn't the inside of a Docker container work as much like a normal non-container system as possible? What's the use case?
In any event, the ptrace access checks also need to be updated. If we're adding cap_userns, then one should not be able to PTRACE_MODE_ATTACH a task with higher cap_userns.
Christian Brauner
maintainerQuoted 6 lines · Hallgrimur H. Gunnarsson
Quick question on
AUDIT_CAPSET: today it's only emitted oncapset()and only logs capability sets thatcapset()can modify (explicitly or implicitly likecap_ambient). It does not includecap_bsetwhich is modified viaprctl(). Sincecapset()never modifiescap_usernseither, does it make sense to treat it likecap_bsetand leave it out ofAUDIT_CAPSET, relying on prctl auditing instead?
Fine by me as well.
Quoted 3 lines
Thanks for the feedback and the detailed proposal. It looks good to me and nicely ties everything together. I'll prepare a V2 for review based on this hybrid design.
Sounds good.
Christian Brauner
maintainerQuoted 10 lines · Andy Lutomirski
Quoted 2 lines · Christian Brauner
* a task that setns()es in later gets
ns->cap_bset& (cred->cap_userns|cred->cap_permitted)I'm not sure this is ideal. If a task has
cap_userns&CAP_NET_ADMIN, then there is no attack surface issue with allowing it to enter a namespace and beNET_ADMINthere even if the namespace itself hasCAP_NET_ADMINcleared fromcap_bset. But any exemption here would need to be a new API so that it isn't used by accident.
Quoted 4 lines
I'm mostly saying this because container managers might want to restrict
cap_usernswithin their containers but still have it themselves for management. But maybe there isn't any need to enter the userns for this purpose.
I don't think there is. A manager that holds the capabilities itself can just do most things from the outside. I think it's nice that once you're inside a namespace you're bound by its capabiltiy set. Otherwise the set isn't a property of the namespace anymore. If someone comes up with a real need to enter we can add an explicit opt-in later?
Quoted 6 lines
Quoted 6 lines
* Root in a container has caps as well so for containers the exemption would be wrong.
So here we need a a lockable
SECURE_NO_USERNS_CAP_RAISEbit thingy. This turns off the exemption and prevents raising the mask.
Quoted 7 lines
Quoted 3 lines
Docker lowers the mask, sets and locks the bit, and
unshare(CLONE_NEWUSER)in the container doesn't hand outCAP_NET_ADMINanymore.Can you clarify this part a bit? I'm not seeing why Docker should be special. Shouldn't the inside of a Docker container work as much like a normal non-container system as possible? What's the use case?
I picked Docker because you brought it up, and your goal of allowing user namespaces even in Docker is kinda the use case. Docker can only drop the CLONE_NEWUSER block from its seccomp profile if nested user namespaces can't get more caps than root/Docker wants to give them.
But the bit isn't at all Docker specific. Any privileged task that wants the mask to apply to itself would benefit. With just the exemption this wouldn't be possible:
(1) A runtime that holds full capabilities gives a user namespace it creates all bits.
It can just set the bit before creating it.
(2) In a container without a user namespace container root has host-level capabilities. Any user namespace it creates gets them through this exemption thing. So it can also add them back to its mask. And the mask is inherited. So every process it starts can then create user namespaces with them.
by raising the bit we stop both. The locked bit keeps container root which also has CAP_SETPCAP from clearing it.
On the host none of that matters as the mask is root's own policy there.
Quoted 3 lines
In any event, the ptrace access checks also need to be updated. If we're adding
cap_userns, then one should not be able toPTRACE_MODE_ATTACHa task with highercap_userns.
Yeah, I mentioned that in my reply earlier.
Quoted 17 lines · Christian Brauner
Quoted 10 lines · Andy Lutomirski
Quoted 2 lines · Christian Brauner
* a task that setns()es in later gets
ns->cap_bset& (cred->cap_userns|cred->cap_permitted)I'm not sure this is ideal. If a task has
cap_userns&CAP_NET_ADMIN, then there is no attack surface issue with allowing it to enter a namespace and beNET_ADMINthere even if the namespace itself hasCAP_NET_ADMINcleared fromcap_bset. But any exemption here would need to be a new API so that it isn't used by accident.Quoted 4 lines
I'm mostly saying this because container managers might want to restrict
cap_usernswithin their containers but still have it themselves for management. But maybe there isn't any need to enter the userns for this purpose.
Quoted 5 lines
I don't think there is. A manager that holds the capabilities itself can just do most things from the outside. I think it's nice that once you're inside a namespace you're bound by its capabiltiy set. Otherwise the set isn't a property of the namespace anymore. If someone comes up with a real need to enter we can add an explicit opt-in later?
Fair enough. Also you've written infinitely more nontrivial container managers than I have (I've written container managers, too, but they're all special-purpose things that don't do much in the way of actual managing).
Quoted 28 lines
Quoted 7 lines
Quoted 7 lines
* Root in a container has caps as well so for containers the exemption would be wrong.
So here we need a a lockable
SECURE_NO_USERNS_CAP_RAISEbit thingy. This turns off the exemption and prevents raising the mask.Quoted 7 lines
Quoted 3 lines
Docker lowers the mask, sets and locks the bit, and
unshare(CLONE_NEWUSER)in the container doesn't hand outCAP_NET_ADMINanymore.Can you clarify this part a bit? I'm not seeing why Docker should be special. Shouldn't the inside of a Docker container work as much like a normal non-container system as possible? What's the use case?
I picked Docker because you brought it up, and your goal of allowing user namespaces even in Docker is kinda the use case. Docker can only drop the
CLONE_NEWUSERblock from its seccomp profile if nested user namespaces can't get more caps than root/Docker wants to give them.But the bit isn't at all Docker specific. Any privileged task that wants the mask to apply to itself would benefit. With just the exemption this wouldn't be possible:
(1) A runtime that holds full capabilities gives a user namespace it creates all bits.
It can just set the bit before creating it.
Quoted 9 lines
(2) In a container without a user namespace container root has host-level capabilities. Any user namespace it creates gets them through this exemption thing. So it can also add them back to its mask. And the mask is inherited. So every process it starts can then create user namespaces with them.
by raising the bit we stop both. The locked bit keeps container root which also has
CAP_SETPCAPfrom clearing it.
I'm still not 100% sure I'm following this. By "exemption" are you talking about the cred->cap_premitted term here?
ns->cap_bset = parent->cap_bset &
(cred->cap_userns | cred->cap_permitted);
(As as aside, as formulated, the parent->cap_bset term should be irrelevant, no? cred always refers to a task in parent, and this whole thing is defined so that cap_userns and cap_permitted are always subsets of parent's cap_bset, right?)
I think I agree that there needs to be a way to turn the cap_permitted thing on and off (and I'm also not sure whether cap_permitted is better than cap_effective), but I'm not convinced that an inheritable and lockable bit is necessary or wise.
How about changing the rule to:
child->cap_bset = parent->cap_bset & soft_cap_userns & (cred->cap_userns | cred->cap_permitted)
a) (ugly but easier) A non-inheritable prctl-controlled mask soft_cap_userns, changing the rule to parent->cap_bset & soft_cap_userns & (cred->cap_userns | cred->cap_permitted). soft_cap_userns would be reset to all ones on on fork and exec to avoid creating new inheritable security-relevant state.
b) A whole new create-a-namespace API where the caller chooses soft_cap_userns at the time they create the namespace.
Quoted 1 line
On the host none of that matters as the mask is root's own policy there.
I'm still not seeing how there's a difference between host vs init-userns-container vs separate-userns-container. After all, in *any* of these contexts, the configuration *of the host or inside the container* might want to restrict cap_userns for unprivileged users or for everyone, which it can do with whatever API we add to do this. And some container manager might run with CAP_NET_ADMIN in such a context, and it might want to create its own container that hasCAP_NET_ADMIN removed from cap_bset. But I might just be being dense
here or I might be misunderstanding you.
There is one thing that continues to bother me about all of this. In a sane world where privilege elevation on exec was simply not a thing (no_new_privs = true always, nosuid always, no file caps, etc), then cap_bset is kind of irrelevant, right? A task either does or does not have NET_ADMIN, and it either does or does not have the ability to create *a task in a new userns, including itself, with NET_ADMIN*. Since our API is based on creating/entering a userns as opposed to spawning tasks into a userns, the rule should be, upon entering a userns:
cap_permitted = cap_userns
or something to that effect. Or maybe:
cap_permitted = ns_enter_requested_caps & cap_userns
and cap_effective and ambient get clamped to cap_permitted.
Unfortunately we don't live in this world, and I'm not convinced that can credibly even approximate it, because people really like their setuid programs working inside a userns. It still bugs me that we're designing permission systems designed to work in the POSIX model that I think we all kind of agree is fundamentally rather messed up.
Quoted 6 lines
Quoted 4 lines
In any event, the ptrace access checks also need to be updated. If we're adding
cap_userns, then one should not be able toPTRACE_MODE_ATTACHa task with highercap_userns.Yeah, I mentioned that in my reply earlier.
Christian Brauner
maintainerQuoted 24 lines · Andy Lutomirski
Quoted 17 lines · Christian Brauner
Quoted 10 lines · Andy Lutomirski
Quoted 2 lines · Christian Brauner
* a task that setns()es in later gets
ns->cap_bset& (cred->cap_userns|cred->cap_permitted)I'm not sure this is ideal. If a task has
cap_userns&CAP_NET_ADMIN, then there is no attack surface issue with allowing it to enter a namespace and beNET_ADMINthere even if the namespace itself hasCAP_NET_ADMINcleared fromcap_bset. But any exemption here would need to be a new API so that it isn't used by accident.Quoted 4 lines
I'm mostly saying this because container managers might want to restrict
cap_usernswithin their containers but still have it themselves for management. But maybe there isn't any need to enter the userns for this purpose.Quoted 5 lines
I don't think there is. A manager that holds the capabilities itself can just do most things from the outside. I think it's nice that once you're inside a namespace you're bound by its capabiltiy set. Otherwise the set isn't a property of the namespace anymore. If someone comes up with a real need to enter we can add an explicit opt-in later?
Quoted 4 lines
Fair enough. Also you've written infinitely more nontrivial container managers than I have (I've written container managers, too, but they're all special-purpose things that don't do much in the way of actual managing).
So I think this is another instance where we're bitten by the complexity of the whole namespace api. In a perfect world our answer would be "Yes, the owner of the userns is definitely capable of performing all relevant actions from outside the userns.". But we're actually not able to say that because there's so many different ways how some <object> is set up or configured for a container and nobody ever sat down and defined the model how a container and it's various resoures are set up.
So once again, here we are guessing our way to a decent decision... Thanks for helping with thinking this through.
Quoted 33 lines
Quoted 33 lines
Quoted 6 lines
Quoted 6 lines
* Root in a container has caps as well so for containers the exemption would be wrong.
So here we need a a lockable
SECURE_NO_USERNS_CAP_RAISEbit thingy. This turns off the exemption and prevents raising the mask.Quoted 7 lines
Quoted 3 lines
Docker lowers the mask, sets and locks the bit, and
unshare(CLONE_NEWUSER)in the container doesn't hand outCAP_NET_ADMINanymore.Can you clarify this part a bit? I'm not seeing why Docker should be special. Shouldn't the inside of a Docker container work as much like a normal non-container system as possible? What's the use case?
I picked Docker because you brought it up, and your goal of allowing user namespaces even in Docker is kinda the use case. Docker can only drop the
CLONE_NEWUSERblock from its seccomp profile if nested user namespaces can't get more caps than root/Docker wants to give them.But the bit isn't at all Docker specific. Any privileged task that wants the mask to apply to itself would benefit. With just the exemption this wouldn't be possible:
(1) A runtime that holds full capabilities gives a user namespace it creates all bits.
It can just set the bit before creating it.(2) In a container without a user namespace container root has host-level capabilities. Any user namespace it creates gets them through this exemption thing. So it can also add them back to its mask. And the mask is inherited. So every process it starts can then create user namespaces with them.
Quoted 6 lines
Quoted 3 lines
by raising the bit we stop both. The locked bit keeps container root which also has
CAP_SETPCAPfrom clearing it.I'm still not 100% sure I'm following this. By "exemption" are you talking about the
cred->cap_premittedterm here?
Yes.
Quoted 5 lines
ns->cap_bset=parent->cap_bset&(cred->cap_userns | cred->cap_permitted);(As as aside, as formulated, the
parent->cap_bsetterm should be irrelevant, no? cred always refers to a task in parent, and this
(
I don't think it i.scap_userns is full by default. Entering a namespace doesn't change it. A task inside a namespace with a reduced cap_bset still has the full mask. Without the term a child namespace gets more caps than its parent had.
cap_permitted can grow through a setuid-root exec in the parent namespace. And that exec is bounded by the tasks bounding set and not by the namespace bounding set.
So that term ensures that the namespace bounding set shrinks monotonically by construction.
I think it would only be redundant if exec would be clamped by cap_bset. I'm not sure if the patchset does this.
/me looks...
Ah, ok... this patch series already clamps exec to the namespace bounding set. So yes, you're right.
)
Quoted 6 lines
whole thing is defined so that
cap_usernsandcap_permittedare always subsets of parent'scap_bset, right?)I think I agree that there needs to be a way to turn the
cap_permittedthing on and off (and I'm also not sure whethercap_permittedis better thancap_effective), but I'm not convinced that an inheritable
The effective set can be raised from the permitted set at will. So I think permitted is just more correct.
Quoted 4 lines
and lockable bit is necessary or wise.
How about changing the rule to:
Quoted 8 lines
child->cap_bset=parent->cap_bset&soft_cap_userns& (cred->cap_userns|cred->cap_permitted)a) (ugly but easier) A non-inheritable prctl-controlled mask
soft_cap_userns, changing the rule toparent->cap_bset&soft_cap_userns& (cred->cap_userns|cred->cap_permitted).soft_cap_usernswould be reset to all ones on on fork and exec to avoid creating new inheritable security-relevant state.
So both let the creator pick. But the bit is for the creator when it wants to self-restrict: container-root without a user namespace.
It's the same reason that securebits and no_new_privs are inheritable and lockable. Afaict, a) is reset on exec so it doesn't control the next exec. b) covers namespace creation but not unsharing a user namespace.
Quoted 7 lines
b) A whole new create-a-namespace API where the caller chooses
soft_cap_usernsat the time they create the namespace.Quoted 1 line
On the host none of that matters as the mask is root's own policy there.
I'm still not seeing how there's a difference between host vs init-userns-container vs separate-userns-container. After all, in
I think the difference is simply whether the restricting task holds the capabilities itself. Unprivileged users on the host don't and so they're not subject to the exemption. The bit is for that case where the task holds the caps.
But ok, if we really don't want to bother with container without user namespaces the bit vs a) thing can also go into a follow-up series.
Quoted 5 lines
Unfortunately we don't live in this world, and I'm not convinced that can credibly even approximate it, because people really like their setuid programs working inside a userns. It still bugs me that we're designing permission systems designed to work in the POSIX model that I think we all kind of agree is fundamentally rather messed up.
I don't think all hope is lost. We have slowly been pushing in this direction. systemd allows to set NoNewPrivileges= in it's global config so it's possible to enable it for the whole system easily.
There's been a ton of work to get rid of classic setuid-exec stuff:
* run0 instead of sudo (with sudo compat), and systemd-ptybrokerd for interactive shells
* nsresourced for user namespaces with delegated ranges, mountfsd for unprivileged image mounts
* outside of systemd: pwaccessd/pwupdd/newidmapd replacing unix_chkpwd, passwd and newuidmap/newgidmap, polkit without a setuid helper, and su/sudo/pkexec wrappers on top of ptybrokerd
But yes, containers are the sore spot. no_new_privs inherited from PID 1 breaks setuid inside of containers.
My idea has been to make this dynamic:
* deny privilege gain on exec in the initial user namespace and allow it in nested ones. I mused about this in
https://github.com/uapi-group/kernel-features/pull/38
Also, since v7.1 there's CLONE_NNP to spawn a child without no_new_privs set.
Hallgrimur, could you please explain why your use case would not work with Landlock? The capability split or new clone flags would be complementary of course.
Quoted 198 lines · Mickaël Salaün
Hi,
I think this is mostly solved with Landlock (kernel v7.4), see
https://docs.kernel.org/userspace-api/landlock.html#capability-and-namespace-restrictions
and
https://lore.kernel.org/all/[email protected]/This approach is agnostic to UID, cgroups, or other ways to identify processes, so it should fit any use case.
What is missing is a split of capabilities (e.g.
CAP_NET_ADMIN) that makes sense from a security and (user) namespace point of view.Regards,
MickaëlQuoted 181 lines · Hallgrimur H. Gunnarsson
When an unprivileged process creates a new user namespace, it is granted a full set of capabilities (
CAP_FULL_SET) scoped to that namespace. While these capabilities are isolated to the namespace, they allow unprivileged local users to reach deep kernel subsystems (most notably networking configuration and raw sockets viaCAP_NET_ADMINandCAP_NET_RAW) that historically assumed a trusted caller and have accounted for a large share of local privilege escalation vulnerabilities.Many workloads and sandboxes use unprivileged user namespaces strictly for basic UID/GID, mount, PID, or network isolation and never need high-risk capabilities like
CAP_NET_ADMINorCAP_NET_RAW. Likewise, system administrators often want a host-wide policy ceiling restricting which capabilities unprivileged user namespaces may acquire, without disabling unprivileged user namespaces altogether.Prior work by Jonathan Calmels [1] proposed addressing this via a sixth per-thread capability set (
cap_userns) alongside a global sysctl mask. During that discussion [1, 2], feedback (e.g. from Casey Schaufler) suggested that rather than adding another per-thread capability set andprctl()interface, capability restrictions could be integrated directly into structuser_namespaceand configured viaclone3(). At the same time, as noted in [1], aclone3()flag alone is not sufficient for administrators who need to enforce a host-wide ceiling on unprivileged user namespaces without modifying every userspace callsite.This series combines both pieces of feedback: it embeds a capability bounding set (
cap_bset) directly into structuser_namespace, reusing the existing taskcap_bset,cap_permitted, andcap_effectivesets on namespace entry, and provides both a system-wide sysctl ceiling for unprivileged user namespaces and aCLONE_NEWUSER_BSETflag for voluntary per-namespace restriction viaclone3().In addition, because restricting
CAP_NET_ADMINat user namespace creation time prevents userspace from bringing up the loopback interface in new network namespaces, the series first introduces an opt-in flag to automatically enable loopback on network namespace creation:1. Opt-in loopback activation on netns creation (Patch 1)
New network namespaces start with the loopback interface (lo) DOWN by default, requiring
CAP_NET_ADMINover the owning user namespace to bring it up. To block external network access while preserving localhost networking, sandboxes commonly create an isolated network namespace with only the loopback interface enabled.However, requiring a sandbox to hold
CAP_NET_ADMINin a new user namespace solely to bring loopback up conflicts with reducing theCAP_NET_ADMINattack surface. Today, an unprivileged sandbox must start withCAP_NET_ADMINto bring loopback up, drop it, and then blockCAP_NET_ADMINfrom being regained in nested user namespaces (e.g. via seccomp ormax_user_namespaceslimits). Conversely, whenCAP_NET_ADMINis restricted at user namespace creation time (via the sysctl ceiling orCLONE_NEWUSER_BSETintroduced in Patches 2-3, or via LSMs such as Landlock), tasks inside the new namespace never acquireCAP_NET_ADMINand cannot bring loopback up from userspace, breaking localhost networking for unprivileged sandboxes.Introduce the
CLONE_NEWNET_LOOPBACKflag forclone3()and the correspondingUNSHARE_NEWNET_LOOPBACKflag forunshare(), which implyCLONE_NEWNETand automatically bring the loopback device up incopy_net_ns()before returning the new network namespace. Making this an explicit opt-in preserves default network namespace semantics while allowing unprivileged sandboxes to create an isolated network namespace with functional localhost networking without ever holdingCAP_NET_ADMIN.2. Per-user-namespace capability bounding set & sysctl ceiling (Patch 2)
Add
cap_bsetto structuser_namespace(initialized toCAP_FULL_SETininit_user_ns) and introduce a system-wide sysctl ceiling for unprivileged users at:
/proc/sys/kernel/unprivileged_userns_caps_allowed
(defaulting toCAP_FULL_SET).When a new user namespace is created:
- Privileged creators (holdingCAP_SYS_ADMINin the parent user namespace) inheritcap_bsetfrom the parent user namespace.
- Unprivileged creators (lackingCAP_SYS_ADMINin the parent user namespace) have the child namespace's bounding set constrained by the sysctl ceiling combined with any effective capabilities the creator already holds in the parent namespace:
child_bset=parent_bset& (sysctl_ceiling|creator_effective)
Allowing the creator to retain capabilities it already holds in the parent namespace ensures that a process granted a specific capability (e.g.CAP_NET_ADMIN) does not lose it when creating a nested user namespace.When a task enters a user namespace via clone()/unshare() or
setns(), itscap_bset,cap_permitted, andcap_effectivesets are clamped touser_ns->cap_bset. In addition,cap_capable_helper()is updated so that implicit capabilities granted to the parent-namespace owner of a user namespace are likewise bounded by the owned namespace'scap_bset.3. Per-namespace restriction via
clone3()(Patch 3)Introduce
CLONE_NEWUSER_BSETand addcap_bsetto structclone_args. When specified alongsideCLONE_NEWUSER, the new user namespace's bounding set is further intersected with the requestedcap_bsetmask, allowing container runtimes and sandboxes to drop unneeded capabilities from a user namespace at creation time even when permitted by the global sysctl.4. Introspection via
NS_USER_GET_INFO(Patch 4)While tasks inside a user namespace see their initial ceiling in /proc/<pid>/status (CapBnd), threads may subsequently drop individual capabilities from their per-thread bounding set. Add an extensible
NS_USER_GET_INFOioctl on userns file descriptors to allow userspace to directly query a user namespace'scap_bset.5. Selftests (Patches 5-8)
Add kselftest suites covering
CLONE_NEWNET_LOOPBACK, the sysctl ceiling, creator capability retention, nested monotonicity, parent-owner bounding,CLONE_NEWUSER_BSETandNS_USER_GET_INFO.[1] https://lore.kernel.org/all/[email protected]/
[2] https://lwn.net/Articles/978846/Note on tree routing:
While Patch 1 (
CLONE_NEWNET_LOOPBACK) touchesnet/core/net_namespace.c, most of its changes add clone3()/unshare() flag plumbing ininclude/uapi/linux/sched.h,kernel/fork.c, andkernel/nsproxy.c, which Patch 3 (CLONE_NEWUSER_BSET) builds directly on top of. To avoid merge conflicts inkernel/fork.candinclude/uapi/linux/sched.h, it may be simplest to route the entire series through a single tree, e.g. a namespace branch in vfs.git with Acked-by from the netdev and capabilities/credentials maintainers, or whichever tree the maintainers prefer.Hallgrimur H. Gunnarsson (8):
net: introduceCLONE_NEWNET_LOOPBACKto auto-enable loopback
userns: introduce capability bounding set for user namespaces
userns: allow restricting capability bounding set viaclone3()
nsfs: addNS_USER_GET_INFOioctl to inspect user namespace
capabilities
selftests/net: add test suite forCLONE_NEWNET_LOOPBACKselftests/capabilities: tests for user namespace capability bounding
set
selftests/capabilities: addclone3()tests forCLONE_NEWUSER_BSETselftests/nsfs: add tests forNS_USER_GET_INFOioctlDocumentation/admin-guide/sysctl/kernel.rst | 37 ++ fs/nsfs.c | 29 + include/linux/cred.h | 3 +- include/linux/sched/task.h | 1 + include/linux/user_namespace.h | 20 +- include/uapi/linux/nsfs.h | 17 + include/uapi/linux/sched.h | 9 + kernel/cred.c | 10 +- kernel/fork.c | 38 +- kernel/nsproxy.c | 9 + kernel/user.c | 1 + kernel/user_namespace.c | 100 +++- net/core/net_namespace.c | 11 + security/commoncap.c | 8 +- .../testing/selftests/capabilities/.gitignore | 1 + tools/testing/selftests/capabilities/Makefile | 2 +- .../capabilities/userns_bounding_set_test.c | 566 ++++++++++++++++++ .../selftests/clone3/clone3_selftests.h | 1 + .../selftests/filesystems/nsfs/.gitignore | 1 + .../selftests/filesystems/nsfs/Makefile | 4 +- .../selftests/filesystems/nsfs/userns.c | 120 ++++ tools/testing/selftests/net/.gitignore | 1 + tools/testing/selftests/net/Makefile | 1 + tools/testing/selftests/net/loopback_netns.c | 103 ++++ 24 files changed, 1069 insertions(+), 24 deletions(-) create mode 100644 tools/testing/selftests/capabilities/userns_bounding_set_test.c create mode 100644 tools/testing/selftests/filesystems/nsfs/userns.c create mode 100644 tools/testing/selftests/net/loopback_netns.cbase-commit:
cee9395acd8043be0644b25c34bfa86623f2b935Signature · 1 line
2.56.0.313.g2479322e68-goog
Christian Brauner
maintainerQuoted 181 lines · Christian Brauner
Quoted 24 lines · Andy Lutomirski
Quoted 17 lines · Christian Brauner
Quoted 10 lines · Andy Lutomirski
Quoted 2 lines · Christian Brauner
* a task that setns()es in later gets
ns->cap_bset& (cred->cap_userns|cred->cap_permitted)I'm not sure this is ideal. If a task has
cap_userns&CAP_NET_ADMIN, then there is no attack surface issue with allowing it to enter a namespace and beNET_ADMINthere even if the namespace itself hasCAP_NET_ADMINcleared fromcap_bset. But any exemption here would need to be a new API so that it isn't used by accident.Quoted 4 lines
I'm mostly saying this because container managers might want to restrict
cap_usernswithin their containers but still have it themselves for management. But maybe there isn't any need to enter the userns for this purpose.Quoted 5 lines
I don't think there is. A manager that holds the capabilities itself can just do most things from the outside. I think it's nice that once you're inside a namespace you're bound by its capabiltiy set. Otherwise the set isn't a property of the namespace anymore. If someone comes up with a real need to enter we can add an explicit opt-in later?
Quoted 4 lines
Fair enough. Also you've written infinitely more nontrivial container managers than I have (I've written container managers, too, but they're all special-purpose things that don't do much in the way of actual managing).
So I think this is another instance where we're bitten by the complexity of the whole namespace api. In a perfect world our answer would be "Yes, the owner of the userns is definitely capable of performing all relevant actions from outside the userns.". But we're actually not able to say that because there's so many different ways how some <object> is set up or configured for a container and nobody ever sat down and defined the model how a container and it's various resoures are set up.
So once again, here we are guessing our way to a decent decision... Thanks for helping with thinking this through.
Quoted 33 lines
Quoted 33 lines
Quoted 6 lines
Quoted 6 lines
* Root in a container has caps as well so for containers the exemption would be wrong.
So here we need a a lockable
SECURE_NO_USERNS_CAP_RAISEbit thingy. This turns off the exemption and prevents raising the mask.Quoted 7 lines
Quoted 3 lines
Docker lowers the mask, sets and locks the bit, and
unshare(CLONE_NEWUSER)in the container doesn't hand outCAP_NET_ADMINanymore.Can you clarify this part a bit? I'm not seeing why Docker should be special. Shouldn't the inside of a Docker container work as much like a normal non-container system as possible? What's the use case?
I picked Docker because you brought it up, and your goal of allowing user namespaces even in Docker is kinda the use case. Docker can only drop the
CLONE_NEWUSERblock from its seccomp profile if nested user namespaces can't get more caps than root/Docker wants to give them.But the bit isn't at all Docker specific. Any privileged task that wants the mask to apply to itself would benefit. With just the exemption this wouldn't be possible:
(1) A runtime that holds full capabilities gives a user namespace it creates all bits.
It can just set the bit before creating it.(2) In a container without a user namespace container root has host-level capabilities. Any user namespace it creates gets them through this exemption thing. So it can also add them back to its mask. And the mask is inherited. So every process it starts can then create user namespaces with them.
Quoted 6 lines
Quoted 3 lines
by raising the bit we stop both. The locked bit keeps container root which also has
CAP_SETPCAPfrom clearing it.I'm still not 100% sure I'm following this. By "exemption" are you talking about the
cred->cap_premittedterm here?Yes.
Quoted 5 lines
ns->cap_bset=parent->cap_bset&(cred->cap_userns | cred->cap_permitted);(As as aside, as formulated, the
parent->cap_bsetterm should be irrelevant, no? cred always refers to a task in parent, and this(
I don't think it i.scap_usernsis full by default. Entering a namespace doesn't change it. A task inside a namespace with a reducedcap_bsetstill has the full mask. Without the term a child namespace gets more caps than its parent had.
cap_permittedcan grow through a setuid-root exec in the parent namespace. And that exec is bounded by the tasks bounding set and not by the namespace bounding set.So that term ensures that the namespace bounding set shrinks monotonically by construction.
I think it would only be redundant if exec would be clamped by
cap_bset. I'm not sure if the patchset does this./me looks...
Ah, ok... this patch series already clamps exec to the namespace bounding set. So yes, you're right.
)Quoted 6 lines
whole thing is defined so that
cap_usernsandcap_permittedare always subsets of parent'scap_bset, right?)I think I agree that there needs to be a way to turn the
cap_permittedthing on and off (and I'm also not sure whethercap_permittedis better thancap_effective), but I'm not convinced that an inheritableThe effective set can be raised from the permitted set at will. So I think permitted is just more correct.
Quoted 4 lines
and lockable bit is necessary or wise.
How about changing the rule to:
Quoted 8 lines
child->cap_bset=parent->cap_bset&soft_cap_userns& (cred->cap_userns|cred->cap_permitted)a) (ugly but easier) A non-inheritable prctl-controlled mask
soft_cap_userns, changing the rule toparent->cap_bset&soft_cap_userns& (cred->cap_userns|cred->cap_permitted).soft_cap_usernswould be reset to all ones on on fork and exec to avoid creating new inheritable security-relevant state.So both let the creator pick. But the bit is for the creator when it wants to self-restrict: container-root without a user namespace.
It's the same reason that securebits and
no_new_privsare inheritable and lockable. Afaict, a) is reset on exec so it doesn't control the next exec. b) covers namespace creation but not unsharing a user namespace.Quoted 7 lines
b) A whole new create-a-namespace API where the caller chooses
soft_cap_usernsat the time they create the namespace.Quoted 1 line
On the host none of that matters as the mask is root's own policy there.
I'm still not seeing how there's a difference between host vs init-userns-container vs separate-userns-container. After all, in
I think the difference is simply whether the restricting task holds the capabilities itself. Unprivileged users on the host don't and so they're not subject to the exemption. The bit is for that case where the task holds the caps.
But ok, if we really don't want to bother with container without user namespaces the bit vs a) thing can also go into a follow-up series.
Quoted 5 lines
Unfortunately we don't live in this world, and I'm not convinced that can credibly even approximate it, because people really like their setuid programs working inside a userns. It still bugs me that we're designing permission systems designed to work in the POSIX model that I think we all kind of agree is fundamentally rather messed up.
I don't think all hope is lost. We have slowly been pushing in this direction. systemd allows to set NoNewPrivileges= in it's global config so it's possible to enable it for the whole system easily.
There's been a ton of work to get rid of classic setuid-exec stuff:
* run0 instead of sudo (with sudo compat), and systemd-ptybrokerd for interactive shells
* nsresourced for user namespaces with delegated ranges, mountfsd for unprivileged image mounts
* outside of systemd: pwaccessd/pwupdd/newidmapd replacingunix_chkpwd, passwd and newuidmap/newgidmap, polkit without a setuid helper, and su/sudo/pkexec wrappers on top of ptybrokerdBut yes, containers are the sore spot.
no_new_privsinherited from PID 1 breaks setuid inside of containers.
Quoted 8 lines
My idea has been to make this dynamic:
* deny privilege gain on exec in the initial user namespace and allow it in nested ones. I mused about this in
https://github.com/uapi-group/kernel-features/pull/38Also, since v7.1 there's
CLONE_NNPto spawn a child withoutno_new_privsset.
Forgot:
https://www.thkukuk.de/blog/no_new_privs/
has an overview of where we're currently at.
Some tools are in:
https://github.com/thkukuk/account-utils
and Thorsten also gave a talk at All Systems Go in September:
Quoted 189 lines · Christian Brauner
Quoted 187 lines · Christian Brauner
Quoted 24 lines · Andy Lutomirski
Quoted 17 lines · Christian Brauner
Quoted 10 lines · Andy Lutomirski
Quoted 2 lines · Christian Brauner
* a task that setns()es in later gets
ns->cap_bset& (cred->cap_userns|cred->cap_permitted)I'm not sure this is ideal. If a task has
cap_userns&CAP_NET_ADMIN, then there is no attack surface issue with allowing it to enter a namespace and beNET_ADMINthere even if the namespace itself hasCAP_NET_ADMINcleared fromcap_bset. But any exemption here would need to be a new API so that it isn't used by accident.Quoted 4 lines
I'm mostly saying this because container managers might want to restrict
cap_usernswithin their containers but still have it themselves for management. But maybe there isn't any need to enter the userns for this purpose.Quoted 5 lines
I don't think there is. A manager that holds the capabilities itself can just do most things from the outside. I think it's nice that once you're inside a namespace you're bound by its capabiltiy set. Otherwise the set isn't a property of the namespace anymore. If someone comes up with a real need to enter we can add an explicit opt-in later?
Quoted 4 lines
Fair enough. Also you've written infinitely more nontrivial container managers than I have (I've written container managers, too, but they're all special-purpose things that don't do much in the way of actual managing).
So I think this is another instance where we're bitten by the complexity of the whole namespace api. In a perfect world our answer would be "Yes, the owner of the userns is definitely capable of performing all relevant actions from outside the userns.". But we're actually not able to say that because there's so many different ways how some <object> is set up or configured for a container and nobody ever sat down and defined the model how a container and it's various resoures are set up.
So once again, here we are guessing our way to a decent decision... Thanks for helping with thinking this through.
Quoted 33 lines
Quoted 33 lines
Quoted 6 lines
Quoted 6 lines
* Root in a container has caps as well so for containers the exemption would be wrong.
So here we need a a lockable
SECURE_NO_USERNS_CAP_RAISEbit thingy. This turns off the exemption and prevents raising the mask.Quoted 7 lines
Quoted 3 lines
Docker lowers the mask, sets and locks the bit, and
unshare(CLONE_NEWUSER)in the container doesn't hand outCAP_NET_ADMINanymore.Can you clarify this part a bit? I'm not seeing why Docker should be special. Shouldn't the inside of a Docker container work as much like a normal non-container system as possible? What's the use case?
I picked Docker because you brought it up, and your goal of allowing user namespaces even in Docker is kinda the use case. Docker can only drop the
CLONE_NEWUSERblock from its seccomp profile if nested user namespaces can't get more caps than root/Docker wants to give them.But the bit isn't at all Docker specific. Any privileged task that wants the mask to apply to itself would benefit. With just the exemption this wouldn't be possible:
(1) A runtime that holds full capabilities gives a user namespace it creates all bits.
It can just set the bit before creating it.(2) In a container without a user namespace container root has host-level capabilities. Any user namespace it creates gets them through this exemption thing. So it can also add them back to its mask. And the mask is inherited. So every process it starts can then create user namespaces with them.
Quoted 6 lines
Quoted 3 lines
by raising the bit we stop both. The locked bit keeps container root which also has
CAP_SETPCAPfrom clearing it.I'm still not 100% sure I'm following this. By "exemption" are you talking about the
cred->cap_premittedterm here?Yes.
Quoted 5 lines
ns->cap_bset=parent->cap_bset&(cred->cap_userns | cred->cap_permitted);(As as aside, as formulated, the
parent->cap_bsetterm should be irrelevant, no? cred always refers to a task in parent, and this(
I don't think it i.scap_usernsis full by default. Entering a namespace doesn't change it. A task inside a namespace with a reducedcap_bsetstill has the full mask. Without the term a child namespace gets more caps than its parent had.
cap_permittedcan grow through a setuid-root exec in the parent namespace. And that exec is bounded by the tasks bounding set and not by the namespace bounding set.So that term ensures that the namespace bounding set shrinks monotonically by construction.
I think it would only be redundant if exec would be clamped by
cap_bset. I'm not sure if the patchset does this./me looks...
Ah, ok... this patch series already clamps exec to the namespace bounding set. So yes, you're right.
)Quoted 6 lines
whole thing is defined so that
cap_usernsandcap_permittedare always subsets of parent'scap_bset, right?)I think I agree that there needs to be a way to turn the
cap_permittedthing on and off (and I'm also not sure whethercap_permittedis better thancap_effective), but I'm not convinced that an inheritableThe effective set can be raised from the permitted set at will. So I think permitted is just more correct.
Quoted 4 lines
and lockable bit is necessary or wise.
How about changing the rule to:
Quoted 8 lines
child->cap_bset=parent->cap_bset&soft_cap_userns& (cred->cap_userns|cred->cap_permitted)a) (ugly but easier) A non-inheritable prctl-controlled mask
soft_cap_userns, changing the rule toparent->cap_bset&soft_cap_userns& (cred->cap_userns|cred->cap_permitted).soft_cap_usernswould be reset to all ones on on fork and exec to avoid creating new inheritable security-relevant state.So both let the creator pick. But the bit is for the creator when it wants to self-restrict: container-root without a user namespace.
It's the same reason that securebits and
no_new_privsare inheritable and lockable. Afaict, a) is reset on exec so it doesn't control the next exec. b) covers namespace creation but not unsharing a user namespace.Quoted 7 lines
b) A whole new create-a-namespace API where the caller chooses
soft_cap_usernsat the time they create the namespace.Quoted 1 line
On the host none of that matters as the mask is root's own policy there.
I'm still not seeing how there's a difference between host vs init-userns-container vs separate-userns-container. After all, in
I think the difference is simply whether the restricting task holds the capabilities itself. Unprivileged users on the host don't and so they're not subject to the exemption. The bit is for that case where the task holds the caps.
But ok, if we really don't want to bother with container without user namespaces the bit vs a) thing can also go into a follow-up series.
Quoted 5 lines
Unfortunately we don't live in this world, and I'm not convinced that can credibly even approximate it, because people really like their setuid programs working inside a userns. It still bugs me that we're designing permission systems designed to work in the POSIX model that I think we all kind of agree is fundamentally rather messed up.
I don't think all hope is lost. We have slowly been pushing in this direction. systemd allows to set NoNewPrivileges= in it's global config so it's possible to enable it for the whole system easily.
There's been a ton of work to get rid of classic setuid-exec stuff:
* run0 instead of sudo (with sudo compat), and systemd-ptybrokerd for interactive shells
* nsresourced for user namespaces with delegated ranges, mountfsd for unprivileged image mounts
* outside of systemd: pwaccessd/pwupdd/newidmapd replacingunix_chkpwd, passwd and newuidmap/newgidmap, polkit without a setuid helper, and su/sudo/pkexec wrappers on top of ptybrokerdBut yes, containers are the sore spot.
no_new_privsinherited from PID 1 breaks setuid inside of containers.My idea has been to make this dynamic:
* deny privilege gain on exec in the initial user namespace and allow it in nested ones. I mused about this in
https://github.com/uapi-group/kernel-features/pull/38
Quoted 8 lines
Quoted 2 lines
Also, since v7.1 there's
CLONE_NNPto spawn a child withoutno_new_privsset.Forgot:
https://www.thkukuk.de/blog/no_new_privs/
has an overview of where we're currently at.
Nice!
I commented in the uapi-group issue:
I think there may be a rather more direct solution to this problem. I seem to recall advocating for clearing no_new_privs when entering a userns way back when, and IIRC I dropped this as part of the extensive negotiation to get NNP into the kernel in the first place. (I think dropping it was probably the right decision to keep the final patch simple.)
But I think I would still advocate for an option to let clone, unshare and setns callers turn no_new_privs off. The logic is that, if you own a userns, you already have all capabilities in it. If you enter it, you get to keep those by having them raised in cap_permitted. Being able to clear NNP and thus drop and subsequently regain them does not let you do anything you couldn’t already do.
An LSM hook for this would be needed because this argument does not apply to non-namespace-scoped LSM-based privileges. But the LSM hook would just be a "may this caller enter this userns and clear no_new_privs while doing so" query. In the absence of LSMs, the operation would be allowed.
This would allow a fully no_new_privs host to run an ordinary container that runs, in the ordinary way, without no_new_privs, and without hitting any new LSM calls after it's started.
The API could be as simple as a CLONE_CLEAR_NNP bit.
Signature · 2 lines
Andy Lutomirski AMA Capital Management, LLC
Christian Brauner
maintainerQuoted 223 lines · Andy Lutomirski
Quoted 189 lines · Christian Brauner
Quoted 187 lines · Christian Brauner
Quoted 24 lines · Andy Lutomirski
Quoted 17 lines · Christian Brauner
Quoted 10 lines · Andy Lutomirski
Quoted 2 lines · Christian Brauner
* a task that setns()es in later gets
ns->cap_bset& (cred->cap_userns|cred->cap_permitted)I'm not sure this is ideal. If a task has
cap_userns&CAP_NET_ADMIN, then there is no attack surface issue with allowing it to enter a namespace and beNET_ADMINthere even if the namespace itself hasCAP_NET_ADMINcleared fromcap_bset. But any exemption here would need to be a new API so that it isn't used by accident.Quoted 4 lines
I'm mostly saying this because container managers might want to restrict
cap_usernswithin their containers but still have it themselves for management. But maybe there isn't any need to enter the userns for this purpose.Quoted 5 lines
I don't think there is. A manager that holds the capabilities itself can just do most things from the outside. I think it's nice that once you're inside a namespace you're bound by its capabiltiy set. Otherwise the set isn't a property of the namespace anymore. If someone comes up with a real need to enter we can add an explicit opt-in later?
Quoted 4 lines
Fair enough. Also you've written infinitely more nontrivial container managers than I have (I've written container managers, too, but they're all special-purpose things that don't do much in the way of actual managing).
So I think this is another instance where we're bitten by the complexity of the whole namespace api. In a perfect world our answer would be "Yes, the owner of the userns is definitely capable of performing all relevant actions from outside the userns.". But we're actually not able to say that because there's so many different ways how some <object> is set up or configured for a container and nobody ever sat down and defined the model how a container and it's various resoures are set up.
So once again, here we are guessing our way to a decent decision... Thanks for helping with thinking this through.
Quoted 33 lines
Quoted 33 lines
Quoted 6 lines
Quoted 6 lines
* Root in a container has caps as well so for containers the exemption would be wrong.
So here we need a a lockable
SECURE_NO_USERNS_CAP_RAISEbit thingy. This turns off the exemption and prevents raising the mask.Quoted 7 lines
Quoted 3 lines
Docker lowers the mask, sets and locks the bit, and
unshare(CLONE_NEWUSER)in the container doesn't hand outCAP_NET_ADMINanymore.Can you clarify this part a bit? I'm not seeing why Docker should be special. Shouldn't the inside of a Docker container work as much like a normal non-container system as possible? What's the use case?
I picked Docker because you brought it up, and your goal of allowing user namespaces even in Docker is kinda the use case. Docker can only drop the
CLONE_NEWUSERblock from its seccomp profile if nested user namespaces can't get more caps than root/Docker wants to give them.But the bit isn't at all Docker specific. Any privileged task that wants the mask to apply to itself would benefit. With just the exemption this wouldn't be possible:
(1) A runtime that holds full capabilities gives a user namespace it creates all bits.
It can just set the bit before creating it.(2) In a container without a user namespace container root has host-level capabilities. Any user namespace it creates gets them through this exemption thing. So it can also add them back to its mask. And the mask is inherited. So every process it starts can then create user namespaces with them.
Quoted 6 lines
Quoted 3 lines
by raising the bit we stop both. The locked bit keeps container root which also has
CAP_SETPCAPfrom clearing it.I'm still not 100% sure I'm following this. By "exemption" are you talking about the
cred->cap_premittedterm here?Yes.
Quoted 5 lines
ns->cap_bset=parent->cap_bset&(cred->cap_userns | cred->cap_permitted);(As as aside, as formulated, the
parent->cap_bsetterm should be irrelevant, no? cred always refers to a task in parent, and this(
I don't think it i.scap_usernsis full by default. Entering a namespace doesn't change it. A task inside a namespace with a reducedcap_bsetstill has the full mask. Without the term a child namespace gets more caps than its parent had.
cap_permittedcan grow through a setuid-root exec in the parent namespace. And that exec is bounded by the tasks bounding set and not by the namespace bounding set.So that term ensures that the namespace bounding set shrinks monotonically by construction.
I think it would only be redundant if exec would be clamped by
cap_bset. I'm not sure if the patchset does this./me looks...
Ah, ok... this patch series already clamps exec to the namespace bounding set. So yes, you're right.
)Quoted 6 lines
whole thing is defined so that
cap_usernsandcap_permittedare always subsets of parent'scap_bset, right?)I think I agree that there needs to be a way to turn the
cap_permittedthing on and off (and I'm also not sure whethercap_permittedis better thancap_effective), but I'm not convinced that an inheritableThe effective set can be raised from the permitted set at will. So I think permitted is just more correct.
Quoted 4 lines
and lockable bit is necessary or wise.
How about changing the rule to:
Quoted 8 lines
child->cap_bset=parent->cap_bset&soft_cap_userns& (cred->cap_userns|cred->cap_permitted)a) (ugly but easier) A non-inheritable prctl-controlled mask
soft_cap_userns, changing the rule toparent->cap_bset&soft_cap_userns& (cred->cap_userns|cred->cap_permitted).soft_cap_usernswould be reset to all ones on on fork and exec to avoid creating new inheritable security-relevant state.So both let the creator pick. But the bit is for the creator when it wants to self-restrict: container-root without a user namespace.
It's the same reason that securebits and
no_new_privsare inheritable and lockable. Afaict, a) is reset on exec so it doesn't control the next exec. b) covers namespace creation but not unsharing a user namespace.Quoted 7 lines
b) A whole new create-a-namespace API where the caller chooses
soft_cap_usernsat the time they create the namespace.Quoted 1 line
On the host none of that matters as the mask is root's own policy there.
I'm still not seeing how there's a difference between host vs init-userns-container vs separate-userns-container. After all, in
I think the difference is simply whether the restricting task holds the capabilities itself. Unprivileged users on the host don't and so they're not subject to the exemption. The bit is for that case where the task holds the caps.
But ok, if we really don't want to bother with container without user namespaces the bit vs a) thing can also go into a follow-up series.
Quoted 5 lines
Unfortunately we don't live in this world, and I'm not convinced that can credibly even approximate it, because people really like their setuid programs working inside a userns. It still bugs me that we're designing permission systems designed to work in the POSIX model that I think we all kind of agree is fundamentally rather messed up.
I don't think all hope is lost. We have slowly been pushing in this direction. systemd allows to set NoNewPrivileges= in it's global config so it's possible to enable it for the whole system easily.
There's been a ton of work to get rid of classic setuid-exec stuff:
* run0 instead of sudo (with sudo compat), and systemd-ptybrokerd for interactive shells
* nsresourced for user namespaces with delegated ranges, mountfsd for unprivileged image mounts
* outside of systemd: pwaccessd/pwupdd/newidmapd replacingunix_chkpwd, passwd and newuidmap/newgidmap, polkit without a setuid helper, and su/sudo/pkexec wrappers on top of ptybrokerdBut yes, containers are the sore spot.
no_new_privsinherited from PID 1 breaks setuid inside of containers.My idea has been to make this dynamic:
* deny privilege gain on exec in the initial user namespace and allow it in nested ones. I mused about this in
https://github.com/uapi-group/kernel-features/pull/38Quoted 8 lines
Quoted 2 lines
Also, since v7.1 there's
CLONE_NNPto spawn a child withoutno_new_privsset.Forgot:
https://www.thkukuk.de/blog/no_new_privs/
has an overview of where we're currently at.
Nice!
I commented in the uapi-group issue:
I think there may be a rather more direct solution to this problem. I seem to recall advocating for clearing
no_new_privswhen entering a userns way back when, and IIRC I dropped this as part of the extensive negotiation to get NNP into the kernel in the first place. (I think dropping it was probably the right decision to keep the final patch simple.)But I think I would still advocate for an option to let clone, unshare and setns callers turn
no_new_privsoff. The logic is that, if you own a userns, you already have all capabilities in it. If you enter it, you get to keep those by having them raised incap_permitted. Being able to clear NNP and thus drop and subsequently regain them does not let you do anything you couldn’t already do.An LSM hook for this would be needed because this argument does not apply to non-namespace-scoped LSM-based privileges. But the LSM hook would just be a "may this caller enter this userns and clear
no_new_privswhile doing so" query. In the absence of LSMs, the operation would be allowed.
Quoted 5 lines
This would allow a fully
no_new_privshost to run an ordinary container that runs, in the ordinary way, withoutno_new_privs, and without hitting any new LSM calls after it's started.The API could be as simple as a
CLONE_CLEAR_NNPbit.
I think that sounds ok. I worry a little it since it would somewhat alter the promise that NNP gives. What model do you envision? It seems that CLONE_CLEAR_NNP would only be allowed with CLONE_NEWUSER. I _think_ this safe even for privileged users that create a user namespace and map uid 0 to uid 0. So I think this could work.
Quoted 44 lines · Christian Brauner
Quoted 41 lines · Andy Lutomirski
Quoted 4 lines
Quoted 4 lines
* deny privilege gain on exec in the initial user namespace and allow it in nested ones. I mused about this in
https://github.com/uapi-group/kernel-features/pull/38Quoted 8 lines
Quoted 2 lines
Also, since v7.1 there's
CLONE_NNPto spawn a child withoutno_new_privsset.Forgot:
https://www.thkukuk.de/blog/no_new_privs/
has an overview of where we're currently at.
Nice!
I commented in the uapi-group issue:
I think there may be a rather more direct solution to this problem. I seem to recall advocating for clearing
no_new_privswhen entering a userns way back when, and IIRC I dropped this as part of the extensive negotiation to get NNP into the kernel in the first place. (I think dropping it was probably the right decision to keep the final patch simple.)But I think I would still advocate for an option to let clone, unshare and setns callers turn
no_new_privsoff. The logic is that, if you own a userns, you already have all capabilities in it. If you enter it, you get to keep those by having them raised incap_permitted. Being able to clear NNP and thus drop and subsequently regain them does not let you do anything you couldn’t already do.An LSM hook for this would be needed because this argument does not apply to non-namespace-scoped LSM-based privileges. But the LSM hook would just be a "may this caller enter this userns and clear
no_new_privswhile doing so" query. In the absence of LSMs, the operation would be allowed.This would allow a fully
no_new_privshost to run an ordinary container that runs, in the ordinary way, withoutno_new_privs, and without hitting any new LSM calls after it's started.
Quoted 7 lines
Quoted 1 line
The API could be as simple as a
CLONE_CLEAR_NNPbit.I think that sounds ok. I worry a little it since it would somewhat alter the promise that NNP gives. What model do you envision? It seems that
CLONE_CLEAR_NNPwould only be allowed withCLONE_NEWUSER. I _think_ this safe even for privileged users that create a user namespace and map uid 0 to uid 0. So I think this could work.
Whoops. I thought that and didn't type that. Yes, I think you should only be able to clear NNP with CLONE_NEWUSER.
(And if something like cells ever lands, presumably a task with NNP set should be allowed to create a cell without NNP in the init task as long as the same LSM hook says it's okay.)
Quoted 3 lines · Mickaël Salaün
Hallgrimur, could you please explain why your use case would not work with Landlock? The capability split or new clone flags would be complementary of course.
Apologies for the late reply.
Landlock's capability restrictions work well for self-sandboxing applications and launchers. The main gap for our use case is setting a host-wide default for unprivileged user namespaces while still permitting exceptions. Because Landlock restricts all capability use (not just capabilities acquired via user namespaces) and its domains are strictly irrevocable, PID 1 cannot apply a default policy at boot without locking out privileged services, file-capability helpers, and authorized workloads. Using Landlock here would require explicit opt-in enforcement at every unprivileged transition boundary (SSH, container/job launchers, etc.), where missing any entrypoint leaves unprivileged user namespaces unrestricted.
In v1 we had the global sysctl to tackle this. In v2 (based on Christian and Andy's feedback), we combine per-cred cap_userns with per-userns cap_bset), and PID 1 or a service manager can lower the default userns ceiling once at the root of the process tree, while privileged tasks automatically retain capabilities held in cap_permitted and can explicitly raise cap_userns for authorized workloads unless locked.
Another minor difference is visibility. Clamping the task's capability sets on userns entry (and exposing CapUns in /proc/<pid>/status in v2) makes it easy for userspace to inspect what is actually restricted.
Christian Brauner
maintainerQuoted 19 lines · Hallgrimur H. Gunnarsson
Quoted 3 lines · Mickaël Salaün
Hallgrimur, could you please explain why your use case would not work with Landlock? The capability split or new clone flags would be complementary of course.
Apologies for the late reply.
Landlock's capability restrictions work well for self-sandboxing applications and launchers. The main gap for our use case is setting a host-wide default for unprivileged user namespaces while still permitting exceptions. Because Landlock restricts all capability use (not just capabilities acquired via user namespaces) and its domains are strictly irrevocable, PID 1 cannot apply a default policy at boot without locking out privileged services, file-capability helpers, and authorized workloads. Using Landlock here would require explicit opt-in enforcement at every unprivileged transition boundary (SSH, container/job launchers, etc.), where missing any entrypoint leaves unprivileged user namespaces unrestricted.
Quoted 3 lines
In v1 we had the global sysctl to tackle this. In v2 (based on Christian and Andy's feedback), we combine per-cred
cap_usernswith per-usernscap_bset), and PID 1 or a service manager can lower the default userns
Plus, this is useful and improves security in general without having to use any LSM framework.