Landlock: Namespace and capability control
Subsystems (8)
Mickaël Salaün
maintainercover 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-2022-0185 (filesystem mount parsing), CVE-2022-25636 and CVE-2023-32233 (netfilter), and CVE-2022-0492 (cgroup v1 release_agent) all demonstrate vulnerabilities exploitable only through capabilities gained via user namespaces. Some distributions 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.
This series adds two new permission categories to Landlock:
- LANDLOCK_PERM_NAMESPACE_ENTER: Restricts which namespace types a sandboxed process can acquire: both creation (unshare/clone) and entry (setns). User namespace creation has no capability check in the kernel, so this is the only enforcement mechanism for that entry point.
- 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). The Landlock ABI version is bumped from 8 to 9.
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.
Christian, could you please review patch 3? It adds a FOR_EACH_NS_TYPE X-macro to ns_common_types.h and derives CLONE_NS_ALL, replacing inline CLONE_NEW* flag enumerations in nsproxy.c and fork.c.
Paul, could you please review patch 2? It adds LSM_AUDIT_DATA_NS, a new audit record type that logs namespace_type and inum for namespace-related LSM denials.
All four 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_ENTER 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_alloc (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_ENTER 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.
Note that 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, which is optional. A dedicated mount access control type is left for future work [3].
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]
Christian Brauner (1):
security: add LSM blob and hooks for namespaces
Mickaël Salaün (10):
security: Add LSM_AUDIT_DATA_NS for namespace audit records
nsproxy: Add FOR_EACH_NS_TYPE() X-macro and CLONE_NS_ALL
landlock: Wrap per-layer access masks in struct layer_rights
landlock: Enforce namespace entry restrictions
landlock: Enforce capability restrictions selftests/landlock: Drain stale audit records on init 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 | 80 +- Documentation/userspace-api/landlock.rst | 156 +- 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 | 47 +- include/linux/security.h | 20 + include/uapi/linux/landlock.h | 89 +- kernel/fork.c | 7 +- kernel/nscommon.c | 12 + kernel/nsproxy.c | 21 +- samples/landlock/sandboxer.c | 164 +- security/landlock/Makefile | 2 + security/landlock/access.h | 72 +- security/landlock/audit.c | 8 + security/landlock/audit.h | 2 + security/landlock/cap.c | 142 ++ security/landlock/cap.h | 49 + security/landlock/cred.h | 47 +- security/landlock/limits.h | 9 + security/landlock/ns.c | 188 +++ security/landlock/ns.h | 74 + security/landlock/ruleset.c | 23 +- security/landlock/ruleset.h | 53 +- security/landlock/setup.c | 4 + security/landlock/syscalls.c | 124 +- security/lsm_audit.c | 4 + security/lsm_init.c | 2 + security/security.c | 76 + tools/testing/selftests/landlock/audit.h | 29 +- tools/testing/selftests/landlock/audit_test.c | 2 - tools/testing/selftests/landlock/base_test.c | 20 +- tools/testing/selftests/landlock/cap_test.c | 614 ++++++++ tools/testing/selftests/landlock/common.h | 23 + tools/testing/selftests/landlock/config | 5 + tools/testing/selftests/landlock/ns_test.c | 1379 +++++++++++++++++ tools/testing/selftests/landlock/wrappers.h | 6 + 38 files changed, 3487 insertions(+), 94 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
base-commit: 5dfb8077be2bbe2c3b9477da759e80fa9f98da42
Signature · 1 line
2.53.0
Mickaël Salaün
maintainerRFC PATCH 1/11 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.
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.
--- 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 ++++++++ kernel/nscommon.c | 12 +++++ kernel/nsproxy.c | 8 +++- security/lsm_init.c | 2 + security/security.c | 76 ++++++++++++++++++++++++++++++ 8 files changed, 124 insertions(+), 1 deletion(-)
include/linux/lsm_hook_defs.h +3 -0
@@ -260,6 +260,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_alloc, 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
@@ -111,6 +111,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
@@ -115,6 +115,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 ;
@@ -533,6 +535,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_alloc (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);
@@ -1407,6 +1412,21 @@ static inline int security_create_user_ns(const struct cred *cred)return 0 ; } +static inline int security_namespace_alloc (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) {
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,13 @@ 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_alloc (ns); +if (ret) { +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,6 +102,7 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_opevoid __ns_common_free (struct ns_common *ns) { +security_namespace_free (ns);proc_free_inum (ns->inum); }
kernel/nsproxy.c +7 -1
@@ -379,7 +379,13 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)static inline int validate_ns (struct nsset *nsset,struct ns_common *ns) { -return ns->ops->install (nsset, ns); +int ret; + + ret = ns->ops->install (nsset, ns); +if (ret) +return ret; + +return security_namespace_install (nsset, ns); }/*
security/lsm_init.c +2 -0
@@ -301,6 +301,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);
@@ -446,6 +447,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 +76 -0
94 lines not on this page · raw message
Signature · 1 line
2.53.0
Christian Brauner
maintainerRe: [RFC PATCH v1 01/11] security: add LSM blob and hooks for namespaces
Quoted 154 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.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]>--- 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 ++++++++ kernel/nscommon.c | 12 +++++ kernel/nsproxy.c | 8 +++- security/lsm_init.c | 2 + security/security.c | 76 ++++++++++++++++++++++++++++++ 8 files changed, 124 insertions(+), 1 deletion(-)include/linux/lsm_hook_defs.h +3
-0@@ -260,6 +260,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_alloc, 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@@ -111,6 +111,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@@ -115,6 +115,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 ;@@ -533,6 +535,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_alloc (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);@@ -1407,6 +1412,21 @@ static inline int security_create_user_ns(const struct cred *cred)return 0 ; } +static inline int security_namespace_alloc (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) {kernel/nscommon.c +4
-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;
kernel/nscommon.c int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope · line 87
Quoted 7 lines
kernel/nscommon.c +4
-0@@ -77,6 +81,13 @@ 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_alloc (ns); +if (ret) { +proc_free_inum (ns->inum);
ret = security_namespace_alloc(ns);
if (ret && !inum)
proc_free_inum(ns->inum);
return ret;
Quoted 20 lines
kernel/nscommon.c +4
-0+return ret; + } +/* * Tree ref starts at 0. It's incremented when namespace enters * active use (installed in nsproxy) and decremented when all @@ -91,6 +102,7 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_opevoid __ns_common_free (struct ns_common *ns) { +security_namespace_free (ns);proc_free_inum (ns->inum); }kernel/nsproxy.c +0
-0@@ -379,7 +379,13 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)
kernel/nsproxy.c static int prepare_nsset(unsigned flags, struct nsset *nsset) · line 388
Quoted 10 lines
kernel/nsproxy.c +7
-1static inline int validate_ns (struct nsset *nsset,struct ns_common *ns) { -return ns->ops->install (nsset, ns); +int ret; + + ret = ns->ops->install (nsset, ns); +if (ret) +return ret; + +return security_namespace_install (nsset, ns);
In my local tree I had that moved before the ->install() and I think that's the correct thing to do. So please switch to that.
The rest looks good to me, thanks.
Mickaël Salaün
maintainerRe: [RFC PATCH v1 01/11] security: add LSM blob and hooks for namespaces
Quoted 189 lines · Christian Brauner
Quoted 154 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.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]>--- 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 ++++++++ kernel/nscommon.c | 12 +++++ kernel/nsproxy.c | 8 +++- security/lsm_init.c | 2 + security/security.c | 76 ++++++++++++++++++++++++++++++ 8 files changed, 124 insertions(+), 1 deletion(-)include/linux/lsm_hook_defs.h +3
-0@@ -260,6 +260,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_alloc, 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@@ -111,6 +111,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@@ -115,6 +115,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 ;@@ -533,6 +535,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_alloc (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);@@ -1407,6 +1412,21 @@ static inline int security_create_user_ns(const struct cred *cred)return 0 ; } +static inline int security_namespace_alloc (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) {kernel/nscommon.c +4
-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;kernel/nscommon.c int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope · line 87
Quoted 7 lines
kernel/nscommon.c +4
-0@@ -77,6 +81,13 @@ 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_alloc (ns); +if (ret) { +proc_free_inum (ns->inum);ret =
security_namespace_alloc(ns);
if (ret && !inum)proc_free_inum(ns->inum);return ret;
Quoted 20 lines
kernel/nscommon.c +4
-0+return ret; + } +/* * Tree ref starts at 0. It's incremented when namespace enters * active use (installed in nsproxy) and decremented when all @@ -91,6 +102,7 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_opevoid __ns_common_free (struct ns_common *ns) { +security_namespace_free (ns);proc_free_inum (ns->inum); }kernel/nsproxy.c +0
-0@@ -379,7 +379,13 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)
Quoted 13 lines
kernel/nsproxy.c static int prepare_nsset(unsigned flags, struct nsset *nsset) · line 388
Quoted 10 lines
kernel/nsproxy.c +7
-1static inline int validate_ns (struct nsset *nsset,struct ns_common *ns) { -return ns->ops->install (nsset, ns); +int ret; + + ret = ns->ops->install (nsset, ns); +if (ret) +return ret; + +return security_namespace_install (nsset, ns);In my local tree I had that moved before the ->install() and I think that's the correct thing to do. So please switch to that.
Looks good, I'll include your fixes in the next version.
Quoted 2 lines
The rest looks good to me, thanks.
Another issue raised by Daniel Durning [1] is freeing of anonymous namespaces.
I'll extend this patch with this new hunk if that's ok:
fs/namespace.c +2 -0
@@ -4186,6 +4186,8 @@ static void free_mnt_ns(struct mnt_namespace *ns) {if (!is_anon_ns (ns))ns_common_free (ns); +else +security_namespace_free (&ns->ns);dec_mnt_namespaces (ns->ucounts);mnt_ns_tree_remove (ns); }
Daniel, could you please confirm that this fixes the memory leak?
[1] https://lore.kernel.org/all/[email protected]/
Quoted 19 lines
Quoted 18 lines
kernel/nsproxy.c +18
-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: The namespace may be freed via kfree_rcu(). LSMs must use +* RCU-safe freeing for any data that might be accessed by concurrent +* RCU readers. +*/ +void security_namespace_free (struct ns_common *ns) +{ +if (!ns->ns_security) +return ; + +call_void_hook (namespace_free, ns); +
Quoted 2 lines
kernel/nsproxy.c
Quoted 2 lines
kernel/nsproxy.c +2
-0+kfree (ns->ns_security); + ns->ns_security =NULL ;
I think it would be safer to replace these two lines with:kfree_rcu_mightsleep(ns->ns_security)
Quoted 1 line
Quoted 1 line
+}
Christian Brauner
maintainerRe: [RFC PATCH v1 01/11] security: add LSM blob and hooks for namespaces
Quoted 204 lines · Mickaël Salaün
Quoted 189 lines · Christian Brauner
Quoted 154 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.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]>--- 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 ++++++++ kernel/nscommon.c | 12 +++++ kernel/nsproxy.c | 8 +++- security/lsm_init.c | 2 + security/security.c | 76 ++++++++++++++++++++++++++++++ 8 files changed, 124 insertions(+), 1 deletion(-)include/linux/lsm_hook_defs.h +3
-0@@ -260,6 +260,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_alloc, 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@@ -111,6 +111,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@@ -115,6 +115,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 ;@@ -533,6 +535,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_alloc (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);@@ -1407,6 +1412,21 @@ static inline int security_create_user_ns(const struct cred *cred)return 0 ; } +static inline int security_namespace_alloc (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) {kernel/nscommon.c +4
-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;kernel/nscommon.c int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope · line 87
Quoted 7 lines
kernel/nscommon.c +4
-0@@ -77,6 +81,13 @@ 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_alloc (ns); +if (ret) { +proc_free_inum (ns->inum);ret =
security_namespace_alloc(ns);
if (ret && !inum)proc_free_inum(ns->inum);return ret;
Quoted 20 lines
kernel/nscommon.c +4
-0+return ret; + } +/* * Tree ref starts at 0. It's incremented when namespace enters * active use (installed in nsproxy) and decremented when all @@ -91,6 +102,7 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_opevoid __ns_common_free (struct ns_common *ns) { +security_namespace_free (ns);proc_free_inum (ns->inum); }kernel/nsproxy.c +0
-0@@ -379,7 +379,13 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)Quoted 13 lines
kernel/nsproxy.c static int prepare_nsset(unsigned flags, struct nsset *nsset) · line 388
Quoted 10 lines
kernel/nsproxy.c +7
-1static inline int validate_ns (struct nsset *nsset,struct ns_common *ns) { -return ns->ops->install (nsset, ns); +int ret; + + ret = ns->ops->install (nsset, ns); +if (ret) +return ret; + +return security_namespace_install (nsset, ns);In my local tree I had that moved before the ->install() and I think that's the correct thing to do. So please switch to that.
Quoted 1 line
Looks good, I'll include your fixes in the next version.
Thanks!
Quoted 14 lines
Quoted 3 lines
The rest looks good to me, thanks.
Another issue raised by Daniel Durning [1] is freeing of anonymous namespaces.
I'll extend this patch with this new hunk if that's ok:
fs/namespace.c +0
-0
fs/namespace.c static void free_mnt_ns(struct mnt_namespace *ns) · line 4193
Quoted 8 lines
fs/namespace.c +2
-0@@ -4186,6 +4186,8 @@ static void free_mnt_ns(struct mnt_namespace *ns) {if (!is_anon_ns (ns))ns_common_free (ns); +else +security_namespace_free (&ns->ns);dec_mnt_namespaces (ns->ucounts);mnt_ns_tree_remove (ns); }
I think that's fixing it at the wrong layer. It's probably better to do sm like:
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 +4 -1
@@ -91,7 +91,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->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)
Quoted 32 lines
Daniel, could you please confirm that this fixes the memory leak?
[1] https://lore.kernel.org/all/[email protected]/
Quoted 19 lines
Quoted 18 lines
kernel/nsproxy.c +18
-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: The namespace may be freed via kfree_rcu(). LSMs must use +* RCU-safe freeing for any data that might be accessed by concurrent +* RCU readers. +*/ +void security_namespace_free (struct ns_common *ns) +{ +if (!ns->ns_security) +return ; + +call_void_hook (namespace_free, ns); +Quoted 2 lines
kernel/nsproxy.c
Quoted 2 lines
kernel/nsproxy.c +2
-0+kfree (ns->ns_security); + ns->ns_security =NULL ;I think it would be safer to replace these two lines with:
kfree_rcu_mightsleep(ns->ns_security)Quoted 1 line
Quoted 1 line
+}
Re: [RFC PATCH v1 01/11] security: add LSM blob and hooks for namespaces
In reply to Mickaël SalaünQuoted 318 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.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]>--- 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 ++++++++ kernel/nscommon.c | 12 +++++ kernel/nsproxy.c | 8 +++- security/lsm_init.c | 2 + security/security.c | 76 ++++++++++++++++++++++++++++++ 8 files changed, 124 insertions(+), 1 deletion(-)include/linux/lsm_hook_defs.h +3
-0@@ -260,6 +260,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_alloc, 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@@ -111,6 +111,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@@ -115,6 +115,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 ;@@ -533,6 +535,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_alloc (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);@@ -1407,6 +1412,21 @@ static inline int security_create_user_ns(const struct cred *cred)return 0 ; } +static inline int security_namespace_alloc (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) {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,13 @@ 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_alloc (ns); +if (ret) { +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,6 +102,7 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_opevoid __ns_common_free (struct ns_common *ns) { +security_namespace_free (ns);proc_free_inum (ns->inum); }kernel/nsproxy.c +7
-1@@ -379,7 +379,13 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)static inline int validate_ns (struct nsset *nsset,struct ns_common *ns) { -return ns->ops->install (nsset, ns); +int ret; + + ret = ns->ops->install (nsset, ns); +if (ret) +return ret; + +return security_namespace_install (nsset, ns); }/* security/lsm_init.c +2
-0@@ -301,6 +301,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);@@ -446,6 +447,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 +76
-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> @@ -355,6 +356,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 @@ -3255,6 +3269,68 @@ int security_create_user_ns(const struct cred *cred)return call_int_hook (userns_create, cred); } +/** +* security_namespace_alloc() - Allocate LSM security data for a namespace +* @ns: the namespace being allocated +* +* Allocate and attach security data 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_alloc (struct ns_common *ns) +{ +int rc; + + rc =lsm_ns_alloc (ns); +if (unlikely (rc)) +return rc; + + rc =call_int_hook (namespace_alloc, 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: The namespace may be freed via kfree_rcu(). LSMs must use +* RCU-safe freeing for any data that might be accessed by concurrent +* RCU readers. +*/ +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.53.0
Paul Moore
maintainerRe: [RFC PATCH v1 01/11] security: add LSM blob and hooks for namespaces
In reply to Mickaël SalaünQuoted 39 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.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]>--- 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 ++++++++ kernel/nscommon.c | 12 +++++ kernel/nsproxy.c | 8 +++- security/lsm_init.c | 2 + security/security.c | 76 ++++++++++++++++++++++++++++++ 8 files changed, 124 insertions(+), 1 deletion(-)
...
Quoted 5 lines
kernel/nscommon.c +0
-0
kernel/nscommon.c int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope · line 89
Quoted 9 lines
kernel/nscommon.c +6
-0@@ -77,6 +81,13 @@ 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_alloc (ns); +if (ret) { +proc_free_inum (ns->inum); +return ret; + }
Since this is an RFC, I'll make the nitpicky comment that it would be better if the LSM hook is called security_namespace_init() instead of security_namespace_alloc(). This fits better with the convention of aligning with the caller's name, as well as to helps to indicate that the LSMs will be initializing the LSM state associated with the ns_common instance.
Quoted 7 lines
kernel/nsproxy.c +0
-0@@ -379,7 +379,13 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)static inline int validate_ns (struct nsset *nsset,struct ns_common *ns)
kernel/nsproxy.c static int prepare_nsset(unsigned flags, struct nsset *nsset) · line 389
Quoted 10 lines
kernel/nsproxy.c +7
-1{ -return ns->ops->install (nsset, ns); +int ret; + + ret = ns->ops->install (nsset, ns); +if (ret) +return ret; + +return security_namespace_install (nsset, ns); }
Do we also want a security_namespace_switch() called from within switch_task_namespaces()? Of course LSMs would not be able to fail or return an error at that point, but it seems reasonable that LSMs might want to update LSM state associated with the current task once the namespaces have been changed. This is similar to all the "_post_" LSM hooks we have for various operations in the VFS and network layers.
I think we would want to pass both the task_struct and whichever nsproxy instance is not stored in the task_struct to the hook. I prefer placing the hook after the task_struct has been updated, but if anyone feels strongly that it should be the other way that's okay with me.
Quoted 15 lines
security/security.c +11
-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: The namespace may be freed via kfree_rcu(). LSMs must use +* RCU-safe freeing for any data that might be accessed by concurrent +* RCU readers. +*/
security/security.c int security_create_user_ns(const struct cred *cred) · line 3317
Quoted 10 lines
security/security.c +10
-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 ; +}
The "namespace may be freed via kfree_rcu()" comment in conjunction with the standard kfree() in the function above raises a red flag. Do we need to take an approach similar to security_inode_free()/inode_free_by_rcu() here?
Signature · 1 line
paul-moore.com
Mickaël Salaün
maintainerRe: [RFC PATCH v1 01/11] security: add LSM blob and hooks for namespaces
Quoted 56 lines · Paul Moore
Quoted 39 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.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]>--- 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 ++++++++ kernel/nscommon.c | 12 +++++ kernel/nsproxy.c | 8 +++- security/lsm_init.c | 2 + security/security.c | 76 ++++++++++++++++++++++++++++++ 8 files changed, 124 insertions(+), 1 deletion(-)...
Quoted 13 lines
kernel/nscommon.c +5
-0@@ -77,6 +81,13 @@ 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_alloc (ns); +if (ret) { +proc_free_inum (ns->inum); +return ret;
Quoted 8 lines
kernel/nscommon.c int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope · line 89
Quoted 1 line
kernel/nscommon.c +1
-0+ }Since this is an RFC, I'll make the nitpicky comment that it would be better if the LSM hook is called
security_namespace_init()instead ofsecurity_namespace_alloc(). This fits better with the convention of aligning with the caller's name, as well as to helps to indicate that the LSMs will be initializing the LSM state associated with thens_commoninstance.
Looks good.
Quoted 17 lines
Quoted 17 lines
kernel/nsproxy.c +7
-1@@ -379,7 +379,13 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)static inline int validate_ns (struct nsset *nsset,struct ns_common *ns) { -return ns->ops->install (nsset, ns); +int ret; + + ret = ns->ops->install (nsset, ns); +if (ret) +return ret; + +return security_namespace_install (nsset, ns);
Quoted 8 lines
kernel/nsproxy.c static int prepare_nsset(unsigned flags, struct nsset *nsset) · line 389
Quoted 1 line
kernel/nsproxy.c +0
-0}Do we also want a
security_namespace_switch()called from withinswitch_task_namespaces()? Of course LSMs would not be able to fail or return an error at that point, but it seems reasonable that LSMs might want to update LSM state associated with the current task once the namespaces have been changed. This is similar to all the "_post_" LSM hooks we have for various operations in the VFS and network layers.
What cannot be infered from security_namespace_install()?
Quoted 29 lines
I think we would want to pass both the
task_structand whichever nsproxy instance is not stored in thetask_structto the hook. I prefer placing the hook after thetask_structhas been updated, but if anyone feels strongly that it should be the other way that's okay with me.Quoted 22 lines
security/security.c +18
-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: The namespace may be freed via kfree_rcu(). LSMs must use +* RCU-safe freeing for any data that might be accessed by concurrent +* RCU readers. +*/ +void security_namespace_free (struct ns_common *ns) +{ +if (!ns->ns_security) +return ; + +call_void_hook (namespace_free, ns); +
Quoted 8 lines
security/security.c int security_create_user_ns(const struct cred *cred) · line 3317
Quoted 3 lines
security/security.c +3
-0+kfree (ns->ns_security); + ns->ns_security =NULL ; +}The "namespace may be freed via
kfree_rcu()" comment in conjunction with the standardkfree()in the function above raises a red flag. Do we need to take an approach similar to security_inode_free()/inode_free_by_rcu() here?
I though at that too, but the key point is that once the namespace is being freed it is not reachable, which is not the case for inode being freed (i.e. because of path walks). So I think the current approach is fine even if the comment might be a bit scary.
Quoted 4 lines
Signature · 2 lines
-- paul-moore.com
Paul Moore
maintainerRe: [RFC PATCH v1 01/11] security: add LSM blob and hooks for namespaces
Quoted 41 lines · Mickaël Salaün
Quoted 40 lines · Paul Moore
Quoted 39 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.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]>--- 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 ++++++++ kernel/nscommon.c | 12 +++++ kernel/nsproxy.c | 8 +++- security/lsm_init.c | 2 + security/security.c | 76 ++++++++++++++++++++++++++++++ 8 files changed, 124 insertions(+), 1 deletion(-)
...
Quoted 25 lines
Quoted 16 lines
Quoted 16 lines
kernel/nsproxy.c +7
-1@@ -379,7 +379,13 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)static inline int validate_ns (struct nsset *nsset,struct ns_common *ns) { -return ns->ops->install (nsset, ns); +int ret; + + ret = ns->ops->install (nsset, ns); +if (ret) +return ret; + +return security_namespace_install (nsset, ns);Quoted 8 lines
kernel/nsproxy.c static int prepare_nsset(unsigned flags, struct nsset *nsset) · line 389
Quoted 1 line
kernel/nsproxy.c +0
-0}Do we also want a
security_namespace_switch()called from withinswitch_task_namespaces()? Of course LSMs would not be able to fail or return an error at that point, but it seems reasonable that LSMs might want to update LSM state associated with the current task once the namespaces have been changed. This is similar to all the "_post_" LSM hooks we have for various operations in the VFS and network layers.
Quoted 1 line
What cannot be infered from
security_namespace_install()?
We don't actually know if the namespace is attached to a process until we get to switch_task_namespaces().
Now that I'm looking at this again, why is the security_namespace_install() call placed after the ns->ops->install() call? From an access control perspective we want the LSM hook before the namespace install, not after as in this patch. From an LSM state update perspective we likely only care about when the namespace/nsset is assigned to a process.
Quoted 37 lines
Quoted 28 lines
I think we would want to pass both the
task_structand whichever nsproxy instance is not stored in thetask_structto the hook. I prefer placing the hook after thetask_structhas been updated, but if anyone feels strongly that it should be the other way that's okay with me.Quoted 22 lines
security/security.c +18
-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: The namespace may be freed via kfree_rcu(). LSMs must use +* RCU-safe freeing for any data that might be accessed by concurrent +* RCU readers. +*/ +void security_namespace_free (struct ns_common *ns) +{ +if (!ns->ns_security) +return ; + +call_void_hook (namespace_free, ns); +Quoted 8 lines
security/security.c int security_create_user_ns(const struct cred *cred) · line 3317
Quoted 3 lines
security/security.c +3
-0+kfree (ns->ns_security); + ns->ns_security =NULL ; +}The "namespace may be freed via
kfree_rcu()" comment in conjunction with the standardkfree()in the function above raises a red flag. Do we need to take an approach similar to security_inode_free()/inode_free_by_rcu() here?
Quoted 4 lines
I though at that too, but the key point is that once the namespace is being freed it is not reachable, which is not the case for inode being freed (i.e. because of path walks). So I think the current approach is fine even if the comment might be a bit scary.
The comment in the code and your comment in this email thread don't seem to align very well; one of those needs to be fixed in the next revision ;)
Signature · 1 line
paul-moore.com
Christian Brauner
maintainerRe: [RFC PATCH v1 01/11] security: add LSM blob and hooks for namespaces
Quoted 70 lines · Paul Moore
Quoted 41 lines · Mickaël Salaün
Quoted 40 lines · Paul Moore
Quoted 39 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.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]>--- 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 ++++++++ kernel/nscommon.c | 12 +++++ kernel/nsproxy.c | 8 +++- security/lsm_init.c | 2 + security/security.c | 76 ++++++++++++++++++++++++++++++ 8 files changed, 124 insertions(+), 1 deletion(-)...
Quoted 25 lines
Quoted 24 lines
Quoted 7 lines
kernel/nsproxy.c +0
-0@@ -379,7 +379,13 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)static inline int validate_ns (struct nsset *nsset,struct ns_common *ns)kernel/nsproxy.c static int prepare_nsset(unsigned flags, struct nsset *nsset) · line 389
Quoted 10 lines
kernel/nsproxy.c +7
-1{ -return ns->ops->install (nsset, ns); +int ret; + + ret = ns->ops->install (nsset, ns); +if (ret) +return ret; + +return security_namespace_install (nsset, ns); }Do we also want a
security_namespace_switch()called from withinswitch_task_namespaces()? Of course LSMs would not be able to fail or return an error at that point, but it seems reasonable that LSMs might want to update LSM state associated with the current task once the namespaces have been changed. This is similar to all the "_post_" LSM hooks we have for various operations in the VFS and network layers.
Quoted 8 lines
Quoted 1 line
What cannot be infered from
security_namespace_install()?We don't actually know if the namespace is attached to a process until we get to
switch_task_namespaces().Now that I'm looking at this again, why is the
security_namespace_install()call placed after thens->ops->install()call? From an access control perspective we want the LSM hook before
See https://lore.kernel.org/20260325-filmverleih-auffressen-e897fcf8d3f2@brauner
where I requested the order to be changed.
Paul Moore
maintainerRe: [RFC PATCH v1 01/11] security: add LSM blob and hooks for namespaces
Quoted 76 lines · Christian Brauner
Quoted 75 lines · Paul Moore
Quoted 41 lines · Mickaël Salaün
Quoted 40 lines · Paul Moore
Quoted 39 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.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]>--- 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 ++++++++ kernel/nscommon.c | 12 +++++ kernel/nsproxy.c | 8 +++- security/lsm_init.c | 2 + security/security.c | 76 ++++++++++++++++++++++++++++++ 8 files changed, 124 insertions(+), 1 deletion(-)...
Quoted 25 lines
Quoted 16 lines
Quoted 16 lines
kernel/nsproxy.c +7
-1@@ -379,7 +379,13 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)static inline int validate_ns (struct nsset *nsset,struct ns_common *ns) { -return ns->ops->install (nsset, ns); +int ret; + + ret = ns->ops->install (nsset, ns); +if (ret) +return ret; + +return security_namespace_install (nsset, ns);Quoted 8 lines
kernel/nsproxy.c static int prepare_nsset(unsigned flags, struct nsset *nsset) · line 389
Quoted 1 line
kernel/nsproxy.c +0
-0}Do we also want a
security_namespace_switch()called from withinswitch_task_namespaces()? Of course LSMs would not be able to fail or return an error at that point, but it seems reasonable that LSMs might want to update LSM state associated with the current task once the namespaces have been changed. This is similar to all the "_post_" LSM hooks we have for various operations in the VFS and network layers.Quoted 1 line
What cannot be infered from
security_namespace_install()?We don't actually know if the namespace is attached to a process until we get to
switch_task_namespaces().
Quoted 6 lines
Quoted 3 lines
Now that I'm looking at this again, why is the
security_namespace_install()call placed after thens->ops->install()call? From an access control perspective we want the LSM hook beforeSee https://lore.kernel.org/20260325-filmverleih-auffressen-e897fcf8d3f2@brauner
where I requested the order to be changed.
So ... does anyone not want this moved? It's time to speak up :)
Signature · 1 line
paul-moore.com
Mickaël Salaün
maintainerRFC PATCH 2/11 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, matching the field names of struct ns_common:
- ns_type: the CLONE_NEW* flag identifying the namespace type, logged in hexadecimal.
- inum: the proc inode number identifying a specific namespace instance. Namespace inode numbers are allocated by proc_alloc_inum() via ida_alloc_max() bounded to UINT_MAX, so the value always fits in 32 bits.
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.
--- 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; +unsigned int inum; + } 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_inum=%u" , + a->u.ns.ns_type, a->u.ns.inum); +break ; }/* switch (a->type) */ }
Signature · 1 line
2.53.0
Re: [RFC PATCH v1 02/11] security: Add LSM_AUDIT_DATA_NS for namespace audit records
Quoted 40 lines · Mickaël Salaün
Add a new LSM audit data type
LSM_AUDIT_DATA_NSthat logs namespace information in audit records. Two fields are provided, matching the field names of structns_common:-
ns_type: the CLONE_NEW* flag identifying the namespace type, logged in hexadecimal.- inum: the proc inode number identifying a specific namespace instance. Namespace inode numbers are allocated by
proc_alloc_inum()viaida_alloc_max()bounded toUINT_MAX, so the value always fits in 32 bits.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_TASKorLSM_AUDIT_DATA_NONEwith custom strings) would either lose the namespace type or require ad-hoc formatting that bypasses the structured audit data union.Cc Christian Brauner <[email protected]>Cc Günther Noack <[email protected]>Cc Paul Moore <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>--- include/linux/lsm_audit.h | 5 +++++ security/lsm_audit.c | 4 ++++ 2 files changed, 9 insertions(+)include/linux/lsm_audit.h +1
-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;
include/linux/lsm_audit.h struct common_audit_data { · line 106
Quoted 6 lines
include/linux/lsm_audit.h +3
-0@@ -100,6 +101,10 @@ struct common_audit_data {int reason;const char *anonclass;u16 nlmsg_type; +struct { +u32 ns_type; +unsigned int inum;
fwiw, you might want to start the 64-bit namespace id as well. But either way:
Mickaël Salaün
maintainerRe: [RFC PATCH v1 02/11] security: Add LSM_AUDIT_DATA_NS for namespace audit records
Quoted 42 lines · Christian Brauner
Quoted 41 lines · Mickaël Salaün
Add a new LSM audit data type
LSM_AUDIT_DATA_NSthat logs namespace information in audit records. Two fields are provided, matching the field names of structns_common:-
ns_type: the CLONE_NEW* flag identifying the namespace type, logged in hexadecimal.- inum: the proc inode number identifying a specific namespace instance. Namespace inode numbers are allocated by
proc_alloc_inum()viaida_alloc_max()bounded toUINT_MAX, so the value always fits in 32 bits.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_TASKorLSM_AUDIT_DATA_NONEwith custom strings) would either lose the namespace type or require ad-hoc formatting that bypasses the structured audit data union.Cc Christian Brauner <[email protected]>Cc Günther Noack <[email protected]>Cc Paul Moore <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>--- include/linux/lsm_audit.h | 5 +++++ security/lsm_audit.c | 4 ++++ 2 files changed, 9 insertions(+)include/linux/lsm_audit.h +1
-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;
Quoted 8 lines
include/linux/lsm_audit.h struct common_audit_data { · line 106
Quoted 5 lines
include/linux/lsm_audit.h +3
-0const char *anonclass;u16 nlmsg_type; +struct { +u32 ns_type; +unsigned int inum;fwiw, you might want to start the 64-bit namespace id as well. But either way:
Right now these numbers are generated by ida_alloc_max(), which return an int. Is there an ongoing patch series for this change?
Quoted 3 lines
Reviewed-by Christian Brauner <[email protected]>
Mickaël Salaün
maintainerRe: [RFC PATCH v1 02/11] security: Add LSM_AUDIT_DATA_NS for namespace audit records
Quoted 52 lines · Mickaël Salaün
Quoted 42 lines · Christian Brauner
Quoted 41 lines · Mickaël Salaün
Add a new LSM audit data type
LSM_AUDIT_DATA_NSthat logs namespace information in audit records. Two fields are provided, matching the field names of structns_common:-
ns_type: the CLONE_NEW* flag identifying the namespace type, logged in hexadecimal.- inum: the proc inode number identifying a specific namespace instance. Namespace inode numbers are allocated by
proc_alloc_inum()viaida_alloc_max()bounded toUINT_MAX, so the value always fits in 32 bits.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_TASKorLSM_AUDIT_DATA_NONEwith custom strings) would either lose the namespace type or require ad-hoc formatting that bypasses the structured audit data union.Cc Christian Brauner <[email protected]>Cc Günther Noack <[email protected]>Cc Paul Moore <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>--- include/linux/lsm_audit.h | 5 +++++ security/lsm_audit.c | 4 ++++ 2 files changed, 9 insertions(+)include/linux/lsm_audit.h +1
-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;Quoted 8 lines
include/linux/lsm_audit.h struct common_audit_data { · line 106
Quoted 5 lines
include/linux/lsm_audit.h +3
-0const char *anonclass;u16 nlmsg_type; +struct { +u32 ns_type; +unsigned int inum;fwiw, you might want to start the 64-bit namespace id as well. But either way:
Quoted 2 lines
Right now these numbers are generated by
ida_alloc_max(), which return an int. Is there an ongoing patch series for this change?
OK, we should not use the inode's number (32-bit) but the namespace ID (64-bit) which is readable with the NS_GET_ID IOCTL on the namespace FDs. I'll use that with ns_id instead of inum. I'll also update the Landlock code and tests accordingly.
Christian Brauner
maintainerRe: [RFC PATCH v1 02/11] security: Add LSM_AUDIT_DATA_NS for namespace audit records
Quoted 53 lines · Mickaël Salaün
Quoted 52 lines · Mickaël Salaün
Quoted 50 lines · Christian Brauner
Quoted 40 lines · Mickaël Salaün
Add a new LSM audit data type
LSM_AUDIT_DATA_NSthat logs namespace information in audit records. Two fields are provided, matching the field names of structns_common:-
ns_type: the CLONE_NEW* flag identifying the namespace type, logged in hexadecimal.- inum: the proc inode number identifying a specific namespace instance. Namespace inode numbers are allocated by
proc_alloc_inum()viaida_alloc_max()bounded toUINT_MAX, so the value always fits in 32 bits.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_TASKorLSM_AUDIT_DATA_NONEwith custom strings) would either lose the namespace type or require ad-hoc formatting that bypasses the structured audit data union.Cc Christian Brauner <[email protected]>Cc Günther Noack <[email protected]>Cc Paul Moore <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>--- include/linux/lsm_audit.h | 5 +++++ security/lsm_audit.c | 4 ++++ 2 files changed, 9 insertions(+)include/linux/lsm_audit.h +1
-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;include/linux/lsm_audit.h struct common_audit_data { · line 106
Quoted 6 lines
include/linux/lsm_audit.h +3
-0@@ -100,6 +101,10 @@ struct common_audit_data {int reason;const char *anonclass;u16 nlmsg_type; +struct { +u32 ns_type; +unsigned int inum;fwiw, you might want to start the 64-bit namespace id as well. But either way:
Quoted 7 lines
Quoted 2 lines
Right now these numbers are generated by
ida_alloc_max(), which return an int. Is there an ongoing patch series for this change?OK, we should not use the inode's number (32-bit) but the namespace ID (64-bit) which is readable with the
NS_GET_IDIOCTL on the namespace FDs. I'll use that withns_idinstead of inum. I'll also update the Landlock code and tests accordingly.
Yes, it's embedded in struct ns_common.
Re: [RFC PATCH v1 02/11] security: Add LSM_AUDIT_DATA_NS for namespace audit records
In reply to Mickaël SalaünQuoted 68 lines · Mickaël Salaün
Add a new LSM audit data type
LSM_AUDIT_DATA_NSthat logs namespace information in audit records. Two fields are provided, matching the field names of structns_common:-
ns_type: the CLONE_NEW* flag identifying the namespace type, logged in hexadecimal.- inum: the proc inode number identifying a specific namespace instance. Namespace inode numbers are allocated by
proc_alloc_inum()viaida_alloc_max()bounded toUINT_MAX, so the value always fits in 32 bits.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_TASKorLSM_AUDIT_DATA_NONEwith custom strings) would either lose the namespace type or require ad-hoc formatting that bypasses the structured audit data union.Cc Christian Brauner <[email protected]>Cc Günther Noack <[email protected]>Cc Paul Moore <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>--- 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; +unsigned int inum; + } 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_inum=%u" , + a->u.ns.ns_type, a->u.ns.inum); +break ; }/* switch (a->type) */ }Signature · 1 line
2.53.0
Mickaël Salaün
maintainerRFC PATCH 3/11 nsproxy: Add FOR_EACH_NS_TYPE() X-macro and CLONE_NS_ALL
In reply to Mickaël SalaünIntroduce the FOR_EACH_NS_TYPE(X) macro as the single source of truth for the set of (struct type, CLONE_NEW* flag) pairs that define Linux namespace types.
Currently, the list of CLONE_NEW* flags is duplicated inline in multiple call sites and would need another copy in each new consumer. This makes it easy to miss one when a new namespace type is added.
Derive two things from the X-macro:
- CLONE_NS_ALL: Bitmask of all known CLONE_NEW* flags, usable as a validity mask or iteration bound.
- ns_common_type(): Rewritten to use the X-macro via a leading-comma _Generic pattern, so the struct-to-flag mapping stays in sync with the flag set automatically.
Replace the inline flag enumerations in copy_namespaces(), unshare_nsproxy_namespaces(), check_setns_flags(), and ksys_unshare() with CLONE_NS_ALL.
When a new namespace type is added, only FOR_EACH_NS_TYPE needs to be updated; CLONE_NS_ALL, ns_common_type(), and all the call sites pick up the change automatically.
--- include/linux/ns/ns_common_types.h | 44 +++++++++++++++++++++++------- kernel/fork.c | 7 ++--- kernel/nsproxy.c | 13 +++------ 3 files changed, 41 insertions(+), 23 deletions(-)
include/linux/ns/ns_common_types.h +34 -10
@@ -7,6 +7,7 @@#include <linux/rbtree.h> #include <linux/refcount.h> #include <linux/types.h> +#include <uapi/linux/sched.h> struct cgroup_namespace ;struct dentry ;
@@ -187,15 +188,38 @@ struct ns_common { struct user_namespace *: (IS_ENABLED(CONFIG_USER_NS) ? &userns_operations : NULL), \ struct uts_namespace *: (IS_ENABLED(CONFIG_UTS_NS) ? &utsns_operations : NULL)) -#define ns_common_type(__ns) \ - _Generic((__ns), \ - struct cgroup_namespace *: CLONE_NEWCGROUP, \ - struct ipc_namespace *: CLONE_NEWIPC, \ - struct mnt_namespace *: CLONE_NEWNS, \ - struct net *: CLONE_NEWNET, \ - struct pid_namespace *: CLONE_NEWPID, \ - struct time_namespace *: CLONE_NEWTIME, \ - struct user_namespace *: CLONE_NEWUSER, \ - struct uts_namespace *: CLONE_NEWUTS) +/* +* FOR_EACH_NS_TYPE - Canonical list of namespace types +* +* Enumerates all (struct type, CLONE_NEW* flag) pairs. This is the +* single source of truth used to derive ns_common_type() and +* CLONE_NS_ALL. When adding a new namespace type, add a single entry +* here; all consumers update automatically. +* +* @X: Callback macro taking (struct_name, clone_flag) as arguments. +*/ +#define FOR_EACH_NS_TYPE (X ) \ + X(cgroup_namespace, CLONE_NEWCGROUP) \ + X(ipc_namespace, CLONE_NEWIPC) \ + X(mnt_namespace, CLONE_NEWNS) \ + X(net, CLONE_NEWNET) \ + X(pid_namespace, CLONE_NEWPID) \ + X(time_namespace, CLONE_NEWTIME) \ + X(user_namespace, CLONE_NEWUSER) \ + X(uts_namespace, CLONE_NEWUTS) + +/* Bitmask of all known CLONE_NEW* flags. */ +#define _NS_TYPE_FLAG_OR (struct_name, flag) | (flag) +#define CLONE_NS_ALL (0 FOR_EACH_NS_TYPE(_NS_TYPE_FLAG_OR)) + +/* +* ns_common_type - Map a namespace struct pointer to its CLONE_NEW* flag +* +* Uses a leading-comma pattern so the FOR_EACH_NS_TYPE expansion +* produces ", struct foo *: FLAG" entries without a trailing comma. +*/ +#define _NS_TYPE_ASSOC (struct_name, flag) , struct struct_name *: (flag) + +#define ns_common_type (__ns) _Generic((__ns)FOR_EACH_NS_TYPE(_NS_TYPE_ASSOC))#endif /* _LINUX_NS_COMMON_TYPES_H */
kernel/fork.c +3 -4
@@ -46,6 +46,7 @@#include <linux/mm_inline.h> #include <linux/memblock.h> #include <linux/nsproxy.h> +#include <linux/ns/ns_common_types.h> #include <linux/capability.h> #include <linux/cpu.h> #include <linux/cgroup.h>
@@ -3046,11 +3047,9 @@ void __init proc_caches_init(void)*/ static int check_unshare_flags (unsigned long unshare_flags) { -if (unshare_flags & ~(CLONE_THREAD |CLONE_FS |CLONE_NEWNS |CLONE_SIGHAND | +if (unshare_flags & ~(CLONE_THREAD |CLONE_FS |CLONE_SIGHAND |CLONE_VM |CLONE_FILES |CLONE_SYSVSEM | -CLONE_NEWUTS |CLONE_NEWIPC |CLONE_NEWNET | -CLONE_NEWUSER |CLONE_NEWPID |CLONE_NEWCGROUP | -CLONE_NEWTIME )) +CLONE_NS_ALL ))return -EINVAL ;/* * Not implemented, but pretend it works if there is nothing
kernel/nsproxy.c +4 -9
@@ -12,6 +12,7 @@#include <linux/slab.h> #include <linux/export.h> #include <linux/nsproxy.h> +#include <linux/ns/ns_common_types.h> #include <linux/init_task.h> #include <linux/mnt_namespace.h> #include <linux/utsname.h>
@@ -170,9 +171,7 @@ int copy_namespaces(u64 flags, struct task_struct *tsk)struct user_namespace *user_ns =task_cred_xxx (tsk, user_ns);struct nsproxy *new_ns; -if (likely (!(flags & (CLONE_NEWNS |CLONE_NEWUTS |CLONE_NEWIPC | -CLONE_NEWPID |CLONE_NEWNET | -CLONE_NEWCGROUP |CLONE_NEWTIME )))) { +if (likely (!(flags & (CLONE_NS_ALL & ~CLONE_NEWUSER )))) {if ((flags &CLONE_VM ) ||likely (old_ns->time_ns_for_children == old_ns->time_ns)) {get_nsproxy (old_ns);
@@ -214,9 +213,7 @@ int unshare_nsproxy_namespaces(unsigned long unshare_flags,struct user_namespace *user_ns;int err =0 ; -if (!(unshare_flags & (CLONE_NEWNS |CLONE_NEWUTS |CLONE_NEWIPC | -CLONE_NEWNET |CLONE_NEWPID |CLONE_NEWCGROUP | -CLONE_NEWTIME ))) +if (!(unshare_flags & (CLONE_NS_ALL & ~CLONE_NEWUSER )))return 0 ; user_ns = new_cred ? new_cred->user_ns :current_user_ns ();
@@ -292,9 +289,7 @@ int exec_task_namespaces(void)static int check_setns_flags (unsigned long flags) { -if (!flags || (flags & ~(CLONE_NEWNS |CLONE_NEWUTS |CLONE_NEWIPC | -CLONE_NEWNET |CLONE_NEWTIME |CLONE_NEWUSER | -CLONE_NEWPID |CLONE_NEWCGROUP ))) +if (!flags || (flags & ~CLONE_NS_ALL ))return -EINVAL ;#ifndef CONFIG_USER_NS
Signature · 1 line
2.53.0
Re: [RFC PATCH v1 03/11] nsproxy: Add FOR_EACH_NS_TYPE() X-macro and CLONE_NS_ALL
Quoted 21 lines · Mickaël Salaün
Introduce the
FOR_EACH_NS_TYPE(X)macro as the single source of truth for the set of (struct type, CLONE_NEW* flag) pairs that define Linux namespace types.Currently, the list of CLONE_NEW* flags is duplicated inline in multiple call sites and would need another copy in each new consumer. This makes it easy to miss one when a new namespace type is added.
Derive two things from the X-macro:
-
CLONE_NS_ALL: Bitmask of all known CLONE_NEW* flags, usable as a validity mask or iteration bound.-
ns_common_type(): Rewritten to use the X-macro via a leading-comma_Genericpattern, so the struct-to-flag mapping stays in sync with the flag set automatically.Replace the inline flag enumerations in
copy_namespaces(),unshare_nsproxy_namespaces(),check_setns_flags(), andksys_unshare()withCLONE_NS_ALL.
Quoted 8 lines
When a new namespace type is added, only
FOR_EACH_NS_TYPEneeds to be updated;CLONE_NS_ALL,ns_common_type(), and all the call sites pick up the change automatically.Cc Christian Brauner <[email protected]>Cc Günther Noack <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>---
Yeah, I love that. I can take that as a separate patch right now even.
Mickaël Salaün
maintainerRe: [RFC PATCH v1 03/11] nsproxy: Add FOR_EACH_NS_TYPE() X-macro and CLONE_NS_ALL
Quoted 26 lines · Christian Brauner
Quoted 25 lines · Mickaël Salaün
Introduce the
FOR_EACH_NS_TYPE(X)macro as the single source of truth for the set of (struct type, CLONE_NEW* flag) pairs that define Linux namespace types.Currently, the list of CLONE_NEW* flags is duplicated inline in multiple call sites and would need another copy in each new consumer. This makes it easy to miss one when a new namespace type is added.
Derive two things from the X-macro:
-
CLONE_NS_ALL: Bitmask of all known CLONE_NEW* flags, usable as a validity mask or iteration bound.-
ns_common_type(): Rewritten to use the X-macro via a leading-comma_Genericpattern, so the struct-to-flag mapping stays in sync with the flag set automatically.Replace the inline flag enumerations in
copy_namespaces(),unshare_nsproxy_namespaces(),check_setns_flags(), andksys_unshare()withCLONE_NS_ALL.When a new namespace type is added, only
FOR_EACH_NS_TYPEneeds to be updated;CLONE_NS_ALL,ns_common_type(), and all the call sites pick up the change automatically.
Quoted 6 lines
Quoted 4 lines
Cc Christian Brauner <[email protected]>Cc Günther Noack <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>---
Yeah, I love that. I can take that as a separate patch right now even.
Yes, please take it.
Quoted 3 lines
Reviewed-by Christian Brauner <[email protected]>
Re: (subset) [RFC PATCH v1 03/11] nsproxy: Add FOR_EACH_NS_TYPE() X-macro and CLONE_NS_ALL
In reply to Mickaël SalaünQuoted 9 lines · Mickaël Salaün
Introduce the
FOR_EACH_NS_TYPE(X)macro as the single source of truth for the set of (struct type, CLONE_NEW* flag) pairs that define Linux namespace types.Currently, the list of CLONE_NEW* flags is duplicated inline in multiple call sites and would need another copy in each new consumer. This makes it easy to miss one when a new namespace type is added.
[...]
Applied to the namespaces-7.1.misc branch of the vfs/vfs.git tree. Patches in the namespaces-7.1.misc branch should appear in linux-next soon.
Please report any outstanding bugs that were missed during review in a new review to the original patch series allowing us to drop it.
It's encouraged to provide Acked-bys and Reviewed-bys even though the patch has now been applied. If possible patch trailers will be updated.
Note that commit hashes shown below are subject to change due to rebase, trailer updates or similar. If in doubt, please check the listed branch.
tree: https://git.kernel.org/pub/scm/linux/kernel/git/vfs/vfs.git branch: namespaces-7.1.misc
[03/11] nsproxy: Add FOR_EACH_NS_TYPE() X-macro and CLONE_NS_ALL
https://git.kernel.org/vfs/vfs/c/935a04923ad2
Mickaël Salaün
maintainerRFC PATCH 4/11 landlock: Wrap per-layer access masks in struct layer_rights
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_rights 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.
--- security/landlock/access.h | 29 ++++++++++++++++++++++------- security/landlock/cred.h | 2 +- security/landlock/ruleset.c | 12 ++++++------ security/landlock/ruleset.h | 28 +++++++++++++++------------- security/landlock/syscalls.c | 2 +- 5 files changed, 45 insertions(+), 28 deletions(-)
security/landlock/access.h +22 -7
@@ -19,7 +19,7 @@/* * 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[] +* by a ruleset/layer. This must be ORed with all ruleset->layers[] * entries when we need to get the absolute handled access masks, see * landlock_upgrade_handled_access_masks(). */
@@ -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_rights - 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_rights { +/** +* @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_rights +landlock_upgrade_handled_access_masks (struct layer_rights layer_rights) {/* * 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_rights.handled.fs) + layer_rights.handled.fs |= _LANDLOCK_ACCESS_FS_INITIALLY_DENIED; -return access_masks; +return layer_rights; }/* 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 +6 -6
@@ -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 );
@@ -48,7 +48,7 @@ static struct landlock_ruleset *create_ruleset(const u32 num_layers)/* * hierarchy = NULL * num_rules = 0 -* access_masks[] = 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_access_masks (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 +15 -13
@@ -146,7 +146,7 @@ struct landlock_ruleset {* 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. +* @layers are then unused. */ struct work_struct work_free;struct {
@@ -173,9 +173,10 @@ struct landlock_ruleset {*/ u32 num_layers;/** -* @access_masks: Contains the subset of filesystem and -* network actions that are restricted by a ruleset. -* A domain saves all layers of merged rulesets in a +* @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
@@ -184,7 +185,7 @@ struct landlock_ruleset {* layers are set once and never changed for the * lifetime of the ruleset. */ -struct access_masks access_masks[]; + struct layer_rights layers[] __counted_by(num_layers); }; }; };
@@ -224,7 +225,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 +236,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 +254,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 +266,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 +277,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 +285,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 +293,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.53.0
Re: [RFC PATCH v1 04/11] landlock: Wrap per-layer access masks in struct layer_rights
Quoted 1 line · Mickaël Salaün
[...]
Hi Mickaël,
As requested I have reviewed this series. All looks good to me with one minor comment on the next patch.
(for patch 4,5,6,10)
Re: [RFC PATCH v1 04/11] landlock: Wrap per-layer access masks in struct layer_rights
In reply to Mickaël SalaünQuoted 29 lines · Mickaël Salaün
The per-layer FAM in struct
landlock_rulesetcurrently stores structaccess_masksdirectly, but upcoming permission features (capability and namespace restrictions) need additional per-layer data beyond the handled-access bitfields.Introduce struct
layer_rightsas a wrapper around structaccess_masksand rename the FAM from access_masks[] to layers[]. This makes room for future per-layer fields (e.g. allowed bitmasks) without modifying structaccess_masksitself, which is also used as a lightweight parameter type for functions that only need the handled-access bitfields.No functional change.
Cc Günther Noack <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>--- security/landlock/access.h | 29 ++++++++++++++++++++++------- security/landlock/cred.h | 2 +- security/landlock/ruleset.c | 12 ++++++------ security/landlock/ruleset.h | 28 +++++++++++++++------------- security/landlock/syscalls.c | 2 +- 5 files changed, 45 insertions(+), 28 deletions(-)security/landlock/access.h +0
-0
security/landlock/access.h line 24
Quoted 7 lines
security/landlock/access.h +1
-1@@ -19,7 +19,7 @@/* * 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[] +* by a ruleset/layer. This must be ORed with all ruleset->layers[] * entries when we need to get the absolute handled access masks, see * landlock_upgrade_handled_access_masks().
Nit: It doesn't get ORed with the ruleset->layers[] entries, but with the access field within them. Suggestion:
This must be ORed with the access field in all ruleset->layers[] entries...
Quoted 33 lines
security/landlock/access.h +16
-1*/ @@ -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_rights - 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_rights { +/** +* @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 *
security/landlock/access.h static_assert(BITS_PER_TYPE(deny_masks_t) >= · line 119
Quoted 7 lines
security/landlock/access.h +2
-2@@ -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_rights +landlock_upgrade_handled_access_masks (struct layer_rights layer_rights)
^^^^^^^^^^^^
Now that this is taking "layer_rights" not access_masks, is this still the right function name?
Quoted 86 lines
security/landlock/access.h +3
-3{/* * 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_rights.handled.fs) + layer_rights.handled.fs |= _LANDLOCK_ACCESS_FS_INITIALLY_DENIED; -return access_masks; +return layer_rights; }/* 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 +6
-6@@ -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 );@@ -48,7 +48,7 @@ static struct landlock_ruleset *create_ruleset(const u32 num_layers)/* * hierarchy = NULL * num_rules = 0 -* access_masks[] = 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_access_masks (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 +1
-1@@ -146,7 +146,7 @@ struct landlock_ruleset {* 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. +* @layers are then unused. */ struct work_struct work_free;struct {
security/landlock/ruleset.h struct landlock_ruleset { · line 179
Quoted 10 lines
security/landlock/ruleset.h +4
-3@@ -173,9 +173,10 @@ struct landlock_ruleset {*/ u32 num_layers;/** -* @access_masks: Contains the subset of filesystem and -* network actions that are restricted by a ruleset. -* A domain saves all layers of merged rulesets in a +* @layers: Per-layer access configuration, including +* handled access masks and allowed permission +* bitmasks. A domain saves all layers of merged +* rulesets in a
^^^^^^^^^^^^^
Nit: Unconventional line break
security/landlock/ruleset.h struct landlock_ruleset { · line 188
Quoted 9 lines
security/landlock/ruleset.h +1
-1* stack (FAM), starting from the first layer to the * last one. These layers are used when merging * rulesets, for user space backward compatibility @@ -184,7 +185,7 @@ struct landlock_ruleset {* layers are set once and never changed for the * lifetime of the ruleset. */ -struct access_masks access_masks[]; + struct layer_rights layers[] __counted_by(num_layers);
Thanks for adding __counted_by() 🏆
Quoted 91 lines
security/landlock/ruleset.h +9
-8}; }; };@@ -224,7 +225,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 +236,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 +254,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 +266,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 +277,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 +285,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 +293,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.53.0
Mickaël Salaün
maintainerRFC PATCH 5/11 landlock: Enforce namespace entry restrictions
In reply to Mickaël SalaünAdd Landlock enforcement for namespace entry via the LSM namespace_alloc and namespace_install hooks. This lets a sandboxed process restrict which namespace types it can acquire, using LANDLOCK_PERM_NAMESPACE_ENTER and per-type rules.
Introduce the handled_perm field in struct landlock_ruleset_attr for permission categories that control broad operations enforced at single kernel chokepoints, achieving complete deny-by-default coverage. Each LANDLOCK_PERM_* flag names a gateway operation (use, enter) whose control transitively covers downstream operations. 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.
Add two namespace hooks:
- hook_namespace_alloc() fires during unshare(CLONE_NEW*) and clone(CLONE_NEW*) via __ns_common_init(), and checks the namespace type against the domain's allowed set.
- hook_namespace_install() fires during setns() via validate_ns(), performing the same type-based check. Both hooks set namespace_type in the audit data; hook_namespace_install() also sets inum for the target namespace.
Both hooks perform a pure bitmask check: 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.
Add the perm_rules bitfield to struct layer_rights (introduced by a preceding commit) to store per-layer namespace type bitmasks. The 8-bit NS field maps to the 8 known namespace types via landlock_ns_type_to_bit(), keeping the storage compact.
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.
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_ENTER 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.
--- include/uapi/linux/landlock.h | 58 +++++- security/landlock/Makefile | 1 + security/landlock/access.h | 42 ++++- security/landlock/audit.c | 4 + security/landlock/audit.h | 1 + security/landlock/cred.h | 42 +++++ security/landlock/limits.h | 7 + security/landlock/ns.c | 188 +++++++++++++++++++ security/landlock/ns.h | 74 ++++++++ security/landlock/ruleset.c | 11 +- security/landlock/ruleset.h | 25 ++- security/landlock/setup.c | 2 + security/landlock/syscalls.c | 70 ++++++- tools/testing/selftests/landlock/base_test.c | 2 +- 14 files changed, 509 insertions(+), 18 deletions(-) create mode 100644 security/landlock/ns.c create mode 100644 security/landlock/ns.h
include/uapi/linux/landlock.h +57 -1
@@ -51,6 +51,14 @@ 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 broad +* operation enforced at a kernel chokepoint: all instances of +* that operation are denied unless explicitly allowed by a rule. +* See Documentation/security/landlock.rst for the rationale. +*/ +__u64 handled_perm; };/**
@@ -153,6 +161,11 @@ 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, };/**
@@ -206,6 +219,24 @@ 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_ENTER. +*/ +__u64 allowed_perm; +/** +* @namespace_types: Bitmask of namespace types (``CLONE_NEW*`` flags) +* that should be allowed to be entered under this rule. Unknown bits +* are silently ignored for forward compatibility. +*/ +__u64 namespace_types; +}; +/** * DOC: fs_access *
@@ -379,6 +410,31 @@ 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 broad operations enforced at kernel chokepoints. +* Each flag names a gateway operation whose control transitively covers +* an open-ended set of downstream operations. 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_ENTER: Restrict entering (creating or joining +* via :manpage:`setns(2)`) specific namespace types. A process in a +* Landlock domain that handles this permission is denied from entering +* namespace types that are not explicitly allowed by a +* %LANDLOCK_RULE_NAMESPACE rule. +*/ +/* clang-format off */ +#define LANDLOCK_PERM_NAMESPACE_ENTER (1ULL << 0) +/* clang-format on */ #endif /* _UAPI_LINUX_LANDLOCK_H */
security/landlock/Makefile +1 -0
@@ -8,6 +8,7 @@ landlock-y := \ cred.o \ task.o \ fs.o \ + ns.o \ tsync.o landlock-$(CONFIG_INET) += net.o
security/landlock/access.h +39 -3
65 lines not on this page · raw message
security/landlock/audit.c +4 -0
@@ -78,6 +78,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_enter" ; }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 +42 -0
48 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_ENTER +#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 +188 -0
188 lines not on this page · raw message
security/landlock/ns.h new file +74 -0
74 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
@@ -190,10 +190,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);
@@ -303,6 +302,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 +66 -4
135 lines not on this page · raw message
tools/testing/selftests/landlock/base_test.c +1 -1
@@ -76,7 +76,7 @@ TEST(abi_version)const struct landlock_ruleset_attr ruleset_attr = { .handled_access_fs =LANDLOCK_ACCESS_FS_READ_FILE , }; -ASSERT_EQ (8 ,landlock_create_ruleset (NULL ,0 , +ASSERT_EQ (9 ,landlock_create_ruleset (NULL ,0 ,LANDLOCK_CREATE_RULESET_VERSION )); ASSERT_EQ(-1, landlock_create_ruleset(&ruleset_attr, 0,
Signature · 1 line
2.53.0
kernel test robot
build botRe: [RFC PATCH v1 05/11] landlock: Enforce namespace entry restrictions
kernel test robot noticed the following build errors:
Hi Mickaël,
[This is a private test report for your RFC patch.] kernel test robot noticed the following build errors:
[auto build test ERROR on 5dfb8077be2bbe2c3b9477da759e80fa9f98da42]
url: https://github.com/intel-lab-lkp/linux/commits/Micka-l-Sala-n/security-add-LSM-blob-and-hooks-for-namespaces/20260314-205540 base: 5dfb8077be2bbe2c3b9477da759e80fa9f98da42 patch link: https://lore.kernel.org/r/20260312100444.2609563-6-mic%40digikod.net patch subject: [RFC PATCH v1 05/11] landlock: Enforce namespace entry restrictions config: m68k-allmodconfig (https://download.01.org/0day-ci/archive/20260329/[email protected]/config) compiler: m68k-linux-gcc (GCC) 15.2.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260329/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
In file included from include/linux/bits.h:30,
from security/landlock/setup.c:9:
>> include/linux/build_bug.h:78:41: error: static assertion failed: "sizeof(struct perm_rules) == sizeof(u64)"
78 | #define __static_assert(expr, msg, ...) _Static_assert(expr, msg)
| ^~~~~~~~~~~~~~
include/linux/build_bug.h:77:34: note: in expansion of macro '__static_assert'
77 | #define static_assert(expr, ...) __static_assert(expr, ##__VA_ARGS__, #expr)
| ^~~~~~~~~~~~~~~
security/landlock/access.h:86:1: note: in expansion of macro 'static_assert'
86 | static_assert(sizeof(struct perm_rules) == sizeof(u64));
| ^~~~~~~~~~~~~vim +78 include/linux/build_bug.h
bc6245e5efd70c4 Ian Abbott 2017-07-10 60 6bab69c65013bed Rasmus Villemoes 2019-03-07 61 /** 6bab69c65013bed Rasmus Villemoes 2019-03-07 62 * static_assert - check integer constant expression at build time 6bab69c65013bed Rasmus Villemoes 2019-03-07 63 * 6bab69c65013bed Rasmus Villemoes 2019-03-07 64 * static_assert() is a wrapper for the C11 _Static_assert, with a 6bab69c65013bed Rasmus Villemoes 2019-03-07 65 * little macro magic to make the message optional (defaulting to the 6bab69c65013bed Rasmus Villemoes 2019-03-07 66 * stringification of the tested expression). 6bab69c65013bed Rasmus Villemoes 2019-03-07 67 * 6bab69c65013bed Rasmus Villemoes 2019-03-07 68 * Contrary to BUILD_BUG_ON(), static_assert() can be used at global 6bab69c65013bed Rasmus Villemoes 2019-03-07 69 * scope, but requires the expression to be an integer constant 6bab69c65013bed Rasmus Villemoes 2019-03-07 70 * expression (i.e., it is not enough that __builtin_constant_p() is 6bab69c65013bed Rasmus Villemoes 2019-03-07 71 * true for expr). 6bab69c65013bed Rasmus Villemoes 2019-03-07 72 * 6bab69c65013bed Rasmus Villemoes 2019-03-07 73 * Also note that BUILD_BUG_ON() fails the build if the condition is 6bab69c65013bed Rasmus Villemoes 2019-03-07 74 * true, while static_assert() fails the build if the expression is 6bab69c65013bed Rasmus Villemoes 2019-03-07 75 * false. 6bab69c65013bed Rasmus Villemoes 2019-03-07 76 */ 6bab69c65013bed Rasmus Villemoes 2019-03-07 77 #define static_assert(expr, ...) __static_assert(expr, ##__VA_ARGS__, #expr)
6bab69c65013bed Rasmus Villemoes 2019-03-07 @78 #define __static_assert(expr, msg, ...) _Static_assert(expr, msg) 6bab69c65013bed Rasmus Villemoes 2019-03-07 7907a368b3f55a79d Maxim Levitsky 2022-10-25 80
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
Re: [RFC PATCH v1 05/11] landlock: Enforce namespace entry restrictions
In reply to Mickaël SalaünQuoted 47 lines · Mickaël Salaün
[...]
include/uapi/linux/landlock.h +24
-0@@ -51,6 +51,14 @@ 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 broad +* operation enforced at a kernel chokepoint: all instances of +* that operation are denied unless explicitly allowed by a rule. +* See Documentation/security/landlock.rst for the rationale. +*/ +__u64 handled_perm; };/** @@ -153,6 +161,11 @@ 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, };/** @@ -206,6 +219,24 @@ 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_ENTER. +*/ +__u64 allowed_perm; +/**
include/uapi/linux/landlock.h struct landlock_net_port_attr { · line 242
Quoted 10 lines
include/uapi/linux/landlock.h +7
-0+* @namespace_types: Bitmask of namespace types (``CLONE_NEW*`` flags) +* that should be allowed to be entered under this rule. Unknown bits +* are silently ignored for forward compatibility. +*/ +__u64 namespace_types; +}; +/** * DOC: fs_access *
This UAPI looks good, follows existing patterns and is extensible.
btw, I guess for consistency, later on this new handled_perm should also have a quiet_perm, which would allow suppressing audit logs for namespace / capability rules (for those (possibly a subset) added with LANDLOCK_ADD_RULE_QUIET)?
Quoted 4 lines
[...]
include/uapi/linux/landlock.h +0
-0@@ -153,6 +153,48 @@ landlock_get_applicable_subject(const struct cred *const cred,return NULL ; }
include/uapi/linux/landlock.h landlock_get_applicable_subject(const struct cred *const cred, · line 164
Quoted 10 lines
include/uapi/linux/landlock.h +9
-0+/** +* landlock_perm_is_denied - Check if a permission bitmask request is denied +* +* @domain: The enforced domain. +* @perm_bit: The LANDLOCK_PERM_* flag to check. +* @request_value: Compact bitmask to look for (e.g. result of +* ``landlock_ns_type_to_bit(CLONE_NEWNET)``). +* +* Iterate from the youngest layer to the oldest. For each layer that
How about this:
/**
* landlock_perm_is_denied - Check if a permission request is denied *
* @domain: The enforced domain.
* @perm_bit: The LANDLOCK_PERM_* flag to check.
* @request_value: Compact bitmask to look for (e.g. result of
* ``landlock_ns_type_to_bit(CLONE_NEWNET)``).
* Must have only bit set.
*
* Iterate from the youngest layer to the oldest. For each layer that
Basically, to make it more obvious that this functions only checks one bit. Currently if a combination of permission bits are passed, this allows access if any of them are allowed, which if accidentally used this way in the future will probably be a bug. I was considering a WARN_ON_ONCE but maybe it's a bit unnecessary for now given the caller always passes a landlock_*_to_bit result (and those already WARN_ON_ONCE if given invalid parameter).
Re: [RFC PATCH v1 05/11] landlock: Enforce namespace entry restrictions
In reply to Mickaël SalaünQuoted 142 lines · Mickaël Salaün
Add Landlock enforcement for namespace entry via the LSM
namespace_allocandnamespace_installhooks. This lets a sandboxed process restrict which namespace types it can acquire, usingLANDLOCK_PERM_NAMESPACE_ENTERand per-type rules.Introduce the
handled_permfield in structlandlock_ruleset_attrfor permission categories that control broad operations enforced at single kernel chokepoints, achieving complete deny-by-default coverage. Each LANDLOCK_PERM_* flag names a gateway operation (use, enter) whose control transitively covers downstream operations. 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.Add two namespace hooks:
-
hook_namespace_alloc()fires duringunshare(CLONE_NEW*)andclone(CLONE_NEW*)via__ns_common_init(), and checks the namespace type against the domain's allowed set.-
hook_namespace_install()fires duringsetns()viavalidate_ns(), performing the same type-based check. Both hooks setnamespace_typein the audit data;hook_namespace_install()also sets inum for the target namespace.Both hooks perform a pure bitmask check: 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.
Add the
perm_rulesbitfield to structlayer_rights(introduced by a preceding commit) to store per-layer namespace type bitmasks. The 8-bit NS field maps to the 8 known namespace types vialandlock_ns_type_to_bit(), keeping the storage compact.
LANDLOCK_RULE_NAMESPACEuses structlandlock_namespace_attrwith anallowed_permfield (matching the pattern ofallowed_accessin existing rule types) and anamespace_typesbitmask 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.User namespace creation does not require capabilities, so Landlock can restrict it directly. Non-user namespace types require
CAP_SYS_ADMINbefore the Landlock check is reached; when bothLANDLOCK_PERM_NAMESPACE_ENTERandLANDLOCK_PERM_CAPABILITY_USEare handled, both must allow the operation.Five KUnit tests verify the
landlock_ns_type_to_bit()andlandlock_ns_types_to_bits()conversion helpers.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]>--- include/uapi/linux/landlock.h | 58 +++++- security/landlock/Makefile | 1 + security/landlock/access.h | 42 ++++- security/landlock/audit.c | 4 + security/landlock/audit.h | 1 + security/landlock/cred.h | 42 +++++ security/landlock/limits.h | 7 + security/landlock/ns.c | 188 +++++++++++++++++++ security/landlock/ns.h | 74 ++++++++ security/landlock/ruleset.c | 11 +- security/landlock/ruleset.h | 25 ++- security/landlock/setup.c | 2 + security/landlock/syscalls.c | 70 ++++++- tools/testing/selftests/landlock/base_test.c | 2 +- 14 files changed, 509 insertions(+), 18 deletions(-) create mode 100644 security/landlock/ns.c create mode 100644 security/landlock/ns.hinclude/uapi/linux/landlock.h +37
-1@@ -51,6 +51,14 @@ 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 broad +* operation enforced at a kernel chokepoint: all instances of +* that operation are denied unless explicitly allowed by a rule. +* See Documentation/security/landlock.rst for the rationale. +*/ +__u64 handled_perm; };/** @@ -153,6 +161,11 @@ 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, };/** @@ -206,6 +219,24 @@ 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_ENTER. +*/ +__u64 allowed_perm; +/** +* @namespace_types: Bitmask of namespace types (``CLONE_NEW*`` flags) +* that should be allowed to be entered under this rule. Unknown bits +* are silently ignored for forward compatibility. +*/ +__u64 namespace_types; +}; +/** * DOC: fs_access * @@ -379,6 +410,31 @@ 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
include/uapi/linux/landlock.h struct landlock_net_port_attr { · line 428
Quoted 10 lines
include/uapi/linux/landlock.h +10
-0+* ~~~~~~~~~~~~~~~~ +* +* These flags restrict broad operations enforced at kernel chokepoints. +* Each flag names a gateway operation whose control transitively covers +* an open-ended set of downstream operations. 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.
It needs an empty line before the "See Documentation/..." for that to be its own paragraph.
As discussed on the documentation patch, there are a few mentions of "chokepoints" and "gateways" here and elsehwhere in this commit and commit message, which should be updated along if that phrasing changes in the documentation.
(I suggested something like "critical enforcement points" there, and added a suggestion which delineated the permission flags more in terms of (a) not being about individual kernel objects and (b) doing deny-by-default for an open-ended list of operations whose full list is defined in a more core part of the kernel.)
Quoted 735 lines
include/uapi/linux/landlock.h +10
-0+* +* - %LANDLOCK_PERM_NAMESPACE_ENTER: Restrict entering (creating or joining +* via :manpage:`setns(2)`) specific namespace types. A process in a +* Landlock domain that handles this permission is denied from entering +* namespace types that are not explicitly allowed by a +* %LANDLOCK_RULE_NAMESPACE rule. +*/ +/* clang-format off */ +#define LANDLOCK_PERM_NAMESPACE_ENTER (1ULL << 0) +/* clang-format on */ #endif /* _UAPI_LINUX_LANDLOCK_H */ security/landlock/Makefile +1
-0@@ -8,6 +8,7 @@ landlock-y := \ cred.o \ task.o \ fs.o \ + ns.o \ tsync.o landlock-$(CONFIG_INET) += net.osecurity/landlock/access.h +39
-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; };union access_masks_all {@@ -61,14 +64,47 @@ union access_masks_all {static_assert (sizeof (typeof_member (union access_masks_all ,masks )) ==sizeof (typeof_member (union access_masks_all ,all ))); +/** +* struct perm_rules - 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_rules { +/** +* @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 ; +}; + +static_assert (sizeof (struct perm_rules ) ==sizeof (u64)); +/** * struct layer_rights - 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_rights { +/** +* @allowed: Per-layer allowed bitmasks for permission types. +* Placed before @handled to avoid an internal padding hole +* (8-byte perm_rules followed by 4-byte access_masks). +*/ +struct perm_rules allowed;/** * @handled: Bitmask of access rights handled (i.e. restricted) by * this layer. security/landlock/audit.c +4
-0@@ -78,6 +78,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_enter" ; }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 +42
-0@@ -153,6 +153,48 @@ landlock_get_applicable_subject(const struct cred *const cred, return NULL; } +/** +* landlock_perm_is_denied - Check if a permission bitmask request is denied +* +* @domain: The enforced domain. +* @perm_bit: The LANDLOCK_PERM_* flag to check. +* @request_value: Compact bitmask to look for (e.g. result of +* ``landlock_ns_type_to_bit(CLONE_NEWNET)``). +* +* Iterate from the youngest layer to the oldest. For each layer that +* handles @perm_bit, check whether @request_value is present in the +* layer's allowed bitmask. Return on the first (youngest) denying +* layer. +* +* Return: The youngest denying layer + 1, or 0 if allowed. +*/ +static inline size_t +landlock_perm_is_denied (const struct landlock_ruleset *const domain, +const access_mask_t perm_bit,const u64 request_value) +{ +ssize_t layer; + +for (layer = domain->num_layers -1 ; layer >=0 ; layer--) { +u64 allowed; + +if (!(domain->layers[layer].handled.perm & perm_bit)) +continue ; + +switch (perm_bit) { +case LANDLOCK_PERM_NAMESPACE_ENTER : + allowed = domain->layers[layer].allowed.ns; +break ; +default : +WARN_ON_ONCE (1 ); +return layer +1 ; + } + +if (!(allowed & request_value)) +return layer +1 ; + } +return 0 ; +} +__init void landlock_add_cred_hooks (void );#endif /* _SECURITY_LANDLOCK_CRED_H */ 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_ENTER +#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 +188
-0@@ -0,0 +1,188 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Landlock - Namespace hooks +* +* Copyright © 2026 Cloudflare +*/ + +#include <linux/lsm_audit.h> +#include <linux/lsm_hooks.h> +#include <linux/ns/ns_common_types.h> +#include <linux/ns_common.h> +#include <linux/nsproxy.h> +#include <uapi/linux/landlock.h> + +#include "audit.h" +#include "cred.h" +#include "limits.h" +#include "ns.h" +#include "ruleset.h" +#include "setup.h" + +/* Ensures the audit inum field can hold ns_common.inum without truncation. */ +static_assert (sizeof (((struct common_audit_data *)NULL )->u.ns.inum) >= +sizeof (((struct ns_common *)NULL )->inum)); + +static const struct access_masks ns_perm = { + .perm =LANDLOCK_PERM_NAMESPACE_ENTER , +}; + +/** +* hook_namespace_alloc - Check namespace entry permission for creation +* +* @ns: The namespace being initialized. +* +* Checks if the current domain allows entering (creating) this namespace +* type. Fires during unshare(2) and clone(2) via __ns_common_init() in +* kernel/nscommon.c. +* +* Return: 0 if allowed, -EPERM if namespace creation is denied. +*/ +static int hook_namespace_alloc (struct ns_common *const ns) +{ +const struct landlock_cred_security *subject; +size_t denied_layer; + +WARN_ON_ONCE (!(CLONE_NS_ALL & ns->ns_type)); + + subject = +landlock_get_applicable_subject (current_cred (), ns_perm,NULL ); +if (!subject) +return 0 ; + + denied_layer =landlock_perm_is_denied ( + subject->domain,LANDLOCK_PERM_NAMESPACE_ENTER , +landlock_ns_type_to_bit (ns->ns_type)); +if (!denied_layer) +return 0 ; + +landlock_log_denial (subject, &(struct landlock_request ){ + .type =LANDLOCK_REQUEST_NAMESPACE , + .audit.type =LSM_AUDIT_DATA_NS , + .audit.u.ns.ns_type = ns->ns_type, + .layer_plus_one = denied_layer, + }); +return -EPERM ; +} + +/** +* hook_namespace_install - Check namespace entry permission +* +* @nsset: The namespace set being modified. +* @ns: The namespace being entered. +* +* Checks if the current domain restricts entering this namespace type. +* Fires during setns(2) via validate_ns() in kernel/nsproxy.c. +* Uses the same type-based check as hook_namespace_alloc(): the +* restriction is on which namespace types the process can enter, +* regardless of who created the namespace. +* +* Return: 0 if entry is allowed, -EPERM if denied. +*/ +static int hook_namespace_install (const struct nsset *nsset, +struct ns_common *ns) +{ +const struct landlock_cred_security *subject; +size_t denied_layer; + +WARN_ON_ONCE (!(CLONE_NS_ALL & ns->ns_type)); + + subject = +landlock_get_applicable_subject (current_cred (), ns_perm,NULL ); +if (!subject) +return 0 ; + + denied_layer =landlock_perm_is_denied ( + subject->domain,LANDLOCK_PERM_NAMESPACE_ENTER , +landlock_ns_type_to_bit (ns->ns_type)); +if (!denied_layer) +return 0 ; + +landlock_log_denial (subject, &(struct landlock_request ){ + .type =LANDLOCK_REQUEST_NAMESPACE , + .audit.type =LSM_AUDIT_DATA_NS , + .audit.u.ns.ns_type = ns->ns_type, + .audit.u.ns.inum = ns->inum, + .layer_plus_one = denied_layer, + }); +return -EPERM ; +} + +static struct security_hook_list landlock_hooks[]__ro_after_init = { +LSM_HOOK_INIT (namespace_alloc, hook_namespace_alloc), +LSM_HOOK_INIT (namespace_install, hook_namespace_install), +}; + +__init void landlock_add_ns_hooks (void ) +{ +security_add_hooks (landlock_hooks,ARRAY_SIZE (landlock_hooks), + &landlock_lsmid); +} + +#ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST + +#include <kunit/test.h> + +/* clang-format off */ +#define _TEST_NS_BIT (struct_name, flag) \ + do { \ + const u64 bit = landlock_ns_type_to_bit(flag); \ + KUNIT_EXPECT_NE(test, 0ULL, bit); \ + KUNIT_EXPECT_EQ(test, 0ULL, seen &bit); \ + seen |= bit; \ + } while (0); +/* clang-format on */ + +static void test_ns_type_to_bit (struct kunit *const test) +{ +u64 seen =0 ; + +FOR_EACH_NS_TYPE (_TEST_NS_BIT) + + KUNIT_EXPECT_EQ(test, GENMASK_ULL(LANDLOCK_NUM_PERM_NS - 1, 0), seen); +} + +static void test_ns_type_to_bit_unknown (struct kunit *const test) +{ +KUNIT_EXPECT_EQ (test,0ULL ,landlock_ns_type_to_bit (CLONE_THREAD )); +} + +static void test_ns_types_to_bits_all (struct kunit *const test) +{ +KUNIT_EXPECT_EQ (test,GENMASK_ULL (LANDLOCK_NUM_PERM_NS -1 ,0 ), +landlock_ns_types_to_bits (CLONE_NS_ALL )); +} + +/* clang-format off */ +#define _TEST_NS_SINGLE (struct_name, flag) \ + KUNIT_EXPECT_EQ(test, landlock_ns_type_to_bit(flag), \ + landlock_ns_types_to_bits(flag)); +/* clang-format on */ + +static void test_ns_types_to_bits_single (struct kunit *const test) +{ + FOR_EACH_NS_TYPE(_TEST_NS_SINGLE) +} + +static void test_ns_types_to_bits_zero (struct kunit *const test) +{ +KUNIT_EXPECT_EQ (test,0ULL ,landlock_ns_types_to_bits (0 )); +} + +static struct kunit_case test_cases[] = { +KUNIT_CASE (test_ns_type_to_bit), +KUNIT_CASE (test_ns_type_to_bit_unknown), +KUNIT_CASE (test_ns_types_to_bits_all), +KUNIT_CASE (test_ns_types_to_bits_single), +KUNIT_CASE (test_ns_types_to_bits_zero), + {} +}; + +static struct kunit_suite test_suite = { + .name ="landlock_ns" , + .test_cases = test_cases, +}; + +kunit_test_suite (test_suite); + +#endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */ security/landlock/ns.h new file +74
-0@@ -0,0 +1,74 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Landlock - Namespace hooks +* +* Copyright © 2026 Cloudflare +*/ + +#ifndef _SECURITY_LANDLOCK_NS_H +#define _SECURITY_LANDLOCK_NS_H + +#include <linux/bitops.h> +#include <linux/bug.h> +#include <linux/compiler_attributes.h> +#include <linux/ns/ns_common_types.h> +#include <linux/types.h> + +#include "limits.h" + +/* _LANDLOCK_NS_CLONE_NEWCGROUP, */ +#define _LANDLOCK_NS_ENUM (struct_name, flag) _LANDLOCK_NS_##flag, + +/* _LANDLOCK_NS_CLONE_NEWCGROUP = 0, */ +enum { + FOR_EACH_NS_TYPE(_LANDLOCK_NS_ENUM) _LANDLOCK_NUM_NS_TYPES, +}; + +static_assert (_LANDLOCK_NUM_NS_TYPES ==LANDLOCK_NUM_PERM_NS ); + +/* +* case CLONE_NEWCGROUP: +* return BIT_ULL(_LANDLOCK_NS_CLONE_NEWCGROUP); +*/ +/* clang-format off */ +#define _LANDLOCK_NS_CASE (struct_name, flag) \ + case flag: \ + return BIT_ULL(_LANDLOCK_NS_##flag); +/* clang-format on */ + +static inline __attribute_const__ u64 +landlock_ns_type_to_bit (const unsigned long ns_type) +{ +switch (ns_type) { +FOR_EACH_NS_TYPE (_LANDLOCK_NS_CASE) + default: + WARN_ON_ONCE(1); +return 0 ; + } +} + +/* +* if (ns_types & CLONE_NEWCGROUP) +* bits |= BIT_ULL(_LANDLOCK_NS_CLONE_NEWCGROUP); +*/ +/* clang-format off */ +#define _LANDLOCK_NS_CONVERT (struct_name, flag) \ + do { \ + if (ns_types & (flag)) \ + bits |= BIT_ULL(_LANDLOCK_NS_##flag); \ + } while (0); +/* clang-format on */ + +static inline __attribute_const__ u64 +landlock_ns_types_to_bits (const u64 ns_types) +{ +u64 bits =0 ; + +WARN_ON_ONCE (ns_types & ~CLONE_NS_ALL ); +FOR_EACH_NS_TYPE (_LANDLOCK_NS_CONVERT) + return bits; +} + +__init void landlock_add_ns_hooks (void ); + +#endif /* _SECURITY_LANDLOCK_NS_H */ 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@@ -190,10 +190,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);@@ -303,6 +302,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 +66
-4@@ -20,6 +20,7 @@#include <linux/fs.h> #include <linux/limits.h> #include <linux/mount.h> +#include <linux/ns/ns_common_types.h> #include <linux/path.h> #include <linux/sched.h> #include <linux/security.h> @@ -34,6 +35,7 @@#include "fs.h" #include "limits.h" #include "net.h" +#include "ns.h" #include "ruleset.h" #include "setup.h" #include "tsync.h" @@ -95,7 +97,9 @@ static void build_check_abi(void)struct landlock_ruleset_attr ruleset_attr;struct landlock_path_beneath_attr path_beneath_attr;struct landlock_net_port_attr net_port_attr; +struct landlock_namespace_attr namespace_attr;size_t ruleset_size, path_beneath_size, net_port_size; +size_t namespace_size;/* * For each user space ABI structures, first checks that there is no @@ -105,8 +109,9 @@ static void build_check_abi(void) ruleset_size =sizeof (ruleset_attr.handled_access_fs); ruleset_size +=sizeof (ruleset_attr.handled_access_net); ruleset_size +=sizeof (ruleset_attr.scoped); + ruleset_size +=sizeof (ruleset_attr.handled_perm);BUILD_BUG_ON (sizeof (ruleset_attr) != ruleset_size); -BUILD_BUG_ON (sizeof (ruleset_attr) !=24 ); +BUILD_BUG_ON (sizeof (ruleset_attr) !=32 ); path_beneath_size =sizeof (path_beneath_attr.allowed_access); path_beneath_size +=sizeof (path_beneath_attr.parent_fd);@@ -117,6 +122,11 @@ static void build_check_abi(void) net_port_size +=sizeof (net_port_attr.port);BUILD_BUG_ON (sizeof (net_port_attr) != net_port_size);BUILD_BUG_ON (sizeof (net_port_attr) !=16 ); + + namespace_size =sizeof (namespace_attr.allowed_perm); + namespace_size +=sizeof (namespace_attr.namespace_types); +BUILD_BUG_ON (sizeof (namespace_attr) != namespace_size); +BUILD_BUG_ON (sizeof (namespace_attr) !=16 ); }/* Ruleset handling */ @@ -166,7 +176,7 @@ static const struct file_operations ruleset_fops = {* If the change involves a fix that requires userspace awareness, also update * the errata documentation in Documentation/userspace-api/landlock.rst . */ -const int landlock_abi_version =8 ; +const int landlock_abi_version =9 ;/** * sys_landlock_create_ruleset - Create a new ruleset @@ -249,10 +259,16 @@ SYSCALL_DEFINE3(landlock_create_ruleset,if ((ruleset_attr.scoped |LANDLOCK_MASK_SCOPE ) !=LANDLOCK_MASK_SCOPE )return -EINVAL ; +/* Checks permission content (and 32-bits cast). */ +if ((ruleset_attr.handled_perm |LANDLOCK_MASK_PERM ) != +LANDLOCK_MASK_PERM ) +return -EINVAL ; +/* Checks arguments and transforms to kernel struct. */ ruleset =landlock_create_ruleset (ruleset_attr.handled_access_fs, ruleset_attr.handled_access_net, - ruleset_attr.scoped); + ruleset_attr.scoped, + ruleset_attr.handled_perm);if (IS_ERR (ruleset))return PTR_ERR (ruleset);@@ -390,13 +406,57 @@ static int add_rule_net_port(struct landlock_ruleset *ruleset, net_port_attr.allowed_access); } +static int add_rule_namespace (struct landlock_ruleset *const ruleset, +const void __user *const rule_attr) +{ +struct landlock_namespace_attr ns_attr; +int res; +access_mask_t mask; + +/* Copies raw user space buffer. */ + res =copy_from_user (&ns_attr, rule_attr,sizeof (ns_attr)); +if (res) +return -EFAULT ; + +/* Informs about useless rule: empty allowed_perm. */ +if (!ns_attr.allowed_perm) +return -ENOMSG ; + +/* The allowed_perm must match LANDLOCK_PERM_NAMESPACE_ENTER. */ +if (ns_attr.allowed_perm !=LANDLOCK_PERM_NAMESPACE_ENTER ) +return -EINVAL ; + +/* Checks that allowed_perm matches the @ruleset constraints. */ + mask =landlock_get_perm_mask (ruleset,0 ); +if (!(mask &LANDLOCK_PERM_NAMESPACE_ENTER )) +return -EINVAL ; + +/* Informs about useless rule: empty namespace_types. */ +if (!ns_attr.namespace_types) +return -ENOMSG ; + +/* +* Stores only the namespace types this kernel knows about. +* Unknown bits are silently accepted for forward compatibility: +* user space compiled against newer headers can pass new +* CLONE_NEW* flags without getting EINVAL on older kernels. +* Unknown bits have no effect because no hook checks them. +*/ +mutex_lock (&ruleset->lock); + ruleset->layers[0 ].allowed.ns |=landlock_ns_types_to_bits ( + ns_attr.namespace_types &CLONE_NS_ALL ); +mutex_unlock (&ruleset->lock); +return 0 ; +} +/** * sys_landlock_add_rule - Add a new rule to a ruleset * * @ruleset_fd: File descriptor tied to the ruleset that should be extended * with the new rule. * @rule_type: Identify the structure type pointed to by @rule_attr: -* %LANDLOCK_RULE_PATH_BENEATH or %LANDLOCK_RULE_NET_PORT. +* %LANDLOCK_RULE_PATH_BENEATH, %LANDLOCK_RULE_NET_PORT, or +* %LANDLOCK_RULE_NAMESPACE. * @rule_attr: Pointer to a rule (matching the @rule_type). * @flags: Must be 0. * @@ -446,6 +506,8 @@ SYSCALL_DEFINE4(landlock_add_rule, const int, ruleset_fd,return add_rule_path_beneath (ruleset, rule_attr);case LANDLOCK_RULE_NET_PORT :return add_rule_net_port (ruleset, rule_attr); +case LANDLOCK_RULE_NAMESPACE : +return add_rule_namespace (ruleset, rule_attr);default :return -EINVAL ; }tools/testing/selftests/landlock/base_test.c +1
-1@@ -76,7 +76,7 @@ TEST(abi_version)const struct landlock_ruleset_attr ruleset_attr = { .handled_access_fs =LANDLOCK_ACCESS_FS_READ_FILE , }; -ASSERT_EQ (8 ,landlock_create_ruleset (NULL ,0 , +ASSERT_EQ (9 ,landlock_create_ruleset (NULL ,0 ,LANDLOCK_CREATE_RULESET_VERSION )); ASSERT_EQ(-1, landlock_create_ruleset(&ruleset_attr, 0,Signature · 1 line
2.53.0
Documentation remarks above are minor, please feel free to tag as reviewed. I could not find any issues in the code.
—Günther
Mickaël Salaün
maintainerRFC PATCH 6/11 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: it runs after cap_capable() (LSM_ORDER_FIRST), so it can deny capabilities that commoncap would allow, but it can 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_ENTER.
Adding the 41-bit capability bitfield to struct perm_rules brings it to 49 out of 64 bits used (41 caps + 8 namespace types, 15 bits padding), keeping struct layer_rights at 16 bytes (8 bytes perm_rules + 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_rules (before the ns bitfield) because capabilities use a direct BIT_ULL(cap) mapping that benefits from starting at bit 0 of the storage unit.
Non-user namespace operations require both LANDLOCK_PERM_NAMESPACE_ENTER (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.
--- include/uapi/linux/landlock.h | 31 ++++++++ security/landlock/Makefile | 1 + security/landlock/access.h | 15 +++- security/landlock/audit.c | 4 + security/landlock/audit.h | 1 + security/landlock/cap.c | 142 ++++++++++++++++++++++++++++++++++ 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, 302 insertions(+), 8 deletions(-) create mode 100644 security/landlock/cap.c create mode 100644 security/landlock/cap.h
include/uapi/linux/landlock.h +31 -0
@@ -166,6 +166,11 @@ enum landlock_rule_type {* landlock_namespace_attr . */ LANDLOCK_RULE_NAMESPACE , +/** +* @LANDLOCK_RULE_CAPABILITY: Type of a &struct +* landlock_capability_attr . +*/ + LANDLOCK_RULE_CAPABILITY, };/**
@@ -237,6 +242,24 @@ 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_*``) that +* should be allowed for use under this rule. Bits above +* ``CAP_LAST_CAP`` are silently ignored for forward compatibility. +*/ +__u64 capabilities; +}; +/** * DOC: fs_access *
@@ -432,9 +455,17 @@ struct landlock_namespace_attr {* Landlock domain that handles this permission is denied from entering * 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_ENTER (1ULL << 0) +#define LANDLOCK_PERM_CAPABILITY_USE (1ULL << 1)/* clang-format on */ #endif /* _UAPI_LINUX_LANDLOCK_H */
security/landlock/Makefile +1 -0
@@ -9,6 +9,7 @@ landlock-y := \ task.o \ fs.o \ ns.o \ + cap.o \ tsync.o landlock-$(CONFIG_INET) += net.o
security/landlock/access.h +11 -4
@@ -72,6 +72,13 @@ static_assert(sizeof(typeof_member(union access_masks_all, masks)) ==* a single 64-bit storage unit. */ struct perm_rules { +/** +* @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
@@ -93,10 +100,10 @@ static_assert(sizeof(struct perm_rules) == sizeof(u64));* 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). +* in 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_rights {/**
security/landlock/audit.c +4 -0
@@ -82,6 +82,10 @@ get_blocker(const enum landlock_request_type type,case LANDLOCK_REQUEST_NAMESPACE :WARN_ON_ONCE (access_bit !=-1 );return "perm.namespace_enter" ; + +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 +142 -0
142 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
@@ -184,6 +184,9 @@ landlock_perm_is_denied(const struct landlock_ruleset *const domain,case LANDLOCK_PERM_NAMESPACE_ENTER : 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_ENTER +#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.53.0
Re: [RFC PATCH v1 06/11] landlock: Enforce capability restrictions
Hello!
Quoted 7 lines · Mickaël Salaün
security/landlock/syscalls.c +1
-0+/*
security/landlock/syscalls.c static int add_rule_namespace(struct landlock_ruleset *const ruleset, · line 498
Quoted 10 lines
security/landlock/syscalls.c +10
-0+* Stores only the capabilities this kernel knows about. +* Unknown bits are silently accepted for forward compatibility: +* user space compiled against newer headers can pass new +* CAP_* bits without getting EINVAL on older kernels. +* Unknown bits have no effect because no hook checks them. +*/ +mutex_lock (&ruleset->lock); + ruleset->layers[0 ].allowed.caps |= +landlock_caps_to_bits (cap_attr.capabilities &CAP_VALID_MASK ); +mutex_unlock (&ruleset->lock);
See the example in the documentation patch set [1]; I think it can be an incompatibility if we ignore the unknown bits here (and I don't know of a scenario where it would be a problem to reject them).
[1] https://lore.kernel.org/all/[email protected]/
–Günther
Re: [RFC PATCH v1 06/11] landlock: Enforce capability restrictions
In reply to Mickaël SalaünQuoted 560 lines · Mickaël Salaün
Add 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_USEand per-capability rules.The capable hook is purely restrictive: it runs after
cap_capable()(LSM_ORDER_FIRST), so it can deny capabilities that commoncap would allow, but it can never grant capabilities that commoncap denied.Add
hook_capable()that useslandlock_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 byLANDLOCK_PERM_NAMESPACE_ENTER.Adding the 41-bit capability bitfield to struct
perm_rulesbrings it to 49 out of 64 bits used (41 caps + 8 namespace types, 15 bits padding), keeping structlayer_rightsat 16 bytes (8 bytesperm_rules+ 4 bytesaccess_masks+ 4 bytes tail padding) and the layers[] array at 256 bytes maximum. The caps bitfield is placed first in structperm_rules(before the ns bitfield) because capabilities use a directBIT_ULL(cap)mapping that benefits from starting at bit 0 of the storage unit.Non-user namespace operations require both
LANDLOCK_PERM_NAMESPACE_ENTER(type allowed) andLANDLOCK_PERM_CAPABILITY_USE(CAP_SYS_ADMINallowed) when both permissions are handled. This follows naturally from the kernel callingcapable(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
-EPERMwhen attempting to use any denied capability.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]>--- include/uapi/linux/landlock.h | 31 ++++++++ security/landlock/Makefile | 1 + security/landlock/access.h | 15 +++- security/landlock/audit.c | 4 + security/landlock/audit.h | 1 + security/landlock/cap.c | 142 ++++++++++++++++++++++++++++++++++ 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, 302 insertions(+), 8 deletions(-) create mode 100644 security/landlock/cap.c create mode 100644 security/landlock/cap.hinclude/uapi/linux/landlock.h +31
-0@@ -166,6 +166,11 @@ enum landlock_rule_type {* landlock_namespace_attr . */ LANDLOCK_RULE_NAMESPACE , +/** +* @LANDLOCK_RULE_CAPABILITY: Type of a &struct +* landlock_capability_attr . +*/ + LANDLOCK_RULE_CAPABILITY, };/** @@ -237,6 +242,24 @@ 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_*``) that +* should be allowed for use under this rule. Bits above +* ``CAP_LAST_CAP`` are silently ignored for forward compatibility. +*/ +__u64 capabilities; +}; +/** * DOC: fs_access * @@ -432,9 +455,17 @@ struct landlock_namespace_attr {* Landlock domain that handles this permission is denied from entering * 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_ENTER (1ULL << 0) +#define LANDLOCK_PERM_CAPABILITY_USE (1ULL << 1)/* clang-format on */ #endif /* _UAPI_LINUX_LANDLOCK_H */ security/landlock/Makefile +1
-0@@ -9,6 +9,7 @@ landlock-y := \ task.o \ fs.o \ ns.o \ + cap.o \ tsync.o landlock-$(CONFIG_INET) += net.osecurity/landlock/access.h +11
-4@@ -72,6 +72,13 @@ static_assert(sizeof(typeof_member(union access_masks_all, masks)) ==* a single 64-bit storage unit. */ struct perm_rules { +/** +* @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 @@ -93,10 +100,10 @@ static_assert(sizeof(struct perm_rules) == sizeof(u64));* 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). +* in 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_rights {/** security/landlock/audit.c +4
-0@@ -82,6 +82,10 @@ get_blocker(const enum landlock_request_type type,case LANDLOCK_REQUEST_NAMESPACE :WARN_ON_ONCE (access_bit !=-1 );return "perm.namespace_enter" ; + +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 +142
-0@@ -0,0 +1,142 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Landlock - Capability hooks +* +* Copyright © 2026 Cloudflare +*/ + +#include <linux/capability.h> +#include <linux/cred.h> +#include <linux/lsm_audit.h> +#include <linux/lsm_hooks.h> +#include <uapi/linux/landlock.h> + +#include "audit.h" +#include "cap.h" +#include "cred.h" +#include "limits.h" +#include "ruleset.h" +#include "setup.h" + +static const struct access_masks cap_perm = { + .perm =LANDLOCK_PERM_CAPABILITY_USE , +}; + +/** +* hook_capable - Deny capability use for Landlock-sandboxed processes +* +* @cred: Credentials being checked. +* @ns: User namespace for the capability check. +* @cap: Capability number (CAP_*). +* @opts: Capability check options. CAP_OPT_NOAUDIT suppresses audit logging. +* +* Pure bitmask check: denies the capability if it is not in the layer's +* allowed set. This hook is purely restrictive: it runs after +* cap_capable() (LSM_ORDER_FIRST), so it can deny capabilities that +* commoncap would allow, but it can never grant capabilities that +* commoncap denied. +* +* Return: 0 if allowed, -EPERM if capability use is denied. +*/ +static int hook_capable (const struct cred *cred,struct user_namespace *ns, +int cap,unsigned int opts) +{ +const struct landlock_cred_security *subject; +size_t denied_layer; + + subject =landlock_get_applicable_subject (cred, cap_perm,NULL ); +if (!subject) +return 0 ; + + denied_layer =landlock_perm_is_denied (subject->domain, +LANDLOCK_PERM_CAPABILITY_USE , +landlock_cap_to_bit (cap)); +if (!denied_layer) +return 0 ; + +/* +* Respects CAP_OPT_NOAUDIT to suppress audit records for +* capability probes (e.g., ns_capable_noaudit(), +* has_capability_noaudit()). +*/ +if (!(opts &CAP_OPT_NOAUDIT )) +landlock_log_denial (subject, + &(struct landlock_request ){ + .type =LANDLOCK_REQUEST_CAPABILITY , + .audit.type =LSM_AUDIT_DATA_CAP , + .audit.u.cap = cap, + .layer_plus_one = denied_layer, + }); + +return -EPERM ; +} + +static struct security_hook_list landlock_hooks[]__ro_after_init = { +LSM_HOOK_INIT (capable, hook_capable), +}; + +__init void landlock_add_cap_hooks (void ) +{ +security_add_hooks (landlock_hooks,ARRAY_SIZE (landlock_hooks), + &landlock_lsmid); +} + +#ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST + +#include <kunit/test.h> + +static void test_cap_to_bit (struct kunit *const test) +{ +KUNIT_EXPECT_EQ (test,BIT_ULL (0 ),landlock_cap_to_bit (0 )); +KUNIT_EXPECT_EQ (test,BIT_ULL (CAP_NET_RAW ), +landlock_cap_to_bit (CAP_NET_RAW )); +KUNIT_EXPECT_EQ (test,BIT_ULL (CAP_SYS_ADMIN ), +landlock_cap_to_bit (CAP_SYS_ADMIN )); +KUNIT_EXPECT_EQ (test,BIT_ULL (CAP_LAST_CAP ), +landlock_cap_to_bit (CAP_LAST_CAP )); +} + +static void test_cap_to_bit_invalid (struct kunit *const test) +{ +KUNIT_EXPECT_EQ (test,0ULL ,landlock_cap_to_bit (-1 )); +KUNIT_EXPECT_EQ (test,0ULL ,landlock_cap_to_bit (CAP_LAST_CAP +1 )); +} + +static void test_caps_to_bits_valid (struct kunit *const test) +{ +KUNIT_EXPECT_EQ (test, (u64 )CAP_VALID_MASK , +landlock_caps_to_bits (CAP_VALID_MASK )); +KUNIT_EXPECT_EQ (test,BIT_ULL (CAP_NET_RAW ), +landlock_caps_to_bits (BIT_ULL (CAP_NET_RAW ))); +} + +static void test_caps_to_bits_unknown (struct kunit *const test) +{ +KUNIT_EXPECT_EQ (test,0ULL , +landlock_caps_to_bits (BIT_ULL (CAP_LAST_CAP +1 ))); +} + +static void test_caps_to_bits_zero (struct kunit *const test) +{ +KUNIT_EXPECT_EQ (test,0ULL ,landlock_caps_to_bits (0 )); +} + +static struct kunit_case test_cases[] = { +/* clang-format off */ +KUNIT_CASE (test_cap_to_bit), +KUNIT_CASE (test_cap_to_bit_invalid), +KUNIT_CASE (test_caps_to_bits_valid), +KUNIT_CASE (test_caps_to_bits_unknown), +KUNIT_CASE (test_caps_to_bits_zero), + {} +/* clang-format on */ +}; + +static struct kunit_suite test_suite = { + .name ="landlock_cap" , + .test_cases = test_cases, +}; + +kunit_test_suite (test_suite); + +#endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */ security/landlock/cap.h new file +49
-0@@ -0,0 +1,49 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Landlock - Capability hooks +* +* Copyright © 2026 Cloudflare +*/ + +#ifndef _SECURITY_LANDLOCK_CAP_H +#define _SECURITY_LANDLOCK_CAP_H + +#include <linux/bitops.h> +#include <linux/bug.h> +#include <linux/capability.h> +#include <linux/compiler_attributes.h> +#include <linux/types.h> + +/** +* landlock_cap_to_bit - Convert a capability number to a compact bitmask +* +* @cap: Capability number (CAP_*). +* +* Return: BIT_ULL(@cap), or 0 if @cap is invalid (with a WARN). +*/ +static inline __attribute_const__ u64 landlock_cap_to_bit(const int cap) +{ +if (WARN_ON_ONCE (!cap_valid (cap))) +return 0 ; + +return BIT_ULL (cap); +} + +/** +* landlock_caps_to_bits - Validate and mask a capability bitmask +* +* @capabilities: Bitmask of capabilities (e.g. from user space). +* +* Return: @capabilities masked to known capabilities. Warns if unknown +* bits are present (callers must pre-mask for user input). +*/ +static inline __attribute_const__ u64 +landlock_caps_to_bits (const u64 capabilities) +{ +WARN_ON_ONCE (capabilities & ~CAP_VALID_MASK ); +return capabilities &CAP_VALID_MASK ; +} + +__init void landlock_add_cap_hooks (void ); + +#endif /* _SECURITY_LANDLOCK_CAP_H */ security/landlock/cred.h +3
-0@@ -184,6 +184,9 @@ landlock_perm_is_denied(const struct landlock_ruleset *const domain,case LANDLOCK_PERM_NAMESPACE_ENTER : 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_ENTER +#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@@ -30,6 +30,7 @@#include <linux/uaccess.h> #include <uapi/linux/landlock.h> +#include "cap.h" #include "cred.h" #include "domain.h" #include "fs.h" @@ -98,8 +99,9 @@ static void build_check_abi(void)struct landlock_path_beneath_attr path_beneath_attr;struct landlock_net_port_attr net_port_attr;struct landlock_namespace_attr namespace_attr; +struct landlock_capability_attr capability_attr;size_t ruleset_size, path_beneath_size, net_port_size; -size_t namespace_size; +size_t namespace_size, capability_size;/* * For each user space ABI structures, first checks that there is no @@ -127,6 +129,11 @@ static void build_check_abi(void) namespace_size +=sizeof (namespace_attr.namespace_types);BUILD_BUG_ON (sizeof (namespace_attr) != namespace_size);BUILD_BUG_ON (sizeof (namespace_attr) !=16 ); + + capability_size =sizeof (capability_attr.allowed_perm); + capability_size +=sizeof (capability_attr.capabilities); +BUILD_BUG_ON (sizeof (capability_attr) != capability_size); +BUILD_BUG_ON (sizeof (capability_attr) !=16 ); }/* Ruleset handling */ @@ -449,14 +456,57 @@ static int add_rule_namespace(struct landlock_ruleset *const ruleset,return 0 ; } +static int add_rule_capability (struct landlock_ruleset *const ruleset, +const void __user *const rule_attr) +{ +struct landlock_capability_attr cap_attr; +int res; +access_mask_t mask; + +/* Copies raw user space buffer. */ + res =copy_from_user (&cap_attr, rule_attr,sizeof (cap_attr)); +if (res) +return -EFAULT ; + +/* Informs about useless rule: empty allowed_perm. */ +if (!cap_attr.allowed_perm) +return -ENOMSG ; + +/* The allowed_perm must match LANDLOCK_PERM_CAPABILITY_USE. */ +if (cap_attr.allowed_perm !=LANDLOCK_PERM_CAPABILITY_USE ) +return -EINVAL ; + +/* Checks that allowed_perm matches the @ruleset constraints. */ + mask =landlock_get_perm_mask (ruleset,0 ); +if (!(mask &LANDLOCK_PERM_CAPABILITY_USE )) +return -EINVAL ; + +/* Informs about useless rule: empty capabilities. */ +if (!cap_attr.capabilities) +return -ENOMSG ; + +/* +* Stores only the capabilities this kernel knows about. +* Unknown bits are silently accepted for forward compatibility: +* user space compiled against newer headers can pass new +* CAP_* bits without getting EINVAL on older kernels. +* Unknown bits have no effect because no hook checks them. +*/ +mutex_lock (&ruleset->lock); + ruleset->layers[0 ].allowed.caps |= +landlock_caps_to_bits (cap_attr.capabilities &CAP_VALID_MASK ); +mutex_unlock (&ruleset->lock); +return 0 ; +} +/** * sys_landlock_add_rule - Add a new rule to a ruleset * * @ruleset_fd: File descriptor tied to the ruleset that should be extended * with the new rule. * @rule_type: Identify the structure type pointed to by @rule_attr: -* %LANDLOCK_RULE_PATH_BENEATH, %LANDLOCK_RULE_NET_PORT, or -* %LANDLOCK_RULE_NAMESPACE. +* %LANDLOCK_RULE_PATH_BENEATH, %LANDLOCK_RULE_NET_PORT, +* %LANDLOCK_RULE_NAMESPACE, or %LANDLOCK_RULE_CAPABILITY. * @rule_attr: Pointer to a rule (matching the @rule_type). * @flags: Must be 0. * @@ -508,6 +558,8 @@ SYSCALL_DEFINE4(landlock_add_rule, const int, ruleset_fd,return add_rule_net_port (ruleset, rule_attr);case LANDLOCK_RULE_NAMESPACE :return add_rule_namespace (ruleset, rule_attr); +case LANDLOCK_RULE_CAPABILITY : +return add_rule_capability (ruleset, rule_attr);default :return -EINVAL ; }Signature · 1 line
2.53.0
—Günther
Mickaël Salaün
maintainerRFC PATCH 7/11 selftests/landlock: Drain stale audit records on init
In reply to Mickaël SalaünNon-audit Landlock tests generate audit records as side effects when audit_enabled is non-zero (e.g. from boot configuration). These records accumulate in the kernel audit backlog while no audit daemon socket is open. When the next test opens a new netlink socket and registers as the audit daemon, the stale backlog is delivered, causing baseline record count checks to fail spuriously.
Fix this by draining all pending records in audit_init() right after setting the receive timeout. The 1-usec SO_RCVTIMEO causes audit_recv() to return -EAGAIN once the backlog is empty, naturally terminating the drain loop.
Domain deallocation records are emitted asynchronously from a work queue, so they may still arrive after the drain. Remove records.domain == 0 checks from tests where a stale deallocation record from a previous test could cause spurious failures.
Also fix a socket file descriptor leak on error paths in audit_init():
if audit_set_status() or setsockopt() fails (e.g. when another audit daemon is already registered), close the socket before returning.
Fix off-by-one checks in matches_log_domain_allocated() and matches_log_domain_deallocated() where snprintf() truncation was detected with ">" instead of ">=" (snprintf() returns the length excluding the NUL terminator, so equality means truncation).
--- tools/testing/selftests/landlock/audit.h | 29 +++++++++++++++---- tools/testing/selftests/landlock/audit_test.c | 2 -- 2 files changed, 23 insertions(+), 8 deletions(-)
tools/testing/selftests/landlock/audit.h +23 -6
@@ -309,7 +309,7 @@ static int __maybe_unused matches_log_domain_allocated(int audit_fd, pid_t pid, log_match_len =snprintf (log_match,sizeof (log_match), log_template, pid); -if (log_match_len >sizeof (log_match)) +if (log_match_len >=sizeof (log_match))return -E2BIG ; return audit_match_record(audit_fd, AUDIT_LANDLOCK_DOMAIN, log_match,
@@ -326,7 +326,7 @@ static int __maybe_unused matches_log_domain_deallocated( log_match_len =snprintf (log_match,sizeof (log_match), log_template, num_denials); -if (log_match_len >sizeof (log_match)) +if (log_match_len >=sizeof (log_match))return -E2BIG ; return audit_match_record(audit_fd, AUDIT_LANDLOCK_DOMAIN, log_match,
@@ -379,19 +379,36 @@ static int audit_init(void) err =audit_set_status (fd,AUDIT_STATUS_ENABLED ,1 );if (err) -return err; + goto err_close; err =audit_set_status (fd,AUDIT_STATUS_PID ,getpid ());if (err) -return err; + goto err_close;/* Sets a timeout for negative tests. */ err =setsockopt (fd,SOL_SOCKET ,SO_RCVTIMEO , &audit_tv_default,sizeof (audit_tv_default)); -if (err) -return -errno; +if (err) { + err = -errno; + goto err_close; + } + +/* +* Drains stale audit records that accumulated in the kernel backlog +* while no audit daemon socket was open. This happens when +* non-audit Landlock tests create domains or trigger denials while +* audit_enabled is non-zero (e.g. from boot configuration), or when +* domain deallocation records arrive asynchronously after a +* previous test's socket was closed. +*/ +while (audit_recv (fd,NULL ) ==0 ) + ;return fd; + +err_close: +close (fd); +return err; }static int audit_init_filter_exe (struct audit_filter *filter,const char *path)
tools/testing/selftests/landlock/audit_test.c +0 -2
@@ -412,7 +412,6 @@ TEST_F(audit_flags, signal) }else {EXPECT_EQ (1 , records.access); } -EXPECT_EQ (0 , records.domain);/* Updates filter rules to match the drop record. */ set_cap (_metadata,CAP_AUDIT_CONTROL );
@@ -601,7 +600,6 @@ TEST_F(audit_exec, signal_and_open)/* Tests that there was no denial until now. */ EXPECT_EQ (0 ,audit_count_records (self->audit_fd, &records));EXPECT_EQ (0 , records.access); -EXPECT_EQ (0 , records.domain);/* * Wait for the child to do a first denied action by layer1 and
Signature · 1 line
2.53.0
Re: [RFC PATCH v1 07/11] selftests/landlock: Drain stale audit records on init
Quoted 120 lines · Mickaël Salaün
Non-audit Landlock tests generate audit records as side effects when
audit_enabledis non-zero (e.g. from boot configuration). These records accumulate in the kernel audit backlog while no audit daemon socket is open. When the next test opens a new netlink socket and registers as the audit daemon, the stale backlog is delivered, causing baseline record count checks to fail spuriously.Fix this by draining all pending records in
audit_init()right after setting the receive timeout. The 1-usecSO_RCVTIMEOcausesaudit_recv()to return-EAGAINonce the backlog is empty, naturally terminating the drain loop.Domain deallocation records are emitted asynchronously from a work queue, so they may still arrive after the drain. Remove records.domain == 0 checks from tests where a stale deallocation record from a previous test could cause spurious failures.
Also fix a socket file descriptor leak on error paths in
audit_init():
ifaudit_set_status()orsetsockopt()fails (e.g. when another audit daemon is already registered), close the socket before returning.Fix off-by-one checks in
matches_log_domain_allocated()andmatches_log_domain_deallocated()wheresnprintf()truncation was detected with ">" instead of ">=" (snprintf()returns the length excluding the NUL terminator, so equality means truncation).Cc Günther Noack <[email protected]>Fixes 6a500b22971c ("selftests/landlock: Add tests for audit flags and domain IDs")Signed-off-by Mickaël Salaün <[email protected]>--- tools/testing/selftests/landlock/audit.h | 29 +++++++++++++++---- tools/testing/selftests/landlock/audit_test.c | 2 -- 2 files changed, 23 insertions(+), 8 deletions(-)tools/testing/selftests/landlock/audit.h +23
-6@@ -309,7 +309,7 @@ static int __maybe_unused matches_log_domain_allocated(int audit_fd, pid_t pid, log_match_len =snprintf (log_match,sizeof (log_match), log_template, pid); -if (log_match_len >sizeof (log_match)) +if (log_match_len >=sizeof (log_match))return -E2BIG ; return audit_match_record(audit_fd, AUDIT_LANDLOCK_DOMAIN, log_match,@@ -326,7 +326,7 @@ static int __maybe_unused matches_log_domain_deallocated( log_match_len =snprintf (log_match,sizeof (log_match), log_template, num_denials); -if (log_match_len >sizeof (log_match)) +if (log_match_len >=sizeof (log_match))return -E2BIG ; return audit_match_record(audit_fd, AUDIT_LANDLOCK_DOMAIN, log_match,@@ -379,19 +379,36 @@ static int audit_init(void) err =audit_set_status (fd,AUDIT_STATUS_ENABLED ,1 );if (err) -return err; + goto err_close; err =audit_set_status (fd,AUDIT_STATUS_PID ,getpid ());if (err) -return err; + goto err_close;/* Sets a timeout for negative tests. */ err =setsockopt (fd,SOL_SOCKET ,SO_RCVTIMEO , &audit_tv_default,sizeof (audit_tv_default)); -if (err) -return -errno; +if (err) { + err = -errno; + goto err_close; + } + +/* +* Drains stale audit records that accumulated in the kernel backlog +* while no audit daemon socket was open. This happens when +* non-audit Landlock tests create domains or trigger denials while +* audit_enabled is non-zero (e.g. from boot configuration), or when +* domain deallocation records arrive asynchronously after a +* previous test's socket was closed. +*/ +while (audit_recv (fd,NULL ) ==0 ) + ;return fd; + +err_close: +close (fd); +return err; }static int audit_init_filter_exe (struct audit_filter *filter,const char *path)tools/testing/selftests/landlock/audit_test.c +0
-2@@ -412,7 +412,6 @@ TEST_F(audit_flags, signal) }else {EXPECT_EQ (1 , records.access); } -EXPECT_EQ (0 , records.domain);/* Updates filter rules to match the drop record. */ set_cap (_metadata,CAP_AUDIT_CONTROL );@@ -601,7 +600,6 @@ TEST_F(audit_exec, signal_and_open)/* Tests that there was no denial until now. */ EXPECT_EQ (0 ,audit_count_records (self->audit_fd, &records));EXPECT_EQ (0 , records.access); -EXPECT_EQ (0 , records.domain);/* * Wait for the child to do a first denied action by layer1 and Signature · 1 line
2.53.0
Ooh, nice catch! I have definitely stumbled across this bug in the past (especially when the kernel is compiled with more debugging options), and I know from Justin that he ran into it as well. Draining the audit logs before sending a new stimulus for audit logging looks like a good approach.
—Günther
Mickaël Salaün
maintainerRFC PATCH 8/11 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_ENTER (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.
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_alloc() is correctly called for every type. Layer stacking tests verify that any-layer-denies semantics work correctly, including the allow-over-allow case. A combined test exercises both LANDLOCK_PERM_CAPABILITY_USE and LANDLOCK_PERM_NAMESPACE_ENTER in a single domain.
Namespace entry tests verify that setns is subject to the same type-based LANDLOCK_PERM_NAMESPACE_ENTER check via security_namespace_install(), including cross-process setns denial and the two-permission interaction where both LANDLOCK_PERM_NAMESPACE_ENTER and LANDLOCK_PERM_CAPABILITY_USE must allow the operation for non-user namespaces.
Audit tests verify that denied namespace creation, denied setns entry, and allowed operations produce the expected audit records (or none).
--- tools/testing/selftests/landlock/common.h | 23 + tools/testing/selftests/landlock/config | 5 + tools/testing/selftests/landlock/ns_test.c | 1379 +++++++++++++++++++ tools/testing/selftests/landlock/wrappers.h | 6 + 4 files changed, 1413 insertions(+) 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/ns_test.c new file +1379 -0
1,379 lines not on this page · raw message
tools/testing/selftests/landlock/wrappers.h +6 -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,8 @@ 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); +}
Signature · 1 line
2.53.0
Mickaël Salaün
maintainerRFC PATCH 9/11 selftests/landlock: Add capability restriction tests
In reply to Mickaël SalaünAdd tests to exercise LANDLOCK_PERM_CAPABILITY_USE enforcement. The tests verify that a sandboxed process is denied a handled capability when no rule grants it, and that an explicit rule restores the capability. Unknown capability values above CAP_LAST_CAP are checked to be silently accepted without effect, ensuring the allow-list stays future-proof when new capabilities are added. A stacking test creates two nested domains restricting different capability sets and confirms that both layers' rules are enforced. Invalid rule attributes (wrong flags, out-of-range values) are tested to 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 denied capabilities produce the correct audit record with the capability number, and that allowed capabilities generate no denial record.
Test coverage for security/landlock is 90.7% of 2282 lines according to LLVM 21.
--- tools/testing/selftests/landlock/base_test.c | 18 + tools/testing/selftests/landlock/cap_test.c | 614 +++++++++++++++++++ 2 files changed, 632 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 +614 -0
614 lines not on this page · raw message
Signature · 1 line
2.53.0
Mickaël Salaün
maintainerRFC PATCH 10/11 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_CAPS environment variable takes a colon-delimited list of allowed capability numbers (e.g. "18" for CAP_SYS_CHROOT). The LL_NS variable takes a colon-delimited list of allowed namespace types by short name (e.g. "user:uts:net"). Update LANDLOCK_ABI_LAST to 9 and add best-effort degradation for older kernels.
Allow creating user and UTS namespaces but deny network namespaces (works as an unprivileged user). All capabilities are available (LL_CAPS 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_ENTER 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 (18), 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_CAPS="18" \
./sandboxer /bin/sh -c \
"unshare --user --keep-caps chroot / true"--- samples/landlock/sandboxer.c | 164 +++++++++++++++++++++++++++++++++-- 1 file changed, 155 insertions(+), 9 deletions(-)
samples/landlock/sandboxer.c +155 -9
@@ -14,6 +14,8 @@#include <fcntl.h> #include <linux/landlock.h> #include <linux/socket.h> +#include <sched.h> +#include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h>
@@ -22,12 +24,16 @@#include <sys/stat.h> #include <sys/syscall.h> #include <unistd.h> -#include <stdbool.h> #if defined(__GLIBC__)#include <linux/prctl.h> #endif +/* From include/linux/bits.h, not available in userspace. */ +#ifndef BITS_PER_TYPE +#define BITS_PER_TYPE (type) (sizeof(type) * 8) +#endif +#ifndef landlock_create_ruleset static inline int landlock_create_ruleset(const struct landlock_ruleset_attr *const attr,
@@ -60,6 +66,8 @@ static inline int landlock_restrict_self(const int ruleset_fd,#define ENV_FS_RW_NAME "LL_FS_RW"#define ENV_TCP_BIND_NAME "LL_TCP_BIND"#define ENV_TCP_CONNECT_NAME "LL_TCP_CONNECT" +#define ENV_CAPS_NAME "LL_CAPS" +#define ENV_NS_NAME "LL_NS"#define ENV_SCOPED_NAME "LL_SCOPED"#define ENV_FORCE_LOG_NAME "LL_FORCE_LOG"#define ENV_DELIMITER ":"
@@ -226,11 +234,125 @@ static int populate_ruleset_net(const char *const env_var, const int ruleset_fd,return ret; } +static __u64 str2ns (const char *const name) +{ +static const struct { +const char *name; +__u64 value; + } ns_map[] = { +/* clang-format off */ + {"cgroup" ,CLONE_NEWCGROUP }, + {"ipc" ,CLONE_NEWIPC }, + {"mnt" ,CLONE_NEWNS }, + {"net" ,CLONE_NEWNET }, + {"pid" ,CLONE_NEWPID }, + {"time" ,CLONE_NEWTIME }, + {"user" ,CLONE_NEWUSER }, + {"uts" ,CLONE_NEWUTS }, +/* clang-format on */ + }; +size_t i; + +for (i =0 ; i <sizeof (ns_map) /sizeof (ns_map[0 ]); i++) { +if (strcmp (name, ns_map[i].name) ==0 ) +return ns_map[i].value; + } +return 0 ; +} + +static int populate_ruleset_caps (const char *const env_var, +const int ruleset_fd) +{ +int ret =1 ; +char *env_cap_name, *env_cap_name_next, *strcap; +struct landlock_capability_attr cap_attr = { + .allowed_perm =LANDLOCK_PERM_CAPABILITY_USE , + }; + + env_cap_name =getenv (env_var); +if (!env_cap_name) +return 0 ; + env_cap_name =strdup (env_cap_name); +unsetenv (env_var); + + env_cap_name_next = env_cap_name; +while ((strcap =strsep (&env_cap_name_next,ENV_DELIMITER ))) { +__u64 cap; + +if (strcmp (strcap,"" ) ==0 ) +continue ; + +if (str2num (strcap, &cap) || + cap >=BITS_PER_TYPE (cap_attr.capabilities)) { +fprintf (stderr, +"Failed to parse capability at \"%s\"\n" , + strcap); + goto out_free_name; + } + cap_attr.capabilities =1ULL << cap; +if (landlock_add_rule (ruleset_fd,LANDLOCK_RULE_CAPABILITY , + &cap_attr,0 )) { +fprintf (stderr, +"Failed to update the ruleset with capability \"%llu\": %s\n" , + (unsigned long long )cap,strerror (errno)); + goto out_free_name; + } + } + ret =0 ; + +out_free_name: +free (env_cap_name); +return ret; +} + +static int populate_ruleset_ns (const char *const env_var,const int ruleset_fd) +{ +int ret =1 ; +char *env_ns_name, *env_ns_name_next, *strns; +struct landlock_namespace_attr ns_attr = { + .allowed_perm =LANDLOCK_PERM_NAMESPACE_ENTER , + }; + + env_ns_name =getenv (env_var); +if (!env_ns_name) +return 0 ; + env_ns_name =strdup (env_ns_name); +unsetenv (env_var); + + env_ns_name_next = env_ns_name; +while ((strns =strsep (&env_ns_name_next,ENV_DELIMITER ))) { +__u64 ns_type; + +if (strcmp (strns,"" ) ==0 ) +continue ; + + ns_type =str2ns (strns); +if (!ns_type) { +fprintf (stderr,"Unknown namespace type \"%s\"\n" , + strns); + goto out_free_name; + } + ns_attr.namespace_types = ns_type; +if (landlock_add_rule (ruleset_fd,LANDLOCK_RULE_NAMESPACE , + &ns_attr,0 )) { +fprintf (stderr, +"Failed to update the ruleset with namespace \"%s\": %s\n" , + strns,strerror (errno)); + goto out_free_name; + } + } + ret =0 ; + +out_free_name: +free (env_ns_name); +return ret; +} +/* Returns true on error, false otherwise. */ static bool check_ruleset_scope (const char *const env_var,struct landlock_ruleset_attr *ruleset_attr) { -char *env_type_scope, *env_type_scope_next, *ipc_scoping_name; +char *env_type_scope, *env_type_scope_next, *scope_name;bool error = false;bool abstract_scoping = false;bool signal_scoping = false;
@@ -247,16 +369,14 @@ static bool check_ruleset_scope(const char *const env_var, env_type_scope =strdup (env_type_scope); env_type_scope_next = env_type_scope; -while ((ipc_scoping_name = -strsep (&env_type_scope_next,ENV_DELIMITER ))) { -if (strcmp ("a" , ipc_scoping_name) ==0 && !abstract_scoping) { +while ((scope_name =strsep (&env_type_scope_next,ENV_DELIMITER ))) { +if (strcmp ("a" , scope_name) ==0 && !abstract_scoping) { abstract_scoping = true; - }else if (strcmp ("s" , ipc_scoping_name) ==0 && - !signal_scoping) { + }else if (strcmp ("s" , scope_name) ==0 && !signal_scoping) { signal_scoping = true; }else {fprintf (stderr,"Unknown or duplicate scope \"%s\"\n" , - ipc_scoping_name); + scope_name); error = true; goto out_free_name; }
@@ -299,7 +419,7 @@ static bool check_ruleset_scope(const char *const env_var,/* clang-format on */ -#define LANDLOCK_ABI_LAST 8 +#define LANDLOCK_ABI_LAST 9#define XSTR (s) #s#define STR (s) XSTR(s)
@@ -322,6 +442,10 @@ static const char help[] ="means an empty list):\n" "* " ENV_TCP_BIND_NAME ": ports allowed to bind (server)\n" "* " ENV_TCP_CONNECT_NAME ": ports allowed to connect (client)\n" +"* " ENV_CAPS_NAME ": capability numbers allowed to use " +"(e.g. 10 for CAP_NET_BIND_SERVICE, 21 for CAP_SYS_ADMIN)\n" +"* " ENV_NS_NAME ": namespace types allowed to enter " +"(cgroup, ipc, mnt, net, pid, time, user, uts)\n" "* " ENV_SCOPED_NAME ": actions denied on the outside of the landlock domain\n" " - \"a\" to restrict opening abstract unix sockets\n" " - \"s\" to restrict sending signals\n"
@@ -334,6 +458,8 @@ static const char help[] =ENV_FS_RW_NAME "=\"/dev/null:/dev/full:/dev/zero:/dev/pts:/tmp\" " ENV_TCP_BIND_NAME "=\"9418\" " ENV_TCP_CONNECT_NAME "=\"80:443\" " +ENV_CAPS_NAME "=\"21\" " +ENV_NS_NAME "=\"user:uts:net\" " ENV_SCOPED_NAME "=\"a:s\" " "%1$s bash -i\n" "\n"
@@ -357,6 +483,8 @@ int main(const int argc, char *const argv[], char *const *const envp) LANDLOCK_ACCESS_NET_CONNECT_TCP, .scoped =LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | LANDLOCK_SCOPE_SIGNAL, + .handled_perm =LANDLOCK_PERM_CAPABILITY_USE | + LANDLOCK_PERM_NAMESPACE_ENTER, };int supported_restrict_flags =LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON ;int set_restrict_flags =0 ;
@@ -438,6 +566,10 @@ int main(const int argc, char *const argv[], char *const *const envp) ~LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON ; __attribute__((fallthrough));case 7 : + __attribute__((fallthrough)); +case 8 : +/* Removes permission support for ABI < 9 */ + ruleset_attr.handled_perm =0 ;/* Must be printed for any ABI < LANDLOCK_ABI_LAST. */ fprintf (stderr, "Hint: You should update the running kernel "
@@ -470,6 +602,14 @@ int main(const int argc, char *const argv[], char *const *const envp) ~LANDLOCK_ACCESS_NET_CONNECT_TCP ; } +/* Removes capability handling if not set by a user. */ +if (!getenv (ENV_CAPS_NAME )) + ruleset_attr.handled_perm &= ~LANDLOCK_PERM_CAPABILITY_USE ; + +/* Removes namespace handling if not set by a user. */ +if (!getenv (ENV_NS_NAME )) + ruleset_attr.handled_perm &= ~LANDLOCK_PERM_NAMESPACE_ENTER ; +if (check_ruleset_scope (ENV_SCOPED_NAME , &ruleset_attr))return 1 ;
@@ -514,6 +654,12 @@ int main(const int argc, char *const argv[], char *const *const envp) goto err_close_ruleset; } +if (populate_ruleset_caps (ENV_CAPS_NAME , ruleset_fd)) + goto err_close_ruleset; + +if (populate_ruleset_ns (ENV_NS_NAME , ruleset_fd)) + goto err_close_ruleset; +if (prctl (PR_SET_NO_NEW_PRIVS ,1 ,0 ,0 ,0 )) {perror ("Failed to restrict privileges" ); goto err_close_ruleset;
Signature · 1 line
2.53.0
Re: [RFC PATCH v1 10/11] samples/landlock: Add capability and namespace restriction support
Quoted 123 lines · Mickaël Salaün
Extend the sandboxer sample to demonstrate the new Landlock capability and namespace restriction features. The
LL_CAPSenvironment variable takes a colon-delimited list of allowed capability numbers (e.g. "18" forCAP_SYS_CHROOT). TheLL_NSvariable takes a colon-delimited list of allowed namespace types by short name (e.g. "user:uts:net"). UpdateLANDLOCK_ABI_LASTto 9 and add best-effort degradation for older kernels.Allow creating user and UTS namespaces but deny network namespaces (works as an unprivileged user). All capabilities are available (
LL_CAPSis not set), but namespace creation is still restricted to the types listed inLL_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 theLANDLOCK_PERM_NAMESPACE_ENTERrule: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(18), 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 theCAP_SYS_CHROOTgranted within the new namespace:LL_FS_RO=/ LL_FS_RW="" LL_NS="user" LL_CAPS="18" \ ./sandboxer /bin/sh -c \ "unshare --user --keep-caps chroot / true"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]>--- samples/landlock/sandboxer.c | 164 +++++++++++++++++++++++++++++++++-- 1 file changed, 155 insertions(+), 9 deletions(-)samples/landlock/sandboxer.c +48
-1@@ -14,6 +14,8 @@#include <fcntl.h> #include <linux/landlock.h> #include <linux/socket.h> +#include <sched.h> +#include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> @@ -22,12 +24,16 @@#include <sys/stat.h> #include <sys/syscall.h> #include <unistd.h> -#include <stdbool.h> #if defined(__GLIBC__)#include <linux/prctl.h> #endif +/* From include/linux/bits.h, not available in userspace. */ +#ifndef BITS_PER_TYPE +#define BITS_PER_TYPE (type) (sizeof(type) * 8) +#endif +#ifndef landlock_create_ruleset static inline int landlock_create_ruleset(const struct landlock_ruleset_attr *const attr,@@ -60,6 +66,8 @@ static inline int landlock_restrict_self(const int ruleset_fd,#define ENV_FS_RW_NAME "LL_FS_RW"#define ENV_TCP_BIND_NAME "LL_TCP_BIND"#define ENV_TCP_CONNECT_NAME "LL_TCP_CONNECT" +#define ENV_CAPS_NAME "LL_CAPS" +#define ENV_NS_NAME "LL_NS"#define ENV_SCOPED_NAME "LL_SCOPED"#define ENV_FORCE_LOG_NAME "LL_FORCE_LOG"#define ENV_DELIMITER ":"@@ -226,11 +234,125 @@ static int populate_ruleset_net(const char *const env_var, const int ruleset_fd,return ret; } +static __u64 str2ns (const char *const name) +{ +static const struct { +const char *name; +__u64 value; + } ns_map[] = { +/* clang-format off */ + {"cgroup" ,CLONE_NEWCGROUP }, + {"ipc" ,CLONE_NEWIPC }, + {"mnt" ,CLONE_NEWNS }, + {"net" ,CLONE_NEWNET }, + {"pid" ,CLONE_NEWPID }, + {"time" ,CLONE_NEWTIME }, + {"user" ,CLONE_NEWUSER }, + {"uts" ,CLONE_NEWUTS }, +/* clang-format on */ + }; +size_t i; + +for (i =0 ; i <sizeof (ns_map) /sizeof (ns_map[0 ]); i++) { +if (strcmp (name, ns_map[i].name) ==0 ) +return ns_map[i].value; + } +return 0 ; +} + +static int populate_ruleset_caps (const char *const env_var, +const int ruleset_fd) +{ +int ret =1 ; +char *env_cap_name, *env_cap_name_next, *strcap; +struct landlock_capability_attr cap_attr = { + .allowed_perm =LANDLOCK_PERM_CAPABILITY_USE , + }; + + env_cap_name =getenv (env_var); +if (!env_cap_name) +return 0 ; + env_cap_name =strdup (env_cap_name);
samples/landlock/sandboxer.c static int populate_ruleset_net(const char *const env_var, const int ruleset_fd, · line 285
Quoted 10 lines
samples/landlock/sandboxer.c +10
-0+unsetenv (env_var); + + env_cap_name_next = env_cap_name; +while ((strcap =strsep (&env_cap_name_next,ENV_DELIMITER ))) { +__u64 cap; + +if (strcmp (strcap,"" ) ==0 ) +continue ; + + if (str2num(strcap, &cap) ||
libcap has cap_from_name(3). I believe we are linking with libcap already to drop them before tests. (I have not used this function myself yet, but it sounds like it would address this case.)
Quoted 175 lines
samples/landlock/sandboxer.c +97
-8+ cap >= BITS_PER_TYPE(cap_attr.capabilities)) { +fprintf (stderr, +"Failed to parse capability at \"%s\"\n" , + strcap); + goto out_free_name; + } + cap_attr.capabilities =1ULL << cap; +if (landlock_add_rule (ruleset_fd,LANDLOCK_RULE_CAPABILITY , + &cap_attr,0 )) { +fprintf (stderr, +"Failed to update the ruleset with capability \"%llu\": %s\n" , + (unsigned long long )cap,strerror (errno)); + goto out_free_name; + } + } + ret =0 ; + +out_free_name: +free (env_cap_name); +return ret; +} + +static int populate_ruleset_ns (const char *const env_var,const int ruleset_fd) +{ +int ret =1 ; +char *env_ns_name, *env_ns_name_next, *strns; +struct landlock_namespace_attr ns_attr = { + .allowed_perm =LANDLOCK_PERM_NAMESPACE_ENTER , + }; + + env_ns_name =getenv (env_var); +if (!env_ns_name) +return 0 ; + env_ns_name =strdup (env_ns_name); +unsetenv (env_var); + + env_ns_name_next = env_ns_name; +while ((strns =strsep (&env_ns_name_next,ENV_DELIMITER ))) { +__u64 ns_type; + +if (strcmp (strns,"" ) ==0 ) +continue ; + + ns_type =str2ns (strns); +if (!ns_type) { +fprintf (stderr,"Unknown namespace type \"%s\"\n" , + strns); + goto out_free_name; + } + ns_attr.namespace_types = ns_type; +if (landlock_add_rule (ruleset_fd,LANDLOCK_RULE_NAMESPACE , + &ns_attr,0 )) { +fprintf (stderr, +"Failed to update the ruleset with namespace \"%s\": %s\n" , + strns,strerror (errno)); + goto out_free_name; + } + } + ret =0 ; + +out_free_name: +free (env_ns_name); +return ret; +} +/* Returns true on error, false otherwise. */ static bool check_ruleset_scope (const char *const env_var,struct landlock_ruleset_attr *ruleset_attr) { -char *env_type_scope, *env_type_scope_next, *ipc_scoping_name; +char *env_type_scope, *env_type_scope_next, *scope_name;bool error = false;bool abstract_scoping = false;bool signal_scoping = false;@@ -247,16 +369,14 @@ static bool check_ruleset_scope(const char *const env_var, env_type_scope =strdup (env_type_scope); env_type_scope_next = env_type_scope; -while ((ipc_scoping_name = -strsep (&env_type_scope_next,ENV_DELIMITER ))) { -if (strcmp ("a" , ipc_scoping_name) ==0 && !abstract_scoping) { +while ((scope_name =strsep (&env_type_scope_next,ENV_DELIMITER ))) { +if (strcmp ("a" , scope_name) ==0 && !abstract_scoping) { abstract_scoping = true; - }else if (strcmp ("s" , ipc_scoping_name) ==0 && - !signal_scoping) { + }else if (strcmp ("s" , scope_name) ==0 && !signal_scoping) { signal_scoping = true; }else {fprintf (stderr,"Unknown or duplicate scope \"%s\"\n" , - ipc_scoping_name); + scope_name); error = true; goto out_free_name; }@@ -299,7 +419,7 @@ static bool check_ruleset_scope(const char *const env_var,/* clang-format on */ -#define LANDLOCK_ABI_LAST 8 +#define LANDLOCK_ABI_LAST 9#define XSTR (s) #s#define STR (s) XSTR(s)@@ -322,6 +442,10 @@ static const char help[] ="means an empty list):\n" "* " ENV_TCP_BIND_NAME ": ports allowed to bind (server)\n" "* " ENV_TCP_CONNECT_NAME ": ports allowed to connect (client)\n" +"* " ENV_CAPS_NAME ": capability numbers allowed to use " +"(e.g. 10 for CAP_NET_BIND_SERVICE, 21 for CAP_SYS_ADMIN)\n" +"* " ENV_NS_NAME ": namespace types allowed to enter " +"(cgroup, ipc, mnt, net, pid, time, user, uts)\n" "* " ENV_SCOPED_NAME ": actions denied on the outside of the landlock domain\n" " - \"a\" to restrict opening abstract unix sockets\n" " - \"s\" to restrict sending signals\n" @@ -334,6 +458,8 @@ static const char help[] =ENV_FS_RW_NAME "=\"/dev/null:/dev/full:/dev/zero:/dev/pts:/tmp\" " ENV_TCP_BIND_NAME "=\"9418\" " ENV_TCP_CONNECT_NAME "=\"80:443\" " +ENV_CAPS_NAME "=\"21\" " +ENV_NS_NAME "=\"user:uts:net\" " ENV_SCOPED_NAME "=\"a:s\" " "%1$s bash -i\n" "\n" @@ -357,6 +483,8 @@ int main(const int argc, char *const argv[], char *const *const envp) LANDLOCK_ACCESS_NET_CONNECT_TCP, .scoped =LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | LANDLOCK_SCOPE_SIGNAL, + .handled_perm =LANDLOCK_PERM_CAPABILITY_USE | + LANDLOCK_PERM_NAMESPACE_ENTER, };int supported_restrict_flags =LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON ;int set_restrict_flags =0 ;@@ -438,6 +566,10 @@ int main(const int argc, char *const argv[], char *const *const envp) ~LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON ; __attribute__((fallthrough));case 7 : + __attribute__((fallthrough)); +case 8 : +/* Removes permission support for ABI < 9 */ + ruleset_attr.handled_perm =0 ;/* Must be printed for any ABI < LANDLOCK_ABI_LAST. */ fprintf (stderr, "Hint: You should update the running kernel "@@ -470,6 +602,14 @@ int main(const int argc, char *const argv[], char *const *const envp) ~LANDLOCK_ACCESS_NET_CONNECT_TCP ; } +/* Removes capability handling if not set by a user. */ +if (!getenv (ENV_CAPS_NAME )) + ruleset_attr.handled_perm &= ~LANDLOCK_PERM_CAPABILITY_USE ; + +/* Removes namespace handling if not set by a user. */ +if (!getenv (ENV_NS_NAME )) + ruleset_attr.handled_perm &= ~LANDLOCK_PERM_NAMESPACE_ENTER ; +if (check_ruleset_scope (ENV_SCOPED_NAME , &ruleset_attr))return 1 ;@@ -514,6 +654,12 @@ int main(const int argc, char *const argv[], char *const *const envp) goto err_close_ruleset; } +if (populate_ruleset_caps (ENV_CAPS_NAME , ruleset_fd)) + goto err_close_ruleset; + +if (populate_ruleset_ns (ENV_NS_NAME , ruleset_fd)) + goto err_close_ruleset; +if (prctl (PR_SET_NO_NEW_PRIVS ,1 ,0 ,0 ,0 )) {perror ("Failed to restrict privileges" ); goto err_close_ruleset;Signature · 1 line
2.53.0
Mickaël Salaün
maintainerRe: [RFC PATCH v1 10/11] samples/landlock: Add capability and namespace restriction support
Quoted 130 lines · Günther Noack
Quoted 129 lines · Mickaël Salaün
Extend the sandboxer sample to demonstrate the new Landlock capability and namespace restriction features. The
LL_CAPSenvironment variable takes a colon-delimited list of allowed capability numbers (e.g. "18" forCAP_SYS_CHROOT). TheLL_NSvariable takes a colon-delimited list of allowed namespace types by short name (e.g. "user:uts:net"). UpdateLANDLOCK_ABI_LASTto 9 and add best-effort degradation for older kernels.Allow creating user and UTS namespaces but deny network namespaces (works as an unprivileged user). All capabilities are available (
LL_CAPSis not set), but namespace creation is still restricted to the types listed inLL_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 theLANDLOCK_PERM_NAMESPACE_ENTERrule: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(18), 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 theCAP_SYS_CHROOTgranted within the new namespace:LL_FS_RO=/ LL_FS_RW="" LL_NS="user" LL_CAPS="18" \ ./sandboxer /bin/sh -c \ "unshare --user --keep-caps chroot / true"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]>--- samples/landlock/sandboxer.c | 164 +++++++++++++++++++++++++++++++++-- 1 file changed, 155 insertions(+), 9 deletions(-)samples/landlock/sandboxer.c +54
-1@@ -14,6 +14,8 @@#include <fcntl.h> #include <linux/landlock.h> #include <linux/socket.h> +#include <sched.h> +#include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> @@ -22,12 +24,16 @@#include <sys/stat.h> #include <sys/syscall.h> #include <unistd.h> -#include <stdbool.h> #if defined(__GLIBC__)#include <linux/prctl.h> #endif +/* From include/linux/bits.h, not available in userspace. */ +#ifndef BITS_PER_TYPE +#define BITS_PER_TYPE (type) (sizeof(type) * 8) +#endif +#ifndef landlock_create_ruleset static inline int landlock_create_ruleset(const struct landlock_ruleset_attr *const attr,@@ -60,6 +66,8 @@ static inline int landlock_restrict_self(const int ruleset_fd,#define ENV_FS_RW_NAME "LL_FS_RW"#define ENV_TCP_BIND_NAME "LL_TCP_BIND"#define ENV_TCP_CONNECT_NAME "LL_TCP_CONNECT" +#define ENV_CAPS_NAME "LL_CAPS" +#define ENV_NS_NAME "LL_NS"#define ENV_SCOPED_NAME "LL_SCOPED"#define ENV_FORCE_LOG_NAME "LL_FORCE_LOG"#define ENV_DELIMITER ":"@@ -226,11 +234,125 @@ static int populate_ruleset_net(const char *const env_var, const int ruleset_fd,return ret; } +static __u64 str2ns (const char *const name) +{ +static const struct { +const char *name; +__u64 value; + } ns_map[] = { +/* clang-format off */ + {"cgroup" ,CLONE_NEWCGROUP }, + {"ipc" ,CLONE_NEWIPC }, + {"mnt" ,CLONE_NEWNS }, + {"net" ,CLONE_NEWNET }, + {"pid" ,CLONE_NEWPID }, + {"time" ,CLONE_NEWTIME }, + {"user" ,CLONE_NEWUSER }, + {"uts" ,CLONE_NEWUTS }, +/* clang-format on */ + }; +size_t i; + +for (i =0 ; i <sizeof (ns_map) /sizeof (ns_map[0 ]); i++) { +if (strcmp (name, ns_map[i].name) ==0 ) +return ns_map[i].value; + } +return 0 ; +} + +static int populate_ruleset_caps (const char *const env_var, +const int ruleset_fd) +{ +int ret =1 ; +char *env_cap_name, *env_cap_name_next, *strcap; +struct landlock_capability_attr cap_attr = { + .allowed_perm =LANDLOCK_PERM_CAPABILITY_USE , + }; + + env_cap_name =getenv (env_var); +if (!env_cap_name) +return 0 ; + env_cap_name =strdup (env_cap_name); +unsetenv (env_var); + + env_cap_name_next = env_cap_name; +while ((strcap =strsep (&env_cap_name_next,ENV_DELIMITER ))) { +__u64 cap; +
Quoted 8 lines
samples/landlock/sandboxer.c static int populate_ruleset_net(const char *const env_var, const int ruleset_fd, · line 285
Quoted 4 lines
samples/landlock/sandboxer.c +4
-0+if (strcmp (strcap,"" ) ==0 ) +continue ; + + if (str2num(strcap, &cap) ||libcap has
cap_from_name(3). I believe we are linking with libcap already to drop them before tests. (I have not used this function myself yet, but it sounds like it would address this case.)
libcap is only used for kselftests, not this sample, but yes, let's use libcap here too.
Quoted 178 lines
Quoted 177 lines
samples/landlock/sandboxer.c +97
-8+ cap >= BITS_PER_TYPE(cap_attr.capabilities)) { +fprintf (stderr, +"Failed to parse capability at \"%s\"\n" , + strcap); + goto out_free_name; + } + cap_attr.capabilities =1ULL << cap; +if (landlock_add_rule (ruleset_fd,LANDLOCK_RULE_CAPABILITY , + &cap_attr,0 )) { +fprintf (stderr, +"Failed to update the ruleset with capability \"%llu\": %s\n" , + (unsigned long long )cap,strerror (errno)); + goto out_free_name; + } + } + ret =0 ; + +out_free_name: +free (env_cap_name); +return ret; +} + +static int populate_ruleset_ns (const char *const env_var,const int ruleset_fd) +{ +int ret =1 ; +char *env_ns_name, *env_ns_name_next, *strns; +struct landlock_namespace_attr ns_attr = { + .allowed_perm =LANDLOCK_PERM_NAMESPACE_ENTER , + }; + + env_ns_name =getenv (env_var); +if (!env_ns_name) +return 0 ; + env_ns_name =strdup (env_ns_name); +unsetenv (env_var); + + env_ns_name_next = env_ns_name; +while ((strns =strsep (&env_ns_name_next,ENV_DELIMITER ))) { +__u64 ns_type; + +if (strcmp (strns,"" ) ==0 ) +continue ; + + ns_type =str2ns (strns); +if (!ns_type) { +fprintf (stderr,"Unknown namespace type \"%s\"\n" , + strns); + goto out_free_name; + } + ns_attr.namespace_types = ns_type; +if (landlock_add_rule (ruleset_fd,LANDLOCK_RULE_NAMESPACE , + &ns_attr,0 )) { +fprintf (stderr, +"Failed to update the ruleset with namespace \"%s\": %s\n" , + strns,strerror (errno)); + goto out_free_name; + } + } + ret =0 ; + +out_free_name: +free (env_ns_name); +return ret; +} +/* Returns true on error, false otherwise. */ static bool check_ruleset_scope (const char *const env_var,struct landlock_ruleset_attr *ruleset_attr) { -char *env_type_scope, *env_type_scope_next, *ipc_scoping_name; +char *env_type_scope, *env_type_scope_next, *scope_name;bool error = false;bool abstract_scoping = false;bool signal_scoping = false;@@ -247,16 +369,14 @@ static bool check_ruleset_scope(const char *const env_var, env_type_scope =strdup (env_type_scope); env_type_scope_next = env_type_scope; -while ((ipc_scoping_name = -strsep (&env_type_scope_next,ENV_DELIMITER ))) { -if (strcmp ("a" , ipc_scoping_name) ==0 && !abstract_scoping) { +while ((scope_name =strsep (&env_type_scope_next,ENV_DELIMITER ))) { +if (strcmp ("a" , scope_name) ==0 && !abstract_scoping) { abstract_scoping = true; - }else if (strcmp ("s" , ipc_scoping_name) ==0 && - !signal_scoping) { + }else if (strcmp ("s" , scope_name) ==0 && !signal_scoping) { signal_scoping = true; }else {fprintf (stderr,"Unknown or duplicate scope \"%s\"\n" , - ipc_scoping_name); + scope_name); error = true; goto out_free_name; }@@ -299,7 +419,7 @@ static bool check_ruleset_scope(const char *const env_var,/* clang-format on */ -#define LANDLOCK_ABI_LAST 8 +#define LANDLOCK_ABI_LAST 9#define XSTR (s) #s#define STR (s) XSTR(s)@@ -322,6 +442,10 @@ static const char help[] ="means an empty list):\n" "* " ENV_TCP_BIND_NAME ": ports allowed to bind (server)\n" "* " ENV_TCP_CONNECT_NAME ": ports allowed to connect (client)\n" +"* " ENV_CAPS_NAME ": capability numbers allowed to use " +"(e.g. 10 for CAP_NET_BIND_SERVICE, 21 for CAP_SYS_ADMIN)\n" +"* " ENV_NS_NAME ": namespace types allowed to enter " +"(cgroup, ipc, mnt, net, pid, time, user, uts)\n" "* " ENV_SCOPED_NAME ": actions denied on the outside of the landlock domain\n" " - \"a\" to restrict opening abstract unix sockets\n" " - \"s\" to restrict sending signals\n" @@ -334,6 +458,8 @@ static const char help[] =ENV_FS_RW_NAME "=\"/dev/null:/dev/full:/dev/zero:/dev/pts:/tmp\" " ENV_TCP_BIND_NAME "=\"9418\" " ENV_TCP_CONNECT_NAME "=\"80:443\" " +ENV_CAPS_NAME "=\"21\" " +ENV_NS_NAME "=\"user:uts:net\" " ENV_SCOPED_NAME "=\"a:s\" " "%1$s bash -i\n" "\n" @@ -357,6 +483,8 @@ int main(const int argc, char *const argv[], char *const *const envp) LANDLOCK_ACCESS_NET_CONNECT_TCP, .scoped =LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | LANDLOCK_SCOPE_SIGNAL, + .handled_perm =LANDLOCK_PERM_CAPABILITY_USE | + LANDLOCK_PERM_NAMESPACE_ENTER, };int supported_restrict_flags =LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON ;int set_restrict_flags =0 ;@@ -438,6 +566,10 @@ int main(const int argc, char *const argv[], char *const *const envp) ~LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON ; __attribute__((fallthrough));case 7 : + __attribute__((fallthrough)); +case 8 : +/* Removes permission support for ABI < 9 */ + ruleset_attr.handled_perm =0 ;/* Must be printed for any ABI < LANDLOCK_ABI_LAST. */ fprintf (stderr, "Hint: You should update the running kernel "@@ -470,6 +602,14 @@ int main(const int argc, char *const argv[], char *const *const envp) ~LANDLOCK_ACCESS_NET_CONNECT_TCP ; } +/* Removes capability handling if not set by a user. */ +if (!getenv (ENV_CAPS_NAME )) + ruleset_attr.handled_perm &= ~LANDLOCK_PERM_CAPABILITY_USE ; + +/* Removes namespace handling if not set by a user. */ +if (!getenv (ENV_NS_NAME )) + ruleset_attr.handled_perm &= ~LANDLOCK_PERM_NAMESPACE_ENTER ; +if (check_ruleset_scope (ENV_SCOPED_NAME , &ruleset_attr))return 1 ;@@ -514,6 +654,12 @@ int main(const int argc, char *const argv[], char *const *const envp) goto err_close_ruleset; } +if (populate_ruleset_caps (ENV_CAPS_NAME , ruleset_fd)) + goto err_close_ruleset; + +if (populate_ruleset_ns (ENV_NS_NAME , ruleset_fd)) + goto err_close_ruleset; +if (prctl (PR_SET_NO_NEW_PRIVS ,1 ,0 ,0 ,0 )) {perror ("Failed to restrict privileges" ); goto err_close_ruleset;Signature · 1 line
2.53.0
Mickaël Salaün
maintainerRFC PATCH 11/11 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), namespace restriction (LANDLOCK_PERM_NAMESPACE_ENTER with LANDLOCK_RULE_NAMESPACE covering creation via unshare/clone and entry via setns), and the backward-compatible degradation pattern for ABI < 9. A table documents the per-namespace-type capability requirements for both creation and entry.
The admin guide adds the new perm.namespace_enter and perm.capability_use audit blocker names with their object identification fields (namespace_type, namespace_inum, 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.
--- Documentation/admin-guide/LSM/landlock.rst | 19 ++- Documentation/security/landlock.rst | 80 ++++++++++- Documentation/userspace-api/landlock.rst | 156 ++++++++++++++++++++- 3 files changed, 245 insertions(+), 10 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: March 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 9+): + - perm.namespace_enter - 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_inum`` 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_inum`` for namespace operations; + ``capability`` for capability use. AUDIT_LANDLOCK_DOMAIN
Documentation/security/landlock.rst +79 -1
98 lines not on this page · raw message
Documentation/userspace-api/landlock.rst +151 -5
219 lines not on this page · raw message
Signature · 1 line
2.53.0
Re: [RFC PATCH v1 11/11] landlock: Add documentation for capability and namespace restrictions
Quoted 92 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), namespace restriction (LANDLOCK_PERM_NAMESPACE_ENTERwithLANDLOCK_RULE_NAMESPACEcovering creation via unshare/clone and entry via setns), and the backward-compatible degradation pattern for ABI < 9. A table documents the per-namespace-type capability requirements for both creation and entry.The admin guide adds the new perm.namespace_enter and perm.capability_use audit blocker names with their object identification fields (
namespace_type,namespace_inum, 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]>--- Documentation/admin-guide/LSM/landlock.rst | 19 ++- Documentation/security/landlock.rst | 80 ++++++++++- Documentation/userspace-api/landlock.rst | 156 ++++++++++++++++++++- 3 files changed, 245 insertions(+), 10 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: March 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 9+): + - perm.namespace_enter - 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_inum`` 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_inum`` 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: September 2025 +:Date: March 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,@@ -89,6 +89,72 @@ this is required to keep access controls consistent over the whole system, and this avoids unattended bypasses through file descriptor passing (i.e. confused deputy attack).
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 101
Quoted 10 lines
Documentation/security/landlock.rst +10
-0+Composability with user namespaces +---------------------------------- + +Landlock domain-based scoping and the kernel's user namespace-based capability +scoping enforce isolation over independent hierarchies. 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 new +scoped features.
The last sentence on orthogonality may better belong under the restriction model section for scoped access rights. I assume that future scopes must also be deterministic with respect to landlock's configuration as well, not just user namespaces.
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 104
Quoted 3 lines
Documentation/security/landlock.rst +3
-0+ +Ruleset restriction models +--------------------------
+1
This section is very helpful for aligning new features with a particular model.
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 107
Quoted 3 lines
Documentation/security/landlock.rst +3
-0+ +Landlock provides three restriction models, each with different coverage +and compatibility properties.
Maybe add:
Each restriction model below corresponds to one or more fields of ``struct landlock_ruleset_attr``.
Quoted 198 lines
Documentation/security/landlock.rst +62
-0+ +Access rights (``handled_access_*``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Access rights control **enumerated operations on kernel objects** +identified by a rule key (a file hierarchy or a network port). Each +``handled_access_*`` field declares a set of access rights that the +ruleset restricts. Multiple access rights share a single rule type. +Operations for which no access right exists yet remain uncontrolled; +new rights are added incrementally across ABI versions. + +Permissions (``handled_perm``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Permissions control **broad operations enforced at single kernel +chokepoints**, achieving complete deny-by-default coverage. Each +``LANDLOCK_PERM_*`` flag maps to its own rule type. When a ruleset +handles a permission, all instances of that operation are denied unless +explicitly allowed by a rule. New kernel values (new ``CAP_*`` +capabilities, new ``CLONE_NEW*`` namespace types) are automatically +denied without any Landlock update. + +Each permission flag names a single gateway operation whose control +transitively covers an open-ended set of downstream operations: for +example, exercising a capability enables privileged operations across +many subsystems; entering a namespace enables gaining capabilities in a +new context. + +Permission rules identify what to allow using constants defined by other +kernel subsystems (``CAP_*``, ``CLONE_NEW*``). Unknown values are +silently ignored because deny-by-default ensures they are denied anyway. +In contrast, unknown ``LANDLOCK_PERM_*`` flags in ``handled_perm`` are +rejected (``-EINVAL``), since Landlock owns that namespace. + +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 +permissions, scopes provide complete coverage of the controlled +operation. + +When adding new Landlock features, new operations on existing rule types +extend the corresponding ``handled_access_*`` field (e.g. a new +filesystem operation extends ``handled_access_fs``). A new object +category with multiple fine-grained operations would use a new +``handled_access_*`` field. New rule types that control a single +chokepoint operation use ``handled_perm``. + Tests =====@@ -110,6 +176,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 +70
-3@@ -8,7 +8,7 @@ Landlock: unprivileged access control ===================================== :Author: Mickaël Salaün -:Date: January 2026 +:Date: March 2026 The goal of Landlock is to enable restriction of ambient rights (e.g. global filesystem or network access) for a set of processes. Because Landlock@@ -33,7 +33,7 @@ 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. -The two existing types of rules are: +The existing types of rules are: Filesystem rules For these rules, the object is a file hierarchy,@@ -44,6 +44,14 @@ Network rules (since ABI v4) For these rules, the object is a TCP port, and the related actions are defined with `network access rights`. +Capability rules (since ABI v9) + For these rules, the object is a set of Linux capabilities, + and the related actions are defined with `permission flags`. + +Namespace rules (since ABI v9) + For these rules, the object is a set of namespace types, + and the related actions are defined with `permission flags`. + Defining and enforcing a security policy ----------------------------------------@@ -84,6 +92,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_ENTER, }; Because we may not know which kernel version an application will be executed@@ -127,6 +138,12 @@ version, and only use the available subset of access rights: /* Removes LANDLOCK_SCOPE_* for ABI < 6 */ ruleset_attr.scoped &= ~(LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | LANDLOCK_SCOPE_SIGNAL); + __attribute__((fallthrough)); + case 6: + case 7: + case 8: + /* Removes permission support for ABI < 9 */ + ruleset_attr.handled_perm = 0; } This enables the creation of an inclusive ruleset that will contain our rules.@@ -191,6 +208,42 @@ number for a specific action: HTTPS connections. err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT, &net_port, 0); +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), + }; + + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_CAPABILITY, + &cap_attr, 0); + +For namespace access-control, we can add rules that allow entering specific +namespace types (creating them via :manpage:`unshare(2)` / :manpage:`clone(2)` +or joining them via :manpage:`setns(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_ENTER, + .namespace_types = CLONE_NEWUSER, + }; + + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NAMESPACE, + &ns_attr, 0); + +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):@@ -354,10 +407,87 @@ 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)`. +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 +------------------------------------- + +See Documentation/security/landlock.rst for the design rationale behind +the permission model (``handled_perm``) and how it differs from access +rights (``handled_access_*``) and scopes (``scoped``). +When a process creates a user namespace, the kernel grants all capabilities +within that namespace. While these capabilities cannot directly bypass Landlock +restrictions (Landlock enforces access controls independently of capability +checks), they open kernel code paths that are normally unreachable to +unprivileged users and may contain exploitable bugs. + +Landlock provides two complementary permissions to address this. +``LANDLOCK_PERM_CAPABILITY_USE`` restricts which capabilities a process can use,
Documentation/userspace-api/landlock.rst The operations which can be scoped are: · line 437
Quoted 10 lines
Documentation/userspace-api/landlock.rst +10
-0+even when it holds them. ``LANDLOCK_PERM_NAMESPACE_ENTER`` restricts which +namespace types a process can create (via :manpage:`unshare(2)` or +:manpage:`clone(2)`) or join (via :manpage:`setns(2)`). After creating a user +namespace, the granted capabilities are scoped to namespaces owned by that user +namespace or its descendants; to exercise a capability such as +``CAP_NET_ADMIN``, the process must create a namespace of the corresponding type +(e.g., a network namespace). Configuring both permissions together provides +full coverage: ``LANDLOCK_PERM_CAPABILITY_USE`` restricts which capabilities are +available, while ``LANDLOCK_PERM_NAMESPACE_ENTER`` restricts the namespaces in +which they can be used.
Maybe add a section on the what this does versus PR_SET_NO_NEW_PRIVS.
The difference might be obvious to people familiar with namespaces and capabilities, but not to many users less familiar with the subject.
I could see users using the LANDLOCK_PERM_* flags erroneously assuming that LANDLOCK_PERM_CAPABILITY_USE is required to restrict gaining of new capabilities through execve(), (ie through setuid) when in fact this is already restricted if nnp is set.
Some clarification on this would be helpful here or where PR_SET_NO_NEW_PRIVS is discussed in the Landlock docs.
Documentation/userspace-api/landlock.rst The operations which can be scoped are: · line 440
Quoted 3 lines
Documentation/userspace-api/landlock.rst +3
-0+ +When a Landlock domain handles ``LANDLOCK_PERM_CAPABILITY_USE``, all Linux +:manpage:`capabilities(7)` are denied by default unless a rule explicitly allows
Nit:
all Linux :manpage:capabilities(7)
might be better as
the exercise of all Linux :manpage:capabilities(7)
Since as pointed out before we do not restrict their precense, but their exercise.
Quoted 97 lines
Documentation/userspace-api/landlock.rst +68
-2+them. This is purely restrictive: Landlock can only deny capabilities that the +traditional capability mechanism would have allowed, never grant additional ones. +Rules are added with ``LANDLOCK_RULE_CAPABILITY`` using a +&struct landlock_capability_attr. Each rule specifies a set of ``CAP_*`` values +(as a bitmask) to allow. Capabilities above ``CAP_LAST_CAP`` are silently +accepted but have no effect since the kernel never checks them; this means new +capabilities introduced by future kernels are automatically denied. + +When a Landlock domain handles ``LANDLOCK_PERM_NAMESPACE_ENTER``, namespace +creation and entry are denied by default unless a rule explicitly allows them. +Rules are added with ``LANDLOCK_RULE_NAMESPACE`` using a +&struct landlock_namespace_attr. Each rule specifies a set of ``CLONE_NEW*`` +flags to allow. + +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_ENTER`` +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``. + +More generally, Landlock domains and user namespaces form independent +hierarchies: Landlock domains restrict what actions are allowed (each stacked +layer narrows the permitted set), while user namespaces restrict where +capabilities take effect (only within the process's own namespace and its +descendants). Landlock access controls are fully determined by the domain +configuration, regardless of the process's position in the user namespace +hierarchy. 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, :manpage:`execve(2)` of +binaries with file capabilities, or :manpage:`capset(2)`. In all cases, +:manpage:`capget(2)` will report the credential's capability sets, but any +denied capability will fail with ``EPERM`` when exercised. + Truncating files ----------------@@ -515,7 +645,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 ----------------------@@ -534,7 +664,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 -------------------@@ -685,6 +816,21 @@ enforce Landlock rulesets across all threads of the calling process using the ``LANDLOCK_RESTRICT_SELF_TSYNC`` flag passed to sys_landlock_restrict_self(). +Capability restriction (ABI < 9) +-------------------------------- + +Starting with the Landlock ABI version 9, 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 < 9) +------------------------------- + +Starting with the Landlock ABI version 9, it is possible to restrict +namespace creation (:manpage:`unshare(2)`, :manpage:`clone(2)`) and entry +(:manpage:`setns(2)`) with the new ``LANDLOCK_PERM_NAMESPACE_ENTER`` permission +flag and ``LANDLOCK_RULE_NAMESPACE`` rule type. + .. _kernel_support: Kernel supportSignature · 1 line
2.53.0
Mickaël Salaün
maintainerRe: [RFC PATCH v1 11/11] landlock: Add documentation for capability and namespace restrictions
Quoted 93 lines · Justin Suess
Quoted 92 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), namespace restriction (LANDLOCK_PERM_NAMESPACE_ENTERwithLANDLOCK_RULE_NAMESPACEcovering creation via unshare/clone and entry via setns), and the backward-compatible degradation pattern for ABI < 9. A table documents the per-namespace-type capability requirements for both creation and entry.The admin guide adds the new perm.namespace_enter and perm.capability_use audit blocker names with their object identification fields (
namespace_type,namespace_inum, 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]>--- Documentation/admin-guide/LSM/landlock.rst | 19 ++- Documentation/security/landlock.rst | 80 ++++++++++- Documentation/userspace-api/landlock.rst | 156 ++++++++++++++++++++- 3 files changed, 245 insertions(+), 10 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: March 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 9+): + - perm.namespace_enter - 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_inum`` 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_inum`` 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: September 2025 +:Date: March 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,@@ -89,6 +89,72 @@ this is required to keep access controls consistent over the whole system, and this avoids unattended bypasses through file descriptor passing (i.e. confused deputy attack).
Quoted 14 lines
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 101
Quoted 10 lines
Documentation/security/landlock.rst +10
-0+Composability with user namespaces +---------------------------------- + +Landlock domain-based scoping and the kernel's user namespace-based capability +scoping enforce isolation over independent hierarchies. 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 new +scoped features.The last sentence on orthogonality may better belong under the restriction model section for scoped access rights. I assume that future scopes must also be deterministic with respect to landlock's configuration as well, not just user namespaces.
Correct
Quoted 7 lines
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 104
Quoted 3 lines
Documentation/security/landlock.rst +3
-0+ +Ruleset restriction models +--------------------------+1
This section is very helpful for aligning new features with a particular model.
Thanks
Quoted 8 lines
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 107
Quoted 4 lines
Documentation/security/landlock.rst +3
-0+ +Landlock provides three restriction models, each with different coverage +and compatibility properties.Maybe add:
Each restriction model below corresponds to one or more fields of ``struct landlock_ruleset_attr``.
Ok
Quoted 202 lines
Quoted 202 lines
Documentation/security/landlock.rst +62
-0+ +Access rights (``handled_access_*``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Access rights control **enumerated operations on kernel objects** +identified by a rule key (a file hierarchy or a network port). Each +``handled_access_*`` field declares a set of access rights that the +ruleset restricts. Multiple access rights share a single rule type. +Operations for which no access right exists yet remain uncontrolled; +new rights are added incrementally across ABI versions. + +Permissions (``handled_perm``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Permissions control **broad operations enforced at single kernel +chokepoints**, achieving complete deny-by-default coverage. Each +``LANDLOCK_PERM_*`` flag maps to its own rule type. When a ruleset +handles a permission, all instances of that operation are denied unless +explicitly allowed by a rule. New kernel values (new ``CAP_*`` +capabilities, new ``CLONE_NEW*`` namespace types) are automatically +denied without any Landlock update. + +Each permission flag names a single gateway operation whose control +transitively covers an open-ended set of downstream operations: for +example, exercising a capability enables privileged operations across +many subsystems; entering a namespace enables gaining capabilities in a +new context. + +Permission rules identify what to allow using constants defined by other +kernel subsystems (``CAP_*``, ``CLONE_NEW*``). Unknown values are +silently ignored because deny-by-default ensures they are denied anyway. +In contrast, unknown ``LANDLOCK_PERM_*`` flags in ``handled_perm`` are +rejected (``-EINVAL``), since Landlock owns that namespace. + +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 +permissions, scopes provide complete coverage of the controlled +operation. + +When adding new Landlock features, new operations on existing rule types +extend the corresponding ``handled_access_*`` field (e.g. a new +filesystem operation extends ``handled_access_fs``). A new object +category with multiple fine-grained operations would use a new +``handled_access_*`` field. New rule types that control a single +chokepoint operation use ``handled_perm``. + Tests =====@@ -110,6 +176,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 +73
-3@@ -8,7 +8,7 @@ Landlock: unprivileged access control ===================================== :Author: Mickaël Salaün -:Date: January 2026 +:Date: March 2026 The goal of Landlock is to enable restriction of ambient rights (e.g. global filesystem or network access) for a set of processes. Because Landlock@@ -33,7 +33,7 @@ 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. -The two existing types of rules are: +The existing types of rules are: Filesystem rules For these rules, the object is a file hierarchy,@@ -44,6 +44,14 @@ Network rules (since ABI v4) For these rules, the object is a TCP port, and the related actions are defined with `network access rights`. +Capability rules (since ABI v9) + For these rules, the object is a set of Linux capabilities, + and the related actions are defined with `permission flags`. + +Namespace rules (since ABI v9) + For these rules, the object is a set of namespace types, + and the related actions are defined with `permission flags`. + Defining and enforcing a security policy ----------------------------------------@@ -84,6 +92,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_ENTER, }; Because we may not know which kernel version an application will be executed@@ -127,6 +138,12 @@ version, and only use the available subset of access rights: /* Removes LANDLOCK_SCOPE_* for ABI < 6 */ ruleset_attr.scoped &= ~(LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | LANDLOCK_SCOPE_SIGNAL); + __attribute__((fallthrough)); + case 6: + case 7: + case 8: + /* Removes permission support for ABI < 9 */ + ruleset_attr.handled_perm = 0; } This enables the creation of an inclusive ruleset that will contain our rules.@@ -191,6 +208,42 @@ number for a specific action: HTTPS connections. err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT, &net_port, 0); +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), + }; + + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_CAPABILITY, + &cap_attr, 0); + +For namespace access-control, we can add rules that allow entering specific +namespace types (creating them via :manpage:`unshare(2)` / :manpage:`clone(2)` +or joining them via :manpage:`setns(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_ENTER, + .namespace_types = CLONE_NEWUSER, + }; + + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NAMESPACE, + &ns_attr, 0); + +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):@@ -354,10 +407,87 @@ 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)`. +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 +------------------------------------- + +See Documentation/security/landlock.rst for the design rationale behind +the permission model (``handled_perm``) and how it differs from access +rights (``handled_access_*``) and scopes (``scoped``). +When a process creates a user namespace, the kernel grants all capabilities +within that namespace. While these capabilities cannot directly bypass Landlock +restrictions (Landlock enforces access controls independently of capability +checks), they open kernel code paths that are normally unreachable to +unprivileged users and may contain exploitable bugs. + +Landlock provides two complementary permissions to address this. +``LANDLOCK_PERM_CAPABILITY_USE`` restricts which capabilities a process can use, +even when it holds them. ``LANDLOCK_PERM_NAMESPACE_ENTER`` restricts which +namespace types a process can create (via :manpage:`unshare(2)` or +:manpage:`clone(2)`) or join (via :manpage:`setns(2)`). After creating a user
Quoted 8 lines
Documentation/userspace-api/landlock.rst The operations which can be scoped are: · line 437
Quoted 7 lines
Documentation/userspace-api/landlock.rst +7
-0+namespace, the granted capabilities are scoped to namespaces owned by that user +namespace or its descendants; to exercise a capability such as +``CAP_NET_ADMIN``, the process must create a namespace of the corresponding type +(e.g., a network namespace). Configuring both permissions together provides +full coverage: ``LANDLOCK_PERM_CAPABILITY_USE`` restricts which capabilities are +available, while ``LANDLOCK_PERM_NAMESPACE_ENTER`` restricts the namespaces in +which they can be used.Maybe add a section on the what this does versus
PR_SET_NO_NEW_PRIVS.
Hmm, what do you mean? What would be the link with this part?
Quoted 8 lines
The difference might be obvious to people familiar with namespaces and capabilities, but not to many users less familiar with the subject.
I could see users using the LANDLOCK_PERM_* flags erroneously assuming that
LANDLOCK_PERM_CAPABILITY_USEis required to restrict gaining of new capabilities throughexecve(), (ie through setuid) when in fact this is already restricted if nnp is set.
What would be the issue if no rule allow capabilities? The most handled_* or scoped bits are set, the better.
Quoted 3 lines
Some clarification on this would be helpful here or where
PR_SET_NO_NEW_PRIVSis discussed in the Landlock docs.
Ok, I'll try to add something about NNP.
Quoted 10 lines
Documentation/userspace-api/landlock.rst The operations which can be scoped are: · line 440
Quoted 3 lines
Documentation/userspace-api/landlock.rst +3
-0+ +When a Landlock domain handles ``LANDLOCK_PERM_CAPABILITY_USE``, all Linux +:manpage:`capabilities(7)` are denied by default unless a rule explicitly allowsNit:
all Linux :manpage:
capabilities(7)might be better as
the exercise of all Linux :manpage:
capabilities(7)
Indeed
Quoted 101 lines
Since as pointed out before we do not restrict their precense, but their exercise.
Quoted 97 lines
Documentation/userspace-api/landlock.rst +68
-2+them. This is purely restrictive: Landlock can only deny capabilities that the +traditional capability mechanism would have allowed, never grant additional ones. +Rules are added with ``LANDLOCK_RULE_CAPABILITY`` using a +&struct landlock_capability_attr. Each rule specifies a set of ``CAP_*`` values +(as a bitmask) to allow. Capabilities above ``CAP_LAST_CAP`` are silently +accepted but have no effect since the kernel never checks them; this means new +capabilities introduced by future kernels are automatically denied. + +When a Landlock domain handles ``LANDLOCK_PERM_NAMESPACE_ENTER``, namespace +creation and entry are denied by default unless a rule explicitly allows them. +Rules are added with ``LANDLOCK_RULE_NAMESPACE`` using a +&struct landlock_namespace_attr. Each rule specifies a set of ``CLONE_NEW*`` +flags to allow. + +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_ENTER`` +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``. + +More generally, Landlock domains and user namespaces form independent +hierarchies: Landlock domains restrict what actions are allowed (each stacked +layer narrows the permitted set), while user namespaces restrict where +capabilities take effect (only within the process's own namespace and its +descendants). Landlock access controls are fully determined by the domain +configuration, regardless of the process's position in the user namespace +hierarchy. 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, :manpage:`execve(2)` of +binaries with file capabilities, or :manpage:`capset(2)`. In all cases, +:manpage:`capget(2)` will report the credential's capability sets, but any +denied capability will fail with ``EPERM`` when exercised. + Truncating files ----------------@@ -515,7 +645,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 ----------------------@@ -534,7 +664,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 -------------------@@ -685,6 +816,21 @@ enforce Landlock rulesets across all threads of the calling process using the ``LANDLOCK_RESTRICT_SELF_TSYNC`` flag passed to sys_landlock_restrict_self(). +Capability restriction (ABI < 9) +-------------------------------- + +Starting with the Landlock ABI version 9, 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 < 9) +------------------------------- + +Starting with the Landlock ABI version 9, it is possible to restrict +namespace creation (:manpage:`unshare(2)`, :manpage:`clone(2)`) and entry +(:manpage:`setns(2)`) with the new ``LANDLOCK_PERM_NAMESPACE_ENTER`` permission +flag and ``LANDLOCK_RULE_NAMESPACE`` rule type. + .. _kernel_support: Kernel supportSignature · 1 line
2.53.0
Re: [RFC PATCH v1 11/11] landlock: Add documentation for capability and namespace restrictions
Quoted 343 lines · Mickaël Salaün
Quoted 93 lines · Justin Suess
Quoted 92 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), namespace restriction (LANDLOCK_PERM_NAMESPACE_ENTERwithLANDLOCK_RULE_NAMESPACEcovering creation via unshare/clone and entry via setns), and the backward-compatible degradation pattern for ABI < 9. A table documents the per-namespace-type capability requirements for both creation and entry.The admin guide adds the new perm.namespace_enter and perm.capability_use audit blocker names with their object identification fields (
namespace_type,namespace_inum, 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]>--- Documentation/admin-guide/LSM/landlock.rst | 19 ++- Documentation/security/landlock.rst | 80 ++++++++++- Documentation/userspace-api/landlock.rst | 156 ++++++++++++++++++++- 3 files changed, 245 insertions(+), 10 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: March 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 9+): + - perm.namespace_enter - 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_inum`` 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_inum`` 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: September 2025 +:Date: March 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,@@ -89,6 +89,72 @@ this is required to keep access controls consistent over the whole system, and this avoids unattended bypasses through file descriptor passing (i.e. confused deputy attack).Quoted 14 lines
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 101
Quoted 10 lines
Documentation/security/landlock.rst +10
-0+Composability with user namespaces +---------------------------------- + +Landlock domain-based scoping and the kernel's user namespace-based capability +scoping enforce isolation over independent hierarchies. 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 new +scoped features.The last sentence on orthogonality may better belong under the restriction model section for scoped access rights. I assume that future scopes must also be deterministic with respect to landlock's configuration as well, not just user namespaces.
Correct
Quoted 7 lines
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 104
Quoted 3 lines
Documentation/security/landlock.rst +3
-0+ +Ruleset restriction models +--------------------------+1
This section is very helpful for aligning new features with a particular model.
Thanks
Quoted 8 lines
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 107
Quoted 4 lines
Documentation/security/landlock.rst +3
-0+ +Landlock provides three restriction models, each with different coverage +and compatibility properties.Maybe add:
Each restriction model below corresponds to one or more fields of ``struct landlock_ruleset_attr``.
Ok
Quoted 202 lines
Quoted 202 lines
Documentation/security/landlock.rst +62
-0+ +Access rights (``handled_access_*``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Access rights control **enumerated operations on kernel objects** +identified by a rule key (a file hierarchy or a network port). Each +``handled_access_*`` field declares a set of access rights that the +ruleset restricts. Multiple access rights share a single rule type. +Operations for which no access right exists yet remain uncontrolled; +new rights are added incrementally across ABI versions. + +Permissions (``handled_perm``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Permissions control **broad operations enforced at single kernel +chokepoints**, achieving complete deny-by-default coverage. Each +``LANDLOCK_PERM_*`` flag maps to its own rule type. When a ruleset +handles a permission, all instances of that operation are denied unless +explicitly allowed by a rule. New kernel values (new ``CAP_*`` +capabilities, new ``CLONE_NEW*`` namespace types) are automatically +denied without any Landlock update. + +Each permission flag names a single gateway operation whose control +transitively covers an open-ended set of downstream operations: for +example, exercising a capability enables privileged operations across +many subsystems; entering a namespace enables gaining capabilities in a +new context. + +Permission rules identify what to allow using constants defined by other +kernel subsystems (``CAP_*``, ``CLONE_NEW*``). Unknown values are +silently ignored because deny-by-default ensures they are denied anyway. +In contrast, unknown ``LANDLOCK_PERM_*`` flags in ``handled_perm`` are +rejected (``-EINVAL``), since Landlock owns that namespace. + +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 +permissions, scopes provide complete coverage of the controlled +operation. + +When adding new Landlock features, new operations on existing rule types +extend the corresponding ``handled_access_*`` field (e.g. a new +filesystem operation extends ``handled_access_fs``). A new object +category with multiple fine-grained operations would use a new +``handled_access_*`` field. New rule types that control a single +chokepoint operation use ``handled_perm``. + Tests =====@@ -110,6 +176,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 +73
-3@@ -8,7 +8,7 @@ Landlock: unprivileged access control ===================================== :Author: Mickaël Salaün -:Date: January 2026 +:Date: March 2026 The goal of Landlock is to enable restriction of ambient rights (e.g. global filesystem or network access) for a set of processes. Because Landlock@@ -33,7 +33,7 @@ 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. -The two existing types of rules are: +The existing types of rules are: Filesystem rules For these rules, the object is a file hierarchy,@@ -44,6 +44,14 @@ Network rules (since ABI v4) For these rules, the object is a TCP port, and the related actions are defined with `network access rights`. +Capability rules (since ABI v9) + For these rules, the object is a set of Linux capabilities, + and the related actions are defined with `permission flags`. + +Namespace rules (since ABI v9) + For these rules, the object is a set of namespace types, + and the related actions are defined with `permission flags`. + Defining and enforcing a security policy ----------------------------------------@@ -84,6 +92,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_ENTER, }; Because we may not know which kernel version an application will be executed@@ -127,6 +138,12 @@ version, and only use the available subset of access rights: /* Removes LANDLOCK_SCOPE_* for ABI < 6 */ ruleset_attr.scoped &= ~(LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | LANDLOCK_SCOPE_SIGNAL); + __attribute__((fallthrough)); + case 6: + case 7: + case 8: + /* Removes permission support for ABI < 9 */ + ruleset_attr.handled_perm = 0; } This enables the creation of an inclusive ruleset that will contain our rules.@@ -191,6 +208,42 @@ number for a specific action: HTTPS connections. err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT, &net_port, 0); +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), + }; + + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_CAPABILITY, + &cap_attr, 0); + +For namespace access-control, we can add rules that allow entering specific +namespace types (creating them via :manpage:`unshare(2)` / :manpage:`clone(2)` +or joining them via :manpage:`setns(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_ENTER, + .namespace_types = CLONE_NEWUSER, + }; + + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NAMESPACE, + &ns_attr, 0); + +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):@@ -354,10 +407,87 @@ 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)`. +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 +------------------------------------- + +See Documentation/security/landlock.rst for the design rationale behind +the permission model (``handled_perm``) and how it differs from access +rights (``handled_access_*``) and scopes (``scoped``). +When a process creates a user namespace, the kernel grants all capabilities +within that namespace. While these capabilities cannot directly bypass Landlock +restrictions (Landlock enforces access controls independently of capability +checks), they open kernel code paths that are normally unreachable to +unprivileged users and may contain exploitable bugs. + +Landlock provides two complementary permissions to address this. +``LANDLOCK_PERM_CAPABILITY_USE`` restricts which capabilities a process can use, +even when it holds them. ``LANDLOCK_PERM_NAMESPACE_ENTER`` restricts which +namespace types a process can create (via :manpage:`unshare(2)` or +:manpage:`clone(2)`) or join (via :manpage:`setns(2)`). After creating a userQuoted 8 lines
Documentation/userspace-api/landlock.rst The operations which can be scoped are: · line 437
Quoted 7 lines
Documentation/userspace-api/landlock.rst +7
-0+namespace, the granted capabilities are scoped to namespaces owned by that user +namespace or its descendants; to exercise a capability such as +``CAP_NET_ADMIN``, the process must create a namespace of the corresponding type +(e.g., a network namespace). Configuring both permissions together provides +full coverage: ``LANDLOCK_PERM_CAPABILITY_USE`` restricts which capabilities are +available, while ``LANDLOCK_PERM_NAMESPACE_ENTER`` restricts the namespaces in +which they can be used.Maybe add a section on the what this does versus
PR_SET_NO_NEW_PRIVS.
Quoted 1 line
Hmm, what do you mean? What would be the link with this part?
PR_SET_NO_NEW_PRIVS prevents gaining of privileges through execution, including capabilities (i.e setcap command, not just setuid/gid). So they're adjacent at least.
Some users might not want to set NNP because they want to execute a binary with w/ CAP_BPF file capabilities set for instance. But they don't need CAP_SYS_ADMIN or whatever for their usecase.
There could be language saying "*hint hint* hey if you can't use NNP, you should really be looking at the capability restrictions".
Quoted 5 lines
Quoted 5 lines
The difference might be obvious to people familiar with namespaces and capabilities, but not to many users less familiar with the subject.
Quoted 7 lines
Quoted 4 lines
I could see users using the LANDLOCK_PERM_* flags erroneously assuming that
LANDLOCK_PERM_CAPABILITY_USEis required to restrict gaining of new capabilities throughexecve(), (ie through setuid) when in fact this is already restricted if nnp is set.What would be the issue if no rule allow capabilities? The most handled_* or scoped bits are set, the better.
Agreed, the more the better.
I just think it would be beneficial to mention the differences up front, especially because NNP won't prevent exercise of existing capabilities, but this will. So the description for this should at least touch on NNP because they are complimentary.
I think a lot of devs that just want to add sandboxing aren't deeply familiar with how capabilities work.
Quoted 21 lines
Quoted 4 lines
Some clarification on this would be helpful here or where
PR_SET_NO_NEW_PRIVSis discussed in the Landlock docs.Ok, I'll try to add something about NNP.
Quoted 10 lines
Documentation/userspace-api/landlock.rst The operations which can be scoped are: · line 440
Quoted 3 lines
Documentation/userspace-api/landlock.rst +3
-0+ +When a Landlock domain handles ``LANDLOCK_PERM_CAPABILITY_USE``, all Linux +:manpage:`capabilities(7)` are denied by default unless a rule explicitly allowsNit:
all Linux :manpage:
capabilities(7)might be better as
the exercise of all Linux :manpage:
capabilities(7)Indeed
Quoted 1 line
[...]
Re: [RFC PATCH v1 11/11] landlock: Add documentation for capability and namespace restrictions
Quoted 344 lines · Justin Suess
Quoted 343 lines · Mickaël Salaün
Quoted 93 lines · Justin Suess
Quoted 92 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), namespace restriction (LANDLOCK_PERM_NAMESPACE_ENTERwithLANDLOCK_RULE_NAMESPACEcovering creation via unshare/clone and entry via setns), and the backward-compatible degradation pattern for ABI < 9. A table documents the per-namespace-type capability requirements for both creation and entry.The admin guide adds the new perm.namespace_enter and perm.capability_use audit blocker names with their object identification fields (
namespace_type,namespace_inum, 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]>--- Documentation/admin-guide/LSM/landlock.rst | 19 ++- Documentation/security/landlock.rst | 80 ++++++++++- Documentation/userspace-api/landlock.rst | 156 ++++++++++++++++++++- 3 files changed, 245 insertions(+), 10 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: March 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 9+): + - perm.namespace_enter - 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_inum`` 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_inum`` 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: September 2025 +:Date: March 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,@@ -89,6 +89,72 @@ this is required to keep access controls consistent over the whole system, and this avoids unattended bypasses through file descriptor passing (i.e. confused deputy attack).Quoted 14 lines
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 101
Quoted 10 lines
Documentation/security/landlock.rst +10
-0+Composability with user namespaces +---------------------------------- + +Landlock domain-based scoping and the kernel's user namespace-based capability +scoping enforce isolation over independent hierarchies. 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 new +scoped features.The last sentence on orthogonality may better belong under the restriction model section for scoped access rights. I assume that future scopes must also be deterministic with respect to landlock's configuration as well, not just user namespaces.
Correct
Quoted 7 lines
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 104
Quoted 3 lines
Documentation/security/landlock.rst +3
-0+ +Ruleset restriction models +--------------------------+1
This section is very helpful for aligning new features with a particular model.
Thanks
Quoted 8 lines
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 107
Quoted 4 lines
Documentation/security/landlock.rst +3
-0+ +Landlock provides three restriction models, each with different coverage +and compatibility properties.Maybe add:
Each restriction model below corresponds to one or more fields of ``struct landlock_ruleset_attr``.
Ok
Quoted 210 lines
Quoted 199 lines
Documentation/security/landlock.rst +62
-0+ +Access rights (``handled_access_*``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Access rights control **enumerated operations on kernel objects** +identified by a rule key (a file hierarchy or a network port). Each +``handled_access_*`` field declares a set of access rights that the +ruleset restricts. Multiple access rights share a single rule type. +Operations for which no access right exists yet remain uncontrolled; +new rights are added incrementally across ABI versions. + +Permissions (``handled_perm``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Permissions control **broad operations enforced at single kernel +chokepoints**, achieving complete deny-by-default coverage. Each +``LANDLOCK_PERM_*`` flag maps to its own rule type. When a ruleset +handles a permission, all instances of that operation are denied unless +explicitly allowed by a rule. New kernel values (new ``CAP_*`` +capabilities, new ``CLONE_NEW*`` namespace types) are automatically +denied without any Landlock update. + +Each permission flag names a single gateway operation whose control +transitively covers an open-ended set of downstream operations: for +example, exercising a capability enables privileged operations across +many subsystems; entering a namespace enables gaining capabilities in a +new context. + +Permission rules identify what to allow using constants defined by other +kernel subsystems (``CAP_*``, ``CLONE_NEW*``). Unknown values are +silently ignored because deny-by-default ensures they are denied anyway. +In contrast, unknown ``LANDLOCK_PERM_*`` flags in ``handled_perm`` are +rejected (``-EINVAL``), since Landlock owns that namespace. + +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 +permissions, scopes provide complete coverage of the controlled +operation. + +When adding new Landlock features, new operations on existing rule types +extend the corresponding ``handled_access_*`` field (e.g. a new +filesystem operation extends ``handled_access_fs``). A new object +category with multiple fine-grained operations would use a new +``handled_access_*`` field. New rule types that control a single +chokepoint operation use ``handled_perm``. + Tests =====@@ -110,6 +176,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 +70
-3@@ -8,7 +8,7 @@ Landlock: unprivileged access control ===================================== :Author: Mickaël Salaün -:Date: January 2026 +:Date: March 2026 The goal of Landlock is to enable restriction of ambient rights (e.g. global filesystem or network access) for a set of processes. Because Landlock@@ -33,7 +33,7 @@ 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. -The two existing types of rules are: +The existing types of rules are: Filesystem rules For these rules, the object is a file hierarchy,@@ -44,6 +44,14 @@ Network rules (since ABI v4) For these rules, the object is a TCP port, and the related actions are defined with `network access rights`. +Capability rules (since ABI v9) + For these rules, the object is a set of Linux capabilities, + and the related actions are defined with `permission flags`. + +Namespace rules (since ABI v9) + For these rules, the object is a set of namespace types, + and the related actions are defined with `permission flags`. + Defining and enforcing a security policy ----------------------------------------@@ -84,6 +92,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_ENTER, }; Because we may not know which kernel version an application will be executed@@ -127,6 +138,12 @@ version, and only use the available subset of access rights: /* Removes LANDLOCK_SCOPE_* for ABI < 6 */ ruleset_attr.scoped &= ~(LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | LANDLOCK_SCOPE_SIGNAL); + __attribute__((fallthrough)); + case 6: + case 7: + case 8: + /* Removes permission support for ABI < 9 */ + ruleset_attr.handled_perm = 0; } This enables the creation of an inclusive ruleset that will contain our rules.@@ -191,6 +208,42 @@ number for a specific action: HTTPS connections. err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT, &net_port, 0); +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), + }; + + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_CAPABILITY, + &cap_attr, 0); + +For namespace access-control, we can add rules that allow entering specific +namespace types (creating them via :manpage:`unshare(2)` / :manpage:`clone(2)` +or joining them via :manpage:`setns(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_ENTER, + .namespace_types = CLONE_NEWUSER, + }; + + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NAMESPACE, + &ns_attr, 0); + +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):@@ -354,10 +407,87 @@ 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)`. +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 +------------------------------------- + +See Documentation/security/landlock.rst for the design rationale behind +the permission model (``handled_perm``) and how it differs from access +rights (``handled_access_*``) and scopes (``scoped``). +When a process creates a user namespace, the kernel grants all capabilities +within that namespace. While these capabilities cannot directly bypass Landlock +restrictions (Landlock enforces access controls independently of capability +checks), they open kernel code paths that are normally unreachable to +unprivileged users and may contain exploitable bugs. + +Landlock provides two complementary permissions to address this. +``LANDLOCK_PERM_CAPABILITY_USE`` restricts which capabilities a process can use,Documentation/userspace-api/landlock.rst The operations which can be scoped are: · line 437
Quoted 10 lines
Documentation/userspace-api/landlock.rst +10
-0+even when it holds them. ``LANDLOCK_PERM_NAMESPACE_ENTER`` restricts which +namespace types a process can create (via :manpage:`unshare(2)` or +:manpage:`clone(2)`) or join (via :manpage:`setns(2)`). After creating a user +namespace, the granted capabilities are scoped to namespaces owned by that user +namespace or its descendants; to exercise a capability such as +``CAP_NET_ADMIN``, the process must create a namespace of the corresponding type +(e.g., a network namespace). Configuring both permissions together provides +full coverage: ``LANDLOCK_PERM_CAPABILITY_USE`` restricts which capabilities are +available, while ``LANDLOCK_PERM_NAMESPACE_ENTER`` restricts the namespaces in +which they can be used.Maybe add a section on the what this does versus
PR_SET_NO_NEW_PRIVS.
Quoted 9 lines
Quoted 1 line
Hmm, what do you mean? What would be the link with this part?
PR_SET_NO_NEW_PRIVSprevents gaining of privileges through execution, including capabilities (i.e setcap command, not just setuid/gid). So they're adjacent at least.Some users might not want to set NNP because they want to execute a binary with w/
CAP_BPFfile capabilities set for instance. But they don't needCAP_SYS_ADMINor whatever for their usecase.
Bad example sorry. They need CAP_SYS_ADMIN to make the ruleset. But this point still applies for other caps or if they drop CAP_SYS_ADMIN after applying the ruleset.
Re: [RFC PATCH v1 11/11] landlock: Add documentation for capability and namespace restrictions
In reply to Mickaël SalaünHello!
Quoted 95 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), namespace restriction (LANDLOCK_PERM_NAMESPACE_ENTERwithLANDLOCK_RULE_NAMESPACEcovering creation via unshare/clone and entry via setns), and the backward-compatible degradation pattern for ABI < 9. A table documents the per-namespace-type capability requirements for both creation and entry.The admin guide adds the new perm.namespace_enter and perm.capability_use audit blocker names with their object identification fields (
namespace_type,namespace_inum, 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]>--- Documentation/admin-guide/LSM/landlock.rst | 19 ++- Documentation/security/landlock.rst | 80 ++++++++++- Documentation/userspace-api/landlock.rst | 156 ++++++++++++++++++++- 3 files changed, 245 insertions(+), 10 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: March 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 9+): + - perm.namespace_enter - 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_inum`` 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_inum`` for namespace operations; + ``capability`` for capability use. AUDIT_LANDLOCK_DOMAINDocumentation/security/landlock.rst +4
-1@@ -7,7 +7,7 @@ Landlock LSM: kernel documentation ================================== :Author: Mickaël Salaün -:Date: September 2025 +:Date: March 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,@@ -89,6 +89,72 @@ this is required to keep access controls consistent over the whole system, and this avoids unattended bypasses through file descriptor passing (i.e. confused deputy attack). +Composability with user namespaces +---------------------------------- +
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 104
Quoted 10 lines
Documentation/security/landlock.rst +10
-0+Landlock domain-based scoping and the kernel's user namespace-based capability +scoping enforce isolation over independent hierarchies. 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 new +scoped features. + +Ruleset restriction models +--------------------------
I have to second Justin, it's a good idea to introduce this explanation.
Quoted 14 lines
Documentation/security/landlock.rst +14
-0+ +Landlock provides three restriction models, each with different coverage +and compatibility properties. + +Access rights (``handled_access_*``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Access rights control **enumerated operations on kernel objects** +identified by a rule key (a file hierarchy or a network port). Each +``handled_access_*`` field declares a set of access rights that the +ruleset restricts. Multiple access rights share a single rule type. +Operations for which no access right exists yet remain uncontrolled; +new rights are added incrementally across ABI versions. +
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 128
Quoted 10 lines
Documentation/security/landlock.rst +10
-0+Permissions (``handled_perm``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Permissions control **broad operations enforced at single kernel +chokepoints**, achieving complete deny-by-default coverage. Each +``LANDLOCK_PERM_*`` flag maps to its own rule type. When a ruleset +handles a permission, all instances of that operation are denied unless +explicitly allowed by a rule. New kernel values (new ``CAP_*`` +capabilities, new ``CLONE_NEW*`` namespace types) are automatically +denied without any Landlock update.
I find the terminology of "chokepoints" and "gateways" in this and the header documentation a bit vague; you could argue that opening a file for reading is also a chokepoint/gateway for using read() later on; it's not immediately clear to me how that's delineated.
In my mind, the handled_* groups of access rights are usually defined by the "namespace" of the objects they are protecting, more than anything else: handled_access_fs: file paths, handled_access_net:
struct sockaddr (which we only expose as "port" for now).
To play the devil's advocate, a possible alternative would have been to introduce:
handled_access_ns with values LANDLOCK_ACCESS_NS_FOO_ENTER, LANDLOCK_ACCESS_NS_BAR_ENTER, etc. (and documenting somewhere that these are guaranteed to stay in sync; a static assert is enough to make sure they do).
handled_access_caps with values LANDLOCK_ACCESS_CAPS_USE_FOO, LANDLOCK_ACCESS_CAPS_USE_BAR, etc., also guaranteed to stay in sync.
That way the blocked accesses would still be "operations", and we would not need to have rules for them because the "object" being protected are the processes within the Landlock domain, so to say.
Arguably, the LANDLOCK_ACCESS_FS_MAKE_* rights already follow a similar pattern.
To be clear, I am myself only 50% convinced whether the API would be better. The implementation would be easier (but that doesn't count much in comparison).
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 140
Quoted 11 lines
Documentation/security/landlock.rst +11
-0+Each permission flag names a single gateway operation whose control +transitively covers an open-ended set of downstream operations: for +example, exercising a capability enables privileged operations across +many subsystems; entering a namespace enables gaining capabilities in a +new context. + +Permission rules identify what to allow using constants defined by other +kernel subsystems (``CAP_*``, ``CLONE_NEW*``). Unknown values are +silently ignored because deny-by-default ensures they are denied anyway. +In contrast, unknown ``LANDLOCK_PERM_*`` flags in ``handled_perm`` are +rejected (``-EINVAL``), since Landlock owns that namespace.
OK I played through the compatibility scenarios which puzzled me in my reply to the cover letter, for both namespaces and capabilities. Namespaces are OK, so I'm just including that for completeness and for comparison, but I think the capabilities might be tricky?
Case A: Namespaces
In the scenario where a caller restricts LANDLOCK_PERM_NAMESPACE_ENTER, but then adds a rule to allow a non-existent namespace number like 1<<63.
Landlock ABI v9:
* The rule is accepted and the unknown value for the namespace type silently ignored
* It is not possible to enter the namespace because the namespace API doesn't exist for it. (But that's appropriate.)
Landlock ABI v_future (the namespace type 1<<63 exists now):
* The rule continues to be accepted.
* When trying to exercise the namespace type, it works.
It seems that this scenario works fine. In the earlier version, entering the namespace already doesn't work because the kernel doesn't have support for it.
Case B: Capabilities
Whne new capabilities are introduced, I see that people have used the pattern where these capabilities are split off from operations which were previously controlled by CAP_SYS_ADMIN. An example is commit a17b53c4a4b5 ("bpf, capability: Introduce CAP_BPF"), which states:
Split BPF operations that are allowed under CAP_SYS_ADMIN into combination of CAP_BPF, CAP_PERFMON, CAP_NET_ADMIN. For backward compatibility include them in CAP_SYS_ADMIN as well.
(The same pattern was also used in the introduction of CAP_CHECKPOINT_RESTORE and CAP_PERFMON. CAP_AUDIT_READ is older and did it differently.)
Let's say there is a frobnicate() syscall guarded by CAP_SYS_ADMIN. A future kernel introduces CAP_FOO and then checks for frobnicate() that either one of CAP_FOO or CAP_SYS_ADMIN are present.
A caller creates a ruleset restricting capability use with Landlock, and adds a rule to allow CAP_FOO but not CAP_SYS_ADMIN (e.g., ^CAP_SYS_ADMIN)
Landlock ABI v9: (CAP_FOO doesn't exist)
* The rule for CAP_FOO is accepted and the unknown value for the capability silently ignored.
* The call to frobnicate() fails because the use of the capability is forbidden
Landlock ABI v10: (CAP_FOO starts to exist)
* The rule continues to be accepted
* The call to frobnicate() **succeeds now**, because the new kernel guards the operation by either one of those capabilities.
So... for capabilities, it seems to be slightly incompatible if users allow capabilities with a rule which are not known yet? The reason for that is the way how capabilities "fork off" from CAP_SYS_ADMIN.
I mean, I can see that it's a pretty fringe scenario if users pass capabilities that don't exist yet, but it *is* strictly speaking an incompatibiliy. Should we check the range of the passed capabilities? Am I overlooking any downsides to this if we force users to stay between 0 and CAP_LAST_CAP?
Quoted 175 lines
Documentation/security/landlock.rst +29
-0+ +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 +permissions, scopes provide complete coverage of the controlled +operation. + +When adding new Landlock features, new operations on existing rule types +extend the corresponding ``handled_access_*`` field (e.g. a new +filesystem operation extends ``handled_access_fs``). A new object +category with multiple fine-grained operations would use a new +``handled_access_*`` field. New rule types that control a single +chokepoint operation use ``handled_perm``. + Tests =====@@ -110,6 +176,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 +80
-3@@ -8,7 +8,7 @@ Landlock: unprivileged access control ===================================== :Author: Mickaël Salaün -:Date: January 2026 +:Date: March 2026 The goal of Landlock is to enable restriction of ambient rights (e.g. global filesystem or network access) for a set of processes. Because Landlock@@ -33,7 +33,7 @@ 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. -The two existing types of rules are: +The existing types of rules are: Filesystem rules For these rules, the object is a file hierarchy,@@ -44,6 +44,14 @@ Network rules (since ABI v4) For these rules, the object is a TCP port, and the related actions are defined with `network access rights`. +Capability rules (since ABI v9) + For these rules, the object is a set of Linux capabilities, + and the related actions are defined with `permission flags`. + +Namespace rules (since ABI v9) + For these rules, the object is a set of namespace types, + and the related actions are defined with `permission flags`. + Defining and enforcing a security policy ----------------------------------------@@ -84,6 +92,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_ENTER, }; Because we may not know which kernel version an application will be executed@@ -127,6 +138,12 @@ version, and only use the available subset of access rights: /* Removes LANDLOCK_SCOPE_* for ABI < 6 */ ruleset_attr.scoped &= ~(LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | LANDLOCK_SCOPE_SIGNAL); + __attribute__((fallthrough)); + case 6: + case 7: + case 8: + /* Removes permission support for ABI < 9 */ + ruleset_attr.handled_perm = 0; } This enables the creation of an inclusive ruleset that will contain our rules.@@ -191,6 +208,42 @@ number for a specific action: HTTPS connections. err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT, &net_port, 0); +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), + }; + + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_CAPABILITY, + &cap_attr, 0); + +For namespace access-control, we can add rules that allow entering specific +namespace types (creating them via :manpage:`unshare(2)` / :manpage:`clone(2)` +or joining them via :manpage:`setns(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_ENTER, + .namespace_types = CLONE_NEWUSER, + }; + + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NAMESPACE, + &ns_attr, 0); + +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):@@ -354,10 +407,87 @@ 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)`. +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 +------------------------------------- + +See Documentation/security/landlock.rst for the design rationale behind +the permission model (``handled_perm``) and how it differs from access +rights (``handled_access_*``) and scopes (``scoped``). +When a process creates a user namespace, the kernel grants all capabilities +within that namespace. While these capabilities cannot directly bypass Landlock +restrictions (Landlock enforces access controls independently of capability +checks), they open kernel code paths that are normally unreachable to +unprivileged users and may contain exploitable bugs. + +Landlock provides two complementary permissions to address this. +``LANDLOCK_PERM_CAPABILITY_USE`` restricts which capabilities a process can use, +even when it holds them. ``LANDLOCK_PERM_NAMESPACE_ENTER`` restricts which +namespace types a process can create (via :manpage:`unshare(2)` or +:manpage:`clone(2)`) or join (via :manpage:`setns(2)`). After creating a user +namespace, the granted capabilities are scoped to namespaces owned by that user +namespace or its descendants; to exercise a capability such as +``CAP_NET_ADMIN``, the process must create a namespace of the corresponding type +(e.g., a network namespace). Configuring both permissions together provides +full coverage: ``LANDLOCK_PERM_CAPABILITY_USE`` restricts which capabilities are +available, while ``LANDLOCK_PERM_NAMESPACE_ENTER`` restricts the namespaces in +which they can be used.
Documentation/userspace-api/landlock.rst The operations which can be scoped are: · line 447
Quoted 10 lines
Documentation/userspace-api/landlock.rst +10
-0+ +When a Landlock domain handles ``LANDLOCK_PERM_CAPABILITY_USE``, all Linux +:manpage:`capabilities(7)` are denied by default unless a rule explicitly allows +them. This is purely restrictive: Landlock can only deny capabilities that the +traditional capability mechanism would have allowed, never grant additional ones. +Rules are added with ``LANDLOCK_RULE_CAPABILITY`` using a +&struct landlock_capability_attr. Each rule specifies a set of ``CAP_*`` values +(as a bitmask) to allow. Capabilities above ``CAP_LAST_CAP`` are silently +accepted but have no effect since the kernel never checks them; this means new +capabilities introduced by future kernels are automatically denied.
(See example above.)
Quoted 90 lines
Documentation/userspace-api/landlock.rst +61
-2+ +When a Landlock domain handles ``LANDLOCK_PERM_NAMESPACE_ENTER``, namespace +creation and entry are denied by default unless a rule explicitly allows them. +Rules are added with ``LANDLOCK_RULE_NAMESPACE`` using a +&struct landlock_namespace_attr. Each rule specifies a set of ``CLONE_NEW*`` +flags to allow. + +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_ENTER`` +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``. + +More generally, Landlock domains and user namespaces form independent +hierarchies: Landlock domains restrict what actions are allowed (each stacked +layer narrows the permitted set), while user namespaces restrict where +capabilities take effect (only within the process's own namespace and its +descendants). Landlock access controls are fully determined by the domain +configuration, regardless of the process's position in the user namespace +hierarchy. 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, :manpage:`execve(2)` of +binaries with file capabilities, or :manpage:`capset(2)`. In all cases, +:manpage:`capget(2)` will report the credential's capability sets, but any +denied capability will fail with ``EPERM`` when exercised. + Truncating files ----------------@@ -515,7 +645,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 ----------------------@@ -534,7 +664,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 -------------------@@ -685,6 +816,21 @@ enforce Landlock rulesets across all threads of the calling process using the ``LANDLOCK_RESTRICT_SELF_TSYNC`` flag passed to sys_landlock_restrict_self(). +Capability restriction (ABI < 9) +-------------------------------- + +Starting with the Landlock ABI version 9, 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 < 9) +------------------------------- + +Starting with the Landlock ABI version 9, it is possible to restrict +namespace creation (:manpage:`unshare(2)`, :manpage:`clone(2)`) and entry +(:manpage:`setns(2)`) with the new ``LANDLOCK_PERM_NAMESPACE_ENTER`` permission +flag and ``LANDLOCK_RULE_NAMESPACE`` rule type. + .. _kernel_support: Kernel supportSignature · 1 line
2.53.0
Mickaël Salaün
maintainerRe: [RFC PATCH v1 11/11] landlock: Add documentation for capability and namespace restrictions
Quoted 132 lines · Günther Noack
Hello!
Quoted 95 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), namespace restriction (LANDLOCK_PERM_NAMESPACE_ENTERwithLANDLOCK_RULE_NAMESPACEcovering creation via unshare/clone and entry via setns), and the backward-compatible degradation pattern for ABI < 9. A table documents the per-namespace-type capability requirements for both creation and entry.The admin guide adds the new perm.namespace_enter and perm.capability_use audit blocker names with their object identification fields (
namespace_type,namespace_inum, 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]>--- Documentation/admin-guide/LSM/landlock.rst | 19 ++- Documentation/security/landlock.rst | 80 ++++++++++- Documentation/userspace-api/landlock.rst | 156 ++++++++++++++++++++- 3 files changed, 245 insertions(+), 10 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: March 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 9+): + - perm.namespace_enter - 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_inum`` 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_inum`` for namespace operations; + ``capability`` for capability use. AUDIT_LANDLOCK_DOMAINDocumentation/security/landlock.rst +4
-1@@ -7,7 +7,7 @@ Landlock LSM: kernel documentation ================================== :Author: Mickaël Salaün -:Date: September 2025 +:Date: March 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,@@ -89,6 +89,72 @@ this is required to keep access controls consistent over the whole system, and this avoids unattended bypasses through file descriptor passing (i.e. confused deputy attack). +Composability with user namespaces +---------------------------------- +Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 104
Quoted 10 lines
Documentation/security/landlock.rst +10
-0+Landlock domain-based scoping and the kernel's user namespace-based capability +scoping enforce isolation over independent hierarchies. 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 new +scoped features. + +Ruleset restriction models +--------------------------I have to second Justin, it's a good idea to introduce this explanation.
Quoted 21 lines
Documentation/security/landlock.rst +21
-0+ +Landlock provides three restriction models, each with different coverage +and compatibility properties. + +Access rights (``handled_access_*``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Access rights control **enumerated operations on kernel objects** +identified by a rule key (a file hierarchy or a network port). Each +``handled_access_*`` field declares a set of access rights that the +ruleset restricts. Multiple access rights share a single rule type. +Operations for which no access right exists yet remain uncontrolled; +new rights are added incrementally across ABI versions. + +Permissions (``handled_perm``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Permissions control **broad operations enforced at single kernel +chokepoints**, achieving complete deny-by-default coverage. Each +``LANDLOCK_PERM_*`` flag maps to its own rule type. When a ruleset +handles a permission, all instances of that operation are denied unless
Quoted 8 lines
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 128
Quoted 3 lines
Documentation/security/landlock.rst +3
-0+explicitly allowed by a rule. New kernel values (new ``CAP_*`` +capabilities, new ``CLONE_NEW*`` namespace types) are automatically +denied without any Landlock update.I find the terminology of "chokepoints" and "gateways" in this and the header documentation a bit vague; you could argue that opening a file for reading is also a chokepoint/gateway for using
read()later on; it's not immediately clear to me how that's delineated.
Yeah, I wanted to express something wider that a fine-grained access right. Any alternative words that would fit better?
Quoted 6 lines
In my mind, the handled_* groups of access rights are usually defined by the "namespace" of the objects they are protecting, more than anything else:
handled_access_fs: file paths,handled_access_net:
struct sockaddr (which we only expose as "port" for now).
Quoted 7 lines
To play the devil's advocate, a possible alternative would have been to introduce:
handled_access_nswith valuesLANDLOCK_ACCESS_NS_FOO_ENTER,LANDLOCK_ACCESS_NS_BAR_ENTER, etc. (and documenting somewhere that these are guaranteed to stay in sync; a static assert is enough to make sure they do).
That was actually one of my initial version, but I couldn't find any meaning ful other access rights that would both be useful for the sandboxing use case and worth the implementation. At the end I concluded that we needed "ambiant" access rights for things that are not really tied to existing kernel objects, and to be able to fully express current and future properties, hence using non-Landlock UAPI (capabilities, namespace types...). The handled_perm name was the less ambiguous one I could find, which still make sense.
Another important property is that the permissions rules don't have access rights, only *one* permission bit which could be removed. I choose to keep it as a safeguard (for UAPI check) and to still be able to add new ones for such rule if one day we really find a useful use case. Anyway, it's basically free.
Quoted 3 lines
handled_access_capswith valuesLANDLOCK_ACCESS_CAPS_USE_FOO,LANDLOCK_ACCESS_CAPS_USE_BAR, etc., also guaranteed to stay in sync.
Genuine question: what would be these FOO and BAR? I couldn't find anything worth it. The idea is to have a simple interface. In fact, initially I didn't have these suffixes (i.e. _USE, _ENTER), and they are not really needed, but these are also safeguards in the case we would need one, and the main motivation is to make the semantic clear to users (and more consistent with other Landlock access rights).
Quoted 4 lines
That way the blocked accesses would still be "operations", and we would not need to have rules for them because the "object" being protected are the processes within the Landlock domain, so to say.
I'm not sure to understand, but an (also) previous version was to just put the capability (and namespace type) bits directly in the ruleset struct. The issue with this approach is that it doesn't work well with a deny-by-default enforcement, and this would not be extensible, and this would not handle well compatibility (fields set to zero by default).
Quoted 3 lines
Arguably, the LANDLOCK_ACCESS_FS_MAKE_* rights already follow a similar pattern.
Hmm, I'm not following.
Quoted 30 lines
To be clear, I am myself only 50% convinced whether the API would be better. The implementation would be easier (but that doesn't count much in comparison).
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 140
Quoted 11 lines
Documentation/security/landlock.rst +11
-0+Each permission flag names a single gateway operation whose control +transitively covers an open-ended set of downstream operations: for +example, exercising a capability enables privileged operations across +many subsystems; entering a namespace enables gaining capabilities in a +new context. + +Permission rules identify what to allow using constants defined by other +kernel subsystems (``CAP_*``, ``CLONE_NEW*``). Unknown values are +silently ignored because deny-by-default ensures they are denied anyway. +In contrast, unknown ``LANDLOCK_PERM_*`` flags in ``handled_perm`` are +rejected (``-EINVAL``), since Landlock owns that namespace.OK I played through the compatibility scenarios which puzzled me in my reply to the cover letter, for both namespaces and capabilities. Namespaces are OK, so I'm just including that for completeness and for comparison, but I think the capabilities might be tricky?
Case A: Namespaces
In the scenario where a caller restricts
LANDLOCK_PERM_NAMESPACE_ENTER, but then adds a rule to allow a non-existent namespace number like 1<<63.
Quoted 5 lines
Landlock ABI v9:
* The rule is accepted and the unknown value for the namespace type silently ignored
* It is not possible to enter the namespace because the namespace API doesn't exist for it. (But that's appropriate.)
Yes, the namespace would just be unknown to the kernel, Landlock doesn't do anything here.
Quoted 4 lines
Landlock ABI
v_future(the namespace type 1<<63 exists now):
* The rule continues to be accepted.
* When trying to exercise the namespace type, it works.
It works because the kernel now know about this namespace. Again, nothing related to Landlock specifically.
Quoted 13 lines
It seems that this scenario works fine. In the earlier version, entering the namespace already doesn't work because the kernel doesn't have support for it.
Case B: Capabilities
Whne new capabilities are introduced, I see that people have used the pattern where these capabilities are split off from operations which were previously controlled by
CAP_SYS_ADMIN. An example is commita17b53c4a4b5("bpf, capability: IntroduceCAP_BPF"), which states:
Quoted 7 lines
Split BPF operations that are allowed under
CAP_SYS_ADMINinto combination ofCAP_BPF,CAP_PERFMON,CAP_NET_ADMIN. For backward compatibility include them inCAP_SYS_ADMINas well.(The same pattern was also used in the introduction of
CAP_CHECKPOINT_RESTOREandCAP_PERFMON.CAP_AUDIT_READis older and did it differently.)
The key point here (and the architectural limitation) is that a new capability cannot completely replace an existing one. The original capability check will remain forever.
Quoted 21 lines
Let's say there is a
frobnicate()syscall guarded byCAP_SYS_ADMIN. A future kernel introducesCAP_FOOand then checks forfrobnicate()that either one ofCAP_FOOorCAP_SYS_ADMINare present.A caller creates a ruleset restricting capability use with Landlock, and adds a rule to allow
CAP_FOObut notCAP_SYS_ADMIN(e.g., ^CAP_SYS_ADMIN)Landlock ABI v9: (
CAP_FOOdoesn't exist)
* The rule forCAP_FOOis accepted and the unknown value for the capability silently ignored.
* The call tofrobnicate()fails because the use of the capability is forbiddenLandlock ABI v10: (
CAP_FOOstarts to exist)
* The rule continues to be accepted
* The call tofrobnicate()**succeeds now**, because the new kernel guards the operation by either one of those capabilities.
Quoted 3 lines
So... for capabilities, it seems to be slightly incompatible if users allow capabilities with a rule which are not known yet? The reason for that is the way how capabilities "fork off" from
CAP_SYS_ADMIN.
The key point is that the compatibility is deferred to the other kernel subsystems. User space need to know which capabilities (or namespace types) are supported before using them. It's not a Landlock compatibility issue.
Quoted 6 lines
I mean, I can see that it's a pretty fringe scenario if users pass capabilities that don't exist yet, but it *is* strictly speaking an incompatibiliy. Should we check the range of the passed capabilities? Am I overlooking any downsides to this if we force users to stay between 0 and
CAP_LAST_CAP?
Checking the range of known capabilities (or namespace types) could break the same Landlock rules on different kernels even if targeting the same Landlock ABI version, which would be much worse. I definitely prefer to have idempotent/deterministic Landlock rules.
Quoted 282 lines
Quoted 177 lines
Documentation/security/landlock.rst +29
-0+ +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 +permissions, scopes provide complete coverage of the controlled +operation. + +When adding new Landlock features, new operations on existing rule types +extend the corresponding ``handled_access_*`` field (e.g. a new +filesystem operation extends ``handled_access_fs``). A new object +category with multiple fine-grained operations would use a new +``handled_access_*`` field. New rule types that control a single +chokepoint operation use ``handled_perm``. + Tests =====@@ -110,6 +176,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 +80
-3@@ -8,7 +8,7 @@ Landlock: unprivileged access control ===================================== :Author: Mickaël Salaün -:Date: January 2026 +:Date: March 2026 The goal of Landlock is to enable restriction of ambient rights (e.g. global filesystem or network access) for a set of processes. Because Landlock@@ -33,7 +33,7 @@ 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. -The two existing types of rules are: +The existing types of rules are: Filesystem rules For these rules, the object is a file hierarchy,@@ -44,6 +44,14 @@ Network rules (since ABI v4) For these rules, the object is a TCP port, and the related actions are defined with `network access rights`. +Capability rules (since ABI v9) + For these rules, the object is a set of Linux capabilities, + and the related actions are defined with `permission flags`. + +Namespace rules (since ABI v9) + For these rules, the object is a set of namespace types, + and the related actions are defined with `permission flags`. + Defining and enforcing a security policy ----------------------------------------@@ -84,6 +92,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_ENTER, }; Because we may not know which kernel version an application will be executed@@ -127,6 +138,12 @@ version, and only use the available subset of access rights: /* Removes LANDLOCK_SCOPE_* for ABI < 6 */ ruleset_attr.scoped &= ~(LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | LANDLOCK_SCOPE_SIGNAL); + __attribute__((fallthrough)); + case 6: + case 7: + case 8: + /* Removes permission support for ABI < 9 */ + ruleset_attr.handled_perm = 0; } This enables the creation of an inclusive ruleset that will contain our rules.@@ -191,6 +208,42 @@ number for a specific action: HTTPS connections. err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT, &net_port, 0); +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), + }; + + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_CAPABILITY, + &cap_attr, 0); + +For namespace access-control, we can add rules that allow entering specific +namespace types (creating them via :manpage:`unshare(2)` / :manpage:`clone(2)` +or joining them via :manpage:`setns(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_ENTER, + .namespace_types = CLONE_NEWUSER, + }; + + err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NAMESPACE, + &ns_attr, 0); + +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):@@ -354,10 +407,87 @@ 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)`. +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 +------------------------------------- + +See Documentation/security/landlock.rst for the design rationale behind +the permission model (``handled_perm``) and how it differs from access +rights (``handled_access_*``) and scopes (``scoped``). +When a process creates a user namespace, the kernel grants all capabilities +within that namespace. While these capabilities cannot directly bypass Landlock +restrictions (Landlock enforces access controls independently of capability +checks), they open kernel code paths that are normally unreachable to +unprivileged users and may contain exploitable bugs. + +Landlock provides two complementary permissions to address this. +``LANDLOCK_PERM_CAPABILITY_USE`` restricts which capabilities a process can use, +even when it holds them. ``LANDLOCK_PERM_NAMESPACE_ENTER`` restricts which +namespace types a process can create (via :manpage:`unshare(2)` or +:manpage:`clone(2)`) or join (via :manpage:`setns(2)`). After creating a user +namespace, the granted capabilities are scoped to namespaces owned by that user +namespace or its descendants; to exercise a capability such as +``CAP_NET_ADMIN``, the process must create a namespace of the corresponding type +(e.g., a network namespace). Configuring both permissions together provides +full coverage: ``LANDLOCK_PERM_CAPABILITY_USE`` restricts which capabilities are +available, while ``LANDLOCK_PERM_NAMESPACE_ENTER`` restricts the namespaces in +which they can be used.Documentation/userspace-api/landlock.rst The operations which can be scoped are: · line 447
Quoted 10 lines
Documentation/userspace-api/landlock.rst +10
-0+ +When a Landlock domain handles ``LANDLOCK_PERM_CAPABILITY_USE``, all Linux +:manpage:`capabilities(7)` are denied by default unless a rule explicitly allows +them. This is purely restrictive: Landlock can only deny capabilities that the +traditional capability mechanism would have allowed, never grant additional ones. +Rules are added with ``LANDLOCK_RULE_CAPABILITY`` using a +&struct landlock_capability_attr. Each rule specifies a set of ``CAP_*`` values +(as a bitmask) to allow. Capabilities above ``CAP_LAST_CAP`` are silently +accepted but have no effect since the kernel never checks them; this means new +capabilities introduced by future kernels are automatically denied.(See example above.)
Quoted 90 lines
Documentation/userspace-api/landlock.rst +61
-2+ +When a Landlock domain handles ``LANDLOCK_PERM_NAMESPACE_ENTER``, namespace +creation and entry are denied by default unless a rule explicitly allows them. +Rules are added with ``LANDLOCK_RULE_NAMESPACE`` using a +&struct landlock_namespace_attr. Each rule specifies a set of ``CLONE_NEW*`` +flags to allow. + +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_ENTER`` +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``. + +More generally, Landlock domains and user namespaces form independent +hierarchies: Landlock domains restrict what actions are allowed (each stacked +layer narrows the permitted set), while user namespaces restrict where +capabilities take effect (only within the process's own namespace and its +descendants). Landlock access controls are fully determined by the domain +configuration, regardless of the process's position in the user namespace +hierarchy. 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, :manpage:`execve(2)` of +binaries with file capabilities, or :manpage:`capset(2)`. In all cases, +:manpage:`capget(2)` will report the credential's capability sets, but any +denied capability will fail with ``EPERM`` when exercised. + Truncating files ----------------@@ -515,7 +645,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 ----------------------@@ -534,7 +664,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 -------------------@@ -685,6 +816,21 @@ enforce Landlock rulesets across all threads of the calling process using the ``LANDLOCK_RESTRICT_SELF_TSYNC`` flag passed to sys_landlock_restrict_self(). +Capability restriction (ABI < 9) +-------------------------------- + +Starting with the Landlock ABI version 9, 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 < 9) +------------------------------- + +Starting with the Landlock ABI version 9, it is possible to restrict +namespace creation (:manpage:`unshare(2)`, :manpage:`clone(2)`) and entry +(:manpage:`setns(2)`) with the new ``LANDLOCK_PERM_NAMESPACE_ENTER`` permission +flag and ``LANDLOCK_RULE_NAMESPACE`` rule type. + .. _kernel_support: Kernel supportSignature · 1 line
2.53.0
Günther Noack
reviewerRe: [RFC PATCH v1 11/11] landlock: Add documentation for capability and namespace restrictions
Quoted 142 lines · Mickaël Salaün
Quoted 132 lines · Günther Noack
Hello!
Quoted 95 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), namespace restriction (LANDLOCK_PERM_NAMESPACE_ENTERwithLANDLOCK_RULE_NAMESPACEcovering creation via unshare/clone and entry via setns), and the backward-compatible degradation pattern for ABI < 9. A table documents the per-namespace-type capability requirements for both creation and entry.The admin guide adds the new perm.namespace_enter and perm.capability_use audit blocker names with their object identification fields (
namespace_type,namespace_inum, 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]>--- Documentation/admin-guide/LSM/landlock.rst | 19 ++- Documentation/security/landlock.rst | 80 ++++++++++- Documentation/userspace-api/landlock.rst | 156 ++++++++++++++++++++- 3 files changed, 245 insertions(+), 10 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: March 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 9+): + - perm.namespace_enter - 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_inum`` 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_inum`` for namespace operations; + ``capability`` for capability use. AUDIT_LANDLOCK_DOMAINDocumentation/security/landlock.rst +4
-1@@ -7,7 +7,7 @@ Landlock LSM: kernel documentation ================================== :Author: Mickaël Salaün -:Date: September 2025 +:Date: March 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,@@ -89,6 +89,72 @@ this is required to keep access controls consistent over the whole system, and this avoids unattended bypasses through file descriptor passing (i.e. confused deputy attack). +Composability with user namespaces +---------------------------------- +Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 104
Quoted 10 lines
Documentation/security/landlock.rst +10
-0+Landlock domain-based scoping and the kernel's user namespace-based capability +scoping enforce isolation over independent hierarchies. 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 new +scoped features. + +Ruleset restriction models +--------------------------I have to second Justin, it's a good idea to introduce this explanation.
Quoted 21 lines
Documentation/security/landlock.rst +21
-0+ +Landlock provides three restriction models, each with different coverage +and compatibility properties. + +Access rights (``handled_access_*``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Access rights control **enumerated operations on kernel objects** +identified by a rule key (a file hierarchy or a network port). Each +``handled_access_*`` field declares a set of access rights that the +ruleset restricts. Multiple access rights share a single rule type. +Operations for which no access right exists yet remain uncontrolled; +new rights are added incrementally across ABI versions. + +Permissions (``handled_perm``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Permissions control **broad operations enforced at single kernel +chokepoints**, achieving complete deny-by-default coverage. Each +``LANDLOCK_PERM_*`` flag maps to its own rule type. When a ruleset +handles a permission, all instances of that operation are denied unlessQuoted 8 lines
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 128
Quoted 3 lines
Documentation/security/landlock.rst +3
-0+explicitly allowed by a rule. New kernel values (new ``CAP_*`` +capabilities, new ``CLONE_NEW*`` namespace types) are automatically +denied without any Landlock update.I find the terminology of "chokepoints" and "gateways" in this and the header documentation a bit vague; you could argue that opening a file for reading is also a chokepoint/gateway for using
read()later on; it's not immediately clear to me how that's delineated.
Quoted 2 lines
Yeah, I wanted to express something wider that a fine-grained access right. Any alternative words that would fit better?
I find it also difficult to explain. A "critical enforcement point", maybe?
Permissions control **permission checks at critical enforcement points**, independent of individual kernel objects. They guard critical features which are prerequisites for further access, such as entering namespaces and using capabilities, and do so in a deny-by-default manner (all namespace and capability types are denied without having to list these individually in the ruleset).
WDYT?
(FWIW, I also found the term "Policy Enforcement Point" on the web, but that seems to be an Enterprise Software term which probably has more specific meaning there; probably better to avoid that name.)
Quoted 22 lines
Quoted 5 lines
In my mind, the handled_* groups of access rights are usually defined by the "namespace" of the objects they are protecting, more than anything else:
handled_access_fs: file paths,handled_access_net:
struct sockaddr (which we only expose as "port" for now).Quoted 7 lines
To play the devil's advocate, a possible alternative would have been to introduce:
handled_access_nswith valuesLANDLOCK_ACCESS_NS_FOO_ENTER,LANDLOCK_ACCESS_NS_BAR_ENTER, etc. (and documenting somewhere that these are guaranteed to stay in sync; a static assert is enough to make sure they do).That was actually one of my initial version, but I couldn't find any meaning ful other access rights that would both be useful for the sandboxing use case and worth the implementation. At the end I concluded that we needed "ambiant" access rights for things that are not really tied to existing kernel objects, and to be able to fully express current and future properties, hence using non-Landlock UAPI (capabilities, namespace types...). The
handled_permname was the less ambiguous one I could find, which still make sense.
Quoted 5 lines
Another important property is that the permissions rules don't have access rights, only *one* permission bit which could be removed. I choose to keep it as a safeguard (for UAPI check) and to still be able to add new ones for such rule if one day we really find a useful use case. Anyway, it's basically free.
Yes, sounds fair. I also think these two points are the crucial ones here, namely (a) it's not specific to a kernel object, and (b) the deny-by-default property (you don't need to list out all the types in the ruleset to block them all). (My suggested rephrasing above talks about these too.)
Quoted 9 lines
Quoted 2 lines
handled_access_capswith valuesLANDLOCK_ACCESS_CAPS_USE_FOO,LANDLOCK_ACCESS_CAPS_USE_BAR, etc., also guaranteed to stay in sync.Genuine question: what would be these FOO and BAR? I couldn't find anything worth it. The idea is to have a simple interface. In fact, initially I didn't have these suffixes (i.e.
_USE,_ENTER), and they are not really needed, but these are also safeguards in the case we would need one, and the main motivation is to make the semantic clear to users (and more consistent with other Landlock access rights).
By "FOO" and "BAR" I meant to imply the different capabilities, e.g., LANDLOCK_ACCESS_CAP_USE_AUDIT_CONTROL, LANDLOCK_ACCESS_CAP_USE_AUDIT_READ, LANDLOCK_ACCESS_CAP_USE_AUDIT_WRITE, LANDLOCK_ACCESS_CAP_USE_BLOCK_SUSPEND, etc.
Quoted 12 lines
Quoted 3 lines
That way the blocked accesses would still be "operations", and we would not need to have rules for them because the "object" being protected are the processes within the Landlock domain, so to say.
I'm not sure to understand, but an (also) previous version was to just put the capability (and namespace type) bits directly in the ruleset struct. The issue with this approach is that it doesn't work well with a deny-by-default enforcement, and this would not be extensible, and this would not handle well compatibility (fields set to zero by default).
Quoted 1 line
Quoted 4 lines
Quoted 2 lines
Arguably, the LANDLOCK_ACCESS_FS_MAKE_* rights already follow a similar pattern.
Hmm, I'm not following.
What I meant is that these are "rolled out" in a similar way to my LANDLOCK_ACCESS_CAP_USE_... examples above, because they list the different file types in LANDLOCK_ACCESS_FS_MAKE_CHAR, ..._MAKE_DIR, ..._MAKE_REG, ..._MAKE_SOCK, etc.
Quoted 92 lines
Quoted 29 lines
To be clear, I am myself only 50% convinced whether the API would be better. The implementation would be easier (but that doesn't count much in comparison).
Documentation/security/landlock.rst this is required to keep access controls consistent over the whole system, and · line 140
Quoted 11 lines
Documentation/security/landlock.rst +11
-0+Each permission flag names a single gateway operation whose control +transitively covers an open-ended set of downstream operations: for +example, exercising a capability enables privileged operations across +many subsystems; entering a namespace enables gaining capabilities in a +new context. + +Permission rules identify what to allow using constants defined by other +kernel subsystems (``CAP_*``, ``CLONE_NEW*``). Unknown values are +silently ignored because deny-by-default ensures they are denied anyway. +In contrast, unknown ``LANDLOCK_PERM_*`` flags in ``handled_perm`` are +rejected (``-EINVAL``), since Landlock owns that namespace.OK I played through the compatibility scenarios which puzzled me in my reply to the cover letter, for both namespaces and capabilities. Namespaces are OK, so I'm just including that for completeness and for comparison, but I think the capabilities might be tricky?
Case A: Namespaces
In the scenario where a caller restricts
LANDLOCK_PERM_NAMESPACE_ENTER, but then adds a rule to allow a non-existent namespace number like 1<<63.Quoted 5 lines
Landlock ABI v9:
* The rule is accepted and the unknown value for the namespace type silently ignored
* It is not possible to enter the namespace because the namespace API doesn't exist for it. (But that's appropriate.)Yes, the namespace would just be unknown to the kernel, Landlock doesn't do anything here.
Quoted 4 lines
Landlock ABI
v_future(the namespace type 1<<63 exists now):
* The rule continues to be accepted.
* When trying to exercise the namespace type, it works.It works because the kernel now know about this namespace. Again, nothing related to Landlock specifically.
Quoted 13 lines
It seems that this scenario works fine. In the earlier version, entering the namespace already doesn't work because the kernel doesn't have support for it.
Case B: Capabilities
Whne new capabilities are introduced, I see that people have used the pattern where these capabilities are split off from operations which were previously controlled by
CAP_SYS_ADMIN. An example is commita17b53c4a4b5("bpf, capability: IntroduceCAP_BPF"), which states:Quoted 7 lines
Split BPF operations that are allowed under
CAP_SYS_ADMINinto combination ofCAP_BPF,CAP_PERFMON,CAP_NET_ADMIN. For backward compatibility include them inCAP_SYS_ADMINas well.(The same pattern was also used in the introduction of
CAP_CHECKPOINT_RESTOREandCAP_PERFMON.CAP_AUDIT_READis older and did it differently.)The key point here (and the architectural limitation) is that a new capability cannot completely replace an existing one. The original capability check will remain forever.
Quoted 21 lines
Let's say there is a
frobnicate()syscall guarded byCAP_SYS_ADMIN. A future kernel introducesCAP_FOOand then checks forfrobnicate()that either one ofCAP_FOOorCAP_SYS_ADMINare present.A caller creates a ruleset restricting capability use with Landlock, and adds a rule to allow
CAP_FOObut notCAP_SYS_ADMIN(e.g., ^CAP_SYS_ADMIN)Landlock ABI v9: (
CAP_FOOdoesn't exist)
* The rule forCAP_FOOis accepted and the unknown value for the capability silently ignored.
* The call tofrobnicate()fails because the use of the capability is forbiddenLandlock ABI v10: (
CAP_FOOstarts to exist)
* The rule continues to be accepted
* The call tofrobnicate()**succeeds now**, because the new kernel guards the operation by either one of those capabilities.
Quoted 8 lines
Quoted 3 lines
So... for capabilities, it seems to be slightly incompatible if users allow capabilities with a rule which are not known yet? The reason for that is the way how capabilities "fork off" from
CAP_SYS_ADMIN.The key point is that the compatibility is deferred to the other kernel subsystems. User space need to know which capabilities (or namespace types) are supported before using them. It's not a Landlock compatibility issue.
Fair enough, OK then. Paraphrasing, to make sure we are aligned: If you allow-list one of the newer capabilities through landlock_add_rule, and then run your program on a kernel where that capability doesn't exist yet, you can not expect that to work. Seems fair.
Quoted 10 lines
Quoted 5 lines
I mean, I can see that it's a pretty fringe scenario if users pass capabilities that don't exist yet, but it *is* strictly speaking an incompatibiliy. Should we check the range of the passed capabilities? Am I overlooking any downsides to this if we force users to stay between 0 and
CAP_LAST_CAP?Checking the range of known capabilities (or namespace types) could break the same Landlock rules on different kernels even if targeting the same Landlock ABI version, which would be much worse. I definitely prefer to have idempotent/deterministic Landlock rules.
Hm, good point. The list of supported capabilities can not be probed through the Landlock ABI number.
—Günther
Christian Brauner
maintainerQuoted 51 lines · Mickaël Salaün
Namespaces are a fundamental building block for containers and application sandboxes, but user namespace creation significantly widens the kernel attack surface. CVE-2022-0185 (filesystem mount parsing), CVE-2022-25636 and CVE-2023-32233 (netfilter), and CVE-2022-0492 (cgroup v1
release_agent) all demonstrate vulnerabilities exploitable only through capabilities gained via user namespaces. Some distributions 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_createLSM 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.
This series adds two new permission categories to Landlock:
-
LANDLOCK_PERM_NAMESPACE_ENTER: Restricts which namespace types a sandboxed process can acquire: both creation (unshare/clone) and entry (setns). User namespace creation has no capability check in the kernel, so this is the only enforcement mechanism for that entry point.-
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_permand 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). The Landlock ABI version is bumped from 8 to 9.The
handled_perminfrastructure 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.
Quoted 6 lines
This series builds on Christian Brauner's namespace LSM blob RFC [1], included as patch 1.
Christian, could you please review patch 3? It adds a
FOR_EACH_NS_TYPEX-macro tons_common_types.hand derivesCLONE_NS_ALL, replacing inline CLONE_NEW* flag enumerations innsproxy.candfork.c.
This all looks good to me, thanks! I'd really love to see this go in.
Hello!
Quoted 18 lines · Mickaël Salaün
Namespaces are a fundamental building block for containers and application sandboxes, but user namespace creation significantly widens the kernel attack surface. CVE-2022-0185 (filesystem mount parsing), CVE-2022-25636 and CVE-2023-32233 (netfilter), and CVE-2022-0492 (cgroup v1
release_agent) all demonstrate vulnerabilities exploitable only through capabilities gained via user namespaces. Some distributions 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_createLSM 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.
Quoted 6 lines
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.
I assume we are talking about an unrestricted systemd user session manager, which would not itself be restricted? (If the entire user session were running under Landlock, users couldn't change their passwords with "passwd" any more, because of the no_new_privs requirement.)
Quoted 11 lines
This series adds two new permission categories to Landlock:
-
LANDLOCK_PERM_NAMESPACE_ENTER: Restricts which namespace types a sandboxed process can acquire: both creation (unshare/clone) and entry (setns). User namespace creation has no capability check in the kernel, so this is the only enforcement mechanism for that entry point.-
LANDLOCK_PERM_CAPABILITY_USE: Restricts which Linux capabilities a sandboxed process can use, regardless of how they were obtained (including through user namespace creation).
Given that you already went through multiple iterations here, I fully expect that I am overlooking something here, but based on the explanation, it's not clear to me why the capability control is needed in addition to the namespace control, to reduce the kernel attack surface.
In my understanding the "attack surface" problem with user namespaces is that they allow unprivileged processes to gain CAP_SYS_ADMIN within that namespace, which unlocks access to code paths which were traditionally reserved for the (top level) root user.
But then, to prevent that from happening, it seems that restricting access to user namespace creation would be sufficient?
(Also, in some cases, I suspect it might be possible to break assumptions that more privileged processes make about filesystem layout if the user can change the mount layout. But that is not an issue with Landlock, as we forbid changes to mounts and also require no_new_privs.)
Quoted 5 lines
Both use new
handled_permand 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). The Landlock ABI version is bumped from 8 to 9.
Compatibility question:
For both permission categories, when they are "handled" in the ruleset, they default to denying *all* types of namespaces, and *all* types of capabilities.
This is different to the handled_access_* rights, where we are requiring users to explicitly list all restricted rights as "handled", because the full list of available operations might be a moving target.
Why is this not a problem for capabilities and for namespaces? Both the list of capabilities and the list of namespaces has been expanded in the past. What happens if a new capability or namespace is invented? If these are evolved, is that backwards compatible for the existing users of these Landlock permission categories?
Quoted 19 lines
The
handled_perminfrastructure 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.
Christian, could you please review patch 3? It adds a
FOR_EACH_NS_TYPEX-macro tons_common_types.hand derivesCLONE_NS_ALL, replacing inline CLONE_NEW* flag enumerations innsproxy.candfork.c.Paul, could you please review patch 2? It adds
LSM_AUDIT_DATA_NS, a new audit record type that logsnamespace_typeand inum for namespace-related LSM denials.
Quoted 7 lines
All four 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_ENTERprevents this by denying the user namespace (eliminating the capability grant) or the specific namespace type needed to exercise it.LANDLOCK_PERM_CAPABILITY_USEindependently prevents it by denying the required capability.
Here, it is also not clear to me why LANDLOCK_PERM_CAPABILITY_USE is needed in addition to LANDLOCK_PERM_NAMESPACE_ENTER.
Looking at capabilities(7), my understanding is that capabilities can only be acquired through:
(1) user namespaces (prevented with LANDLOCK_PERM_NAMESPACE_ENTER)
(2) execve (setuid or individual capabilities, prevented using PR_SET_NO_NEW_PRIVS)
...so if a process were to start out with no such capabilities, wouldn't that be enough to prevent it from gaining more? Am I overlooking another way through which these can be acquired?
The Landlock capability support adds a "filter" for the use of capabilities, but my understanding of the capability system was that it already *is* that filter. As long as we prevent the acquisition of new capabilities, shouldn't that be sufficient?
Quoted 108 lines
Namespace restriction is enforced at two hook sites:
namespace_alloc(unshare/clone) andnamespace_install(setns). Together, these ensure a process denied a namespace type cannot circumvent the restriction by entering a pre-existing namespace viasetns()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 bothCAP_SYS_ADMINto be allowed andCLONE_NEWNETto be allowed).Design evolution:
The first approach added
CAP_OPTflags tosecurity_capable()to distinguish namespace creation contexts. This was too invasive and would have required capability splitting (a dedicatedCAP_NAMESPACE) which does not help because theCAP_SYS_ADMINfallback 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. ASCOPE_NAMESPACEflag restrictedsetns()by the namespace creator's domain, likeSCOPE_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_ADMINexercisable.LANDLOCK_PERM_NAMESPACE_ENTERcontrols where capabilities are exercisable by restricting which namespace types can be acquired.LANDLOCK_PERM_CAPABILITY_USEcontrols 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 inhook_capable(). No scope flag is added in this series.Note that 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, which is optional. A dedicated mount access control type is left for future work [3].
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]Christian Brauner (1):
security: add LSM blob and hooks for namespacesMickaël Salaün (10):
security: AddLSM_AUDIT_DATA_NSfor namespace audit records
nsproxy: AddFOR_EACH_NS_TYPE()X-macro andCLONE_NS_ALL
landlock: Wrap per-layer access masks in structlayer_rights
landlock: Enforce namespace entry restrictions
landlock: Enforce capability restrictions selftests/landlock: Drain stale audit records on init selftests/landlock: Add namespace restriction tests selftests/landlock: Add capability restriction testssamples/landlock: Add capability and namespace restriction support
landlock: Add documentation for capability and namespace restrictionsDocumentation/admin-guide/LSM/landlock.rst | 19 +- Documentation/security/landlock.rst | 80 +- Documentation/userspace-api/landlock.rst | 156 +- 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 | 47 +- include/linux/security.h | 20 + include/uapi/linux/landlock.h | 89 +- kernel/fork.c | 7 +- kernel/nscommon.c | 12 + kernel/nsproxy.c | 21 +- samples/landlock/sandboxer.c | 164 +- security/landlock/Makefile | 2 + security/landlock/access.h | 72 +- security/landlock/audit.c | 8 + security/landlock/audit.h | 2 + security/landlock/cap.c | 142 ++ security/landlock/cap.h | 49 + security/landlock/cred.h | 47 +- security/landlock/limits.h | 9 + security/landlock/ns.c | 188 +++ security/landlock/ns.h | 74 + security/landlock/ruleset.c | 23 +- security/landlock/ruleset.h | 53 +- security/landlock/setup.c | 4 + security/landlock/syscalls.c | 124 +- security/lsm_audit.c | 4 + security/lsm_init.c | 2 + security/security.c | 76 + tools/testing/selftests/landlock/audit.h | 29 +- tools/testing/selftests/landlock/audit_test.c | 2 - tools/testing/selftests/landlock/base_test.c | 20 +- tools/testing/selftests/landlock/cap_test.c | 614 ++++++++ tools/testing/selftests/landlock/common.h | 23 + tools/testing/selftests/landlock/config | 5 + tools/testing/selftests/landlock/ns_test.c | 1379 +++++++++++++++++ tools/testing/selftests/landlock/wrappers.h | 6 + 38 files changed, 3487 insertions(+), 94 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
Quoted 4 lines
base-commit:
5dfb8077be2bbe2c3b9477da759e80fa9f98da42Signature · 1 line
2.53.0
FWIW, I have also skimmed through some of the code and documentation and the code seemed very clean so far.
–Günther
Mickaël Salaün
maintainerQuoted 28 lines · Günther Noack
Hello!
Quoted 18 lines · Mickaël Salaün
Namespaces are a fundamental building block for containers and application sandboxes, but user namespace creation significantly widens the kernel attack surface. CVE-2022-0185 (filesystem mount parsing), CVE-2022-25636 and CVE-2023-32233 (netfilter), and CVE-2022-0492 (cgroup v1
release_agent) all demonstrate vulnerabilities exploitable only through capabilities gained via user namespaces. Some distributions 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_createLSM 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.Quoted 6 lines
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.
Quoted 5 lines
I assume we are talking about an unrestricted systemd user session manager, which would not itself be restricted? (If the entire user session were running under Landlock, users couldn't change their passwords with "passwd" any more, because of the
no_new_privsrequirement.)
systemd can be use to create such session, as other init systems. If no_new_privs is set, commands such as passwd would indeed not work, but:
1. The process applying the Landlock restrictions (e.g. creating the user session) doesn't need to set no_new_privs if it has CAP_SYS_ADMIN in the current user namespace.
2. SUID programs can (and should probably) be replaced with proper client/server interfaces (i.e. for the client to not be privileged), see DBus services (e.g. Account) or homectl for instance.
Quoted 10 lines
Quoted 10 lines
This series adds two new permission categories to Landlock:
-
LANDLOCK_PERM_NAMESPACE_ENTER: Restricts which namespace types a sandboxed process can acquire: both creation (unshare/clone) and entry (setns). User namespace creation has no capability check in the kernel, so this is the only enforcement mechanism for that entry point.
Quoted 5 lines
Quoted 3 lines
-
LANDLOCK_PERM_CAPABILITY_USE: Restricts which Linux capabilities a sandboxed process can use, regardless of how they were obtained (including through user namespace creation).Given that you already went through multiple iterations here, I fully
It's the first public one, but it's well advanced.
Quoted 9 lines
expect that I am overlooking something here, but based on the explanation, it's not clear to me why the capability control is needed in addition to the namespace control, to reduce the kernel attack surface.
In my understanding the "attack surface" problem with user namespaces is that they allow unprivileged processes to gain
CAP_SYS_ADMINwithin that namespace, which unlocks access to code paths which were traditionally reserved for the (top level) root user.
This capability and others.
Quoted 3 lines
But then, to prevent that from happening, it seems that restricting access to user namespace creation would be sufficient?
It would be sufficient to limit the kernel attack surface, but it would make all the related features unusable. As explained in this cover letter, there are already several ways to block everything, but this doesn't help for a lot of use cases and this Landlock feature proposes a new fine-grained and unprivileged way to properly restrict some capabilities.
Quoted 25 lines
(Also, in some cases, I suspect it might be possible to break assumptions that more privileged processes make about filesystem layout if the user can change the mount layout. But that is not an issue with Landlock, as we forbid changes to mounts and also require
no_new_privs.)Quoted 5 lines
Both use new
handled_permand 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). The Landlock ABI version is bumped from 8 to 9.Compatibility question:
For both permission categories, when they are "handled" in the ruleset, they default to denying *all* types of namespaces, and *all* types of capabilities.
This is different to the handled_access_* rights, where we are requiring users to explicitly list all restricted rights as "handled", because the full list of available operations might be a moving target.
Quoted 5 lines
Why is this not a problem for capabilities and for namespaces? Both the list of capabilities and the list of namespaces has been expanded in the past. What happens if a new capability or namespace is invented? If these are evolved, is that backwards compatible for the existing users of these Landlock permission categories?
This question is answered is the documentation (and the commit messages), and that's the main difference between handled_access_* and handled_perm. In a nutshell, the permission rules uses non-Landlock bits that naturally evolve without any Landlock-specific changes.
Quoted 9 lines
Quoted 9 lines
The
handled_perminfrastructure 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.
See here ^
Quoted 20 lines
Quoted 12 lines
This series builds on Christian Brauner's namespace LSM blob RFC [1], included as patch 1.
Christian, could you please review patch 3? It adds a
FOR_EACH_NS_TYPEX-macro tons_common_types.hand derivesCLONE_NS_ALL, replacing inline CLONE_NEW* flag enumerations innsproxy.candfork.c.Paul, could you please review patch 2? It adds
LSM_AUDIT_DATA_NS, a new audit record type that logsnamespace_typeand inum for namespace-related LSM denials.Quoted 7 lines
All four 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_ENTERprevents this by denying the user namespace (eliminating the capability grant) or the specific namespace type needed to exercise it.LANDLOCK_PERM_CAPABILITY_USEindependently prevents it by denying the required capability.
Quoted 2 lines
Here, it is also not clear to me why
LANDLOCK_PERM_CAPABILITY_USEis needed in addition toLANDLOCK_PERM_NAMESPACE_ENTER.
This is also explained in the documentation.
Quoted 8 lines
Looking at capabilities(7), my understanding is that capabilities can only be acquired through:
(1) user namespaces (prevented with
LANDLOCK_PERM_NAMESPACE_ENTER)
(2) execve (setuid or individual capabilities, prevented usingPR_SET_NO_NEW_PRIVS)
Quoted 8 lines
...so if a process were to start out with no such capabilities, wouldn't that be enough to prevent it from gaining more? Am I overlooking another way through which these can be acquired?
The Landlock capability support adds a "filter" for the use of capabilities, but my understanding of the capability system was that it already *is* that filter. As long as we prevent the acquisition of new capabilities, shouldn't that be sufficient?
In a nutshell, capabilities applies to namespaces (and their type), so it makes sense to be able to control them together, see the chroot example. Please take a look at the documentation.
Quoted 120 lines
Quoted 110 lines
Namespace restriction is enforced at two hook sites:
namespace_alloc(unshare/clone) andnamespace_install(setns). Together, these ensure a process denied a namespace type cannot circumvent the restriction by entering a pre-existing namespace viasetns()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 bothCAP_SYS_ADMINto be allowed andCLONE_NEWNETto be allowed).Design evolution:
The first approach added
CAP_OPTflags tosecurity_capable()to distinguish namespace creation contexts. This was too invasive and would have required capability splitting (a dedicatedCAP_NAMESPACE) which does not help because theCAP_SYS_ADMINfallback 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. ASCOPE_NAMESPACEflag restrictedsetns()by the namespace creator's domain, likeSCOPE_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_ADMINexercisable.LANDLOCK_PERM_NAMESPACE_ENTERcontrols where capabilities are exercisable by restricting which namespace types can be acquired.LANDLOCK_PERM_CAPABILITY_USEcontrols 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 inhook_capable(). No scope flag is added in this series.Note that 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, which is optional. A dedicated mount access control type is left for future work [3].
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]Christian Brauner (1):
security: add LSM blob and hooks for namespacesMickaël Salaün (10):
security: AddLSM_AUDIT_DATA_NSfor namespace audit records
nsproxy: AddFOR_EACH_NS_TYPE()X-macro andCLONE_NS_ALL
landlock: Wrap per-layer access masks in structlayer_rights
landlock: Enforce namespace entry restrictions
landlock: Enforce capability restrictions selftests/landlock: Drain stale audit records on init selftests/landlock: Add namespace restriction tests selftests/landlock: Add capability restriction testssamples/landlock: Add capability and namespace restriction support
landlock: Add documentation for capability and namespace restrictionsDocumentation/admin-guide/LSM/landlock.rst | 19 +- Documentation/security/landlock.rst | 80 +- Documentation/userspace-api/landlock.rst | 156 +- 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 | 47 +- include/linux/security.h | 20 + include/uapi/linux/landlock.h | 89 +- kernel/fork.c | 7 +- kernel/nscommon.c | 12 + kernel/nsproxy.c | 21 +- samples/landlock/sandboxer.c | 164 +- security/landlock/Makefile | 2 + security/landlock/access.h | 72 +- security/landlock/audit.c | 8 + security/landlock/audit.h | 2 + security/landlock/cap.c | 142 ++ security/landlock/cap.h | 49 + security/landlock/cred.h | 47 +- security/landlock/limits.h | 9 + security/landlock/ns.c | 188 +++ security/landlock/ns.h | 74 + security/landlock/ruleset.c | 23 +- security/landlock/ruleset.h | 53 +- security/landlock/setup.c | 4 + security/landlock/syscalls.c | 124 +- security/lsm_audit.c | 4 + security/lsm_init.c | 2 + security/security.c | 76 + tools/testing/selftests/landlock/audit.h | 29 +- tools/testing/selftests/landlock/audit_test.c | 2 - tools/testing/selftests/landlock/base_test.c | 20 +- tools/testing/selftests/landlock/cap_test.c | 614 ++++++++ tools/testing/selftests/landlock/common.h | 23 + tools/testing/selftests/landlock/config | 5 + tools/testing/selftests/landlock/ns_test.c | 1379 +++++++++++++++++ tools/testing/selftests/landlock/wrappers.h | 6 + 38 files changed, 3487 insertions(+), 94 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.cQuoted 4 lines
base-commit:
5dfb8077be2bbe2c3b9477da759e80fa9f98da42Signature · 1 line
2.53.0FWIW, I have also skimmed through some of the code and documentation and the code seemed very clean so far.
–Günther
Quoted 35 lines · Mickaël Salaün
Quoted 28 lines · Günther Noack
Hello!
Quoted 18 lines · Mickaël Salaün
Namespaces are a fundamental building block for containers and application sandboxes, but user namespace creation significantly widens the kernel attack surface. CVE-2022-0185 (filesystem mount parsing), CVE-2022-25636 and CVE-2023-32233 (netfilter), and CVE-2022-0492 (cgroup v1
release_agent) all demonstrate vulnerabilities exploitable only through capabilities gained via user namespaces. Some distributions 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_createLSM 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.Quoted 6 lines
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.
Quoted 5 lines
I assume we are talking about an unrestricted systemd user session manager, which would not itself be restricted? (If the entire user session were running under Landlock, users couldn't change their passwords with "passwd" any more, because of the
no_new_privsrequirement.)
Quoted 9 lines
systemd can be use to create such session, as other init systems. If
no_new_privsis set, commands such as passwd would indeed not work, but:
1. The process applying the Landlock restrictions (e.g. creating the user session) doesn't need to setno_new_privsif it hasCAP_SYS_ADMINin the current user namespace.
2. SUID programs can (and should probably) be replaced with proper client/server interfaces (i.e. for the client to not be privileged), see DBus services (e.g. Account) or homectl for instance.
I also think services are a better approach than the suid bit, but that's to my knowledge not the state of affairs yet (until Lennart makes it happen, hint hint ;-)).
Quoted 70 lines
Quoted 8 lines
Quoted 8 lines
This series adds two new permission categories to Landlock:
-
LANDLOCK_PERM_NAMESPACE_ENTER: Restricts which namespace types a sandboxed process can acquire: both creation (unshare/clone) and entry (setns). User namespace creation has no capability check in the kernel, so this is the only enforcement mechanism for that entry point.Quoted 5 lines
Quoted 3 lines
-
LANDLOCK_PERM_CAPABILITY_USE: Restricts which Linux capabilities a sandboxed process can use, regardless of how they were obtained (including through user namespace creation).Given that you already went through multiple iterations here, I fully
It's the first public one, but it's well advanced.
Quoted 9 lines
expect that I am overlooking something here, but based on the explanation, it's not clear to me why the capability control is needed in addition to the namespace control, to reduce the kernel attack surface.
In my understanding the "attack surface" problem with user namespaces is that they allow unprivileged processes to gain
CAP_SYS_ADMINwithin that namespace, which unlocks access to code paths which were traditionally reserved for the (top level) root user.This capability and others.
Quoted 3 lines
But then, to prevent that from happening, it seems that restricting access to user namespace creation would be sufficient?
It would be sufficient to limit the kernel attack surface, but it would make all the related features unusable. As explained in this cover letter, there are already several ways to block everything, but this doesn't help for a lot of use cases and this Landlock feature proposes a new fine-grained and unprivileged way to properly restrict some capabilities.
Quoted 25 lines
(Also, in some cases, I suspect it might be possible to break assumptions that more privileged processes make about filesystem layout if the user can change the mount layout. But that is not an issue with Landlock, as we forbid changes to mounts and also require
no_new_privs.)Quoted 5 lines
Both use new
handled_permand 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). The Landlock ABI version is bumped from 8 to 9.Compatibility question:
For both permission categories, when they are "handled" in the ruleset, they default to denying *all* types of namespaces, and *all* types of capabilities.
This is different to the handled_access_* rights, where we are requiring users to explicitly list all restricted rights as "handled", because the full list of available operations might be a moving target.
Quoted 5 lines
Why is this not a problem for capabilities and for namespaces? Both the list of capabilities and the list of namespaces has been expanded in the past. What happens if a new capability or namespace is invented? If these are evolved, is that backwards compatible for the existing users of these Landlock permission categories?
Quoted 4 lines
This question is answered is the documentation (and the commit messages), and that's the main difference between handled_access_* and
handled_perm. In a nutshell, the permission rules uses non-Landlock bits that naturally evolve without any Landlock-specific changes.
I think the deny-by-default is fine given that these namespaces and capabilities do not exist yet. It is the case where users add a rule and we silently ignore unknown bits in the bitfield, which I think introduces a small problem. I responded to the documentation commit with what I believe is a counterexample for the capabilities case. (Let's discuss it on the documentation patch in the context of the examples.)
Quoted 46 lines
Quoted 7 lines
Quoted 7 lines
The
handled_perminfrastructure 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.See here ^
Quoted 20 lines
Quoted 12 lines
This series builds on Christian Brauner's namespace LSM blob RFC [1], included as patch 1.
Christian, could you please review patch 3? It adds a
FOR_EACH_NS_TYPEX-macro tons_common_types.hand derivesCLONE_NS_ALL, replacing inline CLONE_NEW* flag enumerations innsproxy.candfork.c.Paul, could you please review patch 2? It adds
LSM_AUDIT_DATA_NS, a new audit record type that logsnamespace_typeand inum for namespace-related LSM denials.Quoted 7 lines
All four 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_ENTERprevents this by denying the user namespace (eliminating the capability grant) or the specific namespace type needed to exercise it.LANDLOCK_PERM_CAPABILITY_USEindependently prevents it by denying the required capability.Quoted 2 lines
Here, it is also not clear to me why
LANDLOCK_PERM_CAPABILITY_USEis needed in addition toLANDLOCK_PERM_NAMESPACE_ENTER.This is also explained in the documentation.
Quoted 11 lines
Looking at capabilities(7), my understanding is that capabilities can only be acquired through:
(1) user namespaces (prevented with
LANDLOCK_PERM_NAMESPACE_ENTER)
(2) execve (setuid or individual capabilities, prevented usingPR_SET_NO_NEW_PRIVS)...so if a process were to start out with no such capabilities, wouldn't that be enough to prevent it from gaining more? Am I overlooking another way through which these can be acquired?
Quoted 8 lines
Quoted 4 lines
The Landlock capability support adds a "filter" for the use of capabilities, but my understanding of the capability system was that it already *is* that filter. As long as we prevent the acquisition of new capabilities, shouldn't that be sufficient?
In a nutshell, capabilities applies to namespaces (and their type), so it makes sense to be able to control them together, see the chroot example. Please take a look at the documentation.
I had a hard time puzzling it together in the documentation, but the chroot example helped.
So, if I am understanding correctly, the idea is that you need it in order to create a new user namespace, but the restrict the use of capabilities within that user namespace (not only CAP_SYS_ADMIN, but also more individual ones). Sounds reasonable.
I can also see that in order to do that without the Landlock capability support, the first process within the new namespace would immediately need to drop capabilities, and that may be outside of the control of the person defining the Landlock policy..?
–Günther
Mickaël Salaün
maintainerQuoted 190 lines · Günther Noack
Quoted 35 lines · Mickaël Salaün
Quoted 28 lines · Günther Noack
Hello!
Quoted 18 lines · Mickaël Salaün
Namespaces are a fundamental building block for containers and application sandboxes, but user namespace creation significantly widens the kernel attack surface. CVE-2022-0185 (filesystem mount parsing), CVE-2022-25636 and CVE-2023-32233 (netfilter), and CVE-2022-0492 (cgroup v1
release_agent) all demonstrate vulnerabilities exploitable only through capabilities gained via user namespaces. Some distributions 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_createLSM 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.Quoted 6 lines
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.
Quoted 5 lines
I assume we are talking about an unrestricted systemd user session manager, which would not itself be restricted? (If the entire user session were running under Landlock, users couldn't change their passwords with "passwd" any more, because of the
no_new_privsrequirement.)Quoted 9 lines
systemd can be use to create such session, as other init systems. If
no_new_privsis set, commands such as passwd would indeed not work, but:
1. The process applying the Landlock restrictions (e.g. creating the user session) doesn't need to setno_new_privsif it hasCAP_SYS_ADMINin the current user namespace.
2. SUID programs can (and should probably) be replaced with proper client/server interfaces (i.e. for the client to not be privileged), see DBus services (e.g. Account) or homectl for instance.I also think services are a better approach than the suid bit, but that's to my knowledge not the state of affairs yet (until Lennart makes it happen, hint hint ;-)).
Quoted 70 lines
Quoted 8 lines
Quoted 8 lines
This series adds two new permission categories to Landlock:
-
LANDLOCK_PERM_NAMESPACE_ENTER: Restricts which namespace types a sandboxed process can acquire: both creation (unshare/clone) and entry (setns). User namespace creation has no capability check in the kernel, so this is the only enforcement mechanism for that entry point.Quoted 5 lines
Quoted 3 lines
-
LANDLOCK_PERM_CAPABILITY_USE: Restricts which Linux capabilities a sandboxed process can use, regardless of how they were obtained (including through user namespace creation).Given that you already went through multiple iterations here, I fully
It's the first public one, but it's well advanced.
Quoted 9 lines
expect that I am overlooking something here, but based on the explanation, it's not clear to me why the capability control is needed in addition to the namespace control, to reduce the kernel attack surface.
In my understanding the "attack surface" problem with user namespaces is that they allow unprivileged processes to gain
CAP_SYS_ADMINwithin that namespace, which unlocks access to code paths which were traditionally reserved for the (top level) root user.This capability and others.
Quoted 3 lines
But then, to prevent that from happening, it seems that restricting access to user namespace creation would be sufficient?
It would be sufficient to limit the kernel attack surface, but it would make all the related features unusable. As explained in this cover letter, there are already several ways to block everything, but this doesn't help for a lot of use cases and this Landlock feature proposes a new fine-grained and unprivileged way to properly restrict some capabilities.
Quoted 25 lines
(Also, in some cases, I suspect it might be possible to break assumptions that more privileged processes make about filesystem layout if the user can change the mount layout. But that is not an issue with Landlock, as we forbid changes to mounts and also require
no_new_privs.)Quoted 5 lines
Both use new
handled_permand 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). The Landlock ABI version is bumped from 8 to 9.Compatibility question:
For both permission categories, when they are "handled" in the ruleset, they default to denying *all* types of namespaces, and *all* types of capabilities.
This is different to the handled_access_* rights, where we are requiring users to explicitly list all restricted rights as "handled", because the full list of available operations might be a moving target.
Quoted 5 lines
Why is this not a problem for capabilities and for namespaces? Both the list of capabilities and the list of namespaces has been expanded in the past. What happens if a new capability or namespace is invented? If these are evolved, is that backwards compatible for the existing users of these Landlock permission categories?
Quoted 4 lines
This question is answered is the documentation (and the commit messages), and that's the main difference between handled_access_* and
handled_perm. In a nutshell, the permission rules uses non-Landlock bits that naturally evolve without any Landlock-specific changes.I think the deny-by-default is fine given that these namespaces and capabilities do not exist yet. It is the case where users add a rule and we silently ignore unknown bits in the bitfield, which I think introduces a small problem. I responded to the documentation commit with what I believe is a counterexample for the capabilities case. (Let's discuss it on the documentation patch in the context of the examples.)
Quoted 46 lines
Quoted 7 lines
Quoted 7 lines
The
handled_perminfrastructure 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.See here ^
Quoted 20 lines
Quoted 12 lines
This series builds on Christian Brauner's namespace LSM blob RFC [1], included as patch 1.
Christian, could you please review patch 3? It adds a
FOR_EACH_NS_TYPEX-macro tons_common_types.hand derivesCLONE_NS_ALL, replacing inline CLONE_NEW* flag enumerations innsproxy.candfork.c.Paul, could you please review patch 2? It adds
LSM_AUDIT_DATA_NS, a new audit record type that logsnamespace_typeand inum for namespace-related LSM denials.Quoted 7 lines
All four 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_ENTERprevents this by denying the user namespace (eliminating the capability grant) or the specific namespace type needed to exercise it.LANDLOCK_PERM_CAPABILITY_USEindependently prevents it by denying the required capability.Quoted 2 lines
Here, it is also not clear to me why
LANDLOCK_PERM_CAPABILITY_USEis needed in addition toLANDLOCK_PERM_NAMESPACE_ENTER.This is also explained in the documentation.
Quoted 11 lines
Looking at capabilities(7), my understanding is that capabilities can only be acquired through:
(1) user namespaces (prevented with
LANDLOCK_PERM_NAMESPACE_ENTER)
(2) execve (setuid or individual capabilities, prevented usingPR_SET_NO_NEW_PRIVS)...so if a process were to start out with no such capabilities, wouldn't that be enough to prevent it from gaining more? Am I overlooking another way through which these can be acquired?
Quoted 8 lines
Quoted 4 lines
The Landlock capability support adds a "filter" for the use of capabilities, but my understanding of the capability system was that it already *is* that filter. As long as we prevent the acquisition of new capabilities, shouldn't that be sufficient?
In a nutshell, capabilities applies to namespaces (and their type), so it makes sense to be able to control them together, see the chroot example. Please take a look at the documentation.
Quoted 5 lines
I had a hard time puzzling it together in the documentation, but the chroot example helped.
So, if I am understanding correctly, the idea is that you need it in order to create a new user namespace,
The user namespace is the only namespace that doesn't require a capability, but all others need at least one (which can be gained with a user namespace).
Quoted 3 lines
but the restrict the use of
capabilities within that user namespace (not onlyCAP_SYS_ADMIN, but also more individual ones). Sounds reasonable.
That enables us to restrict the use of capabilities (within a user namespace or not), and then, because capabilities applies to a namespace hierarchy, to restrict some operations too. The limitation lies in the split of capabilities (e.g. CAP_SYS_ADMIN is needed to create most namespaces), but we cannot do anything about that (because of compatibility). We can only hope that new capabilities will be introduced to improve the situation.
Quoted 5 lines
I can also see that in order to do that without the Landlock capability support, the first process within the new namespace would immediately need to drop capabilities, and that may be outside of the control of the person defining the Landlock policy..?
Right, dropping capabilities doesn't make sense for a (sandboxed) attacker able to create a user namespace.