Landlock: Namespace and capability control
Subsystems (5)
Mickaël Salaün
maintainerv2 cover Landlock: Namespace and capability control
Namespaces are a fundamental building block for containers and application sandboxes, but user namespace creation significantly widens the kernel attack surface. CVE-2026-43284 / CVE-2026-43500 ("Dirty Frag"), CVE-2026-46300 ("Fragnesia"), CVE-2023-32233 and CVE-2022-25636 (netfilter), CVE-2022-0492 (cgroup v1 release_agent), and CVE-2022-0185 (filesystem mount parsing) all demonstrate vulnerabilities exploitable only through capabilities gained via user namespaces. Advisories for the 2026 CVEs recommend disabling unprivileged user-namespace creation as a temporary mitigation. Some distributions (e.g. Debian and Arch's linux-hardened kernel via the kernel.unprivileged_userns_clone sysctl) block user namespace creation entirely, but this removes a useful isolation primitive. Fine-grained control allows trusted programs to use namespaces while preventing unnecessary exposure for programs that do not need them.
Existing mechanisms (user.max_*_namespaces sysctls, userns_create LSM hook, PR_SET_NO_NEW_PRIVS, and capset) each address part of this threat but none provides per-process, fine-grained control over both namespace types and capabilities. Container runtimes resort to seccomp-based clone/unshare filtering, but seccomp cannot dereference clone3's flag structure, forcing runtimes to block clone3 entirely.
Landlock's composable layer model enables several patterns: a user session manager can restrict namespace types and capabilities broadly while allowing trusted programs to create the namespaces they need, and each deeper layer can further restrict the allowed set. Container runtimes can similarly deny namespace creation inside managed containers.
Two permissions are needed because the controlled operations sit on different LSM hook sites (namespace_init/namespace_install vs capable) and address independent threat axes: capability acquisition via user-namespace creation, and capability exercise after acquisition. Collapsing them into a single permission would conflate hook semantics. LANDLOCK_PERM_NAMESPACE_USE intentionally covers every kernel path that grants access to a namespace (creation, entry, and fd reference) because each path widens the kernel attack surface for that namespace type; splitting it into finer create/enter/fd-reference permissions would add UAPI surface without isolating a distinct attack axis.
This series adds two new permission categories to Landlock:
- LANDLOCK_PERM_NAMESPACE_USE: Restricts which namespace types a sandboxed process can use: creation (unshare/clone), entry (setns), and fd reference (open_tree, fsmount). User namespace creation has no capability check in the kernel, so this is the only enforcement mechanism for that path.
- LANDLOCK_PERM_CAPABILITY_USE: Restricts which Linux capabilities a sandboxed process can use, regardless of how they were obtained (including through user namespace creation).
Both use new handled_perm and LANDLOCK_RULE_* constants following the existing allow-list model. The UAPI uses raw CAP_* and CLONE_NEW* values directly; unknown values are silently accepted for forward compatibility (the allow-list denies them by default). This series is planned to merge in the same kernel version as the UDP series, which already bumped the Landlock ABI to 10; no second bump is needed.
The handled_perm infrastructure is designed to be reusable by future permission categories. The last patch documents the design rationale for the permission model and the criteria for choosing between handled_access_*, handled_perm, and scoped. A patch series to add socket creation control is under review [2]; it could benefit from the same permission model to achieve complete deny-by-default coverage of socket creation.
This series builds on Christian Brauner's namespace LSM blob RFC [1], included as patch 1. The FOR_EACH_NS_TYPE patch from v1 has been merged in master: commit 935a04923ad2 ("nsproxy: Add FOR_EACH_NS_TYPE() X-macro and CLONE_NS_ALL").
Paul, could you please review patch 1 and 2? The first adds the new LSM hooks and the second adds LSM_AUDIT_DATA_NS, a new audit record type that logs namespace_type and ns_id for namespace-related LSM denials.
All of these example vulnerabilities follow the same pattern: an unprivileged user creates a user namespace to obtain capabilities, then creates a second namespace to exercise them against vulnerable code. LANDLOCK_PERM_NAMESPACE_USE prevents this by denying the user namespace (eliminating the capability grant) or the specific namespace type needed to exercise it. LANDLOCK_PERM_CAPABILITY_USE independently prevents it by denying the required capability.
Namespace restriction is enforced at two hook sites: namespace_init (unshare/clone) and namespace_install (setns). Together, these ensure a process denied a namespace type cannot circumvent the restriction by entering a pre-existing namespace via setns() on an inherited or passed file descriptor. When a domain handles both permissions, both must independently allow the operation (e.g., unshare(CLONE_NEWNET) requires both CAP_SYS_ADMIN to be allowed and CLONE_NEWNET to be allowed).
Design evolution:
The first approach added CAP_OPT flags to security_capable() to distinguish namespace creation contexts. This was too invasive and would have required capability splitting (a dedicated CAP_NAMESPACE) which does not help because the CAP_SYS_ADMIN fallback for backward compatibility undermines the distinction.
The second stored the namespace creator's domain in the LSM blob and used domain ancestry comparison in hook_capable() to bypass capability checks for namespace management operations. A SCOPE_NAMESPACE flag restricted setns() by the namespace creator's domain, like SCOPE_SIGNAL. Both were dropped: scopes should only concern Landlock properties (domain relationships), not kernel namespace state; and the cross-namespace heuristic (ns != cred->user_ns) did not accurately identify namespace management operations.
The final design drops all of this. The key insight is that capabilities gained through user namespace creation are only exercisable against namespaces of a specific type: creating a network namespace is what makes CAP_NET_ADMIN exercisable. LANDLOCK_PERM_NAMESPACE_USE controls where capabilities are exercisable by restricting which namespace types can be acquired. LANDLOCK_PERM_CAPABILITY_USE controls which capabilities are available, as a pure per-layer bitmask check with no namespace awareness. The two are independently enforced at their own hook sites, with no interaction in hook_capable(). No scope flag is added in this series.
When Landlock filesystem restrictions are in use, mount namespace creation has an inherent limitation: all mount topology changes are denied when any filesystem right is handled. A dedicated mount access control type is left for future work [3].
Per Paul Moore's review, no security_namespace_switch() post-hook is added in this series: such a hook would only serve LSMs that maintain per-task state derived from the active namespace set (SELinux-style state tracking), and no current LSM (including this series) needs that. Landlock enforces at namespace_install() and namespace_init(), before the task-to-nsproxy switch. The hook is left for a separate LSM infrastructure proposal once a concrete user emerges.
https://lore.kernel.org/r/[email protected] [1]
https://lore.kernel.org/r/[email protected] [2]
https://github.com/landlock-lsm/linux/issues/14 [3]
Changes since RFC v1:
https://lore.kernel.org/r/[email protected]
- Move security_namespace_install() before ns->ops->install() in validate_ns() and fix proc_free_inum() error path when inum is caller-provided (patch 1, suggested by Christian Brauner).
- Replace inum with ns_id in namespace audit records: ns_id is the stable 64-bit namespace identifier, never recycled (patches 2, 4, 6, 9; suggested by Christian Brauner).
- Fix user_denied.setns test to expect EPERM from Landlock instead of EINVAL from userns_install() after hook reordering (patch 6).
- Add __packed __aligned(sizeof(u64)) to struct perm_masks to fix m68k build failure where GCC packs bitfields at byte granularity, and add WARN_ON_ONCE guards for invalid perm_bit or request_value in landlock_perm_is_denied() (patch 4, suggested by Tingmao Wang).
- Fix anonymous mount namespace blob leak: make __ns_common_free() always call security_namespace_free() and conditionally call proc_free_inum() via MNT_NS_INO_SPECIAL_MAX, so free_mnt_ns() calls ns_common_free() unconditionally (patch 1, suggested by Christian Brauner, also reported by Daniel Durning).
- Unify hook_namespace_init() and hook_namespace_install() into a shared check_ns_type() helper and drop the redundant entry-level WARN_ON_ONCE (the downstream warns in landlock_ns_type_to_bit() and landlock_perm_is_denied() suffice; patch 4).
- Remove duplicate ns_audit.unshare_denied test (identical to ns_audit.create_denied; patch 6).
- Add sandboxed_allowed variant to setns_cross_process to cover allowed cross-process setns (patch 6).
- Rebase onto landlock-next (includes the resolve_unix and UDP series). No ABI bump in v2: the series is planned to merge in the same kernel as the UDP series, which already bumped to 10.
- Drop three patches now upstream on landlock-next: the two audit-test fixes (filter dealloc records, default audit socket timeout) sent independently with Cc: stable, plus the allowed_access best-effort filtering demonstration patch.
- Rename LANDLOCK_PERM_NAMESPACE_ENTER to LANDLOCK_PERM_NAMESPACE_USE (and audit blocker perm.namespace_enter to perm.namespace_use) for semantic accuracy: the verb _ENTER fits setns/unshare/clone but misleads for open_tree and fsmount where the caller holds an fd reference without entering. _USE covers both cases and mirrors LANDLOCK_PERM_CAPABILITY_USE.
- Add a Design philosophy section to Documentation/security/landlock.rst stating Landlock's principle:
restrict access to data, other tasks, and kernel resources.
- Rewrite Documentation/security/landlock.rst Ruleset restriction models with the per-object (handled_access_*) versus per-category (handled_perm) framing in place of the previous chokepoints/ gateways wording.
- Enumerate the seven syscall paths covered by LANDLOCK_PERM_NAMESPACE_USE in Documentation/userspace-api/landlock.rst (membership via unshare/clone/setns; fd reference via open_tree and fsmount).
- Document the deterministic-semantics rationale for accepting unknown category member values in rule bodies (per-category permissions section of Documentation/security/landlock.rst); range-checking against CAP_LAST_CAP is intentionally avoided.
- Address Günther Noack's nits in the layer_config wrapper patch:
clarify that _LANDLOCK_ACCESS_FS_INITIALLY_DENIED is ORed with the .handled field of all ruleset->layers[] entries; rename landlock_upgrade_handled_access_masks() to landlock_upgrade_handled_layer_config() to match the parameter type; rewrap the @layers kdoc to greedy fill (eliminating v1's manual short "rulesets in a" line).
- Rename struct layer_rights to struct layer_config: "config" is the more general term for per-layer state.
- Rename internal struct perm_rules to struct perm_masks to parallel the sibling access_masks in struct layer_config.
- Collect Reviewed-by tags from Günther Noack on patches 2, 3, 4, and 5 from the v1 thread. Patch 1 and patch 8 changed substantially since v1 (the mount-namespace blob leak fix and validate_ns() reordering for patch 1; the libcap migration for patch 8), so the Reviewed-by tags from reviewers who had not requested those changes are not carried forward; the affected reviewers are kept as Cc:.
- Rename security_namespace_alloc() to security_namespace_init() (and the LSM hook namespace_alloc -> namespace_init, plus Landlock's hook_namespace_alloc() -> hook_namespace_init()) to match the caller-name convention and reflect that the hook initialises LSM state attached to a constructed ns_common rather than allocating it (patch 1, suggested by Paul Moore).
- Refine the security_namespace_free() kdoc to clarify that RCU-safe blob freeing is required only if an LSM exposes data within the blob to concurrent RCU readers, and document that the blob memory itself is released with kfree() after the namespace_free hooks return (patch 1, suggested by Paul Moore).
- Use cap_from_name(3) from libcap in the sandboxer; LL_CAP now takes colon-delimited capability names (e.g. "cap_sys_chroot") or numbers (libcap's numeric fallback), and the Makefile links libcap (patch 8, suggested by Günther Noack).
- Rename the sandboxer env var LL_CAPS to LL_CAP for consistency with the singular form used by all other LL_* sandboxer env vars (LL_NS, LL_FS_RO, LL_FS_RW, LL_TCP_BIND, LL_TCP_CONNECT, LL_SCOPED, LL_FORCE_LOG; patch 8).
- Add a bridging sentence in the per-category permissions section of Documentation/security/landlock.rst contrasting per-category permissions with per-object access rights (patch 9, suggested by Günther Noack).
- Disambiguate the orthogonality invariant in Documentation/security/landlock.rst ("all new scoped features" -> "all Landlock access controls") to avoid clash with the UAPI scoped field (patch 9, suggested by Justin Suess).
- Add an introductory paragraph in Documentation/userspace-api/landlock.rst contrasting LANDLOCK_PERM_CAPABILITY_USE with PR_SET_NO_NEW_PRIVS (patch 9, suggested by Justin Suess).
- Add an explicit static_assert that LANDLOCK_NUM_PERM_CAP + LANDLOCK_NUM_PERM_NS fits in u64, complementing the implicit sizeof guard on struct perm_masks (patch 5).
- Document that setns_cross_process exercises only CLONE_NEWUTS (patch 6).
- Add add_rule_unknown_no_runtime_effect tests asserting that a rule listing only unknown bits has no runtime effect (patches 6, 7).
- Extend the cap/ns stacking tests with the parent-denies/child- allows variant to complete per-layer walker direction coverage (patches 6, 7).
Christian Brauner (1):
security: add LSM blob and hooks for namespaces
Mickaël Salaün (8):
security: Add LSM_AUDIT_DATA_NS for namespace audit records
landlock: Wrap per-layer access masks in struct layer_config
landlock: Enforce namespace use restrictions
landlock: Enforce capability restrictions selftests/landlock: Add namespace restriction tests selftests/landlock: Add capability restriction tests samples/landlock: Add capability and namespace restriction support
landlock: Add documentation for capability and namespace restrictions
Documentation/admin-guide/LSM/landlock.rst | 19 +- Documentation/security/landlock.rst | 151 +- Documentation/userspace-api/landlock.rst | 216 ++- fs/namespace.c | 3 +- include/linux/lsm_audit.h | 5 + include/linux/lsm_hook_defs.h | 3 + include/linux/lsm_hooks.h | 1 + include/linux/ns/ns_common_types.h | 3 + include/linux/security.h | 20 + include/uapi/linux/landlock.h | 97 +- include/uapi/linux/nsfs.h | 1 + kernel/nscommon.c | 17 +- kernel/nsproxy.c | 6 + samples/landlock/Makefile | 1 + samples/landlock/sandboxer.c | 144 +- security/landlock/Makefile | 4 +- security/landlock/access.h | 77 +- security/landlock/audit.c | 8 + security/landlock/audit.h | 2 + security/landlock/cap.c | 141 ++ security/landlock/cap.h | 49 + security/landlock/cred.h | 54 +- security/landlock/limits.h | 9 + security/landlock/ns.c | 156 ++ security/landlock/ns.h | 73 + security/landlock/ruleset.c | 27 +- security/landlock/ruleset.h | 62 +- security/landlock/setup.c | 4 + security/landlock/syscalls.c | 122 +- security/lsm_audit.c | 4 + security/lsm_init.c | 2 + security/security.c | 77 + tools/testing/selftests/landlock/base_test.c | 18 + tools/testing/selftests/landlock/cap_test.c | 673 +++++++ tools/testing/selftests/landlock/common.h | 23 + tools/testing/selftests/landlock/config | 5 + tools/testing/selftests/landlock/fs_test.c | 13 +- tools/testing/selftests/landlock/ns_test.c | 1795 ++++++++++++++++++ tools/testing/selftests/landlock/wrappers.h | 29 + 39 files changed, 4028 insertions(+), 86 deletions(-) create mode 100644 security/landlock/cap.c create mode 100644 security/landlock/cap.h create mode 100644 security/landlock/ns.c create mode 100644 security/landlock/ns.h create mode 100644 tools/testing/selftests/landlock/cap_test.c create mode 100644 tools/testing/selftests/landlock/ns_test.c
Signature · 1 line
2.54.0
Mickaël Salaün
maintainerPATCH v2 1/9 security: add LSM blob and hooks for namespaces
From: Christian Brauner <[email protected]>
All namespace types now share the same ns_common infrastructure. Extend this to include a security blob so LSMs can start managing namespaces uniformly without having to add one-off hooks or security fields to every individual namespace type.
Add a ns_security pointer to ns_common and the corresponding lbs_ns blob size to lsm_blob_sizes. Allocation and freeing hooks are called from the common __ns_common_init() and __ns_common_free() paths so every namespace type gets covered in one go. All information about the namespace type and the appropriate casting helpers to get at the containing namespace are available via ns_common making it straightforward for LSMs to differentiate when they need to.
A namespace_install hook is called from validate_ns() during setns(2) giving LSMs a chance to enforce policy on namespace transitions. The LSM check runs before ns->ops->install() so the security module can deny the operation before any type-specific installation effects.
Individual namespace types can still have their own specialized security hooks when needed. This is just the common baseline that makes it easy to track and manage namespaces from the security side without requiring every namespace type to reinvent the wheel.
---
Changes since v1:
https://lore.kernel.org/r/[email protected]
- Move security_namespace_install() before ns->ops->install() in validate_ns() (suggested by Christian Brauner).
- Only call proc_free_inum() on security_namespace_alloc() failure when inum was allocated by this function (suggested by Christian Brauner).
- Fix anonymous mount namespace blob leak: move security_namespace_free() into __ns_common_free() and make proc_free_inum() conditional on dynamically allocated inums via MNT_NS_INO_SPECIAL_MAX, so free_mnt_ns() can call ns_common_free() unconditionally (suggested by Christian Brauner). Also reported by Daniel Durning while working on SELinux support for these hooks:
https://lore.kernel.org/r/[email protected]
- Rename security_namespace_alloc() to security_namespace_init() to match the caller-name convention and reflect that the hook initialises LSM state attached to a constructed ns_common rather than allocating the ns_common itself (suggested by Paul Moore).
- Refine the security_namespace_free() kdoc to clarify that RCU-safe blob freeing is required only if an LSM exposes data within the blob to concurrent RCU readers, and document that the blob memory itself is released with kfree() after the namespace_free hooks return (suggested by Paul Moore).
- Günther Noack's v1 Reviewed-by is not carried forward to v2:
the validate_ns() reordering and the anonymous-mount-namespace blob-leak fix are semantic changes that were not part of his review. Cc'd instead.
--- fs/namespace.c | 3 +- include/linux/lsm_hook_defs.h | 3 ++ include/linux/lsm_hooks.h | 1 + include/linux/ns/ns_common_types.h | 3 ++ include/linux/security.h | 20 ++++++++ include/uapi/linux/nsfs.h | 1 + kernel/nscommon.c | 17 ++++++- kernel/nsproxy.c | 6 +++ security/lsm_init.c | 2 + security/security.c | 77 ++++++++++++++++++++++++++++++ 10 files changed, 130 insertions(+), 3 deletions(-)
fs/namespace.c +1 -2
@@ -4179,8 +4179,7 @@ static void dec_mnt_namespaces(struct ucounts *ucounts)static void free_mnt_ns (struct mnt_namespace *ns) { -if (!is_anon_ns (ns)) -ns_common_free (ns); +ns_common_free (ns);dec_mnt_namespaces (ns->ucounts);mnt_ns_tree_remove (ns); }
include/linux/lsm_hook_defs.h +3 -0
@@ -265,6 +265,9 @@ LSM_HOOK(int, -ENOSYS, task_prctl, int option, unsigned long arg2, LSM_HOOK(void, LSM_RET_VOID, task_to_inode, struct task_struct *p, struct inode *inode) LSM_HOOK(int, 0, userns_create, const struct cred *cred) +LSM_HOOK(int, 0, namespace_init, struct ns_common *ns) +LSM_HOOK(void, LSM_RET_VOID, namespace_free, struct ns_common *ns) +LSM_HOOK(int, 0, namespace_install, const struct nsset *nsset, struct ns_common *ns) LSM_HOOK(int, 0, ipc_permission, struct kern_ipc_perm *ipcp, short flag) LSM_HOOK(void, LSM_RET_VOID, ipc_getlsmprop, struct kern_ipc_perm *ipcp, struct lsm_prop *prop)
include/linux/lsm_hooks.h +1 -0
@@ -112,6 +112,7 @@ struct lsm_blob_sizes {unsigned int lbs_ipc;unsigned int lbs_key;unsigned int lbs_msg_msg; +unsigned int lbs_ns;unsigned int lbs_perf_event;unsigned int lbs_task;unsigned int lbs_xattr_count;/* num xattr slots in new_xattrs array */
include/linux/ns/ns_common_types.h +3 -0
@@ -116,6 +116,9 @@ struct ns_common {struct dentry *stashed;const struct proc_ns_operations *ops;unsigned int inum; +#ifdef CONFIG_SECURITY +void *ns_security; +#endif union {struct ns_tree ;struct rcu_head ns_rcu;
include/linux/security.h +20 -0
@@ -67,6 +67,7 @@ enum fs_value_type;struct watch ;struct watch_notification ;struct lsm_ctx ; +struct nsset ;/* Default (no) options for the capable function */ #define CAP_OPT_NONE 0x0
@@ -80,6 +81,7 @@ struct lsm_ctx;struct ctl_table ;struct audit_krule ; +struct ns_common ;struct user_namespace ;struct timezone ;
@@ -540,6 +542,9 @@ int security_task_prctl(int option, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5);void security_task_to_inode (struct task_struct *p,struct inode *inode);int security_create_user_ns (const struct cred *cred); +int security_namespace_init (struct ns_common *ns); +void security_namespace_free (struct ns_common *ns); +int security_namespace_install (const struct nsset *nsset,struct ns_common *ns);int security_ipc_permission (struct kern_ipc_perm *ipcp,short flag);void security_ipc_getlsmprop (struct kern_ipc_perm *ipcp,struct lsm_prop *prop);int security_msg_msg_alloc (struct msg_msg *msg);
@@ -1430,6 +1435,21 @@ static inline int security_create_user_ns(const struct cred *cred)return 0 ; } +static inline int security_namespace_init (struct ns_common *ns) +{ +return 0 ; +} + +static inline void security_namespace_free (struct ns_common *ns) +{ +} + +static inline int security_namespace_install (const struct nsset *nsset, +struct ns_common *ns) +{ +return 0 ; +} +static inline int security_ipc_permission (struct kern_ipc_perm *ipcp,short flag) {
include/uapi/linux/nsfs.h +1 -0
@@ -55,6 +55,7 @@ enum init_ns_ino { MNT_NS_INIT_INO = 0xEFFFFFF8U,#ifdef __KERNEL__MNT_NS_ANON_INO =0xEFFFFFF7U , + MNT_NS_INO_SPECIAL_MAX = MNT_NS_ANON_INO, #endif };
kernel/nscommon.c +16 -1
@@ -4,6 +4,7 @@#include <linux/ns_common.h> #include <linux/nstree.h> #include <linux/proc_ns.h> +#include <linux/security.h> #include <linux/user_namespace.h> #include <linux/vfsdebug.h>
@@ -59,6 +60,9 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_operefcount_set (&ns->__ns_ref,1 ); ns->stashed =NULL ; +#ifdef CONFIG_SECURITY + ns->ns_security =NULL ; +#endif ns->ops = ops; ns->ns_id =0 ; ns->ns_type = ns_type;
@@ -77,6 +81,14 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope ret =proc_alloc_inum (&ns->inum);if (ret)return ret; + + ret =security_namespace_init (ns); +if (ret) { +if (!inum) +proc_free_inum (ns->inum); +return ret; + } +/* * Tree ref starts at 0. It's incremented when namespace enters * active use (installed in nsproxy) and decremented when all
@@ -91,7 +103,10 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_opevoid __ns_common_free (struct ns_common *ns) { -proc_free_inum (ns->inum); +security_namespace_free (ns); + +if (ns->inum >MNT_NS_INO_SPECIAL_MAX ) +proc_free_inum (ns->inum); }struct ns_common *__must_check ns_owner (struct ns_common *ns)
kernel/nsproxy.c +6 -0
@@ -385,6 +385,12 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)static inline int validate_ns (struct nsset *nsset,struct ns_common *ns) { +int ret; + + ret =security_namespace_install (nsset, ns); +if (ret) +return ret; +return ns->ops->install (nsset, ns); }
security/lsm_init.c +2 -0
@@ -303,6 +303,7 @@ static void __init lsm_prepare(struct lsm_info *lsm)lsm_blob_size_update (&blobs->lbs_ipc, &blob_sizes.lbs_ipc);lsm_blob_size_update (&blobs->lbs_key, &blob_sizes.lbs_key);lsm_blob_size_update (&blobs->lbs_msg_msg, &blob_sizes.lbs_msg_msg); +lsm_blob_size_update (&blobs->lbs_ns, &blob_sizes.lbs_ns);lsm_blob_size_update (&blobs->lbs_perf_event, &blob_sizes.lbs_perf_event);lsm_blob_size_update (&blobs->lbs_sock, &blob_sizes.lbs_sock);
@@ -450,6 +451,7 @@ int __init security_init(void)lsm_pr ("blob(ipc) size %d\n" , blob_sizes.lbs_ipc);lsm_pr ("blob(key) size %d\n" , blob_sizes.lbs_key);lsm_pr ("blob(msg_msg)_size %d\n" , blob_sizes.lbs_msg_msg); +lsm_pr ("blob(ns) size %d\n" , blob_sizes.lbs_ns);lsm_pr ("blob(sock) size %d\n" , blob_sizes.lbs_sock);lsm_pr ("blob(superblock) size %d\n" , blob_sizes.lbs_superblock);lsm_pr ("blob(perf_event) size %d\n" , blob_sizes.lbs_perf_event);
security/security.c +77 -0
95 lines not on this page · raw message
Signature · 1 line
2.54.0
Mickaël Salaün
maintainerRe: [PATCH v2 1/9] security: add LSM blob and hooks for namespaces
Paul, could you please take a look at this patch and the next one? I'd like to push it to linux-next to get more feedback.
Quoted 384 lines · Mickaël Salaün
From: Christian Brauner <[email protected]>
All namespace types now share the same
ns_commoninfrastructure. Extend this to include a security blob so LSMs can start managing namespaces uniformly without having to add one-off hooks or security fields to every individual namespace type.Add a
ns_securitypointer tons_commonand the correspondinglbs_nsblob size tolsm_blob_sizes. Allocation and freeing hooks are called from the common__ns_common_init()and__ns_common_free()paths so every namespace type gets covered in one go. All information about the namespace type and the appropriate casting helpers to get at the containing namespace are available vians_commonmaking it straightforward for LSMs to differentiate when they need to.A
namespace_installhook is called fromvalidate_ns()during setns(2) giving LSMs a chance to enforce policy on namespace transitions. The LSM check runs beforens->ops->install()so the security module can deny the operation before any type-specific installation effects.Individual namespace types can still have their own specialized security hooks when needed. This is just the common baseline that makes it easy to track and manage namespaces from the security side without requiring every namespace type to reinvent the wheel.
Cc Günther Noack <[email protected]>Cc Paul Moore <[email protected]>Cc Serge E. Hallyn <[email protected]>Signed-off-by Christian Brauner <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>---
Changes since v1:
https://lore.kernel.org/r/[email protected]
- Movesecurity_namespace_install()beforens->ops->install()invalidate_ns()(suggested by Christian Brauner).
- Only callproc_free_inum()onsecurity_namespace_alloc()failure when inum was allocated by this function (suggested by Christian Brauner).
- Fix anonymous mount namespace blob leak: movesecurity_namespace_free()into__ns_common_free()and makeproc_free_inum()conditional on dynamically allocated inums viaMNT_NS_INO_SPECIAL_MAX, sofree_mnt_ns()can callns_common_free()unconditionally (suggested by Christian Brauner). Also reported by Daniel Durning while working on SELinux support for these hooks:
https://lore.kernel.org/r/[email protected]
- Renamesecurity_namespace_alloc()tosecurity_namespace_init()to match the caller-name convention and reflect that the hook initialises LSM state attached to a constructedns_commonrather than allocating thens_commonitself (suggested by Paul Moore).
- Refine thesecurity_namespace_free()kdoc to clarify that RCU-safe blob freeing is required only if an LSM exposes data within the blob to concurrent RCU readers, and document that the blob memory itself is released withkfree()after thenamespace_freehooks return (suggested by Paul Moore).
- Günther Noack's v1 Reviewed-by is not carried forward to v2:
thevalidate_ns()reordering and the anonymous-mount-namespace blob-leak fix are semantic changes that were not part of his review. Cc'd instead.--- fs/namespace.c | 3 +- include/linux/lsm_hook_defs.h | 3 ++ include/linux/lsm_hooks.h | 1 + include/linux/ns/ns_common_types.h | 3 ++ include/linux/security.h | 20 ++++++++ include/uapi/linux/nsfs.h | 1 + kernel/nscommon.c | 17 ++++++- kernel/nsproxy.c | 6 +++ security/lsm_init.c | 2 + security/security.c | 77 ++++++++++++++++++++++++++++++ 10 files changed, 130 insertions(+), 3 deletions(-)fs/namespace.c +1
-2@@ -4179,8 +4179,7 @@ static void dec_mnt_namespaces(struct ucounts *ucounts)static void free_mnt_ns (struct mnt_namespace *ns) { -if (!is_anon_ns (ns)) -ns_common_free (ns); +ns_common_free (ns);dec_mnt_namespaces (ns->ucounts);mnt_ns_tree_remove (ns); }include/linux/lsm_hook_defs.h +3
-0@@ -265,6 +265,9 @@ LSM_HOOK(int, -ENOSYS, task_prctl, int option, unsigned long arg2, LSM_HOOK(void, LSM_RET_VOID, task_to_inode, struct task_struct *p, struct inode *inode) LSM_HOOK(int, 0, userns_create, const struct cred *cred) +LSM_HOOK(int, 0, namespace_init, struct ns_common *ns) +LSM_HOOK(void, LSM_RET_VOID, namespace_free, struct ns_common *ns) +LSM_HOOK(int, 0, namespace_install, const struct nsset *nsset, struct ns_common *ns) LSM_HOOK(int, 0, ipc_permission, struct kern_ipc_perm *ipcp, short flag) LSM_HOOK(void, LSM_RET_VOID, ipc_getlsmprop, struct kern_ipc_perm *ipcp, struct lsm_prop *prop)include/linux/lsm_hooks.h +1
-0@@ -112,6 +112,7 @@ struct lsm_blob_sizes {unsigned int lbs_ipc;unsigned int lbs_key;unsigned int lbs_msg_msg; +unsigned int lbs_ns;unsigned int lbs_perf_event;unsigned int lbs_task;unsigned int lbs_xattr_count;/* num xattr slots in new_xattrs array */ include/linux/ns/ns_common_types.h +3
-0@@ -116,6 +116,9 @@ struct ns_common {struct dentry *stashed;const struct proc_ns_operations *ops;unsigned int inum; +#ifdef CONFIG_SECURITY +void *ns_security; +#endif union {struct ns_tree ;struct rcu_head ns_rcu;include/linux/security.h +20
-0@@ -67,6 +67,7 @@ enum fs_value_type;struct watch ;struct watch_notification ;struct lsm_ctx ; +struct nsset ;/* Default (no) options for the capable function */ #define CAP_OPT_NONE 0x0@@ -80,6 +81,7 @@ struct lsm_ctx;struct ctl_table ;struct audit_krule ; +struct ns_common ;struct user_namespace ;struct timezone ;@@ -540,6 +542,9 @@ int security_task_prctl(int option, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5);void security_task_to_inode (struct task_struct *p,struct inode *inode);int security_create_user_ns (const struct cred *cred); +int security_namespace_init (struct ns_common *ns); +void security_namespace_free (struct ns_common *ns); +int security_namespace_install (const struct nsset *nsset,struct ns_common *ns);int security_ipc_permission (struct kern_ipc_perm *ipcp,short flag);void security_ipc_getlsmprop (struct kern_ipc_perm *ipcp,struct lsm_prop *prop);int security_msg_msg_alloc (struct msg_msg *msg);@@ -1430,6 +1435,21 @@ static inline int security_create_user_ns(const struct cred *cred)return 0 ; } +static inline int security_namespace_init (struct ns_common *ns) +{ +return 0 ; +} + +static inline void security_namespace_free (struct ns_common *ns) +{ +} + +static inline int security_namespace_install (const struct nsset *nsset, +struct ns_common *ns) +{ +return 0 ; +} +static inline int security_ipc_permission (struct kern_ipc_perm *ipcp,short flag) {include/uapi/linux/nsfs.h +1
-0@@ -55,6 +55,7 @@ enum init_ns_ino { MNT_NS_INIT_INO = 0xEFFFFFF8U,#ifdef __KERNEL__MNT_NS_ANON_INO =0xEFFFFFF7U , + MNT_NS_INO_SPECIAL_MAX = MNT_NS_ANON_INO, #endif };kernel/nscommon.c +16
-1@@ -4,6 +4,7 @@#include <linux/ns_common.h> #include <linux/nstree.h> #include <linux/proc_ns.h> +#include <linux/security.h> #include <linux/user_namespace.h> #include <linux/vfsdebug.h> @@ -59,6 +60,9 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_operefcount_set (&ns->__ns_ref,1 ); ns->stashed =NULL ; +#ifdef CONFIG_SECURITY + ns->ns_security =NULL ; +#endif ns->ops = ops; ns->ns_id =0 ; ns->ns_type = ns_type;@@ -77,6 +81,14 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope ret =proc_alloc_inum (&ns->inum);if (ret)return ret; + + ret =security_namespace_init (ns); +if (ret) { +if (!inum) +proc_free_inum (ns->inum); +return ret; + } +/* * Tree ref starts at 0. It's incremented when namespace enters * active use (installed in nsproxy) and decremented when all @@ -91,7 +103,10 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_opevoid __ns_common_free (struct ns_common *ns) { -proc_free_inum (ns->inum); +security_namespace_free (ns); + +if (ns->inum >MNT_NS_INO_SPECIAL_MAX ) +proc_free_inum (ns->inum); }struct ns_common *__must_check ns_owner (struct ns_common *ns)kernel/nsproxy.c +6
-0@@ -385,6 +385,12 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)static inline int validate_ns (struct nsset *nsset,struct ns_common *ns) { +int ret; + + ret =security_namespace_install (nsset, ns); +if (ret) +return ret; +return ns->ops->install (nsset, ns); }security/lsm_init.c +2
-0@@ -303,6 +303,7 @@ static void __init lsm_prepare(struct lsm_info *lsm)lsm_blob_size_update (&blobs->lbs_ipc, &blob_sizes.lbs_ipc);lsm_blob_size_update (&blobs->lbs_key, &blob_sizes.lbs_key);lsm_blob_size_update (&blobs->lbs_msg_msg, &blob_sizes.lbs_msg_msg); +lsm_blob_size_update (&blobs->lbs_ns, &blob_sizes.lbs_ns);lsm_blob_size_update (&blobs->lbs_perf_event, &blob_sizes.lbs_perf_event);lsm_blob_size_update (&blobs->lbs_sock, &blob_sizes.lbs_sock);@@ -450,6 +451,7 @@ int __init security_init(void)lsm_pr ("blob(ipc) size %d\n" , blob_sizes.lbs_ipc);lsm_pr ("blob(key) size %d\n" , blob_sizes.lbs_key);lsm_pr ("blob(msg_msg)_size %d\n" , blob_sizes.lbs_msg_msg); +lsm_pr ("blob(ns) size %d\n" , blob_sizes.lbs_ns);lsm_pr ("blob(sock) size %d\n" , blob_sizes.lbs_sock);lsm_pr ("blob(superblock) size %d\n" , blob_sizes.lbs_superblock);lsm_pr ("blob(perf_event) size %d\n" , blob_sizes.lbs_perf_event);security/security.c +77
-0@@ -26,6 +26,7 @@#include <linux/string.h> #include <linux/xattr.h> #include <linux/msg.h> +#include <linux/ns_common.h> #include <linux/overflow.h> #include <linux/perf_event.h> #include <linux/fs.h> @@ -381,6 +382,19 @@ static int lsm_superblock_alloc(struct super_block *sb) GFP_KERNEL); } +/** +* lsm_ns_alloc - allocate a composite namespace blob +* @ns: the namespace that needs a blob +* +* Allocate the namespace blob for all the modules +* +* Returns 0, or -ENOMEM if memory can't be allocated. +*/ +static int lsm_ns_alloc (struct ns_common *ns) +{ +return lsm_blob_alloc (&ns->ns_security, blob_sizes.lbs_ns,GFP_KERNEL ); +} +/** * lsm_fill_user_ctx - Fill a user space lsm_ctx structure * @uctx: a userspace LSM context to be filled @@ -3358,6 +3372,69 @@ int security_create_user_ns(const struct cred *cred)return call_int_hook (userns_create, cred); } +/** +* security_namespace_init() - Initialize LSM security data for a namespace +* @ns: the namespace being initialized +* +* Initialize the LSM security blob attached to the namespace. The namespace type +* is available via ns->ns_type, and the owning user namespace (if any) +* via ns->ops->owner(ns). +* +* Return: Returns 0 if successful, otherwise < 0 error code. +*/ +int security_namespace_init (struct ns_common *ns) +{ +int rc; + + rc =lsm_ns_alloc (ns); +if (unlikely (rc)) +return rc; + + rc =call_int_hook (namespace_init, ns); +if (unlikely (rc)) +security_namespace_free (ns); + +return rc; +} + +/** +* security_namespace_free() - Release LSM security data from a namespace +* @ns: the namespace being freed +* +* Release security data attached to the namespace. Called before the +* namespace structure is freed. +* +* Note: If an LSM exposes data within the security blob to concurrent +* RCU readers, it must use RCU-safe freeing for that data. The blob +* memory itself is released with kfree() after the namespace_free +* hooks return. +*/ +void security_namespace_free (struct ns_common *ns) +{ +if (!ns->ns_security) +return ; + +call_void_hook (namespace_free, ns); + +kfree (ns->ns_security); + ns->ns_security =NULL ; +} + +/** +* security_namespace_install() - Check permission to install a namespace +* @nsset: the target nsset being configured +* @ns: the namespace being installed +* +* Check permission before allowing a namespace to be installed into the +* process's set of namespaces via setns(2). +* +* Return: Returns 0 if permission is granted, otherwise < 0 error code. +*/ +int security_namespace_install (const struct nsset *nsset,struct ns_common *ns) +{ +return call_int_hook (namespace_install, nsset, ns); +} +/** * security_ipc_permission() - Check if sysv ipc access is allowed * @ipcp: ipc permission structure Signature · 1 line
2.54.0
Paul Moore
maintainerRe: [PATCH v2 1/9] security: add LSM blob and hooks for namespaces
Quoted 3 lines · Mickaël Salaün
Paul, could you please take a look at this patch and the next one? I'd like to push it to linux-next to get more feedback.
I saw the patches Mickaël, they are in the queue and will be reviewed in due time. Considering the delay in getting this revision out after my last review, another week or two shouldn't pose a problem.
Signature · 1 line
paul-moore.com
Paul Moore
maintainerRe: [PATCH v2 1/9] security: add LSM blob and hooks for namespaces
In reply to Mickaël SalaünQuoted 86 lines · On May 27, 2026 =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= <[email protected]> wrote:
All namespace types now share the same
ns_commoninfrastructure. Extend this to include a security blob so LSMs can start managing namespaces uniformly without having to add one-off hooks or security fields to every individual namespace type.Add a
ns_securitypointer tons_commonand the correspondinglbs_nsblob size tolsm_blob_sizes. Allocation and freeing hooks are called from the common__ns_common_init()and__ns_common_free()paths so every namespace type gets covered in one go. All information about the namespace type and the appropriate casting helpers to get at the containing namespace are available vians_commonmaking it straightforward for LSMs to differentiate when they need to.A
namespace_installhook is called fromvalidate_ns()during setns(2) giving LSMs a chance to enforce policy on namespace transitions. The LSM check runs beforens->ops->install()so the security module can deny the operation before any type-specific installation effects.Individual namespace types can still have their own specialized security hooks when needed. This is just the common baseline that makes it easy to track and manage namespaces from the security side without requiring every namespace type to reinvent the wheel.
Cc Günther Noack <[email protected]>Cc Paul Moore <[email protected]>Cc Serge E. Hallyn <[email protected]>Signed-off-by Christian Brauner <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>---
Changes since v1:
https://lore.kernel.org/r/[email protected]
- Movesecurity_namespace_install()beforens->ops->install()invalidate_ns()(suggested by Christian Brauner).
- Only callproc_free_inum()onsecurity_namespace_alloc()failure when inum was allocated by this function (suggested by Christian Brauner).
- Fix anonymous mount namespace blob leak: movesecurity_namespace_free()into__ns_common_free()and makeproc_free_inum()conditional on dynamically allocated inums viaMNT_NS_INO_SPECIAL_MAX, sofree_mnt_ns()can callns_common_free()unconditionally (suggested by Christian Brauner). Also reported by Daniel Durning while working on SELinux support for these hooks:
https://lore.kernel.org/r/[email protected]
- Renamesecurity_namespace_alloc()tosecurity_namespace_init()to match the caller-name convention and reflect that the hook initialises LSM state attached to a constructedns_commonrather than allocating thens_commonitself (suggested by Paul Moore).
- Refine thesecurity_namespace_free()kdoc to clarify that RCU-safe blob freeing is required only if an LSM exposes data within the blob to concurrent RCU readers, and document that the blob memory itself is released withkfree()after thenamespace_freehooks return (suggested by Paul Moore).
- Günther Noack's v1 Reviewed-by is not carried forward to v2:
thevalidate_ns()reordering and the anonymous-mount-namespace blob-leak fix are semantic changes that were not part of his review. Cc'd instead.--- fs/namespace.c | 3 +- include/linux/lsm_hook_defs.h | 3 ++ include/linux/lsm_hooks.h | 1 + include/linux/ns/ns_common_types.h | 3 ++ include/linux/security.h | 20 ++++++++ include/uapi/linux/nsfs.h | 1 + kernel/nscommon.c | 17 ++++++- kernel/nsproxy.c | 6 +++ security/lsm_init.c | 2 + security/security.c | 77 ++++++++++++++++++++++++++++++ 10 files changed, 130 insertions(+), 3 deletions(-)fs/namespace.c +1
-2@@ -4179,8 +4179,7 @@ static void dec_mnt_namespaces(struct ucounts *ucounts)static void free_mnt_ns (struct mnt_namespace *ns) { -if (!is_anon_ns (ns)) -ns_common_free (ns); +ns_common_free (ns);dec_mnt_namespaces (ns->ucounts);mnt_ns_tree_remove (ns); }
...
Quoted 38 lines
kernel/nscommon.c +12
-0@@ -4,6 +4,7 @@#include <linux/ns_common.h> #include <linux/nstree.h> #include <linux/proc_ns.h> +#include <linux/security.h> #include <linux/user_namespace.h> #include <linux/vfsdebug.h> @@ -59,6 +60,9 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_operefcount_set (&ns->__ns_ref,1 ); ns->stashed =NULL ; +#ifdef CONFIG_SECURITY + ns->ns_security =NULL ; +#endif ns->ops = ops; ns->ns_id =0 ; ns->ns_type = ns_type;@@ -77,6 +81,14 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope ret =proc_alloc_inum (&ns->inum);if (ret)return ret; + + ret =security_namespace_init (ns); +if (ret) { +if (!inum) +proc_free_inum (ns->inum); +return ret; + } +/* * Tree ref starts at 0. It's incremented when namespace enters * active use (installed in nsproxy) and decremented when all
kernel/nscommon.c int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope · line 109
Quoted 8 lines
kernel/nscommon.c +4
-1@@ -91,7 +103,10 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_opevoid __ns_common_free (struct ns_common *ns) { -proc_free_inum (ns->inum); +security_namespace_free (ns); + +if (ns->inum >MNT_NS_INO_SPECIAL_MAX ) +proc_free_inum (ns->inum);
The ns->inum check in the if-conditional above isn't quite the same as the is_anon_ns() check it replaces in free_mnt_ns(). You touch on this a bit in the changelog, but that really should be explained in the commit description.
... or honestly, should that change be a separate patch?
Quoted 9 lines
kernel/nscommon.c +0
-0}struct ns_common *__must_check ns_owner (struct ns_common *ns)kernel/nsproxy.c +0
-0@@ -385,6 +385,12 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)
kernel/nsproxy.c static int prepare_nsset(unsigned flags, struct nsset *nsset) · line 395
Quoted 10 lines
kernel/nsproxy.c +6
-0static inline int validate_ns (struct nsset *nsset,struct ns_common *ns) { +int ret; + + ret =security_namespace_install (nsset, ns); +if (ret) +return ret; +return ns->ops->install (nsset, ns); }
In the previous revision to the patchset I asked about a security_namespace_switch() hook as we don't know if a namespace is actually attached to a process until we get to switch_task_namespaces(). Perhaps that was answered, but I don't recall reading any mail about that and I'm not able to uncover any responses on lore.
Quoted 62 lines
security/security.c +40
-0@@ -26,6 +26,7 @@#include <linux/string.h> #include <linux/xattr.h> #include <linux/msg.h> +#include <linux/ns_common.h> #include <linux/overflow.h> #include <linux/perf_event.h> #include <linux/fs.h> @@ -381,6 +382,19 @@ static int lsm_superblock_alloc(struct super_block *sb) GFP_KERNEL); } +/** +* lsm_ns_alloc - allocate a composite namespace blob +* @ns: the namespace that needs a blob +* +* Allocate the namespace blob for all the modules +* +* Returns 0, or -ENOMEM if memory can't be allocated. +*/ +static int lsm_ns_alloc (struct ns_common *ns) +{ +return lsm_blob_alloc (&ns->ns_security, blob_sizes.lbs_ns,GFP_KERNEL ); +} +/** * lsm_fill_user_ctx - Fill a user space lsm_ctx structure * @uctx: a userspace LSM context to be filled @@ -3358,6 +3372,69 @@ int security_create_user_ns(const struct cred *cred)return call_int_hook (userns_create, cred); } +/** +* security_namespace_init() - Initialize LSM security data for a namespace +* @ns: the namespace being initialized +* +* Initialize the LSM security blob attached to the namespace. The namespace type +* is available via ns->ns_type, and the owning user namespace (if any) +* via ns->ops->owner(ns). +* +* Return: Returns 0 if successful, otherwise < 0 error code. +*/ +int security_namespace_init (struct ns_common *ns) +{ +int rc; + + rc =lsm_ns_alloc (ns); +if (unlikely (rc)) +return rc; + + rc =call_int_hook (namespace_init, ns); +if (unlikely (rc)) +security_namespace_free (ns); + +return rc; +} + +/**
security/security.c int security_create_user_ns(const struct cred *cred) · line 3410
Quoted 10 lines
security/security.c +10
-0+* security_namespace_free() - Release LSM security data from a namespace +* @ns: the namespace being freed +* +* Release security data attached to the namespace. Called before the +* namespace structure is freed. +* +* Note: If an LSM exposes data within the security blob to concurrent +* RCU readers, it must use RCU-safe freeing for that data. The blob +* memory itself is released with kfree() after the namespace_free +* hooks return.
I appreciate that you revised the "Note:" based on my previous comments, but now it reads just like normal guidance on RCU and object lifetimes. Do we need this "Note:" at all?
Quoted 32 lines
security/security.c +27
-0+*/ +void security_namespace_free (struct ns_common *ns) +{ +if (!ns->ns_security) +return ; + +call_void_hook (namespace_free, ns); + +kfree (ns->ns_security); + ns->ns_security =NULL ; +} + +/** +* security_namespace_install() - Check permission to install a namespace +* @nsset: the target nsset being configured +* @ns: the namespace being installed +* +* Check permission before allowing a namespace to be installed into the +* process's set of namespaces via setns(2). +* +* Return: Returns 0 if permission is granted, otherwise < 0 error code. +*/ +int security_namespace_install (const struct nsset *nsset,struct ns_common *ns) +{ +return call_int_hook (namespace_install, nsset, ns); +} +/** * security_ipc_permission() - Check if sysv ipc access is allowed * @ipcp: ipc permission structure Signature · 1 line
2.54.0
--
paul-moore.com
Mickaël Salaün
maintainerRe: [PATCH v2 1/9] security: add LSM blob and hooks for namespaces
Quoted 142 lines · Paul Moore
Quoted 86 lines · On May 27, 2026 =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= <[email protected]> wrote:
All namespace types now share the same
ns_commoninfrastructure. Extend this to include a security blob so LSMs can start managing namespaces uniformly without having to add one-off hooks or security fields to every individual namespace type.Add a
ns_securitypointer tons_commonand the correspondinglbs_nsblob size tolsm_blob_sizes. Allocation and freeing hooks are called from the common__ns_common_init()and__ns_common_free()paths so every namespace type gets covered in one go. All information about the namespace type and the appropriate casting helpers to get at the containing namespace are available vians_commonmaking it straightforward for LSMs to differentiate when they need to.A
namespace_installhook is called fromvalidate_ns()during setns(2) giving LSMs a chance to enforce policy on namespace transitions. The LSM check runs beforens->ops->install()so the security module can deny the operation before any type-specific installation effects.Individual namespace types can still have their own specialized security hooks when needed. This is just the common baseline that makes it easy to track and manage namespaces from the security side without requiring every namespace type to reinvent the wheel.
Cc Günther Noack <[email protected]>Cc Paul Moore <[email protected]>Cc Serge E. Hallyn <[email protected]>Signed-off-by Christian Brauner <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>---
Changes since v1:
https://lore.kernel.org/r/[email protected]
- Movesecurity_namespace_install()beforens->ops->install()invalidate_ns()(suggested by Christian Brauner).
- Only callproc_free_inum()onsecurity_namespace_alloc()failure when inum was allocated by this function (suggested by Christian Brauner).
- Fix anonymous mount namespace blob leak: movesecurity_namespace_free()into__ns_common_free()and makeproc_free_inum()conditional on dynamically allocated inums viaMNT_NS_INO_SPECIAL_MAX, sofree_mnt_ns()can callns_common_free()unconditionally (suggested by Christian Brauner). Also reported by Daniel Durning while working on SELinux support for these hooks:
https://lore.kernel.org/r/[email protected]
- Renamesecurity_namespace_alloc()tosecurity_namespace_init()to match the caller-name convention and reflect that the hook initialises LSM state attached to a constructedns_commonrather than allocating thens_commonitself (suggested by Paul Moore).
- Refine thesecurity_namespace_free()kdoc to clarify that RCU-safe blob freeing is required only if an LSM exposes data within the blob to concurrent RCU readers, and document that the blob memory itself is released withkfree()after thenamespace_freehooks return (suggested by Paul Moore).
- Günther Noack's v1 Reviewed-by is not carried forward to v2:
thevalidate_ns()reordering and the anonymous-mount-namespace blob-leak fix are semantic changes that were not part of his review. Cc'd instead.--- fs/namespace.c | 3 +- include/linux/lsm_hook_defs.h | 3 ++ include/linux/lsm_hooks.h | 1 + include/linux/ns/ns_common_types.h | 3 ++ include/linux/security.h | 20 ++++++++ include/uapi/linux/nsfs.h | 1 + kernel/nscommon.c | 17 ++++++- kernel/nsproxy.c | 6 +++ security/lsm_init.c | 2 + security/security.c | 77 ++++++++++++++++++++++++++++++ 10 files changed, 130 insertions(+), 3 deletions(-)fs/namespace.c +1
-2@@ -4179,8 +4179,7 @@ static void dec_mnt_namespaces(struct ucounts *ucounts)static void free_mnt_ns (struct mnt_namespace *ns) { -if (!is_anon_ns (ns)) -ns_common_free (ns); +ns_common_free (ns);dec_mnt_namespaces (ns->ucounts);mnt_ns_tree_remove (ns); }...
Quoted 38 lines
kernel/nscommon.c +12
-0@@ -4,6 +4,7 @@#include <linux/ns_common.h> #include <linux/nstree.h> #include <linux/proc_ns.h> +#include <linux/security.h> #include <linux/user_namespace.h> #include <linux/vfsdebug.h> @@ -59,6 +60,9 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_operefcount_set (&ns->__ns_ref,1 ); ns->stashed =NULL ; +#ifdef CONFIG_SECURITY + ns->ns_security =NULL ; +#endif ns->ops = ops; ns->ns_id =0 ; ns->ns_type = ns_type;@@ -77,6 +81,14 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope ret =proc_alloc_inum (&ns->inum);if (ret)return ret; + + ret =security_namespace_init (ns); +if (ret) { +if (!inum) +proc_free_inum (ns->inum); +return ret; + } +/* * Tree ref starts at 0. It's incremented when namespace enters * active use (installed in nsproxy) and decremented when all kernel/nscommon.c int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope · line 109
Quoted 8 lines
kernel/nscommon.c +4
-1@@ -91,7 +103,10 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_opevoid __ns_common_free (struct ns_common *ns) { -proc_free_inum (ns->inum); +security_namespace_free (ns); + +if (ns->inum >MNT_NS_INO_SPECIAL_MAX ) +proc_free_inum (ns->inum);The
ns->inumcheck in the if-conditional above isn't quite the same as theis_anon_ns()check it replaces infree_mnt_ns(). You touch on this a bit in the changelog, but that really should be explained in the commit description.
Quoted 1 line
... or honestly, should that change be a separate patch?
I think it's fine, but it's Christian's patch, so I'll let him answer and propose a new commit description.
Quoted 10 lines
Quoted 10 lines
kernel/nscommon.c +0
-0}struct ns_common *__must_check ns_owner (struct ns_common *ns)kernel/nsproxy.c +0
-0@@ -385,6 +385,12 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)
Quoted 16 lines
kernel/nsproxy.c static int prepare_nsset(unsigned flags, struct nsset *nsset) · line 395
Quoted 10 lines
kernel/nsproxy.c +6
-0static inline int validate_ns (struct nsset *nsset,struct ns_common *ns) { +int ret; + + ret =security_namespace_install (nsset, ns); +if (ret) +return ret; +return ns->ops->install (nsset, ns); }In the previous revision to the patchset I asked about a
security_namespace_switch()hook as we don't know if a namespace is actually attached to a process until we get toswitch_task_namespaces(). Perhaps that was answered, but I don't recall reading any mail about that and I'm not able to uncover any responses on lore.
From the cover letter:
no security_namespace_switch() post-hook is
added in this series: such a hook would only serve LSMs that maintain per-task state derived from the active namespace set (SELinux-style state tracking), and no current LSM (including this series) needs that. Landlock enforces at namespace_install() and namespace_init(), before the task-to-nsproxy switch. The hook is left for a separate LSM infrastructure proposal once a concrete user emerges.
This follows the guidance of adding new hooks: there must be at least one user.
Quoted 69 lines
Quoted 69 lines
security/security.c +46
-0@@ -26,6 +26,7 @@#include <linux/string.h> #include <linux/xattr.h> #include <linux/msg.h> +#include <linux/ns_common.h> #include <linux/overflow.h> #include <linux/perf_event.h> #include <linux/fs.h> @@ -381,6 +382,19 @@ static int lsm_superblock_alloc(struct super_block *sb) GFP_KERNEL); } +/** +* lsm_ns_alloc - allocate a composite namespace blob +* @ns: the namespace that needs a blob +* +* Allocate the namespace blob for all the modules +* +* Returns 0, or -ENOMEM if memory can't be allocated. +*/ +static int lsm_ns_alloc (struct ns_common *ns) +{ +return lsm_blob_alloc (&ns->ns_security, blob_sizes.lbs_ns,GFP_KERNEL ); +} +/** * lsm_fill_user_ctx - Fill a user space lsm_ctx structure * @uctx: a userspace LSM context to be filled @@ -3358,6 +3372,69 @@ int security_create_user_ns(const struct cred *cred)return call_int_hook (userns_create, cred); } +/** +* security_namespace_init() - Initialize LSM security data for a namespace +* @ns: the namespace being initialized +* +* Initialize the LSM security blob attached to the namespace. The namespace type +* is available via ns->ns_type, and the owning user namespace (if any) +* via ns->ops->owner(ns). +* +* Return: Returns 0 if successful, otherwise < 0 error code. +*/ +int security_namespace_init (struct ns_common *ns) +{ +int rc; + + rc =lsm_ns_alloc (ns); +if (unlikely (rc)) +return rc; + + rc =call_int_hook (namespace_init, ns); +if (unlikely (rc)) +security_namespace_free (ns); + +return rc; +} + +/** +* security_namespace_free() - Release LSM security data from a namespace +* @ns: the namespace being freed +* +* Release security data attached to the namespace. Called before the +* namespace structure is freed. +*
Quoted 8 lines
security/security.c int security_create_user_ns(const struct cred *cred) · line 3410
Quoted 4 lines
security/security.c +4
-0+* Note: If an LSM exposes data within the security blob to concurrent +* RCU readers, it must use RCU-safe freeing for that data. The blob +* memory itself is released with kfree() after the namespace_free +* hooks return. I appreciate that you revised the "Note:" based on my previous comments, but now it reads just like normal guidance on RCU and object lifetimes. Do we need this "Note:" at all?
Indeed, it's normal guidance, I'll remove it.
Quoted 37 lines
Quoted 33 lines
security/security.c +27
-0+*/ +void security_namespace_free (struct ns_common *ns) +{ +if (!ns->ns_security) +return ; + +call_void_hook (namespace_free, ns); + +kfree (ns->ns_security); + ns->ns_security =NULL ; +} + +/** +* security_namespace_install() - Check permission to install a namespace +* @nsset: the target nsset being configured +* @ns: the namespace being installed +* +* Check permission before allowing a namespace to be installed into the +* process's set of namespaces via setns(2). +* +* Return: Returns 0 if permission is granted, otherwise < 0 error code. +*/ +int security_namespace_install (const struct nsset *nsset,struct ns_common *ns) +{ +return call_int_hook (namespace_install, nsset, ns); +} +/** * security_ipc_permission() - Check if sysv ipc access is allowed * @ipcp: ipc permission structure Signature · 1 line
2.54.0--
paul-moore.com
Paul Moore
maintainerRe: [PATCH v2 1/9] security: add LSM blob and hooks for namespaces
Quoted 7 lines · Mickaël Salaün
Quoted 6 lines · Paul Moore
Quoted 5 lines · On May 27, 2026 =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= <[email protected]> wrote:
All namespace types now share the same
ns_commoninfrastructure. Extend this to include a security blob so LSMs can start managing namespaces uniformly without having to add one-off hooks or security fields to every individual namespace type.
...
Quoted 15 lines
Quoted 15 lines
kernel/nscommon.c int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope · line 109
Quoted 9 lines
kernel/nscommon.c +4
-1@@ -91,7 +103,10 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_opevoid __ns_common_free (struct ns_common *ns) { -proc_free_inum (ns->inum); +security_namespace_free (ns); + +if (ns->inum >MNT_NS_INO_SPECIAL_MAX ) +proc_free_inum (ns->inum);The
ns->inumcheck in the if-conditional above isn't quite the same as theis_anon_ns()check it replaces infree_mnt_ns(). You touch on this a bit in the changelog, but that really should be explained in the commit description.
Quoted 4 lines
Quoted 1 line
... or honestly, should that change be a separate patch?
I think it's fine, but it's Christian's patch, so I'll let him answer and propose a new commit description.
I don't have a strong opinion on either approach, either a separate patch or doc update, but one of the two needs to happen.
Quoted 33 lines
Quoted 6 lines
Quoted 6 lines
kernel/nsproxy.c +0
-0@@ -385,6 +385,12 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)Quoted 16 lines
kernel/nsproxy.c static int prepare_nsset(unsigned flags, struct nsset *nsset) · line 395
Quoted 10 lines
kernel/nsproxy.c +6
-0static inline int validate_ns (struct nsset *nsset,struct ns_common *ns) { +int ret; + + ret =security_namespace_install (nsset, ns); +if (ret) +return ret; +return ns->ops->install (nsset, ns); }In the previous revision to the patchset I asked about a
security_namespace_switch()hook as we don't know if a namespace is actually attached to a process until we get toswitch_task_namespaces(). Perhaps that was answered, but I don't recall reading any mail about that and I'm not able to uncover any responses on lore.From the cover letter:
no
security_namespace_switch()post-hook is
added in this series: such a hook would only serve LSMs that maintain per-task state derived from the active namespace set (SELinux-style state tracking), and no current LSM (including this series) needs that. Landlock enforces atnamespace_install()andnamespace_init(), before the task-to-nsproxy switch. The hook is left for a separate LSM infrastructure proposal once a concrete user emerges.
Quoted 2 lines
This follows the guidance of adding new hooks: there must be at least one user.
I'm aware of the new hook guidance, I was the one who documented it :)
In the future, it's both helpful and polite to reply to the email asking the question with your response. Adding it to the cover letter is fine, but to be perfectly honest, once we get past v1 of a patchset, I don't often read the cover letter very closely unless there is a significant change. However, I do look back at the previous posting to ensure all the feedback from everyone has been either answered or incorporated into the current revision.
Signature · 1 line
paul-moore.com
Mickaël Salaün
maintainerRe: [PATCH v2 1/9] security: add LSM blob and hooks for namespaces
Quoted 26 lines · Paul Moore
Quoted 7 lines · Mickaël Salaün
Quoted 6 lines · Paul Moore
Quoted 5 lines · On May 27, 2026 =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= <[email protected]> wrote:
All namespace types now share the same
ns_commoninfrastructure. Extend this to include a security blob so LSMs can start managing namespaces uniformly without having to add one-off hooks or security fields to every individual namespace type....
Quoted 15 lines
Quoted 15 lines
kernel/nscommon.c int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope · line 109
Quoted 9 lines
kernel/nscommon.c +4
-1@@ -91,7 +103,10 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_opevoid __ns_common_free (struct ns_common *ns) { -proc_free_inum (ns->inum); +security_namespace_free (ns); + +if (ns->inum >MNT_NS_INO_SPECIAL_MAX ) +proc_free_inum (ns->inum);The
ns->inumcheck in the if-conditional above isn't quite the same as theis_anon_ns()check it replaces infree_mnt_ns(). You touch on this a bit in the changelog, but that really should be explained in the commit description.
Quoted 7 lines
Quoted 4 lines
Quoted 1 line
... or honestly, should that change be a separate patch?
I think it's fine, but it's Christian's patch, so I'll let him answer and propose a new commit description.
I don't have a strong opinion on either approach, either a separate patch or doc update, but one of the two needs to happen.
Noted, I'll follow on this with Christian.
Quoted 34 lines
Quoted 34 lines
Quoted 7 lines
Quoted 7 lines
kernel/nsproxy.c +0
-0@@ -385,6 +385,12 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)Quoted 16 lines
kernel/nsproxy.c static int prepare_nsset(unsigned flags, struct nsset *nsset) · line 395
Quoted 10 lines
kernel/nsproxy.c +6
-0static inline int validate_ns (struct nsset *nsset,struct ns_common *ns) { +int ret; + + ret =security_namespace_install (nsset, ns); +if (ret) +return ret; +return ns->ops->install (nsset, ns); }In the previous revision to the patchset I asked about a
security_namespace_switch()hook as we don't know if a namespace is actually attached to a process until we get toswitch_task_namespaces(). Perhaps that was answered, but I don't recall reading any mail about that and I'm not able to uncover any responses on lore.From the cover letter:
no
security_namespace_switch()post-hook is
added in this series: such a hook would only serve LSMs that maintain per-task state derived from the active namespace set (SELinux-style state tracking), and no current LSM (including this series) needs that. Landlock enforces atnamespace_install()andnamespace_init(), before the task-to-nsproxy switch. The hook is left for a separate LSM infrastructure proposal once a concrete user emerges.
Quoted 4 lines
Quoted 2 lines
This follows the guidance of adding new hooks: there must be at least one user.
I'm aware of the new hook guidance, I was the one who documented it :)
I know. I guess that means you're ok with that?
Quoted 8 lines
In the future, it's both helpful and polite to reply to the email asking the question with your response. Adding it to the cover letter is fine, but to be perfectly honest, once we get past v1 of a patchset, I don't often read the cover letter very closely unless there is a significant change. However, I do look back at the previous posting to ensure all the feedback from everyone has been either answered or incorporated into the current revision.
I forgot to reply to your email, I didn't mean to be impolite, sorry for the inconvenience. It's useful to know that the cover letter is not always part of your review process.
Christian Brauner
maintainerRe: [PATCH v2 1/9] security: add LSM blob and hooks for namespaces
Quoted 29 lines · Mickaël Salaün
Quoted 28 lines · Paul Moore
Quoted 7 lines · Mickaël Salaün
Quoted 6 lines · Paul Moore
Quoted 5 lines · On May 27, 2026 =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= <[email protected]> wrote:
All namespace types now share the same
ns_commoninfrastructure. Extend this to include a security blob so LSMs can start managing namespaces uniformly without having to add one-off hooks or security fields to every individual namespace type....
Quoted 17 lines
Quoted 16 lines
kernel/nscommon.c int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope · line 109
Quoted 9 lines
kernel/nscommon.c +4
-1@@ -91,7 +103,10 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_opevoid __ns_common_free (struct ns_common *ns) { -proc_free_inum (ns->inum); +security_namespace_free (ns); + +if (ns->inum >MNT_NS_INO_SPECIAL_MAX ) +proc_free_inum (ns->inum);The
ns->inumcheck in the if-conditional above isn't quite the same as theis_anon_ns()check it replaces infree_mnt_ns(). You touch on this a bit in the changelog, but that really should be explained in the commit description.... or honestly, should that change be a separate patch?
Quoted 7 lines
Quoted 5 lines
Quoted 2 lines
I think it's fine, but it's Christian's patch, so I'll let him answer and propose a new commit description.
I don't have a strong opinion on either approach, either a separate patch or doc update, but one of the two needs to happen.
Noted, I'll follow on this with Christian.
I think we should add this as a separate patch.
Mickaël Salaün
maintainerRe: [PATCH v2 1/9] security: add LSM blob and hooks for namespaces
Quoted 33 lines · Christian Brauner
Quoted 32 lines · Mickaël Salaün
Quoted 31 lines · Paul Moore
Quoted 7 lines · Mickaël Salaün
Quoted 6 lines · Paul Moore
Quoted 5 lines · On May 27, 2026 =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= <[email protected]> wrote:
All namespace types now share the same
ns_commoninfrastructure. Extend this to include a security blob so LSMs can start managing namespaces uniformly without having to add one-off hooks or security fields to every individual namespace type....
Quoted 19 lines
Quoted 15 lines
kernel/nscommon.c int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope · line 109
Quoted 9 lines
kernel/nscommon.c +4
-1@@ -91,7 +103,10 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_opevoid __ns_common_free (struct ns_common *ns) { -proc_free_inum (ns->inum); +security_namespace_free (ns); + +if (ns->inum >MNT_NS_INO_SPECIAL_MAX ) +proc_free_inum (ns->inum);The
ns->inumcheck in the if-conditional above isn't quite the same as theis_anon_ns()check it replaces infree_mnt_ns(). You touch on this a bit in the changelog, but that really should be explained in the commit description.Quoted 1 line
... or honestly, should that change be a separate patch?
I think it's fine, but it's Christian's patch, so I'll let him answer and propose a new commit description.
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines
I don't have a strong opinion on either approach, either a separate patch or doc update, but one of the two needs to happen.
Noted, I'll follow on this with Christian.
I think we should add this as a separate patch.
Ok, I wrote this patch and I'll sent it with v3.
Paul Moore
maintainerRe: [PATCH v2 1/9] security: add LSM blob and hooks for namespaces
In reply to Mickaël SalaünQuoted 4 lines · Mickaël Salaün
Quoted 3 lines · Paul Moore
Quoted 2 lines · Mickaël Salaün
Quoted 1 line · Paul Moore
On May 27, 2026 =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= <[email protected]> wrote:
...
Quoted 3 lines
Quoted 1 line
I'm aware of the new hook guidance, I was the one who documented it :)
I know. I guess that means you're ok with that?
Yes.
Just a heads-up, and some of this depends on timing, but as we've got multiple patchsets (there is a SELinux patchset that depends on these hooks) I'll want to take this hook additions via the LSM tree. I can take the associated Landlock patches too if you like, or you base the Landlock tree off the LSM branch; no worries either way, we can sort out the details once the patchset is ready for merging.
Signature · 1 line
paul-moore.com
Mickaël Salaün
maintainerRe: [PATCH v2 1/9] security: add LSM blob and hooks for namespaces
Quoted 6 lines · Paul Moore
Quoted 4 lines · Mickaël Salaün
Quoted 3 lines · Paul Moore
Quoted 2 lines · Mickaël Salaün
Quoted 1 line · Paul Moore
On May 27, 2026 =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= <[email protected]> wrote:
Quoted 7 lines
...
Quoted 3 lines
Quoted 1 line
I'm aware of the new hook guidance, I was the one who documented it :)
I know. I guess that means you're ok with that?
Yes.
Thanks. I applied your suggestions wrt comments and patch split for v3.
Quoted 7 lines
Just a heads-up, and some of this depends on timing, but as we've got multiple patchsets (there is a SELinux patchset that depends on these hooks) I'll want to take this hook additions via the LSM tree. I can take the associated Landlock patches too if you like, or you base the Landlock tree off the LSM branch; no worries either way, we can sort out the details once the patchset is ready for merging.
If it's all right with you, I'd prefer to carry the LSM hook patches in the Landlock tree this cycle, so the whole namespace/capability series stays a single consistent set of commits. I also have ongoing Landlock work (e.g. tracepoints) that needs to build on these hooks, which is easier to manage with them on landlock-next.
That shouldn't hold up the SELinux side: if those patches aren't in a hurry, letting the hooks stay in the -next branch until the next merge window also give them some time to get a broader set of checks. Happy to revisit if the timing gets tight on your end.
Mickaël Salaün
maintainerPATCH v2 2/9 security: Add LSM_AUDIT_DATA_NS for namespace audit records
In reply to Mickaël SalaünAdd a new LSM audit data type LSM_AUDIT_DATA_NS that logs namespace information in audit records. Two fields are provided:
- ns_type: the CLONE_NEW* flag identifying the namespace type, logged in hexadecimal.
- ns_id: the unique 64-bit namespace identifier, retrievable from userspace via NS_GET_ID or listns(2). Unlike the proc inode number (inum), ns_id is never recycled. For namespace creation denials, ns_id is 0 because the namespace does not exist yet.
A new audit data type is needed because no existing LSM_AUDIT_DATA_* type carries namespace information. The closest alternatives (e.g. LSM_AUDIT_DATA_TASK or LSM_AUDIT_DATA_NONE with custom strings) would either lose the namespace type or require ad-hoc formatting that bypasses the structured audit data union.
---
Changes since v1:
https://lore.kernel.org/r/[email protected]
- Replace inum with ns_id in the audit record: ns_id is the stable 64-bit namespace identifier (never recycled), accessible to userspace via NS_GET_ID and listns(2) (suggested by Christian Brauner).
- Add Reviewed-by: Christian Brauner.
- Add Reviewed-by: Günther Noack.
--- include/linux/lsm_audit.h | 5 +++++ security/lsm_audit.c | 4 ++++ 2 files changed, 9 insertions(+)
include/linux/lsm_audit.h +5 -0
@@ -78,6 +78,7 @@ struct common_audit_data {#define LSM_AUDIT_DATA_NOTIFICATION 16#define LSM_AUDIT_DATA_ANONINODE 17#define LSM_AUDIT_DATA_NLMSGTYPE 18 +#define LSM_AUDIT_DATA_NS 19union {struct path path;struct dentry *dentry;
@@ -100,6 +101,10 @@ struct common_audit_data {int reason;const char *anonclass;u16 nlmsg_type; +struct { +u32 ns_type; +u64 ns_id; + } ns; } u;/* this union contains LSM specific data */ union {
security/lsm_audit.c +4 -0
@@ -403,6 +403,10 @@ void audit_log_lsm_data(struct audit_buffer *ab,case LSM_AUDIT_DATA_NLMSGTYPE :audit_log_format (ab," nl-msgtype=%hu" , a->u.nlmsg_type);break ; +case LSM_AUDIT_DATA_NS : +audit_log_format (ab," namespace_type=0x%x namespace_id=%llu" , + a->u.ns.ns_type, a->u.ns.ns_id); +break ; }/* switch (a->type) */ }
Signature · 1 line
2.54.0
Mickaël Salaün
maintainerPATCH v2 3/9 landlock: Wrap per-layer access masks in struct layer_config
In reply to Mickaël SalaünThe per-layer FAM in struct landlock_ruleset currently stores struct access_masks directly, but upcoming permission features (capability and namespace restrictions) need additional per-layer data beyond the handled-access bitfields.
Introduce struct layer_config as a wrapper around struct access_masks and rename the FAM from access_masks[] to layers[]. This makes room for future per-layer fields (e.g. allowed bitmasks) without modifying struct access_masks itself, which is also used as a lightweight parameter type for functions that only need the handled-access bitfields.
No functional change.
---
Changes since v1:
https://lore.kernel.org/r/[email protected]
- Add Reviewed-by: Tingmao Wang.
- Address Günther Noack's review nits:
- Clarify that _LANDLOCK_ACCESS_FS_INITIALLY_DENIED is ORed with
the .handled field of all ruleset->layers[] entries (not the
entries themselves). - Rename landlock_upgrade_handled_access_masks() to landlock_upgrade_handled_layer_config() to match the parameter type.
- Rewrap the @layers kdoc in struct landlock_ruleset.
- Rename struct layer_rights to struct layer_config: "config" is the more general term for per-layer state.
- Add Reviewed-by: Günther Noack.
--- security/landlock/access.h | 33 +++++++++++++++++++++++--------- security/landlock/cred.h | 2 +- security/landlock/ruleset.c | 16 ++++++++-------- security/landlock/ruleset.h | 37 ++++++++++++++++++------------------ security/landlock/syscalls.c | 2 +- 5 files changed, 53 insertions(+), 37 deletions(-)
security/landlock/access.h +24 -9
@@ -19,9 +19,9 @@/* * All access rights that are denied by default whether they are handled or not -* by a ruleset/layer. This must be ORed with all ruleset->access_masks[] -* entries when we need to get the absolute handled access masks, see -* landlock_upgrade_handled_access_masks(). +* by a ruleset/layer. This must be ORed with the .handled field of all +* ruleset->layers[] entries when we need to get the absolute handled access +* masks, see landlock_upgrade_handled_layer_config(). */ /* clang-format off */ #define _LANDLOCK_ACCESS_FS_INITIALLY_DENIED ( \
@@ -45,7 +45,7 @@ static_assert(BITS_PER_TYPE(access_mask_t) >= LANDLOCK_NUM_SCOPE);/* Makes sure for_each_set_bit() and for_each_clear_bit() calls are OK. */ static_assert (sizeof (unsigned long ) >=sizeof (access_mask_t)); -/* Ruleset access masks. */ +/* Handled access masks (bitfields only). */ struct access_masks {access_mask_t fs :LANDLOCK_NUM_ACCESS_FS ;access_mask_t net :LANDLOCK_NUM_ACCESS_NET ;
@@ -61,6 +61,21 @@ union access_masks_all {static_assert (sizeof (typeof_member (union access_masks_all ,masks )) ==sizeof (typeof_member (union access_masks_all ,all ))); +/** +* struct layer_config - Per-layer access configuration +* +* Wraps the handled-access bitfields together with any additional per-layer +* data (e.g. allowed bitmasks added by future patches). This is the element +* type of the &struct landlock_ruleset.layers FAM. +*/ +struct layer_config { +/** +* @handled: Bitmask of access rights handled (i.e. restricted) by this +* layer. +*/ +struct access_masks handled; +}; +/** * struct layer_access_masks - A boolean matrix of layers and access rights *
@@ -100,17 +115,17 @@ static_assert(BITS_PER_TYPE(deny_masks_t) >=static_assert (HWEIGHT (LANDLOCK_MAX_NUM_LAYERS ) ==1 );/* Upgrades with all initially denied by default access rights. */ -static inline struct access_masks -landlock_upgrade_handled_access_masks (struct access_masks access_masks) +static inline struct layer_config +landlock_upgrade_handled_layer_config (struct layer_config layer_config) {/* * All access rights that are denied by default whether they are * explicitly handled or not. */ -if (access_masks.fs) - access_masks.fs |= _LANDLOCK_ACCESS_FS_INITIALLY_DENIED; +if (layer_config.handled.fs) + layer_config.handled.fs |= _LANDLOCK_ACCESS_FS_INITIALLY_DENIED; -return access_masks; +return layer_config; }/* Checks the subset relation between access masks. */
security/landlock/cred.h +1 -1
@@ -139,7 +139,7 @@ landlock_get_applicable_subject(const struct cred *const cred,for (layer_level = domain->num_layers -1 ; layer_level >=0 ; layer_level--) {union access_masks_all layer = { - .masks = domain->access_masks[layer_level], + .masks = domain->layers[layer_level].handled, };if (layer.all & masks_all.all) {
security/landlock/ruleset.c +8 -8
@@ -32,7 +32,7 @@ static struct landlock_ruleset *create_ruleset(const u32 num_layers) {struct landlock_ruleset *new_ruleset; - new_ruleset =kzalloc_flex (*new_ruleset, access_masks, num_layers, + new_ruleset =kzalloc_flex (*new_ruleset, layers, num_layers,GFP_KERNEL_ACCOUNT );if (!new_ruleset)return ERR_PTR (-ENOMEM );
@@ -46,9 +46,9 @@ static struct landlock_ruleset *create_ruleset(const u32 num_layers) new_ruleset->num_layers = num_layers;/* -* hierarchy = NULL -* num_rules = 0 -* access_masks[] = 0 +* - hierarchy = NULL +* - num_rules = 0 +* - layers[] = 0 */ return new_ruleset; }
@@ -381,8 +381,8 @@ static int merge_ruleset(struct landlock_ruleset *const dst, err = -EINVAL ; goto out_unlock; } - dst->access_masks[dst->num_layers -1 ] = -landlock_upgrade_handled_access_masks (src->access_masks[0 ]); + dst->layers[dst->num_layers -1 ] = +landlock_upgrade_handled_layer_config (src->layers[0 ]);/* Merges the @src inode tree. */ err =merge_tree (dst, src,LANDLOCK_KEY_INODE );
@@ -464,8 +464,8 @@ static int inherit_ruleset(struct landlock_ruleset *const parent, goto out_unlock; }/* Copies the parent layer stack and leaves a space for the new layer. */ -memcpy (child->access_masks, parent->access_masks, -flex_array_size (parent, access_masks, parent->num_layers)); +memcpy (child->layers, parent->layers, +flex_array_size (parent, layers, parent->num_layers));if (WARN_ON_ONCE (!parent->hierarchy)) { err = -EINVAL ;
security/landlock/ruleset.h +19 -18
@@ -145,8 +145,8 @@ struct landlock_ruleset {* @work_free: Enables to free a ruleset within a lockless * section. This is only used by * landlock_put_ruleset_deferred() when @usage reaches zero. -* The fields @lock, @usage, @num_rules, @num_layers and -* @access_masks are then unused. +* The fields @lock, @usage, @num_rules, @num_layers and @layers +* are then unused. */ struct work_struct work_free;struct {
@@ -173,18 +173,18 @@ struct landlock_ruleset {*/ u32 num_layers;/** -* @access_masks: Contains the subset of filesystem and -* network actions that are restricted by a ruleset. +* @layers: Per-layer access configuration, including +* handled access masks and allowed permission bitmasks. * A domain saves all layers of merged rulesets in a * stack (FAM), starting from the first layer to the * last one. These layers are used when merging -* rulesets, for user space backward compatibility -* (i.e. future-proof), and to properly handle merged -* rulesets without overlapping access rights. These -* layers are set once and never changed for the -* lifetime of the ruleset. +* rulesets, for user space backward compatibility (i.e. +* future-proof), and to properly handle merged rulesets +* without overlapping access rights. These layers are +* set once and never changed for the lifetime of the +* ruleset. */ -struct access_masks access_masks[]; + struct layer_config layers[] __counted_by(num_layers); }; }; };
@@ -224,7 +224,8 @@ static inline void landlock_get_ruleset(struct landlock_ruleset *const ruleset)* * @domain: Landlock ruleset (used as a domain) * -* Return: An access_masks result of the OR of all the domain's access masks. +* Return: An access_masks result of the OR of all the domain's handled access +* masks. */ static inline struct access_masks landlock_union_access_masks (const struct landlock_ruleset *const domain)
@@ -234,7 +235,7 @@ landlock_union_access_masks(const struct landlock_ruleset *const domain)for (layer_level =0 ; layer_level < domain->num_layers; layer_level++) {union access_masks_all layer = { - .masks = domain->access_masks[layer_level], + .masks = domain->layers[layer_level].handled, }; matches.all |= layer.all;
@@ -252,7 +253,7 @@ landlock_add_fs_access_mask(struct landlock_ruleset *const ruleset,/* Should already be checked in sys_landlock_create_ruleset(). */ WARN_ON_ONCE (fs_access_mask != fs_mask); - ruleset->access_masks[layer_level].fs |= fs_mask; + ruleset->layers[layer_level].handled.fs |= fs_mask; } static inline void
@@ -264,7 +265,7 @@ landlock_add_net_access_mask(struct landlock_ruleset *const ruleset,/* Should already be checked in sys_landlock_create_ruleset(). */ WARN_ON_ONCE (net_access_mask != net_mask); - ruleset->access_masks[layer_level].net |= net_mask; + ruleset->layers[layer_level].handled.net |= net_mask; } static inline void
@@ -275,7 +276,7 @@ landlock_add_scope_mask(struct landlock_ruleset *const ruleset,/* Should already be checked in sys_landlock_create_ruleset(). */ WARN_ON_ONCE (scope_mask != mask); - ruleset->access_masks[layer_level].scope |= mask; + ruleset->layers[layer_level].handled.scope |= mask; } static inline access_mask_t
@@ -283,7 +284,7 @@ landlock_get_fs_access_mask(const struct landlock_ruleset *const ruleset, const u16 layer_level) {/* Handles all initially denied by default access rights. */ -return ruleset->access_masks[layer_level].fs | +return ruleset->layers[layer_level].handled.fs | _LANDLOCK_ACCESS_FS_INITIALLY_DENIED; }
@@ -291,14 +292,14 @@ static inline access_mask_t landlock_get_net_access_mask(const struct landlock_ruleset *const ruleset, const u16 layer_level) { - return ruleset->access_masks[layer_level].net; + return ruleset->layers[layer_level].handled.net; }static inline access_mask_t landlock_get_scope_mask (const struct landlock_ruleset *const ruleset,const u16 layer_level) { -return ruleset->access_masks[layer_level].scope; +return ruleset->layers[layer_level].handled.scope; } bool landlock_unmask_layers(const struct landlock_rule *const rule,
security/landlock/syscalls.c +1 -1
@@ -341,7 +341,7 @@ static int add_rule_path_beneath(struct landlock_ruleset *const ruleset,return -ENOMSG ;/* Checks that allowed_access matches the @ruleset constraints. */ - mask = ruleset->access_masks[0 ].fs; + mask = ruleset->layers[0 ].handled.fs;if ((path_beneath_attr.allowed_access | mask) != mask)return -EINVAL ;
Signature · 1 line
2.54.0
Mickaël Salaün
maintainerPATCH v2 4/9 landlock: Enforce namespace use restrictions
In reply to Mickaël SalaünAdd Landlock enforcement for namespace use via the LSM namespace_init and namespace_install hooks. This lets a sandboxed process restrict which namespace types it can acquire, using LANDLOCK_PERM_NAMESPACE_USE and per-type rules.
Introduce the handled_perm field in struct landlock_ruleset_attr for per-category permissions: each permission gates all uses of a kernel-defined category (CLONE_NEW* for namespace types, CAP_* for capabilities) and provides complete deny-by-default coverage of category members. Rule values reference constants from other kernel subsystems (CLONE_NEW* for namespaces); unknown values are silently accepted because the allow-list denies them by default. See the "Ruleset restriction models" section in the kernel documentation for the full design rationale.
Depends on commit 935a04923ad2 ("nsproxy: Add FOR_EACH_NS_TYPE() X-macro and CLONE_NS_ALL") for the FOR_EACH_NS_TYPE() macro used to enumerate known namespace types and the CLONE_NS_ALL mask used to validate namespace_types bitmasks.
Both hooks share check_ns_type(): if the namespace's CLONE_NEW* type is not in the layer's allowed set, the operation is denied. No domain ancestry bypass, no namespace creator tracking, just a flat per-layer allowed-types bitmask.
- hook_namespace_init() fires during unshare(CLONE_NEW*) and clone(CLONE_NEW*) via __ns_common_init().
- hook_namespace_install() fires during setns() via validate_ns().
Both record namespace_type and ns_id in the audit data; ns_id is zero at allocation time and logged as such.
Add the perm_masks bitfield to struct layer_config (introduced by a preceding commit) to store per-layer namespace type bitmasks; the name parallels the sibling access_masks. The 8-bit NS field maps to the 8 known namespace types via landlock_ns_type_to_bit(), keeping the storage compact. struct perm_masks is __packed __aligned(sizeof(u64)) to guarantee consistent layout across architectures: on m68k, GCC packs bitfields at byte granularity without __packed, so a u64 bitfield struct can be smaller than sizeof(u64).
LANDLOCK_RULE_NAMESPACE uses struct landlock_namespace_attr with an allowed_perm field (matching the pattern of allowed_access in existing rule types) and a namespace_types bitmask of CLONE_NEW* flags. Unknown namespace type bits are silently accepted for forward compatibility; they have no effect since the allow-list denies by default. The allowed_perm field reserves room for future sub-permissions within a rule type without a UAPI break, and acts as a type discriminant at the syscall boundary: rejecting mismatches with -EINVAL catches struct misuse even when rule attribute structs share the same wire format.
User namespace creation does not require capabilities, so Landlock can restrict it directly. Non-user namespace types require CAP_SYS_ADMIN before the Landlock check is reached; when both LANDLOCK_PERM_NAMESPACE_USE and LANDLOCK_PERM_CAPABILITY_USE are handled, both must allow the operation.
Five KUnit tests verify the landlock_ns_type_to_bit() and landlock_ns_types_to_bits() conversion helpers.
Depends-on: 935a04923ad2 ("nsproxy: Add FOR_EACH_NS_TYPE() X-macro and CLONE_NS_ALL")
---
Changes since v1:
https://lore.kernel.org/r/[email protected]
- Add __packed __aligned(sizeof(u64)) to struct perm_masks to fix static_assert failure on m68k, where GCC packs bitfields at byte granularity.
- Use ns_id instead of inum in namespace audit records.
- Add WARN_ON_ONCE guards for invalid perm_bit or request_value in landlock_perm_is_denied(), denying with the youngest layer on invalid input (suggested by Tingmao Wang).
- Fix double backtick in landlock_perm_is_denied() kernel-doc.
- Add Reviewed-by: Tingmao Wang.
- Mention commit 935a04923ad2 ("nsproxy: Add FOR_EACH_NS_TYPE() X-macro and CLONE_NS_ALL") as a dependency in the body and add
Depends-on: trailer.
- Rename internal struct perm_rules to perm_masks to parallel the sibling access_masks in struct layer_config.
- Document the allowed_perm design rationale (extensibility for future sub-permissions, type discriminant safeguard).
- Rename LANDLOCK_PERM_NAMESPACE_ENTER to LANDLOCK_PERM_NAMESPACE_USE and audit blocker perm.namespace_enter to perm.namespace_use for semantic accuracy. The verb _ENTER fits setns/unshare/clone (caller becomes namespace member) but misleads for open_tree and fsmount (caller holds an fd reference, does not enter). _USE covers both cases and mirrors LANDLOCK_PERM_CAPABILITY_USE. Update the commit title accordingly.
- Replace "chokepoint"/"gateway" prose in @handled_perm kdoc and the Permission flags DOC block with the per-category framing.
- Expand the LANDLOCK_PERM_NAMESPACE_USE kdoc to enumerate creation (unshare/clone/clone3), joining (setns), and fd-reference (open_tree/fsmount) paths.
- Rewrite the commit body to drop chokepoint/gateway terminology in favour of per-category framing, matching the doc rewrite.
- Rename struct layer_rights to struct layer_config (companion change to the introducing commit).
- Surface the empty-check semantics in the landlock_namespace_attr.namespace_types kdoc: a rule that sets only bits unknown to the running kernel succeeds but has no runtime effect.
- Cascade the LSM hook rename namespace_alloc -> namespace_init (LSM_HOOK_INIT registration and local handler hook_namespace_alloc -> hook_namespace_init), companion change to the introducing commit.
- Rename the static helper landlock_check_ns_type() to check_ns_type():
the landlock_ prefix is reserved for non-static symbols exported via headers; file-static helpers follow the prefix-free convention used in security/landlock/.
- Add Reviewed-by: Günther Noack.
--- include/uapi/linux/landlock.h | 62 +++++++++++++- security/landlock/Makefile | 3 +- security/landlock/access.h | 40 ++++++++- security/landlock/audit.c | 4 + security/landlock/audit.h | 1 + security/landlock/cred.h | 49 +++++++++++ security/landlock/limits.h | 7 ++ security/landlock/ns.c | 156 ++++++++++++++++++++++++++++++++++ security/landlock/ns.h | 73 ++++++++++++++++ security/landlock/ruleset.c | 11 +-- security/landlock/ruleset.h | 25 +++++- security/landlock/setup.c | 2 + security/landlock/syscalls.c | 68 ++++++++++++++- 13 files changed, 484 insertions(+), 17 deletions(-) create mode 100644 security/landlock/ns.c create mode 100644 security/landlock/ns.h
include/uapi/linux/landlock.h +61 -1
@@ -51,6 +51,15 @@ struct landlock_ruleset_attr {* resources (e.g. IPCs). */ __u64 scoped; +/** +* @handled_perm: Bitmask of permissions (cf. `Permission flags`_) that +* this ruleset handles. Each permission controls a per-category +* operation gated by an enum (CLONE_NEW* for namespace types, CAP_* for +* capabilities); all uses of category members are denied unless +* explicitly allowed by a rule. See +* Documentation/security/landlock.rst for the rationale. +*/ +__u64 handled_perm; };/**
@@ -155,6 +164,10 @@ enum landlock_rule_type {* landlock_net_port_attr . */ LANDLOCK_RULE_NET_PORT , +/** +* @LANDLOCK_RULE_NAMESPACE: Type of a &struct landlock_namespace_attr . +*/ + LANDLOCK_RULE_NAMESPACE, };/**
@@ -208,6 +221,27 @@ struct landlock_net_port_attr {__u64 port; }; +/** +* struct landlock_namespace_attr - Namespace type definition +* +* Argument of sys_landlock_add_rule() with %LANDLOCK_RULE_NAMESPACE. +*/ +struct landlock_namespace_attr { +/** +* @allowed_perm: Must be set to %LANDLOCK_PERM_NAMESPACE_USE. +*/ +__u64 allowed_perm; +/** +* @namespace_types: Bitmask of namespace types (``CLONE_NEW*`` flags) +* to allow under this rule. Must be non-zero (otherwise the call +* returns ``-ENOMSG``); the non-zero check runs on the raw input before +* unknown-bit masking, so a rule that sets only bits unknown to the +* running kernel succeeds but has no runtime effect. Unknown bits are +* silently ignored for forward compatibility. +*/ +__u64 namespace_types; +}; +/** * DOC: fs_access *
@@ -431,6 +465,32 @@ struct landlock_net_port_attr {/* clang-format off */ #define LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET (1ULL << 0)#define LANDLOCK_SCOPE_SIGNAL (1ULL << 1) -/* clang-format on*/ +/* clang-format on */ + +/** +* DOC: perm +* +* Permission flags +* ~~~~~~~~~~~~~~~~ +* +* These flags restrict per-category operations gated by enums (CLONE_NEW* for +* namespace types, CAP_* for capabilities). Each flag covers every kernel path +* that exercises a member of the category. Handled permissions that are not +* explicitly allowed by a rule are denied by default. Rule values reference +* constants from other kernel subsystems; unknown values are silently accepted +* for forward compatibility since the allow-list denies them by default. See +* Documentation/security/landlock.rst for design details. +* +* - %LANDLOCK_PERM_NAMESPACE_USE: Restrict the use of specific namespace +* types -- creation (:manpage:`unshare(2)`, :manpage:`clone(2)`, +* :manpage:`clone3(2)`), joining (:manpage:`setns(2)`), and acquiring an +* fd reference (:manpage:`open_tree(2)`, :manpage:`fsmount(2)`). A +* process in a Landlock domain that handles this permission is denied +* from using namespace types that are not explicitly allowed by a +* %LANDLOCK_RULE_NAMESPACE rule. +*/ +/* clang-format off */ +#define LANDLOCK_PERM_NAMESPACE_USE (1ULL << 0) +/* clang-format on */ #endif /* _UAPI_LINUX_LANDLOCK_H */
security/landlock/Makefile +2 -1
@@ -8,7 +8,8 @@ landlock-y := \ cred.o \ task.o \ fs.o \ - tsync.o + tsync.o \ + ns.o landlock-$(CONFIG_INET) += net.o
security/landlock/access.h +37 -3
@@ -42,6 +42,8 @@ static_assert(BITS_PER_TYPE(access_mask_t) >= LANDLOCK_NUM_ACCESS_FS);static_assert (BITS_PER_TYPE (access_mask_t) >=LANDLOCK_NUM_ACCESS_NET );/* Makes sure all scoped rights can be stored. */ static_assert (BITS_PER_TYPE (access_mask_t) >=LANDLOCK_NUM_SCOPE ); +/* Makes sure all permission types can be stored. */ +static_assert (BITS_PER_TYPE (access_mask_t) >=LANDLOCK_NUM_PERM );/* Makes sure for_each_set_bit() and for_each_clear_bit() calls are OK. */ static_assert (sizeof (unsigned long ) >=sizeof (access_mask_t));
@@ -50,6 +52,7 @@ struct access_masks { access_mask_t fs : LANDLOCK_NUM_ACCESS_FS; access_mask_t net : LANDLOCK_NUM_ACCESS_NET; access_mask_t scope : LANDLOCK_NUM_SCOPE; + access_mask_t perm : LANDLOCK_NUM_PERM; } __packed__aligned(sizeof(u32)) ;union access_masks_all {
@@ -61,14 +64,45 @@ union access_masks_all {static_assert (sizeof (typeof_member (union access_masks_all ,masks )) ==sizeof (typeof_member (union access_masks_all ,all ))); +/** +* struct perm_masks - Per-layer allowed bitmasks for permission types +* +* Compact bitfield struct holding the allowed bitmasks for permission types +* that use flat (non-tree) per-layer storage. All fields share a single 64-bit +* storage unit. +*/ +struct perm_masks { +/** +* @ns: Allowed namespace types. Each bit corresponds to a sequential +* index assigned by the ``_LANDLOCK_NS_*`` enum (derived from +* ``FOR_EACH_NS_TYPE``). Bits are converted from ``CLONE_NEW*`` flags +* at rule-add time via ``landlock_ns_types_to_bits()`` and at +* enforcement time via ``landlock_ns_type_to_bit()``. +*/ +u64 ns :LANDLOCK_NUM_PERM_NS ; +} __packed__aligned(sizeof(u64)) ; + +static_assert (sizeof (struct perm_masks ) ==sizeof (u64)); +/** * struct layer_config - Per-layer access configuration * -* Wraps the handled-access bitfields together with any additional per-layer -* data (e.g. allowed bitmasks added by future patches). This is the element -* type of the &struct landlock_ruleset.layers FAM. +* Wraps the handled-access bitfields together with per-layer allowed bitmasks. +* This is the element type of the &struct landlock_ruleset.layers FAM. +* +* Unlike filesystem and network access rights, which are tracked per-object in +* red-black trees, namespace types use a flat bitmask because their keyspace is +* small and bounded (~8 namespace types). A single rule adds to the allowed +* set via bitwise OR; at enforcement time each layer is checked directly (no +* tree lookup needed). */ struct layer_config { +/** +* @allowed: Per-layer allowed bitmasks for permission types. Placed +* before @handled to avoid an internal padding hole (8-byte perm_masks +* followed by 4-byte access_masks). +*/ +struct perm_masks allowed;/** * @handled: Bitmask of access rights handled (i.e. restricted) by this * layer.
security/landlock/audit.c +4 -0
@@ -82,6 +82,10 @@ get_blocker(const enum landlock_request_type type,case LANDLOCK_REQUEST_SCOPE_SIGNAL :WARN_ON_ONCE (access_bit !=-1 );return "scope.signal" ; + +case LANDLOCK_REQUEST_NAMESPACE : +WARN_ON_ONCE (access_bit !=-1 ); +return "perm.namespace_use" ; }WARN_ON_ONCE (1 );
security/landlock/audit.h +1 -0
@@ -21,6 +21,7 @@ enum landlock_request_type {LANDLOCK_REQUEST_NET_ACCESS ,LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET ,LANDLOCK_REQUEST_SCOPE_SIGNAL , + LANDLOCK_REQUEST_NAMESPACE, };/*
security/landlock/cred.h +49 -0
55 lines not on this page · raw message
security/landlock/limits.h +7 -0
@@ -12,6 +12,7 @@#include <linux/bitops.h> #include <linux/limits.h> +#include <linux/ns/ns_common_types.h> #include <uapi/linux/landlock.h> /* clang-format off */
@@ -31,6 +32,12 @@#define LANDLOCK_MASK_SCOPE ((LANDLOCK_LAST_SCOPE << 1) - 1)#define LANDLOCK_NUM_SCOPE __const_hweight64(LANDLOCK_MASK_SCOPE) +#define LANDLOCK_LAST_PERM LANDLOCK_PERM_NAMESPACE_USE +#define LANDLOCK_MASK_PERM ((LANDLOCK_LAST_PERM << 1) - 1) +#define LANDLOCK_NUM_PERM __const_hweight64(LANDLOCK_MASK_PERM) + +#define LANDLOCK_NUM_PERM_NS __const_hweight64((u64)(CLONE_NS_ALL)) +#define LANDLOCK_LAST_RESTRICT_SELF LANDLOCK_RESTRICT_SELF_TSYNC#define LANDLOCK_MASK_RESTRICT_SELF ((LANDLOCK_LAST_RESTRICT_SELF << 1) - 1)
security/landlock/ns.c new file +156 -0
156 lines not on this page · raw message
security/landlock/ns.h new file +73 -0
73 lines not on this page · raw message
security/landlock/ruleset.c +6 -5
@@ -53,15 +53,14 @@ static struct landlock_ruleset *create_ruleset(const u32 num_layers)return new_ruleset; } -struct landlock_ruleset * -landlock_create_ruleset (const access_mask_t fs_access_mask, -const access_mask_t net_access_mask, -const access_mask_t scope_mask) +struct landlock_ruleset *landlock_create_ruleset ( +const access_mask_t fs_access_mask,const access_mask_t net_access_mask, +const access_mask_t scope_mask,const access_mask_t perm_mask) {struct landlock_ruleset *new_ruleset;/* Informs about useless ruleset. */ -if (!fs_access_mask && !net_access_mask && !scope_mask) +if (!fs_access_mask && !net_access_mask && !scope_mask && !perm_mask)return ERR_PTR (-ENOMSG ); new_ruleset =create_ruleset (1 );if (IS_ERR (new_ruleset))
@@ -72,6 +71,8 @@ landlock_create_ruleset(const access_mask_t fs_access_mask,landlock_add_net_access_mask (new_ruleset, net_access_mask,0 );if (scope_mask)landlock_add_scope_mask (new_ruleset, scope_mask,0 ); +if (perm_mask) +landlock_add_perm_mask (new_ruleset, perm_mask,0 );return new_ruleset; }
security/landlock/ruleset.h +21 -4
@@ -189,10 +189,9 @@ struct landlock_ruleset { }; }; -struct landlock_ruleset * -landlock_create_ruleset (const access_mask_t access_mask_fs, -const access_mask_t access_mask_net, -const access_mask_t scope_mask); +struct landlock_ruleset *landlock_create_ruleset ( +const access_mask_t access_mask_fs,const access_mask_t access_mask_net, +const access_mask_t scope_mask,const access_mask_t perm_mask);void landlock_put_ruleset (struct landlock_ruleset *const ruleset);void landlock_put_ruleset_deferred (struct landlock_ruleset *const ruleset);
@@ -302,6 +301,24 @@ landlock_get_scope_mask(const struct landlock_ruleset *const ruleset,return ruleset->layers[layer_level].handled.scope; } +static inline void +landlock_add_perm_mask (struct landlock_ruleset *const ruleset, +const access_mask_t perm_mask,const u16 layer_level) +{ +access_mask_t mask = perm_mask &LANDLOCK_MASK_PERM ; + +/* Should already be checked in sys_landlock_create_ruleset(). */ +WARN_ON_ONCE (perm_mask != mask); + ruleset->layers[layer_level].handled.perm |= mask; +} + +static inline access_mask_t +landlock_get_perm_mask (const struct landlock_ruleset *const ruleset, +const u16 layer_level) +{ +return ruleset->layers[layer_level].handled.perm; +} +bool landlock_unmask_layers (const struct landlock_rule *const rule,struct layer_access_masks *masks);
security/landlock/setup.c +2 -0
@@ -17,6 +17,7 @@#include "fs.h" #include "id.h" #include "net.h" +#include "ns.h" #include "setup.h" #include "task.h"
@@ -68,6 +69,7 @@ static int __init landlock_init(void)landlock_add_task_hooks ();landlock_add_fs_hooks ();landlock_add_net_hooks (); +landlock_add_ns_hooks ();landlock_init_id (); landlock_initialized = true;pr_info ("Up and running.\n" );
security/landlock/syscalls.c +65 -3
127 lines not on this page · raw message
Signature · 1 line
2.54.0
Mickaël Salaün
maintainerPATCH v2 5/9 landlock: Enforce capability restrictions
In reply to Mickaël SalaünAdd Landlock enforcement for capability use via the LSM capable hook. This lets a sandboxed process restrict which Linux capabilities it can exercise, using LANDLOCK_PERM_CAPABILITY_USE and per-capability rules.
The capable hook is purely restrictive: commoncap is registered with LSM_ORDER_FIRST so cap_capable() always runs first, which means Landlock can deny capabilities that commoncap would allow but never grant capabilities that commoncap denied.
Add hook_capable() that uses landlock_perm_is_denied() to perform a pure bitmask check: if the capability is not in the layer's allowed set, the check is denied. No domain ancestry bypass, no cross-namespace discriminant, just a flat per-layer allowed-caps bitmask, matching the same pattern used by LANDLOCK_PERM_NAMESPACE_USE.
Adding the 41-bit capability bitfield to struct perm_masks brings it to 49 out of 64 bits used (41 caps + 8 namespace types, 15 bits padding), keeping struct layer_config at 16 bytes (8 bytes perm_masks + 4 bytes access_masks + 4 bytes tail padding) and the layers[] array at 256 bytes maximum. The caps bitfield is placed first in struct perm_masks (before the ns bitfield) because capabilities use a direct BIT_ULL(cap) mapping that benefits from starting at bit 0 of the storage unit. An explicit static_assert documents the LANDLOCK_NUM_PERM_CAP + LANDLOCK_NUM_PERM_NS <= BITS_PER_TYPE(u64) invariant alongside the existing sizeof guard.
Non-user namespace operations require both LANDLOCK_PERM_NAMESPACE_USE (type allowed) and LANDLOCK_PERM_CAPABILITY_USE (CAP_SYS_ADMIN allowed) when both permissions are handled. This follows naturally from the kernel calling capable(CAP_SYS_ADMIN) before namespace operations: both hooks fire independently and audit logs identify which permission was denied.
The enforcement is purely at exercise time via the capable hook, not by modifying the credential's capability sets. Stripping denied capabilities would give processes an accurate capget(2) view of their usable capabilities, but no LSM other than commoncap modifies capability sets; Landlock follows this convention and restricts use without altering what the process holds. A sandboxed process inside a user namespace will see all capabilities via capget(2) but will receive -EPERM when attempting to use any denied capability.
---
Changes since v1:
https://lore.kernel.org/r/[email protected]
- Add Reviewed-by: Tingmao Wang.
- Rename internal struct perm_rules to perm_masks (companion change to the preceding commit).
- Rename LANDLOCK_PERM_NAMESPACE_ENTER references to LANDLOCK_PERM_NAMESPACE_USE (companion change to the introducing commit).
- Rename struct layer_rights to struct layer_config (companion change to the introducing commit).
- Clarify in the commit body and hook_capable() kdoc that commoncap (not Landlock) is registered with LSM_ORDER_FIRST.
- Surface the empty-check semantics in the landlock_capability_attr.capabilities kdoc: a rule that sets only bits unknown to the running kernel (above CAP_LAST_CAP) succeeds but has no runtime effect.
- Add explicit static_assert that LANDLOCK_NUM_PERM_CAP + LANDLOCK_NUM_PERM_NS fits in a u64, complementing the existing implicit sizeof guard on struct perm_masks.
- Add Reviewed-by: Günther Noack.
--- include/uapi/linux/landlock.h | 35 +++++++++ security/landlock/Makefile | 3 +- security/landlock/access.h | 18 ++++- security/landlock/audit.c | 4 + security/landlock/audit.h | 1 + security/landlock/cap.c | 141 ++++++++++++++++++++++++++++++++++ security/landlock/cap.h | 49 ++++++++++++ security/landlock/cred.h | 3 + security/landlock/limits.h | 4 +- security/landlock/setup.c | 2 + security/landlock/syscalls.c | 58 +++++++++++++- 11 files changed, 309 insertions(+), 9 deletions(-) create mode 100644 security/landlock/cap.c create mode 100644 security/landlock/cap.h
include/uapi/linux/landlock.h +35 -0
@@ -168,6 +168,11 @@ enum landlock_rule_type {* @LANDLOCK_RULE_NAMESPACE: Type of a &struct landlock_namespace_attr . */ LANDLOCK_RULE_NAMESPACE , +/** +* @LANDLOCK_RULE_CAPABILITY: Type of a &struct +* landlock_capability_attr . +*/ + LANDLOCK_RULE_CAPABILITY, };/**
@@ -242,6 +247,28 @@ struct landlock_namespace_attr {__u64 namespace_types; }; +/** +* struct landlock_capability_attr - Capability definition +* +* Argument of sys_landlock_add_rule() with %LANDLOCK_RULE_CAPABILITY. +*/ +struct landlock_capability_attr { +/** +* @allowed_perm: Must be set to %LANDLOCK_PERM_CAPABILITY_USE. +*/ +__u64 allowed_perm; +/** +* @capabilities: Bitmask of capabilities (``1ULL << CAP_*``) to allow +* under this rule. Must be non-zero (otherwise the call returns +* ``-ENOMSG``); the non-zero check runs on the raw input before +* unknown-bit masking, so a rule that sets only bits unknown to the +* running kernel (above ``CAP_LAST_CAP``) succeeds but has no runtime +* effect. Bits above ``CAP_LAST_CAP`` are silently ignored for forward +* compatibility. +*/ +__u64 capabilities; +}; +/** * DOC: fs_access *
@@ -488,9 +515,17 @@ struct landlock_namespace_attr {* process in a Landlock domain that handles this permission is denied * from using namespace types that are not explicitly allowed by a * %LANDLOCK_RULE_NAMESPACE rule. +* - %LANDLOCK_PERM_CAPABILITY_USE: Restrict the use of specific Linux +* capabilities. A process in a Landlock domain that handles this +* permission is denied from exercising capabilities that are not +* explicitly allowed by a %LANDLOCK_RULE_CAPABILITY rule. This hook +* is purely restrictive: it can deny capabilities that the kernel +* would otherwise grant, but it can never grant capabilities that the +* kernel already denied. */ /* clang-format off */ #define LANDLOCK_PERM_NAMESPACE_USE (1ULL << 0) +#define LANDLOCK_PERM_CAPABILITY_USE (1ULL << 1)/* clang-format on */ #endif /* _UAPI_LINUX_LANDLOCK_H */
security/landlock/Makefile +2 -1
@@ -9,7 +9,8 @@ landlock-y := \ task.o \ fs.o \ tsync.o \ - ns.o + ns.o \ + cap.o landlock-$(CONFIG_INET) += net.o
security/landlock/access.h +14 -4
@@ -72,6 +72,13 @@ static_assert(sizeof(typeof_member(union access_masks_all, masks)) ==* storage unit. */ struct perm_masks { +/** +* @caps: Allowed capabilities. Each bit corresponds to a ``CAP_*`` +* value (e.g. ``CAP_NET_RAW`` = bit 13). Bits are stored directly +* (sequential mapping) and masked with ``CAP_VALID_MASK`` at rule-add +* time. +*/ +u64 caps :LANDLOCK_NUM_PERM_CAP ;/** * @ns: Allowed namespace types. Each bit corresponds to a sequential * index assigned by the ``_LANDLOCK_NS_*`` enum (derived from
@@ -83,6 +90,9 @@ struct perm_masks { } __packed__aligned(sizeof(u64)) ;static_assert (sizeof (struct perm_masks ) ==sizeof (u64)); +/* All perm_masks bitfields must fit in a single u64. */ +static_assert (LANDLOCK_NUM_PERM_CAP +LANDLOCK_NUM_PERM_NS <= +BITS_PER_TYPE (u64));/** * struct layer_config - Per-layer access configuration
@@ -91,10 +101,10 @@ static_assert(sizeof(struct perm_masks) == sizeof(u64));* This is the element type of the &struct landlock_ruleset.layers FAM. * * Unlike filesystem and network access rights, which are tracked per-object in -* red-black trees, namespace types use a flat bitmask because their keyspace is -* small and bounded (~8 namespace types). A single rule adds to the allowed -* set via bitwise OR; at enforcement time each layer is checked directly (no -* tree lookup needed). +* red-black trees, namespace types and capabilities use flat bitmasks because +* their keyspaces are small and bounded (~8 namespace types, 41 capabilities). +* A single rule adds to the allowed set via bitwise OR; at enforcement time +* each layer is checked directly (no tree lookup needed). */ struct layer_config {/**
security/landlock/audit.c +4 -0
@@ -86,6 +86,10 @@ get_blocker(const enum landlock_request_type type,case LANDLOCK_REQUEST_NAMESPACE :WARN_ON_ONCE (access_bit !=-1 );return "perm.namespace_use" ; + +case LANDLOCK_REQUEST_CAPABILITY : +WARN_ON_ONCE (access_bit !=-1 ); +return "perm.capability_use" ; }WARN_ON_ONCE (1 );
security/landlock/audit.h +1 -0
@@ -22,6 +22,7 @@ enum landlock_request_type {LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET ,LANDLOCK_REQUEST_SCOPE_SIGNAL ,LANDLOCK_REQUEST_NAMESPACE , + LANDLOCK_REQUEST_CAPABILITY, };/*
security/landlock/cap.c new file +141 -0
141 lines not on this page · raw message
security/landlock/cap.h new file +49 -0
49 lines not on this page · raw message
security/landlock/cred.h +3 -0
@@ -191,6 +191,9 @@ landlock_perm_is_denied(const struct landlock_ruleset *const domain,case LANDLOCK_PERM_NAMESPACE_USE : allowed = domain->layers[layer].allowed.ns;break ; +case LANDLOCK_PERM_CAPABILITY_USE : + allowed = domain->layers[layer].allowed.caps; +break ;default :WARN_ON_ONCE (1 );return layer +1 ;
security/landlock/limits.h +3 -1
@@ -11,6 +11,7 @@#define _SECURITY_LANDLOCK_LIMITS_H#include <linux/bitops.h> +#include <linux/capability.h> #include <linux/limits.h> #include <linux/ns/ns_common_types.h> #include <uapi/linux/landlock.h>
@@ -32,11 +33,12 @@#define LANDLOCK_MASK_SCOPE ((LANDLOCK_LAST_SCOPE << 1) - 1)#define LANDLOCK_NUM_SCOPE __const_hweight64(LANDLOCK_MASK_SCOPE) -#define LANDLOCK_LAST_PERM LANDLOCK_PERM_NAMESPACE_USE +#define LANDLOCK_LAST_PERM LANDLOCK_PERM_CAPABILITY_USE#define LANDLOCK_MASK_PERM ((LANDLOCK_LAST_PERM << 1) - 1)#define LANDLOCK_NUM_PERM __const_hweight64(LANDLOCK_MASK_PERM)#define LANDLOCK_NUM_PERM_NS __const_hweight64((u64)(CLONE_NS_ALL)) +#define LANDLOCK_NUM_PERM_CAP (CAP_LAST_CAP + 1)#define LANDLOCK_LAST_RESTRICT_SELF LANDLOCK_RESTRICT_SELF_TSYNC#define LANDLOCK_MASK_RESTRICT_SELF ((LANDLOCK_LAST_RESTRICT_SELF << 1) - 1)
security/landlock/setup.c +2 -0
@@ -11,6 +11,7 @@#include <linux/lsm_hooks.h> #include <uapi/linux/lsm.h> +#include "cap.h" #include "common.h" #include "cred.h" #include "errata.h"
@@ -70,6 +71,7 @@ static int __init landlock_init(void)landlock_add_fs_hooks ();landlock_add_net_hooks ();landlock_add_ns_hooks (); +landlock_add_cap_hooks ();landlock_init_id (); landlock_initialized = true;pr_info ("Up and running.\n" );
security/landlock/syscalls.c +55 -3
95 lines not on this page · raw message
Signature · 1 line
2.54.0
Mickaël Salaün
maintainerPATCH v2 6/9 selftests/landlock: Add namespace restriction tests
In reply to Mickaël SalaünAdd tests covering the two namespace-related Landlock permission types:LANDLOCK_PERM_NAMESPACE_USE (namespace creation via unshare/clone and namespace entry via setns) and its interaction with LANDLOCK_PERM_CAPABILITY_USE.
Rule validation tests verify that the kernel correctly accepts known CLONE_NEW* types, silently accepts unknown bits (including holes, upper-range bits, and bit 63) for forward compatibility, and rejects an empty namespace_types bitmask. Invalid allowed_perm combinations and non-zero flags are also covered. A dedicated test asserts that a rule listing only unknown bits is accepted at rule-add time but has no runtime effect: an actual CLONE_NEW* operation is still denied by deny-by-default once the domain is enforced.
Namespace creation tests use FIXTURE_VARIANT to exercise all eight namespace types (user, UTS, IPC, mount, cgroup, PID, network, time) across allowed/denied and privileged/unprivileged combinations. This verifies that security_namespace_init() is correctly called for every type. Layer stacking tests verify that any-layer-denies semantics work correctly across the three combinations of per-layer allow/deny that exercise distinct walker paths (allow/deny, allow/allow, deny/allow). A combined test exercises both LANDLOCK_PERM_CAPABILITY_USE and LANDLOCK_PERM_NAMESPACE_USE in a single domain.
Namespace entry tests verify that setns is subject to the same type-based LANDLOCK_PERM_NAMESPACE_USE check via security_namespace_install(), including cross-process setns denial and the two-permission interaction where both LANDLOCK_PERM_NAMESPACE_USE and LANDLOCK_PERM_CAPABILITY_USE must allow the operation for non-user namespaces.
Mount-namespace fd-acquisition tests cover the four open_tree(2) and fsmount(2) variants that create a mount namespace:open_tree(OPEN_TREE_CLONE) and fsmount(FSMOUNT_CLOEXEC) for anonymous namespaces, and open_tree(OPEN_TREE_NAMESPACE) and fsmount(FSMOUNT_NAMESPACE) for new non-anonymous namespaces. All four converge in security_namespace_init() with CLONE_NEWNS and exercise different code paths through alloc_mnt_ns().
A multi-flag unshare test exercises a combined unshare with CLONE_NEWUSER | CLONE_NEWUTS under partial-allow rules, documenting the kernel's atomic behavior: namespace creation is sequential, and a Landlock denial on any type rolls back the whole syscall with EPERM.
Audit tests verify that denied namespace creation, denied setns entry, and allowed operations produce the expected audit records (or none).
---
Changes since v1:
https://lore.kernel.org/r/[email protected]
- Update audit test patterns: namespace_inum replaced by namespace_id.
- Fix user_denied.setns expected error: security_namespace_install() now runs before userns_install(), so Landlock returns EPERM before userns_install() returns EINVAL.
- Rename LANDLOCK_PERM_NAMESPACE_ENTER references to LANDLOCK_PERM_NAMESPACE_USE (companion change to the introducing commit).
- Add ns_proc_open fixture covering all 8 namespace types: verify that open("/proc/self/ns/<type>", O_RDONLY) does not trigger Landlock denial under LANDLOCK_PERM_NAMESPACE_USE. Defensive boundary documentation that the procfs ns/<type> open path is outside the per-category permission's scope; catches future regressions if a hook is misplaced.
- Add ns_mount_fd fixture covering open_tree(OPEN_TREE_CLONE), open_tree(OPEN_TREE_NAMESPACE), fsmount(FSMOUNT_CLOEXEC), and fsmount(FSMOUNT_NAMESPACE) with denied/allowed/unsandboxed variants. All four converge in security_namespace_init() with CLONE_NEWNS but exercise different code paths through alloc_mnt_ns().
- Add ns_create_multi_flag fixture covering a combined unshare with CLONE_NEWUSER | CLONE_NEWUTS under partial-allow rules: documents that any Landlock denial in the sequential namespace creation rolls back the entire syscall with EPERM.
- Reshape setns_cross_process variants: rename allowed to sandboxed_allowed and add an unsandboxed variant, so the fixture now covers denied, sandboxed_allowed, and unsandboxed.
- Add sys_open_tree, sys_fsopen, sys_fsconfig, sys_fsmount syscall wrappers in wrappers.h, and update fs_test.c to use sys_open_tree instead of its local open_tree wrapper.
- Rename comments referencing security_namespace_alloc() and hook_namespace_alloc() to security_namespace_init() and hook_namespace_init() (companion change to the LSM hook rename in the introducing commit).
- Document that setns_cross_process exercises only CLONE_NEWUTS:
the same enforcement applies to every namespace type via the unified hook_namespace_install() helper.
- Add add_rule_unknown_no_runtime_effect: assert that a rule listing only unknown namespace bits is accepted at rule-add time but has no runtime effect, so an actual CLONE_NEW* operation is still denied by deny-by-default once the domain is enforced.
- Add ns_stacking parent_denies variant covering the inverse direction of stacking: layer 1 denies, layer 2 allows, operation still denied. Completes the per-layer walker direction coverage.
--- tools/testing/selftests/landlock/common.h | 23 + tools/testing/selftests/landlock/config | 5 + tools/testing/selftests/landlock/fs_test.c | 13 +- tools/testing/selftests/landlock/ns_test.c | 1795 +++++++++++++++++++ tools/testing/selftests/landlock/wrappers.h | 29 + 5 files changed, 1855 insertions(+), 10 deletions(-) create mode 100644 tools/testing/selftests/landlock/ns_test.c
tools/testing/selftests/landlock/common.h +23 -0
@@ -128,6 +128,29 @@ static void __maybe_unused clear_ambient_cap(EXPECT_EQ (0 ,cap_get_ambient (cap)); } +/* +* Returns true if the current process is in the initial user namespace. +* Compares the readlink targets of /proc/self/ns/user and /proc/1/ns/user. +*/ +static bool __maybe_unused is_in_init_user_ns (void ) +{ +char self_buf[64 ], init_buf[64 ]; +ssize_t self_len, init_len; + + self_len =readlink ("/proc/self/ns/user" , self_buf,sizeof (self_buf)); +if (self_len <=0 || self_len >= (ssize_t )sizeof (self_buf)) +return false; + + init_len =readlink ("/proc/1/ns/user" , init_buf,sizeof (init_buf)); +if (init_len <=0 || init_len >= (ssize_t )sizeof (init_buf)) +return false; + +if (self_len != init_len) +return false; + +return memcmp (self_buf, init_buf, self_len) ==0 ; +} +/* Receives an FD from a UNIX socket. Returns the received FD, or -errno. */ static int __maybe_unused recv_fd (int usock) {
tools/testing/selftests/landlock/config +5 -0
@@ -3,6 +3,7 @@ CONFIG_AUDIT=y CONFIG_CGROUPS=y CONFIG_CGROUP_SCHED=y CONFIG_INET=y +CONFIG_IPC_NS=y CONFIG_IPV6=y CONFIG_KEYS=y CONFIG_MPTCP=y
@@ -10,10 +11,14 @@ CONFIG_MPTCP_IPV6=y CONFIG_NET=y CONFIG_NET_NS=y CONFIG_OVERLAY_FS=y +CONFIG_PID_NS=y CONFIG_PROC_FS=y CONFIG_SECURITY=y CONFIG_SECURITY_LANDLOCK=y CONFIG_SHMEM=y CONFIG_SYSFS=y +CONFIG_TIME_NS=y CONFIG_TMPFS=y CONFIG_TMPFS_XATTR=y +CONFIG_USER_NS=y +CONFIG_UTS_NS=y
tools/testing/selftests/landlock/fs_test.c +3 -10
@@ -54,13 +54,6 @@ int renameat2(int olddirfd, const char *oldpath, int newdirfd, }#endif -#ifndef open_tree -int open_tree (int dfd,const char *filename,unsigned int flags) -{ -return syscall (__NR_open_tree, dfd, filename, flags); -} -#endif -static int sys_execveat (int dirfd,const char *pathname,char *const argv[],char *const envp[],int flags) {
@@ -2454,9 +2447,9 @@ TEST_F_FORK(layout1, refer_mount_root_deny)/* Creates a mount object from a non-mount point. */ set_cap (_metadata,CAP_SYS_ADMIN ); - root_fd = -open_tree (AT_FDCWD , dir_s1d1, -AT_EMPTY_PATH |OPEN_TREE_CLONE |OPEN_TREE_CLOEXEC ); + root_fd =sys_open_tree (AT_FDCWD , dir_s1d1, +AT_EMPTY_PATH |OPEN_TREE_CLONE | +OPEN_TREE_CLOEXEC );clear_cap (_metadata,CAP_SYS_ADMIN );ASSERT_LE (0 , root_fd);
tools/testing/selftests/landlock/ns_test.c new file +1795 -0
1,795 lines not on this page · raw message
tools/testing/selftests/landlock/wrappers.h +29 -0
@@ -9,6 +9,7 @@#define _GNU_SOURCE#include <linux/landlock.h> +#include <linux/sched.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h>
@@ -45,3 +46,31 @@ static inline pid_t sys_gettid(void) {return syscall (__NR_gettid); } + +static inline pid_t sys_clone3 (struct clone_args *args,size_t size) +{ +return syscall (__NR_clone3, args, size); +} + +static inline int sys_open_tree (int dfd,const char *filename, +unsigned int flags) +{ +return syscall (__NR_open_tree, dfd, filename, flags); +} + +static inline int sys_fsopen (const char *fsname,unsigned int flags) +{ +return syscall (__NR_fsopen, fsname, flags); +} + +static inline int sys_fsconfig (int fs_fd,unsigned int cmd,const char *key, +const void *value,int aux) +{ +return syscall (__NR_fsconfig, fs_fd, cmd, key, value, aux); +} + +static inline int sys_fsmount (int fs_fd,unsigned int flags, +unsigned int attr_flags) +{ +return syscall (__NR_fsmount, fs_fd, flags, attr_flags); +}
Signature · 1 line
2.54.0
Mickaël Salaün
maintainerPATCH v2 7/9 selftests/landlock: Add capability restriction tests
In reply to Mickaël SalaünAdd tests to exercise LANDLOCK_PERM_CAPABILITY_USE enforcement. A sandboxed process is denied a handled capability when no rule grants it, and an explicit rule restores the capability. Unknown capability values above CAP_LAST_CAP are silently accepted at rule-add time but have no runtime effect, so deny-by-default still applies once the domain is enforced. Stacking variants cover the three per-layer combinations that exercise distinct walker paths (allow/deny, allow/allow, deny/allow) plus a mixed-layer case where one layer does not handle LANDLOCK_PERM_CAPABILITY_USE, forcing the walker to skip it. Invalid rule attributes (unknown flags, out-of-range values) return the expected errors.
Two tests exercise non-standard capability gain paths. The first enforces a domain via CAP_SYS_ADMIN (no_new_privs is not set) and verifies that denied capabilities are blocked even when still in the effective set. The second creates a user namespace under a Landlock domain to verify that capabilities gained through the kernel's user namespace ownership bypass (cap_capable_helper) are still restricted by the domain's rules.
Audit tests verify that a denied capability produces the expected audit record with the capability number, and that an allowed capability generates no denial record.
Test coverage for security/landlock is 91.6% of 2398 lines according to LLVM 22.
---
Changes since v1:
https://lore.kernel.org/r/[email protected]
- Reflow comments after check-linux.sh comment fixes.
- Rename LANDLOCK_PERM_NAMESPACE_ENTER references to LANDLOCK_PERM_NAMESPACE_USE and bump the abi_version expectation to 11 (companion changes to the introducing commit).
- Add add_rule_unknown_no_runtime_effect: assert that a rule listing only unknown capability bits is accepted at rule-add time but has no runtime effect, so an actual CAP_* exercise (sethostname with CAP_SYS_ADMIN) is still denied by deny-by-default once the domain is enforced.
- Add cap_stacking parent_denies variant covering the inverse direction of stacking: layer 1 denies CAP_SYS_ADMIN, layer 2 allows, capability still denied. Completes the per-layer walker direction coverage.
- Assert records.domain == 0 in cap_audit.allowed so the test also checks that no domain-allocation record is emitted when nothing is denied.
--- tools/testing/selftests/landlock/base_test.c | 18 + tools/testing/selftests/landlock/cap_test.c | 673 +++++++++++++++++++ 2 files changed, 691 insertions(+) create mode 100644 tools/testing/selftests/landlock/cap_test.c
tools/testing/selftests/landlock/base_test.c +18 -0
@@ -142,6 +142,24 @@ TEST(errata)ASSERT_EQ (EINVAL , errno); } +#define PERM_LAST LANDLOCK_PERM_CAPABILITY_USE + +TEST (ruleset_with_unknown_perm) +{ +__u64 perm_mask; + +for (perm_mask =1ULL <<63 ; perm_mask !=PERM_LAST ; perm_mask >>=1 ) { +struct landlock_ruleset_attr ruleset_attr = { + .handled_perm = perm_mask, + }; + +/* Unknown handled_perm values must be rejected. */ +ASSERT_EQ (-1 ,landlock_create_ruleset (&ruleset_attr, +sizeof (ruleset_attr),0 )); +ASSERT_EQ (EINVAL , errno); + } +} +/* Tests ordering of syscall argument checks. */ TEST (create_ruleset_checks_ordering) {
tools/testing/selftests/landlock/cap_test.c new file +673 -0
673 lines not on this page · raw message
Signature · 1 line
2.54.0
Mickaël Salaün
maintainerPATCH v2 8/9 samples/landlock: Add capability and namespace restriction support
In reply to Mickaël SalaünExtend the sandboxer sample to demonstrate the new Landlock capability and namespace restriction features. The LL_CAP environment variable takes a colon-delimited list of allowed capabilities, parsed with cap_from_name(3) from libcap. Names (e.g. "cap_sys_chroot", "CAP_SYS_ADMIN") are accepted; numeric strings (e.g. "18") work too via cap_from_name's internal numeric fallback. The LL_NS variable takes a colon-delimited list of allowed namespace types by short name (e.g. "user:uts:net"). Add best-effort degradation for older kernels that predate the LANDLOCK_PERM_* features.
Allow creating user and UTS namespaces but deny network namespaces (works as an unprivileged user). All capabilities are available (LL_CAP is not set), but namespace creation is still restricted to the types listed in LL_NS. The first command succeeds because user and UTS types are in the allowed set, and sets the hostname inside the new UTS namespace. The second command fails because the network namespace type is not allowed by the LANDLOCK_PERM_NAMESPACE_USE rule:
LL_FS_RO=/ LL_FS_RW=/proc LL_NS="user:uts" \
./sandboxer /bin/sh -c \
"unshare --user --uts --map-root-user hostname sandbox \
&& ! unshare --user --net true"Allow only user namespace creation and CAP_SYS_CHROOT, denying all other capabilities and namespace types (works as an unprivileged user). An unprivileged process creates a user namespace (no capability required) and calls chroot inside it using the CAP_SYS_CHROOT granted within the new namespace:
LL_FS_RO=/ LL_FS_RW="" LL_NS="user" LL_CAP="cap_sys_chroot" \
./sandboxer /bin/sh -c \
"unshare --user --keep-caps chroot / true"---
Changes since v1:
https://lore.kernel.org/r/[email protected]
- Rename LANDLOCK_PERM_NAMESPACE_ENTER references to LANDLOCK_PERM_NAMESPACE_USE (companion change to the introducing commit).
- Replace handled_perm = 0 with a per-bit mask in the ABI compat fall-through, mirroring the doc example so future ABI extensions adding new LANDLOCK_PERM_* bits do not get stripped.
- Parse LL_CAP values with cap_from_name(3) from libcap so users can pass capability names (e.g. "cap_sys_chroot") in addition to numbers. cap_from_name accepts both: the canonical name lookup is case-insensitive, and a numeric-string fallback maps "18" to CAP_SYS_CHROOT identically to the previous numeric-only path. Drop the BITS_PER_TYPE workaround and the manual numeric bound check (cap_from_name does the right thing in both cases). Link the sandboxer against libcap by adding userldlibs += -lcap in samples/landlock/Makefile. Update help text and example command to show capability names (suggested by Günther Noack).
- Rename the LL_CAPS env var to LL_CAP for consistency with the singular form of all other sandboxer env vars (LL_NS, LL_FS_RO, LL_FS_RW, LL_TCP_BIND, LL_TCP_CONNECT, LL_SCOPED, LL_FORCE_LOG). Internal symbols renamed accordingly: ENV_CAPS_NAME -> ENV_CAP_NAME, populate_ruleset_caps() -> populate_ruleset_cap().
- Tingmao Wang's v1 Reviewed-by is not carried forward to v2: the cap_from_name() / libcap migration is a material implementation change requested by Günther Noack that was not part of his review. Cc'd instead.
--- samples/landlock/Makefile | 1 + samples/landlock/sandboxer.c | 144 ++++++++++++++++++++++++++++++++++- 2 files changed, 142 insertions(+), 3 deletions(-)
samples/landlock/Makefile +1 -0
@@ -3,6 +3,7 @@ userprogs-always-y := sandboxer userccflags += -I usr/include +userldlibs += -lcap .PHONY: all clean
samples/landlock/sandboxer.c +141 -3
209 lines not on this page · raw message
Signature · 1 line
2.54.0
Mickaël Salaün
maintainerPATCH v2 9/9 landlock: Add documentation for capability and namespace restrictions
In reply to Mickaël SalaünDocument the two new Landlock permission categories in the userspace API guide, admin guide, and kernel security documentation.
The userspace API guide adds sections on capability restriction (LANDLOCK_PERM_CAPABILITY_USE with LANDLOCK_RULE_CAPABILITY) and namespace restriction (LANDLOCK_PERM_NAMESPACE_USE with LANDLOCK_RULE_NAMESPACE, covering creation, entry, and fd-reference acquisition), the backward-compatible degradation pattern for ABI < 10, and the per-namespace-type capability requirements.
The admin guide adds the new perm.namespace_use and perm.capability_use audit blocker names with their object identification fields (namespace_type, namespace_id, capability).
The kernel security documentation adds a "Ruleset restriction models" section defining the three models (handled_access_*, handled_perm, scoped), their coverage and compatibility properties, and the criteria for choosing between them for future features. It also documents composability with user namespaces and adds kernel-doc references for the new capability and namespace headers.
---
Changes since v1:
https://lore.kernel.org/r/[email protected]
The userspace API and security guides were revamped to match the v2 permission model: the previous chokepoints/gateways prose is replaced with the per-object (handled_access_*) versus per-category (handled_perm) framing, and a new Design philosophy section in the security guide states Landlock's principle (data, processes, kernel resources).
- Rename namespace_inum to namespace_id in audit field documentation to match the renamed audit field.
- Rename LANDLOCK_PERM_NAMESPACE_ENTER references to LANDLOCK_PERM_NAMESPACE_USE (companion change to the introducing commit), and enumerate the seven kernel paths it gates in the userspace API guide (membership via unshare/clone/clone3/setns; fd reference via open_tree/fsmount).
- Clarify that LANDLOCK_PERM_NAMESPACE_USE gates *acquisition* of namespace associations only (namespaces the process is already a member of when the domain is enforced are implicitly allowed) and that LANDLOCK_PERM_CAPABILITY_USE gates every exercise of a capability after the domain is enforced, regardless of how the capability was obtained.
- Document the rationale for accepting (rather than rejecting) unknown category member values in rule bodies: rejection would tie Landlock policy semantics to the running kernel's category-member set, making cross-kernel policies brittle. Acceptance is fail-safe in both directions and lets a policy activate as written when a value becomes real on a future kernel.
- Replace handled_perm = 0 with a per-bit mask in the userspace API guide's ABI compat fall-through, so future ABI extensions adding new LANDLOCK_PERM_* bits do not get stripped on the path that drops the v10 bits.
- Add a bridging sentence in the per-category permissions section of Documentation/security/landlock.rst contrasting per-category permissions with per-object access rights: per-category gates the prerequisite operation itself rather than restricting specific operations on a single resource instance (suggested by Günther Noack).
- Disambiguate the orthogonality invariant in Documentation/security/landlock.rst from the UAPI scoped field ("all new scoped features" -> "all Landlock access controls"; suggested by Justin Suess).
- Add an introductory paragraph in Documentation/userspace-api/landlock.rst contrasting LANDLOCK_PERM_CAPABILITY_USE with PR_SET_NO_NEW_PRIVS: NNP is the broader mechanism that blocks privilege acquisition via execve(2), while CAPABILITY_USE restricts the exercise of capabilities the process already holds (including those gained via CLONE_NEWUSER, which NNP does not block); sandboxes typically set both (suggested by Justin Suess).
- Disambiguate "category": object-side uses "object type" / "resource kind"; "category" stays for the per-category permissions model.
--- Documentation/admin-guide/LSM/landlock.rst | 19 +- Documentation/security/landlock.rst | 151 +++++++++++++- Documentation/userspace-api/landlock.rst | 216 +++++++++++++++++++-- 3 files changed, 367 insertions(+), 19 deletions(-)
Documentation/admin-guide/LSM/landlock.rst +15 -4
@@ -6,7 +6,7 @@ Landlock: system-wide management ================================ :Author: Mickaël Salaün -:Date: January 2026 +:Date: May 2026 Landlock can leverage the audit framework to log events.
@@ -59,14 +59,25 @@ AUDIT_LANDLOCK_ACCESS - scope.abstract_unix_socket - Abstract UNIX socket connection denied - scope.signal - Signal sending denied + **perm.*** - Permission restrictions (ABI 10+): + - perm.namespace_use - Namespace entry was denied (creation via + :manpage:`unshare(2)` / :manpage:`clone(2)` or joining via + :manpage:`setns(2)`); + ``namespace_type`` indicates the type (hex CLONE_NEW* bitmask), + ``namespace_id`` identifies the target namespace for + :manpage:`setns(2)` operations + - perm.capability_use - Capability use was denied; + ``capability`` indicates the capability number + Multiple blockers can appear in a single event (comma-separated) when multiple access rights are missing. For example, creating a regular file in a directory that lacks both ``make_reg`` and ``refer`` rights would show ``blockers=fs.make_reg,fs.refer``. - The object identification fields (path, dev, ino for filesystem; opid, - ocomm for signals) depend on the type of access being blocked and provide - context about what resource was involved in the denial. + The object identification fields depend on the type of access being blocked: + ``path``, ``dev``, ``ino`` for filesystem; ``opid``, ``ocomm`` for signals; + ``namespace_type`` and ``namespace_id`` for namespace operations; + ``capability`` for capability use. AUDIT_LANDLOCK_DOMAIN
Documentation/security/landlock.rst +150 -1
169 lines not on this page · raw message
Documentation/userspace-api/landlock.rst +202 -14
269 lines not on this page · raw message
Signature · 1 line
2.54.0
Re: [PATCH v2 9/9] landlock: Add documentation for capability and namespace restrictions
Quoted 143 lines · Mickaël Salaün
Document the two new Landlock permission categories in the userspace API guide, admin guide, and kernel security documentation.
The userspace API guide adds sections on capability restriction (
LANDLOCK_PERM_CAPABILITY_USEwithLANDLOCK_RULE_CAPABILITY) and namespace restriction (LANDLOCK_PERM_NAMESPACE_USEwithLANDLOCK_RULE_NAMESPACE, covering creation, entry, and fd-reference acquisition), the backward-compatible degradation pattern for ABI < 10, and the per-namespace-type capability requirements.The admin guide adds the new perm.namespace_use and perm.capability_use audit blocker names with their object identification fields (
namespace_type,namespace_id, capability).The kernel security documentation adds a "Ruleset restriction models" section defining the three models (handled_access_*,
handled_perm, scoped), their coverage and compatibility properties, and the criteria for choosing between them for future features. It also documents composability with user namespaces and adds kernel-doc references for the new capability and namespace headers.Cc Christian Brauner <[email protected]>Cc Günther Noack <[email protected]>Cc Paul Moore <[email protected]>Cc Serge E. Hallyn <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>---
Changes since v1:
https://lore.kernel.org/r/[email protected]The userspace API and security guides were revamped to match the v2 permission model: the previous chokepoints/gateways prose is replaced with the per-object (handled_access_*) versus per-category (
handled_perm) framing, and a new Design philosophy section in the security guide states Landlock's principle (data, processes, kernel resources).- Rename
namespace_inumtonamespace_idin audit field documentation to match the renamed audit field.
- RenameLANDLOCK_PERM_NAMESPACE_ENTERreferences toLANDLOCK_PERM_NAMESPACE_USE(companion change to the introducing commit), and enumerate the seven kernel paths it gates in the userspace API guide (membership via unshare/clone/clone3/setns; fd reference via open_tree/fsmount).
- Clarify thatLANDLOCK_PERM_NAMESPACE_USEgates *acquisition* of namespace associations only (namespaces the process is already a member of when the domain is enforced are implicitly allowed) and thatLANDLOCK_PERM_CAPABILITY_USEgates every exercise of a capability after the domain is enforced, regardless of how the capability was obtained.
- Document the rationale for accepting (rather than rejecting) unknown category member values in rule bodies: rejection would tie Landlock policy semantics to the running kernel's category-member set, making cross-kernel policies brittle. Acceptance is fail-safe in both directions and lets a policy activate as written when a value becomes real on a future kernel.
- Replacehandled_perm= 0 with a per-bit mask in the userspace API guide's ABI compat fall-through, so future ABI extensions adding new LANDLOCK_PERM_* bits do not get stripped on the path that drops the v10 bits.
- Add a bridging sentence in the per-category permissions section ofDocumentation/security/landlock.rstcontrasting per-category permissions with per-object access rights: per-category gates the prerequisite operation itself rather than restricting specific operations on a single resource instance (suggested by Günther Noack).
- Disambiguate the orthogonality invariant inDocumentation/security/landlock.rstfrom the UAPI scoped field ("all new scoped features" -> "all Landlock access controls"; suggested by Justin Suess).
- Add an introductory paragraph inDocumentation/userspace-api/landlock.rstcontrastingLANDLOCK_PERM_CAPABILITY_USEwithPR_SET_NO_NEW_PRIVS: NNP is the broader mechanism that blocks privilege acquisition via execve(2), whileCAPABILITY_USErestricts the exercise of capabilities the process already holds (including those gained viaCLONE_NEWUSER, which NNP does not block); sandboxes typically set both (suggested by Justin Suess).
- Disambiguate "category": object-side uses "object type" / "resource kind"; "category" stays for the per-category permissions model.--- Documentation/admin-guide/LSM/landlock.rst | 19 +- Documentation/security/landlock.rst | 151 +++++++++++++- Documentation/userspace-api/landlock.rst | 216 +++++++++++++++++++-- 3 files changed, 367 insertions(+), 19 deletions(-)Documentation/admin-guide/LSM/landlock.rst +15
-4@@ -6,7 +6,7 @@ Landlock: system-wide management ================================ :Author: Mickaël Salaün -:Date: January 2026 +:Date: May 2026 Landlock can leverage the audit framework to log events.@@ -59,14 +59,25 @@ AUDIT_LANDLOCK_ACCESS - scope.abstract_unix_socket - Abstract UNIX socket connection denied - scope.signal - Signal sending denied + **perm.*** - Permission restrictions (ABI 10+): + - perm.namespace_use - Namespace entry was denied (creation via + :manpage:`unshare(2)` / :manpage:`clone(2)` or joining via + :manpage:`setns(2)`); + ``namespace_type`` indicates the type (hex CLONE_NEW* bitmask), + ``namespace_id`` identifies the target namespace for + :manpage:`setns(2)` operations + - perm.capability_use - Capability use was denied; + ``capability`` indicates the capability number + Multiple blockers can appear in a single event (comma-separated) when multiple access rights are missing. For example, creating a regular file in a directory that lacks both ``make_reg`` and ``refer`` rights would show ``blockers=fs.make_reg,fs.refer``. - The object identification fields (path, dev, ino for filesystem; opid, - ocomm for signals) depend on the type of access being blocked and provide - context about what resource was involved in the denial. + The object identification fields depend on the type of access being blocked: + ``path``, ``dev``, ``ino`` for filesystem; ``opid``, ``ocomm`` for signals; + ``namespace_type`` and ``namespace_id`` for namespace operations; + ``capability`` for capability use. AUDIT_LANDLOCK_DOMAINDocumentation/security/landlock.rst +1
-1@@ -7,7 +7,7 @@ Landlock LSM: kernel documentation ================================== :Author: Mickaël Salaün -:Date: March 2026 +:Date: May 2026 Landlock's goal is to create scoped access-control (i.e. sandboxing). To harden a whole system, this feature should be available to any process,
Documentation/security/landlock.rst The reasoning is: · line 136
Quoted 8 lines
Documentation/security/landlock.rst +5
-0@@ -129,6 +129,143 @@ The reasoning is: restrictions, because access within the same scope is already allowed based on ``LANDLOCK_ACCESS_FS_RESOLVE_UNIX``. +Composability with user namespaces +---------------------------------- + +Landlock domain-based scoping and the kernel's user namespace-based capability +scoping enforce isolation over independent hierarchies.
Minor grammatical nit: "user namespace-based" is a bit hard to read because it reads like (user) (namespace-based), where it should be reading as (user namespace)-(based).
In my understanding after digging around, I believe the recommended approach is to use "user-namespace-based", or em-dashes, or simply rephrase it ("the kernel's capability scoping based on user namespaces").
Reference (6th question):
https://www.chicagomanualofstyle.org/qanda/data/faq/topics/HyphensEnDashesEmDashes.html#:~:text=But%20%E2%80%9Ctime%20clock%E2%80%9D%20is%20an%20open%20compound%2C%20so%20this%20seems%20contradictory
Quoted 11 lines
Documentation/security/landlock.rst +11
-0+Landlock checks domain +ancestry; the kernel's ``ns_capable()`` checks user namespace ancestry. These +hierarchies are orthogonal: Landlock enforcement is deterministic with respect +to its own configuration, regardless of namespace or capability state, and vice +versa. This orthogonality is a design invariant that must hold for all Landlock +access controls. + +Design philosophy +----------------- + +Landlock's goal is to restrict a sandboxed process's access to three kinds of
Documentation/security/landlock.rst The reasoning is:
Quoted 10 lines
Documentation/security/landlock.rst +10
-0+resources: data (files, sockets, pipes), other processes (signals, ptrace), and +kernel-internal resources whose use widens the kernel attack surface +(capabilities, namespace types). Each access right or permission gates one or +more operations that grant such access; restricting the operations is how +Landlock restricts the underlying access. + +When designing a new access control, identify the protected resource kind +first (data, processes, or kernel-internal resources). The operation set +follows from the protected resource: which kernel paths grant access to it, and +at which moment those paths can be gated.
Minor grammatical suggestion (a bit more verbose but maybe clearer):
The operations to restrict follow from the protected resource, by identifying which kernel code paths grant access to the resource and at which place in the code the access to the resource can be gated.
Documentation/security/landlock.rst The reasoning is: · line 159
Quoted 4 lines
Documentation/security/landlock.rst +4
-0+Do not design a permission around +"restrict the unshare(2) syscall" or similar mechanism-centric framings; design +it around "restrict the process from acquiring access to namespace types" (the +protected resource), letting the operation set follow.
I like the rewritten "design philosophy" section, this is much clearer than in V1. :)
Documentation/security/landlock.rst The reasoning is: · line 165
Quoted 5 lines
Documentation/security/landlock.rst +5
-0+Ruleset restriction models +-------------------------- + +Landlock provides three restriction models that differ in how rules identify the +resource being restricted.
Maybe add two paragraphs here to explain the commonalities as well, e.g.
In general, the ``struct landlock_ruleset_attr`` specifies the operations to be denied by default under the enforced policy.
The *rules* added to the ruleset define the exceptions to these restrictions, allow-listing specific conditions under which these operations are still permitted.
Documentation/security/landlock.rst The reasoning is:
Quoted 7 lines
Documentation/security/landlock.rst +7
-0+Per-object access rights (``handled_access_*``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Per-object access rights control operations on a specific resource instance, +identified in the rule key by a value drawn from an open-ended space: a file +hierarchy referenced by ``parent_fd``, or a network port identified by its +16-bit number.
(New paragraph here?)
Documentation/security/landlock.rst The reasoning is: · line 175
Quoted 2 lines
Documentation/security/landlock.rst +2
-0+ Each ``handled_access_*`` field declares a set of access rights +that the ruleset restricts.
Minor suggestion:
Each ``handled_access_*`` field declares a set of access rights, operations which are to be denied by default once the ruleset is enforced.
(New paragraph here?)
Documentation/security/landlock.rst The reasoning is: · line 179
Quoted 8 lines
Documentation/security/landlock.rst +7
-0+The rule body declares which of the multiple +distinct operations on that object instance are allowed (open, read, write, +truncate; bind, connect). +New operations on an existing rule type extend the +corresponding ``handled_access_*`` field (e.g. a new filesystem operation +extends ``handled_access_fs``). A new object type with multiple fine-grained +operations would use a new ``handled_access_*`` field.
Suggestion:
Operations are grouped by object type in the respective ``handled_access_*`` field. When a future version of Landlock introduces a new operation for an existing object type, it is added to the existing ``handled_access_*`` field for that object type. When Landlock adds a new object type, a new ``handled_access_*`` field for that object type is added.
Documentation/security/landlock.rst The reasoning is: · line 189
Quoted 10 lines
Documentation/security/landlock.rst +10
-0+ +Per-category permissions (``handled_perm``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Per-category permissions control the process's exercise of category members, +where the category is a small kernel-defined enumeration (a Linux capability +number ``CAP_*``, a namespace type ``CLONE_NEW*``). Unlike per-object access +rights, which restrict specific operations on a single resource instance, +per-category permissions gate the prerequisite operation itself (exercising a +capability, acquiring a namespace), so gating it transitively covers a broad set
^^^^^^^^^
"entering"?Documentation/security/landlock.rst The reasoning is: · line 194
Quoted 1 line
Documentation/security/landlock.rst +1
-0+of downstream operations.
(New paragraph here?)
Documentation/security/landlock.rst The reasoning is:
Quoted 10 lines
Documentation/security/landlock.rst +10
-0+These category members are the LSM-level +access-control objects (the entities the process is authorized against) even +though they are enum values rather than externally-instantiated kernel data +structures. Per-category permissions apply where the controlled operation +collapses to "may the process use this category member at all" (use a +capability; acquire a namespace), so the rule body lists which category members +the process may exercise; each ``LANDLOCK_PERM_*`` flag maps to its own rule +type and covers every kernel path that exercises a member. When a ruleset +handles a permission, all uses of category members are denied unless explicitly +allowed by a rule.
Nit: It feels that "Each LANDLOCK_PERM_* flag maps to its own rule type" is one of the most important sentences here, and I'd maybe move that at the beginning of a paragraph to make it a bit more prominent.
(New paragraph here?)
Quoted 16 lines
Documentation/security/landlock.rst +15
-0+See Documentation/userspace-api/landlock.rst for the +concrete syscall paths covered by each permission. + +The category enum is owned by the corresponding kernel subsystem (capabilities, +namespaces, etc.). Userspace policy authors query category member availability +via the relevant non-Landlock interfaces: + +* For capabilities: ``<linux/capability.h>``, + ``/proc/sys/kernel/cap_last_cap``, ``prctl(PR_CAPBSET_READ)``. +* For namespaces: ``<linux/sched.h>``, ``/proc/$$/ns/*``, + :manpage:`unshare(2)` runtime probe. + +The Landlock ABI version does not encode this availability; ABI versioning +describes which Landlock features (rule types, access rights, scopes, +permissions) the kernel implements, not which category members the kernel knows
Documentation/security/landlock.rst The reasoning is: · line 223
Quoted 10 lines
Documentation/security/landlock.rst +10
-0+about. + +Forward compatibility for new category members follows a simple rule set: + +* New members in future kernels are automatically denied: rules whitelist + specific values, and a member not in any rule is denied. +* Kernel-side compatibility for split categories is handled by the owning + subsystem (e.g., when ``CAP_BPF`` was split from ``CAP_SYS_ADMIN``, the + kernel kept checking either capability, so a rule denying ``CAP_SYS_ADMIN`` + continues to deny operations gated by ``CAP_SYS_ADMIN || CAP_BPF`` patterns).
This is not clear to me; a rule is not denying anything, because rules only allow things. Did you mean to write "a rule allowing CAP_SYS_ADMIN continues to allow operations gated by "CAP_SYS_ADMIN || CAP_BPF"?
After CAP_BPF was split off of CAP_SYS_ADMIN, either one of these two capabilities is now sufficient for the operation guarded by it.
Quoted 92 lines
Documentation/security/landlock.rst +57
-0+* Unknown values in the rule body are silently accepted rather than rejected. + Rejecting them would tie Landlock policy semantics to the running kernel's + category-member set: a rule built against future headers would fail to load + on older kernels, forcing policy authors to know each kernel's enumeration. + Acceptance is fail-safe in both directions: a rule referring to a value the + running kernel does not yet know has no effect (deny-by-default still applies + to that operation), and a rule written against future headers loads + identically across kernels so the same policy keeps the same restrictions. + When a value becomes real on a future kernel, the policy activates as written + by the author. +* In contrast, unknown ``LANDLOCK_PERM_*`` flags in ``handled_perm`` are + rejected (``-EINVAL``), since Landlock owns that bit space. + +Cross-domain scopes (``scoped``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Scopes restrict **cross-domain interactions** categorically, without rules. +Setting a scope flag (e.g. ``LANDLOCK_SCOPE_SIGNAL``) denies the operation to +targets outside the Landlock domain or its children. Like per-category +permissions, scopes provide complete coverage of the controlled operation. + +Choosing a model for a new feature +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +* If the new feature controls operations on resource objects supplied by the + sandbox author, extend or add a per-object access right + (``handled_access_*``). +* If the new feature controls a per-category operation gated by an enum (a + Linux capability, a namespace type, a socket family, etc.), use a + per-category permission (``handled_perm``). When several such enums could + classify the operation, prefer the enum the originating subsystem already + uses for capability/access checks (e.g. ``CAP_*`` for ``capable()`` hooks, + ``CLONE_NEW*`` for namespace hooks). +* When an operation is gated by multiple kernel-defined enums (a classic + example being ``CAP_SYS_ADMIN`` plus a ``CLONE_NEW*`` flag for non-user + namespace creation), define one per-category permission per enum dimension. + Sandbox authors handle each dimension's permission in ``handled_perm`` and + add rules for each; the kernel enforces each dimension at its own LSM hook. + ``LANDLOCK_PERM_NAMESPACE_USE`` and ``LANDLOCK_PERM_CAPABILITY_USE`` follow + this pattern. +* If the new feature restricts a categorical cross-domain interaction with no + per-target granularity, use a cross-domain scope (``scoped``). +* For all three models, confirm a single LSM hook (or small set of related + hooks) covers every kernel path that exercises the operation. + Tests =====@@ -150,6 +287,18 @@ Filesystem .. kernel-doc:: security/landlock/fs.h :identifiers: +Namespace +--------- + +.. kernel-doc:: security/landlock/ns.h + :identifiers: + +Capability +---------- + +.. kernel-doc:: security/landlock/cap.h + :identifiers: + Process credential ------------------Documentation/userspace-api/landlock.rst +6
-7@@ -29,20 +29,29 @@ If Landlock is not currently supported, we need to Landlock rules ============== -A Landlock rule describes an action on an object which the process intends to -perform. A set of rules is aggregated in a ruleset, which can then restrict -the thread enforcing it, and its future children. +A Landlock rule describes the actions a process is allowed to perform on a +specific resource. A set of rules is aggregated in a ruleset, which can then +restrict the thread enforcing it, and its future children. -The two existing types of rules are: +The existing types of rules are: Filesystem rules - For these rules, the object is a file hierarchy, - and the related filesystem actions are defined with - `filesystem access rights`. + The rule key is a file hierarchy, and the actions it allows are + defined with `filesystem access rights`.
Documentation/userspace-api/landlock.rst If Landlock is not currently supported, we need to · line 49
Quoted 10 lines
Documentation/userspace-api/landlock.rst +7
-2Network rules (since ABI v4) - For these rules, the object is a TCP port, - and the related actions are defined with `network access rights`. + The rule key is a TCP port, and the actions it allows are defined with + `network access rights`. + +Capability rules (since ABI v10) + The rule body lists which members of the Linux capability category + the process may exercise; the action is defined with `permission + flags`.
Suggestion:
The rule body lists which Linux capabilities the process may exercise; ...
(The notion of "category" was introduced in the design rationale, and would probably confuse me if I hadn't read that first.)
Documentation/userspace-api/landlock.rst If Landlock is not currently supported, we need to · line 54
Quoted 5 lines
Documentation/userspace-api/landlock.rst +5
-0+ +Namespace rules (since ABI v10) + The rule body lists which members of the namespace-type + category the process may use; the action is defined with `permission + flags`.
Similar here:
The rule body lists which namespace types the process may use; ...
Should it say "...the process may *enter*" instead? I noticed that you renamed the LANDLOCK_PERM_NAMESPACE_USE enum, but it's still about *entering* these namespaces, right? In a sense, a process is *using* each of these namespace types also during normal user lookup, file lookup etc, and that is all not restricted here.
Quoted 38 lines
Documentation/userspace-api/landlock.rst +18
-0Defining and enforcing a security policy ----------------------------------------@@ -85,6 +94,9 @@ to be explicit about the denied-by-default access rights. .scoped = LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | LANDLOCK_SCOPE_SIGNAL, + .handled_perm = + LANDLOCK_PERM_CAPABILITY_USE | + LANDLOCK_PERM_NAMESPACE_USE, }; Because we may not know which kernel version an application will be executed@@ -132,6 +144,11 @@ version, and only use the available subset of access rights: case 6 ... 8: /* Removes LANDLOCK_ACCESS_FS_RESOLVE_UNIX for ABI < 9 */ ruleset_attr.handled_access_fs &= ~LANDLOCK_ACCESS_FS_RESOLVE_UNIX; + __attribute__((fallthrough)); + case 9: + /* Removes LANDLOCK_PERM_* for ABI < 10 */ + ruleset_attr.handled_perm &= ~(LANDLOCK_PERM_NAMESPACE_USE | + LANDLOCK_PERM_CAPABILITY_USE); } This enables the creation of an inclusive ruleset that will contain our rules.@@ -202,6 +219,53 @@ number for a specific action: HTTPS connections. err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT, &net_port, 0); +Capability and namespace rules use a different attribute layout: +``allowed_perm`` identifies the permission category (a single +``LANDLOCK_PERM_*`` flag) and a type-specific value field carries the bitmask to +allow within it. See `Capability and namespace restrictions`_ for the model. + +For capability access-control, we can add rules that allow specific +capabilities. For instance, to allow ``CAP_SYS_CHROOT`` (so the sandboxed +process can call :manpage:`chroot(2)` inside a user namespace): + +.. code-block:: c
Documentation/userspace-api/landlock.rst number for a specific action: HTTPS connections. · line 241
Quoted 10 lines
Documentation/userspace-api/landlock.rst +10
-0+ + struct landlock_capability_attr cap_attr = { + .allowed_perm = LANDLOCK_PERM_CAPABILITY_USE, + .capabilities = (1ULL << CAP_SYS_CHROOT), + }; + + cap_attr.allowed_perm &= ruleset_attr.handled_perm; + if (cap_attr.allowed_perm) + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_CAPABILITY, + &cap_attr, 0);
I would suggest to cross-reference the capabilities(7) man page in this section, which lists the available CAP_* enum values.
Quoted 9 lines
Documentation/userspace-api/landlock.rst +9
-0+ +For namespace access-control, we can add rules that allow entering specific +namespace types (creating them via :manpage:`unshare(2)` / :manpage:`clone(2)` / +:manpage:`clone3(2)`, joining them via :manpage:`setns(2)`, or acquiring an fd +reference via :manpage:`open_tree(2)` / :manpage:`fsmount(2)`). For instance, +to allow creating user namespaces (which grants all capabilities inside the new +namespace): + +.. code-block:: c
Documentation/userspace-api/landlock.rst number for a specific action: HTTPS connections. · line 260
Quoted 10 lines
Documentation/userspace-api/landlock.rst +10
-0+ + struct landlock_namespace_attr ns_attr = { + .allowed_perm = LANDLOCK_PERM_NAMESPACE_USE, + .namespace_types = CLONE_NEWUSER, + }; + + ns_attr.allowed_perm &= ruleset_attr.handled_perm; + if (ns_attr.allowed_perm) + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NAMESPACE, + &ns_attr, 0);
Likewise cross-reference namespaces(7) in this section, as a reference for the available CLONE_* enum values?
Quoted 23 lines
Documentation/userspace-api/landlock.rst +13
-3+Together, these two rules allow an unprivileged process to create a user +namespace and call :manpage:`chroot(2)` inside it, while denying all other +capabilities and namespace types. User namespace creation is the one operation +that does not require ``CAP_SYS_ADMIN``, so no capability rule is needed for it. +See `Capability and namespace restrictions`_ for details on capability +requirements. + When passing a non-zero ``flags`` argument to ``landlock_restrict_self()``, a similar backwards compatibility check is needed for the restrict flags (see sys_landlock_restrict_self() documentation for available flags):@@ -380,9 +444,115 @@ The operations which can be scoped are: A :manpage:`sendto(2)` on a socket which was previously connected will not be restricted. This works for both datagram and stream sockets. -IPC scoping does not support exceptions via :manpage:`landlock_add_rule(2)`. -If an operation is scoped within a domain, no rules can be added to allow access -to resources or processes outside of the scope. +Scoping does not support exceptions via :manpage:`landlock_add_rule(2)`. If an +operation is scoped within a domain, no rules can be added to allow access to +resources or processes outside of the scope. + +Capability and namespace restrictions +-------------------------------------
Documentation/userspace-api/landlock.rst The operations which can be scoped are: · line 462
Quoted 10 lines
Documentation/userspace-api/landlock.rst +10
-0+ +``handled_perm`` declares per-category permissions: each permission selects +which members of a kernel-defined category (CAP_* capabilities, CLONE_NEW* +namespace types) the process may use. Unlike per-object access rights +(``handled_access_*``) or cross-domain scopes (``scoped``), per-category +permissions constrain the sandboxed process's own use of these enums; members +not allowed by a rule are denied by default. + +``LANDLOCK_PERM_NAMESPACE_USE`` gates *acquisition* of namespace +associations:
"*acquisition of access* to namespaces"?
In my understanding, it is not just "entering", which would make the NS ambiently available to a process, but also the implicit acquisition of a new namespace as it is happening under the hood for open_tree(2)?
Quoted 39 lines
Documentation/userspace-api/landlock.rst +39
-0+creation via :manpage:`unshare(2)` / :manpage:`clone(2)` +/ :manpage:`clone3(2)`, entry via :manpage:`setns(2)`, and fd-reference +acquisition via :manpage:`open_tree(2)` / :manpage:`fsmount(2)`. Namespaces +the process is already a member of when the domain is enforced are implicitly +allowed (the process could not continue running otherwise); rules describe which +new namespace types the process may acquire. ``LANDLOCK_PERM_CAPABILITY_USE`` +gates every exercise of a capability after the domain is enforced, regardless +of how the capability was obtained (inherited credentials, ``CLONE_NEWUSER`` +grant, ``setuid``/file-cap-bearing :manpage:`execve(2)`, etc.). Configuring +both together restricts what privileges are available *and* the namespaces in +which they take effect, which matters because user namespace creation has no +capability check and grants all capabilities within the new namespace: gating +only one of the two leaves a kernel attack-surface widening path open. + +``LANDLOCK_PERM_CAPABILITY_USE`` complements :manpage:`prctl(2)` +``PR_SET_NO_NEW_PRIVS`` but does not replace it. ``PR_SET_NO_NEW_PRIVS`` +prevents privilege *acquisition* via :manpage:`execve(2)` (setuid, file +capability xattrs, privilege-elevating LSM transitions) and is a prerequisite +for unprivileged Landlock self-sandboxing. ``LANDLOCK_PERM_CAPABILITY_USE`` +restricts *exercise* of capabilities the process already holds, including those +gained via ``CLONE_NEWUSER`` which ``PR_SET_NO_NEW_PRIVS`` does not block. +Sandboxes typically set both. + +Rules are added with ``LANDLOCK_RULE_CAPABILITY`` and &struct +landlock_capability_attr (each rule lists ``CAP_*`` values to allow), and with +``LANDLOCK_RULE_NAMESPACE`` and &struct landlock_namespace_attr (each rule +lists ``CLONE_NEW*`` flags to allow). Landlock is purely restrictive: it can +only deny what the traditional check would have allowed, never grant additional +privileges. + +Rule bodies silently accept values unknown to the current kernel (capabilities +above ``CAP_LAST_CAP``, unrecognised ``CLONE_NEW*`` bits): they have no runtime +effect, so a rule compiled against future kernel headers loads without error on +older kernels. Future kernels gain new members denied by default until a rule +explicitly allows them. + +The single ``LANDLOCK_PERM_NAMESPACE_USE`` bit gates every kernel path that +grants the calling process access to a namespace of the controlled types, +whether by becoming a member of the namespace or by holding a file descriptor
Documentation/userspace-api/landlock.rst The operations which can be scoped are: · line 510
Quoted 10 lines
Documentation/userspace-api/landlock.rst +10
-0+that references it. The covered syscall paths are: + +* :manpage:`unshare(2)` with ``CLONE_NEW*``: the caller becomes a member of a + newly-created namespace. +* :manpage:`clone(2)` (or :manpage:`clone3(2)`) with ``CLONE_NEW*``: the + child becomes a member of a newly-created namespace. +* :manpage:`setns(2)`: the caller becomes a member of an existing namespace + referenced by file descriptor. +* :manpage:`open_tree(2)` with ``OPEN_TREE_NAMESPACE``: the caller obtains a + file descriptor referring to a newly-created mount namespace.
(OPEN_TREE_NAMESPACE is not documented in the man page so far. Friendly nudge, Christian. :-))
Documentation/userspace-api/landlock.rst The operations which can be scoped are: · line 514
Quoted 4 lines
Documentation/userspace-api/landlock.rst +4
-0+* :manpage:`open_tree(2)` with ``OPEN_TREE_CLONE``: the caller obtains a file + descriptor referring to a newly-created anonymous mount namespace. +* :manpage:`fsmount(2)` with ``FSMOUNT_NAMESPACE``: the caller obtains a file + descriptor referring to a newly-created mount namespace.
(Ditto, it's not in the manpage; it's only getting introduced in 7.1, so I hope it will eventually still end up there.)
Quoted 73 lines
Documentation/userspace-api/landlock.rst +50
-2+* :manpage:`fsmount(2)` (default): the caller obtains a file descriptor + referring to a newly-created anonymous mount namespace. + +Anonymous mount namespaces (created by ``open_tree(OPEN_TREE_CLONE)`` and the +default :manpage:`fsmount(2)`) are intentionally covered by the bit even though +the calling process does not become a member of them. Without this coverage, a +sandboxed process could combine ``open_tree(OPEN_TREE_CLONE)`` with +:manpage:`move_mount(2)` to graft mounts from a freshly-allocated mount +namespace into its current namespace, bypassing the policy. + +In practice, unprivileged processes first create a user namespace (which +requires no capability and grants all capabilities within it), then use those +capabilities to create other namespace types. All non-user namespace types +require ``CAP_SYS_ADMIN`` for both creation and :manpage:`setns(2)` entry; mount +namespace entry additionally requires ``CAP_SYS_CHROOT``. For +:manpage:`setns(2)`, capabilities are checked relative to the target namespace, +so a process in an ancestor user namespace naturally satisfies them; this +includes joining user namespaces, which requires ``CAP_SYS_ADMIN``. When +``LANDLOCK_PERM_CAPABILITY_USE`` is also handled, each of these capabilities +must be explicitly allowed by a rule. + +When combining ``CLONE_NEWUSER`` with other ``CLONE_NEW*`` flags in a single +:manpage:`unshare(2)` call, the ``CAP_SYS_ADMIN`` check targets the newly +created user namespace, which is handled by ``LANDLOCK_PERM_NAMESPACE_USE`` +independently from ``LANDLOCK_PERM_CAPABILITY_USE``. Performing the user +namespace creation and the additional namespace creation in two separate +:manpage:`unshare(2)` calls requires a rule allowing ``CAP_SYS_ADMIN`` if the +domain also handles ``LANDLOCK_PERM_CAPABILITY_USE``. + +When creating child user namespaces, it is recommended to also create a +dedicated Landlock domain with restrictions relevant to each namespace context. + +Note that ``LANDLOCK_PERM_CAPABILITY_USE`` restricts the *use* of capabilities, +not their presence in the process's credential. Capability sets can change +after a domain is enforced through user namespace entry or :manpage:`capset(2)`; +privileged sandboxes that did not set ``PR_SET_NO_NEW_PRIVS`` may also gain +capabilities through :manpage:`execve(2)` of binaries with file capabilities. +In all cases, :manpage:`capget(2)` will report the credential's capability sets, +but any denied capability will fail with ``EPERM`` when exercised. Do not rely +on :manpage:`capget(2)` to determine whether the policy permits a given +capability; only the actual operation will return ``EPERM`` upon denial. Truncating files ----------------@@ -545,7 +715,7 @@ Access rights ------------- .. kernel-doc:: include/uapi/linux/landlock.h - :identifiers: fs_access net_access scope + :identifiers: fs_access net_access scope perm Creating a new ruleset ----------------------@@ -564,7 +734,8 @@ Extending a ruleset .. kernel-doc:: include/uapi/linux/landlock.h :identifiers: landlock_rule_type landlock_path_beneath_attr - landlock_net_port_attr + landlock_net_port_attr landlock_capability_attr + landlock_namespace_attr Enforcing a ruleset -------------------@@ -722,6 +893,23 @@ Starting with the Landlock ABI version 9, it is possible to restrict connections to pathname UNIX domain sockets (:manpage:`unix(7)`) using the new ``LANDLOCK_ACCESS_FS_RESOLVE_UNIX`` right. +Capability restriction (ABI < 10) +--------------------------------- + +Starting with the Landlock ABI version 10, it is possible to restrict +:manpage:`capabilities(7)` with the new ``LANDLOCK_PERM_CAPABILITY_USE`` +permission flag and ``LANDLOCK_RULE_CAPABILITY`` rule type.
Documentation/userspace-api/landlock.rst Starting with the Landlock ABI version 9, it is possible to restrict · line 911
Quoted 10 lines
Documentation/userspace-api/landlock.rst +10
-0+ +Namespace restriction (ABI < 10) +-------------------------------- + +Starting with the Landlock ABI version 10, it is possible to restrict namespace +use across creation (:manpage:`unshare(2)`, :manpage:`clone(2)`, +:manpage:`clone3(2)`), entry (:manpage:`setns(2)`), and fd-reference acquisition +(:manpage:`open_tree(2)`, :manpage:`fsmount(2)`) with the new +``LANDLOCK_PERM_NAMESPACE_USE`` permission flag and ``LANDLOCK_RULE_NAMESPACE`` +rule type.
This section would also benefit from a link to namespaces(7), which documents the list of different namespaces.
Quoted 7 lines
Documentation/userspace-api/landlock.rst +1
-0+ .. _kernel_support: Kernel supportSignature · 1 line
2.54.0
Overall, I have a fair amount of remarks here, but most of them are much more on the "suggestion" side -- this documentation is much clearer than in V1, IMHO. :)
–Günther
Mickaël Salaün
maintainerRe: [PATCH v2 9/9] landlock: Add documentation for capability and namespace restrictions
Quoted 147 lines · Günther Noack
Quoted 146 lines · Mickaël Salaün
Document the two new Landlock permission categories in the userspace API guide, admin guide, and kernel security documentation.
The userspace API guide adds sections on capability restriction (
LANDLOCK_PERM_CAPABILITY_USEwithLANDLOCK_RULE_CAPABILITY) and namespace restriction (LANDLOCK_PERM_NAMESPACE_USEwithLANDLOCK_RULE_NAMESPACE, covering creation, entry, and fd-reference acquisition), the backward-compatible degradation pattern for ABI < 10, and the per-namespace-type capability requirements.The admin guide adds the new perm.namespace_use and perm.capability_use audit blocker names with their object identification fields (
namespace_type,namespace_id, capability).The kernel security documentation adds a "Ruleset restriction models" section defining the three models (handled_access_*,
handled_perm, scoped), their coverage and compatibility properties, and the criteria for choosing between them for future features. It also documents composability with user namespaces and adds kernel-doc references for the new capability and namespace headers.Cc Christian Brauner <[email protected]>Cc Günther Noack <[email protected]>Cc Paul Moore <[email protected]>Cc Serge E. Hallyn <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>---
Changes since v1:
https://lore.kernel.org/r/[email protected]The userspace API and security guides were revamped to match the v2 permission model: the previous chokepoints/gateways prose is replaced with the per-object (handled_access_*) versus per-category (
handled_perm) framing, and a new Design philosophy section in the security guide states Landlock's principle (data, processes, kernel resources).- Rename
namespace_inumtonamespace_idin audit field documentation to match the renamed audit field.
- RenameLANDLOCK_PERM_NAMESPACE_ENTERreferences toLANDLOCK_PERM_NAMESPACE_USE(companion change to the introducing commit), and enumerate the seven kernel paths it gates in the userspace API guide (membership via unshare/clone/clone3/setns; fd reference via open_tree/fsmount).
- Clarify thatLANDLOCK_PERM_NAMESPACE_USEgates *acquisition* of namespace associations only (namespaces the process is already a member of when the domain is enforced are implicitly allowed) and thatLANDLOCK_PERM_CAPABILITY_USEgates every exercise of a capability after the domain is enforced, regardless of how the capability was obtained.
- Document the rationale for accepting (rather than rejecting) unknown category member values in rule bodies: rejection would tie Landlock policy semantics to the running kernel's category-member set, making cross-kernel policies brittle. Acceptance is fail-safe in both directions and lets a policy activate as written when a value becomes real on a future kernel.
- Replacehandled_perm= 0 with a per-bit mask in the userspace API guide's ABI compat fall-through, so future ABI extensions adding new LANDLOCK_PERM_* bits do not get stripped on the path that drops the v10 bits.
- Add a bridging sentence in the per-category permissions section ofDocumentation/security/landlock.rstcontrasting per-category permissions with per-object access rights: per-category gates the prerequisite operation itself rather than restricting specific operations on a single resource instance (suggested by Günther Noack).
- Disambiguate the orthogonality invariant inDocumentation/security/landlock.rstfrom the UAPI scoped field ("all new scoped features" -> "all Landlock access controls"; suggested by Justin Suess).
- Add an introductory paragraph inDocumentation/userspace-api/landlock.rstcontrastingLANDLOCK_PERM_CAPABILITY_USEwithPR_SET_NO_NEW_PRIVS: NNP is the broader mechanism that blocks privilege acquisition via execve(2), whileCAPABILITY_USErestricts the exercise of capabilities the process already holds (including those gained viaCLONE_NEWUSER, which NNP does not block); sandboxes typically set both (suggested by Justin Suess).
- Disambiguate "category": object-side uses "object type" / "resource kind"; "category" stays for the per-category permissions model.--- Documentation/admin-guide/LSM/landlock.rst | 19 +- Documentation/security/landlock.rst | 151 +++++++++++++- Documentation/userspace-api/landlock.rst | 216 +++++++++++++++++++-- 3 files changed, 367 insertions(+), 19 deletions(-)Documentation/admin-guide/LSM/landlock.rst +15
-4@@ -6,7 +6,7 @@ Landlock: system-wide management ================================ :Author: Mickaël Salaün -:Date: January 2026 +:Date: May 2026 Landlock can leverage the audit framework to log events.@@ -59,14 +59,25 @@ AUDIT_LANDLOCK_ACCESS - scope.abstract_unix_socket - Abstract UNIX socket connection denied - scope.signal - Signal sending denied + **perm.*** - Permission restrictions (ABI 10+): + - perm.namespace_use - Namespace entry was denied (creation via + :manpage:`unshare(2)` / :manpage:`clone(2)` or joining via + :manpage:`setns(2)`); + ``namespace_type`` indicates the type (hex CLONE_NEW* bitmask), + ``namespace_id`` identifies the target namespace for + :manpage:`setns(2)` operations + - perm.capability_use - Capability use was denied; + ``capability`` indicates the capability number + Multiple blockers can appear in a single event (comma-separated) when multiple access rights are missing. For example, creating a regular file in a directory that lacks both ``make_reg`` and ``refer`` rights would show ``blockers=fs.make_reg,fs.refer``. - The object identification fields (path, dev, ino for filesystem; opid, - ocomm for signals) depend on the type of access being blocked and provide - context about what resource was involved in the denial. + The object identification fields depend on the type of access being blocked: + ``path``, ``dev``, ``ino`` for filesystem; ``opid``, ``ocomm`` for signals; + ``namespace_type`` and ``namespace_id`` for namespace operations; + ``capability`` for capability use. AUDIT_LANDLOCK_DOMAINDocumentation/security/landlock.rst +1
-1@@ -7,7 +7,7 @@ Landlock LSM: kernel documentation ================================== :Author: Mickaël Salaün -:Date: March 2026 +:Date: May 2026 Landlock's goal is to create scoped access-control (i.e. sandboxing). To harden a whole system, this feature should be available to any process,@@ -129,6 +129,143 @@ The reasoning is: restrictions, because access within the same scope is already allowed based on ``LANDLOCK_ACCESS_FS_RESOLVE_UNIX``.
Quoted 9 lines
Documentation/security/landlock.rst The reasoning is:
Quoted 5 lines
Documentation/security/landlock.rst +5
-0+Composability with user namespaces +---------------------------------- + +Landlock domain-based scoping and the kernel's user namespace-based capability +scoping enforce isolation over independent hierarchies.Minor grammatical nit: "user namespace-based" is a bit hard to read because it reads like (user) (namespace-based), where it should be reading as (user namespace)-(based).
fixed
Quoted 8 lines
In my understanding after digging around, I believe the recommended approach is to use "user-namespace-based", or em-dashes, or simply rephrase it ("the kernel's capability scoping based on user namespaces").
Reference (6th question):
https://www.chicagomanualofstyle.org/qanda/data/faq/topics/HyphensEnDashesEmDashes.html#:~:text=But%20%E2%80%9Ctime%20clock%E2%80%9D%20is%20an%20open%20compound%2C%20so%20this%20seems%20contradictory
I'll go with the user-namespace-based.
Quoted 26 lines
Quoted 13 lines
Documentation/security/landlock.rst +11
-0+Landlock checks domain +ancestry; the kernel's ``ns_capable()`` checks user namespace ancestry. These +hierarchies are orthogonal: Landlock enforcement is deterministic with respect +to its own configuration, regardless of namespace or capability state, and vice +versa. This orthogonality is a design invariant that must hold for all Landlock +access controls. + +Design philosophy +----------------- + +Landlock's goal is to restrict a sandboxed process's access to three kinds ofDocumentation/security/landlock.rst The reasoning is:
Quoted 10 lines
Documentation/security/landlock.rst +10
-0+resources: data (files, sockets, pipes), other processes (signals, ptrace), and +kernel-internal resources whose use widens the kernel attack surface +(capabilities, namespace types). Each access right or permission gates one or +more operations that grant such access; restricting the operations is how +Landlock restricts the underlying access. + +When designing a new access control, identify the protected resource kind +first (data, processes, or kernel-internal resources). The operation set +follows from the protected resource: which kernel paths grant access to it, and +at which moment those paths can be gated.Minor grammatical suggestion (a bit more verbose but maybe clearer):
Quoted 3 lines
The operations to restrict follow from the protected resource, by identifying which kernel code paths grant access to the resource and at which place in the code the access to the resource can be gated.
ok
Quoted 9 lines
Documentation/security/landlock.rst The reasoning is: · line 159
Quoted 6 lines
Documentation/security/landlock.rst +4
-0+Do not design a permission around +"restrict the unshare(2) syscall" or similar mechanism-centric framings; design +it around "restrict the process from acquiring access to namespace types" (the +protected resource), letting the operation set follow.I like the rewritten "design philosophy" section, this is much clearer than in V1. :)
good :)
Quoted 11 lines
Documentation/security/landlock.rst The reasoning is: · line 165
Quoted 7 lines
Documentation/security/landlock.rst +5
-0+Ruleset restriction models +-------------------------- + +Landlock provides three restriction models that differ in how rules identify the +resource being restricted.Maybe add two paragraphs here to explain the commonalities as well, e.g.
Quoted 6 lines
In general, the ``struct landlock_ruleset_attr`` specifies the operations to be denied by default under the enforced policy.
The *rules* added to the ruleset define the exceptions to these restrictions, allow-listing specific conditions under which these operations are still permitted.
Ok, I added that.
Quoted 22 lines
Documentation/security/landlock.rst The reasoning is:
Quoted 9 lines
Documentation/security/landlock.rst +7
-0+Per-object access rights (``handled_access_*``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Per-object access rights control operations on a specific resource instance, +identified in the rule key by a value drawn from an open-ended space: a file +hierarchy referenced by ``parent_fd``, or a network port identified by its +16-bit number.(New paragraph here?)
Documentation/security/landlock.rst The reasoning is: · line 175
Quoted 2 lines
Documentation/security/landlock.rst +2
-0+ Each ``handled_access_*`` field declares a set of access rights +that the ruleset restricts.Minor suggestion:
Each ``handled_access_*`` field declares a set of access rights, operations which are to be denied by default once the ruleset is enforced.
(New paragraph here?)
Quoted 8 lines
Documentation/security/landlock.rst The reasoning is: · line 179
Quoted 8 lines
Documentation/security/landlock.rst +7
-0+The rule body declares which of the multiple +distinct operations on that object instance are allowed (open, read, write, +truncate; bind, connect). +New operations on an existing rule type extend the +corresponding ``handled_access_*`` field (e.g. a new filesystem operation +extends ``handled_access_fs``). A new object type with multiple fine-grained +operations would use a new ``handled_access_*`` field.
ok
Quoted 9 lines
Suggestion:
Operations are grouped by object type in the respective ``handled_access_*`` field. When a future version of Landlock introduces a new operation for an existing object type, it is added to the existing ``handled_access_*`` field for that object type. When Landlock adds a new object type, a new ``handled_access_*`` field for that object type is added.
ok
Quoted 34 lines
Documentation/security/landlock.rst The reasoning is: · line 189
Quoted 11 lines
Documentation/security/landlock.rst +10
-0+ +Per-category permissions (``handled_perm``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Per-category permissions control the process's exercise of category members, +where the category is a small kernel-defined enumeration (a Linux capability +number ``CAP_*``, a namespace type ``CLONE_NEW*``). Unlike per-object access +rights, which restrict specific operations on a single resource instance, +per-category permissions gate the prerequisite operation itself (exercising a +capability, acquiring a namespace), so gating it transitively covers a broad set^^^^^^^^^ "entering"?Documentation/security/landlock.rst The reasoning is: · line 194
Quoted 1 line
Documentation/security/landlock.rst +1
-0+of downstream operations.(New paragraph here?)
Documentation/security/landlock.rst The reasoning is:
Quoted 10 lines
Documentation/security/landlock.rst +10
-0+These category members are the LSM-level +access-control objects (the entities the process is authorized against) even +though they are enum values rather than externally-instantiated kernel data +structures. Per-category permissions apply where the controlled operation +collapses to "may the process use this category member at all" (use a +capability; acquire a namespace), so the rule body lists which category members +the process may exercise; each ``LANDLOCK_PERM_*`` flag maps to its own rule +type and covers every kernel path that exercises a member. When a ruleset +handles a permission, all uses of category members are denied unless explicitly +allowed by a rule.Nit: It feels that "Each LANDLOCK_PERM_* flag maps to its own rule type" is one of the most important sentences here, and I'd maybe move that at the beginning of a paragraph to make it a bit more prominent.
Quoted 1 line
(New paragraph here?)
ok
Quoted 24 lines
Quoted 24 lines
Documentation/security/landlock.rst +22
-0+See Documentation/userspace-api/landlock.rst for the +concrete syscall paths covered by each permission. + +The category enum is owned by the corresponding kernel subsystem (capabilities, +namespaces, etc.). Userspace policy authors query category member availability +via the relevant non-Landlock interfaces: + +* For capabilities: ``<linux/capability.h>``, + ``/proc/sys/kernel/cap_last_cap``, ``prctl(PR_CAPBSET_READ)``. +* For namespaces: ``<linux/sched.h>``, ``/proc/$$/ns/*``, + :manpage:`unshare(2)` runtime probe. + +The Landlock ABI version does not encode this availability; ABI versioning +describes which Landlock features (rule types, access rights, scopes, +permissions) the kernel implements, not which category members the kernel knows +about. + +Forward compatibility for new category members follows a simple rule set: + +* New members in future kernels are automatically denied: rules whitelist + specific values, and a member not in any rule is denied. +* Kernel-side compatibility for split categories is handled by the owning
Quoted 8 lines
Documentation/security/landlock.rst The reasoning is: · line 223
Quoted 3 lines
Documentation/security/landlock.rst +3
-0+ subsystem (e.g., when ``CAP_BPF`` was split from ``CAP_SYS_ADMIN``, the + kernel kept checking either capability, so a rule denying ``CAP_SYS_ADMIN`` + continues to deny operations gated by ``CAP_SYS_ADMIN || CAP_BPF`` patterns).This is not clear to me; a rule is not denying anything, because rules only allow things. Did you mean to write "a rule allowing
CAP_SYS_ADMINcontinues to allow operations gated by "CAP_SYS_ADMIN||CAP_BPF"?
Yep, my mistake due to a few rewordings.
Quoted 123 lines
After
CAP_BPFwas split off ofCAP_SYS_ADMIN, either one of these two capabilities is now sufficient for the operation guarded by it.Quoted 92 lines
Documentation/security/landlock.rst +57
-0+* Unknown values in the rule body are silently accepted rather than rejected. + Rejecting them would tie Landlock policy semantics to the running kernel's + category-member set: a rule built against future headers would fail to load + on older kernels, forcing policy authors to know each kernel's enumeration. + Acceptance is fail-safe in both directions: a rule referring to a value the + running kernel does not yet know has no effect (deny-by-default still applies + to that operation), and a rule written against future headers loads + identically across kernels so the same policy keeps the same restrictions. + When a value becomes real on a future kernel, the policy activates as written + by the author. +* In contrast, unknown ``LANDLOCK_PERM_*`` flags in ``handled_perm`` are + rejected (``-EINVAL``), since Landlock owns that bit space. + +Cross-domain scopes (``scoped``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Scopes restrict **cross-domain interactions** categorically, without rules. +Setting a scope flag (e.g. ``LANDLOCK_SCOPE_SIGNAL``) denies the operation to +targets outside the Landlock domain or its children. Like per-category +permissions, scopes provide complete coverage of the controlled operation. + +Choosing a model for a new feature +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +* If the new feature controls operations on resource objects supplied by the + sandbox author, extend or add a per-object access right + (``handled_access_*``). +* If the new feature controls a per-category operation gated by an enum (a + Linux capability, a namespace type, a socket family, etc.), use a + per-category permission (``handled_perm``). When several such enums could + classify the operation, prefer the enum the originating subsystem already + uses for capability/access checks (e.g. ``CAP_*`` for ``capable()`` hooks, + ``CLONE_NEW*`` for namespace hooks). +* When an operation is gated by multiple kernel-defined enums (a classic + example being ``CAP_SYS_ADMIN`` plus a ``CLONE_NEW*`` flag for non-user + namespace creation), define one per-category permission per enum dimension. + Sandbox authors handle each dimension's permission in ``handled_perm`` and + add rules for each; the kernel enforces each dimension at its own LSM hook. + ``LANDLOCK_PERM_NAMESPACE_USE`` and ``LANDLOCK_PERM_CAPABILITY_USE`` follow + this pattern. +* If the new feature restricts a categorical cross-domain interaction with no + per-target granularity, use a cross-domain scope (``scoped``). +* For all three models, confirm a single LSM hook (or small set of related + hooks) covers every kernel path that exercises the operation. + Tests =====@@ -150,6 +287,18 @@ Filesystem .. kernel-doc:: security/landlock/fs.h :identifiers: +Namespace +--------- + +.. kernel-doc:: security/landlock/ns.h + :identifiers: + +Capability +---------- + +.. kernel-doc:: security/landlock/cap.h + :identifiers: + Process credential ------------------Documentation/userspace-api/landlock.rst +6
-7@@ -29,20 +29,29 @@ If Landlock is not currently supported, we need to Landlock rules ============== -A Landlock rule describes an action on an object which the process intends to -perform. A set of rules is aggregated in a ruleset, which can then restrict -the thread enforcing it, and its future children. +A Landlock rule describes the actions a process is allowed to perform on a +specific resource. A set of rules is aggregated in a ruleset, which can then +restrict the thread enforcing it, and its future children. -The two existing types of rules are: +The existing types of rules are: Filesystem rules - For these rules, the object is a file hierarchy, - and the related filesystem actions are defined with - `filesystem access rights`. + The rule key is a file hierarchy, and the actions it allows are + defined with `filesystem access rights`.Documentation/userspace-api/landlock.rst If Landlock is not currently supported, we need to · line 49
Quoted 10 lines
Documentation/userspace-api/landlock.rst +7
-2Network rules (since ABI v4) - For these rules, the object is a TCP port, - and the related actions are defined with `network access rights`. + The rule key is a TCP port, and the actions it allows are defined with + `network access rights`. + +Capability rules (since ABI v10) + The rule body lists which members of the Linux capability category + the process may exercise; the action is defined with `permission + flags`.Suggestion:
The rule body lists which Linux capabilities the process may exercise; ...
(The notion of "category" was introduced in the design rationale, and would probably confuse me if I hadn't read that first.)
Documentation/userspace-api/landlock.rst If Landlock is not currently supported, we need to · line 54
Quoted 5 lines
Documentation/userspace-api/landlock.rst +5
-0+ +Namespace rules (since ABI v10) + The rule body lists which members of the namespace-type + category the process may use; the action is defined with `permission + flags`.Similar here:
Quoted 7 lines
The rule body lists which namespace types the process may use; ...
Should it say "...the process may *enter*" instead? I noticed that you renamed the
LANDLOCK_PERM_NAMESPACE_USEenum, but it's still about *entering* these namespaces, right? In a sense, a process is *using* each of these namespace types also during normal user lookup, file lookup etc, and that is all not restricted here.
As explained in the changelog of this patch:
LANDLOCK_PERM_NAMESPACE_USE gates *acquisition* of namespace associations only (namespaces the process is already a member of when the domain is enforced are implicitly allowed) and that LANDLOCK_PERM_CAPABILITY_USE gates every exercise of a capability after the domain is enforced, regardless of how the capability was obtained.
I realized that "enter" fits setns/unshare/clone, but not open_tree/fsmount which only use/update a namespace, as you also noticed below.
Quoted 45 lines
Quoted 45 lines
Documentation/userspace-api/landlock.rst +23
-0Defining and enforcing a security policy ----------------------------------------@@ -85,6 +94,9 @@ to be explicit about the denied-by-default access rights. .scoped = LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | LANDLOCK_SCOPE_SIGNAL, + .handled_perm = + LANDLOCK_PERM_CAPABILITY_USE | + LANDLOCK_PERM_NAMESPACE_USE, }; Because we may not know which kernel version an application will be executed@@ -132,6 +144,11 @@ version, and only use the available subset of access rights: case 6 ... 8: /* Removes LANDLOCK_ACCESS_FS_RESOLVE_UNIX for ABI < 9 */ ruleset_attr.handled_access_fs &= ~LANDLOCK_ACCESS_FS_RESOLVE_UNIX; + __attribute__((fallthrough)); + case 9: + /* Removes LANDLOCK_PERM_* for ABI < 10 */ + ruleset_attr.handled_perm &= ~(LANDLOCK_PERM_NAMESPACE_USE | + LANDLOCK_PERM_CAPABILITY_USE); } This enables the creation of an inclusive ruleset that will contain our rules.@@ -202,6 +219,53 @@ number for a specific action: HTTPS connections. err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT, &net_port, 0); +Capability and namespace rules use a different attribute layout: +``allowed_perm`` identifies the permission category (a single +``LANDLOCK_PERM_*`` flag) and a type-specific value field carries the bitmask to +allow within it. See `Capability and namespace restrictions`_ for the model. + +For capability access-control, we can add rules that allow specific +capabilities. For instance, to allow ``CAP_SYS_CHROOT`` (so the sandboxed +process can call :manpage:`chroot(2)` inside a user namespace): + +.. code-block:: c + + struct landlock_capability_attr cap_attr = { + .allowed_perm = LANDLOCK_PERM_CAPABILITY_USE, + .capabilities = (1ULL << CAP_SYS_CHROOT), + };
Quoted 8 lines
Documentation/userspace-api/landlock.rst number for a specific action: HTTPS connections. · line 241
Quoted 5 lines
Documentation/userspace-api/landlock.rst +5
-0+ + cap_attr.allowed_perm &= ruleset_attr.handled_perm; + if (cap_attr.allowed_perm) + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_CAPABILITY, + &cap_attr, 0);I would suggest to cross-reference the capabilities(7) man page in this section, which lists the available CAP_* enum values.
ok
Quoted 15 lines
Quoted 15 lines
Documentation/userspace-api/landlock.rst +14
-0+ +For namespace access-control, we can add rules that allow entering specific +namespace types (creating them via :manpage:`unshare(2)` / :manpage:`clone(2)` / +:manpage:`clone3(2)`, joining them via :manpage:`setns(2)`, or acquiring an fd +reference via :manpage:`open_tree(2)` / :manpage:`fsmount(2)`). For instance, +to allow creating user namespaces (which grants all capabilities inside the new +namespace): + +.. code-block:: c + + struct landlock_namespace_attr ns_attr = { + .allowed_perm = LANDLOCK_PERM_NAMESPACE_USE, + .namespace_types = CLONE_NEWUSER, + };
Quoted 8 lines
Documentation/userspace-api/landlock.rst number for a specific action: HTTPS connections. · line 260
Quoted 5 lines
Documentation/userspace-api/landlock.rst +5
-0+ + ns_attr.allowed_perm &= ruleset_attr.handled_perm; + if (ns_attr.allowed_perm) + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NAMESPACE, + &ns_attr, 0);Likewise cross-reference namespaces(7) in this section, as a reference for the available CLONE_* enum values?
ok
Quoted 38 lines
Quoted 25 lines
Documentation/userspace-api/landlock.rst +13
-3+Together, these two rules allow an unprivileged process to create a user +namespace and call :manpage:`chroot(2)` inside it, while denying all other +capabilities and namespace types. User namespace creation is the one operation +that does not require ``CAP_SYS_ADMIN``, so no capability rule is needed for it. +See `Capability and namespace restrictions`_ for details on capability +requirements. + When passing a non-zero ``flags`` argument to ``landlock_restrict_self()``, a similar backwards compatibility check is needed for the restrict flags (see sys_landlock_restrict_self() documentation for available flags):@@ -380,9 +444,115 @@ The operations which can be scoped are: A :manpage:`sendto(2)` on a socket which was previously connected will not be restricted. This works for both datagram and stream sockets. -IPC scoping does not support exceptions via :manpage:`landlock_add_rule(2)`. -If an operation is scoped within a domain, no rules can be added to allow access -to resources or processes outside of the scope. +Scoping does not support exceptions via :manpage:`landlock_add_rule(2)`. If an +operation is scoped within a domain, no rules can be added to allow access to +resources or processes outside of the scope. + +Capability and namespace restrictions +-------------------------------------Documentation/userspace-api/landlock.rst The operations which can be scoped are: · line 462
Quoted 10 lines
Documentation/userspace-api/landlock.rst +10
-0+ +``handled_perm`` declares per-category permissions: each permission selects +which members of a kernel-defined category (CAP_* capabilities, CLONE_NEW* +namespace types) the process may use. Unlike per-object access rights +(``handled_access_*``) or cross-domain scopes (``scoped``), per-category +permissions constrain the sandboxed process's own use of these enums; members +not allowed by a rule are denied by default. + +``LANDLOCK_PERM_NAMESPACE_USE`` gates *acquisition* of namespace +associations:"*acquisition of access* to namespaces"?
Quoted 3 lines
In my understanding, it is not just "entering", which would make the NS ambiently available to a process, but also the implicit acquisition of a new namespace as it is happening under the hood for
open_tree(2)?
Yes, hence the use of "use" for LANDLOCK_PERM_NAMESPACE_USE.
Quoted 141 lines
Quoted 40 lines
Documentation/userspace-api/landlock.rst +39
-0+creation via :manpage:`unshare(2)` / :manpage:`clone(2)` +/ :manpage:`clone3(2)`, entry via :manpage:`setns(2)`, and fd-reference +acquisition via :manpage:`open_tree(2)` / :manpage:`fsmount(2)`. Namespaces +the process is already a member of when the domain is enforced are implicitly +allowed (the process could not continue running otherwise); rules describe which +new namespace types the process may acquire. ``LANDLOCK_PERM_CAPABILITY_USE`` +gates every exercise of a capability after the domain is enforced, regardless +of how the capability was obtained (inherited credentials, ``CLONE_NEWUSER`` +grant, ``setuid``/file-cap-bearing :manpage:`execve(2)`, etc.). Configuring +both together restricts what privileges are available *and* the namespaces in +which they take effect, which matters because user namespace creation has no +capability check and grants all capabilities within the new namespace: gating +only one of the two leaves a kernel attack-surface widening path open. + +``LANDLOCK_PERM_CAPABILITY_USE`` complements :manpage:`prctl(2)` +``PR_SET_NO_NEW_PRIVS`` but does not replace it. ``PR_SET_NO_NEW_PRIVS`` +prevents privilege *acquisition* via :manpage:`execve(2)` (setuid, file +capability xattrs, privilege-elevating LSM transitions) and is a prerequisite +for unprivileged Landlock self-sandboxing. ``LANDLOCK_PERM_CAPABILITY_USE`` +restricts *exercise* of capabilities the process already holds, including those +gained via ``CLONE_NEWUSER`` which ``PR_SET_NO_NEW_PRIVS`` does not block. +Sandboxes typically set both. + +Rules are added with ``LANDLOCK_RULE_CAPABILITY`` and &struct +landlock_capability_attr (each rule lists ``CAP_*`` values to allow), and with +``LANDLOCK_RULE_NAMESPACE`` and &struct landlock_namespace_attr (each rule +lists ``CLONE_NEW*`` flags to allow). Landlock is purely restrictive: it can +only deny what the traditional check would have allowed, never grant additional +privileges. + +Rule bodies silently accept values unknown to the current kernel (capabilities +above ``CAP_LAST_CAP``, unrecognised ``CLONE_NEW*`` bits): they have no runtime +effect, so a rule compiled against future kernel headers loads without error on +older kernels. Future kernels gain new members denied by default until a rule +explicitly allows them. + +The single ``LANDLOCK_PERM_NAMESPACE_USE`` bit gates every kernel path that +grants the calling process access to a namespace of the controlled types, +whether by becoming a member of the namespace or by holding a file descriptorDocumentation/userspace-api/landlock.rst The operations which can be scoped are: · line 510
Quoted 10 lines
Documentation/userspace-api/landlock.rst +10
-0+that references it. The covered syscall paths are: + +* :manpage:`unshare(2)` with ``CLONE_NEW*``: the caller becomes a member of a + newly-created namespace. +* :manpage:`clone(2)` (or :manpage:`clone3(2)`) with ``CLONE_NEW*``: the + child becomes a member of a newly-created namespace. +* :manpage:`setns(2)`: the caller becomes a member of an existing namespace + referenced by file descriptor. +* :manpage:`open_tree(2)` with ``OPEN_TREE_NAMESPACE``: the caller obtains a + file descriptor referring to a newly-created mount namespace.(
OPEN_TREE_NAMESPACEis not documented in the man page so far. Friendly nudge, Christian. :-))Documentation/userspace-api/landlock.rst The operations which can be scoped are: · line 514
Quoted 4 lines
Documentation/userspace-api/landlock.rst +4
-0+* :manpage:`open_tree(2)` with ``OPEN_TREE_CLONE``: the caller obtains a file + descriptor referring to a newly-created anonymous mount namespace. +* :manpage:`fsmount(2)` with ``FSMOUNT_NAMESPACE``: the caller obtains a file + descriptor referring to a newly-created mount namespace.(Ditto, it's not in the manpage; it's only getting introduced in 7.1, so I hope it will eventually still end up there.)
Quoted 78 lines
Documentation/userspace-api/landlock.rst +55
-2+* :manpage:`fsmount(2)` (default): the caller obtains a file descriptor + referring to a newly-created anonymous mount namespace. + +Anonymous mount namespaces (created by ``open_tree(OPEN_TREE_CLONE)`` and the +default :manpage:`fsmount(2)`) are intentionally covered by the bit even though +the calling process does not become a member of them. Without this coverage, a +sandboxed process could combine ``open_tree(OPEN_TREE_CLONE)`` with +:manpage:`move_mount(2)` to graft mounts from a freshly-allocated mount +namespace into its current namespace, bypassing the policy. + +In practice, unprivileged processes first create a user namespace (which +requires no capability and grants all capabilities within it), then use those +capabilities to create other namespace types. All non-user namespace types +require ``CAP_SYS_ADMIN`` for both creation and :manpage:`setns(2)` entry; mount +namespace entry additionally requires ``CAP_SYS_CHROOT``. For +:manpage:`setns(2)`, capabilities are checked relative to the target namespace, +so a process in an ancestor user namespace naturally satisfies them; this +includes joining user namespaces, which requires ``CAP_SYS_ADMIN``. When +``LANDLOCK_PERM_CAPABILITY_USE`` is also handled, each of these capabilities +must be explicitly allowed by a rule. + +When combining ``CLONE_NEWUSER`` with other ``CLONE_NEW*`` flags in a single +:manpage:`unshare(2)` call, the ``CAP_SYS_ADMIN`` check targets the newly +created user namespace, which is handled by ``LANDLOCK_PERM_NAMESPACE_USE`` +independently from ``LANDLOCK_PERM_CAPABILITY_USE``. Performing the user +namespace creation and the additional namespace creation in two separate +:manpage:`unshare(2)` calls requires a rule allowing ``CAP_SYS_ADMIN`` if the +domain also handles ``LANDLOCK_PERM_CAPABILITY_USE``. + +When creating child user namespaces, it is recommended to also create a +dedicated Landlock domain with restrictions relevant to each namespace context. + +Note that ``LANDLOCK_PERM_CAPABILITY_USE`` restricts the *use* of capabilities, +not their presence in the process's credential. Capability sets can change +after a domain is enforced through user namespace entry or :manpage:`capset(2)`; +privileged sandboxes that did not set ``PR_SET_NO_NEW_PRIVS`` may also gain +capabilities through :manpage:`execve(2)` of binaries with file capabilities. +In all cases, :manpage:`capget(2)` will report the credential's capability sets, +but any denied capability will fail with ``EPERM`` when exercised. Do not rely +on :manpage:`capget(2)` to determine whether the policy permits a given +capability; only the actual operation will return ``EPERM`` upon denial. Truncating files ----------------@@ -545,7 +715,7 @@ Access rights ------------- .. kernel-doc:: include/uapi/linux/landlock.h - :identifiers: fs_access net_access scope + :identifiers: fs_access net_access scope perm Creating a new ruleset ----------------------@@ -564,7 +734,8 @@ Extending a ruleset .. kernel-doc:: include/uapi/linux/landlock.h :identifiers: landlock_rule_type landlock_path_beneath_attr - landlock_net_port_attr + landlock_net_port_attr landlock_capability_attr + landlock_namespace_attr Enforcing a ruleset -------------------@@ -722,6 +893,23 @@ Starting with the Landlock ABI version 9, it is possible to restrict connections to pathname UNIX domain sockets (:manpage:`unix(7)`) using the new ``LANDLOCK_ACCESS_FS_RESOLVE_UNIX`` right. +Capability restriction (ABI < 10) +--------------------------------- + +Starting with the Landlock ABI version 10, it is possible to restrict +:manpage:`capabilities(7)` with the new ``LANDLOCK_PERM_CAPABILITY_USE`` +permission flag and ``LANDLOCK_RULE_CAPABILITY`` rule type. + +Namespace restriction (ABI < 10) +-------------------------------- + +Starting with the Landlock ABI version 10, it is possible to restrict namespace
Quoted 8 lines
Documentation/userspace-api/landlock.rst Starting with the Landlock ABI version 9, it is possible to restrict · line 911
Quoted 5 lines
Documentation/userspace-api/landlock.rst +5
-0+use across creation (:manpage:`unshare(2)`, :manpage:`clone(2)`, +:manpage:`clone3(2)`), entry (:manpage:`setns(2)`), and fd-reference acquisition +(:manpage:`open_tree(2)`, :manpage:`fsmount(2)`) with the new +``LANDLOCK_PERM_NAMESPACE_USE`` permission flag and ``LANDLOCK_RULE_NAMESPACE`` +rule type.This section would also benefit from a link to namespaces(7), which documents the list of different namespaces.
ok
Quoted 4 lines
Quoted 4 lines
Documentation/userspace-api/landlock.rst +1
-0+ .. _kernel_support:
Quoted 8 lines
Quoted 4 lines
Documentation/userspace-api/landlock.rst +0
-0Kernel supportSignature · 1 line
2.54.0Overall, I have a fair amount of remarks here, but most of them are much more on the "suggestion" side -- this documentation is much clearer than in V1, IMHO. :)
Thanks for this meticulous review!