Landlock: Namespace and capability control
Subsystems (6)
Mickaël Salaün
maintainerv4 cover Landlock: Namespace and capability control
Hi,
This series adds composable Landlock controls for namespace types and Linux capabilities. It is based on v7.3-rc5 plus the merged LSM prerequisites, ending at c0a3be0adcce971e28de1c3baeeac472fe97fcaf.
The first three patches from v3 are now merged as commits 4f238e6e1c2c ("ns: Free anonymous mount namespaces via ns_common_free()"), f675d2e95569 ("lsm: add LSM blob and hooks for namespaces"), and e26307d83048 ("lsm: add LSM_AUDIT_DATA_NS for namespace audit records") in lsm/dev (and landlock/next), so they are not resent. The updated base also includes commit 11d73af7b083 ("lsm: update the BUILD_BUG_ON() in audit_log_lsm_data()"), which makes the audit-data size bound architecture-independent. The old quiet-mask copy patch is also dropped: the ruleset snapshot and create-domain tracepoint already run under the same ruleset lock, and the shared layer refactoring now provides complete locked assignments. The resulting v4 series contains eight patches.
Tingmao's Reviewed-by tag is not carried on the namespace and capability enforcement patches, which now fold in the new trace events and ABI 12, so a fresh review of those two is welcome.
Motivation
==========
Namespaces are a fundamental building block for containers and application sandboxes, but user namespace creation significantly widens the kernel attack surface. CVE-2026-43284 / CVE-2026-43500 ("Dirty Frag"), CVE-2026-46300 ("Fragnesia"), CVE-2023-32233 and CVE-2022-25636 (netfilter), CVE-2022-0492 (cgroup v1 release_agent), and CVE-2022-0185 (filesystem mount parsing) all demonstrate vulnerabilities reachable through capabilities gained via user namespaces. Advisories for the 2026 CVEs recommend disabling unprivileged user-namespace creation as a temporary mitigation. Some distributions, including Debian and Arch's linux-hardened kernel through kernel.unprivileged_userns_clone, block it entirely, but this removes a useful isolation primitive. Fine-grained, per-process restrictions can retain that isolation while reducing unnecessary kernel exposure.
Existing mechanisms (user.max_*_namespaces, userns_create, PR_SET_NO_NEW_PRIVS, capability sets, and seccomp) each address only part of this threat. In particular, seccomp cannot dereference clone3()'s flag structure and is not composable across independently stacked policies. Landlock layers let a session manager or container runtime set broad limits while allowing each descendant to add stricter ones.
Permissions and enforcement
===========================
The series introduces two independent, deny-by-default permissions with Landlock ABI 12:
- LANDLOCK_PERMISSION_NAMESPACE_USE controls which CLONE_NEW* namespace types a process may acquire. security_namespace_init() covers creation through clone(2), clone3(2), unshare(2), open_tree(2) and fsmount(2); security_namespace_install() covers entry through setns(2).
- LANDLOCK_PERMISSION_CAPABILITY_USE controls which CAP_* capabilities a process may exercise, independently of the target user namespace and regardless of how those capabilities were acquired, including through a new user namespace or a privileged exec.
The permissions are separate because they are enforced at independent LSM hooks and address independent axes: acquiring access to a namespace and exercising a capability. If a domain handles both, both must allow an operation: creating a network namespace needs a namespace rule allowing CLONE_NEWNET and, because the kernel checks it, a capability rule allowing CAP_SYS_ADMIN. User namespace creation has no capability check, so the namespace permission alone controls that path.
handled_permissions selects the permission types, and the capability and namespace rule attributes carry raw CAP_* and CLONE_NEW* values. Unknown member values are accepted and ignored for forward compatibility; deny-by-default behavior remains unchanged. Every successful permission-rule call advances the ruleset version and emits an add-rule trace event, including repeated and unknown-only effective no-ops, so tracing preserves the syscall history.
Each rule can independently mark specific denied members quiet with quiet_capabilities or quiet_namespace_types. Quiet members remain denied and visible to tracing with logged=0; only audit submission is suppressed.
Implementation
==============
The first two patches prepare a shared per-layer representation:quiet_masks becomes quiet_access, then each ruleset/domain layer is represented by struct layer_config. The namespace patch adds the shared permission infrastructure and the capability patch fills the second permission dimension. struct permission_masks remains one forced 8-byte value containing 8 namespace bits and 41 capability bits on this base; struct layer_config is 16 bytes. Allowed and quiet masks are snapshotted under the ruleset lock.
Namespace and capability denials use the common Landlock logging path. Audit submission honors quiet masks, while denial tracepoints remain visible. The capability hook performs a fast applicability check followed by a flat per-layer bitmask walk; the namespace hooks use the same permission walker.
The sample adds LL_CAP, LL_CAP_QUIET, LL_NS and LL_NS_QUIET, and now requires the libcap development headers and library. Empty capability or namespace lists keep their intentional fail-closed meaning; absent lists leave the permission unhandled.
Limitations and future work
===========================
When Landlock filesystem restrictions are active, every mount-topology change is denied if any filesystem right is handled. Namespace-use control does not lift that existing limitation; a dedicated mount access-control type remains future work [1].
[1] https://github.com/landlock-lsm/linux/issues/14
Changelog
=========
Changes since v3:
https://patch.msgid.link/[email protected]
- Rebase onto v7.3-rc5 plus the merged LSM prerequisites, including the architecture-independent audit-data size bound, ending
at c0a3be0adcce.
- Assign the namespace and capability permissions to ABI 12.
- Spell out perm as permission across the UAPI, the internals, the trace fields, the tests, the sample, and the documentation, and name the audit blockers namespace.use and capability.use after their domains.
- Adapt the internal split to ruleset->layer and domain->layers[], using complete struct layer_config snapshots for handled and allowed masks.
- Add handled_permissions plus namespace/capability rule and denial trace events. Successful permission rules, including effective no-ops, advance the version; audit-suppressed denials remain trace-visible.
- Gate the sample's new permission rules on ABI 12; consume unsupported settings, reject capability numbers that cannot fit in the UAPI's 64-bit mask, and document the complete policy and its libcap dependency.
- Refresh permission, audit, trace, and permission-rule error documentation; make target-user-namespace independence explicit; and regenerate the basic trace example.
- Add trace and audit selftests for raw namespace values and IDs, permission-rule versions, rejected and repeated calls, ordinary and quiet denials, unrecorded CAP_OPT_NOAUDIT probes, target-user-namespace independence, allow/quiet overlap, youngest-denier selection, and invalid rule pointers; suppress expected namespace and capability conversion warnings, fix the clone3 assertion, isolate hostname changes in private UTS namespaces, and drop CAP_AUDIT_CONTROL after fixture cleanup.
- Drop v3 patches 1-3 because their equivalents are merged.
- Drop Tingmao Wang's Reviewed-by from the namespace and capability enforcement patches, which now fold in the new trace events and ABI 12.
- Drop v3 patch 6 because ruleset->lock already serialized the ruleset snapshot and trace emission.
Changes since v2:
https://patch.msgid.link/[email protected]
- Rebased onto v7.2-rc4, which now ships ABI 10 (UDP support and the
merged quiet feature) and the series' dependencies; the new
permissions therefore bump the Landlock ABI to 11, and handled_perm
is placed after the released quiet_access_*/quiet_scoped fields.
- Added per-member quiet support for the capability and namespace permissions to their enforcement patches (patches 7 and 8): each rule carries independent allowed and quiet member bitmasks
(quiet_capabilities / quiet_namespace_types). The capability and namespace rule attributes are renamed accordingly (perm plus allowed_* plus quiet_*) and grow to 24 bytes.
- Extended the namespace and capability selftests (patches 9 and 10)
for the rebase and the per-member quiet feature: renamed the rule attributes (perm plus allowed_*/quiet_*), bumped the ABI expectation
to 11, and added per-member quiet audit tests (quiet-only denial, per-member quiet, allow-and-quiet, quiet-inert-when-also-allowed, youngest-layer-wins, parent-only-denying). Added further coverage: a positive both-caps mount setns leg and a both-perms inverse test, an install-hook mirror
of the unknown-bit no-runtime-effect test, quieted-setns and unknown-quiet-bit audit cases, positive controls proving quiet and CAP_OPT_NOAUDIT suppression are per-member (not global), an
assertion that a quieted capability is still denied, and a combined-unshare pair proving CLONE_NEWUSER combined with another
type in one unshare(2) still needs an allowed CAP_SYS_ADMIN.
- Dropped the Reviewed-by tags from Günther Noack and Tingmao Wang on patches 7 and 8: those tags covered the v1 patches, which did not
carry the per-member quiet support folded in here; a fresh review of
the quiet additions is welcome.
- Removed the RCU note from the security_namespace_free() kdoc
(patch 2, suggested by Paul Moore).
- Documentation: fixed the CAP_BPF forward-compatibility example (rules allow-list), dropped the "category" jargon, added capabilities(7) / namespaces(7) references, and clarified the namespace "use" semantics (suggested by Günther Noack); also documented the combined deny-by-default, that creating a non-user namespace needs
CAP_SYS_ADMIN even when CLONE_NEWUSER is combined in one unshare(),
and the per-member audit quieting for the two permissions.
- Sandboxer (patch 11): added LL_CAP_QUIET and LL_NS_QUIET to quiet capability and namespace-type denials, merged with the allowed bits
into one rule per category.
- New patch 1 ("ns: Free anonymous mount namespaces via
ns_common_free()"): the anonymous-mount free-path change is split out
of the LSM hooks patch, with a commit message explaining the
inum-range check (suggested by Christian Brauner and Paul Moore).
- New patches 4 and 6 ("landlock: Rename quiet_masks to quiet_access"
and "landlock: Copy the quiet mask in the ruleset merge helper"):
rename the base's quiet-mask field for symmetry with the new
quiet_perm, and copy both quiet masks inside merge_ruleset() under the ruleset lock so a new domain captures a single atomic snapshot of the ruleset (allowed plus quiet); no user-visible change.
Changes since RFC v1:
https://patch.msgid.link/[email protected]
- Move security_namespace_install() before ns->ops->install() in validate_ns() and fix proc_free_inum() error path when inum is caller-provided (patch 1, suggested by Christian Brauner).
- Replace inum with ns_id in namespace audit records: ns_id is the stable 64-bit namespace identifier, never recycled (patches 2, 4, 6, 9; suggested by Christian Brauner).
- Fix user_denied.setns test to expect EPERM from Landlock instead of EINVAL from userns_install() after hook reordering (patch 6).
- Add __packed __aligned(sizeof(u64)) to struct perm_masks to fix m68k build failure where GCC packs bitfields at byte granularity, and add WARN_ON_ONCE guards for invalid perm_bit or request_value in landlock_perm_is_denied() (patch 4, suggested by Tingmao Wang).
- Fix anonymous mount namespace blob leak: make __ns_common_free() always call security_namespace_free() and conditionally call proc_free_inum() via MNT_NS_INO_SPECIAL_MAX, so free_mnt_ns() calls ns_common_free() unconditionally (patch 1, suggested by Christian Brauner, also reported by Daniel Durning).
- Unify hook_namespace_init() and hook_namespace_install() into a shared check_ns_type() helper and drop the redundant entry-level WARN_ON_ONCE (the downstream warns in landlock_ns_type_to_bit() and landlock_perm_is_denied() suffice; patch 4).
- Remove duplicate ns_audit.unshare_denied test (identical to ns_audit.create_denied; patch 6).
- Add sandboxed_allowed variant to setns_cross_process to cover allowed cross-process setns (patch 6).
- Rebase onto landlock/next (includes the resolve_unix and UDP series). No ABI bump in v2: the series is planned to merge in the same kernel as the UDP series, which already bumped to 10.
- Drop three patches now upstream on landlock/next: the two audit-test fixes (filter dealloc records, default audit socket timeout) sent independently with Cc: stable, plus the allowed_access best-effort filtering demonstration patch.
- Rename LANDLOCK_PERM_NAMESPACE_ENTER to LANDLOCK_PERM_NAMESPACE_USE (and audit blocker perm.namespace_enter to perm.namespace_use) for semantic accuracy: the verb _ENTER fits setns/unshare/clone but misleads for open_tree and fsmount where the caller holds an fd reference without entering. _USE covers both cases and mirrors LANDLOCK_PERM_CAPABILITY_USE.
- Add a Design philosophy section to Documentation/security/landlock.rst stating Landlock's principle:
restrict access to data, other tasks, and kernel resources.
- Rewrite Documentation/security/landlock.rst Ruleset restriction models with the per-object (handled_access_*) versus per-category (handled_perm) framing in place of the previous chokepoints/ gateways wording.
- Enumerate the seven syscall paths covered by LANDLOCK_PERM_NAMESPACE_USE in Documentation/userspace-api/landlock.rst (membership via unshare/clone/setns; fd reference via open_tree and fsmount).
- Document the deterministic-semantics rationale for accepting unknown category member values in rule bodies (per-category permissions section of Documentation/security/landlock.rst); range-checking against CAP_LAST_CAP is intentionally avoided.
- Address Günther Noack's nits in the layer_config wrapper patch:
clarify that _LANDLOCK_ACCESS_FS_INITIALLY_DENIED is ORed with the .handled field of all ruleset->layers[] entries; rename landlock_upgrade_handled_access_masks() to landlock_upgrade_handled_layer_config() to match the parameter type; rewrap the @layers kdoc to greedy fill (eliminating v1's manual short "rulesets in a" line).
- Rename struct layer_rights to struct layer_config: "config" is the more general term for per-layer state.
- Rename internal struct perm_rules to struct perm_masks to parallel the sibling access_masks in struct layer_config.
- Collect Reviewed-by tags from Günther Noack on patches 2, 3, 4, and 5 from the v1 thread. Patch 1 and patch 8 changed substantially since v1 (the mount-namespace blob leak fix and validate_ns() reordering for patch 1; the libcap migration for patch 8), so the Reviewed-by tags from reviewers who had not requested those changes are not carried forward; the affected reviewers are kept as Cc:.
- Rename security_namespace_alloc() to security_namespace_init() (and the LSM hook namespace_alloc -> namespace_init, plus Landlock's hook_namespace_alloc() -> hook_namespace_init()) to match the caller-name convention and reflect that the hook initialises LSM state attached to a constructed ns_common rather than allocating it (patch 1, suggested by Paul Moore).
- Refine the security_namespace_free() kdoc to clarify that RCU-safe blob freeing is required only if an LSM exposes data within the blob to concurrent RCU readers, and document that the blob memory itself is released with kfree() after the namespace_free hooks return (patch 1, suggested by Paul Moore).
- Use cap_from_name(3) from libcap in the sandboxer; LL_CAP now takes colon-delimited capability names (e.g. "cap_sys_chroot") or numbers (libcap's numeric fallback), and the Makefile links libcap (patch 8, suggested by Günther Noack).
- Rename the sandboxer env var LL_CAPS to LL_CAP for consistency with the singular form used by all other LL_* sandboxer env vars (LL_NS, LL_FS_RO, LL_FS_RW, LL_TCP_BIND, LL_TCP_CONNECT, LL_SCOPED, LL_FORCE_LOG; patch 8).
- Add a bridging sentence in the per-category permissions section of Documentation/security/landlock.rst contrasting per-category permissions with per-object access rights (patch 9, suggested by Günther Noack).
- Disambiguate the orthogonality invariant in Documentation/security/landlock.rst ("all new scoped features" -> "all Landlock access controls") to avoid clash with the UAPI scoped field (patch 9, suggested by Justin Suess).
- Add an introductory paragraph in Documentation/userspace-api/landlock.rst contrasting LANDLOCK_PERM_CAPABILITY_USE with PR_SET_NO_NEW_PRIVS (patch 9, suggested by Justin Suess).
- Add an explicit static_assert that LANDLOCK_NUM_PERM_CAP + LANDLOCK_NUM_PERM_NS fits in u64, complementing the implicit sizeof guard on struct perm_masks (patch 5).
- Document that setns_cross_process exercises only CLONE_NEWUTS (patch 6).
- Add add_rule_unknown_no_runtime_effect tests asserting that a rule listing only unknown bits has no runtime effect (patches 6, 7).
- Extend the cap/ns stacking tests with the parent-denies/child- allows variant to complete per-layer walker direction coverage (patches 6, 7).
Mickaël Salaün (8):
landlock: Rename quiet_masks to quiet_access
landlock: Wrap per-layer access masks in struct layer_config
landlock: Enforce namespace use restrictions
landlock: Enforce capability restrictions selftests/landlock: Add namespace restriction tests selftests/landlock: Add capability restriction tests samples/landlock: Add capability and namespace restriction support
landlock: Add documentation for capability and namespace restrictions
Documentation/admin-guide/LSM/landlock.rst | 46 +- Documentation/security/landlock.rst | 178 +- Documentation/trace/events-landlock.rst | 66 +- Documentation/userspace-api/landlock.rst | 243 +- include/linux/landlock.h | 29 +- include/trace/events/landlock.h | 244 +- include/uapi/linux/landlock.h | 139 +- samples/Kconfig | 6 +- samples/landlock/Makefile | 1 + samples/landlock/sandboxer.c | 230 +- security/landlock/Makefile | 4 +- security/landlock/access.h | 61 +- security/landlock/audit.c | 32 +- security/landlock/cap.c | 163 + security/landlock/cap.h | 48 + security/landlock/cred.h | 2 +- security/landlock/domain.c | 13 +- security/landlock/domain.h | 98 +- security/landlock/fs.c | 2 +- security/landlock/limits.h | 9 + security/landlock/log.c | 53 +- security/landlock/log.h | 10 +- security/landlock/net.c | 2 +- security/landlock/ns.c | 241 ++ security/landlock/ns.h | 18 + security/landlock/ruleset.c | 27 +- security/landlock/ruleset.h | 33 +- security/landlock/setup.c | 4 + security/landlock/syscalls.c | 217 +- security/landlock/trace.c | 27 +- tools/testing/selftests/landlock/base_test.c | 21 +- tools/testing/selftests/landlock/cap_test.c | 1364 +++++++++ tools/testing/selftests/landlock/common.h | 23 + tools/testing/selftests/landlock/config | 5 + tools/testing/selftests/landlock/fs_test.c | 13 +- tools/testing/selftests/landlock/ns_test.c | 2643 +++++++++++++++++ tools/testing/selftests/landlock/trace.h | 52 +- tools/testing/selftests/landlock/trace_test.c | 8 +- tools/testing/selftests/landlock/wrappers.h | 29 + 39 files changed, 6225 insertions(+), 179 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: c0a3be0adcce971e28de1c3baeeac472fe97fcaf
Signature · 1 line
2.55.0
Mickaël Salaün
maintainerPATCH v4 1/8 landlock: Rename quiet_masks to quiet_access
The base stores the fs/net/scope quiet bitmasks in a struct access_masks field named quiet_masks. A following commit adds the sibling struct permission_masks field quiet_permission for capabilities and namespaces. quiet_masks drops the access category and keeps the type half ("masks"), while quiet_permission keeps the category and drops the type half, so the two read as an inconsistent pair.
Rename the base field to quiet_access, giving the symmetric, category-named pair quiet_access/quiet_permission that also matches the UAPI handled_access_*/quiet_access_* naming. This is a no-functional-change rename.
---
Changes since v3:
https://patch.msgid.link/[email protected]
- Adapt the rename to the split ruleset/domain and logging code.
- Add Reviewed-by: Tingmao Wang.
Changes since v2:
- New patch.
--- security/landlock/domain.c | 2 +- security/landlock/domain.h | 4 ++-- security/landlock/log.c | 6 +++--- security/landlock/ruleset.h | 4 ++-- security/landlock/syscalls.c | 10 +++++----- 5 files changed, 13 insertions(+), 13 deletions(-)
security/landlock/domain.c +1 -1
@@ -479,7 +479,7 @@ landlock_merge_ruleset(struct landlock_domain *const parent,return ERR_PTR (err);#ifdef CONFIG_SECURITY_LANDLOCK_LOG - new_dom->hierarchy->quiet_masks = ruleset->quiet_masks; + new_dom->hierarchy->quiet_access = ruleset->quiet_access;#endif /* CONFIG_SECURITY_LANDLOCK_LOG */ return no_free_ptr (new_dom);
security/landlock/domain.h +2 -2
@@ -130,10 +130,10 @@ struct landlock_hierarchy {*/ log_new_exec :1 ;/** -* @quiet_masks: Bitmasks of access that should be quieted (i.e. not +* @quiet_access: Bitmasks of access that should be quieted (i.e. not * logged) if the related object is marked as quiet. */ -struct access_masks quiet_masks; +struct access_masks quiet_access;#endif /* CONFIG_SECURITY_LANDLOCK_LOG */ };
security/landlock/log.c +3 -3
@@ -436,7 +436,7 @@ is_denial_quieted(const struct landlock_request *const request,if (object_quiet_flag) {const access_mask_t quiet_mask =pick_access_mask_for_request_type ( - request->type, youngest_denied->quiet_masks); + request->type, youngest_denied->quiet_access);return (quiet_mask & missing) == missing; }
@@ -447,10 +447,10 @@ is_denial_quieted(const struct landlock_request *const request,*/ switch (request->type) {case LANDLOCK_REQUEST_SCOPE_SIGNAL : -return !!(youngest_denied->quiet_masks.scope & +return !!(youngest_denied->quiet_access.scope &LANDLOCK_SCOPE_SIGNAL );case LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET : -return !!(youngest_denied->quiet_masks.scope & +return !!(youngest_denied->quiet_access.scope &LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET );/* * Leave LANDLOCK_REQUEST_PTRACE and LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY
security/landlock/ruleset.h +2 -2
@@ -182,11 +182,11 @@ struct landlock_ruleset {#endif /* CONFIG_TRACEPOINTS */ /** -* @quiet_masks: Stores the quiet flags for an unmerged ruleset. For a +* @quiet_access: Stores the quiet flags for an unmerged ruleset. For a * merged domain, this is stored in each layer's struct * landlock_hierarchy instead. */ -struct access_masks quiet_masks; +struct access_masks quiet_access;/** * @handled_masks: Contains the subset of filesystem and network actions * that are handled by this ruleset.
security/landlock/syscalls.c +5 -5
@@ -280,9 +280,9 @@ SYSCALL_DEFINE3(landlock_create_ruleset,if (IS_ERR (ruleset))return PTR_ERR (ruleset); - ruleset->quiet_masks.fs = ruleset_attr.quiet_access_fs; - ruleset->quiet_masks.net = ruleset_attr.quiet_access_net; - ruleset->quiet_masks.scope = ruleset_attr.quiet_scoped; + ruleset->quiet_access.fs = ruleset_attr.quiet_access_fs; + ruleset->quiet_access.net = ruleset_attr.quiet_access_net; + ruleset->quiet_access.scope = ruleset_attr.quiet_scoped;/* * Emits before anon_inode_getfd() installs the file descriptor, while
@@ -382,7 +382,7 @@ static int add_rule_path_beneath(struct landlock_ruleset *const ruleset,return -EINVAL ;/* Checks for useless quiet flag. */ -if (flags &LANDLOCK_ADD_RULE_QUIET && !ruleset->quiet_masks.fs) +if (flags &LANDLOCK_ADD_RULE_QUIET && !ruleset->quiet_access.fs)return -EINVAL ;/* Gets and checks the new rule. */
@@ -423,7 +423,7 @@ static int add_rule_net_port(struct landlock_ruleset *ruleset,return -EINVAL ;/* Checks for useless quiet flag. */ -if (flags &LANDLOCK_ADD_RULE_QUIET && !ruleset->quiet_masks.net) +if (flags &LANDLOCK_ADD_RULE_QUIET && !ruleset->quiet_access.net)return -EINVAL ;/* Denies inserting a rule with port greater than 65535. */
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v4 1/8] landlock: Rename quiet_masks to quiet_access
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 12 lines
The base stores the
fs/net/scopequiet bitmasks in a structaccess_masksfield namedquiet_masks. A following commit adds the sibling structpermission_masksfieldquiet_permissionfor capabilities and namespaces.quiet_masksdrops the access category and keeps the type half ("masks"), whilequiet_permissionkeeps the category and drops the type half, so the two read as an inconsistent pair.Rename the base field to
quiet_access, giving the symmetric, category-named pair quiet_access/quiet_permission that also matches the UAPI handled_access_*/quiet_access_* naming. This is a no-functional-change rename.
Quoted 4 lines
Cc Günther Noack <[email protected]>Cc Tingmao Wang <[email protected]>Reviewed-by Tingmao Wang <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Mickaël Salaün
maintainerPATCH v4 2/8 landlock: Wrap per-layer access masks in struct layer_config
In reply to Mickaël SalaünThe domain layer FAM stores struct access_masks values directly, while a ruleset stores the equivalent single mutable value. Per-category permissions need additional per-layer data beyond the handled-access bitfields.
Introduce struct layer_config as the common value type. Keeping the handled bitfields in its .handled member leaves struct access_masks as a lightweight parameter type for functions that only need those bitfields, while the complete layer can be snapshotted with one assignment.
At this point struct layer_config only wraps the four-byte access_masks, so it does not grow the per-domain allocation: the maximum 16-entry FAM remains 64 bytes.
No functional change.
---
Changes since v3:
https://patch.msgid.link/[email protected]
- Adapt the wrapper to the ruleset/domain split by using one layer_config value for the ruleset singleton and the domain FAM.
- Generalize the struct access_masks comment because the type also represents quiet and request masks.
Changes since v2:
https://patch.msgid.link/[email protected]
- The rebase required adopting the released check-time struct layer_masks and the new per-ruleset quiet_access (added by the base's merged quiet feature) and updating the struct landlock_ruleset @layers kdoc; struct layer_config already existed in v2.
Changes since v1:
https://patch.msgid.link/[email protected]
- Add Reviewed-by: Tingmao Wang.
- Address Günther Noack's review nits:
- Clarify that _LANDLOCK_ACCESS_FS_INITIALLY_DENIED is ORed with
the .handled field of all ruleset->layers[] entries (not the
entries themselves). - Rename landlock_upgrade_handled_access_masks() to landlock_upgrade_handled_layer_config() to match the parameter type.
- Rewrap the @layers kdoc in struct landlock_ruleset.
- Rename struct layer_rights to struct layer_config: "config" is the more general term for per-layer state.
- Add Reviewed-by: Günther Noack.
--- include/trace/events/landlock.h | 6 +++--- security/landlock/access.h | 32 +++++++++++++++++++++++--------- security/landlock/cred.h | 2 +- security/landlock/domain.c | 10 +++++----- security/landlock/domain.h | 30 ++++++++++++++---------------- security/landlock/fs.c | 2 +- security/landlock/net.c | 2 +- security/landlock/ruleset.c | 6 +++--- security/landlock/ruleset.h | 5 ++--- security/landlock/syscalls.c | 4 ++-- 10 files changed, 55 insertions(+), 44 deletions(-)
include/trace/events/landlock.h +3 -3
@@ -353,9 +353,9 @@ TRACE_EVENT(landlock_create_ruleset,TP_fast_assign ( __entry->ruleset_id = ruleset->id; __entry->ruleset_version = ruleset->version; - __entry->handled_fs = ruleset->handled_masks.fs; - __entry->handled_net = ruleset->handled_masks.net; - __entry->scoped = ruleset->handled_masks.scope; + __entry->handled_fs = ruleset->layer.handled.fs; + __entry->handled_net = ruleset->layer.handled.net; + __entry->scoped = ruleset->layer.handled.scope; ), TP_printk("ruleset=%llx.%llu handled_fs=%s handled_net=%s scoped=%s",
security/landlock/access.h +23 -9
@@ -19,9 +19,9 @@/* * All access rights that are denied by default whether they are handled or not -* by a ruleset/layer. This must be ORed with all domain->handled_masks[] -* entries when we need to get the absolute handled access masks, see -* landlock_upgrade_handled_access_masks(). +* by a ruleset/layer. This must be ORed with the .handled field of all +* domain->layers[] entries when we need to get the absolute handled access +* masks, see landlock_upgrade_handled_layer_config(). */ /* clang-format off */ #define _LANDLOCK_ACCESS_FS_INITIALLY_DENIED ( \
@@ -45,7 +45,7 @@ static_assert(BITS_PER_TYPE(access_mask_t) >= LANDLOCK_NUM_SCOPE);/* Makes sure for_each_set_bit() and for_each_clear_bit() calls are OK. */ static_assert (sizeof (unsigned long ) >=sizeof (access_mask_t)); -/* Ruleset access masks. */ +/* 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,20 @@ union access_masks_all {static_assert (sizeof (typeof_member (union access_masks_all ,masks )) ==sizeof (typeof_member (union access_masks_all ,all ))); +/** +* struct layer_config - Per-layer access configuration +* +* A ruleset stores one mutable layer and a domain stores a flexible array of +* immutable layers. +*/ +struct layer_config { +/** +* @handled: Bitmask of access rights handled (i.e. restricted) by this +* layer. +*/ +struct access_masks handled; +}; +#define _LANDLOCK_LAYER_MASK_PADDING \ (BITS_PER_TYPE(access_mask_t) - LANDLOCK_NUM_ACCESS_MAX - \ IS_ENABLED(CONFIG_SECURITY_LANDLOCK_LOG))
@@ -131,17 +145,17 @@ static_assert(BITS_PER_TYPE(deny_masks_t) >=static_assert (HWEIGHT (LANDLOCK_MAX_NUM_LAYERS ) ==1 );/* Upgrades with all initially denied by default access rights. */ -static inline struct access_masks -landlock_upgrade_handled_access_masks (struct access_masks access_masks) +static inline struct layer_config +landlock_upgrade_handled_layer_config (struct layer_config layer_config) {/* * All access rights that are denied by default whether they are * explicitly handled or not. */ -if (access_masks.fs) - access_masks.fs |= _LANDLOCK_ACCESS_FS_INITIALLY_DENIED; +if (layer_config.handled.fs) + layer_config.handled.fs |= _LANDLOCK_ACCESS_FS_INITIALLY_DENIED; -return access_masks; +return layer_config; }/* Checks the subset relation between access masks. */
security/landlock/cred.h +1 -1
@@ -138,7 +138,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->handled_masks[layer_level], + .masks = domain->layers[layer_level].handled, };if (layer.all & masks_all.all) {
security/landlock/domain.c +5 -5
@@ -50,7 +50,7 @@ static struct landlock_domain *create_domain(const u32 num_layers)struct landlock_domain *new_domain;build_check_domain (); - new_domain =kzalloc_flex (*new_domain, handled_masks, num_layers, + new_domain =kzalloc_flex (*new_domain, layers, num_layers,GFP_KERNEL_ACCOUNT );if (!new_domain)return ERR_PTR (-ENOMEM );
@@ -328,8 +328,8 @@ static int merge_ruleset(struct landlock_domain *const dst,if (WARN_ON_ONCE (dst->num_layers <1 ))return -EINVAL ; - dst->handled_masks[dst->num_layers -1 ] = -landlock_upgrade_handled_access_masks (src->handled_masks); + dst->layers[dst->num_layers -1 ] = +landlock_upgrade_handled_layer_config (src->layer);/* Merges the @src inode tree. */ err =merge_tree (dst, src,LANDLOCK_KEY_INODE );
@@ -404,8 +404,8 @@ static int inherit_ruleset(struct landlock_domain *const parent,/* * Copies the parent layer stack and leaves a space for the new layer. */ -memcpy (child->handled_masks, parent->handled_masks, -flex_array_size (parent, handled_masks, parent->num_layers)); +memcpy (child->layers, parent->layers, +flex_array_size (parent, layers, parent->num_layers));if (WARN_ON_ONCE (!parent->hierarchy))return -EINVAL ;
security/landlock/domain.h +14 -16
@@ -217,7 +217,7 @@ struct landlock_domain {* @work_free: Enables to free a domain within a lockless * section. This is only used by landlock_put_domain_deferred() * when @usage reaches zero. The fields @usage, @num_layers and -* @handled_masks are then unused. +* @layers are then unused. */ struct work_struct work_free;struct {
@@ -233,18 +233,16 @@ struct landlock_domain {*/ u32 num_layers;/** -* @handled_masks: Contains the subset of filesystem and -* network actions that are restricted by a domain. A -* domain saves all layers of merged rulesets in a stack -* (FAM), starting from the first layer to the last one. -* These layers are used when merging rulesets, for user -* space backward compatibility (i.e. future-proof), and -* to properly handle merged rulesets without -* overlapping access rights. These layers are set once -* and never changed for the lifetime of the domain. +* @layers: Per-layer access configuration. A domain +* saves all layers of merged rulesets in a stack (FAM), +* starting from the first layer to the last one. These +* layers are used when merging rulesets, for user space +* backward compatibility (i.e. future-proof), and to +* properly handle merged rulesets without overlapping +* access rights. These layers are set once and never +* changed for the lifetime of the domain. */ -struct access_masks - handled_masks[] __counted_by(num_layers); + struct layer_config layers[] __counted_by(num_layers); }; }; };
@@ -254,7 +252,7 @@ landlock_get_fs_access_mask(const struct landlock_domain *const domain, const u16 layer_level) {/* Handles all initially denied by default access rights. */ -return domain->handled_masks[layer_level].fs | +return domain->layers[layer_level].handled.fs | _LANDLOCK_ACCESS_FS_INITIALLY_DENIED; }
@@ -262,14 +260,14 @@ static inline access_mask_t landlock_get_net_access_mask(const struct landlock_domain *const domain, const u16 layer_level) { - return domain->handled_masks[layer_level].net; + return domain->layers[layer_level].handled.net; }static inline access_mask_t landlock_get_scope_mask (const struct landlock_domain *const domain,const u16 layer_level) { -return domain->handled_masks[layer_level].scope; +return domain->layers[layer_level].handled.scope; }/**
@@ -288,7 +286,7 @@ landlock_union_access_masks(const struct landlock_domain *const domain)for (layer_level =0 ; layer_level < domain->num_layers; layer_level++) {union access_masks_all layer = { - .masks = domain->handled_masks[layer_level], + .masks = domain->layers[layer_level].handled, }; matches.all |= layer.all;
security/landlock/fs.c +1 -1
@@ -342,7 +342,7 @@ int landlock_append_fs_rule(struct landlock_ruleset *const ruleset,/* Transforms relative access rights to absolute ones. */ access_rights |=LANDLOCK_MASK_ACCESS_FS & - ~(ruleset->handled_masks.fs | + ~(ruleset->layer.handled.fs | _LANDLOCK_ACCESS_FS_INITIALLY_DENIED); id.key.object =get_inode_object (d_backing_inode (path->dentry));if (IS_ERR (id.key.object))
security/landlock/net.c +1 -1
@@ -35,7 +35,7 @@ int landlock_append_net_rule(struct landlock_ruleset *const ruleset,BUILD_BUG_ON (sizeof (port) >sizeof (id.key.data));/* Transforms relative access rights to absolute ones. */ - access_rights |=LANDLOCK_MASK_ACCESS_NET & ~ruleset->handled_masks.net; + access_rights |=LANDLOCK_MASK_ACCESS_NET & ~ruleset->layer.handled.net;mutex_lock (&ruleset->lock); err =landlock_insert_rule (ruleset, id, access_rights, flags);
security/landlock/ruleset.c +3 -3
@@ -64,20 +64,20 @@ landlock_create_ruleset(const access_mask_t fs_access_mask,LANDLOCK_MASK_ACCESS_FS ;WARN_ON_ONCE (fs_access_mask != mask); - new_ruleset->handled_masks.fs |= mask; + new_ruleset->layer.handled.fs |= mask; }if (net_access_mask) {const access_mask_t mask = net_access_mask &LANDLOCK_MASK_ACCESS_NET ;WARN_ON_ONCE (net_access_mask != mask); - new_ruleset->handled_masks.net |= mask; + new_ruleset->layer.handled.net |= mask; }if (scope_mask) {const access_mask_t mask = scope_mask &LANDLOCK_MASK_SCOPE ;WARN_ON_ONCE (scope_mask != mask); - new_ruleset->handled_masks.scope |= mask; + new_ruleset->layer.handled.scope |= mask; }return new_ruleset; }
security/landlock/ruleset.h +2 -3
@@ -188,10 +188,9 @@ struct landlock_ruleset {*/ struct access_masks quiet_access;/** -* @handled_masks: Contains the subset of filesystem and network actions -* that are handled by this ruleset. +* @layer: Access configuration for this ruleset's single mutable layer. */ -struct access_masks handled_masks; +struct layer_config layer; }; struct landlock_ruleset *
security/landlock/syscalls.c +2 -2
@@ -377,7 +377,7 @@ static int add_rule_path_beneath(struct landlock_ruleset *const ruleset,return -ENOMSG ;/* Checks that allowed_access matches the @ruleset constraints. */ - mask = ruleset->handled_masks.fs; + mask = ruleset->layer.handled.fs;if ((path_beneath_attr.allowed_access | mask) != mask)return -EINVAL ;
@@ -418,7 +418,7 @@ static int add_rule_net_port(struct landlock_ruleset *ruleset,return -ENOMSG ;/* Checks that allowed_access matches the @ruleset constraints. */ - mask = ruleset->handled_masks.net; + mask = ruleset->layer.handled.net;if ((net_port_attr.allowed_access | mask) != mask)return -EINVAL ;
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v4 2/8] landlock: Wrap per-layer access masks in struct layer_config
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 14 lines
The domain layer FAM stores struct
access_masksvalues directly, while a ruleset stores the equivalent single mutable value. Per-category permissions need additional per-layer data beyond the handled-access bitfields.Introduce struct
layer_configas the common value type. Keeping the handled bitfields in its .handled member leaves structaccess_masksas a lightweight parameter type for functions that only need those bitfields, while the complete layer can be snapshotted with one assignment.At this point struct
layer_configonly wraps the four-byteaccess_masks, so it does not grow the per-domain allocation: the maximum 16-entry FAM remains 64 bytes.
Quoted 6 lines
No functional change.
Cc Günther Noack <[email protected]>Reviewed-by Günther Noack <[email protected]>Reviewed-by Tingmao Wang <[email protected]>Signed-off-by Mickaël Salaün <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Mickaël Salaün
maintainerPATCH v4 3/8 landlock: Enforce namespace use restrictions
In reply to Mickaël SalaünAdd Landlock enforcement for namespace use through the LSM namespace_init and namespace_install hooks. This lets a sandboxed process restrict which namespace types it can create, join, or acquire a file descriptor for, using LANDLOCK_PERMISSION_NAMESPACE_USE and per-type rules.
Introduce the handled_permissions field in struct landlock_ruleset_attr:
each permission gates every use of a kernel-defined category (CLONE_NEW* namespace types, CAP_* capabilities) with complete deny-by-default coverage, so unknown member values need no validation, being denied until a rule allows them. This UAPI extension advances the Landlock ABI from 11 to 12.
There is no domain-ancestry bypass and no namespace-creator tracking, only a flat per-layer allowed-types bitmask: hook_namespace_init() covers creation through clone(2), unshare(2), open_tree(2) and fsmount(2), and hook_namespace_install() covers setns(2). Each permission hook maps its member mask explicitly in the shared permission walker, which warns and denies if a future caller omits that mapping. These categorical denials return -EPERM, matching Landlock's scope and mount-topology denials rather than its object-access -EACCES convention.
struct permission_masks is forced to eight bytes with __packed and __aligned because it must eventually hold both the eight namespace types and all capabilities, and because m68k GCC otherwise packs its u64 bitfields at byte granularity, making the structure smaller than sizeof(u64). Carrying it grows struct layer_config from 4 to 16 bytes, so the largest 16-entry domain FAM grows from 64 to 256 bytes.
The permissions selector keeps the rule attribute self-describing:
- User space can mask it against handled_permissions, as it masks allowed_access against handled_access_fs, so a program built against newer headers still adds the rules an older kernel supports.
- It tells apart two attributes that share the same three-u64 layout. Unknown member bits are ignored, so without it a mismatched rule type would apply a capability mask as namespace types.
- It leaves room for a rule to carry several permissions, or for another rule type to key the same permission differently.
The rule also carries a quiet_namespace_types bitmask that suppresses audit submission for denied members without granting them. A sandbox knowingly running a caller that probes a type it will never be granted would otherwise flood the audit log and drown the surprising denials that matter. Quiet is per-member rather than a coarse per-category ruleset bit, so a sandbox can silence CLONE_NEWNET while still auditing CLONE_NEWUTS; making it the complement of the allowed set would be broad, could not audit a member that is neither allowed nor explicitly quieted, and would auto-hide members added by future kernels. It is a per-rule bitmask rather than the LANDLOCK_ADD_RULE_QUIET flag and the ruleset quiet_access_* masks, which suit the unbounded rb-tree objects of filesystem and network rules, so that flag is rejected here. Only the youngest denying layer's quiet mask decides, so a parent cannot silence a denial made by a deeper layer.
Trace the handled permission mask, every successful namespace rule, and namespace denials. Successful effective no-ops advance the version, and quiet denials remain trace-visible with logged=0. The denial event takes the blockers argument of the filesystem and network events and records the same blockers_type and blockers_access fields, so one filter expression spans the mask-bearing denial events. Handled and rule permission masks may contain permissions from multiple domains in one field, so their names are domain-qualified, such as namespace.use. A blocker is already interpreted in the domain supplied by the audit prefix or denial event, so it retains the bare action name use, matching existing access blockers such as read_file.
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 the capability permission added by the next commit is also handled, both must allow the operation.
---
Changes since v3:
https://patch.msgid.link/[email protected]
- Adapt to the merged namespace/audit prerequisites and the ruleset/domain split, snapshotting the allowed and quiet masks under the source ruleset lock.
- Suppress and assert the expected warnings in the invalid-input KUnit tests.
- Map namespace types with a lookup table, and drop __attribute_const__ from the conversion helpers, which warn on invalid input.
- Advance the Landlock ABI to 12.
- Spell out perm as permission in the UAPI constant and members, the internal masks and helpers, and the trace fields, and name the audit blocker namespace.use after its domain instead of perm.namespace_use.
- Justify the permissions selector by what it does today: user space can mask it against handled_permissions, and it tells apart two attributes that share one layout, whose unknown member bits are ignored.
- Trace handled permissions, successful namespace rules, and denials. Successful effective no-ops advance the version, while quiet denials remain trace-visible with logged=0.
- Tell programs to omit empty rules.
- Complete the permission-rule errors and explain fail-closed dispatch and the -EPERM convention.
- Drop Reviewed-by: Tingmao Wang: this version folds the namespace trace events and ABI 12 into this patch, which her v3 review did not cover; a fresh review is welcome.
Changes since v2:
https://patch.msgid.link/[email protected]
- Rename the namespace rule attribute fields (allowed_perm to perm, namespace_types to allowed_namespace_types) and add a quiet_namespace_types bitmask that suppresses the audit records of specific denied namespace types, together with the shared per-layer quiet member mask read in landlock_log_denial(); the rule attribute grows from 16 to 24 bytes.
- Copy the accumulated quiet_perm mask into the domain hierarchy in merge_ruleset(), under the ruleset merge lock and atomically with the allowed mask (no separate lock).
- Dropped Reviewed-by: Günther Noack and Tingmao Wang, as this version adds the quiet member mask described above, which their v1 review did not cover. Fresh review welcome.
Changes since v1:
https://patch.msgid.link/[email protected]
- Add __packed __aligned(sizeof(u64)) to struct perm_masks to fix static_assert failure on m68k, where GCC packs bitfields at byte granularity.
- Use ns_id instead of inum in namespace audit records.
- Add WARN_ON_ONCE guards for invalid perm_bit or request_value in landlock_perm_is_denied(), denying with the youngest layer on invalid input (suggested by Tingmao Wang).
- Fix double backtick in landlock_perm_is_denied() kernel-doc.
- Add Reviewed-by: Tingmao Wang.
- Mention commit 935a04923ad2 ("nsproxy: Add FOR_EACH_NS_TYPE() X-macro and CLONE_NS_ALL") as a dependency in the body and add
Depends-on: trailer.
- Rename internal struct perm_rules to perm_masks to parallel the sibling access_masks in struct layer_config.
- Document the allowed_perm design rationale (extensibility for future sub-permissions, type discriminant safeguard).
- Rename LANDLOCK_PERM_NAMESPACE_ENTER to LANDLOCK_PERM_NAMESPACE_USE and audit blocker perm.namespace_enter to perm.namespace_use for semantic accuracy. The verb _ENTER fits setns/unshare/clone (caller becomes namespace member) but misleads for open_tree and fsmount (caller holds an fd reference, does not enter). _USE covers both cases and mirrors LANDLOCK_PERM_CAPABILITY_USE. Update the commit title accordingly.
- Replace "chokepoint"/"gateway" prose in @handled_perm kdoc and the Permission flags DOC block with the per-category framing.
- Expand the LANDLOCK_PERM_NAMESPACE_USE kdoc to enumerate creation (unshare/clone/clone3), joining (setns), and fd-reference (open_tree/fsmount) paths.
- Rewrite the commit body to drop chokepoint/gateway terminology in favour of per-category framing, matching the doc rewrite.
- Rename struct layer_rights to struct layer_config (companion change to the introducing commit).
- Surface the empty-check semantics in the landlock_namespace_attr.namespace_types kdoc: a rule that sets only bits unknown to the running kernel succeeds but has no runtime effect.
- Cascade the LSM hook rename namespace_alloc -> namespace_init (LSM_HOOK_INIT registration and local handler hook_namespace_alloc -> hook_namespace_init), companion change to the introducing commit.
- Rename the static helper landlock_check_ns_type() to check_ns_type():
the landlock_ prefix is reserved for non-static symbols exported via headers; file-static helpers follow the prefix-free convention used in security/landlock/.
- Add Reviewed-by: Günther Noack.
--- include/linux/landlock.h | 26 +- include/trace/events/landlock.h | 131 +++++++++- include/uapi/linux/landlock.h | 73 ++++++ security/landlock/Makefile | 3 +- security/landlock/access.h | 29 ++- security/landlock/audit.c | 28 +- security/landlock/domain.c | 1 + security/landlock/domain.h | 61 +++++ security/landlock/limits.h | 7 + security/landlock/log.c | 37 ++- security/landlock/log.h | 9 +- security/landlock/ns.c | 241 ++++++++++++++++++ security/landlock/ns.h | 18 ++ security/landlock/ruleset.c | 21 +- security/landlock/ruleset.h | 24 +- security/landlock/setup.c | 2 + security/landlock/syscalls.c | 114 ++++++++- security/landlock/trace.c | 15 +- tools/testing/selftests/landlock/base_test.c | 2 +- tools/testing/selftests/landlock/trace.h | 3 +- tools/testing/selftests/landlock/trace_test.c | 8 +- 21 files changed, 800 insertions(+), 53 deletions(-) create mode 100644 security/landlock/ns.c create mode 100644 security/landlock/ns.h
include/linux/landlock.h +23 -3
@@ -13,14 +13,16 @@#include <uapi/linux/landlock.h> /* -* Access-right and scope names, shared between the audit records (get_blocker() -* in security/landlock/audit.c) and the trace events +* Access-right, scope, and permission names, shared between the audit records +* (get_blocker() in security/landlock/audit.c) and the trace events * (include/trace/events/landlock.h). A consumer defines * _LANDLOCK_NAME_ENTRY(mask, name) before expanding a list and undefines it * afterwards: audit maps each entry to a "[bit] = name" slot for O(1) lookup, * the trace events map it to a __print_flags() { mask, name } pair. The bit * value lives only in the LANDLOCK_* UAPI constant each entry references. -* Names are unprefixed; audit prepends the "fs."/"net."/"scope." category. +* Access-right and scope names are unprefixed; audit prepends the +* "fs."/"net."/"scope." category. Permission entries carry an action and a +* domain for the qualified and bare views below. */ #define _LANDLOCK_ACCESS_FS_NAMES \ _LANDLOCK_NAME_ENTRY(LANDLOCK_ACCESS_FS_EXECUTE, "execute"), \
@@ -53,4 +55,22 @@ "abstract_unix_socket"), \ _LANDLOCK_NAME_ENTRY(LANDLOCK_SCOPE_SIGNAL, "signal") +#define _LANDLOCK_PERMISSION_NAMESPACE_NAME "namespace" + +#define _LANDLOCK_PERMISSION_LIST (entry) \ + entry(LANDLOCK_PERMISSION_NAMESPACE_USE, "use", \ + _LANDLOCK_PERMISSION_NAMESPACE_NAME) + +#define _LANDLOCK_PERMISSION_QUALIFIED_ENTRY (mask, action, domain) \ + _LANDLOCK_NAME_ENTRY(mask, domain "." action) + +#define _LANDLOCK_PERMISSION_BARE_ENTRY (mask, action, ...) \ + _LANDLOCK_NAME_ENTRY(mask, action) + +#define _LANDLOCK_PERMISSION_NAMES \ + _LANDLOCK_PERMISSION_LIST(_LANDLOCK_PERMISSION_QUALIFIED_ENTRY) + +#define _LANDLOCK_PERMISSION_BLOCKER_NAMES \ + _LANDLOCK_PERMISSION_LIST(_LANDLOCK_PERMISSION_BARE_ENTRY) +#endif /* _LINUX_LANDLOCK_H */
include/trace/events/landlock.h +119 -12
178 lines not on this page · raw message
include/uapi/linux/landlock.h +73 -0
95 lines not on this page · raw message
security/landlock/Makefile +2 -1
@@ -9,7 +9,8 @@ landlock-y := \ task.o \ fs.o \ tsync.o \ - domain.o + domain.o \ + ns.o landlock-$(CONFIG_INET) += net.o
security/landlock/access.h +25 -4
@@ -42,14 +42,17 @@ 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 permissions can be stored. */ +static_assert (BITS_PER_TYPE (access_mask_t) >=LANDLOCK_NUM_PERMISSION );/* Makes sure for_each_set_bit() and for_each_clear_bit() calls are OK. */ static_assert (sizeof (unsigned long ) >=sizeof (access_mask_t)); -/* Access masks (bitfields only). */ +/* Access and permission masks (bitfields only). */ 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 permissions :LANDLOCK_NUM_PERMISSION ; } __packed__aligned(sizeof(u32)) ;union access_masks_all {
@@ -61,16 +64,34 @@ union access_masks_all {static_assert (sizeof (typeof_member (union access_masks_all ,masks )) ==sizeof (typeof_member (union access_masks_all ,all ))); +/** +* struct permission_masks - Per-permission member bitmasks +*/ +struct permission_masks { +/** +* @ns_types: Namespace type member mask, indexed in FOR_EACH_NS_TYPE() +* order. +*/ +u64 ns_types :LANDLOCK_NUM_NAMESPACE_TYPE ; +} __packed__aligned(sizeof(u64)) ; + +static_assert (sizeof (struct permission_masks ) ==sizeof (u64)); +/** * struct layer_config - Per-layer access configuration * * A ruleset stores one mutable layer and a domain stores a flexible array of -* immutable layers. +* immutable layers. Unlike filesystem and network access rights, namespace +* types use a flat bitmask because their keyspace is small and bounded. */ struct layer_config {/** -* @handled: Bitmask of access rights handled (i.e. restricted) by this -* layer. +* @allowed: Members allowed by each handled permission. +*/ +struct permission_masks allowed; +/** +* @handled: Bitmask of access rights and permissions handled (i.e. +* restricted) by this layer. */ struct access_masks handled; };
security/landlock/audit.c +21 -7
@@ -21,10 +21,10 @@#include "log.h" /* -* Access-right and scope names are built from the lists shared with the trace -* events (see <linux/landlock.h>). The designated initializer places each name -* at its bit index, so the lookup stays O(1) and does not depend on the entry -* order. log_blockers() adds the "fs."/"net."/"scope." category prefix. +* Access-right, scope, and permission names are built from the lists shared +* with the trace events (see <linux/landlock.h>). The designated initializer +* places each name at its bit index, so the lookup stays O(1) and does not +* depend on the entry order. log_blockers() adds the related category prefix. */ #define _LANDLOCK_NAME_ENTRY (mask, name) [BIT_INDEX(mask)] = name
@@ -40,6 +40,12 @@ static const char *const scope_strings[] = { _LANDLOCK_SCOPE_NAMES };static_assert (ARRAY_SIZE (scope_strings) ==LANDLOCK_NUM_SCOPE ); +static const char *const permission_strings[] = { + _LANDLOCK_PERMISSION_BLOCKER_NAMES +}; + +static_assert (ARRAY_SIZE (permission_strings) ==LANDLOCK_NUM_PERMISSION ); +#undef _LANDLOCK_NAME_ENTRY static __attribute_const__ const char *
@@ -73,6 +79,11 @@ get_blocker(const enum landlock_request_type type,case LANDLOCK_REQUEST_SCOPE_SIGNAL :WARN_ON_ONCE (access_bit !=-1 );return scope_strings[BIT_INDEX (LANDLOCK_SCOPE_SIGNAL )]; + +case LANDLOCK_REQUEST_NAMESPACE : +if (WARN_ON_ONCE (access_bit >=ARRAY_SIZE (permission_strings))) +return "unknown" ; +return permission_strings[access_bit]; }WARN_ON_ONCE (1 );
@@ -82,8 +93,8 @@ get_blocker(const enum landlock_request_type type,/* * Returns the audit category prefix prepended to the unprefixed blocker name * returned by get_blocker() (filesystem and network access rights, -* change_topology, and scopes). The ptrace blocker is standalone and carries -* its full name in get_blocker(), so it uses no prefix. +* change_topology, scopes, and permissions). The ptrace blocker is standalone: +* its full name comes from get_blocker(), so it uses no prefix. */ static __attribute_const__ const char *blocker_prefix (const enum landlock_request_type type)
@@ -102,6 +113,9 @@ blocker_prefix(const enum landlock_request_type type)case LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET :case LANDLOCK_REQUEST_SCOPE_SIGNAL :return "scope." ; + +case LANDLOCK_REQUEST_NAMESPACE : +return _LANDLOCK_PERMISSION_NAMESPACE_NAME"." ; }WARN_ON_ONCE (1 );
@@ -163,7 +177,7 @@ static void log_domain(struct landlock_hierarchy *const hierarchy)* * @request: Detail of the user space request. * @youngest_denied: The youngest hierarchy node that denied the access. -* @missing: The set of denied access rights. +* @missing: The set of denied access rights or permissions. * @logged: Whether the denial is selected for logging, as computed by * landlock_log_denial() (domain policy and quiet rules). *
security/landlock/domain.c +1 -0
@@ -480,6 +480,7 @@ landlock_merge_ruleset(struct landlock_domain *const parent,#ifdef CONFIG_SECURITY_LANDLOCK_LOG new_dom->hierarchy->quiet_access = ruleset->quiet_access; + new_dom->hierarchy->quiet_permission = ruleset->quiet_permission;#endif /* CONFIG_SECURITY_LANDLOCK_LOG */ return no_free_ptr (new_dom);
security/landlock/domain.h +61 -0
71 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_PERMISSION LANDLOCK_PERMISSION_NAMESPACE_USE +#define LANDLOCK_MASK_PERMISSION ((LANDLOCK_LAST_PERMISSION << 1) - 1) +#define LANDLOCK_NUM_PERMISSION __const_hweight64(LANDLOCK_MASK_PERMISSION) + +#define LANDLOCK_NUM_NAMESPACE_TYPE __const_hweight64((u64)CLONE_NS_ALL) +#define LANDLOCK_NUM_ACCESS_MAX \ MAX(MAX(LANDLOCK_NUM_ACCESS_FS, LANDLOCK_NUM_ACCESS_NET), LANDLOCK_NUM_SCOPE)
security/landlock/log.c +33 -4
@@ -17,6 +17,7 @@#include "domain.h" #include "limits.h" #include "log.h" +#include "ns.h" #include "ruleset.h" #include "trace.h"
@@ -382,6 +383,31 @@ static bool is_valid_request(const struct landlock_request *const request)if (WARN_ON_ONCE (!(!!request->layer_plus_one ^ !!request->access)))return false; +if (WARN_ON_ONCE (request->access && request->permission)) +return false; + +switch (request->type) { +case LANDLOCK_REQUEST_NAMESPACE : +if (WARN_ON_ONCE (request->permission != +LANDLOCK_PERMISSION_NAMESPACE_USE ) || +WARN_ON_ONCE (request->audit.type !=LSM_AUDIT_DATA_NS )) +return false; +break ; +case LANDLOCK_REQUEST_PTRACE : +case LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY : +case LANDLOCK_REQUEST_FS_ACCESS : +case LANDLOCK_REQUEST_NET_ACCESS : +case LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET : +case LANDLOCK_REQUEST_SCOPE_SIGNAL : +if (WARN_ON_ONCE (request->permission)) +return false; +break ; +default : +WARN_ONCE (1 ,"Unknown Landlock request type %d\n" , + request->type); +return false; + } +if (request->access) {if (WARN_ON_ONCE (!(!!request->layer_masks ^ !!request->all_existing_optional_access)))
@@ -442,8 +468,8 @@ is_denial_quieted(const struct landlock_request *const request, }/* -* Either the object is not quiet, or this is a scope request. We check -* request->type to distinguish between the two cases. +* Per-object quieting did not apply. Check request->type for scope and +* permission quieting; ptrace and topology requests are never quiet. */ switch (request->type) {case LANDLOCK_REQUEST_SCOPE_SIGNAL :
@@ -452,6 +478,9 @@ is_denial_quieted(const struct landlock_request *const request,case LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET :return !!(youngest_denied->quiet_access.scope &LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET ); +case LANDLOCK_REQUEST_NAMESPACE : +return !!(youngest_denied->quiet_permission.ns_types & +landlock_ns_type_to_bit (request->audit.u.ns.ns_type));/* * Leave LANDLOCK_REQUEST_PTRACE and LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY * unhandled for now - they are never quiet.
@@ -508,8 +537,8 @@ void landlock_log_denial(const struct landlock_cred_security *const subject,if (!is_valid_request (request))return ; - missing = request->access; -if (missing) { + missing = request->access ? request->access : request->permission; +if (request->access) {/* Gets the nearest domain that denies the request. */ if (request->layer_masks) { youngest_layer = get_denied_layer(subject->domain,
security/landlock/log.h +8 -1
@@ -25,9 +25,11 @@ enum landlock_request_type {LANDLOCK_REQUEST_NET_ACCESS ,LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET ,LANDLOCK_REQUEST_SCOPE_SIGNAL , + LANDLOCK_REQUEST_NAMESPACE, };struct landlock_blockers { +/* Blocking access rights or permissions, as selected by @type. */ access_mask_t access;enum landlock_request_type type; };
@@ -58,8 +60,13 @@ struct landlock_signal_trace {* CONFIG_SECURITY_LANDLOCK_LOG is not set. */ struct landlock_request { -/* Mandatory fields. */ +/* Mandatory request type. */ enum landlock_request_type type; + +/* Required field for permission requests. */ +access_mask_t permission; + +/* Mandatory audit context. */ struct common_audit_data audit;/**
security/landlock/ns.c new file +241 -0
241 lines not on this page · raw message
security/landlock/ns.h new file +18 -0
@@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Landlock - Namespace hooks +* +* Copyright © 2026 Cloudflare, Inc. +*/ + +#ifndef _SECURITY_LANDLOCK_NS_H +#define _SECURITY_LANDLOCK_NS_H + +#include <linux/types.h> + +u64 landlock_ns_type_to_bit (u32 ns_type); +u64 landlock_ns_types_to_bits (u64 ns_types); + +__init void landlock_add_ns_hooks (void ); + +#endif /* _SECURITY_LANDLOCK_NS_H */
security/landlock/ruleset.c +16 -5
@@ -31,15 +31,15 @@#include <trace/events/landlock.h> -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 permission_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 && + !permission_mask)return ERR_PTR (-ENOMSG ); new_ruleset =kzalloc_obj (*new_ruleset,GFP_KERNEL_ACCOUNT );
@@ -66,6 +66,7 @@ landlock_create_ruleset(const access_mask_t fs_access_mask,WARN_ON_ONCE (fs_access_mask != mask); new_ruleset->layer.handled.fs |= mask; } +if (net_access_mask) {const access_mask_t mask = net_access_mask &LANDLOCK_MASK_ACCESS_NET ;
@@ -73,12 +74,22 @@ landlock_create_ruleset(const access_mask_t fs_access_mask,WARN_ON_ONCE (net_access_mask != mask); new_ruleset->layer.handled.net |= mask; } +if (scope_mask) {const access_mask_t mask = scope_mask &LANDLOCK_MASK_SCOPE ;WARN_ON_ONCE (scope_mask != mask); new_ruleset->layer.handled.scope |= mask; } + +if (permission_mask) { +const access_mask_t mask = permission_mask & +LANDLOCK_MASK_PERMISSION ; + +WARN_ON_ONCE (permission_mask != mask); + new_ruleset->layer.handled.permissions |= mask; + } +return new_ruleset; }
security/landlock/ruleset.h +19 -5
@@ -184,19 +184,27 @@ struct landlock_ruleset {/** * @quiet_access: Stores the quiet flags for an unmerged ruleset. For a * merged domain, this is stored in each layer's struct -* landlock_hierarchy instead. +* landlock_hierarchy instead. Its permissions member is unused because +* permission quieting is per member rather than per permission. */ struct access_masks quiet_access; +#ifdef CONFIG_SECURITY_LANDLOCK_LOG +/** +* @quiet_permission: Per-member quiet bitmasks for permission types in +* this ruleset. A denied member whose bit is set here is not submitted +* to audit when this layer denies it. +*/ +struct permission_masks quiet_permission; +#endif /* CONFIG_SECURITY_LANDLOCK_LOG */ /** * @layer: Access configuration for this ruleset's single mutable layer. */ struct layer_config layer; }; -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 permission_mask);void landlock_put_ruleset (struct landlock_ruleset *const ruleset);
@@ -247,4 +255,10 @@ static inline void landlock_get_ruleset(struct landlock_ruleset *const ruleset) refcount_inc(&ruleset->usage); } +static inline access_mask_t +landlock_get_permission_mask (const struct landlock_ruleset *const ruleset) +{ +return ruleset->layer.handled.permissions; +} +#endif /* _SECURITY_LANDLOCK_RULESET_H */
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 +107 -7
201 lines not on this page · raw message
security/landlock/trace.c +14 -1
@@ -62,7 +62,7 @@ void landlock_trace_free_domain(const struct landlock_hierarchy *const hierarchy* * @request: Detail of the user space request. * @youngest_denied: The youngest hierarchy node that denied the access. -* @missing: The final missing access subset, when applicable. +* @missing: The final missing access or permission subset, when applicable. * @same_exec: Whether the policy subject is the same executable that called * landlock_restrict_self() for the denying domain, as computed * by landlock_log_denial().
@@ -81,6 +81,19 @@ void landlock_trace_denial( const access_mask_t missing, const bool same_exec, const bool logged) { switch (request->type) { + case LANDLOCK_REQUEST_NAMESPACE: + if (trace_landlock_deny_permission_namespace_enabled()) { + const struct landlock_blockers blockers = { + .access = missing, + .type = request->type, + }; + +trace_landlock_deny_permission_namespace ( + youngest_denied, same_exec, logged, &blockers, + request->audit.u.ns.ns_type, + request->audit.u.ns.ns_id); + } +break ;case LANDLOCK_REQUEST_FS_ACCESS :case LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY :if (trace_landlock_deny_access_fs_enabled ()) {
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 (11 ,landlock_create_ruleset (NULL ,0 , +ASSERT_EQ (12 ,landlock_create_ruleset (NULL ,0 ,LANDLOCK_CREATE_RULESET_VERSION )); ASSERT_EQ(-1, landlock_create_ruleset(&ruleset_attr, 0,
tools/testing/selftests/landlock/trace.h +2 -1
@@ -101,7 +101,8 @@"ruleset=[0-9a-f]\\+\\.[0-9]\\+ " \"handled_fs=[a-z_|]* " \"handled_net=[a-z_|]* " \ - "scoped=[a-z_|]*$" +"scoped=[a-z_|]* " \ + "handled_permissions=[a-z._|]*$"#define REGEX_CREATE_DOMAIN (task) \ TRACE_PREFIX(task) \
tools/testing/selftests/landlock/trace_test.c +7 -1
@@ -148,7 +148,7 @@ TEST_F(trace, no_trace_when_disabled)/* * Verifies that landlock_create_ruleset emits a trace event with the correct -* handled access masks. +* handled access and permission masks. */ TEST_F(trace, create_ruleset) {
@@ -186,6 +186,12 @@ TEST_F(trace, create_ruleset) "handled_net", field, sizeof(field)));EXPECT_STREQ ("bind_tcp" , field); +/* Verify that no permission is handled. */ +EXPECT_EQ (0 ,tracefs_extract_field ( + buf,REGEX_CREATE_RULESET (TRACE_TASK ), +"handled_permissions" , field,sizeof (field))); +EXPECT_STREQ ("" , field); +/* Verify version is 0 at creation (no rules added yet). */ EXPECT_EQ(0, tracefs_extract_field(buf, REGEX_CREATE_RULESET(TRACE_TASK),
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v4 3/8] landlock: Enforce namespace use restrictions
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 13 lines
Add Landlock enforcement for namespace use through the LSM
namespace_initandnamespace_installhooks. This lets a sandboxed process restrict which namespace types it can create, join, or acquire a file descriptor for, usingLANDLOCK_PERMISSION_NAMESPACE_USEand per-type rules.Introduce the
handled_permissionsfield in structlandlock_ruleset_attr:
each permission gates every use of a kernel-defined category (CLONE_NEW* namespace types, CAP_* capabilities) with complete deny-by-default coverage, so unknown member values need no validation, being denied until a rule allows them. This UAPI extension advances the Landlock ABI from 11 to 12.
Quoted 8 lines
There is no domain-ancestry bypass and no namespace-creator tracking, only a flat per-layer allowed-types bitmask:
hook_namespace_init()[ ... ]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]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Mickaël Salaün
maintainerPATCH v4 4/8 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_PERMISSION_CAPABILITY_USE and per-capability rules.
The check is a flat per-layer allowed-capabilities test, with no domain-ancestry bypass, no cross-namespace discriminant, and no dependency on the target user namespace. These categorical denials return -EPERM, like the namespace permission introduced by the previous commit, and they mirror its per-capability allowed and quiet masks, so LANDLOCK_ADD_RULE_QUIET stays rejected for this rule type. Successful capability rules and denials are traced as the previous commit describes.
Enforce only at capability exercise time rather than modifying the credential's capability sets. Modifying them would give capget(2) an accurate view of usable capabilities, but no LSM other than commoncap does so; Landlock follows that convention. A sandboxed process inside a user namespace therefore sees all capabilities via capget(2) but receives -EPERM when attempting to use one that is denied.
An earlier design bypassed this hook for namespace management through a domain-ancestry comparison with the namespace creator's stored Landlock domain. That made a Landlock decision depend on kernel namespace state, and the ns != cred->user_ns heuristic did not accurately identify namespace-management operations. The flat, namespace-agnostic check instead enforces capability and namespace restrictions independently; creating a non-user namespace requires an allowed CAP_SYS_ADMIN even when combined with CLONE_NEWUSER in one unshare().
---
Changes since v3:
https://patch.msgid.link/[email protected]
- Adapt the capability mask to the ruleset/domain split.
- Spell out perm as permission in the UAPI constant and members, the internal masks and helpers, and the trace fields, and name the audit blocker capability.use after its domain instead of perm.capability_use.
- Suppress and assert the expected warnings in the invalid-input KUnit tests.
- Drop __attribute_const__ from the conversion helpers, which warn on invalid input.
- Trace successful capability rules and denials. Successful effective no-ops advance the version, while quiet denials remain trace-visible with logged=0.
- Tell programs to omit empty rules, complete the rule errors, and explain target-user-namespace independence and the -EPERM convention.
- Drop Reviewed-by: Tingmao Wang: this version folds the capability trace events into this patch, which her v3 review did not cover; a fresh review is welcome.
Changes since v2:
https://patch.msgid.link/[email protected]
- Rename the capability rule attribute fields (allowed_perm to perm, capabilities to allowed_capabilities) and add a quiet_capabilities bitmask that suppresses the audit records of specific denied capabilities, consuming the shared per-layer quiet member mask in landlock_log_denial(); the rule attribute grows from 16 to 24 bytes.
- Dropped Reviewed-by: Günther Noack and Tingmao Wang, as this version adds the quiet member mask described above, which their v1 review did not cover. Fresh review welcome.
Changes since v1:
https://patch.msgid.link/[email protected]
- Add Reviewed-by: Tingmao Wang.
- Rename internal struct perm_rules to perm_masks (companion change to the preceding commit).
- Rename LANDLOCK_PERM_NAMESPACE_ENTER references to LANDLOCK_PERM_NAMESPACE_USE (companion change to the introducing commit).
- Rename struct layer_rights to struct layer_config (companion change to the introducing commit).
- Clarify in the commit body and hook_capable() kdoc that commoncap (not Landlock) is registered with LSM_ORDER_FIRST.
- Surface the empty-check semantics in the landlock_capability_attr.capabilities kdoc: a rule that sets only bits unknown to the running kernel (above CAP_LAST_CAP) succeeds but has no runtime effect.
- Add explicit static_assert that LANDLOCK_NUM_PERM_CAP + LANDLOCK_NUM_PERM_NS fits in a u64, complementing the existing implicit sizeof guard on struct perm_masks.
- Add Reviewed-by: Günther Noack.
--- include/linux/landlock.h | 5 +- include/trace/events/landlock.h | 96 +++++++++++++++++++ include/uapi/linux/landlock.h | 49 ++++++++++ security/landlock/Makefile | 3 +- security/landlock/access.h | 10 +- security/landlock/audit.c | 4 + security/landlock/cap.c | 163 ++++++++++++++++++++++++++++++++ security/landlock/cap.h | 48 ++++++++++ security/landlock/domain.h | 3 + security/landlock/limits.h | 4 +- security/landlock/log.c | 10 ++ security/landlock/log.h | 1 + security/landlock/setup.c | 2 + security/landlock/syscalls.c | 95 ++++++++++++++++++- security/landlock/trace.c | 12 +++ 15 files changed, 498 insertions(+), 7 deletions(-) create mode 100644 security/landlock/cap.c create mode 100644 security/landlock/cap.h
include/linux/landlock.h +4 -1
@@ -56,10 +56,13 @@ _LANDLOCK_NAME_ENTRY(LANDLOCK_SCOPE_SIGNAL, "signal")#define _LANDLOCK_PERMISSION_NAMESPACE_NAME "namespace" +#define _LANDLOCK_PERMISSION_CAPABILITY_NAME "capability"#define _LANDLOCK_PERMISSION_LIST (entry) \ entry(LANDLOCK_PERMISSION_NAMESPACE_USE, "use", \ - _LANDLOCK_PERMISSION_NAMESPACE_NAME) + _LANDLOCK_PERMISSION_NAMESPACE_NAME), \ + entry(LANDLOCK_PERMISSION_CAPABILITY_USE, "use", \ + _LANDLOCK_PERMISSION_CAPABILITY_NAME)#define _LANDLOCK_PERMISSION_QUALIFIED_ENTRY (mask, action, domain) \ _LANDLOCK_NAME_ENTRY(mask, domain "." action)
include/trace/events/landlock.h +96 -0
114 lines not on this page · raw message
include/uapi/linux/landlock.h +49 -0
68 lines not on this page · raw message
security/landlock/Makefile +2 -1
@@ -10,7 +10,8 @@ landlock-y := \ fs.o \ tsync.o \ domain.o \ - ns.o + ns.o \ + cap.o landlock-$(CONFIG_INET) += net.o
security/landlock/access.h +9 -1
@@ -73,16 +73,24 @@ struct permission_masks {* order. */ u64 ns_types : LANDLOCK_NUM_NAMESPACE_TYPE; +/** +* @caps: Capability member mask, indexed by CAP_* values. +*/ + u64 caps : LANDLOCK_NUM_CAPABILITY; } __packed__aligned(sizeof(u64)) ;static_assert (sizeof (struct permission_masks ) ==sizeof (u64)); +/* All permission_masks bitfields must fit in a single u64. */ +static_assert (LANDLOCK_NUM_CAPABILITY +LANDLOCK_NUM_NAMESPACE_TYPE <= +BITS_PER_TYPE (u64));/** * struct layer_config - Per-layer access configuration * * A ruleset stores one mutable layer and a domain stores a flexible array of * immutable layers. Unlike filesystem and network access rights, namespace -* types use a flat bitmask because their keyspace is small and bounded. +* types and capabilities use flat bitmasks because their keyspaces are small +* and bounded. */ struct layer_config {/**
security/landlock/audit.c +4 -0
@@ -81,6 +81,7 @@ get_blocker(const enum landlock_request_type type,return scope_strings[BIT_INDEX (LANDLOCK_SCOPE_SIGNAL )];case LANDLOCK_REQUEST_NAMESPACE : +case LANDLOCK_REQUEST_CAPABILITY :if (WARN_ON_ONCE (access_bit >=ARRAY_SIZE (permission_strings)))return "unknown" ;return permission_strings[access_bit];
@@ -116,6 +117,9 @@ blocker_prefix(const enum landlock_request_type type)case LANDLOCK_REQUEST_NAMESPACE :return _LANDLOCK_PERMISSION_NAMESPACE_NAME"." ; + +case LANDLOCK_REQUEST_CAPABILITY : +return _LANDLOCK_PERMISSION_CAPABILITY_NAME"." ; }WARN_ON_ONCE (1 );
security/landlock/cap.c new file +163 -0
163 lines not on this page · raw message
security/landlock/cap.h new file +48 -0
48 lines not on this page · raw message
security/landlock/domain.h +3 -0
@@ -371,6 +371,9 @@ landlock_permission_is_denied(const struct landlock_domain *const domain,case LANDLOCK_PERMISSION_NAMESPACE_USE : allowed = domain->layers[layer].allowed.ns_types;break ; +case LANDLOCK_PERMISSION_CAPABILITY_USE : + allowed = domain->layers[layer].allowed.caps; +break ;default :WARN_ONCE (1 ,"Unknown permission %u\n" , (unsigned int )permission_bit);
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_PERMISSION LANDLOCK_PERMISSION_NAMESPACE_USE +#define LANDLOCK_LAST_PERMISSION LANDLOCK_PERMISSION_CAPABILITY_USE#define LANDLOCK_MASK_PERMISSION ((LANDLOCK_LAST_PERMISSION << 1) - 1)#define LANDLOCK_NUM_PERMISSION __const_hweight64(LANDLOCK_MASK_PERMISSION)#define LANDLOCK_NUM_NAMESPACE_TYPE __const_hweight64((u64)CLONE_NS_ALL) +#define LANDLOCK_NUM_CAPABILITY (CAP_LAST_CAP + 1)#define LANDLOCK_NUM_ACCESS_MAX \ MAX(MAX(LANDLOCK_NUM_ACCESS_FS, LANDLOCK_NUM_ACCESS_NET), LANDLOCK_NUM_SCOPE)
security/landlock/log.c +10 -0
@@ -12,6 +12,7 @@#include "access.h" #include "audit.h" +#include "cap.h" #include "common.h" #include "cred.h" #include "domain.h"
@@ -393,6 +394,12 @@ static bool is_valid_request(const struct landlock_request *const request) WARN_ON_ONCE(request->audit.type != LSM_AUDIT_DATA_NS))return false;break ; +case LANDLOCK_REQUEST_CAPABILITY : +if (WARN_ON_ONCE (request->permission != +LANDLOCK_PERMISSION_CAPABILITY_USE ) || +WARN_ON_ONCE (request->audit.type !=LSM_AUDIT_DATA_CAP )) +return false; +break ;case LANDLOCK_REQUEST_PTRACE :case LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY :case LANDLOCK_REQUEST_FS_ACCESS :
@@ -481,6 +488,9 @@ is_denial_quieted(const struct landlock_request *const request,case LANDLOCK_REQUEST_NAMESPACE :return !!(youngest_denied->quiet_permission.ns_types &landlock_ns_type_to_bit (request->audit.u.ns.ns_type)); +case LANDLOCK_REQUEST_CAPABILITY : +return !!(youngest_denied->quiet_permission.caps & +landlock_cap_to_bit (request->audit.u.cap));/* * Leave LANDLOCK_REQUEST_PTRACE and LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY * unhandled for now - they are never quiet.
security/landlock/log.h +1 -0
@@ -26,6 +26,7 @@ enum landlock_request_type {LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET ,LANDLOCK_REQUEST_SCOPE_SIGNAL ,LANDLOCK_REQUEST_NAMESPACE , + LANDLOCK_REQUEST_CAPABILITY, }; struct landlock_blockers {
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 +92 -3
144 lines not on this page · raw message
security/landlock/trace.c +12 -0
@@ -94,6 +94,18 @@ void landlock_trace_denial( request->audit.u.ns.ns_id); }break ; +case LANDLOCK_REQUEST_CAPABILITY : +if (trace_landlock_deny_permission_capability_enabled ()) { +const struct landlock_blockers blockers = { + .access = missing, + .type = request->type, + }; + +trace_landlock_deny_permission_capability ( + youngest_denied, same_exec, logged, &blockers, + request->audit.u.cap); + } +break ;case LANDLOCK_REQUEST_FS_ACCESS :case LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY :if (trace_landlock_deny_access_fs_enabled ()) {
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v4 4/8] landlock: Enforce capability restrictions
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 14 lines
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_PERMISSION_CAPABILITY_USEand per-capability rules.The check is a flat per-layer allowed-capabilities test, with no domain-ancestry bypass, no cross-namespace discriminant, and no dependency on the target user namespace. These categorical denials return
-EPERM, like the namespace permission introduced by the previous commit, and they mirror its per-capability allowed and quiet masks, soLANDLOCK_ADD_RULE_QUIETstays rejected for this rule type. Successful capability rules and denials are traced as the previous commit describes.
Quoted 7 lines
Enforce only at capability exercise time rather than modifying the
[ ... ]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]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Mickaël Salaün
maintainerPATCH v4 5/8 selftests/landlock: Add namespace restriction tests
In reply to Mickaël SalaünAdd tests covering LANDLOCK_PERMISSION_NAMESPACE_USE (namespace creation via unshare/clone and namespace entry via setns) and its interaction with LANDLOCK_PERMISSION_CAPABILITY_USE.
Rule validation covers the forward-compatibility contract: unknown CLONE_NEW* bits, including holes, upper-range bits and bit 63, are accepted at rule-add time yet have no runtime effect, because deny-by-default still applies once the domain is enforced. Empty masks, invalid permission selectors and non-zero flags are rejected.
Creation tests use FIXTURE_VARIANT to exercise all eight namespace types across allowed/denied and privileged/unprivileged combinations, so every type is shown to reach security_namespace_init(). Stacking tests cover the three per-layer allow/deny combinations that exercise distinct walker paths, and one domain handles both permissions at once.
Entry tests subject setns to the same type-based check through security_namespace_install(), across processes, and require both permissions to allow a non-user namespace.
The four open_tree(2) and fsmount(2) variants, anonymous and not, all create a mount namespace: they converge in security_namespace_init() with CLONE_NEWNS through different alloc_mnt_ns() paths. A CLONE_NEWUSER | CLONE_NEWUTS unshare under partial-allow rules shows that creation is sequential, so a denial on either type rolls the whole syscall back with EPERM.
Audit tests cover allowed and denied creation and entry, per-member quiet masks and the youngest-denying-layer rule. Trace tests cover handled permissions, successful and rejected rules, version history, namespace IDs, and quiet denials, including repeated and unknown-only effective no-ops.
---
Changes since v3:
https://patch.msgid.link/[email protected]
- Cover the EFAULT result for an invalid namespace rule pointer.
- Drop CAP_AUDIT_CONTROL after cleaning up the audit fixture.
- Add trace tests for handled permissions, successful and rejected rules, namespace IDs, and quiet denials, including repeated and unknown-only effective no-ops.
- Make the successful clone3 assertion fatal before passing its PID to waitpid().
Changes since v2:
https://patch.msgid.link/[email protected]
- Rebased for ABI 11 and the renamed namespace rule attribute (perm plus allowed_namespace_types/quiet_namespace_types).
- Add per-member quiet audit tests for the namespace permission:
create_quieted, quiet_is_per_member, allow_and_quiet, allow_and_quiet_same_member (quiet on an allowed member is inert), quiet_youngest_layer_wins, and quiet_parent_only_denying_layer, plus a quiet-only-rule leg in add_rule_bad_attr and the add_ns_rule_full helper.
- Add a positive both-caps mount setns leg (two_perm_mnt_setns_allowed) and the both-perms inverse test two_perm_ns_denied (the capability is allowed but the namespace type is not, so the namespace hook denies).
- Add two_perm_combined_unshare_denied and two_perm_combined_unshare_allowed: combining CLONE_NEWUSER with another type in a single unshare(2) does not exempt the non-user namespace from the capability check, so it still requires an allowed CAP_SYS_ADMIN when the domain handles LANDLOCK_PERM_CAPABILITY_USE.
- Add add_rule_unknown_no_runtime_effect_setns, the install-hook mirror of the creation-hook unknown-bit test.
- Add ns_audit.setns_quieted (a quieted setns denial is still EPERM but unlogged) and ns_audit.quiet_unknown_bit_no_effect (an unknown quiet bit does not suppress a known denial).
- Trim ns_proc_open to two representative types (user and mnt): opening /proc/self/ns/* never reaches a Landlock hook and the path is namespace-type-agnostic, so the other per-type variants added no coverage.
Changes since v1:
https://patch.msgid.link/[email protected]
- Update audit test patterns: namespace_inum replaced by namespace_id.
- Fix user_denied.setns expected error: security_namespace_install() now runs before userns_install(), so Landlock returns EPERM before userns_install() returns EINVAL.
- Rename LANDLOCK_PERM_NAMESPACE_ENTER references to LANDLOCK_PERM_NAMESPACE_USE (companion change to the introducing commit).
- Add ns_proc_open fixture covering all 8 namespace types: verify that open("/proc/self/ns/<type>", O_RDONLY) does not trigger Landlock denial under LANDLOCK_PERM_NAMESPACE_USE. Defensive boundary documentation that the procfs ns/<type> open path is outside the per-category permission's scope; catches future regressions if a hook is misplaced.
- Add ns_mount_fd fixture covering open_tree(OPEN_TREE_CLONE), open_tree(OPEN_TREE_NAMESPACE), fsmount(FSMOUNT_CLOEXEC), and fsmount(FSMOUNT_NAMESPACE) with denied/allowed/unsandboxed variants. All four converge in security_namespace_init() with CLONE_NEWNS but exercise different code paths through alloc_mnt_ns().
- Add ns_create_multi_flag fixture covering a combined unshare with CLONE_NEWUSER | CLONE_NEWUTS under partial-allow rules: documents that any Landlock denial in the sequential namespace creation rolls back the entire syscall with EPERM.
- Reshape setns_cross_process variants: rename allowed to sandboxed_allowed and add an unsandboxed variant, so the fixture now covers denied, sandboxed_allowed, and unsandboxed.
- Add sys_open_tree, sys_fsopen, sys_fsconfig, sys_fsmount syscall wrappers in wrappers.h, and update fs_test.c to use sys_open_tree instead of its local open_tree wrapper.
- Rename comments referencing security_namespace_alloc() and hook_namespace_alloc() to security_namespace_init() and hook_namespace_init() (companion change to the LSM hook rename in the introducing commit).
- Document that setns_cross_process exercises only CLONE_NEWUTS:
the same enforcement applies to every namespace type via the unified hook_namespace_install() helper.
- Add add_rule_unknown_no_runtime_effect: assert that a rule listing only unknown namespace bits is accepted at rule-add time but has no runtime effect, so an actual CLONE_NEW* operation is still denied by deny-by-default once the domain is enforced.
- Add ns_stacking parent_denies variant covering the inverse direction of stacking: layer 1 denies, layer 2 allows, operation still denied. Completes the per-layer walker direction coverage.
--- tools/testing/selftests/landlock/common.h | 23 + tools/testing/selftests/landlock/config | 5 + tools/testing/selftests/landlock/fs_test.c | 13 +- tools/testing/selftests/landlock/ns_test.c | 2643 +++++++++++++++++++ tools/testing/selftests/landlock/trace.h | 25 + tools/testing/selftests/landlock/wrappers.h | 29 + 6 files changed, 2728 insertions(+), 10 deletions(-) create mode 100644 tools/testing/selftests/landlock/ns_test.c
tools/testing/selftests/landlock/common.h +23 -0
@@ -130,6 +130,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
@@ -5,6 +5,7 @@ CONFIG_CGROUP_SCHED=y CONFIG_ENABLE_DEFAULT_TRACERS=y CONFIG_FTRACE=y CONFIG_INET=y +CONFIG_IPC_NS=y CONFIG_IPV6=y CONFIG_KEYS=y CONFIG_MPTCP=y
@@ -12,10 +13,14 @@ CONFIG_MPTCP_IPV6=y CONFIG_NET=y CONFIG_NET_NS=y CONFIG_OVERLAY_FS=y +CONFIG_PID_NS=y CONFIG_PROC_FS=y CONFIG_SECURITY=y CONFIG_SECURITY_LANDLOCK=y CONFIG_SHMEM=y CONFIG_SYSFS=y +CONFIG_TIME_NS=y CONFIG_TMPFS=y CONFIG_TMPFS_XATTR=y +CONFIG_USER_NS=y +CONFIG_UTS_NS=y
tools/testing/selftests/landlock/fs_test.c +3 -10
@@ -57,13 +57,6 @@ int renameat2(int olddirfd, const char *oldpath, int newdirfd, }#endif -#ifndef open_tree -int open_tree (int dfd,const char *filename,unsigned int flags) -{ -return syscall (__NR_open_tree, dfd, filename, flags); -} -#endif -static int sys_execveat (int dirfd,const char *pathname,char *const argv[],char *const envp[],int flags) {
@@ -2628,9 +2621,9 @@ TEST_F_FORK(layout1, refer_mount_root_deny)/* Creates a mount object from a non-mount point. */ set_cap (_metadata,CAP_SYS_ADMIN ); - root_fd = -open_tree (AT_FDCWD , dir_s1d1, -AT_EMPTY_PATH |OPEN_TREE_CLONE |OPEN_TREE_CLOEXEC ); + root_fd =sys_open_tree (AT_FDCWD , dir_s1d1, +AT_EMPTY_PATH |OPEN_TREE_CLONE | +OPEN_TREE_CLOEXEC );clear_cap (_metadata,CAP_SYS_ADMIN );ASSERT_LE (0 , root_fd);
tools/testing/selftests/landlock/ns_test.c new file +2643 -0
2,643 lines not on this page · raw message
tools/testing/selftests/landlock/trace.h +25 -0
@@ -31,6 +31,8 @@ TRACEFS_LANDLOCK_DIR "/landlock_add_rule_path_beneath/enable"#define TRACEFS_ADD_RULE_NET_PORT_ENABLE \ TRACEFS_LANDLOCK_DIR "/landlock_add_rule_net_port/enable" +#define TRACEFS_ADD_RULE_NAMESPACE_ENABLE \ + TRACEFS_LANDLOCK_DIR "/landlock_add_rule_namespace/enable"#define TRACEFS_CHECK_RULE_FS_ENABLE \ TRACEFS_LANDLOCK_DIR "/landlock_check_rule_inode/enable"#define TRACEFS_CHECK_RULE_NET_ENABLE \
@@ -39,6 +41,8 @@ TRACEFS_LANDLOCK_DIR "/landlock_deny_access_fs/enable"#define TRACEFS_DENY_ACCESS_NET_ENABLE \ TRACEFS_LANDLOCK_DIR "/landlock_deny_access_net/enable" +#define TRACEFS_DENY_PERMISSION_NAMESPACE_ENABLE \ + TRACEFS_LANDLOCK_DIR "/landlock_deny_permission_namespace/enable"#define TRACEFS_DENY_PTRACE_ENABLE \ TRACEFS_LANDLOCK_DIR "/landlock_deny_ptrace/enable"#define TRACEFS_DENY_SCOPE_SIGNAL_ENABLE \
@@ -95,6 +99,17 @@"access_rights=[a-z_|]* " \ "port=[0-9]\\+$" +#define REGEX_ADD_RULE_NAMESPACE_VERSION (task, version) \ + TRACE_PREFIX(task) \ + "landlock_add_rule_namespace: " \ + "ruleset=[0-9a-f]\\+\\." version " " \ + "permissions=[a-z._|]* " \ + "allowed_namespace_types=0x[0-9a-f]\\+ " \ + "quiet_namespace_types=0x[0-9a-f]\\+$" + +#define REGEX_ADD_RULE_NAMESPACE (task) \ + REGEX_ADD_RULE_NAMESPACE_VERSION(task, "[0-9]\\+") +#define REGEX_CREATE_RULESET (task) \ TRACE_PREFIX(task) \ "landlock_create_ruleset: " \
@@ -148,6 +163,16 @@"blockers=[a-z_|]* " \ "port=-\\?[0-9]\\+$" +#define REGEX_DENY_PERMISSION_NAMESPACE (task) \ + TRACE_PREFIX(task) \ + "landlock_deny_permission_namespace: " \ + "domain=[0-9a-f]\\+ " \ + "same_exec=[01] " \ + "logged=[01] " \ + "blockers=[a-z_|]* " \ + "namespace_type=0x[0-9a-f]\\+ " \ + "namespace_id=[0-9]\\+$" +#define REGEX_DENY_PTRACE (task) \ TRACE_PREFIX(task) \ "landlock_deny_ptrace: " \
tools/testing/selftests/landlock/wrappers.h +29 -0
@@ -9,6 +9,7 @@#define _GNU_SOURCE#include <linux/landlock.h> +#include <linux/sched.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h>
@@ -45,3 +46,31 @@ static inline pid_t sys_gettid(void) {return syscall (__NR_gettid); } + +static inline pid_t sys_clone3 (struct clone_args *args,size_t size) +{ +return syscall (__NR_clone3, args, size); +} + +static inline int sys_open_tree (int dfd,const char *filename, +unsigned int flags) +{ +return syscall (__NR_open_tree, dfd, filename, flags); +} + +static inline int sys_fsopen (const char *fsname,unsigned int flags) +{ +return syscall (__NR_fsopen, fsname, flags); +} + +static inline int sys_fsconfig (int fs_fd,unsigned int cmd,const char *key, +const void *value,int aux) +{ +return syscall (__NR_fsconfig, fs_fd, cmd, key, value, aux); +} + +static inline int sys_fsmount (int fs_fd,unsigned int flags, +unsigned int attr_flags) +{ +return syscall (__NR_fsmount, fs_fd, flags, attr_flags); +}
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v4 5/8] selftests/landlock: Add namespace restriction tests
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] selftests/landlock: Data truncation of 64-bit namespace flags in audit log string matching --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] selftests/landlock: Data truncation of 64-bit namespace flags in audit log string matching --
commit 5fd29f953c165adc6df65241e36e43cef7dbf0ae
Author: Mickaël Salaün <[email protected]>
selftests/landlock: Add namespace restriction tests
This commit adds extensive tests for the LANDLOCK_PERMISSION_NAMESPACE_USE restriction, covering namespace creation and entry. It includes rule validation, forward compatibility checks, layer stacking, and audit logging.
Quoted 5 lines
tools/testing/selftests/landlock/ns_test.c new file +0
-0
[ ... ]
tools/testing/selftests/landlock/ns_test.c line 1902
Quoted 9 lines
tools/testing/selftests/landlock/ns_test.c new file +9
-0+static int matches_log_ns_create (int audit_fd,__u64 ns_type) +{ +static const char log_template[] =REGEX_LANDLOCK_PREFIX +" blockers=namespace\\.use namespace_type=0x%x namespace_id=0$" ; +char log_match[sizeof (log_template) +10 ]; +int log_match_len; + + log_match_len =snprintf (log_match,sizeof (log_match), log_template, + (unsigned int )ns_type);
[Severity: Low]
Does this format string risk truncating the ns_type value? The ns_type parameter is a 64-bit __u64, but it is explicitly cast to unsigned int and formatted with %x. If a namespace flag exceeding 32 bits is ever tested, the upper 32 bits will be truncated, producing an incorrect audit log match string and causing test failures.
Quoted 7 lines
tools/testing/selftests/landlock/ns_test.c new file +7
-0+if (log_match_len >=sizeof (log_match)) +return -E2BIG ; + +return audit_match_record (audit_fd,AUDIT_LANDLOCK_ACCESS , log_match, +NULL ); +} +
tools/testing/selftests/landlock/ns_test.c line 1919
Quoted 10 lines
tools/testing/selftests/landlock/ns_test.c new file +10
-0+static int matches_log_ns_setns (int audit_fd,__u64 ns_type,__u64 ns_id) +{ +static const char log_template[] =REGEX_LANDLOCK_PREFIX +" blockers=namespace\\.use namespace_type=0x%x namespace_id=%llu$" ; +char log_match[sizeof (log_template) +32 ]; +int log_match_len; + + log_match_len =snprintf (log_match,sizeof (log_match), log_template, + (unsigned int )ns_type, + (unsigned long long )ns_id);
[Severity: Low]
This seems to have the same truncation issue as matches_log_ns_create() above. The 64-bit ns_type parameter is cast to a 32-bit unsigned int and formatted with %x, which will drop the upper 32 bits.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Mickaël Salaün
maintainerRe: [PATCH v4 5/8] selftests/landlock: Add namespace restriction tests
Quoted 23 lines · On Fri, Oct 02, 2026 at 12:56:28PM +0000, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] selftests/landlock: Data truncation of 64-bit namespace flags in audit log string matching --commit
5fd29f953c165adc6df65241e36e43cef7dbf0ae
Author: Mickaël Salaün <[email protected]>selftests/landlock: Add namespace restriction tests
This commit adds extensive tests for the
LANDLOCK_PERMISSION_NAMESPACE_USErestriction, covering namespace creation and entry. It includes rule validation, forward compatibility checks, layer stacking, and audit logging.Quoted 5 lines
tools/testing/selftests/landlock/ns_test.c new file +0
-0[ ... ]
Quoted 16 lines
tools/testing/selftests/landlock/ns_test.c line 1902
Quoted 9 lines
tools/testing/selftests/landlock/ns_test.c new file +9
-0+static int matches_log_ns_create (int audit_fd,__u64 ns_type) +{ +static const char log_template[] =REGEX_LANDLOCK_PREFIX +" blockers=namespace\\.use namespace_type=0x%x namespace_id=0$" ; +char log_match[sizeof (log_template) +10 ]; +int log_match_len; + + log_match_len =snprintf (log_match,sizeof (log_match), log_template, + (unsigned int )ns_type);[Severity: Low]
Does this format string risk truncating thens_typevalue? Thens_typeparameter is a 64-bit__u64, but it is explicitly cast to unsigned int and formatted with %x. If a namespace flag exceeding 32 bits is ever tested, the upper 32 bits will be truncated, producing an incorrect audit log match string and causing test failures.
The cast is intentional and doe snot truncate an emitted audit value (which is 32-bit).
Quoted 15 lines
Quoted 15 lines
tools/testing/selftests/landlock/ns_test.c new file +14
-0+if (log_match_len >=sizeof (log_match)) +return -E2BIG ; + +return audit_match_record (audit_fd,AUDIT_LANDLOCK_ACCESS , log_match, +NULL ); +} + +static int matches_log_ns_setns (int audit_fd,__u64 ns_type,__u64 ns_id) +{ +static const char log_template[] =REGEX_LANDLOCK_PREFIX +" blockers=namespace\\.use namespace_type=0x%x namespace_id=%llu$" ; +char log_match[sizeof (log_template) +32 ]; +int log_match_len; +
Quoted 8 lines
tools/testing/selftests/landlock/ns_test.c line 1919
Quoted 3 lines
tools/testing/selftests/landlock/ns_test.c new file +3
-0+ log_match_len =snprintf (log_match,sizeof (log_match), log_template, + (unsigned int )ns_type, + (unsigned long long )ns_id);[Severity: Low]
This seems to have the same truncation issue asmatches_log_ns_create()above. The 64-bitns_typeparameter is cast to a 32-bit unsigned int and formatted with %x, which will drop the upper 32 bits.
No issue here as well.
Quoted 4 lines
Signature · 2 lines
-- Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Mickaël Salaün
maintainerPATCH v4 6/8 selftests/landlock: Add capability restriction tests
In reply to Mickaël SalaünAdd tests to exercise LANDLOCK_PERMISSION_CAPABILITY_USE enforcement. A sandboxed process is denied a handled capability when no rule grants it, and an explicit rule restores it. Unknown capability values above CAP_LAST_CAP are accepted at rule-add time yet have no runtime effect, because deny-by-default still applies once the domain is enforced. Stacking tests cover the per-layer allow/deny combinations, including a layer that does not handle the permission, and invalid rule attributes return the expected errors.
Three tests exercise non-standard capability contexts: enforcing a domain via CAP_SYS_ADMIN authorization without no_new_privs, restricting capabilities gained through the kernel's user namespace ownership bypass (cap_capable_helper), and checking CAP_SYS_ADMIN against a descendant user namespace, with an unsandboxed positive control, to confirm the decision is independent of the target.
Audit tests verify denied and allowed capabilities, per-member quiet interactions, and CAP_OPT_NOAUDIT suppression. Trace tests cover accepted, rejected, and no-op rule adds, and normal, quiet, and CAP_OPT_NOAUDIT denials.
Test coverage for security/landlock is 91.8% of 2864 lines according to LLVM 22.
---
Changes since v3:
https://patch.msgid.link/[email protected]
- Cover the EFAULT result for an invalid capability rule pointer.
- Drop CAP_AUDIT_CONTROL after cleaning up the audit fixture.
- Isolate cap_stacking and cap_audit in private UTS namespaces before their successful sethostname() calls.
- Add trace tests for successful and rejected rules, effective no-ops, and normal, quiet, and CAP_OPT_NOAUDIT denials.
- Extend audit coverage for normal-denial controls, same-member allow/quiet overlap, and youngest-denier behavior.
- Test target-user-namespace independence with an unsandboxed positive control.
Changes since v2:
https://patch.msgid.link/[email protected]
- Rebased for ABI 11 and the renamed capability rule attribute (perm plus allowed_capabilities/quiet_capabilities).
- Add per-member quiet audit tests for the capability permission:
cap_audit.quieted, plus quiet-only and allow+quiet legs in add_rule_bad_attr and the add_cap_rule_full helper.
- add_rule_bad_attr: drop the dead quiet_capabilities reset after the allow+quiet rule and reset it explicitly where the following rule needs an allow-only attr, clarifying intent.
- Strengthen the audit tests with positive controls: cap_audit.quieted and cap_audit.noaudit_probe_not_logged now also assert that a normal (non-quiet, non-noaudit) capability denial in the same domain IS logged, proving suppression is not global. cap_audit.quieted also asserts the quieted capability is still denied (EPERM), not merely unlogged.
- Add cap_audit.quiet_unknown_bit_no_effect (an unknown quiet bit does not suppress a known capability denial).
Changes since v1:
https://patch.msgid.link/[email protected]
- Reflow comments after check-linux.sh comment fixes.
- Rename LANDLOCK_PERM_NAMESPACE_ENTER references to LANDLOCK_PERM_NAMESPACE_USE and bump the abi_version expectation to 11 (companion changes to the introducing commit).
- Add add_rule_unknown_no_runtime_effect: assert that a rule listing only unknown capability bits is accepted at rule-add time but has no runtime effect, so an actual CAP_* exercise (sethostname with CAP_SYS_ADMIN) is still denied by deny-by-default once the domain is enforced.
- Add cap_stacking parent_denies variant covering the inverse direction of stacking: layer 1 denies CAP_SYS_ADMIN, layer 2 allows, capability still denied. Completes the per-layer walker direction coverage.
- Assert records.domain == 0 in cap_audit.allowed so the test also checks that no domain-allocation record is emitted when nothing is denied.
--- tools/testing/selftests/landlock/base_test.c | 19 + tools/testing/selftests/landlock/cap_test.c | 1364 ++++++++++++++++++ tools/testing/selftests/landlock/trace.h | 24 + 3 files changed, 1407 insertions(+) create mode 100644 tools/testing/selftests/landlock/cap_test.c
tools/testing/selftests/landlock/base_test.c +19 -0
@@ -142,6 +142,25 @@ TEST(errata)ASSERT_EQ (EINVAL , errno); } +#define PERMISSION_LAST LANDLOCK_PERMISSION_CAPABILITY_USE + +TEST (ruleset_with_unknown_permission) +{ +__u64 permission_mask; + +for (permission_mask =1ULL <<63 ; permission_mask !=PERMISSION_LAST ; + permission_mask >>=1 ) { +struct landlock_ruleset_attr ruleset_attr = { + .handled_permissions = permission_mask, + }; + +/* Unknown handled_permissions 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 +1364 -0
1,364 lines not on this page · raw message
tools/testing/selftests/landlock/trace.h +24 -0
@@ -33,6 +33,8 @@ TRACEFS_LANDLOCK_DIR "/landlock_add_rule_net_port/enable"#define TRACEFS_ADD_RULE_NAMESPACE_ENABLE \ TRACEFS_LANDLOCK_DIR "/landlock_add_rule_namespace/enable" +#define TRACEFS_ADD_RULE_CAPABILITY_ENABLE \ + TRACEFS_LANDLOCK_DIR "/landlock_add_rule_capability/enable"#define TRACEFS_CHECK_RULE_FS_ENABLE \ TRACEFS_LANDLOCK_DIR "/landlock_check_rule_inode/enable"#define TRACEFS_CHECK_RULE_NET_ENABLE \
@@ -43,6 +45,8 @@ TRACEFS_LANDLOCK_DIR "/landlock_deny_access_net/enable"#define TRACEFS_DENY_PERMISSION_NAMESPACE_ENABLE \ TRACEFS_LANDLOCK_DIR "/landlock_deny_permission_namespace/enable" +#define TRACEFS_DENY_PERMISSION_CAPABILITY_ENABLE \ + TRACEFS_LANDLOCK_DIR "/landlock_deny_permission_capability/enable"#define TRACEFS_DENY_PTRACE_ENABLE \ TRACEFS_LANDLOCK_DIR "/landlock_deny_ptrace/enable"#define TRACEFS_DENY_SCOPE_SIGNAL_ENABLE \
@@ -110,6 +114,17 @@#define REGEX_ADD_RULE_NAMESPACE (task) \ REGEX_ADD_RULE_NAMESPACE_VERSION(task, "[0-9]\\+") +#define REGEX_ADD_RULE_CAPABILITY_VERSION (task, version) \ + TRACE_PREFIX(task) \ + "landlock_add_rule_capability: " \ + "ruleset=[0-9a-f]\\+\\." version " " \ + "permissions=[a-z._|]* " \ + "allowed_capabilities=0x[0-9a-f]\\+ " \ + "quiet_capabilities=0x[0-9a-f]\\+$" + +#define REGEX_ADD_RULE_CAPABILITY (task) \ + REGEX_ADD_RULE_CAPABILITY_VERSION(task, "[0-9]\\+") +#define REGEX_CREATE_RULESET (task) \ TRACE_PREFIX(task) \ "landlock_create_ruleset: " \
@@ -173,6 +188,15 @@"namespace_type=0x[0-9a-f]\\+ " \ "namespace_id=[0-9]\\+$" +#define REGEX_DENY_PERMISSION_CAPABILITY (task) \ + TRACE_PREFIX(task) \ + "landlock_deny_permission_capability: " \ + "domain=[0-9a-f]\\+ " \ + "same_exec=[01] " \ + "logged=[01] " \ + "blockers=[a-z_|]* " \ + "capability=[0-9]\\+$" +#define REGEX_DENY_PTRACE (task) \ TRACE_PREFIX(task) \ "landlock_deny_ptrace: " \
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v4 6/8] selftests/landlock: Add capability restriction tests
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] selftests/landlock: host hostname modification in cap_without_nnp test failure --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] selftests/landlock: host hostname modification in cap_without_nnp test failure --
commit 359c59ecc043d1cac20779ee8cc6bc19e3b8e705
Author: Mickaël Salaün <[email protected]> selftests/landlock: Add capability restriction tests
This commit adds tests to exercise capability restrictions enforced by Landlock. It covers various standard capability evaluations, stacking combinations, and non-standard contexts such as enforcing a domain without no_new_privs.
Quoted 5 lines
tools/testing/selftests/landlock/cap_test.c new file +0
-0
[ ... ]
Quoted 16 lines
tools/testing/selftests/landlock/cap_test.c new file +16
-0+TEST (cap_without_nnp) +{ +int ruleset_fd; + +disable_caps (_metadata); + + ruleset_fd =create_cap_ruleset (); +ASSERT_LE (0 , ruleset_fd); + +/* Allow CAP_SYS_CHROOT but not CAP_SYS_ADMIN. */ +ASSERT_EQ (0 ,add_cap_rule (ruleset_fd,CAP_SYS_CHROOT )); + +/* +* Enforce WITHOUT NNP: landlock_restrict_self() succeeds when the +* caller has CAP_SYS_ADMIN (checked before the new domain takes +* effect).
tools/testing/selftests/landlock/cap_test.c line 583
Quoted 10 lines
tools/testing/selftests/landlock/cap_test.c new file +10
-0+*/ +set_cap (_metadata,CAP_SYS_ADMIN ); +ASSERT_EQ (0 ,landlock_restrict_self (ruleset_fd,0 )); +EXPECT_EQ (0 ,close (ruleset_fd)); + +/* +* CAP_SYS_ADMIN is still in effective set but Landlock denies it: +* cap_capable() returns 0, then hook_capable() returns -EPERM. +*/ +EXPECT_EQ (-1 ,sethostname ("test" ,4 ));
[Severity: Medium]
Will this modify the host system's hostname if the test fails?
The cap_without_nnp test does not appear to isolate its UTS namespace via unshare(CLONE_NEWUTS) before verifying the sethostname() restriction. If the Landlock enforcement does not block the operation during a failing test run, could the sethostname("test", 4) call succeed and unexpectedly change the test machine's global hostname?
Quoted 6 lines
tools/testing/selftests/landlock/cap_test.c new file +6
-0+EXPECT_EQ (EPERM , errno); + +/* CAP_SYS_CHROOT is allowed by the rule. */ +set_cap (_metadata,CAP_SYS_CHROOT ); +EXPECT_EQ (0 ,chroot ("/" )); +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
Mickaël Salaün
maintainerRe: [PATCH v4 6/8] selftests/landlock: Add capability restriction tests
Quoted 49 lines · On Fri, Oct 02, 2026 at 12:53:55PM +0000, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] selftests/landlock: host hostname modification incap_without_nnptest failure --commit
359c59ecc043d1cac20779ee8cc6bc19e3b8e705
Author: Mickaël Salaün <[email protected]> selftests/landlock: Add capability restriction testsThis commit adds tests to exercise capability restrictions enforced by Landlock. It covers various standard capability evaluations, stacking combinations, and non-standard contexts such as enforcing a domain without
no_new_privs.Quoted 5 lines
tools/testing/selftests/landlock/cap_test.c new file +0
-0[ ... ]
Quoted 16 lines
tools/testing/selftests/landlock/cap_test.c new file +16
-0+TEST (cap_without_nnp) +{ +int ruleset_fd; + +disable_caps (_metadata); + + ruleset_fd =create_cap_ruleset (); +ASSERT_LE (0 , ruleset_fd); + +/* Allow CAP_SYS_CHROOT but not CAP_SYS_ADMIN. */ +ASSERT_EQ (0 ,add_cap_rule (ruleset_fd,CAP_SYS_CHROOT )); + +/* +* Enforce WITHOUT NNP: landlock_restrict_self() succeeds when the +* caller has CAP_SYS_ADMIN (checked before the new domain takes +* effect). tools/testing/selftests/landlock/cap_test.c line 583
Quoted 10 lines
tools/testing/selftests/landlock/cap_test.c new file +10
-0+*/ +set_cap (_metadata,CAP_SYS_ADMIN ); +ASSERT_EQ (0 ,landlock_restrict_self (ruleset_fd,0 )); +EXPECT_EQ (0 ,close (ruleset_fd)); + +/* +* CAP_SYS_ADMIN is still in effective set but Landlock denies it: +* cap_capable() returns 0, then hook_capable() returns -EPERM. +*/ +EXPECT_EQ (-1 ,sethostname ("test" ,4 ));[Severity: Medium]
Will this modify the host system's hostname if the test fails?
Quoted 5 lines
The
cap_without_nnptest does not appear to isolate its UTS namespace viaunshare(CLONE_NEWUTS)before verifying thesethostname()restriction. If the Landlock enforcement does not block the operation during a failing test run, could thesethostname("test", 4)call succeed and unexpectedly change the test machine's global hostname?
I'll fix these issues.
Quoted 11 lines
Quoted 7 lines
tools/testing/selftests/landlock/cap_test.c new file +6
-0+EXPECT_EQ (EPERM , errno); + +/* CAP_SYS_CHROOT is allowed by the rule. */ +set_cap (_metadata,CAP_SYS_CHROOT ); +EXPECT_EQ (0 ,chroot ("/" )); +}Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
Mickaël Salaün
maintainerPATCH v4 7/8 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. LL_CAP takes a colon-delimited list of allowed capabilities, parsed with cap_from_name(3) from libcap so names and numeric strings are both accepted. LL_NS takes a colon-delimited list of allowed namespace types by short name. Add best-effort degradation for older kernels that predate the LANDLOCK_PERMISSION_* features.
Allow creating user and UTS namespaces but deny network namespaces, as an unprivileged user. The first command succeeds and sets the hostname inside the new UTS namespace; the second is denied because the network namespace type is not allowed:
LL_FS_RO=/ LL_FS_RW=/proc LL_NS="user:uts" \
./sandboxer /bin/sh -c \
"unshare --user --uts --map-root-user hostname sandbox \
&& ! unshare --user --net true"Allow only user namespace creation and CAP_SYS_CHROOT, denying all other capabilities and namespace types. An unprivileged process creates a user namespace, which requires no capability, and calls chroot inside it using the CAP_SYS_CHROOT granted within that namespace:
LL_FS_RO=/ LL_FS_RW="" LL_NS="user" LL_CAP="cap_sys_chroot" \
./sandboxer /bin/sh -c \
"unshare --user --keep-caps chroot / true"Allow user namespace creation but deny network namespaces, and quiet the network-namespace denials with LL_NS_QUIET so the denied creation is not audit logged. The negated second command makes the whole line succeed:
LL_FS_RO=/ LL_FS_RW=/proc LL_NS="user" LL_NS_QUIET="net" \
./sandboxer /bin/sh -c \
"unshare --user --map-root-user true && ! unshare --user --net true"---
Changes since v3:
https://patch.msgid.link/[email protected]
- Bump the sample's latest supported ABI to 12.
- Gate namespace and capability permissions and rule calls on ABI 12. Consume unsupported settings before executing the sandboxed command.
- Reject capability numbers that cannot fit in the UAPI's 64-bit mask.
- Expand the Kconfig help from filesystem-only wording to the complete sandboxer policy and state the libcap development-file dependency.
- Clarify that quiet capability and namespace members suppress audit logging, and that quieting alone still restricts the permission.
Changes since v2:
https://patch.msgid.link/[email protected]
- Rebased for ABI 11: bump LANDLOCK_ABI_LAST to 11 and extend the ABI back-compat fall-through with a new case stripping the LANDLOCK_PERM_* handled bits for ABI < 11.
- Adopt the renamed capability and namespace rule attributes: the rule bodies use perm plus allowed_capabilities / allowed_namespace_types (matching the per-member quiet restructuring in the enforcement patches).
- Add LL_CAP_QUIET and LL_NS_QUIET to quiet capability and namespace-type denials (per-member, merged into the allowed rule).
Changes since v1:
https://patch.msgid.link/[email protected]
- Rename LANDLOCK_PERM_NAMESPACE_ENTER references to LANDLOCK_PERM_NAMESPACE_USE (companion change to the introducing commit).
- Replace handled_perm = 0 with a per-bit mask in the ABI compat fall-through, mirroring the doc example so future ABI extensions adding new LANDLOCK_PERM_* bits do not get stripped.
- Parse LL_CAP values with cap_from_name(3) from libcap so users can pass capability names (e.g. "cap_sys_chroot") in addition to numbers. cap_from_name accepts both: the canonical name lookup is case-insensitive, and a numeric-string fallback maps "18" to CAP_SYS_CHROOT identically to the previous numeric-only path. Drop the BITS_PER_TYPE workaround and the manual numeric bound check (cap_from_name does the right thing in both cases). Link the sandboxer against libcap by adding userldlibs += -lcap in samples/landlock/Makefile. Update help text and example command to show capability names (suggested by Günther Noack).
- Rename the LL_CAPS env var to LL_CAP for consistency with the singular form of all other sandboxer env vars (LL_NS, LL_FS_RO, LL_FS_RW, LL_TCP_BIND, LL_TCP_CONNECT, LL_SCOPED, LL_FORCE_LOG). Internal symbols renamed accordingly: ENV_CAPS_NAME -> ENV_CAP_NAME, populate_ruleset_caps() -> populate_ruleset_cap().
- Tingmao Wang's v1 Reviewed-by is not carried forward to v2: the cap_from_name() / libcap migration is a material implementation change requested by Günther Noack that was not part of his review. Cc'd instead.
--- samples/Kconfig | 6 +- samples/landlock/Makefile | 1 + samples/landlock/sandboxer.c | 230 ++++++++++++++++++++++++++++++++++- 3 files changed, 232 insertions(+), 5 deletions(-)
samples/Kconfig +4 -2
@@ -166,8 +166,10 @@ config SAMPLE_LANDLOCK bool "Landlock example" depends on CC_CAN_LINK && HEADERS_INSTALL help - Build a simple Landlock sandbox manager able to start a process - restricted by a user-defined filesystem access control policy. + Build a Landlock sandbox manager able to start a process restricted + by user-defined filesystem, network, scope, namespace, and capability + policies. This sample requires the libcap development headers and + library. config SAMPLE_PIDFD bool "pidfd sample"
samples/landlock/Makefile +1 -0
@@ -3,6 +3,7 @@ userprogs-always-y := sandboxer userccflags += -I usr/include +userldlibs += -lcap .PHONY: all clean
samples/landlock/sandboxer.c +227 -3
306 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v4 7/8] samples/landlock: Add capability and namespace restriction support
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Low] build: sample landlock fails on systems without libcap-dev - [Low] build: missing fallback for…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Low] build: sample landlock fails on systems without libcap-dev
- [Low] build: missing fallback for CLONE_NEWTIME breaks build on glibc < 2.33 --
commit c88aebdbd55f6c34b61885d4e3d918bc61983af0
Author: Mickaël Salaün <[email protected]>
samples/landlock: Add capability and namespace restriction support
This commit extends the sandboxer sample to demonstrate new Landlock capability and namespace restriction features. It allows parsing allowed namespaces and capabilities using libcap, adding appropriate command line arguments for testing.
Quoted 17 lines
samples/Kconfig +4
-2@@ -166,8 +166,10 @@ config SAMPLE_LANDLOCK bool "Landlock example" depends on CC_CAN_LINK && HEADERS_INSTALL help - Build a simple Landlock sandbox manager able to start a process - restricted by a user-defined filesystem access control policy. + Build a Landlock sandbox manager able to start a process restricted + by user-defined filesystem, network, scope, namespace, and capability + policies. This sample requires the libcap development headers and + library. config SAMPLE_PIDFD bool "pidfd sample"
[ ... ]
samples/landlock/Makefile line 6
Quoted 9 lines
samples/landlock/Makefile +1
-0@@ -3,6 +3,7 @@ userprogs-always-y := sandboxer userccflags += -I usr/include +userldlibs += -lcap
[Severity: Low]
Does this unconditional linking cause build failures during make allmodconfig or make samples if the host system lacks the libcap-dev library?
Since the Kconfig does not verify the presence of the libcap library (for example, using a $(success,...) check), the build will unconditionally attempt to link against it and fail when the dependency is missing. Could a dependency check be added in the Kconfig to prevent breaking automated testing on minimal host environments?
Quoted 2 lines
samples/landlock/Makefile +0
-0.PHONY: all clean
[ ... ]
Quoted 11 lines
samples/landlock/sandboxer.c +3
-0@@ -232,6 +241,166 @@ 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 {
samples/landlock/sandboxer.c static int populate_ruleset_net(const char *const env_var, const int ruleset_fd, · line 256
Quoted 10 lines
samples/landlock/sandboxer.c +10
-0+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 },
[Severity: Low]
Will this missing fallback macro for CLONE_NEWTIME cause compilation failures on older host environments?
The CLONE_NEWTIME macro was added to the glibc sched.h header starting in version 2.33. If the sample is built on a system with an older glibc, it fails to compile. Can we add a fallback preprocessor definition for CLONE_NEWTIME so the sample can still build on older distributions?
Quoted 5 lines
samples/landlock/sandboxer.c +5
-0+ { "user", CLONE_NEWUSER }, + { "uts", CLONE_NEWUTS }, + /* clang-format on */ + }; +size_t i;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Mickaël Salaün
maintainerRe: [PATCH v4 7/8] samples/landlock: Add capability and namespace restriction support
Quoted 49 lines · On Fri, Oct 02, 2026 at 12:53:30PM +0000, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Low] build: sample landlock fails on systems without libcap-dev
- [Low] build: missing fallback forCLONE_NEWTIMEbreaks build on glibc < 2.33 --commit
c88aebdbd55f6c34b61885d4e3d918bc61983af0
Author: Mickaël Salaün <[email protected]>
samples/landlock: Add capability and namespace restriction supportThis commit extends the sandboxer sample to demonstrate new Landlock capability and namespace restriction features. It allows parsing allowed namespaces and capabilities using libcap, adding appropriate command line arguments for testing.
Quoted 17 lines
samples/Kconfig +4
-2@@ -166,8 +166,10 @@ config SAMPLE_LANDLOCK bool "Landlock example" depends on CC_CAN_LINK && HEADERS_INSTALL help - Build a simple Landlock sandbox manager able to start a process - restricted by a user-defined filesystem access control policy. + Build a Landlock sandbox manager able to start a process restricted + by user-defined filesystem, network, scope, namespace, and capability + policies. This sample requires the libcap development headers and + library. config SAMPLE_PIDFD bool "pidfd sample"[ ... ]
samples/landlock/Makefile line 6
Quoted 9 lines
samples/landlock/Makefile +1
-0@@ -3,6 +3,7 @@ userprogs-always-y := sandboxer userccflags += -I usr/include +userldlibs += -lcap[Severity: Low]
Does this unconditional linking cause build failures during make allmodconfig or make samples if the host system lacks the libcap-dev library?
Quoted 5 lines
Since the
Kconfigdoes not verify the presence of the libcap library (for example, using a $(success,...) check), the build will unconditionally attempt to link against it and fail when the dependency is missing. Could a dependency check be added in theKconfigto prevent breaking automated testing on minimal host environments?
I'll make libcap-dev optional.
Quoted 32 lines
Quoted 3 lines
samples/landlock/Makefile +0
-0.PHONY: all clean[ ... ]
Quoted 11 lines
samples/landlock/sandboxer.c +3
-0@@ -232,6 +241,166 @@ 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 {samples/landlock/sandboxer.c static int populate_ruleset_net(const char *const env_var, const int ruleset_fd, · line 256
Quoted 10 lines
samples/landlock/sandboxer.c +10
-0+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 },[Severity: Low]
Will this missing fallback macro forCLONE_NEWTIMEcause compilation failures on older host environments?
Quoted 4 lines
The
CLONE_NEWTIMEmacro was added to the glibcsched.hheader starting in version 2.33. If the sample is built on a system with an older glibc, it fails to compile. Can we add a fallback preprocessor definition forCLONE_NEWTIMEso the sample can still build on older distributions?
I'll use the kernel headers.
Quoted 10 lines
Quoted 6 lines
samples/landlock/sandboxer.c +5
-0+ { "user", CLONE_NEWUSER }, + { "uts", CLONE_NEWUTS }, + /* clang-format on */ + }; +size_t i;Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Mickaël Salaün
maintainerPATCH v4 8/8 landlock: Add documentation for capability and namespace restrictions
In reply to Mickaël SalaünDocument the two new Landlock permission categories, introduced with ABI 12, in the userspace API guide, admin guide, trace-event guide, UAPI comments, and kernel security documentation.
The kernel security documentation generalizes the existing per-object access-rights framing into three restriction models (handled_access_*, handled_permissions, scoped) and states criteria for choosing among them, so future permission or scope additions have a documented place to land.
---
Changes since v3:
https://patch.msgid.link/[email protected]
- Document the new permissions as ABI 12.
- Name the documented audit blockers namespace.use and capability.use after their domains.
- Document handled_permissions, the four permission rule and denial events, effective no-ops, raw member values, namespace IDs, and audit-suppressed denials; add handled_permissions to the basic trace example.
- Describe the namespace creation and entry paths, and state that quiet denials stay trace-visible.
- Describe the quiet ruleset fields as suppressing audit records rather than logs, now that denials are also trace events.
Changes since v2:
https://patch.msgid.link/[email protected]
- Fix the CAP_BPF forward-compatibility example in Documentation/security/landlock.rst: rules allow-list, so describe a rule *allowing* CAP_SYS_ADMIN continuing to allow operations now gated by CAP_SYS_ADMIN || CAP_BPF (was worded as a rule "denying"; suggested by Günther Noack).
- Drop the "category" jargon from the Capability rules and Namespace rules summaries in Documentation/userspace-api/landlock.rst and add capabilities(7) / namespaces(7) cross-references there, in the rule examples, and in the ABI restriction sections (suggested by Günther Noack).
- Reword LANDLOCK_PERM_NAMESPACE_USE as gating "acquisition of access to namespaces" (was "acquisition of namespace associations") and "allow using" (was "allow entering") specific namespace types, to match the _USE semantics covering creation, entry, and fd-reference (suggested by Günther Noack).
- Document the per-member audit quieting for the new permissions in the Capability and namespace restrictions section: the quiet_capabilities and quiet_namespace_types rule fields suppress the audit records of specific denied members (independently of the allowed members), require the permission to be handled, are member-granular, and should quiet only known-expected members, never a blanket set.
- Documentation/security/landlock.rst prose polish (suggested by Günther Noack):
hyphenate "user-namespace-based"; reword the design-philosophy operation-set sentence; add an introductory paragraph to "Ruleset restriction models" (the ruleset denies by default, rules allow-list exceptions); split the per-object and per-category sections into shorter paragraphs and lead the per-category one with "Each LANDLOCK_PERM_* flag maps to its own rule type"; reframe the per-object new-operation/new-object-type text around object type (was "rule type") and tighten it.
- State the combined deny-by-default explicitly in Documentation/userspace-api/landlock.rst: when a domain handles both permissions, an operation is allowed only if each independently allows it (e.g. unshare(CLONE_NEWNET) needs both CLONE_NEWNET and CAP_SYS_ADMIN allowed).
- Note that the open_tree(OPEN_TREE_CLONE) / move_mount anonymous-mount bypass path requires CAP_SYS_ADMIN (typically obtained by first creating a user namespace).
- Add a concrete downstream-operations example to the per-category model in Documentation/security/landlock.rst (denying CAP_SYS_ADMIN blocks all admin operations such as mounts).
- Document that creating a non-user namespace always requires CAP_SYS_ADMIN, so when the domain handles LANDLOCK_PERM_CAPABILITY_USE a rule allowing CAP_SYS_ADMIN is needed even when CLONE_NEWUSER is combined in the same unshare() call; only user namespace creation needs no capability rule.
Changes since v1:
https://patch.msgid.link/[email protected]
The userspace API and security guides were revamped to match the v2 permission model: the previous chokepoints/gateways prose is replaced with the per-object (handled_access_*) versus per-category (handled_perm) framing, and a new Design philosophy section in the security guide states Landlock's principle (data, processes, kernel resources).
- Rename namespace_inum to namespace_id in audit field documentation to match the renamed audit field.
- Rename LANDLOCK_PERM_NAMESPACE_ENTER references to LANDLOCK_PERM_NAMESPACE_USE (companion change to the introducing commit), and enumerate the seven kernel paths it gates in the userspace API guide (membership via unshare/clone/clone3/setns; fd reference via open_tree/fsmount).
- Clarify that LANDLOCK_PERM_NAMESPACE_USE gates *acquisition* of namespace associations only (namespaces the process is already a member of when the domain is enforced are implicitly allowed) and that LANDLOCK_PERM_CAPABILITY_USE gates every exercise of a capability after the domain is enforced, regardless of how the capability was obtained.
- Document the rationale for accepting (rather than rejecting) unknown category member values in rule bodies: rejection would tie Landlock policy semantics to the running kernel's category-member set, making cross-kernel policies brittle. Acceptance is fail-safe in both directions and lets a policy activate as written when a value becomes real on a future kernel.
- Replace handled_perm = 0 with a per-bit mask in the userspace API guide's ABI compat fall-through, so future ABI extensions adding new LANDLOCK_PERM_* bits do not get stripped on the path that drops the v10 bits.
- Add a bridging sentence in the per-category permissions section of Documentation/security/landlock.rst contrasting per-category permissions with per-object access rights: per-category gates the prerequisite operation itself rather than restricting specific operations on a single resource instance (suggested by Günther Noack).
- Disambiguate the orthogonality invariant in Documentation/security/landlock.rst from the UAPI scoped field ("all new scoped features" -> "all Landlock access controls"; suggested by Justin Suess).
- Add an introductory paragraph in Documentation/userspace-api/landlock.rst contrasting LANDLOCK_PERM_CAPABILITY_USE with PR_SET_NO_NEW_PRIVS: NNP is the broader mechanism that blocks privilege acquisition via execve(2), while CAPABILITY_USE restricts the exercise of capabilities the process already holds (including those gained via CLONE_NEWUSER, which NNP does not block); sandboxes typically set both (suggested by Justin Suess).
- Disambiguate "category": object-side uses "object type" / "resource kind"; "category" stays for the per-category permissions model.
--- Documentation/admin-guide/LSM/landlock.rst | 46 ++-- Documentation/security/landlock.rst | 178 ++++++++++++++- Documentation/trace/events-landlock.rst | 66 ++++-- Documentation/userspace-api/landlock.rst | 243 +++++++++++++++++++-- include/trace/events/landlock.h | 11 +- include/uapi/linux/landlock.h | 17 +- 6 files changed, 503 insertions(+), 58 deletions(-)
Documentation/admin-guide/LSM/landlock.rst +33 -13
@@ -7,7 +7,7 @@ Landlock: system-wide management ================================ :Author: Mickaël Salaün -:Date: August 2026 +:Date: October 2026 Landlock can leverage the audit framework to log events.
@@ -20,10 +20,12 @@ Audit Denied access requests are logged by default for a sandboxed program if `audit` is enabled. This default behavior can be changed with the sys_landlock_restrict_self() flags (cf. -Documentation/userspace-api/landlock.rst), or suppressed on a per-object -basis by using ``LANDLOCK_ADD_RULE_QUIET`` (ABI 10+). Landlock logs can -also be masked thanks to audit rules. Landlock can generate 2 audit -record types. +Documentation/userspace-api/landlock.rst), suppressed on a per-object +basis by using ``LANDLOCK_ADD_RULE_QUIET`` (ABI 10+), or suppressed for +specific capability or namespace members with the corresponding permission +rule's ``quiet_*`` field (ABI 12+). Quiet rules only suppress audit submission; +they do not suppress denial trace events. Landlock logs can also be masked +thanks to audit rules. Landlock can generate two audit record types. Record types ------------
@@ -65,14 +67,28 @@ AUDIT_LANDLOCK_ACCESS - scope.abstract_unix_socket - Abstract UNIX socket connection denied - scope.signal - Signal sending denied + **namespace.*** - Namespace restrictions (ABI 12+): + - namespace.use - Namespace use was denied (creation via + :manpage:`unshare(2)`, :manpage:`clone(2)`, :manpage:`clone3(2)`, + :manpage:`open_tree(2)`, or :manpage:`fsmount(2)`, or joining via + :manpage:`setns(2)`); + ``namespace_type`` indicates the type (hex ``CLONE_NEW*`` bitmask), + and ``namespace_id`` identifies the target namespace for + :manpage:`setns(2)` operations (zero for creation) + + **capability.*** - Capability restrictions (ABI 12+): + - capability.use - Capability use was denied; + ``capability`` indicates the capability number + Multiple blockers can appear in a single event (comma-separated) when multiple access rights are missing. For example, creating a regular file in a directory that lacks both ``make_reg`` and ``refer`` rights would show ``blockers=fs.make_reg,fs.refer``. - The object identification fields (path, dev, ino for filesystem; opid, - ocomm for signals) depend on the type of access being blocked and provide - context about what resource was involved in the denial. + The object identification fields depend on the type of access being blocked: + ``path``, ``dev``, ``ino`` for filesystem; ``opid``, ``ocomm`` for signals; + ``namespace_type`` and ``namespace_id`` for namespace operations; + ``capability`` for capability use. AUDIT_LANDLOCK_DOMAIN
@@ -178,8 +194,9 @@ If you get spammed with audit logs related to Landlock, this is either an attack attempt or a bug in the security policy. We can put in place some filters to limit noise with two complementary ways: -- with sys_landlock_restrict_self()'s flags, or - ``LANDLOCK_ADD_RULE_QUIET`` (ABI 10+) if we can fix the sandboxed +- with sys_landlock_restrict_self()'s flags, + ``LANDLOCK_ADD_RULE_QUIET`` (ABI 10+), or the permission rules' + per-member ``quiet_*`` fields (ABI 12+) if we can fix the sandboxed programs, - or with audit rules (see :manpage:`auditctl(8)`).
@@ -243,8 +260,10 @@ with these exceptions: - **NOAUDIT hooks**: Some LSM hooks suppress logging for speculative permission probes (e.g., reading ``/proc/<pid>/status`` uses - ``PTRACE_MODE_NOAUDIT``). When NOAUDIT is set, neither audit records - nor trace events are emitted, and the denial is not counted in + ``PTRACE_MODE_NOAUDIT``, and :manpage:`listxattr(2)` probes + ``CAP_SYS_ADMIN`` with ``CAP_OPT_NOAUDIT`` to decide whether to list + ``trusted.*`` extended attributes). When NOAUDIT is set, neither audit + records nor trace events are emitted, and the denial is not counted in ``denials``. The denial is still enforced. This avoids performance overhead and noise from speculative probes that test permissions without performing an actual access.
@@ -269,7 +288,8 @@ Observability security considerations Both audit records and trace events expose information about all Landlock-sandboxed processes on the system, including filesystem paths -being accessed, network ports, and process identities. System +being accessed, network ports, capability numbers, namespace types and IDs, +and process identities. System administrators must ensure that access to audit logs (controlled by the audit subsystem configuration) and to trace events (requiring ``CAP_SYS_ADMIN`` or ``CAP_BPF`` + ``CAP_PERFMON``) is restricted to
Documentation/security/landlock.rst +176 -2
202 lines not on this page · raw message
Documentation/trace/events-landlock.rst +49 -17
114 lines not on this page · raw message
Documentation/userspace-api/landlock.rst +230 -13
305 lines not on this page · raw message
include/trace/events/landlock.h +6 -5
@@ -278,11 +278,12 @@ static inline const char *__trace_landlock_print_layers(* Every denial event shares three fields. domain is the ID of the * innermost domain that blocked the access. same_exec tells whether the * current task is the same executable that entered that domain. logged is -* the domain's audit-logging decision for this denial (its log_status is -* enabled and the per-execution flag selected by same_exec is set); a -* stateless ftrace filter can select the denials the domain submits to -* audit with logged==1, without reconstructing it from the per-execution -* log flags. Denial events order their fields as domain, same_exec, +* the complete audit-submission selection for this denial: the domain's +* log_status and per-execution flag, per-object or per-member quiet rules, +* and request-specific no-audit options. This excludes global audit state +* and audit-side filters. A stateless ftrace filter can select the denials +* the domain submits to audit with logged==1, without reconstructing those +* inputs. Denial events order their fields as domain, same_exec, * logged, then the blockers verdict input, then the * type-specific object fields, then any variable-length field. *
include/uapi/linux/landlock.h +9 -8
@@ -33,14 +33,14 @@* (and that they have tested with a kernel that supported them all). * * @quiet_access_fs and @quiet_access_net are bitmasks of actions for which a -* denial by this layer will not trigger a log if the corresponding object (or -* its children, for filesystem rules) is marked with the "quiet" bit via -* %LANDLOCK_ADD_RULE_QUIET, even if logging would normally take place per +* denial by this layer will not trigger an audit record if the corresponding +* object (or its children, for filesystem rules) is marked with the "quiet" bit +* via %LANDLOCK_ADD_RULE_QUIET, even if logging would normally take place per * landlock_restrict_self() flags. @quiet_scoped is similar, except that it * does not require marking any objects as quiet - if the ruleset is created * with any bits set in @quiet_scoped, then denial of such scoped resources will -* not trigger any log. These 3 fields are available since Landlock ABI version -* 10. +* not trigger an audit record. These three fields are available since Landlock +* ABI version 10. * * @quiet_access_fs, @quiet_access_net and @quiet_scoped must be a subset of * @handled_access_fs, @handled_access_net and @scoped respectively.
@@ -66,16 +66,17 @@ struct landlock_ruleset_attr {__u64 scoped;/** * @quiet_access_fs: Bitmask of filesystem actions which should not be -* logged if per-object quiet flag is set. +* submitted to audit if the per-object quiet flag is set. */ __u64 quiet_access_fs;/** * @quiet_access_net: Bitmask of network actions which should not be -* logged if per-object quiet flag is set. +* submitted to audit if the per-object quiet flag is set. */ __u64 quiet_access_net;/** -* @quiet_scoped: Bitmask of scoped actions which should not be logged. +* @quiet_scoped: Bitmask of scoped actions which should not be +* submitted to audit. */ __u64 quiet_scoped;/**
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v4 8/8] landlock: Add documentation for capability and namespace restrictions
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 10 lines
Document the two new Landlock permission categories, introduced with ABI 12, in the userspace API guide, admin guide, trace-event guide, UAPI comments, and kernel security documentation.
The kernel security documentation generalizes the existing per-object access-rights framing into three restriction models (handled_access_*,
handled_permissions, scoped) and states criteria for choosing among them, so future permission or scope additions have a documented place to land.
Quoted 5 lines
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]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8