* [PATCH v2 1/4] userns: introduce capability bounding set for user namespaces
2026-11-19 10:42 [PATCH v2 0/4] userns: per-namespace capability bounding set Hallgrimur H. Gunnarsson
@ 2026-11-19 10:42 ` Hallgrimur H. Gunnarsson
2026-11-19 10:42 ` [PATCH v2 2/4] capability: bound ptrace and cred subset checks by userns ceilings Hallgrimur H. Gunnarsson
` (2 subsequent siblings)
3 siblings, 0 replies; 5+ messages in thread
From: Hallgrimur H. Gunnarsson @ 2026-11-19 10:42 UTC (permalink / raw)
To: Christian Brauner, Serge Hallyn, Andy Lutomirski
Cc: Paul Moore, James Morris, David Howells, Jarkko Sakkinen,
Kees Cook, Jonathan Corbet, Shuah Khan, Randy Dunlap,
Mickaël Salaün, Jonathan Calmels, Jann Horn,
Günther Noack, KP Singh, Casey Schaufler, linux-fsdevel,
linux-security-module, linux-api, containers, keyrings, linux-doc,
linux-kselftest, linux-kernel, Hallgrimur H. Gunnarsson
When a process creates a new user namespace, it receives a full set of
capabilities (CAP_FULL_SET) scoped to that namespace. While namespaced
in scope, several of these capabilities (such as CAP_NET_ADMIN and
CAP_NET_RAW) expose broad kernel attack surface that many sandboxes and
containers never need. However, there is currently no configurable way
to withhold such capabilities from user namespaces while still granting
them to workloads that require them.
Introduce a per-user-namespace capability bounding set
(user_ns->cap_bset) and a per-credential userns capability set
(cred->cap_userns) queried and modified via prctl(PR_CAP_USERNS).
Lowering or clearing capabilities in cap_userns (PR_CAP_USERNS_LOWER
and PR_CAP_USERNS_CLEAR_ALL) requires CAP_SETPCAP in the current user
namespace or no_new_privs, while raising a capability
(PR_CAP_USERNS_RAISE) requires holding it in cap_permitted.
By default, a credential's userns capability ceiling (cred_userns_bset)
combines cap_userns with cap_permitted (matching what the task could
raise via PR_CAP_USERNS_RAISE), so privileged tasks retain capabilities
they already hold even when cap_userns has been lowered. Setting
SECBIT_CAP_USERNS_STRICT enforces cap_userns strictly, ignores
cap_permitted, and disables PR_CAP_USERNS_RAISE, allowing privileged
launchers or outer containers to spawn trimmed descendant user
namespaces without dropping their own cap_permitted. Both
SECBIT_CAP_USERNS_STRICT and its lock bit persist across user namespace
transitions.
When a new user namespace is created, set its cap_bset to the
intersection of its parent's cap_bset and the creator's ceiling
(parent_ns->cap_bset & cred_userns_bset(cred)), so capability bounding
sets decrease monotonically down the namespace hierarchy.
On user namespace entry (during creation or via setns()), clamp the
task's permitted, effective, and bounding sets to user_ns->cap_bset &
cred_userns_bset(cred) instead of granting CAP_FULL_SET, and intersect
cap_userns with user_ns->cap_bset. Because user namespace transitions
only move downward in the hierarchy, bits absent from user_ns->cap_bset
can never be acquired in descendant namespaces. Clearing them keeps
cap_userns and PR_CAP_USERNS_IS_SET accurate after setns() and keeps
all six task capability sets as subsets of user_ns->cap_bset.
In cap_capable_helper(), bound implicit parent-owner capabilities by
the owned namespace's cap_bset, and grant them only when that cap_bset
is a subset of cred_userns_bset(cred), preventing tasks from exercising
privileges over less-restricted descendant namespaces.
Initialize both init_user_ns.cap_bset and init_cred.cap_userns to
CAP_FULL_SET, preserving existing behavior unless cap_userns is
explicitly restricted.
Suggested-by: Christian Brauner <brauner@kernel.org>
Suggested-by: Andy Lutomirski <luto@kernel.org>
Signed-off-by: Hallgrimur H. Gunnarsson <halg@google.com>
---
Documentation/security/credentials.rst | 12 ++++-
include/linux/cred.h | 22 +++++++++
include/linux/user_namespace.h | 12 +++++
include/uapi/linux/prctl.h | 7 +++
include/uapi/linux/securebits.h | 16 +++++-
init/init_task.c | 1 +
kernel/user.c | 1 +
kernel/user_namespace.c | 33 +++++++++----
security/commoncap.c | 68 ++++++++++++++++++++++++--
security/keys/process_keys.c | 1 +
10 files changed, 158 insertions(+), 15 deletions(-)
diff --git a/Documentation/security/credentials.rst b/Documentation/security/credentials.rst
index a39a2a2f67aa..2645cc81515a 100644
--- a/Documentation/security/credentials.rst
+++ b/Documentation/security/credentials.rst
@@ -149,6 +149,7 @@ The Linux kernel supports the following types of credentials:
- Set of inheritable capabilities
- Set of effective capabilities
- Capability bounding set
+ - Set of userns capabilities
These are only carried by tasks. They indicate superior capabilities
granted piecemeal to a task that an ordinary task wouldn't otherwise have.
@@ -170,12 +171,19 @@ The Linux kernel supports the following types of credentials:
``execve()``, especially when a binary is executed that will execute as
UID 0.
+ The userns capabilities (manipulated via ``prctl(PR_CAP_USERNS)``) define
+ a ceiling on the capabilities a task may acquire when creating or entering
+ a user namespace, and prevent exercising implicit owner capabilities via
+ any owned user namespace whose bounding set exceeds this ceiling.
+ Capabilities held in the permitted set remain included in this ceiling by
+ default unless ``SECBIT_CAP_USERNS_STRICT`` is set.
+
3. Secure management flags (securebits).
These are only carried by tasks. These govern the way the above
credentials are manipulated and inherited over certain operations such as
- execve(). They aren't used directly as objective or subjective
- credentials.
+ execve() and user namespace transitions. They aren't used directly as
+ objective or subjective credentials.
4. Keys and keyrings.
diff --git a/include/linux/cred.h b/include/linux/cred.h
index 49c26af37349..20857d11e032 100644
--- a/include/linux/cred.h
+++ b/include/linux/cred.h
@@ -14,6 +14,7 @@
#include <linux/atomic.h>
#include <linux/refcount.h>
#include <linux/uidgid.h>
+#include <linux/securebits.h>
#include <linux/sched.h>
#include <linux/sched/user.h>
@@ -128,6 +129,7 @@ struct cred {
kernel_cap_t cap_effective; /* caps we can actually use */
kernel_cap_t cap_bset; /* capability bounding set */
kernel_cap_t cap_ambient; /* Ambient capability set */
+ kernel_cap_t cap_userns; /* userns capability set */
#ifdef CONFIG_KEYS
unsigned char jit_keyring; /* default keyring to attach requested
* keys to */
@@ -178,6 +180,26 @@ static inline bool cap_ambient_invariant_ok(const struct cred *cred)
cred->cap_inheritable));
}
+/**
+ * cred_userns_bset - Ceiling on capabilities a userns may grant @cred
+ * @cred: Credentials to evaluate
+ *
+ * By default, capabilities already held in cap_permitted are also allowed
+ * (matching what @cred could raise via PR_CAP_USERNS_RAISE). When
+ * SECBIT_CAP_USERNS_STRICT is set, cap_userns is enforced strictly and
+ * cap_permitted is ignored. Because both cap_userns and cap_permitted are
+ * bounded by cred->user_ns->cap_bset, the returned mask never exceeds the
+ * enclosing user namespace's bounding set.
+ *
+ * Return: Capability mask @cred may acquire in or exercise over a userns.
+ */
+static inline kernel_cap_t cred_userns_bset(const struct cred *cred)
+{
+ if (cred->securebits & SECBIT_CAP_USERNS_STRICT)
+ return cred->cap_userns;
+ return cap_combine(cred->cap_userns, cred->cap_permitted);
+}
+
static inline const struct cred *override_creds(const struct cred *override_cred)
{
const struct cred *old = current->cred;
diff --git a/include/linux/user_namespace.h b/include/linux/user_namespace.h
index 91232053775d..5f31390aa583 100644
--- a/include/linux/user_namespace.h
+++ b/include/linux/user_namespace.h
@@ -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>
@@ -84,6 +85,7 @@ struct user_namespace {
int level;
kuid_t owner;
kgid_t group;
+ kernel_cap_t cap_bset;
struct ns_common ns;
unsigned long flags;
/* parent_could_setfcap: true if the creator if this ns had CAP_SETFCAP
@@ -183,6 +185,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);
@@ -221,6 +228,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;
diff --git a/include/uapi/linux/prctl.h b/include/uapi/linux/prctl.h
index b6ec6f693719..137a5d0a6704 100644
--- a/include/uapi/linux/prctl.h
+++ b/include/uapi/linux/prctl.h
@@ -416,4 +416,11 @@ struct prctl_mm_map {
# define PR_CFI_DISABLE _BITUL(1)
# define PR_CFI_LOCK _BITUL(2)
+/* Control the userns capability mask */
+#define PR_CAP_USERNS 82
+# define PR_CAP_USERNS_IS_SET 1
+# define PR_CAP_USERNS_RAISE 2
+# define PR_CAP_USERNS_LOWER 3
+# define PR_CAP_USERNS_CLEAR_ALL 4
+
#endif /* _LINUX_PRCTL_H */
diff --git a/include/uapi/linux/securebits.h b/include/uapi/linux/securebits.h
index 3fba30dbd68b..cc8ed81683e2 100644
--- a/include/uapi/linux/securebits.h
+++ b/include/uapi/linux/securebits.h
@@ -69,12 +69,26 @@
#define SECBIT_EXEC_DENY_INTERACTIVE_LOCKED \
(issecure_mask(SECURE_EXEC_DENY_INTERACTIVE_LOCKED))
+/*
+ * When set, creating or entering a user namespace only grants capabilities
+ * present in cap_userns (ignoring cap_permitted), and PR_CAP_USERNS_RAISE
+ * is disabled.
+ */
+#define SECURE_CAP_USERNS_STRICT 12
+#define SECURE_CAP_USERNS_STRICT_LOCKED 13 /* make bit-12 immutable */
+
+#define SECBIT_CAP_USERNS_STRICT \
+ (issecure_mask(SECURE_CAP_USERNS_STRICT))
+#define SECBIT_CAP_USERNS_STRICT_LOCKED \
+ (issecure_mask(SECURE_CAP_USERNS_STRICT_LOCKED))
+
#define SECURE_ALL_BITS (issecure_mask(SECURE_NOROOT) | \
issecure_mask(SECURE_NO_SETUID_FIXUP) | \
issecure_mask(SECURE_KEEP_CAPS) | \
issecure_mask(SECURE_NO_CAP_AMBIENT_RAISE) | \
issecure_mask(SECURE_EXEC_RESTRICT_FILE) | \
- issecure_mask(SECURE_EXEC_DENY_INTERACTIVE))
+ issecure_mask(SECURE_EXEC_DENY_INTERACTIVE) | \
+ issecure_mask(SECURE_CAP_USERNS_STRICT))
#define SECURE_ALL_LOCKS (SECURE_ALL_BITS << 1)
#define SECURE_ALL_UNPRIVILEGED (issecure_mask(SECURE_EXEC_RESTRICT_FILE) | \
diff --git a/init/init_task.c b/init/init_task.c
index ce7c2b07d855..a5c4bf902dcc 100644
--- a/init/init_task.c
+++ b/init/init_task.c
@@ -92,6 +92,7 @@ static struct cred init_cred = {
.cap_permitted = CAP_FULL_SET,
.cap_effective = CAP_FULL_SET,
.cap_bset = CAP_FULL_SET,
+ .cap_userns = CAP_FULL_SET,
.user = INIT_USER,
.user_ns = &init_user_ns,
.group_info = &init_groups,
diff --git a/kernel/user.c b/kernel/user.c
index 21bafdc11379..97d95e733a8c 100644
--- a/kernel/user.c
+++ b/kernel/user.c
@@ -68,6 +68,7 @@ struct user_namespace init_user_ns = {
},
.owner = GLOBAL_ROOT_UID,
.group = GLOBAL_ROOT_GID,
+ .cap_bset = CAP_FULL_SET,
.flags = USERNS_INIT_FLAGS,
#ifdef CONFIG_KEYS
.keyring_name_list = LIST_HEAD_INIT(init_user_ns.keyring_name_list),
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index cd748e1cbace..96cdc29f3611 100644
--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -4,6 +4,7 @@
#include <linux/export.h>
#include <linux/nsproxy.h>
#include <linux/slab.h>
+#include <linux/capability.h>
#include <linux/sched/signal.h>
#include <linux/user_namespace.h>
#include <linux/proc_ns.h>
@@ -44,18 +45,30 @@ static void dec_user_namespaces(struct ucounts *ucounts)
static void set_cred_user_ns(struct cred *cred, struct user_namespace *user_ns)
{
- /* Start with the same capabilities as init but useless for doing
- * anything as the capabilities are bound to the new user namespace.
- * The exec securebits grant nothing, they are restrictions the task
- * placed on itself. Keep them and their locks.
+ unsigned int keep_secbits;
+ kernel_cap_t caps;
+
+ /*
+ * Preserve unprivileged and userns-strict securebits and their locks
+ * across user namespace transitions.
+ */
+ keep_secbits = SECURE_ALL_UNPRIVILEGED | SECBIT_CAP_USERNS_STRICT;
+ cred->securebits &= keep_secbits | (keep_secbits << 1);
+ cred->securebits |= SECUREBITS_DEFAULT;
+
+ /*
+ * Invariant: for every credential in a user namespace, all six task
+ * capability masks (effective, permitted, inheritable, ambient, bset,
+ * and userns) are subsets of user_ns->cap_bset.
*/
- cred->securebits = SECUREBITS_DEFAULT |
- (cred->securebits & (SECURE_ALL_UNPRIVILEGED | SECURE_ALL_UNPRIVILEGED << 1));
+ caps = cap_intersect(user_ns->cap_bset, cred_userns_bset(cred));
+
cred->cap_inheritable = CAP_EMPTY_SET;
- cred->cap_permitted = CAP_FULL_SET;
- cred->cap_effective = CAP_FULL_SET;
+ cred->cap_permitted = caps;
+ cred->cap_effective = caps;
cred->cap_ambient = CAP_EMPTY_SET;
- cred->cap_bset = CAP_FULL_SET;
+ cred->cap_bset = caps;
+ cred->cap_userns = cap_intersect(user_ns->cap_bset, cred->cap_userns);
#ifdef CONFIG_KEYS
key_put(cred->request_key_auth);
cred->request_key_auth = NULL;
@@ -148,6 +161,8 @@ int create_user_ns(struct cred *new)
set_userns_rlimit_max(ns, UCOUNT_RLIMIT_SIGPENDING, rlimit(RLIMIT_SIGPENDING));
set_userns_rlimit_max(ns, UCOUNT_RLIMIT_MEMLOCK, rlimit(RLIMIT_MEMLOCK));
ns->ucounts = ucounts;
+ ns->cap_bset = cap_intersect(parent_ns->cap_bset,
+ cred_userns_bset(new));
/* Inherit USERNS_SETGROUPS_ALLOWED from our parent */
mutex_lock(&userns_state_mutex);
diff --git a/security/commoncap.c b/security/commoncap.c
index d47ab3022343..ddac8e917680 100644
--- a/security/commoncap.c
+++ b/security/commoncap.c
@@ -88,11 +88,15 @@ 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 within the owned namespace's
+ * bounding set, as long as it does not exceed the caller's
+ * userns capability ceiling.
*/
- if ((ns->parent == cred_ns) && uid_eq(ns->owner, cred->euid))
+ if (ns->parent == cred_ns && uid_eq(ns->owner, cred->euid) &&
+ cap_issubset(ns->cap_bset, cred_userns_bset(cred)) &&
+ userns_has_cap(ns, cap))
return 0;
/*
@@ -1283,6 +1287,59 @@ static int cap_prctl_drop(unsigned long cap)
return commit_creds(new);
}
+static int prctl_cap_userns(unsigned long op, unsigned long cap)
+{
+ const struct cred *cred = current_cred();
+ kernel_cap_t userns = cred->cap_userns;
+ struct cred *new;
+
+ switch (op) {
+ case PR_CAP_USERNS_IS_SET:
+ if (!cap_valid(cap))
+ return -EINVAL;
+ return cap_raised(userns, cap);
+
+ case PR_CAP_USERNS_RAISE:
+ if (!cap_valid(cap))
+ return -EINVAL;
+ if (!cap_raised(cred->cap_permitted, cap) ||
+ (cred->securebits & SECBIT_CAP_USERNS_STRICT))
+ return -EPERM;
+ cap_raise(userns, cap);
+ break;
+
+ case PR_CAP_USERNS_LOWER:
+ if (!cap_valid(cap))
+ return -EINVAL;
+ if (!task_no_new_privs(current) &&
+ !ns_capable(current_user_ns(), CAP_SETPCAP))
+ return -EPERM;
+ cap_lower(userns, cap);
+ break;
+
+ case PR_CAP_USERNS_CLEAR_ALL:
+ if (cap)
+ return -EINVAL;
+ if (!task_no_new_privs(current) &&
+ !ns_capable(current_user_ns(), CAP_SETPCAP))
+ return -EPERM;
+ cap_clear(userns);
+ break;
+
+ default:
+ return -EINVAL;
+ }
+
+ if (cap_isidentical(userns, cred->cap_userns))
+ return 0;
+
+ new = prepare_creds();
+ if (!new)
+ return -ENOMEM;
+ new->cap_userns = userns;
+ return commit_creds(new);
+}
+
/**
* cap_task_prctl - Implement process control functions for this security module
* @option: The process control function requested
@@ -1434,6 +1491,11 @@ int cap_task_prctl(int option, unsigned long arg2, unsigned long arg3,
return commit_creds(new);
}
+ case PR_CAP_USERNS:
+ if (arg4 || arg5)
+ return -EINVAL;
+ return prctl_cap_userns(arg2, arg3);
+
default:
/* No functionality available - continue with default */
return -ENOSYS;
diff --git a/security/keys/process_keys.c b/security/keys/process_keys.c
index 3af71c6322af..183fe18a8f62 100644
--- a/security/keys/process_keys.c
+++ b/security/keys/process_keys.c
@@ -1026,6 +1026,7 @@ void key_change_session_keyring(struct callback_head *twork)
new->cap_effective = old->cap_effective;
new->cap_ambient = old->cap_ambient;
new->cap_bset = old->cap_bset;
+ new->cap_userns = old->cap_userns;
new->jit_keyring = old->jit_keyring;
new->thread_keyring = key_get(old->thread_keyring);
--
2.56.1.708.g77570a6a1d-goog
^ permalink raw reply related [flat|nested] 5+ messages in thread* [PATCH v2 4/4] selftests/capabilities: add userns capability bounding set tests
2026-11-19 10:42 [PATCH v2 0/4] userns: per-namespace capability bounding set Hallgrimur H. Gunnarsson
` (2 preceding siblings ...)
2026-11-19 10:42 ` [PATCH v2 3/4] proc: expose userns capability mask as CapUns in /proc/<pid>/status Hallgrimur H. Gunnarsson
@ 2026-11-19 10:42 ` Hallgrimur H. Gunnarsson
3 siblings, 0 replies; 5+ messages in thread
From: Hallgrimur H. Gunnarsson @ 2026-11-19 10:42 UTC (permalink / raw)
To: Christian Brauner, Serge Hallyn, Andy Lutomirski
Cc: Paul Moore, James Morris, David Howells, Jarkko Sakkinen,
Kees Cook, Jonathan Corbet, Shuah Khan, Randy Dunlap,
Mickaël Salaün, Jonathan Calmels, Jann Horn,
Günther Noack, KP Singh, Casey Schaufler, linux-fsdevel,
linux-security-module, linux-api, containers, keyrings, linux-doc,
linux-kselftest, linux-kernel, Hallgrimur H. Gunnarsson
Add selftests in tools/testing/selftests/capabilities covering:
- prctl(PR_CAP_USERNS) argument validation and authorization rules for
lowering, clearing, and raising capabilities.
- Default full capability grants, cap_userns restrictions (including
clearing all capabilities), and monotonic inheritance across nested
user namespaces.
- Default retention of capabilities in cap_permitted, and strict
enforcement and persistence of SECBIT_CAP_USERNS_STRICT and its lock
across user namespace transitions.
- Credential and cap_userns clamping upon entering a user namespace via
setns().
- Implicit parent-owner capability bounding by the owned namespace's
cap_bset (including over descendants) and the caller's userns
ceiling, while preserving explicit ancestor capabilities.
- Ptrace restrictions across PTRACE_ATTACH, PTRACE_TRACEME, and
PTRACE_MODE_READ for same-userns peers and owned descendant
namespaces, while preserving explicit CAP_SYS_PTRACE.
- Preservation of dumpable and pdeath_signal when narrowing the userns
ceiling and resets when widening it.
- CapUns reporting in /proc/self/status.
Signed-off-by: Hallgrimur H. Gunnarsson <halg@google.com>
---
.../testing/selftests/capabilities/.gitignore | 1 +
tools/testing/selftests/capabilities/Makefile | 2 +-
.../capabilities/userns_bounding_set_test.c | 1064 +++++++++++++++++
3 files changed, 1066 insertions(+), 1 deletion(-)
create mode 100644 tools/testing/selftests/capabilities/userns_bounding_set_test.c
diff --git a/tools/testing/selftests/capabilities/.gitignore b/tools/testing/selftests/capabilities/.gitignore
index 426d9adca67c..28767c08dea8 100644
--- a/tools/testing/selftests/capabilities/.gitignore
+++ b/tools/testing/selftests/capabilities/.gitignore
@@ -1,3 +1,4 @@
# SPDX-License-Identifier: GPL-2.0-only
test_execve
+userns_bounding_set_test
validate_cap
diff --git a/tools/testing/selftests/capabilities/Makefile b/tools/testing/selftests/capabilities/Makefile
index 411ac098308f..b29f7b117c11 100644
--- a/tools/testing/selftests/capabilities/Makefile
+++ b/tools/testing/selftests/capabilities/Makefile
@@ -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
diff --git a/tools/testing/selftests/capabilities/userns_bounding_set_test.c b/tools/testing/selftests/capabilities/userns_bounding_set_test.c
new file mode 100644
index 000000000000..9aa9e5b31130
--- /dev/null
+++ b/tools/testing/selftests/capabilities/userns_bounding_set_test.c
@@ -0,0 +1,1064 @@
+// SPDX-License-Identifier: GPL-2.0
+#define _GNU_SOURCE
+
+#include <errno.h>
+#include <fcntl.h>
+#include <sched.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <sys/ptrace.h>
+#include <sys/socket.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <linux/capability.h>
+#include <linux/prctl.h>
+#include <linux/sched.h>
+#include <linux/securebits.h>
+
+#include "../clone3/clone3_selftests.h"
+#include "../kselftest_harness.h"
+
+#define MAX_TRACEES 2
+
+struct cap_state {
+ bool bset;
+ bool permitted;
+ bool effective;
+};
+
+static int get_cap_state(int cap, struct cap_state *state)
+{
+ struct __user_cap_header_struct hdr = {
+ .version = _LINUX_CAPABILITY_VERSION_3,
+ .pid = 0,
+ };
+ struct __user_cap_data_struct data[2];
+ uint32_t mask;
+ int idx;
+
+ if (cap < 0 || cap > CAP_LAST_CAP)
+ return -EINVAL;
+
+ if (syscall(SYS_capget, &hdr, data) != 0)
+ return -errno;
+
+ idx = CAP_TO_INDEX(cap);
+ mask = CAP_TO_MASK(cap);
+
+ state->bset = (prctl(PR_CAPBSET_READ, cap, 0, 0, 0) == 1);
+ state->permitted = (data[idx].permitted & mask) != 0;
+ state->effective = (data[idx].effective & mask) != 0;
+
+ return 0;
+}
+
+static bool cap_raised(int cap)
+{
+ struct cap_state t;
+
+ if (get_cap_state(cap, &t) != 0)
+ return false;
+
+ return t.bset && t.permitted && t.effective;
+}
+
+static bool cap_dropped(int cap)
+{
+ struct cap_state t;
+
+ if (get_cap_state(cap, &t) != 0)
+ return false;
+
+ return !t.bset && !t.permitted && !t.effective;
+}
+
+static int set_caps(uint64_t permitted, uint64_t effective)
+{
+ struct __user_cap_header_struct hdr = {
+ .version = _LINUX_CAPABILITY_VERSION_3,
+ };
+ struct __user_cap_data_struct data[2] = {
+ {
+ .permitted = (uint32_t)permitted,
+ .effective = (uint32_t)effective,
+ },
+ {
+ .permitted = (uint32_t)(permitted >> 32),
+ .effective = (uint32_t)(effective >> 32),
+ },
+ };
+
+ return syscall(SYS_capset, &hdr, data);
+}
+
+static int drop_all_caps(void)
+{
+ return set_caps(0, 0);
+}
+
+static int drop_caps_except(int cap)
+{
+ uint64_t cap_mask = 1ULL << cap;
+
+ return set_caps(cap_mask, cap_mask);
+}
+
+static int write_file(const char *path, const char *str)
+{
+ ssize_t len = strlen(str);
+ ssize_t ret;
+ int fd, err;
+
+ fd = open(path, O_WRONLY | O_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+ ret = write(fd, str, len);
+ err = errno;
+ close(fd);
+
+ if (ret < 0)
+ return -err;
+ return (ret == len) ? 0 : -EIO;
+}
+
+static int map_current_ugid(uid_t uid, gid_t gid)
+{
+ char map_buf[64];
+ int ret;
+
+ /*
+ * May return -EPERM in nested user namespaces when an ancestor
+ * namespace already set setgroups to "deny".
+ */
+ ret = write_file("/proc/self/setgroups", "deny\n");
+ if (ret != 0 && ret != -EPERM)
+ return ret;
+
+ snprintf(map_buf, sizeof(map_buf), "0 %u 1\n", uid);
+ ret = write_file("/proc/self/uid_map", map_buf);
+ if (ret != 0)
+ return ret;
+
+ snprintf(map_buf, sizeof(map_buf), "0 %u 1\n", gid);
+ return write_file("/proc/self/gid_map", map_buf);
+}
+
+static int read_proc_userns(uint64_t *val)
+{
+ static const char prefix[] = "CapUns:\t";
+ FILE *f = fopen("/proc/self/status", "r");
+ char line[256];
+ int ret = -1;
+
+ if (!f)
+ return -1;
+
+ while (fgets(line, sizeof(line), f)) {
+ if (strncmp(line, prefix, strlen(prefix)) == 0) {
+ *val = strtoull(line + strlen(prefix), NULL, 16);
+ ret = 0;
+ break;
+ }
+ }
+
+ fclose(f);
+ return ret;
+}
+
+/*
+ * Spawns a child userns owned by the caller's euid without mutating the
+ * caller's credentials. Uses CLONE_FILES so the child can open its own
+ * /proc/self/ns/user directly into the parent's fd table and exit cleanly.
+ */
+static int open_child_userns_without(int lower_cap)
+{
+ struct __clone_args args = {
+ .flags = CLONE_FILES,
+ .exit_signal = SIGCHLD,
+ };
+ int ns_fd, status;
+ pid_t child;
+
+ ns_fd = open("/dev/null", O_RDONLY | O_CLOEXEC);
+ if (ns_fd < 0)
+ return -1;
+
+ child = sys_clone3(&args, sizeof(args));
+ if (child < 0) {
+ close(ns_fd);
+ return -1;
+ }
+
+ if (child == 0) {
+ int fd;
+
+ if (lower_cap >= 0) {
+ if (prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ lower_cap, 0, 0) != 0)
+ _exit(1);
+ if (prctl(PR_SET_SECUREBITS, SECBIT_CAP_USERNS_STRICT,
+ 0, 0, 0) != 0)
+ _exit(1);
+ }
+ if (unshare(CLONE_NEWUSER) != 0)
+ _exit(1);
+
+ fd = open("/proc/self/ns/user", O_RDONLY | O_CLOEXEC);
+ if (fd < 0)
+ _exit(1);
+ if (dup3(fd, ns_fd, O_CLOEXEC) < 0)
+ _exit(1);
+ close(fd);
+ _exit(0);
+ }
+
+ if (waitpid(child, &status, 0) != child ||
+ !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
+ close(ns_fd);
+ return -1;
+ }
+
+ return ns_fd;
+}
+
+static int open_child_userns(void)
+{
+ return open_child_userns_without(-1);
+}
+
+FIXTURE(userns_bset) {
+};
+
+FIXTURE_SETUP(userns_bset)
+{
+ uid_t uid = geteuid();
+ gid_t gid = getegid();
+
+ if (prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET, 0, 0, 0) < 0 &&
+ errno == EINVAL)
+ SKIP(return, "PR_CAP_USERNS not supported");
+
+ if (unshare(CLONE_NEWUSER) != 0)
+ SKIP(return, "unshare(CLONE_NEWUSER) failed");
+
+ ASSERT_EQ(0, map_current_ugid(uid, gid));
+}
+
+FIXTURE_TEARDOWN(userns_bset)
+{
+}
+
+/*
+ * An unprivileged userns creator with the default full cap_userns mask
+ * receives all capabilities (0..CAP_LAST_CAP) in a new user namespace.
+ */
+TEST_F(userns_bset, default_full_capabilities)
+{
+ int cap;
+
+ for (cap = 0; cap <= CAP_LAST_CAP; cap++)
+ EXPECT_EQ(1, prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET,
+ cap, 0, 0));
+
+ ASSERT_EQ(0, drop_all_caps());
+ ASSERT_EQ(0, unshare(CLONE_NEWUSER));
+
+ for (cap = 0; cap <= CAP_LAST_CAP; cap++)
+ EXPECT_TRUE(cap_raised(cap));
+}
+
+/*
+ * Verify prctl(PR_CAP_USERNS) rejects unknown sub-options, out-of-range
+ * capabilities, and non-zero reserved arguments.
+ */
+TEST_F(userns_bset, prctl_invalid_args)
+{
+ EXPECT_EQ(-1, prctl(PR_CAP_USERNS, 999, 0, 0, 0));
+ EXPECT_EQ(EINVAL, errno);
+
+ EXPECT_EQ(-1, prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET,
+ CAP_LAST_CAP + 1, 0, 0));
+ EXPECT_EQ(EINVAL, errno);
+ EXPECT_EQ(-1, prctl(PR_CAP_USERNS, PR_CAP_USERNS_RAISE,
+ CAP_LAST_CAP + 1, 0, 0));
+ EXPECT_EQ(EINVAL, errno);
+ EXPECT_EQ(-1, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_LAST_CAP + 1, 0, 0));
+ EXPECT_EQ(EINVAL, errno);
+
+ EXPECT_EQ(-1, prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET,
+ CAP_NET_ADMIN, 1, 0));
+ EXPECT_EQ(EINVAL, errno);
+ EXPECT_EQ(-1, prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET,
+ CAP_NET_ADMIN, 0, 1));
+ EXPECT_EQ(EINVAL, errno);
+
+ EXPECT_EQ(-1, prctl(PR_CAP_USERNS, PR_CAP_USERNS_CLEAR_ALL, 1, 0, 0));
+ EXPECT_EQ(EINVAL, errno);
+}
+
+/*
+ * Verify PR_CAP_USERNS_LOWER and PR_CAP_USERNS_CLEAR_ALL require either
+ * CAP_SETPCAP or no_new_privs.
+ */
+TEST_F(userns_bset, prctl_lower_authorization)
+{
+ /* CAP_SETPCAP alone (without no_new_privs) authorizes LOWER */
+ ASSERT_EQ(0, drop_caps_except(CAP_SETPCAP));
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_RAW, 0, 0));
+ EXPECT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET,
+ CAP_NET_RAW, 0, 0));
+
+ /* Without CAP_SETPCAP or no_new_privs, LOWER and CLEAR_ALL must fail */
+ ASSERT_EQ(0, drop_all_caps());
+ EXPECT_EQ(-1, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+ EXPECT_EQ(EPERM, errno);
+ EXPECT_EQ(-1, prctl(PR_CAP_USERNS, PR_CAP_USERNS_CLEAR_ALL, 0, 0, 0));
+ EXPECT_EQ(EPERM, errno);
+
+ /* Setting no_new_privs unlocks LOWER and CLEAR_ALL */
+ ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0));
+
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+ EXPECT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET,
+ CAP_NET_ADMIN, 0, 0));
+
+ EXPECT_EQ(1, prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET,
+ CAP_SYS_ADMIN, 0, 0));
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_CLEAR_ALL, 0, 0, 0));
+ EXPECT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET,
+ CAP_SYS_ADMIN, 0, 0));
+}
+
+/*
+ * Verify PR_CAP_USERNS_RAISE requires the capability in cap_permitted.
+ */
+TEST_F(userns_bset, prctl_raise_requires_permitted)
+{
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+ EXPECT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET,
+ CAP_NET_ADMIN, 0, 0));
+
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_RAISE,
+ CAP_NET_ADMIN, 0, 0));
+ EXPECT_EQ(1, prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET,
+ CAP_NET_ADMIN, 0, 0));
+
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+ ASSERT_EQ(0, drop_caps_except(CAP_SETPCAP));
+
+ EXPECT_EQ(-1, prctl(PR_CAP_USERNS, PR_CAP_USERNS_RAISE,
+ CAP_NET_ADMIN, 0, 0));
+ EXPECT_EQ(EPERM, errno);
+}
+
+/*
+ * Verify /proc/self/status CapUns reflects PR_CAP_USERNS mutations.
+ */
+TEST_F(userns_bset, proc_status_cap_uns)
+{
+ uint64_t cap_uns = 0;
+
+ ASSERT_EQ(0, read_proc_userns(&cap_uns));
+ EXPECT_NE(0ULL, cap_uns & (1ULL << CAP_NET_ADMIN));
+ EXPECT_NE(0ULL, cap_uns & (1ULL << CAP_SYS_ADMIN));
+
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+ ASSERT_EQ(0, read_proc_userns(&cap_uns));
+ EXPECT_EQ(0ULL, cap_uns & (1ULL << CAP_NET_ADMIN));
+ EXPECT_NE(0ULL, cap_uns & (1ULL << CAP_SYS_ADMIN));
+
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_RAISE,
+ CAP_NET_ADMIN, 0, 0));
+ ASSERT_EQ(0, read_proc_userns(&cap_uns));
+ EXPECT_NE(0ULL, cap_uns & (1ULL << CAP_NET_ADMIN));
+
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_CLEAR_ALL, 0, 0, 0));
+ ASSERT_EQ(0, read_proc_userns(&cap_uns));
+ EXPECT_EQ(0ULL, cap_uns);
+}
+
+/*
+ * Lowering CAP_NET_ADMIN in cap_userns prevents an unprivileged creator from
+ * acquiring it in a child userns while keeping other capabilities intact.
+ */
+TEST_F(userns_bset, unprivileged_restriction)
+{
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+ ASSERT_EQ(0, drop_all_caps());
+ ASSERT_EQ(0, unshare(CLONE_NEWUSER));
+
+ EXPECT_TRUE(cap_raised(CAP_SYS_ADMIN));
+ EXPECT_TRUE(cap_dropped(CAP_NET_ADMIN));
+}
+
+/*
+ * Clearing all capabilities in cap_userns produces a userns with an empty
+ * bounding, permitted, and effective set for an unprivileged creator.
+ */
+TEST_F(userns_bset, clear_all_caps)
+{
+ int cap;
+
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_CLEAR_ALL, 0, 0, 0));
+ ASSERT_EQ(0, drop_all_caps());
+ ASSERT_EQ(0, unshare(CLONE_NEWUSER));
+
+ for (cap = 0; cap <= CAP_LAST_CAP; cap++)
+ EXPECT_TRUE(cap_dropped(cap));
+}
+
+/*
+ * A userns creator retains capabilities held in cred->cap_permitted even when
+ * lowered in cred->cap_userns.
+ */
+TEST_F(userns_bset, creator_retains_permitted_caps)
+{
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_RAW, 0, 0));
+ ASSERT_EQ(0, drop_caps_except(CAP_NET_ADMIN));
+
+ ASSERT_EQ(0, unshare(CLONE_NEWUSER));
+
+ EXPECT_TRUE(cap_raised(CAP_NET_ADMIN));
+ EXPECT_TRUE(cap_dropped(CAP_NET_RAW));
+ EXPECT_TRUE(cap_raised(CAP_SYS_ADMIN));
+
+ EXPECT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET,
+ CAP_NET_ADMIN, 0, 0));
+ EXPECT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET,
+ CAP_NET_RAW, 0, 0));
+}
+
+/*
+ * Verify SECURE_CAP_USERNS_STRICT:
+ * - Prevents PR_CAP_USERNS_RAISE even when cap is in cap_permitted.
+ * - Prevents retaining lowered caps via cap_permitted on userns creation.
+ * - Persists (with its lock bit) across userns transition.
+ */
+TEST_F(userns_bset, securebit_cap_userns_strict)
+{
+ int secbits;
+
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+ ASSERT_EQ(0, prctl(PR_SET_SECUREBITS,
+ SECBIT_CAP_USERNS_STRICT |
+ SECBIT_CAP_USERNS_STRICT_LOCKED, 0, 0, 0));
+
+ /* Lock prevents clearing */
+ EXPECT_EQ(-1, prctl(PR_SET_SECUREBITS, 0, 0, 0, 0));
+ EXPECT_EQ(EPERM, errno);
+
+ /* Cannot raise even though CAP_NET_ADMIN is in cap_permitted */
+ EXPECT_EQ(-1, prctl(PR_CAP_USERNS, PR_CAP_USERNS_RAISE,
+ CAP_NET_ADMIN, 0, 0));
+ EXPECT_EQ(EPERM, errno);
+
+ /* Child userns does not inherit CAP_NET_ADMIN from cap_permitted */
+ ASSERT_EQ(0, unshare(CLONE_NEWUSER));
+ EXPECT_TRUE(cap_dropped(CAP_NET_ADMIN));
+ EXPECT_TRUE(cap_raised(CAP_SYS_ADMIN));
+
+ /* Securebit and lock persist across userns transition */
+ secbits = prctl(PR_GET_SECUREBITS, 0, 0, 0, 0);
+ ASSERT_GE(secbits, 0);
+ EXPECT_NE(0, secbits & SECBIT_CAP_USERNS_STRICT);
+ EXPECT_NE(0, secbits & SECBIT_CAP_USERNS_STRICT_LOCKED);
+}
+
+/*
+ * Verify ns->cap_bset decreases monotonically across nested user namespaces.
+ */
+TEST_F(userns_bset, nested_monotonic_restriction)
+{
+ /* Child userns lacks CAP_NET_ADMIN (keep CAP_SETFCAP to map uid 0) */
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+ ASSERT_EQ(0, drop_caps_except(CAP_SETFCAP));
+ ASSERT_EQ(0, unshare(CLONE_NEWUSER));
+ ASSERT_EQ(0, map_current_ugid(0, 0));
+
+ EXPECT_TRUE(cap_dropped(CAP_NET_ADMIN));
+ EXPECT_TRUE(cap_raised(CAP_NET_RAW));
+
+ /* Lower a second cap and unshare a grandchild userns */
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_RAW, 0, 0));
+ ASSERT_EQ(0, drop_all_caps());
+ ASSERT_EQ(0, unshare(CLONE_NEWUSER));
+
+ /* Grandchild lacks both parent's dropped cap and newly lowered cap */
+ EXPECT_TRUE(cap_dropped(CAP_NET_ADMIN));
+ EXPECT_TRUE(cap_dropped(CAP_NET_RAW));
+ EXPECT_TRUE(cap_raised(CAP_SYS_ADMIN));
+}
+
+/*
+ * Verify setns() clamps both active capabilities and cap_userns to the target
+ * namespace's cap_bset, even when held in cap_permitted and cap_userns.
+ */
+TEST_F(userns_bset, setns_clamps_to_userns_bset)
+{
+ int trimmed_ns_fd;
+
+ trimmed_ns_fd = open_child_userns_without(CAP_NET_ADMIN);
+ ASSERT_GE(trimmed_ns_fd, 0);
+
+ ASSERT_EQ(0, drop_caps_except(CAP_NET_ADMIN));
+ ASSERT_EQ(1, prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET,
+ CAP_NET_ADMIN, 0, 0));
+ ASSERT_EQ(0, setns(trimmed_ns_fd, CLONE_NEWUSER));
+ close(trimmed_ns_fd);
+
+ EXPECT_TRUE(cap_dropped(CAP_NET_ADMIN));
+ EXPECT_TRUE(cap_raised(CAP_SYS_ADMIN));
+ EXPECT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET,
+ CAP_NET_ADMIN, 0, 0));
+}
+
+/*
+ * Verify setns() clamps capabilities to the caller's userns capability ceiling
+ * when entering a less-restricted child userns.
+ */
+TEST_F(userns_bset, setns_clamps_to_task_cap_userns)
+{
+ int full_ns_fd;
+
+ full_ns_fd = open_child_userns();
+ ASSERT_GE(full_ns_fd, 0);
+
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+ ASSERT_EQ(0, prctl(PR_SET_SECUREBITS, SECBIT_CAP_USERNS_STRICT,
+ 0, 0, 0));
+ ASSERT_TRUE(cap_raised(CAP_NET_ADMIN));
+
+ ASSERT_EQ(0, setns(full_ns_fd, CLONE_NEWUSER));
+ close(full_ns_fd);
+
+ EXPECT_TRUE(cap_dropped(CAP_NET_ADMIN));
+ EXPECT_TRUE(cap_raised(CAP_SYS_ADMIN));
+}
+
+/*
+ * Verify a child's ns->cap_bset does not restrict an ancestor holding the
+ * capability from acting on the child userns, while still clamping credentials
+ * upon entry.
+ */
+TEST_F(userns_bset, ancestor_capable_over_trimmed_child)
+{
+ int no_sys_admin_ns_fd;
+
+ no_sys_admin_ns_fd = open_child_userns_without(CAP_SYS_ADMIN);
+ ASSERT_GE(no_sys_admin_ns_fd, 0);
+
+ ASSERT_EQ(0, setns(no_sys_admin_ns_fd, CLONE_NEWUSER));
+ close(no_sys_admin_ns_fd);
+
+ EXPECT_TRUE(cap_dropped(CAP_SYS_ADMIN));
+ EXPECT_TRUE(cap_raised(CAP_NET_ADMIN));
+}
+
+/*
+ * Verify an unprivileged parent owner only holds implicit capabilities that
+ * are present in the owned namespace's cap_bset, even when the caller's own
+ * cap_userns is unrestricted.
+ */
+TEST_F(userns_bset, parent_owner_bounded_by_owned_bset)
+{
+ int full_ns_fd, no_sys_admin_ns_fd;
+
+ full_ns_fd = open_child_userns();
+ ASSERT_GE(full_ns_fd, 0);
+ no_sys_admin_ns_fd = open_child_userns_without(CAP_SYS_ADMIN);
+ ASSERT_GE(no_sys_admin_ns_fd, 0);
+
+ ASSERT_EQ(0, drop_all_caps());
+
+ /* Denied when the owned namespace's cap_bset lacks CAP_SYS_ADMIN */
+ EXPECT_EQ(-1, setns(no_sys_admin_ns_fd, CLONE_NEWUSER));
+ EXPECT_EQ(EPERM, errno);
+
+ /* Allowed when the owned namespace's cap_bset contains CAP_SYS_ADMIN */
+ EXPECT_EQ(0, setns(full_ns_fd, CLONE_NEWUSER));
+
+ close(no_sys_admin_ns_fd);
+ close(full_ns_fd);
+}
+
+/*
+ * Verify an unprivileged parent owner only holds implicit capabilities over a
+ * child userns when the child's cap_bset is a subset of the caller's userns
+ * capability ceiling.
+ */
+TEST_F(userns_bset, parent_owner_requires_bset_subset)
+{
+ int full_ns_fd, trimmed_ns_fd;
+
+ full_ns_fd = open_child_userns();
+ ASSERT_GE(full_ns_fd, 0);
+ trimmed_ns_fd = open_child_userns_without(CAP_NET_ADMIN);
+ ASSERT_GE(trimmed_ns_fd, 0);
+
+ ASSERT_EQ(0, drop_all_caps());
+ ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0));
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+
+ /* Denied: full_ns has CAP_NET_ADMIN outside caller's ceiling */
+ EXPECT_EQ(-1, setns(full_ns_fd, CLONE_NEWUSER));
+ EXPECT_EQ(EPERM, errno);
+
+ /* Allowed: trimmed_ns->cap_bset is a subset of caller's ceiling */
+ EXPECT_EQ(0, setns(trimmed_ns_fd, CLONE_NEWUSER));
+
+ close(trimmed_ns_fd);
+ close(full_ns_fd);
+}
+
+struct tracee {
+ pid_t pid;
+ int fd;
+};
+
+FIXTURE(userns_ptrace) {
+ struct tracee tracees[MAX_TRACEES];
+};
+
+FIXTURE_SETUP(userns_ptrace)
+{
+ uid_t uid = geteuid();
+ gid_t gid = getegid();
+ int i;
+
+ for (i = 0; i < MAX_TRACEES; i++) {
+ self->tracees[i].pid = -1;
+ self->tracees[i].fd = -1;
+ }
+
+ if (prctl(PR_CAP_USERNS, PR_CAP_USERNS_IS_SET, 0, 0, 0) < 0 &&
+ errno == EINVAL)
+ SKIP(return, "PR_CAP_USERNS not supported");
+
+ if (unshare(CLONE_NEWUSER) != 0)
+ SKIP(return, "unshare(CLONE_NEWUSER) failed");
+
+ ASSERT_EQ(0, map_current_ugid(uid, gid));
+}
+
+FIXTURE_TEARDOWN(userns_ptrace)
+{
+ int i;
+
+ for (i = 0; i < MAX_TRACEES; i++) {
+ if (self->tracees[i].fd >= 0)
+ close(self->tracees[i].fd);
+ if (self->tracees[i].pid > 0) {
+ kill(self->tracees[i].pid, SIGKILL);
+ waitpid(self->tracees[i].pid, NULL, 0);
+ }
+ }
+}
+
+/*
+ * Spawn a child initialized with @setup() that blocks until FIXTURE_TEARDOWN.
+ */
+static pid_t start_tracee(struct tracee *tracees, int (*setup)(void))
+{
+ int slot = -1, sv[2];
+ char ch = 0;
+ pid_t pid;
+ int i;
+
+ for (i = 0; i < MAX_TRACEES; i++) {
+ if (tracees[i].pid < 0) {
+ slot = i;
+ break;
+ }
+ }
+ if (slot < 0)
+ return -1;
+
+ if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) != 0)
+ return -1;
+
+ pid = fork();
+ if (pid < 0) {
+ close(sv[0]);
+ close(sv[1]);
+ return -1;
+ }
+
+ if (pid == 0) {
+ close(sv[0]);
+ if (setup && setup() != 0)
+ _exit(1);
+ if (write(sv[1], &ch, 1) != 1)
+ _exit(1);
+ while (read(sv[1], &ch, 1) < 0 && errno == EINTR)
+ ;
+ close(sv[1]);
+ _exit(0);
+ }
+
+ close(sv[1]);
+ if (read(sv[0], &ch, 1) != 1) {
+ close(sv[0]);
+ kill(pid, SIGKILL);
+ waitpid(pid, NULL, 0);
+ return -1;
+ }
+
+ tracees[slot].pid = pid;
+ tracees[slot].fd = sv[0];
+ return pid;
+}
+
+static int try_ptrace_attach(pid_t pid)
+{
+ int err, status;
+ pid_t ret;
+
+ if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) != 0)
+ return -errno;
+ do {
+ ret = waitpid(pid, &status, 0);
+ } while (ret < 0 && errno == EINTR);
+ if (ret != pid) {
+ err = -errno;
+ ptrace(PTRACE_DETACH, pid, NULL, NULL);
+ return err;
+ }
+ if (ptrace(PTRACE_DETACH, pid, NULL, NULL) != 0)
+ return -errno;
+ return 0;
+}
+
+/* Unprivileged task in caller's userns with a full userns ceiling. */
+static int tracee_same_ns_full(void)
+{
+ return drop_all_caps();
+}
+
+/* Unprivileged task in caller's userns with CAP_NET_ADMIN lowered. */
+static int tracee_same_ns_no_net_admin(void)
+{
+ if (prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER, CAP_NET_ADMIN, 0, 0) != 0)
+ return -1;
+ return drop_all_caps();
+}
+
+/* Task with full capabilities inside an untrimmed child userns. */
+static int tracee_child_ns_full(void)
+{
+ return unshare(CLONE_NEWUSER);
+}
+
+/* Task inside a trimmed child userns lacking CAP_NET_ADMIN. */
+static int tracee_child_ns_no_net_admin(void)
+{
+ if (prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER, CAP_NET_ADMIN, 0, 0) != 0)
+ return -1;
+ if (drop_all_caps() != 0)
+ return -1;
+ return unshare(CLONE_NEWUSER);
+}
+
+/*
+ * Unprivileged task in an untrimmed child userns with CAP_NET_ADMIN dropped
+ * from task caps.
+ */
+static int tracee_child_ns_dropped_caps(void)
+{
+ if (unshare(CLONE_NEWUSER) != 0)
+ return -1;
+ if (prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER, CAP_NET_ADMIN, 0, 0) != 0)
+ return -1;
+ if (prctl(PR_CAPBSET_DROP, CAP_NET_ADMIN, 0, 0, 0) != 0)
+ return -1;
+ return drop_all_caps();
+}
+
+/*
+ * Unprivileged task in an empty grandchild userns under an untrimmed child
+ * userns.
+ */
+static int tracee_grandchild_ns_empty(void)
+{
+ if (unshare(CLONE_NEWUSER) != 0)
+ return -1;
+ if (map_current_ugid(0, 0) != 0)
+ return -1;
+ if (prctl(PR_CAP_USERNS, PR_CAP_USERNS_CLEAR_ALL, 0, 0, 0) != 0)
+ return -1;
+ if (drop_all_caps() != 0)
+ return -1;
+ return unshare(CLONE_NEWUSER);
+}
+
+/*
+ * Unprivileged tracer in the same userns cannot PTRACE_ATTACH a peer with a
+ * wider userns capability ceiling, while attaching to an equally restricted
+ * peer succeeds.
+ */
+TEST_F(userns_ptrace, same_ns_ceiling)
+{
+ pid_t full, trimmed;
+
+ full = start_tracee(self->tracees, tracee_same_ns_full);
+ ASSERT_GT(full, 0);
+ trimmed = start_tracee(self->tracees, tracee_same_ns_no_net_admin);
+ ASSERT_GT(trimmed, 0);
+
+ ASSERT_EQ(0, drop_all_caps());
+ ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0));
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+
+ EXPECT_EQ(-EPERM, try_ptrace_attach(full));
+ EXPECT_EQ(0, try_ptrace_attach(trimmed));
+}
+
+/*
+ * Implicit CAP_SYS_PTRACE from owning a child userns does not allow a
+ * restricted parent task to attach to a less restricted child userns.
+ */
+TEST_F(userns_ptrace, owned_child_ns_ceiling)
+{
+ pid_t full, trimmed;
+
+ full = start_tracee(self->tracees, tracee_child_ns_full);
+ ASSERT_GT(full, 0);
+ trimmed = start_tracee(self->tracees, tracee_child_ns_no_net_admin);
+ ASSERT_GT(trimmed, 0);
+
+ ASSERT_EQ(0, drop_all_caps());
+ ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0));
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+
+ EXPECT_EQ(-EPERM, try_ptrace_attach(full));
+ EXPECT_EQ(0, try_ptrace_attach(trimmed));
+}
+
+/*
+ * A tracer holding CAP_SYS_PTRACE in its own credentials can still attach to
+ * less restricted tasks in both its own userns and descendant user namespaces.
+ */
+TEST_F(userns_ptrace, explicit_cap_sys_ptrace)
+{
+ pid_t same, child;
+
+ same = start_tracee(self->tracees, tracee_same_ns_full);
+ ASSERT_GT(same, 0);
+ child = start_tracee(self->tracees, tracee_child_ns_full);
+ ASSERT_GT(child, 0);
+
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+ ASSERT_EQ(0, prctl(PR_SET_SECUREBITS, SECBIT_CAP_USERNS_STRICT,
+ 0, 0, 0));
+ ASSERT_EQ(0, drop_caps_except(CAP_SYS_PTRACE));
+
+ EXPECT_EQ(0, try_ptrace_attach(same));
+ EXPECT_EQ(0, try_ptrace_attach(child));
+}
+
+/*
+ * PTRACE_MODE_READ_FSCREDS (gating /proc/<pid>/ns/user and /proc/<pid>/fd/)
+ * is likewise bounded by the caller's userns capability ceiling, preventing
+ * a restricted task from stealing open fds or setns()-joining a populated
+ * untrimmed child userns to gain intra-namespace CAP_SYS_PTRACE over tasks
+ * inside it.
+ */
+TEST_F(userns_ptrace, read_mode_ceiling)
+{
+ pid_t full, trimmed;
+ char path[64];
+ int fd;
+
+ full = start_tracee(self->tracees, tracee_child_ns_full);
+ ASSERT_GT(full, 0);
+ trimmed = start_tracee(self->tracees, tracee_child_ns_no_net_admin);
+ ASSERT_GT(trimmed, 0);
+
+ ASSERT_EQ(0, drop_all_caps());
+ ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0));
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+
+ snprintf(path, sizeof(path), "/proc/%d/ns/user", full);
+ EXPECT_EQ(-1, open(path, O_RDONLY | O_CLOEXEC));
+ EXPECT_EQ(EACCES, errno);
+
+ snprintf(path, sizeof(path), "/proc/%d/ns/user", trimmed);
+ fd = open(path, O_RDONLY | O_CLOEXEC);
+ EXPECT_GE(fd, 0);
+ if (fd >= 0)
+ close(fd);
+}
+
+/*
+ * Verify PTRACE_TRACEME fails when the parent tracer has a narrower userns
+ * capability ceiling than the child, and succeeds once the child matches it.
+ */
+TEST_F(userns_ptrace, traceme_ceiling)
+{
+ int sync_pipe[2];
+ int status;
+ char ch = 0;
+ pid_t child;
+
+ ASSERT_EQ(0, drop_all_caps());
+ ASSERT_EQ(0, pipe(sync_pipe));
+
+ child = fork();
+ ASSERT_GE(child, 0);
+
+ if (child == 0) {
+ close(sync_pipe[1]);
+ if (read(sync_pipe[0], &ch, 1) != 1)
+ _exit(1);
+ close(sync_pipe[0]);
+
+ /* Parent lowered CAP_NET_ADMIN; child still has full mask */
+ if (ptrace(PTRACE_TRACEME, 0, NULL, NULL) != -1 ||
+ errno != EPERM)
+ _exit(2);
+
+ /* Matching parent's ceiling allows PTRACE_TRACEME */
+ if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0)
+ _exit(3);
+ if (prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0) != 0)
+ _exit(4);
+
+ if (ptrace(PTRACE_TRACEME, 0, NULL, NULL) != 0)
+ _exit(5);
+
+ _exit(0);
+ }
+
+ close(sync_pipe[0]);
+ ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0));
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+
+ ASSERT_EQ(1, write(sync_pipe[1], &ch, 1));
+ close(sync_pipe[1]);
+
+ ASSERT_EQ(child, waitpid(child, &status, 0));
+ ASSERT_TRUE(WIFEXITED(status));
+ EXPECT_EQ(0, WEXITSTATUS(status));
+}
+
+/*
+ * Verify a restricted parent owner cannot attach to a task in an untrimmed
+ * child userns even after that task drops the restricted capability from all
+ * of its own capability sets, since the child namespace itself remains less
+ * restricted than the tracer.
+ */
+TEST_F(userns_ptrace, owned_child_ns_dropped_task_caps)
+{
+ pid_t child;
+
+ child = start_tracee(self->tracees, tracee_child_ns_dropped_caps);
+ ASSERT_GT(child, 0);
+
+ ASSERT_EQ(0, drop_all_caps());
+ ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0));
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+
+ EXPECT_EQ(-EPERM, try_ptrace_attach(child));
+}
+
+/*
+ * Verify narrowing the userns capability ceiling preserves dumpability and the
+ * parent-death signal, while widening it resets both.
+ */
+TEST_F(userns_ptrace, ceiling_widening_resets_dumpable)
+{
+ int suid_dumpable = 0;
+ int pdeath_sig = 0;
+ FILE *f;
+
+ f = fopen("/proc/sys/fs/suid_dumpable", "r");
+ if (f) {
+ if (fscanf(f, "%d", &suid_dumpable) != 1)
+ suid_dumpable = 0;
+ fclose(f);
+ }
+
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_ADMIN, 0, 0));
+ ASSERT_EQ(0, prctl(PR_SET_SECUREBITS, SECBIT_CAP_USERNS_STRICT,
+ 0, 0, 0));
+
+ ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 1, 0, 0, 0));
+ ASSERT_EQ(0, prctl(PR_SET_PDEATHSIG, SIGUSR1, 0, 0, 0));
+
+ /* Narrowing the ceiling preserves dumpable and parent-death signal */
+ ASSERT_EQ(0, prctl(PR_CAP_USERNS, PR_CAP_USERNS_LOWER,
+ CAP_NET_RAW, 0, 0));
+ EXPECT_EQ(1, prctl(PR_GET_DUMPABLE, 0, 0, 0, 0));
+ ASSERT_EQ(0, prctl(PR_GET_PDEATHSIG, &pdeath_sig, 0, 0, 0));
+ EXPECT_EQ(SIGUSR1, pdeath_sig);
+
+ /*
+ * Clearing SECBIT_CAP_USERNS_STRICT widens the effective ceiling via
+ * cap_permitted, resetting both.
+ */
+ ASSERT_EQ(0, prctl(PR_SET_SECUREBITS, 0, 0, 0, 0));
+ EXPECT_EQ(suid_dumpable, prctl(PR_GET_DUMPABLE, 0, 0, 0, 0));
+ ASSERT_EQ(0, prctl(PR_GET_PDEATHSIG, &pdeath_sig, 0, 0, 0));
+ EXPECT_EQ(0, pdeath_sig);
+}
+
+/*
+ * Verify an unprivileged owner of an untrimmed child userns retains implicit
+ * capabilities (ptrace and setns) over a grandchild userns with an empty
+ * cap_bset, while setns() still clamps capabilities to the grandchild's
+ * cap_bset upon entry.
+ */
+TEST_F(userns_ptrace, owned_child_ns_trimmed_grandchild)
+{
+ char path[64];
+ pid_t child;
+ int ns_fd;
+
+ child = start_tracee(self->tracees, tracee_grandchild_ns_empty);
+ ASSERT_GT(child, 0);
+
+ ASSERT_EQ(0, drop_all_caps());
+ EXPECT_EQ(0, try_ptrace_attach(child));
+
+ snprintf(path, sizeof(path), "/proc/%d/ns/user", child);
+ ns_fd = open(path, O_RDONLY | O_CLOEXEC);
+ ASSERT_GE(ns_fd, 0);
+
+ ASSERT_EQ(0, setns(ns_fd, CLONE_NEWUSER));
+ close(ns_fd);
+
+ EXPECT_TRUE(cap_dropped(CAP_SYS_ADMIN));
+ EXPECT_TRUE(cap_dropped(CAP_NET_ADMIN));
+}
+
+TEST_HARNESS_MAIN
--
2.56.1.708.g77570a6a1d-goog
^ permalink raw reply related [flat|nested] 5+ messages in thread