Skip to contentSkip to conversation

Landlock tracepoints

PATCH Superseded Mickaël Salaün 2 participants 24 messages Jul 22 – Aug 6

Subsystems (6)
Documentation VFS Kselftest Tracing +2 more subsystems

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Mickaël Salaün

author maintainer
#0 lore raw

v3 cover Landlock tracepoints

Hi,

This series adds 14 tracepoints that cover the full Landlock lifecycle, from ruleset creation to domain destruction. They can be used directly via /sys/kernel/tracing/events/landlock/* or attached by eBPF programs for richer introspection.

Christian, please take a look at patch 9, which adds DEFINE_FREE(__putname) to include/linux/fs.h .

Steven, Masami, Mathieu, please take a look at patch 7, which adds __print_untrusted_str() for trace events, and patches 8-14 which add the new tracepoints.

This series now looks good to be merged in my "next" tree, provided VFS and tracing maintainers are ok with it.

Patches 1-6 refactor Landlock internals: they split struct landlock_domain from struct landlock_ruleset, move denial logging into a common framework shared by audit and tracing, decouple the per-denial logging decision from audit, and consolidate the access-right and scope names into a shared header. Patch 7 adds __print_untrusted_str() to the tracing core. Patches 8-12 add lifecycle tracepoints: ruleset creation and destruction, rule addition for filesystem and network, domain creation, enforcement, and destruction, and per-rule access checks. Patches 13-14 add denial tracepoints for filesystem, network, ptrace, and scope operations. Patches 15-19 add selftests and patch 20 adds documentation.

Each rule type has a dedicated tracepoint with strongly-typed fields (dev/ino for filesystem, port for network), following the same approach as the audit logs.

The scope and ptrace denial events also record the other party's Landlock domain ID, so a consumer that tracked domain creation can reproduce the two-domain verdict behind a relational denial.

This feature is useful to troubleshoot policy issues and should limit the need for custom debugging kernel code when developing new Landlock features.

Landlock already has audit support for logging denied access requests, which is useful to identify security issues or sandbox misconfiguration. However, audit might not be enough to debug Landlock policies. The main difference with audit events is that traces are disabled by default, can be very verbose, and can be filtered according to process and Landlock properties (e.g. domain ID).

As for audit, tracing may expose sensitive information about all sandboxed processes on the system, and must only be accessible to the system administrator. For unprivileged monitoring scoped to a single sandbox (e.g., interactive permission prompts), Tingmao Wang's "Landlock supervise" RFC [1] proposes a dedicated userspace API. The infrastructure changes in this series (the domain type split, the denial framework, and the tracepoint consistency guarantees) benefit that approach.

I will release a companion tool that leverages these tracepoints to monitor Landlock events in real time.

This series applies on top of v7.2-rc4.

Changes since v2:
https://patch.msgid.link/[email protected]
- Renamed the landlock_restrict_self tracepoint to landlock_create_domain and reordered its arguments to (domain, ruleset) for domain-first consistency with the other domain-lifecycle events.
- Ordered the add_rule_net and check_rule tracepoint arguments with the common part first: access_rights before port (add_rule_net), and domain, rule before access_request and the object (check_rule).
- Recorded the other party's Landlock domain as a scalar ID on scope and ptrace denials: target_domain=, peer_domain=, tracee_domain= (0 when unsandboxed).
- Replaced the deny events' log_same_exec and log_new_exec fields with a single kernel-computed logged field; logged and the quiet suppression are gated on CONFIG_SECURITY_LANDLOCK_LOG, so the value is identical in a tracepoints-only build (CONFIG_AUDIT=n).
- Fixed a NULL dereference in landlock_deny_access_fs on a denied ftruncate() or ioctl() by selecting the path from the request's audit-data type.
- Moved landlock_restrict_self's creation event under the ruleset lock, before the thread-sync; a thread-sync abort still emits the matching free_domain, keeping the create/free pair balanced.
- Split the denial-logging framework three ways (common log.c, audit.c, and a tracepoint-only trace.c), each behind its own CONFIG, so the tracepoints work without CONFIG_AUDIT and every commit stays bisectable.
- Rendered trace access masks as symbolic names (check_rule grants=, denial blockers=) instead of raw hex, and renamed the check_rule request= and denial comm= labels to access_request= and tracee_comm=/target_comm=.
- Reworked the trace documentation: consolidated the shared eBPF and trace-event guarantees into a DOC block, de-duplicated the admin guide and the trace event reference, and documented the logged field and the grants= format.
- Extended the trace selftests: asserted the relational domain-ID fields across the signal, abstract-unix-socket, and ptrace hooks, added a check_rule_net field test, and added landlock_enforce_domain coverage of the single-threaded, TSYNC, multi-threaded, non-leader, flags-only, and thread-sync-abort cases.
- New patch: added the landlock_enforce_domain tracepoint, the per-thread enforcement outcome, emitted once per thread the domain is applied to after its commit_creds(). It carries complete (the single event concluding the operation) and process_wide (the enforcement covers every eligible thread, via LANDLOCK_RESTRICT_SELF_TSYNC or a single-threaded process); complete && process_wide is the whole-process-enforced guarantee.
- New patch 5 factors the per-denial logging decision into a shared, config-independent logged verdict used by audit and tracing.
- New patch 6 consolidates the access-right and scope names in a shared header (enabling the symbolic rendering above).
- Dropped v2 patch 10 ("landlock: Set audit_net.sk for socket access checks") and its follow-up AF_UNSPEC UDP-send fix, both merged upstream; subsequent patches renumbered.

Changes since RFC v1:
https://patch.msgid.link/[email protected]
- New patches 1-4: split struct landlock_domain from struct landlock_ruleset; split denial logging from audit into common framework with CONFIG_SECURITY_LANDLOCK_LOG.
- Patch 5 (was v1 3/5): removed WARN_ON() (pointed out by Steven Rostedt).
- New patch 6: added create_ruleset and free_ruleset tracepoints (split from the v1 add_rule_fs tracepoint patch).
- Patch 7 (was v1 4/5): added add_rule_net tracepoint, used ruleset Landlock ID instead of kernel pointer, added version field to struct landlock_ruleset, differentiated d_absolute_path() error cases (suggested by Tingmao Wang), moved DEFINE_FREE(__putname) to include/linux/fs.h (noticed by Tingmao Wang).
- New patch 8: added restrict_self and free_domain tracepoints.
- Patch 9 (was v1 5/5): merged find-rule consolidation, added check_rule_net tracepoint.
- New patch 10: split audit_net.sk fix with Fixes: tag.
- New patches 11-12: added denial tracepoints for filesystem, network, ptrace, and scope operations.
- New patches 13-17: split selftests into per-feature commits with documentation.

[1] https://lore.kernel.org/r/[email protected]

Regards,

Mickaël Salaün (20):
landlock: Prepare ruleset and domain type split
landlock: Move domain query functions to domain.c
landlock: Split struct landlock_domain from struct landlock_ruleset
landlock: Split denial logging from audit into common framework
landlock: Decouple the per-denial logging decision from CONFIG_AUDIT
landlock: Consolidate access-right and scope names in a shared header
tracing: Add __print_untrusted_str()
landlock: Add create_ruleset and free_ruleset tracepoints
landlock: Add landlock_add_rule_fs and landlock_add_rule_net
tracepoints
landlock: Add create_domain and free_domain tracepoints
landlock: Add landlock_enforce_domain tracepoint
landlock: Add tracepoints for rule checking
landlock: Add landlock_deny_access_fs and landlock_deny_access_net
landlock: Add tracepoints for ptrace and scope denials selftests/landlock: Add trace event test infrastructure and tests selftests/landlock: Add filesystem tracepoint tests selftests/landlock: Add network tracepoint tests selftests/landlock: Add scope and ptrace tracepoint tests selftests/landlock: Add landlock_enforce_domain trace tests
landlock: Document tracepoints

 Documentation/admin-guide/LSM/landlock.rst    |  105 +-
 Documentation/security/landlock.rst           |   38 +-
 Documentation/trace/events-landlock.rst       |  313 ++++
 Documentation/trace/index.rst                 |    1 +
 Documentation/userspace-api/landlock.rst      |   14 +-
 MAINTAINERS                                   |    3 +
 include/linux/fs.h                            |    1 +
 include/linux/landlock.h                      |   56 +
 include/linux/trace_events.h                  |    2 +
 include/trace/events/landlock.h               |  908 +++++++++
 include/trace/stages/stage3_trace_output.h    |    4 +
 include/trace/stages/stage7_class_define.h    |    1 +
 kernel/trace/trace_output.c                   |   44 +
 security/landlock/Kconfig                     |    5 +
 security/landlock/Makefile                    |   12 +-
 security/landlock/access.h                    |    6 +-
 security/landlock/audit.c                     |  641 +------
 security/landlock/audit.h                     |   57 +-
 security/landlock/cred.c                      |   14 +-
 security/landlock/cred.h                      |   29 +-
 security/landlock/domain.c                    |  475 ++++-
 security/landlock/domain.h                    |  162 +-
 security/landlock/fs.c                        |  218 ++-
 security/landlock/fs.h                        |   38 +-
 security/landlock/id.h                        |    6 +-
 security/landlock/log.c                       |  586 ++++++
 security/landlock/log.h                       |   86 +
 security/landlock/net.c                       |   38 +-
 security/landlock/ruleset.c                   |  546 +-----
 security/landlock/ruleset.h                   |  250 +--
 security/landlock/syscalls.c                  |   89 +-
 security/landlock/task.c                      |   76 +-
 security/landlock/trace.c                     |  185 ++
 security/landlock/trace.h                     |   44 +
 security/landlock/tsync.c                     |   15 +
 tools/testing/selftests/landlock/audit.h      |   35 -
 tools/testing/selftests/landlock/common.h     |   47 +
 tools/testing/selftests/landlock/config       |    2 +
 tools/testing/selftests/landlock/fs_test.c    |  483 +++++
 tools/testing/selftests/landlock/net_test.c   |  747 +++++++-
 .../testing/selftests/landlock/ptrace_test.c  |  402 ++++
 .../landlock/scoped_abstract_unix_test.c      |  463 +++++
 .../selftests/landlock/scoped_signal_test.c   |  404 ++++
 tools/testing/selftests/landlock/trace.h      |  646 +++++++
 .../selftests/landlock/trace_fs_test.c        |  496 +++++
 tools/testing/selftests/landlock/trace_test.c | 1623 +++++++++++++++++
 tools/testing/selftests/landlock/true.c       |   10 +
 47 files changed, 8981 insertions(+), 1445 deletions(-)
 create mode 100644 Documentation/trace/events-landlock.rst
 create mode 100644 include/linux/landlock.h
 create mode 100644 include/trace/events/landlock.h
 create mode 100644 security/landlock/log.c
 create mode 100644 security/landlock/log.h
 create mode 100644 security/landlock/trace.c
 create mode 100644 security/landlock/trace.h
 create mode 100644 tools/testing/selftests/landlock/trace.h
 create mode 100644 tools/testing/selftests/landlock/trace_fs_test.c
 create mode 100644 tools/testing/selftests/landlock/trace_test.c
Signature · 1 line
2.54.0
author maintainer
#1 lore raw

PATCH v3 1/20 landlock: Prepare ruleset and domain type split

Rulesets and domains serve fundamentally different purposes: a ruleset is mutable and user-facing, created by landlock_create_ruleset(), while a domain is immutable after construction and enforced on tasks via landlock_restrict_self(). Today both are represented by struct landlock_ruleset, which conflates mutable and immutable state in a single type: the lock field is unused by domains, the hierarchy field is unused by rulesets, and lifecycle functions must handle both cases.

Prepare for a clean type split by introducing two new structures:

- struct landlock_rules: the red-black tree roots and rule count, shared by both rulesets and domains. Decoupling rule storage from the domain API lets the backing data structure change independently (e.g. to a hash table, cf. [1]).
- struct landlock_domain: the immutable domain enforced on tasks, with no lock field because its rules and access masks are fixed once construction completes. The name reflects the role, not the internal data structure.

Add the domain lifecycle helpers (landlock_get_domain(), landlock_put_domain(), landlock_put_domain_deferred()) and move domain.o from landlock-$(CONFIG_AUDIT) to landlock-y, because these are needed unconditionally, not just for audit logging.

No behavioral change. The new types and lifecycle functions are not yet used by any caller.

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Adapt rule insertion to the base's quiet flag (landlock_insert_rule() gains a flags argument).
- Drop Tingmao Wang's Reviewed-by; the rebase reworked the patch.

Changes since v1:
- New patch.

---
 security/landlock/Makefile  |  6 +--
 security/landlock/domain.c  | 35 ++++++++++++++++
 security/landlock/domain.h  | 69 ++++++++++++++++++++++++++++++++
 security/landlock/ruleset.c | 71 ++++++++++++++++-----------------
 security/landlock/ruleset.h | 79 +++++++++++++++++++++++++++----------
 5 files changed, 200 insertions(+), 60 deletions(-)
security/landlock/Makefile +3 -3
index ffa7646d99f3..23e13644916f 100644
@@ -8,11 +8,11 @@ landlock-y := \
 	cred.o \
 	task.o \
 	fs.o \
-	tsync.o
+	tsync.o \
+	domain.o
 
 landlock-$(CONFIG_INET) += net.o
 
 landlock-$(CONFIG_AUDIT) += \
 	id.o \
-	audit.o \
-	domain.o
+	audit.o
security/landlock/domain.c +35 -0
index 9a8355fccd26..c5efb7635a7b 100644
@@ -15,14 +15,49 @@
 #include <linux/mm.h>
 #include <linux/path.h>
 #include <linux/pid.h>
+#include <linux/refcount.h>
 #include <linux/sched.h>
 #include <linux/signal.h>
+#include <linux/slab.h>
 #include <linux/uidgid.h>
+#include <linux/workqueue.h>
 
 #include "access.h"
 #include "common.h"
 #include "domain.h"
 #include "id.h"
+#include "ruleset.h"
+
+static void free_domain(struct landlock_domain *const domain)
+{
+	might_sleep();
+	landlock_free_rules(&domain->rules);
+	landlock_put_hierarchy(domain->hierarchy);
+	kfree(domain);
+}
+
+void landlock_put_domain(struct landlock_domain *const domain)
+{
+	might_sleep();
+	if (domain && refcount_dec_and_test(&domain->usage))
+		free_domain(domain);
+}
+
+static void free_domain_work(struct work_struct *const work)
+{
+	struct landlock_domain *domain;
+
+	domain = container_of(work, struct landlock_domain, work_free);
+	free_domain(domain);
+}
+
+void landlock_put_domain_deferred(struct landlock_domain *const domain)
+{
+	if (domain && refcount_dec_and_test(&domain->usage)) {
+		INIT_WORK(&domain->work_free, free_domain_work);
+		schedule_work(&domain->work_free);
+	}
+}
 
 #ifdef CONFIG_AUDIT
 
security/landlock/domain.h +69 -0

88 lines not on this page · raw message

security/landlock/ruleset.c +35 -36

189 lines not on this page · raw message

security/landlock/ruleset.h +58 -21

132 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#2 lore raw

PATCH v3 2/20 landlock: Move domain query functions to domain.c

In reply to Mickaël Salaün

Grouping domain-specific code in one compilation unit reduces coupling between domain and ruleset implementations.

Move the access-check functions that only operate on a domain (rule lookup, layer unmasking, layer-mask init, access-mask union) from ruleset.[ch] to domain.[ch]. They evaluate whether a domain grants a requested access during the pathwalk and network checks and do not modify the domain.

The merge and inherit chain stays in ruleset.c for now because it calls the static create_ruleset() allocator; a following commit moves it once the domain type switch eliminates that dependency.

No behavioral change. The functions move with unchanged signatures and bodies.

Cc Günther Noack <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Adapt the moved access-check helpers to the base's struct layer_masks (renamed from struct layer_access_masks), including the per-layer quiet flag.

Changes since v1:
- New patch.

---
 security/landlock/domain.c  | 162 ++++++++++++++++++++++++++++++++++++
 security/landlock/domain.h  |  38 +++++++++
 security/landlock/net.c     |   1 +
 security/landlock/ruleset.c | 150 ---------------------------------
 security/landlock/ruleset.h |  38 ---------
 5 files changed, 201 insertions(+), 188 deletions(-)
security/landlock/domain.c +162 -0
index c5efb7635a7b..8fb74107c2ef 100644
@@ -10,11 +10,15 @@
 #include <kunit/test.h>
 #include <linux/bitops.h>
 #include <linux/bits.h>
+#include <linux/cleanup.h>
 #include <linux/cred.h>
+#include <linux/err.h>
 #include <linux/file.h>
 #include <linux/mm.h>
+#include <linux/overflow.h>
 #include <linux/path.h>
 #include <linux/pid.h>
+#include <linux/rbtree.h>
 #include <linux/refcount.h>
 #include <linux/sched.h>
 #include <linux/signal.h>
@@ -26,6 +30,7 @@
 #include "common.h"
 #include "domain.h"
 #include "id.h"
+#include "limits.h"
 #include "ruleset.h"
 
 static void free_domain(struct landlock_domain *const domain)
@@ -59,6 +64,163 @@ void landlock_put_domain_deferred(struct landlock_domain *const domain)
 	}
 }
 
+/* The returned access has the same lifetime as the domain. */
+const struct landlock_rule *
+landlock_find_rule(const struct landlock_ruleset *const ruleset,
+		   const struct landlock_id id)
+{
+	const struct rb_root *root;
+	const struct rb_node *node;
+
+	root = landlock_get_rule_root((struct landlock_rules *)&ruleset->rules,
+				      id.type);
+	if (IS_ERR(root))
+		return NULL;
+	node = root->rb_node;
+
+	while (node) {
+		struct landlock_rule *this =
+			rb_entry(node, struct landlock_rule, node);
+
+		if (this->key.data == id.key.data)
+			return this;
+		if (this->key.data < id.key.data)
+			node = node->rb_right;
+		else
+			node = node->rb_left;
+	}
+	return NULL;
+}
+
+/**
+ * landlock_unmask_layers - Remove the access rights in @masks which are
+ *                          granted in @rule
+ *
+ * Updates the set of (per-layer) unfulfilled access rights @masks so that all
+ * the access rights granted in @rule are removed from it (because they are now
+ * fulfilled).
+ *
+ * @rule: A rule that grants a set of access rights for each layer.
+ * @masks: A matrix of unfulfilled access rights for each layer.
+ *
+ * Return: True if the request is allowed (i.e. the access rights granted all
+ * remaining unfulfilled access rights and masks has no leftover set bits).
+ */
+bool landlock_unmask_layers(const struct landlock_rule *const rule,
+			    struct layer_masks *masks)
+{
+	if (!masks)
+		return true;
+	if (!rule)
+		return false;
+
+	/*
+	 * An access is granted if, for each policy layer, at least one rule
+	 * encountered on the pathwalk grants the requested access, regardless
+	 * of its position in the layer stack.  We must then check the remaining
+	 * layers for each inode, from the first added layer to the last one.
+	 * When there are multiple requested accesses, for each policy layer,
+	 * the full set of requested accesses may not be granted by only one
+	 * rule, but by the union (binary OR) of multiple rules.  For example,
+	 * /a/b <execute> + /a <read> grants /a/b <execute + read>.
+	 *
+	 * This function is called once per matching rule during the pathwalk,
+	 * progressively clearing bits in @masks.  The overall access decision
+	 * is per-layer: access is granted iff masks->layers[l].access == 0 for
+	 * all layers l.  When two independent mechanisms can each grant access
+	 * within a layer (e.g. a path rule OR a scope exception), the
+	 * composition must evaluate per-layer: FOR-ALL l (A(l) OR B(l)), not
+	 * (FOR-ALL l A(l)) OR (FOR-ALL l B(l)), to prevent bypass when
+	 * different layers grant via different mechanisms.
+	 */
+	for (size_t i = 0; i < rule->num_layers; i++) {
+		const struct landlock_layer *const layer = &rule->layers[i];
+
+		/* Clear the bits where the layer in the rule grants access. */
+		masks->layers[layer->level - 1].access &= ~layer->access;
+
+#ifdef CONFIG_AUDIT
+		/* Collect rule flags for each layer. */
+		if (layer->flags.quiet)
+			masks->layers[layer->level - 1].quiet = true;
+#endif /* CONFIG_AUDIT */
+	}
+
+	for (size_t i = 0; i < ARRAY_SIZE(masks->layers); i++) {
+		if (masks->layers[i].access)
+			return false;
+	}
+	return true;
+}
+
+typedef access_mask_t
+get_access_mask_t(const struct landlock_ruleset *const ruleset,
+		  const u16 layer_level);
+
+/**
+ * landlock_init_layer_masks - Initialize layer masks from an access request
+ *
+ * Populates @masks such that for each access right in @access_request, the bits
+ * for all the layers are set where this access right is handled.  Rule flags
+ * are also zeroed.
+ *
+ * @domain: The domain that defines the current restrictions.
+ * @access_request: The requested access rights to check.
+ * @masks: Layer access masks to populate.
+ * @key_type: The key type to switch between access masks of different types.
+ *
+ * Return: An access mask where each access right bit is set which is handled in
+ * any of the active layers in @domain.
+ */
+access_mask_t
+landlock_init_layer_masks(const struct landlock_ruleset *const domain,
+			  const access_mask_t access_request,
+			  struct layer_masks *const masks,
+			  const enum landlock_key_type key_type)
+{
+	access_mask_t handled_accesses = 0;
+	get_access_mask_t *get_access_mask;
+
+	switch (key_type) {
+	case LANDLOCK_KEY_INODE:
+		get_access_mask = landlock_get_fs_access_mask;
+		break;
+
+#if IS_ENABLED(CONFIG_INET)
+	case LANDLOCK_KEY_NET_PORT:
+		get_access_mask = landlock_get_net_access_mask;
+		break;
+#endif /* IS_ENABLED(CONFIG_INET) */
+
+	default:
+		WARN_ON_ONCE(1);
+		return 0;
+	}
+
+	/* An empty access request can happen because of O_WRONLY | O_RDWR. */
+	if (!access_request)
+		return 0;
+
+	for (size_t i = 0; i < domain->num_layers; i++) {
+		const access_mask_t handled = get_access_mask(domain, i);
+
+		masks->layers[i].access = access_request & handled;
+		handled_accesses |= masks->layers[i].access;
+#ifdef CONFIG_AUDIT
+		masks->layers[i].quiet = false;
+#endif /* CONFIG_AUDIT */
+	}
+	for (size_t i = domain->num_layers; i < ARRAY_SIZE(masks->layers);
+	     i++) {
+		masks->layers[i].access = 0;
+#ifdef CONFIG_AUDIT
+		masks->layers[i].quiet = false;
+#endif /* CONFIG_AUDIT */
+	}
+
+	return handled_accesses;
+}
+
 #ifdef CONFIG_AUDIT
 
 /**
security/landlock/domain.h +38 -0
index bcfd0452e260..9f9b892ab17d 100644
@@ -233,12 +233,50 @@ struct landlock_domain {
 	};
 };
 
+/**
+ * landlock_union_access_masks - Return all access rights handled in the
+ *				 domain
+ *
+ * @domain: Landlock ruleset (used as a domain)
+ *
+ * Return: An access_masks result of the OR of all the domain's access masks.
+ */
+static inline struct access_masks
+landlock_union_access_masks(const struct landlock_ruleset *const domain)
+{
+	union access_masks_all matches = {};
+	size_t layer_level;
+
+	for (layer_level = 0; layer_level < domain->num_layers; layer_level++) {
+		union access_masks_all layer = {
+			.masks = domain->access_masks[layer_level],
+		};
+
+		matches.all |= layer.all;
+	}
+
+	return matches.masks;
+}
+
 void landlock_put_domain(struct landlock_domain *const domain);
 void landlock_put_domain_deferred(struct landlock_domain *const domain);
 
 DEFINE_FREE(landlock_put_domain, struct landlock_domain *,
 	    if (!IS_ERR_OR_NULL(_T)) landlock_put_domain(_T))
 
+const struct landlock_rule *
+landlock_find_rule(const struct landlock_ruleset *const ruleset,
+		   const struct landlock_id id);
+
+bool landlock_unmask_layers(const struct landlock_rule *const rule,
+			    struct layer_masks *masks);
+
+access_mask_t
+landlock_init_layer_masks(const struct landlock_ruleset *const domain,
+			  const access_mask_t access_request,
+			  struct layer_masks *masks,
+			  const enum landlock_key_type key_type);
+
 static inline void landlock_get_domain(struct landlock_domain *const domain)
 {
 	if (domain)
security/landlock/net.c +1 -0
index 46c17116fcf4..feecc8c77ab4 100644
@@ -15,6 +15,7 @@
 #include "audit.h"
 #include "common.h"
 #include "cred.h"
+#include "domain.h"
 #include "limits.h"
 #include "net.h"
 #include "ruleset.h"
security/landlock/ruleset.c +0 -150

153 lines not on this page · raw message

security/landlock/ruleset.h +0 -38
index c8c83efff4c5..f9486c06b7ec 100644
@@ -235,10 +235,6 @@ struct landlock_ruleset *
 landlock_merge_ruleset(struct landlock_ruleset *const parent,
 		       struct landlock_ruleset *const ruleset);
 
-const struct landlock_rule *
-landlock_find_rule(const struct landlock_ruleset *const ruleset,
-		   const struct landlock_id id);
-
 /**
  * landlock_get_rule_root - Get the root of a rule tree by key type
  *
@@ -272,31 +268,6 @@ static inline void landlock_get_ruleset(struct landlock_ruleset *const ruleset)
 		refcount_inc(&ruleset->usage);
 }
 
-/**
- * landlock_union_access_masks - Return all access rights handled in the
- *				 domain
- *
- * @domain: Landlock ruleset (used as a domain)
- *
- * Return: An access_masks result of the OR of all the domain's access masks.
- */
-static inline struct access_masks
-landlock_union_access_masks(const struct landlock_ruleset *const domain)
-{
-	union access_masks_all matches = {};
-	size_t layer_level;
-
-	for (layer_level = 0; layer_level < domain->num_layers; layer_level++) {
-		union access_masks_all layer = {
-			.masks = domain->access_masks[layer_level],
-		};
-
-		matches.all |= layer.all;
-	}
-
-	return matches.masks;
-}
-
 static inline void
 landlock_add_fs_access_mask(struct landlock_ruleset *const ruleset,
 			    const access_mask_t fs_access_mask,
@@ -355,13 +326,4 @@ landlock_get_scope_mask(const struct landlock_ruleset *const ruleset,
 	return ruleset->access_masks[layer_level].scope;
 }
 
-bool landlock_unmask_layers(const struct landlock_rule *const rule,
-			    struct layer_masks *masks);
-
-access_mask_t
-landlock_init_layer_masks(const struct landlock_ruleset *const domain,
-			  const access_mask_t access_request,
-			  struct layer_masks *masks,
-			  const enum landlock_key_type key_type);
-
 #endif /* _SECURITY_LANDLOCK_RULESET_H */
Signature · 1 line
2.54.0
author maintainer
#3 lore raw

PATCH v3 3/20 landlock: Split struct landlock_domain from struct landlock_ruleset

In reply to Mickaël Salaün

Switch all domain users to the new struct landlock_domain type introduced by a previous commit, eliminating the conflation between mutable rulesets and immutable domains. landlock_merge_ruleset() now returns and allocates a struct landlock_domain, and the merge and inherit helpers move next to it; the former static insert_rule() is exported as landlock_rule_insert() for its new caller across the translation-unit boundary.

The merge destination is now a private struct landlock_domain still under construction (owned by the calling thread, not yet shared), so the merge and inherit helpers lock only the source ruleset: the previous lock of both destination and source collapses to a single mutex_lock(&src->lock).

Rename the per-layer access-mask field from access_masks to handled_masks, naming it by the role it plays (the rights each layer handles) rather than by its type, paralleling the struct access_masks quiet_masks field. Drop the now domain-only fields (hierarchy, work_free, num_layers) from struct landlock_ruleset.

The new struct landlock_domain field in cred.h pulls in domain.h, which includes audit.h, which previously included cred.h, forming an include cycle. Break it by having audit.h forward-declare the struct landlock_cred_security and struct landlock_hierarchy it uses instead of including cred.h.

Cc Günther Noack <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Rename the per-layer FAM (struct landlock_domain) and the unmerged-ruleset field (struct landlock_ruleset) from access_masks to handled_masks, naming them by role alongside the per-layer quiet_masks field.
- Rename struct layer_access_masks to the base's struct layer_masks.

Changes since v1:
- New patch.

---
 security/landlock/access.h   |   2 +-
 security/landlock/audit.c    |  12 +-
 security/landlock/audit.h    |   4 +-
 security/landlock/cred.c     |   6 +-
 security/landlock/cred.h     |  21 ++-
 security/landlock/domain.c   | 258 +++++++++++++++++++++++++-
 security/landlock/domain.h   |  43 ++++-
 security/landlock/fs.c       |  25 ++-
 security/landlock/net.c      |   3 +-
 security/landlock/ruleset.c  | 338 +++++------------------------------
 security/landlock/ruleset.h  | 141 +++------------
 security/landlock/syscalls.c |  10 +-
 security/landlock/task.c     |  20 +--
 13 files changed, 403 insertions(+), 480 deletions(-)
security/landlock/access.h +1 -1
index d926078bf0a5..1a8227a709d9 100644
@@ -19,7 +19,7 @@
 
 /*
  * All access rights that are denied by default whether they are handled or not
- * by a ruleset/layer.  This must be ORed with all ruleset->access_masks[]
+ * by a ruleset/layer.  This must be ORed with all domain->handled_masks[]
  * entries when we need to get the absolute handled access masks, see
  * landlock_upgrade_handled_access_masks().
  */
security/landlock/audit.c +6 -6
index 50536c568526..7cb00619a741 100644
@@ -138,7 +138,7 @@ static void log_domain(struct landlock_hierarchy *const hierarchy)
 }
 
 static struct landlock_hierarchy *
-get_hierarchy(const struct landlock_ruleset *const domain, const size_t layer)
+get_hierarchy(const struct landlock_domain *const domain, const size_t layer)
 {
 	struct landlock_hierarchy *hierarchy = domain->hierarchy;
 	ssize_t i;
@@ -171,7 +171,7 @@ static void test_get_hierarchy(struct kunit *const test)
 		.parent = &dom1_hierarchy,
 		.id = 30,
 	};
-	struct landlock_ruleset dom2 = {
+	struct landlock_domain dom2 = {
 		.hierarchy = &dom2_hierarchy,
 		.num_layers = 3,
 	};
@@ -185,7 +185,7 @@ static void test_get_hierarchy(struct kunit *const test)
 #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
 
 /* Get the youngest layer that denied the access_request. */
-static size_t get_denied_layer(const struct landlock_ruleset *const domain,
+static size_t get_denied_layer(const struct landlock_domain *const domain,
 			       access_mask_t *const access_request,
 			       const struct layer_masks *masks)
 {
@@ -205,7 +205,7 @@ static size_t get_denied_layer(const struct landlock_ruleset *const domain,
 
 static void test_get_denied_layer(struct kunit *const test)
 {
-	const struct landlock_ruleset dom = {
+	const struct landlock_domain dom = {
 		.num_layers = 5,
 	};
 	const struct layer_masks masks = {
@@ -682,8 +682,8 @@ void landlock_log_denial(const struct landlock_cred_security *const subject,
  * Only domains which previously appeared in the audit logs are logged again.
  * This is useful to know when a domain will never show again in the audit log.
  *
- * Called in a work queue scheduled by landlock_put_ruleset_deferred() called
- * by hook_cred_free().
+ * Called in a work queue scheduled by landlock_put_domain_deferred() called by
+ * hook_cred_free().
  */
 void landlock_log_drop_domain(const struct landlock_hierarchy *const hierarchy)
 {
security/landlock/audit.h +3 -1
index 620f8a24291d..4617a855712c 100644
@@ -12,7 +12,9 @@
 #include <linux/lsm_audit.h>
 
 #include "access.h"
-#include "cred.h"
+
+struct landlock_cred_security;
+struct landlock_hierarchy;
 
 enum landlock_request_type {
 	LANDLOCK_REQUEST_PTRACE = 1,
security/landlock/cred.c +3 -3
index cc419de75cd6..58b544993db4 100644
@@ -22,7 +22,7 @@ static void hook_cred_transfer(struct cred *const new,
 	const struct landlock_cred_security *const old_llcred =
 		landlock_cred(old);
 
-	landlock_get_ruleset(old_llcred->domain);
+	landlock_get_domain(old_llcred->domain);
 	*landlock_cred(new) = *old_llcred;
 }
 
@@ -35,10 +35,10 @@ static int hook_cred_prepare(struct cred *const new,
 
 static void hook_cred_free(struct cred *const cred)
 {
-	struct landlock_ruleset *const dom = landlock_cred(cred)->domain;
+	struct landlock_domain *const dom = landlock_cred(cred)->domain;
 
 	if (dom)
-		landlock_put_ruleset_deferred(dom);
+		landlock_put_domain_deferred(dom);
 }
 
 #ifdef CONFIG_AUDIT
security/landlock/cred.h +10 -11
index f287c56b5fd4..e7830cfed041 100644
@@ -16,6 +16,7 @@
 #include <linux/rcupdate.h>
 
 #include "access.h"
+#include "domain.h"
 #include "limits.h"
 #include "ruleset.h"
 #include "setup.h"
@@ -31,9 +32,9 @@
  */
 struct landlock_cred_security {
 	/**
-	 * @domain: Immutable ruleset enforced on a task.
+	 * @domain: Immutable domain enforced on a task.
 	 */
-	struct landlock_ruleset *domain;
+	struct landlock_domain *domain;
 
 #ifdef CONFIG_AUDIT
 	/**
@@ -70,22 +71,20 @@ landlock_cred(const struct cred *cred)
 static inline void landlock_cred_copy(struct landlock_cred_security *dst,
 				      const struct landlock_cred_security *src)
 {
-	landlock_put_ruleset(dst->domain);
+	landlock_put_domain(dst->domain);
 
 	*dst = *src;
 
-	landlock_get_ruleset(src->domain);
+	landlock_get_domain(src->domain);
 }
 
-static inline struct landlock_ruleset *landlock_get_current_domain(void)
+static inline struct landlock_domain *landlock_get_current_domain(void)
 {
 	return landlock_cred(current_cred())->domain;
 }
 
-/*
- * The call needs to come from an RCU read-side critical section.
- */
-static inline const struct landlock_ruleset *
+/* The call needs to come from an RCU read-side critical section. */
+static inline const struct landlock_domain *
 landlock_get_task_domain(const struct task_struct *const task)
 {
 	return landlock_cred(__task_cred(task))->domain;
@@ -126,7 +125,7 @@ landlock_get_applicable_subject(const struct cred *const cred,
 	const union access_masks_all masks_all = {
 		.masks = masks,
 	};
-	const struct landlock_ruleset *domain;
+	const struct landlock_domain *domain;
 	ssize_t layer_level;
 
 	if (!cred)
@@ -139,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->access_masks[layer_level],
+			.masks = domain->handled_masks[layer_level],
 		};
 
 		if (layer.all & masks_all.all) {
security/landlock/domain.c +254 -4

300 lines not on this page · raw message

security/landlock/domain.h +35 -8

92 lines not on this page · raw message

security/landlock/fs.c +12 -13
index f7e5e4ef9eac..0b77d310ffd4 100644
@@ -336,12 +336,11 @@ int landlock_append_fs_rule(struct landlock_ruleset *const ruleset,
 	if (!d_is_dir(path->dentry) &&
 	    !access_mask_subset(access_rights, ACCESS_FILE))
 		return -EINVAL;
-	if (WARN_ON_ONCE(ruleset->num_layers != 1))
-		return -EINVAL;
 
 	/* Transforms relative access rights to absolute ones. */
 	access_rights |= LANDLOCK_MASK_ACCESS_FS &
-			 ~landlock_get_fs_access_mask(ruleset, 0);
+			 ~(ruleset->handled_masks.fs |
+			   _LANDLOCK_ACCESS_FS_INITIALLY_DENIED);
 	id.key.object = get_inode_object(d_backing_inode(path->dentry));
 	if (IS_ERR(id.key.object))
 		return PTR_ERR(id.key.object);
@@ -364,7 +363,7 @@ int landlock_append_fs_rule(struct landlock_ruleset *const ruleset,
  * Returns NULL if no rule is found or if @dentry is negative.
  */
 static const struct landlock_rule *
-find_rule(const struct landlock_ruleset *const domain,
+find_rule(const struct landlock_domain *const domain,
 	  const struct dentry *const dentry)
 {
 	const struct landlock_rule *rule;
@@ -749,7 +748,7 @@ static void test_is_eacces_with_write(struct kunit *const test)
  * Return: True if the access request is granted, false otherwise.
  */
 static bool
-is_access_to_paths_allowed(const struct landlock_ruleset *const domain,
+is_access_to_paths_allowed(const struct landlock_domain *const domain,
 			   const struct path *const path,
 			   const access_mask_t access_request_parent1,
 			   struct layer_masks *layer_masks_parent1,
@@ -1039,7 +1038,7 @@ static access_mask_t maybe_remove(const struct dentry *const dentry)
  * Return: True if all the domain access rights are allowed for @dir, false if
  * the walk reached @mnt_root.
  */
-static bool collect_domain_accesses(const struct landlock_ruleset *const domain,
+static bool collect_domain_accesses(const struct landlock_domain *const domain,
 				    const struct dentry *const mnt_root,
 				    struct dentry *dir,
 				    struct layer_masks *layer_masks_dom)
@@ -1589,8 +1588,8 @@ static int hook_path_truncate(const struct path *const path)
  * @masks: Layer access masks to unmask
  * @access: Access bits that control scoping
  */
-static void unmask_scoped_access(const struct landlock_ruleset *const client,
-				 const struct landlock_ruleset *const server,
+static void unmask_scoped_access(const struct landlock_domain *const client,
+				 const struct landlock_domain *const server,
 				 struct layer_masks *const masks,
 				 const access_mask_t access)
 {
@@ -1644,7 +1643,7 @@ static void unmask_scoped_access(const struct landlock_ruleset *const client,
 static int hook_unix_find(const struct path *const path, struct sock *other,
 			  int flags)
 {
-	const struct landlock_ruleset *dom_other;
+	const struct landlock_domain *dom_other;
 	const struct landlock_cred_security *subject;
 	struct layer_masks layer_masks;
 	struct landlock_request request = {};
@@ -1939,7 +1938,7 @@ static bool control_current_fowner(struct fown_struct *const fown)
 
 static void hook_file_set_fowner(struct file *file)
 {
-	struct landlock_ruleset *prev_dom;
+	struct landlock_domain *prev_dom;
 	struct landlock_cred_security fown_subject = {};
 	struct pid *prev_tg, *fown_tg = NULL;
 	size_t fown_layer = 0;
@@ -1952,7 +1951,7 @@ static void hook_file_set_fowner(struct file *file)
 			landlock_get_applicable_subject(
 				current_cred(), signal_scope, &fown_layer);
 		if (new_subject) {
-			landlock_get_ruleset(new_subject->domain);
+			landlock_get_domain(new_subject->domain);
 			fown_subject = *new_subject;
 			fown_tg = get_pid(task_tgid(current));
 		}
@@ -1967,14 +1966,14 @@ static void hook_file_set_fowner(struct file *file)
 #endif /* CONFIG_AUDIT*/
 
 	/* May be called in an RCU read-side critical section. */
-	landlock_put_ruleset_deferred(prev_dom);
+	landlock_put_domain_deferred(prev_dom);
 	put_pid(prev_tg);
 }
 
 static void hook_file_free_security(struct file *file)
 {
 	put_pid(landlock_file(file)->fown_tg);
-	landlock_put_ruleset_deferred(landlock_file(file)->fown_subject.domain);
+	landlock_put_domain_deferred(landlock_file(file)->fown_subject.domain);
 }
 
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
security/landlock/net.c +1 -2
index feecc8c77ab4..7447738ca2e6 100644
@@ -33,8 +33,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 &
-			 ~landlock_get_net_access_mask(ruleset, 0);
+	access_rights |= LANDLOCK_MASK_ACCESS_NET & ~ruleset->handled_masks.net;
 
 	mutex_lock(&ruleset->lock);
 	err = landlock_insert_rule(ruleset, id, access_rights, flags);
security/landlock/ruleset.c +41 -297

420 lines not on this page · raw message

security/landlock/ruleset.h +23 -118

177 lines not on this page · raw message

security/landlock/syscalls.c +4 -6
index 36b02892c62f..fe8505dc0ba5 100644
@@ -308,8 +308,6 @@ static struct landlock_ruleset *get_ruleset_from_fd(const int fd,
 	if (!(fd_file(ruleset_f)->f_mode & mode))
 		return ERR_PTR(-EPERM);
 	ruleset = fd_file(ruleset_f)->private_data;
-	if (WARN_ON_ONCE(ruleset->num_layers != 1))
-		return ERR_PTR(-EINVAL);
 	landlock_get_ruleset(ruleset);
 	return ruleset;
 }
@@ -367,7 +365,7 @@ static int add_rule_path_beneath(struct landlock_ruleset *const ruleset,
 		return -ENOMSG;
 
 	/* Checks that allowed_access matches the @ruleset constraints. */
-	mask = ruleset->access_masks[0].fs;
+	mask = ruleset->handled_masks.fs;
 	if ((path_beneath_attr.allowed_access | mask) != mask)
 		return -EINVAL;
 
@@ -408,7 +406,7 @@ static int add_rule_net_port(struct landlock_ruleset *ruleset,
 		return -ENOMSG;
 
 	/* Checks that allowed_access matches the @ruleset constraints. */
-	mask = landlock_get_net_access_mask(ruleset, 0);
+	mask = ruleset->handled_masks.net;
 	if ((net_port_attr.allowed_access | mask) != mask)
 		return -EINVAL;
 
@@ -595,7 +593,7 @@ SYSCALL_DEFINE2(landlock_restrict_self, const int, ruleset_fd, const __u32,
 		 * manipulating the current credentials because they are
 		 * dedicated per thread.
 		 */
-		struct landlock_ruleset *const new_dom =
+		struct landlock_domain *const new_dom =
 			landlock_merge_ruleset(new_llcred->domain, ruleset);
 		if (IS_ERR(new_dom)) {
 			abort_creds(new_cred);
@@ -610,7 +608,7 @@ SYSCALL_DEFINE2(landlock_restrict_self, const int, ruleset_fd, const __u32,
 #endif /* CONFIG_AUDIT */
 
 		/* Replaces the old (prepared) domain. */
-		landlock_put_ruleset(new_llcred->domain);
+		landlock_put_domain(new_llcred->domain);
 		new_llcred->domain = new_dom;
 
 #ifdef CONFIG_AUDIT
security/landlock/task.c +10 -10
index 360d226d0f51..40e6bfa4bc75 100644
@@ -41,8 +41,8 @@
  * Return: True if @parent is an ancestor of or equal to @child, false
  * otherwise.
  */
-static bool domain_scope_le(const struct landlock_ruleset *const parent,
-			    const struct landlock_ruleset *const child)
+static bool domain_scope_le(const struct landlock_domain *const parent,
+			    const struct landlock_domain *const child)
 {
 	const struct landlock_hierarchy *walker;
 
@@ -63,8 +63,8 @@ static bool domain_scope_le(const struct landlock_ruleset *const parent,
 	return false;
 }
 
-static int domain_ptrace(const struct landlock_ruleset *const parent,
-			 const struct landlock_ruleset *const child)
+static int domain_ptrace(const struct landlock_domain *const parent,
+			 const struct landlock_domain *const child)
 {
 	if (domain_scope_le(parent, child))
 		return 0;
@@ -96,7 +96,7 @@ static int hook_ptrace_access_check(struct task_struct *const child,
 		return 0;
 
 	scoped_guard(rcu) {
-		const struct landlock_ruleset *const child_dom =
+		const struct landlock_domain *const child_dom =
 			landlock_get_task_domain(child);
 		err = domain_ptrace(parent_subject->domain, child_dom);
 	}
@@ -135,7 +135,7 @@ static int hook_ptrace_access_check(struct task_struct *const child,
 static int hook_ptrace_traceme(struct task_struct *const parent)
 {
 	const struct landlock_cred_security *parent_subject;
-	const struct landlock_ruleset *child_dom;
+	const struct landlock_domain *child_dom;
 	int err;
 
 	child_dom = landlock_get_current_domain();
@@ -176,8 +176,8 @@ static int hook_ptrace_traceme(struct task_struct *const parent)
  * Return: True if @server is in a different domain from @client and @client
  * is scoped to access @server (i.e. access should be denied), false otherwise.
  */
-static bool domain_is_scoped(const struct landlock_ruleset *const client,
-			     const struct landlock_ruleset *const server,
+static bool domain_is_scoped(const struct landlock_domain *const client,
+			     const struct landlock_domain *const server,
 			     access_mask_t scope)
 {
 	int client_layer, server_layer;
@@ -236,9 +236,9 @@ static bool domain_is_scoped(const struct landlock_ruleset *const client,
 }
 
 static bool sock_is_scoped(struct sock *const other,
-			   const struct landlock_ruleset *const domain)
+			   const struct landlock_domain *const domain)
 {
-	const struct landlock_ruleset *dom_other;
+	const struct landlock_domain *dom_other;
 
 	/* The credentials will not change. */
 	lockdep_assert_held(&unix_sk(other)->lock);
Signature · 1 line
2.54.0
#4 lore raw

Re: [PATCH v3 03/20] landlock: Split struct landlock_domain from struct landlock_ruleset

Quoted 8 lines · Mickaël Salaün

Switch all domain users to the new struct landlock_domain type introduced by a previous commit, eliminating the conflation between mutable rulesets and immutable domains. landlock_merge_ruleset() now returns and allocates a struct landlock_domain, and the merge and inherit helpers move next to it; the former static insert_rule() is exported as landlock_rule_insert() for its new caller across the translation-unit boundary.

Seems a little confusing that we have

landlock_rule_insert()

and

landlock_insert_rule()

Maybe a rename of one these would be appropriate?

Otherwise looks good :)

Justin

Quoted 1 line

[...]

author maintainer
#5 lore raw

Re: [PATCH v3 03/20] landlock: Split struct landlock_domain from struct landlock_ruleset

Quoted 9 lines · Justin Suess
Quoted 8 lines · Mickaël Salaün

Switch all domain users to the new struct landlock_domain type introduced by a previous commit, eliminating the conflation between mutable rulesets and immutable domains. landlock_merge_ruleset() now returns and allocates a struct landlock_domain, and the merge and inherit helpers move next to it; the former static insert_rule() is exported as landlock_rule_insert() for its new caller across the translation-unit boundary.

Quoted 3 lines

Seems a little confusing that we have

landlock_rule_insert()

(the new one)

Quoted 4 lines

and

landlock_insert_rule()

(the existing one)

Quoted 2 lines

Maybe a rename of one these would be appropriate?

It's indeed confusing... What about landlock_store_rule()? I couldn't find anything better given the already taken names.

Quoted 6 lines

Otherwise looks good :)

Justin

Quoted 1 line

[...]

author maintainer
#6 lore raw

PATCH v3 4/20 landlock: Split denial logging from audit into common framework

In reply to Mickaël Salaün

Tracepoint emission requires the denial framework (layer identification, request validation) without depending on CONFIG_AUDIT. Separate the denial logging infrastructure from the audit-specific code by introducing a common log framework.

Create CONFIG_SECURITY_LANDLOCK_LOG, enabled by default when CONFIG_AUDIT is set; a following commit extends it to CONFIG_TRACEPOINTS when the first tracepoint consumer is added. Move the common framework (the request types, the layer identification and request validation, and the landlock_log_denial() and landlock_log_free_domain() entry points) into log.c and log.h, and keep the audit-specific record formatting in audit.c. log.o is built for CONFIG_SECURITY_LANDLOCK_LOG and audit.o for CONFIG_AUDIT, so the common framework is available to a tracepoints-only build. The entry points dispatch to no-op static inline audit stubs without CONFIG_AUDIT, so the call sites stay unconditional. Rename the former landlock_log_drop_domain() to landlock_log_free_domain() to match the landlock_free_domain tracepoint added in a following commit.

landlock_log_denial() counts denials even without audit, so its declaration and no-op stub are guarded by CONFIG_SECURITY_LANDLOCK_LOG, not CONFIG_AUDIT; a CONFIG_AUDIT guard would expose the stub and clash with log.c's definition in a tracepoints-only build.

Widen the ID allocation (id.o and the landlock_init_id() / landlock_get_id_range() declarations) and the log-state representation (the domain_exec and log_subdomains_off credential fields, the landlock_hierarchy log fields, and the code that maintains them) from CONFIG_AUDIT to CONFIG_SECURITY_LANDLOCK_LOG, so each field and its writer share one guard and are available to tracing without audit support.

Widen the denial-path state that feeds the per-denial logging decision the same way, so the "logged" verdict is computed identically whether or not CONFIG_AUDIT is set. Widening fown_layer is what keeps the file-owner-signal path valid without audit: otherwise hook_file_send_sigiotask() would leave layer_plus_one at zero, tripping the is_valid_request() canary and dropping the LANDLOCK_SCOPE_SIGNAL denial from tracing.

The ruleset-level quiet_masks stays on no CONFIG guard: it is builder state validated and stored from user input, kept available so LANDLOCK_ADD_RULE_QUIET flags are accepted and ignored, not rejected, when CONFIG_SECURITY_LANDLOCK_LOG is disabled.

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Split the denial logging into a common framework (landlock_log_denial() and landlock_log_free_domain(), layer identification, request validation) and the audit-specific record formatting (landlock_audit_denial(), landlock_audit_free_domain()) built as separate translation units, each gated by its own CONFIG, instead of renaming audit.c to log.c. The dispatchers reach the audit helpers through no-op stubs so the call sites stay unconditional.
- Gate CONFIG_SECURITY_LANDLOCK_LOG on CONFIG_AUDIT only; a following commit extends it to CONFIG_TRACEPOINTS with the first tracepoint.
- Move the log_subdomains_off credential field and the log-state writers (hook_bprm_creds_for_exec(), the landlock_restrict_self() log assignments) to CONFIG_SECURITY_LANDLOCK_LOG alongside domain_exec and the hierarchy log fields, so each field and its writer share one guard.
- Thread the base's quiet flag through the split (object_quiet parameter to landlock_audit_denial()).
- Widen the quiet consumer state and the file-owner-signal layer identification (fown_layer) from CONFIG_AUDIT to CONFIG_SECURITY_LANDLOCK_LOG so the per-denial logged verdict is computed identically whether CONFIG_AUDIT is set; the ruleset-level quiet_masks stays ungated to accept and ignore quiet flags when the log framework is disabled.

Changes since v1:
- New patch.

---
 security/landlock/Kconfig    |   5 +
 security/landlock/Makefile   |   6 +-
 security/landlock/access.h   |   4 +-
 security/landlock/audit.c    | 485 ++-------------------------------
 security/landlock/audit.h    |  61 ++---
 security/landlock/cred.c     |   8 +-
 security/landlock/cred.h     |   8 +-
 security/landlock/domain.c   |  24 +-
 security/landlock/domain.h   |  14 +-
 security/landlock/fs.c       |  27 +-
 security/landlock/fs.h       |   8 +-
 security/landlock/id.h       |   6 +-
 security/landlock/log.c      | 502 +++++++++++++++++++++++++++++++++++
 security/landlock/log.h      |  77 ++++++
 security/landlock/net.c      |   2 +-
 security/landlock/syscalls.c |  12 +-
 security/landlock/task.c     |   6 +-
 17 files changed, 685 insertions(+), 570 deletions(-)
 create mode 100644 security/landlock/log.c
 create mode 100644 security/landlock/log.h
security/landlock/Kconfig +5 -0
index 3f1493402052..b4e7f0e9ba9b 100644
@@ -21,6 +21,11 @@ config SECURITY_LANDLOCK
 	  you should also prepend "landlock," to the content of CONFIG_LSM to
 	  enable Landlock at boot time.
 
+config SECURITY_LANDLOCK_LOG
+	bool
+	depends on SECURITY_LANDLOCK
+	default y if AUDIT
+
 config SECURITY_LANDLOCK_KUNIT_TEST
 	bool "KUnit tests for Landlock" if !KUNIT_ALL_TESTS
 	depends on KUNIT=y
security/landlock/Makefile +4 -2
index 23e13644916f..2462e6c5921e 100644
@@ -13,6 +13,8 @@ landlock-y := \
 
 landlock-$(CONFIG_INET) += net.o
 
-landlock-$(CONFIG_AUDIT) += \
+landlock-$(CONFIG_SECURITY_LANDLOCK_LOG) += \
 	id.o \
-	audit.o
+	log.o
+
+landlock-$(CONFIG_AUDIT) += audit.o
security/landlock/access.h +2 -2
index 1a8227a709d9..bbbb41f41147 100644
@@ -74,13 +74,13 @@ struct layer_mask {
 	 * @access: The unfulfilled access rights for this layer.
 	 */
 	access_mask_t access : LANDLOCK_NUM_ACCESS_MAX;
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 	/**
 	 * @quiet: Whether we have encountered a rule with the quiet flag for
 	 * this layer.  Used to control logging.
 	 */
 	access_mask_t quiet : 1;
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 } __packed __aligned(sizeof(access_mask_t));
 
 /*
security/landlock/audit.c +19 -466

534 lines not on this page · raw message

security/landlock/audit.h +16 -45

84 lines not on this page · raw message

security/landlock/cred.c +4 -4
index 58b544993db4..03449c26247e 100644
@@ -41,7 +41,7 @@ static void hook_cred_free(struct cred *const cred)
 		landlock_put_domain_deferred(dom);
 }
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 
 static int hook_bprm_creds_for_exec(struct linux_binprm *const bprm)
 {
@@ -50,16 +50,16 @@ static int hook_bprm_creds_for_exec(struct linux_binprm *const bprm)
 	return 0;
 }
 
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(cred_prepare, hook_cred_prepare),
 	LSM_HOOK_INIT(cred_transfer, hook_cred_transfer),
 	LSM_HOOK_INIT(cred_free, hook_cred_free),
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 	LSM_HOOK_INIT(bprm_creds_for_exec, hook_bprm_creds_for_exec),
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 };
 
 __init void landlock_add_cred_hooks(void)
security/landlock/cred.h +4 -4
index e7830cfed041..a5ff9957949a 100644
@@ -36,7 +36,7 @@ struct landlock_cred_security {
 	 */
 	struct landlock_domain *domain;
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 	/**
 	 * @domain_exec: Bitmask identifying the domain layers that were enforced by
 	 * the current task's executed file (i.e. no new execve(2) since
@@ -50,17 +50,17 @@ struct landlock_cred_security {
 	 * not require a current domain.
 	 */
 	u8 log_subdomains_off : 1;
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 } __packed;
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 
 /* Makes sure all layer executions can be stored. */
 static_assert(BITS_PER_TYPE(typeof_member(struct landlock_cred_security,
 					  domain_exec)) >=
 	      LANDLOCK_MAX_NUM_LAYERS);
 
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 
 static inline struct landlock_cred_security *
 landlock_cred(const struct cred *cred)
security/landlock/domain.c +14 -10
index 2e0d75175c2a..6444cf27bda2 100644
@@ -171,11 +171,11 @@ bool landlock_unmask_layers(const struct landlock_rule *const rule,
 		/* Clear the bits where the layer in the rule grants access. */
 		masks->layers[layer->level - 1].access &= ~layer->access;
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 		/* Collect rule flags for each layer. */
 		if (layer->flags.quiet)
 			masks->layers[layer->level - 1].quiet = true;
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 	}
 
 	for (size_t i = 0; i < ARRAY_SIZE(masks->layers); i++) {
@@ -238,16 +238,16 @@ landlock_init_layer_masks(const struct landlock_domain *const domain,
 
 		masks->layers[i].access = access_request & handled;
 		handled_accesses |= masks->layers[i].access;
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 		masks->layers[i].quiet = false;
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 	}
 	for (size_t i = domain->num_layers; i < ARRAY_SIZE(masks->layers);
 	     i++) {
 		masks->layers[i].access = 0;
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 		masks->layers[i].quiet = false;
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 	}
 
 	return handled_accesses;
@@ -464,14 +464,14 @@ landlock_merge_ruleset(struct landlock_domain *const parent,
 	if (err)
 		return ERR_PTR(err);
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 	new_dom->hierarchy->quiet_masks = ruleset->quiet_masks;
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 
 	return no_free_ptr(new_dom);
 }
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 
 /**
  * get_current_exe - Get the current's executable path, if any
@@ -582,6 +582,10 @@ int landlock_init_hierarchy_log(struct landlock_hierarchy *const hierarchy)
 	return 0;
 }
 
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
+
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
+
 static deny_masks_t
 get_layer_deny_mask(const access_mask_t all_existing_optional_access,
 		    const unsigned long access_bit, const size_t layer)
@@ -753,4 +757,4 @@ kunit_test_suite(test_suite);
 
 #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
 
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
security/landlock/domain.h +7 -7
index f0925297dcba..1237e3e25240 100644
@@ -21,7 +21,7 @@
 #include <linux/workqueue.h>
 
 #include "access.h"
-#include "audit.h"
+#include "log.h"
 #include "ruleset.h"
 
 enum landlock_log_status {
@@ -84,7 +84,7 @@ struct landlock_hierarchy {
 	 */
 	refcount_t usage;
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 	/**
 	 * @log_status: Whether this domain should be logged or not.  Because
 	 * concurrent log entries may be created at the same time, it is still
@@ -119,10 +119,10 @@ struct landlock_hierarchy {
 	 * logged) if the related object is marked as quiet.
 	 */
 	struct access_masks quiet_masks;
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 };
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 
 deny_masks_t
 landlock_get_deny_masks(const access_mask_t all_existing_optional_access,
@@ -145,7 +145,7 @@ landlock_free_hierarchy_details(struct landlock_hierarchy *const hierarchy)
 	kfree(hierarchy->details);
 }
 
-#else /* CONFIG_AUDIT */
+#else /* CONFIG_SECURITY_LANDLOCK_LOG */
 
 static inline int
 landlock_init_hierarchy_log(struct landlock_hierarchy *const hierarchy)
@@ -158,7 +158,7 @@ landlock_free_hierarchy_details(struct landlock_hierarchy *const hierarchy)
 {
 }
 
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 
 static inline void
 landlock_get_hierarchy(struct landlock_hierarchy *const hierarchy)
@@ -172,7 +172,7 @@ static inline void landlock_put_hierarchy(struct landlock_hierarchy *hierarchy)
 	while (hierarchy && refcount_dec_and_test(&hierarchy->usage)) {
 		const struct landlock_hierarchy *const freeme = hierarchy;
 
-		landlock_log_drop_domain(hierarchy);
+		landlock_log_free_domain(hierarchy);
 		landlock_free_hierarchy_details(hierarchy);
 		hierarchy = hierarchy->parent;
 		kfree(freeme);
security/landlock/fs.c +14 -13
index 0b77d310ffd4..d39da6e9fa8c 100644
@@ -42,12 +42,12 @@
 #include <uapi/linux/landlock.h>
 
 #include "access.h"
-#include "audit.h"
 #include "common.h"
 #include "cred.h"
 #include "domain.h"
 #include "fs.h"
 #include "limits.h"
+#include "log.h"
 #include "object.h"
 #include "ruleset.h"
 #include "setup.h"
@@ -932,10 +932,11 @@ is_access_to_paths_allowed(const struct landlock_domain *const domain,
 	path_put(&walker_path);
 
 	/*
-	 * Check CONFIG_AUDIT to enable elision of log_request_parent* and
-	 * associated caller's stack variables thanks to dead code elimination.
+	 * Check CONFIG_SECURITY_LANDLOCK_LOG to enable elision of
+	 * log_request_parent* and associated caller's stack variables thanks to
+	 * dead code elimination.
 	 */
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 	if (!allowed_parent1 && log_request_parent1) {
 		log_request_parent1->type = LANDLOCK_REQUEST_FS_ACCESS;
 		log_request_parent1->audit.type = LSM_AUDIT_DATA_PATH;
@@ -951,7 +952,7 @@ is_access_to_paths_allowed(const struct landlock_domain *const domain,
 		log_request_parent2->access = access_masked_parent2;
 		log_request_parent2->layer_masks = layer_masks_parent2;
 	}
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 
 	return allowed_parent1 && allowed_parent2;
 }
@@ -1801,14 +1802,14 @@ static int hook_file_open(struct file *const file)
 	 * file access rights in the opened struct file.
 	 */
 	landlock_file(file)->allowed_access = allowed_access;
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 	landlock_file(file)->deny_masks = landlock_get_deny_masks(
 		_LANDLOCK_ACCESS_FS_OPTIONAL, optional_access, &layer_masks);
 	landlock_file(file)->quiet_optional_accesses =
 		landlock_get_quiet_optional_accesses(
 			_LANDLOCK_ACCESS_FS_OPTIONAL,
 			landlock_file(file)->deny_masks, &layer_masks);
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 
 	if (access_mask_subset(open_access_request, allowed_access))
 		return 0;
@@ -1842,10 +1843,10 @@ static int hook_file_truncate(struct file *const file)
 		},
 		.all_existing_optional_access = _LANDLOCK_ACCESS_FS_OPTIONAL,
 		.access = LANDLOCK_ACCESS_FS_TRUNCATE,
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 		.deny_masks = landlock_file(file)->deny_masks,
 		.quiet_optional_accesses = landlock_file(file)->quiet_optional_accesses,
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 	});
 	return -EACCES;
 }
@@ -1882,10 +1883,10 @@ static int hook_file_ioctl_common(const struct file *const file,
 		},
 		.all_existing_optional_access = _LANDLOCK_ACCESS_FS_OPTIONAL,
 		.access = LANDLOCK_ACCESS_FS_IOCTL_DEV,
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 		.deny_masks = landlock_file(file)->deny_masks,
 		.quiet_optional_accesses = landlock_file(file)->quiet_optional_accesses,
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 	});
 	return -EACCES;
 }
@@ -1961,9 +1962,9 @@ static void hook_file_set_fowner(struct file *file)
 	prev_tg = landlock_file(file)->fown_tg;
 	landlock_file(file)->fown_subject = fown_subject;
 	landlock_file(file)->fown_tg = fown_tg;
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 	landlock_file(file)->fown_layer = fown_layer;
-#endif /* CONFIG_AUDIT*/
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 
 	/* May be called in an RCU read-side critical section. */
 	landlock_put_domain_deferred(prev_dom);
security/landlock/fs.h +4 -4
index b4421d9df68f..c16f24e30bd5 100644
@@ -57,7 +57,7 @@ struct landlock_file_security {
 	 */
 	access_mask_t allowed_access;
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 	/**
 	 * @deny_masks: Domain layer levels that deny an optional access (see
 	 * _LANDLOCK_ACCESS_FS_OPTIONAL).
@@ -75,7 +75,7 @@ struct landlock_file_security {
 	 * LANDLOCK_SCOPE_SIGNAL.
 	 */
 	u8 fown_layer;
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 
 	/**
 	 * @fown_subject: Landlock credential of the task that set the PID that
@@ -97,7 +97,7 @@ struct landlock_file_security {
 	struct pid *fown_tg;
 };
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 
 /* Makes sure all layers can be identified. */
 /* clang-format off */
@@ -113,7 +113,7 @@ static_assert(BITS_PER_TYPE(typeof_member(struct landlock_file_security,
 					  quiet_optional_accesses)) >=
 	      HWEIGHT(_LANDLOCK_ACCESS_FS_OPTIONAL));
 
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 
 /**
  * struct landlock_superblock_security - Superblock security blob
security/landlock/id.h +3 -3
index 45dcfb9e9a8b..2a43c2b523a8 100644
@@ -8,18 +8,18 @@
 #ifndef _SECURITY_LANDLOCK_ID_H
 #define _SECURITY_LANDLOCK_ID_H
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 
 void __init landlock_init_id(void);
 
 u64 landlock_get_id_range(size_t number_of_ids);
 
-#else /* CONFIG_AUDIT */
+#else /* CONFIG_SECURITY_LANDLOCK_LOG */
 
 static inline void __init landlock_init_id(void)
 {
 }
 
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 
 #endif /* _SECURITY_LANDLOCK_ID_H */
security/landlock/log.c new file +502 -0

502 lines not on this page · raw message

security/landlock/log.h new file +77 -0

77 lines not on this page · raw message

security/landlock/net.c +1 -1
index 7447738ca2e6..e27b3ba15664 100644
@@ -12,11 +12,11 @@
 #include <linux/socket.h>
 #include <net/ipv6.h>
 
-#include "audit.h"
 #include "common.h"
 #include "cred.h"
 #include "domain.h"
 #include "limits.h"
+#include "log.h"
 #include "net.h"
 #include "ruleset.h"
 
security/landlock/syscalls.c +6 -6
index fe8505dc0ba5..0ad20a6f9564 100644
@@ -574,11 +574,11 @@ SYSCALL_DEFINE2(landlock_restrict_self, const int, ruleset_fd, const __u32,
 
 	new_llcred = landlock_cred(new_cred);
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 	prev_log_subdomains = !new_llcred->log_subdomains_off;
 	new_llcred->log_subdomains_off = !prev_log_subdomains ||
 					 !log_subdomains;
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 
 	/*
 	 * The only case when a ruleset may not be set is if
@@ -600,20 +600,20 @@ SYSCALL_DEFINE2(landlock_restrict_self, const int, ruleset_fd, const __u32,
 			return PTR_ERR(new_dom);
 		}
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 		new_dom->hierarchy->log_same_exec = log_same_exec;
 		new_dom->hierarchy->log_new_exec = log_new_exec;
 		if ((!log_same_exec && !log_new_exec) || !prev_log_subdomains)
 			new_dom->hierarchy->log_status = LANDLOCK_LOG_DISABLED;
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 
 		/* Replaces the old (prepared) domain. */
 		landlock_put_domain(new_llcred->domain);
 		new_llcred->domain = new_dom;
 
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 		new_llcred->domain_exec |= BIT(new_dom->num_layers - 1);
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 	}
 
 	if (flags & LANDLOCK_RESTRICT_SELF_TSYNC) {
security/landlock/task.c +3 -3
index 40e6bfa4bc75..c0da22736ea0 100644
@@ -20,11 +20,11 @@
 #include <net/af_unix.h>
 #include <net/sock.h>
 
-#include "audit.h"
 #include "common.h"
 #include "cred.h"
 #include "domain.h"
 #include "fs.h"
+#include "log.h"
 #include "ruleset.h"
 #include "setup.h"
 #include "task.h"
@@ -435,9 +435,9 @@ static int hook_file_send_sigiotask(struct task_struct *tsk,
 			.type = LSM_AUDIT_DATA_TASK,
 			.u.tsk = tsk,
 		},
-#ifdef CONFIG_AUDIT
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
 		.layer_plus_one = landlock_file(fown->file)->fown_layer + 1,
-#endif /* CONFIG_AUDIT */
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
 	});
 	return -EPERM;
 }
Signature · 1 line
2.54.0
author maintainer
#7 lore raw

PATCH v3 5/20 landlock: Decouple the per-denial logging decision from CONFIG_AUDIT

In reply to Mickaël Salaün

Until now, whether a denial is logged was decided inside landlock_audit_denial(): a per-execution flag check (log_same_exec or log_new_exec, selected by the credential's domain_exec bitmask), preceded by a LANDLOCK_LOG_DISABLED early return in landlock_log_denial() for domains an ancestor fully quieted.

Factor that decision into a single is_denial_logged() helper called once by landlock_log_denial(), and pass its result to landlock_audit_denial() as a "logged" boolean. A following commit passes the same boolean to the deny tracepoints, so audit and tracing share one decision that stays correct as new log state is added, and a tracepoints-only build (CONFIG_AUDIT=n) computes it identically. Computing the logged verdict once in the shared helper makes audit and tracing apply identical filtering, so they cannot report different logged= values for the same denial as log controls grow.

Move the LANDLOCK_LOG_DISABLED gate out of landlock_log_denial() into the decision so num_denials counts every denial, including those a domain quiets. This was previously masked: the only reader of num_denials is the audit "domain deallocated" record, emitted only for domains that reached LANDLOCK_LOG_RECORDED; a fully quieted domain never records, so its undercount was never observable. A following commit adds a free_domain tracepoint that reports num_denials, which needs the full count.

This is not a functional change for audit: the logged decision and the audit_enabled gate are preserved, so the emitted records are identical.

Cc Günther Noack <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
- New patch.

---
 security/landlock/audit.c | 90 ++++-----------------------------------
 security/landlock/audit.h | 14 ++----
 security/landlock/log.c   | 88 ++++++++++++++++++++++++++++++++++++--
 3 files changed, 97 insertions(+), 95 deletions(-)
security/landlock/audit.c +9 -81
index dfa1e5a64aac..32260e7cbfe9 100644
@@ -136,104 +136,32 @@ static void log_domain(struct landlock_hierarchy *const hierarchy)
 	WRITE_ONCE(hierarchy->log_status, LANDLOCK_LOG_RECORDED);
 }
 
-static access_mask_t
-pick_access_mask_for_request_type(const enum landlock_request_type type,
-				  const struct access_masks access_masks)
-{
-	switch (type) {
-	case LANDLOCK_REQUEST_FS_ACCESS:
-		return access_masks.fs;
-	case LANDLOCK_REQUEST_NET_ACCESS:
-		return access_masks.net;
-	default:
-		WARN_ONCE(1, "Invalid request type %d passed to %s", type,
-			  __func__);
-		return 0;
-	}
-}
-
 /**
  * landlock_audit_denial - Create an audit record for a denied access request
  *
- * @subject: The Landlock subject's credential denying an action.
  * @request: Detail of the user space request.
  * @youngest_denied: The youngest hierarchy node that denied the access.
- * @youngest_layer: The layer index of @youngest_denied.
  * @missing: The set of denied access rights.
- * @object_quiet_flag: Whether the object denied by @youngest_denied is
- *                     covered by a quiet rule in that layer.
+ * @logged: Whether the denial is selected for logging, as computed by
+ *          landlock_log_denial() (domain policy and quiet rules).
  *
- * Called from landlock_log_denial() with the same arguments.
+ * Emits the record when audit is enabled and the denial is selected for
+ * logging.
  */
-void landlock_audit_denial(const struct landlock_cred_security *const subject,
-			   const struct landlock_request *const request,
+void landlock_audit_denial(const struct landlock_request *const request,
 			   struct landlock_hierarchy *const youngest_denied,
-			   const size_t youngest_layer,
-			   const access_mask_t missing,
-			   const bool object_quiet_flag)
+			   const access_mask_t missing, const bool logged)
 {
 	struct audit_buffer *ab;
-	bool quiet_applicable_to_access = false;
 
 	if (!audit_enabled)
 		return;
 
-	/* Checks if the current exec was restricting itself. */
-	if (subject->domain_exec & BIT(youngest_layer)) {
-		/* Ignores denials for the same execution. */
-		if (!youngest_denied->log_same_exec)
-			return;
-	} else {
-		/* Ignores denials after a new execution. */
-		if (!youngest_denied->log_new_exec)
-			return;
-	}
-
 	/*
-	 * Checks if the object is marked quiet by the layer that denied the
-	 * request.  If it's a different layer that marked it as quiet, but that
-	 * layer is not the one that denied the request, we should still audit
-	 * log the denial.
+	 * Skips denials the domain's policy or a quiet rule excludes from
+	 * logging (folded into @logged by landlock_log_denial()).
 	 */
-	if (object_quiet_flag) {
-		/*
-		 * We now check if the denied requests are all covered by the
-		 * layer's quiet access bits.
-		 */
-		const access_mask_t quiet_mask =
-			pick_access_mask_for_request_type(
-				request->type, youngest_denied->quiet_masks);
-
-		quiet_applicable_to_access = (quiet_mask & missing) == missing;
-	} else {
-		/*
-		 * Either the object is not quiet, or this is a scope request.
-		 * We check request->type to distinguish between the two cases.
-		 */
-		const access_mask_t quiet_mask =
-			youngest_denied->quiet_masks.scope;
-
-		switch (request->type) {
-		case LANDLOCK_REQUEST_SCOPE_SIGNAL:
-			quiet_applicable_to_access =
-				!!(quiet_mask & LANDLOCK_SCOPE_SIGNAL);
-			break;
-		case LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET:
-			quiet_applicable_to_access =
-				!!(quiet_mask &
-				   LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET);
-			break;
-		/*
-		 * Leave LANDLOCK_REQUEST_PTRACE and
-		 * LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY unhandled for now - they
-		 * are never quiet.
-		 */
-		default:
-			break;
-		}
-	}
-
-	if (quiet_applicable_to_access)
+	if (!logged)
 		return;
 
 	/* Uses consistent allocation flags wrt common_lsm_audit(). */
security/landlock/audit.h +4 -10
index 1b36bb3c6cfd..14a514065e08 100644
@@ -12,18 +12,14 @@
 
 #include "access.h"
 
-struct landlock_cred_security;
 struct landlock_hierarchy;
 struct landlock_request;
 
 #ifdef CONFIG_AUDIT
 
-void landlock_audit_denial(const struct landlock_cred_security *const subject,
-			   const struct landlock_request *const request,
+void landlock_audit_denial(const struct landlock_request *const request,
 			   struct landlock_hierarchy *const youngest_denied,
-			   const size_t youngest_layer,
-			   const access_mask_t missing,
-			   const bool object_quiet_flag);
+			   const access_mask_t missing, const bool logged);
 
 void landlock_audit_free_domain(
 	const struct landlock_hierarchy *const hierarchy);
@@ -31,11 +27,9 @@ void landlock_audit_free_domain(
 #else /* CONFIG_AUDIT */
 
 static inline void
-landlock_audit_denial(const struct landlock_cred_security *const subject,
-		      const struct landlock_request *const request,
+landlock_audit_denial(const struct landlock_request *const request,
 		      struct landlock_hierarchy *const youngest_denied,
-		      const size_t youngest_layer, const access_mask_t missing,
-		      const bool object_quiet_flag)
+		      const access_mask_t missing, const bool logged)
 {
 }
 
security/landlock/log.c +84 -4

106 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#8 lore raw

PATCH v3 6/20 landlock: Consolidate access-right and scope names in a shared header

In reply to Mickaël Salaün

Audit formats denial records with per-right name strings. A following commit adds trace events that print the same access and scope masks with __print_flags() and need the same names, but a trace event header cannot include Landlock-internal headers, so the names cannot be shared from the logging unit.

Define the filesystem, network, and scope names once, as the _LANDLOCK_ACCESS_FS_NAMES, _LANDLOCK_ACCESS_NET_NAMES, and _LANDLOCK_SCOPE_NAMES lists in the public Landlock header. Each entry is a _LANDLOCK_NAME_ENTRY() the consumer expands: audit maps it to a "[bit] = name" array slot for an O(1) lookup, the trace events map it to a __print_flags() { mask, name } pair. The bit value comes only from the LANDLOCK_* UAPI constant each entry references, so every bit-to-name mapping has a single source and does not depend on entry order.

The shared names are unprefixed; blocker_prefix() prepends the fs./net./scope. category for audit records, so the scope names move from inline literals to the shared table too. Audit records are unchanged.

No functional change.

Cc Günther Noack <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
- New patch.

---
 MAINTAINERS               |  1 +
 include/linux/landlock.h  | 55 +++++++++++++++++++++++++
 security/landlock/audit.c | 84 ++++++++++++++++++++++++---------------
 3 files changed, 109 insertions(+), 31 deletions(-)
 create mode 100644 include/linux/landlock.h
MAINTAINERS +1 -0
index a674e36529f7..91de7e3c2836 100644
@@ -14598,6 +14598,7 @@ F:	Documentation/admin-guide/LSM/landlock.rst
 F:	Documentation/security/landlock.rst
 F:	Documentation/userspace-api/landlock.rst
 F:	fs/ioctl.c
+F:	include/linux/landlock.h
 F:	include/uapi/linux/landlock.h
 F:	samples/landlock/
 F:	security/landlock/
include/linux/landlock.h new file +55 -0

55 lines not on this page · raw message

security/landlock/audit.c +53 -31

136 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#9 lore raw

PATCH v3 7/20 tracing: Add __print_untrusted_str()

In reply to Mickaël Salaün

Landlock tracepoints expose filesystem paths and process names that may contain spaces, equal signs, or other characters that break ftrace field parsing.

Add a __print_untrusted_str() TP_printk helper that escapes separators (space, equal sign), quotes, backslashes, and non-printable bytes via string_escape_mem(), so an untrusted string cannot inject field separators or control characters into the ftrace output and can be unambiguously recovered.

This guarantee applies to the in-kernel ftrace text output (trace, trace_pipe). Userspace libtraceevent (perf, trace-cmd) does not yet parse this helper, so a companion libtraceevent change is needed for those consumers to pretty-print the field.

Cc Günther Noack <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Mathieu Desnoyers <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Add a Return: kdoc for trace_print_untrusted_str_seq() and rename its declaration parameter to src.

Changes since v1:
https://patch.msgid.link/[email protected]
- Remove WARN_ON() (pointed out by Steven Rostedt).

---
 include/linux/trace_events.h               |  2 +
 include/trace/stages/stage3_trace_output.h |  4 ++
 include/trace/stages/stage7_class_define.h |  1 +
 kernel/trace/trace_output.c                | 44 ++++++++++++++++++++++
 4 files changed, 51 insertions(+)
include/linux/trace_events.h +2 -0
index 308c76b57d13..4ece9b8d9d6b 100644
@@ -60,6 +60,8 @@ trace_print_hex_dump_seq(struct trace_seq *p, const char *prefix_str,
 			 int prefix_type, int rowsize, int groupsize,
 			 const void *buf, size_t len, bool ascii);
 
+const char *trace_print_untrusted_str_seq(struct trace_seq *s, const char *src);
+
 int trace_raw_output_prep(struct trace_iterator *iter,
 			  struct trace_event *event);
 extern __printf(2, 3)
include/trace/stages/stage3_trace_output.h +4 -0
index 181b81335781..0235dbd11b52 100644
@@ -133,6 +133,10 @@
 	trace_print_hex_dump_seq(p, prefix_str, prefix_type,		\
 				 rowsize, groupsize, buf, len, ascii)
 
+#undef __print_untrusted_str
+#define __print_untrusted_str(str)					\
+		trace_print_untrusted_str_seq(p, __get_str(str))
+
 #undef __print_ns_to_secs
 #define __print_ns_to_secs(value)			\
 	({						\
include/trace/stages/stage7_class_define.h +1 -0
index 47008897a795..f29a82e7a4c4 100644
@@ -24,6 +24,7 @@
 #undef __print_array
 #undef __print_dynamic_array
 #undef __print_hex_dump
+#undef __print_untrusted_str
 #undef __get_buf
 
 #undef __event_in_hardirq
kernel/trace/trace_output.c +44 -0

56 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#10 lore raw

Re: [PATCH v3 07/20] tracing: Add __print_untrusted_str()

Hi Steven,

I addressed your previous review for this helper, is this patch ok with you now?

I also addressed your other review about the tracepoints. They are well tested, including with a dedicated tool I wrote (not public yet). Could you get a quick look for me to push this series to -next before the merge window?

Thanks

Quoted 144 lines · Mickaël Salaün

Landlock tracepoints expose filesystem paths and process names that may contain spaces, equal signs, or other characters that break ftrace field parsing.

Add a __print_untrusted_str() TP_printk helper that escapes separators (space, equal sign), quotes, backslashes, and non-printable bytes via string_escape_mem(), so an untrusted string cannot inject field separators or control characters into the ftrace output and can be unambiguously recovered.

This guarantee applies to the in-kernel ftrace text output (trace, trace_pipe). Userspace libtraceevent (perf, trace-cmd) does not yet parse this helper, so a companion libtraceevent change is needed for those consumers to pretty-print the field.

Cc Günther Noack <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Mathieu Desnoyers <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Add a Return: kdoc for trace_print_untrusted_str_seq() and rename its declaration parameter to src.

Changes since v1:
https://patch.msgid.link/[email protected]
- Remove WARN_ON() (pointed out by Steven Rostedt).

---
 include/linux/trace_events.h               |  2 +
 include/trace/stages/stage3_trace_output.h |  4 ++
 include/trace/stages/stage7_class_define.h |  1 +
 kernel/trace/trace_output.c                | 44 ++++++++++++++++++++++
 4 files changed, 51 insertions(+)
include/linux/trace_events.h +2 -0
index 308c76b57d13..4ece9b8d9d6b 100644
@@ -60,6 +60,8 @@ trace_print_hex_dump_seq(struct trace_seq *p, const char *prefix_str,
 			 int prefix_type, int rowsize, int groupsize,
 			 const void *buf, size_t len, bool ascii);
 
+const char *trace_print_untrusted_str_seq(struct trace_seq *s, const char *src);
+
 int trace_raw_output_prep(struct trace_iterator *iter,
 			  struct trace_event *event);
 extern __printf(2, 3)
include/trace/stages/stage3_trace_output.h +4 -0
index 181b81335781..0235dbd11b52 100644
@@ -133,6 +133,10 @@
 	trace_print_hex_dump_seq(p, prefix_str, prefix_type,		\
 				 rowsize, groupsize, buf, len, ascii)
 
+#undef __print_untrusted_str
+#define __print_untrusted_str(str)					\
+		trace_print_untrusted_str_seq(p, __get_str(str))
+
 #undef __print_ns_to_secs
 #define __print_ns_to_secs(value)			\
 	({						\
include/trace/stages/stage7_class_define.h +1 -0
index 47008897a795..f29a82e7a4c4 100644
@@ -24,6 +24,7 @@
 #undef __print_array
 #undef __print_dynamic_array
 #undef __print_hex_dump
+#undef __print_untrusted_str
 #undef __get_buf
 
 #undef __event_in_hardirq
kernel/trace/trace_output.c +44 -0
index a5ad76175d10..f0a9b29b3e36 100644
@@ -16,6 +16,7 @@
 #include <linux/btf.h>
 #include <linux/bpf.h>
 #include <linux/hashtable.h>
+#include <linux/string_helpers.h>
 
 #include "trace_output.h"
 #include "trace_btf.h"
@@ -325,6 +326,49 @@ trace_print_hex_dump_seq(struct trace_seq *p, const char *prefix_str,
 }
 EXPORT_SYMBOL(trace_print_hex_dump_seq);
 
+/**
+ * trace_print_untrusted_str_seq - print a string after escaping characters
+ * @s: trace seq struct to write to
+ * @src: The string to print
+ *
+ * Prints a string to a trace seq after escaping all special characters,
+ * including common separators (space, equal sign), quotes, and backslashes.
+ * This transforms a string from an untrusted source (e.g. user space) to make
+ * it:
+ * - safe to parse,
+ * - easy to read (for simple strings),
+ * - easy to get back the original.
+ *
+ * Return: A pointer to the escaped string within the trace seq buffer, or
+ * %NULL if @src is %NULL or the buffer is exhausted.
+ */
+const char *trace_print_untrusted_str_seq(struct trace_seq *s,
+					   const char *src)
+{
+	int escaped_size;
+	char *buf;
+	size_t buf_size = seq_buf_get_buf(&s->seq, &buf);
+	const char *ret = trace_seq_buffer_ptr(s);
+
+	/* Buffer exhaustion is normal when the trace buffer is full. */
+	if (!src || buf_size == 0)
+		return NULL;
+
+	escaped_size = string_escape_mem(src, strlen(src), buf, buf_size,
+		ESCAPE_SPACE | ESCAPE_SPECIAL | ESCAPE_NAP | ESCAPE_APPEND |
+		ESCAPE_OCTAL, " ='\"\\");
+	if (unlikely(escaped_size >= buf_size)) {
+		/* We need some room for the final '\0'. */
+		seq_buf_set_overflow(&s->seq);
+		s->full = 1;
+		return NULL;
+	}
+	seq_buf_commit(&s->seq, escaped_size);
+	trace_seq_putc(s, 0);
+	return ret;
+}
+EXPORT_SYMBOL(trace_print_untrusted_str_seq);
+
 int trace_raw_output_prep(struct trace_iterator *iter,
 			  struct trace_event *trace_event)
 {
Signature · 1 line
2.54.0
author maintainer
#11 lore raw

PATCH v3 8/20 landlock: Add create_ruleset and free_ruleset tracepoints

In reply to Mickaël Salaün

Add the first Landlock tracepoints, for ruleset lifecycle:
landlock_create_ruleset fires from the landlock_create_ruleset() syscall handler, and landlock_free_ruleset fires in free_ruleset() before the ruleset is freed.

These tracepoints, and the ones added by the following commits, share a common design. Rather than one polymorphic event distinguished by a status field (as audit uses a shared record type with a "status=" field), each lifecycle transition and denial type gets its own event with a type-safe TP_PROTO, giving precise ftrace filtering by event name and type-safe eBPF access. TP_PROTO passes the object pointer and the fields are read from it in TP_fast_assign, so an eBPF program reads the full object state (rules, access masks, hierarchy) via BTF from a single pointer rather than from the flattened TP_STRUCT__entry fields. The whole cost is paid only when a tracer is attached; the static branch is not taken otherwise. Trace fields carry the bare access-right and scope names (read_file), reusing the audit name tables; audit prepends the category (fs.read_file), which the trace event name already conveys. The trace header's DOC comment documents the consistency and locking guarantees these events share.

create_ruleset needs no lock because the ruleset is not yet shared (its file descriptor is not yet installed). The deallocation events use the "free_" prefix, not "drop_", because they fire when the object is actually freed.

Add trace.c, built for CONFIG_TRACEPOINTS, which defines CREATE_TRACE_POINTS, and extend CONFIG_SECURITY_LANDLOCK_LOG to also be selected by CONFIG_TRACEPOINTS so the common log framework is available to a tracepoints-only build.

Add an id field to struct landlock_ruleset, gated on CONFIG_TRACEPOINTS and assigned from landlock_get_id_range() at creation. Only the tracepoints consume it (audit identifies domains, not rulesets), so it does not exist in an audit-only build. The Landlock ID is a stable u64 that names the ruleset across the trace stream and uses the same scheme as audit, so a ruleset can be correlated between trace and audit records.

Cc Günther Noack <[email protected]>
Cc Justin Suess <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Mathieu Desnoyers <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Reformatted TP_STRUCT__entry and TP_fast_assign to kernel tracing convention (requested by Steven Rostedt).
- Render the handled access masks as symbolic names with __print_flags(), shared with the audit blocker names.
- Move the id.h declaration guard widening (landlock_init_id, landlock_get_id_range) to the earlier commit that builds id.o under CONFIG_SECURITY_LANDLOCK_LOG, so intermediate patches build without CONFIG_AUDIT.
- Refine the trace-event consistency-guarantee DOC comment (observable from user space, balanced creation and deallocation events) and document why create_ruleset emits before the file descriptor is installed.
- Define CREATE_TRACE_POINTS in a dedicated trace.c built for CONFIG_TRACEPOINTS, and extend CONFIG_SECURITY_LANDLOCK_LOG to be selected by CONFIG_TRACEPOINTS here (the first tracepoint consumer), rather than placing CREATE_TRACE_POINTS in the audit and log translation unit.
- Gate the struct landlock_ruleset id field on CONFIG_TRACEPOINTS (only tracing uses it) instead of CONFIG_SECURITY_LANDLOCK_LOG.

Changes since v1:
- New patch (split from the v1 add_rule_fs tracepoint patch).

---
 MAINTAINERS                     |   1 +
 include/linux/landlock.h        |   1 +
 include/trace/events/landlock.h | 139 ++++++++++++++++++++++++++++++++
 security/landlock/Kconfig       |   2 +-
 security/landlock/Makefile      |   2 +
 security/landlock/ruleset.c     |   8 ++
 security/landlock/ruleset.h     |   9 +++
 security/landlock/syscalls.c    |  11 +++
 security/landlock/trace.c       |  17 ++++
 9 files changed, 189 insertions(+), 1 deletion(-)
 create mode 100644 include/trace/events/landlock.h
 create mode 100644 security/landlock/trace.c
MAINTAINERS +1 -0
index 91de7e3c2836..ca41aec9993c 100644
@@ -14599,6 +14599,7 @@ F:	Documentation/security/landlock.rst
 F:	Documentation/userspace-api/landlock.rst
 F:	fs/ioctl.c
 F:	include/linux/landlock.h
+F:	include/trace/events/landlock.h
 F:	include/uapi/linux/landlock.h
 F:	samples/landlock/
 F:	security/landlock/
include/linux/landlock.h +1 -0
index cabe6c784833..004cbd0b9298 100644
@@ -9,6 +9,7 @@
 #ifndef _LINUX_LANDLOCK_H
 #define _LINUX_LANDLOCK_H
 
+#include <linux/types.h>
 #include <uapi/linux/landlock.h>
 
 /*
include/trace/events/landlock.h new file +139 -0

139 lines not on this page · raw message

security/landlock/Kconfig +1 -1
index b4e7f0e9ba9b..7aeac29160e8 100644
@@ -24,7 +24,7 @@ config SECURITY_LANDLOCK
 config SECURITY_LANDLOCK_LOG
 	bool
 	depends on SECURITY_LANDLOCK
-	default y if AUDIT
+	default y if AUDIT || TRACEPOINTS
 
 config SECURITY_LANDLOCK_KUNIT_TEST
 	bool "KUnit tests for Landlock" if !KUNIT_ALL_TESTS
security/landlock/Makefile +2 -0
index 2462e6c5921e..2711f4876939 100644
@@ -18,3 +18,5 @@ landlock-$(CONFIG_SECURITY_LANDLOCK_LOG) += \
 	log.o
 
 landlock-$(CONFIG_AUDIT) += audit.o
+
+landlock-$(CONFIG_TRACEPOINTS) += trace.o
security/landlock/ruleset.c +8 -0
index 13edb77f07a0..3bfee53177d8 100644
@@ -23,10 +23,13 @@
 #include <uapi/linux/landlock.h>
 
 #include "access.h"
+#include "id.h"
 #include "limits.h"
 #include "object.h"
 #include "ruleset.h"
 
+#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,
@@ -50,6 +53,10 @@ landlock_create_ruleset(const access_mask_t fs_access_mask,
 	new_ruleset->rules.root_net_port = RB_ROOT;
 #endif /* IS_ENABLED(CONFIG_INET) */
 
+#ifdef CONFIG_TRACEPOINTS
+	new_ruleset->id = landlock_get_id_range(1);
+#endif /* CONFIG_TRACEPOINTS */
+
 	/* Should already be checked in landlock_create_ruleset(). */
 	if (fs_access_mask) {
 		const access_mask_t mask = fs_access_mask &
@@ -325,6 +332,7 @@ void landlock_free_rules(struct landlock_rules *const rules)
 static void free_ruleset(struct landlock_ruleset *const ruleset)
 {
 	might_sleep();
+	trace_landlock_free_ruleset(ruleset);
 	landlock_free_rules(&ruleset->rules);
 	kfree(ruleset);
 }
security/landlock/ruleset.h +9 -0
index da6a12a8e066..ca1fd5f4c417 100644
@@ -4,6 +4,7 @@
  *
  * Copyright © 2016-2020 Mickaël Salaün <[email protected]>
  * Copyright © 2018-2020 ANSSI
+ * Copyright © 2026 Cloudflare, Inc.
  */
 
 #ifndef _SECURITY_LANDLOCK_RULESET_H
@@ -164,6 +165,14 @@ struct landlock_ruleset {
 	 * @usage: Number of file descriptors referencing this ruleset.
 	 */
 	refcount_t usage;
+
+#ifdef CONFIG_TRACEPOINTS
+	/**
+	 * @id: Unique identifier for this ruleset, used for tracing.
+	 */
+	u64 id;
+#endif /* CONFIG_TRACEPOINTS */
+
 	/**
 	 * @quiet_masks: Stores the quiet flags for an unmerged ruleset.  For a
 	 * merged domain, this is stored in each layer's struct
security/landlock/syscalls.c +11 -0
index 0ad20a6f9564..dbc4facf00b6 100644
@@ -38,6 +38,8 @@
 #include "setup.h"
 #include "tsync.h"
 
+#include <trace/events/landlock.h>
+
 static bool is_initialized(void)
 {
 	if (likely(landlock_initialized))
@@ -281,6 +283,15 @@ SYSCALL_DEFINE3(landlock_create_ruleset,
 	ruleset->quiet_masks.net = ruleset_attr.quiet_access_net;
 	ruleset->quiet_masks.scope = ruleset_attr.quiet_scoped;
 
+	/*
+	 * Emits before anon_inode_getfd() installs the file descriptor, while
+	 * the ruleset is still private to this thread: no lock is needed, and
+	 * the event cannot race a concurrent close() freeing the ruleset under
+	 * the tracepoint's BTF read.  This is the last point at which the
+	 * ruleset is guaranteed alive and unshared.
+	 */
+	trace_landlock_create_ruleset(ruleset);
+
 	/* Creates anonymous FD referring to the ruleset. */
 	ruleset_fd = anon_inode_getfd("[landlock-ruleset]", &ruleset_fops,
 				      ruleset, O_RDWR | O_CLOEXEC);
security/landlock/trace.c new file +17 -0
new file mode 100644
index 000000000000..aeb6eeebe42a
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Landlock - Tracepoint helpers
+ *
+ * Copyright © 2025 Microsoft Corporation
+ * Copyright © 2026 Cloudflare, Inc.
+ */
+
+#include "ruleset.h"
+
+/*
+ * Generates the tracepoint definitions in this translation unit.  The trace
+ * event header dereferences the traced objects in TP_fast_assign, so the full
+ * struct definitions (e.g. ruleset.h) must be included before it.
+ */
+#define CREATE_TRACE_POINTS
+#include <trace/events/landlock.h>
Signature · 1 line
2.54.0
author maintainer
#12 lore raw

PATCH v3 9/20 landlock: Add landlock_add_rule_fs and landlock_add_rule_net tracepoints

In reply to Mickaël Salaün

Add tracepoints for Landlock rule addition, landlock_add_rule_fs for filesystem rules and landlock_add_rule_net for network rules, so trace consumers can correlate filesystem objects and network ports with their rulesets. Both are emitted under the ruleset lock (asserted in TP_fast_assign) so an eBPF program reads the ruleset, including the rule just inserted, in a consistent snapshot.

Add a version field to struct landlock_ruleset, gated on CONFIG_TRACEPOINTS like the id field and incremented under the ruleset lock on each successful landlock_add_rule(2), including when it only extends an existing rule's access rights. It fills the existing 4-byte hole after usage, so the struct does not grow. Pairing the ruleset ID with the version lets a later restrict_self event record the exact ruleset revision merged into a domain.

Resolve the filesystem rule's absolute path with d_absolute_path() rather than the d_path() audit uses: d_absolute_path() produces namespace-independent paths that do not depend on the tracer's chroot state, making trace output deterministic regardless of mount namespace configuration. Distinguish the error cases as "<too_long>" (-ENAMETOOLONG) and "<unreachable>" (anonymous files or detached mounts).

Cc Christian Brauner <[email protected]>
Cc Günther Noack <[email protected]>
Cc Justin Suess <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Mathieu Desnoyers <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Order the add_rule_net tracepoint arguments access_rights before port, matching add_rule_fs.
- Reformatted TP_STRUCT__entry and TP_fast_assign to kernel tracing convention (requested by Steven Rostedt).
- Render access_rights as symbolic names with __print_flags(), shared with the audit blocker names, instead of raw hex.
- Drop the tautological version static assertion (the counter tracks add-rule operations, not rule count) and clarify that @version is incremented on access-right extensions too.
- Gate the version field and its writer on CONFIG_TRACEPOINTS (only tracing uses it) instead of CONFIG_SECURITY_LANDLOCK_LOG, matching the id field.
- Adapt rule insertion to the base's quiet flag (landlock_insert_rule() flags argument).

Changes since v1:
https://patch.msgid.link/[email protected]
- Added landlock_add_rule_net tracepoint for network rules.
- Dropped key=inode:0x%lx from add_rule_fs printk, using dev/ino instead.
- Used ruleset Landlock ID instead of kernel pointer in printk.
- Differentiated d_absolute_path() error cases (suggested by Tingmao Wang).
- Moved DEFINE_FREE(__putname) to include/linux/fs.h (noticed by Tingmao Wang).
- Added version field to struct landlock_ruleset.
- Added version to add_rule trace events (format:
ruleset=<id>.<version>).
- Added d_absolute_path() vs d_path() rationale to commit message.

---
 include/linux/fs.h              |   1 +
 include/trace/events/landlock.h | 115 +++++++++++++++++++++++++++++++-
 security/landlock/fs.c          |  19 ++++++
 security/landlock/fs.h          |  30 +++++++++
 security/landlock/net.c         |  11 +++
 security/landlock/ruleset.c     |  13 +++-
 security/landlock/ruleset.h     |   7 ++
 7 files changed, 191 insertions(+), 5 deletions(-)
include/linux/fs.h +1 -0
index 50ce731a2b78..925517c672f3 100644
@@ -2587,6 +2587,7 @@ extern void __init vfs_caches_init(void);
 
 #define __getname()		kmalloc(PATH_MAX, GFP_KERNEL)
 #define __putname(name)		kfree(name)
+DEFINE_FREE(__putname, char *, if (_T) __putname(_T))
 
 void emergency_thaw_all(void);
 extern int sync_filesystem(struct super_block *);
include/trace/events/landlock.h +112 -3

156 lines not on this page · raw message

security/landlock/fs.c +19 -0
index d39da6e9fa8c..48744a21d0a3 100644
@@ -52,6 +52,8 @@
 #include "ruleset.h"
 #include "setup.h"
 
+#include <trace/events/landlock.h>
+
 /* Underlying object management */
 
 static void release_inode(struct landlock_object *const object)
@@ -346,7 +348,24 @@ int landlock_append_fs_rule(struct landlock_ruleset *const ruleset,
 		return PTR_ERR(id.key.object);
 	mutex_lock(&ruleset->lock);
 	err = landlock_insert_rule(ruleset, id, access_rights, flags);
+
+	/*
+	 * Emit after the rule insertion succeeds, so every event corresponds to
+	 * a rule that is actually in the ruleset.  The ruleset lock is still
+	 * held for BTF consistency (enforced by lockdep_assert_held in
+	 * TP_fast_assign).
+	 */
+	if (!err && trace_landlock_add_rule_fs_enabled()) {
+		char *buffer __free(__putname) = __getname();
+		const char *pathname =
+			buffer ? resolve_path_for_trace(path, buffer) :
+				 "<no_mem>";
+
+		trace_landlock_add_rule_fs(ruleset, access_rights, path,
+					   pathname);
+	}
 	mutex_unlock(&ruleset->lock);
+
 	/*
 	 * No need to check for an error because landlock_insert_rule()
 	 * increments the refcount for the new object if needed.
security/landlock/fs.h +30 -0
index c16f24e30bd5..4e3d7cbd7e1e 100644
@@ -11,6 +11,7 @@
 #define _SECURITY_LANDLOCK_FS_H
 
 #include <linux/build_bug.h>
+#include <linux/cleanup.h>
 #include <linux/fs.h>
 #include <linux/init.h>
 #include <linux/rcupdate.h>
@@ -153,4 +154,33 @@ int landlock_append_fs_rule(struct landlock_ruleset *const ruleset,
 			    const struct path *const path,
 			    access_mask_t access_hierarchy, const u32 flags);
 
+/**
+ * resolve_path_for_trace - Resolve a path for tracepoint display
+ *
+ * @path: The path to resolve.
+ * @buf: A buffer of at least PATH_MAX bytes for the resolved path.
+ *
+ * Uses d_absolute_path() to produce a namespace-independent absolute path,
+ * unlike d_path() which resolves relative to the process's chroot.  This
+ * ensures trace output is deterministic regardless of the tracer's mount
+ * namespace.
+ *
+ * Return: A pointer into @buf with the resolved path, or an error string
+ * ("<too_long>", "<unreachable>").
+ */
+static inline const char *resolve_path_for_trace(const struct path *path,
+						 char *buf)
+{
+	const char *p;
+
+	p = d_absolute_path(path, buf, PATH_MAX);
+	if (!IS_ERR_OR_NULL(p))
+		return p;
+
+	if (PTR_ERR(p) == -ENAMETOOLONG)
+		return "<too_long>";
+
+	return "<unreachable>";
+}
+
 #endif /* _SECURITY_LANDLOCK_FS_H */
security/landlock/net.c +11 -0
index e27b3ba15664..ead97fcfdcff 100644
@@ -20,6 +20,8 @@
 #include "net.h"
 #include "ruleset.h"
 
+#include <trace/events/landlock.h>
+
 int landlock_append_net_rule(struct landlock_ruleset *const ruleset,
 			     const u16 port, access_mask_t access_rights,
 			     const u32 flags)
@@ -37,6 +39,15 @@ int landlock_append_net_rule(struct landlock_ruleset *const ruleset,
 
 	mutex_lock(&ruleset->lock);
 	err = landlock_insert_rule(ruleset, id, access_rights, flags);
+
+	/*
+	 * Emit after the rule insertion succeeds, so every event corresponds to
+	 * a rule that is actually in the ruleset.  The ruleset lock is still
+	 * held for BTF consistency (enforced by lockdep_assert_held in
+	 * TP_fast_assign).
+	 */
+	if (!err)
+		trace_landlock_add_rule_net(ruleset, access_rights, port);
 	mutex_unlock(&ruleset->lock);
 
 	return err;
security/landlock/ruleset.c +11 -2
index 3bfee53177d8..b78714047ddf 100644
@@ -4,6 +4,7 @@
  *
  * Copyright © 2016-2020 Mickaël Salaün <[email protected]>
  * Copyright © 2018-2020 ANSSI
+ * Copyright © 2026 Cloudflare, Inc.
  */
 
 #include <linux/bits.h>
@@ -306,11 +307,19 @@ int landlock_insert_rule(struct landlock_ruleset *const ruleset,
 			.quiet = !!(flags & LANDLOCK_ADD_RULE_QUIET),
 		},
 	} };
+	int err;
 
 	build_check_layer();
 	lockdep_assert_held(&ruleset->lock);
-	return landlock_rule_insert(&ruleset->rules, id, &layers,
-				    ARRAY_SIZE(layers));
+	err = landlock_rule_insert(&ruleset->rules, id, &layers,
+				   ARRAY_SIZE(layers));
+
+#ifdef CONFIG_TRACEPOINTS
+	if (!err)
+		ruleset->version++;
+#endif /* CONFIG_TRACEPOINTS */
+
+	return err;
 }
 
 void landlock_free_rules(struct landlock_rules *const rules)
security/landlock/ruleset.h +7 -0
index ca1fd5f4c417..799d9b3cc205 100644
@@ -167,6 +167,13 @@ struct landlock_ruleset {
 	refcount_t usage;
 
 #ifdef CONFIG_TRACEPOINTS
+	/**
+	 * @version: Counter incremented on each successful
+	 * landlock_add_rule(2), including when it only extends an existing
+	 * rule's access rights.  Used by tracepoints to correlate a domain with
+	 * the exact ruleset state it was created from.  Protected by @lock.
+	 */
+	u32 version;
 	/**
 	 * @id: Unique identifier for this ruleset, used for tracing.
 	 */
Signature · 1 line
2.54.0
author maintainer
#13 lore raw

PATCH v3 10/20 landlock: Add create_domain and free_domain tracepoints

In reply to Mickaël Salaün

Add a landlock_create_domain tracepoint emitted from landlock_restrict_self() after the new domain is created, so a consumer can correlate the source ruleset with the resulting domain. The flags-only path (ruleset_fd == -1) creates no domain and emits no event.

Move the ruleset lock acquisition from landlock_merge_ruleset() to the caller so the lock is held across both the merge and the tracepoint emission, giving an eBPF program a consistent ruleset snapshot. Release it before the thread-sync: holding ruleset->lock across landlock_restrict_sibling_threads() would deadlock a sibling blocked on the same lock. The event therefore fires before the (rare) thread-sync failure path; when that path aborts the just-created domain, the matching free_domain event fires so the create/free pair stays balanced.

Add a landlock_free_domain tracepoint that fires when a domain's hierarchy node is freed. The hierarchy node is the lifecycle boundary because it represents the domain's identity and outlives the domain's access masks, which may still be active in descendant domains.

A domain freed without ever being committed to a credential was never visible to user space, so free_domain is suppressed for it. This is tracked by a new landlock_log_status value, LANDLOCK_LOG_UNCOMMITTED, which is also the zero value so a hierarchy whose initialization failed defaults to not observable. A hierarchy is born UNCOMMITTED and is promoted to LANDLOCK_LOG_PENDING (or LANDLOCK_LOG_DISABLED when logging is off) right after its create_domain event fires; a thread-sync failure does not reset it, so an aborted domain that already emitted create_domain still emits the matching free_domain. Promoting right after the event, rather than at commit_creds() time, avoids a race: on a successful thread-sync the sibling threads commit the new domain in lockstep before landlock_restrict_self() returns, so the shared domain may already have moved to LANDLOCK_LOG_RECORDED through a plain store, and a late promotion would race that store and could unbalance the domain allocation and deallocation audit records.

Cc Günther Noack <[email protected]>
Cc Justin Suess <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Mathieu Desnoyers <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Renamed the landlock_restrict_self tracepoint to landlock_create_domain and reordered its arguments to (domain, ruleset) for domain-first consistency with the other domain-lifecycle events.
- Reformat the TRACE_EVENT body (TP_PROTO, TP_STRUCT__entry, TP_fast_assign, TP_printk) to the kernel tracing convention with one field per line and tab-aligned columns (requested by Steven Rostedt).
- Emit the create_domain creation event under the ruleset lock, just after the merge and before the thread-sync wait, so an observer reads the exact ruleset frozen into the domain and the lock is not held across thread-sync (where a sibling blocked in landlock_add_rule() on the same lock would stall it).
- Gate free_domain on a new LANDLOCK_LOG_UNCOMMITTED status so a domain freed before its creation event fired emits no free_domain; create_domain marks the domain committed right after emitting the event, so a later thread-sync failure still emits the matching free_domain and the create/free pair stays balanced.
- Emit free_domain from landlock_trace_free_domain() in a dedicated tracing translation unit, and move the decoupling of the log state and landlock_log_free_domain() from CONFIG_AUDIT to the commit that separates the common log framework from audit.
- Clarify in the create_domain emission comment that the event fires before the infallible commit_creds().
- Clarify the free_domain kdoc: the event fires when the hierarchy node's refcount reaches zero, after all child domains release their parent reference (the earlier "all descendants freed" phrasing could be misread).

Changes since v1:
- New patch.

---
 include/trace/events/landlock.h | 82 +++++++++++++++++++++++++++++++++
 security/landlock/domain.c      | 28 ++++++-----
 security/landlock/domain.h      | 16 ++++++-
 security/landlock/log.c         |  6 ++-
 security/landlock/syscalls.c    | 45 +++++++++++++++++-
 security/landlock/trace.c       | 31 ++++++++++++-
 security/landlock/trace.h       | 28 +++++++++++
 7 files changed, 219 insertions(+), 17 deletions(-)
 create mode 100644 security/landlock/trace.h
include/trace/events/landlock.h +82 -0
index 69a75cf47f65..cb0e21a2fa1f 100644
@@ -13,6 +13,8 @@
 #include <linux/landlock.h>
 #include <linux/tracepoint.h>
 
+struct landlock_domain;
+struct landlock_hierarchy;
 struct landlock_ruleset;
 struct path;
 
@@ -240,6 +242,86 @@ TRACE_EVENT(landlock_add_rule_net,
 		__entry->port)
 );
 
+/**
+ * landlock_create_domain - New domain created
+ *
+ * @domain: Newly created domain (never NULL, immutable after creation).
+ *          @domain->hierarchy->id is its unique ID, shared with the
+ *          landlock_enforce_domain and landlock_free_domain events;
+ *          @domain->hierarchy->details holds the requesting process.
+ * @ruleset: Source ruleset frozen into the domain (never NULL).  The
+ *           ruleset lock is held across the emission, so a BPF program
+ *           reading it via BTF sees the exact merged ruleset;
+ *           @ruleset->id / @ruleset->version identify it.
+ *
+ * Emitted by sys_landlock_restrict_self() once, in the requesting
+ * thread's context, right after the merge and before thread-sync.  The
+ * flags-only path (ruleset_fd == -1) creates no domain and does not
+ * emit this event.  Paired with the per-thread landlock_enforce_domain
+ * (join on @domain->hierarchy->id) and balanced by a matching
+ * landlock_free_domain event.
+ */
+TRACE_EVENT(landlock_create_domain,
+
+	TP_PROTO(const struct landlock_domain *domain,
+		 const struct landlock_ruleset *ruleset),
+
+	TP_ARGS(domain, ruleset),
+
+	TP_STRUCT__entry(
+		__field(	__u64,		domain_id	)
+		__field(	__u64,		parent_id	)
+		__field(	__u64,		ruleset_id	)
+		__field(	__u32,		ruleset_version	)
+	),
+
+	TP_fast_assign(
+		lockdep_assert_held(&ruleset->lock);
+		__entry->domain_id	= domain->hierarchy->id;
+		__entry->parent_id	= domain->hierarchy->parent ?
+					  domain->hierarchy->parent->id : 0;
+		__entry->ruleset_id	= ruleset->id;
+		__entry->ruleset_version = ruleset->version;
+	),
+
+	TP_printk("domain=%llx parent=%llx ruleset=%llx.%u",
+		__entry->domain_id, __entry->parent_id,
+		__entry->ruleset_id, __entry->ruleset_version)
+);
+
+/**
+ * landlock_free_domain - Domain freed
+ *
+ * @hierarchy: Hierarchy node being freed (never NULL).
+ *
+ * Emitted when the hierarchy node's last reference is dropped: its
+ * refcount reaches zero after all child domains have released their
+ * parent reference.  A committed domain is
+ * freed from a kworker via landlock_put_domain_deferred() (the credential
+ * free path runs in RCU context, where sleeping is forbidden), so the
+ * current task is not the sandboxed task that triggered the free.  Balanced
+ * by a matching landlock_create_domain event.
+ */
+TRACE_EVENT(landlock_free_domain,
+
+	TP_PROTO(const struct landlock_hierarchy *hierarchy),
+
+	TP_ARGS(hierarchy),
+
+	TP_STRUCT__entry(
+		__field(	__u64,		domain_id	)
+		__field(	__u64,		denials		)
+	),
+
+	TP_fast_assign(
+		__entry->domain_id	= hierarchy->id;
+		__entry->denials	= atomic64_read(&hierarchy->num_denials);
+	),
+
+	TP_printk("domain=%llx denials=%llu",
+		__entry->domain_id, __entry->denials)
+);
+
 #undef _LANDLOCK_NAME_ENTRY
 
 #endif /* _TRACE_LANDLOCK_H */
security/landlock/domain.c +17 -11
index 6444cf27bda2..082c4da68536 100644
@@ -309,31 +309,28 @@ static int merge_ruleset(struct landlock_domain *const dst,
 	if (WARN_ON_ONCE(!dst || !dst->hierarchy))
 		return -EINVAL;
 
-	mutex_lock(&src->lock);
+	lockdep_assert_held(&src->lock);
 
 	/* Stacks the new layer. */
-	if (WARN_ON_ONCE(dst->num_layers < 1)) {
-		err = -EINVAL;
-		goto out_unlock;
-	}
+	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);
 
 	/* Merges the @src inode tree. */
 	err = merge_tree(dst, src, LANDLOCK_KEY_INODE);
 	if (err)
-		goto out_unlock;
+		return err;
 
 #if IS_ENABLED(CONFIG_INET)
 	/* Merges the @src network port tree. */
 	err = merge_tree(dst, src, LANDLOCK_KEY_NET_PORT);
 	if (err)
-		goto out_unlock;
+		return err;
 #endif /* IS_ENABLED(CONFIG_INET) */
 
-out_unlock:
-	mutex_unlock(&src->lock);
-	return err;
+	return 0;
 }
 
 static int inherit_tree(struct landlock_domain *const parent,
@@ -415,6 +412,8 @@ static int inherit_ruleset(struct landlock_domain *const parent,
  * The current task is requesting to be restricted.  The subjective credentials
  * must not be in an overridden state. cf. landlock_init_hierarchy_log().
  *
+ * The caller must hold @ruleset->lock.
+ *
  * Return: A new domain merging @parent and @ruleset on success, or ERR_PTR() on
  * failure.  If @parent is NULL, the new domain duplicates @ruleset.
  */
@@ -427,6 +426,7 @@ landlock_merge_ruleset(struct landlock_domain *const parent,
 	int err;
 
 	might_sleep();
+	lockdep_assert_held(&ruleset->lock);
 	if (WARN_ON_ONCE(!ruleset))
 		return ERR_PTR(-EINVAL);
 
@@ -575,7 +575,13 @@ int landlock_init_hierarchy_log(struct landlock_hierarchy *const hierarchy)
 
 	hierarchy->details = details;
 	hierarchy->id = landlock_get_id_range(1);
-	hierarchy->log_status = LANDLOCK_LOG_PENDING;
+	/*
+	 * The hierarchy is born unobservable: landlock_restrict_self() moves it
+	 * out of LANDLOCK_LOG_UNCOMMITTED once it has emitted the creation
+	 * event, so the matching free_domain event fires for it and not for a
+	 * hierarchy whose creation was never observed.
+	 */
+	hierarchy->log_status = LANDLOCK_LOG_UNCOMMITTED;
 	hierarchy->log_same_exec = true;
 	hierarchy->log_new_exec = false;
 	atomic64_set(&hierarchy->num_denials, 0);
security/landlock/domain.h +15 -1
index 1237e3e25240..8351e22016fe 100644
@@ -25,7 +25,21 @@
 #include "ruleset.h"
 
 enum landlock_log_status {
-	LANDLOCK_LOG_PENDING = 0,
+	/*
+	 * Hierarchy whose creation event has not been emitted, so it is not yet
+	 * observable from user space.  A hierarchy is born in this state (the
+	 * zero value, so a partially initialized hierarchy defaults to "not
+	 * observable") and leaves it when landlock_restrict_self() emits its
+	 * creation event, right after the merge and before the thread-sync
+	 * wait.  No trace free_domain event (and no audit deallocation record)
+	 * fires while a hierarchy is in this state, so a hierarchy that never
+	 * became observable (e.g. its initialization failed) is freed silently.
+	 * A domain aborted by a thread-sync failure already emitted its
+	 * creation event, so it is no longer UNCOMMITTED and does fire
+	 * free_domain.
+	 */
+	LANDLOCK_LOG_UNCOMMITTED = 0,
+	LANDLOCK_LOG_PENDING,
 	LANDLOCK_LOG_RECORDED,
 	LANDLOCK_LOG_DISABLED,
 };
security/landlock/log.c +4 -2
index f42e6dc4de5c..13033808bdbd 100644
@@ -17,6 +17,7 @@
 #include "limits.h"
 #include "log.h"
 #include "ruleset.h"
+#include "trace.h"
 
 static struct landlock_hierarchy *
 get_hierarchy(const struct landlock_domain *const domain, const size_t layer)
@@ -550,14 +551,15 @@ void landlock_log_denial(const struct landlock_cred_security *const subject,
  *
  * @hierarchy: The domain's hierarchy being deallocated.
  *
- * Called in a work queue scheduled by landlock_put_domain_deferred() called by
- * hook_cred_free().
+ * Called from landlock_put_domain_deferred() (via a work queue scheduled by
+ * hook_cred_free()) or directly from landlock_put_domain().
  */
 void landlock_log_free_domain(const struct landlock_hierarchy *const hierarchy)
 {
 	if (WARN_ON_ONCE(!hierarchy))
 		return;
 
+	landlock_trace_free_domain(hierarchy);
 	landlock_audit_free_domain(hierarchy);
 }
 
security/landlock/syscalls.c +43 -2

73 lines not on this page · raw message

security/landlock/trace.c +30 -1
index aeb6eeebe42a..5e6df313c7d2 100644
@@ -6,12 +6,41 @@
  * Copyright © 2026 Cloudflare, Inc.
  */
 
+#include "trace.h"
+#include "domain.h"
 #include "ruleset.h"
 
 /*
  * Generates the tracepoint definitions in this translation unit.  The trace
  * event header dereferences the traced objects in TP_fast_assign, so the full
- * struct definitions (e.g. ruleset.h) must be included before it.
+ * struct definitions (e.g. ruleset.h, domain.h) must be included before it.
  */
 #define CREATE_TRACE_POINTS
 #include <trace/events/landlock.h>
+
+/**
+ * landlock_trace_free_domain - Emit a tracepoint on domain deallocation
+ *
+ * @hierarchy: The domain's hierarchy being deallocated.
+ *
+ * Fires only for a hierarchy whose creation event was emitted, i.e. one that
+ * left LANDLOCK_LOG_UNCOMMITTED in landlock_restrict_self().  This keeps the
+ * create/free pair balanced: a hierarchy that never became observable is freed
+ * silently, while a domain that landlock_restrict_self() created and a
+ * thread-sync failure then aborted still fires free_domain, because its
+ * creation event already fired.
+ *
+ * Called from landlock_log_free_domain().
+ */
+void landlock_trace_free_domain(const struct landlock_hierarchy *const hierarchy)
+{
+	/*
+	 * The log_status read is a correctness guard (keep the create/free pair
+	 * balanced), not a cost guard, so this cold path needs no
+	 * trace_..._enabled() check: the tracepoint is a static-branch no-op
+	 * when disabled.  The denial path guards trace_..._enabled() instead
+	 * because it does expensive __getname()/path work before emitting.
+	 */
+	if (READ_ONCE(hierarchy->log_status) != LANDLOCK_LOG_UNCOMMITTED)
+		trace_landlock_free_domain(hierarchy);
+}
security/landlock/trace.h new file +28 -0
new file mode 100644
index 000000000000..59c8ea348625
@@ -0,0 +1,28 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Landlock - Tracepoint helpers
+ *
+ * Copyright © 2025 Microsoft Corporation
+ * Copyright © 2026 Cloudflare, Inc.
+ */
+
+#ifndef _SECURITY_LANDLOCK_TRACE_H
+#define _SECURITY_LANDLOCK_TRACE_H
+
+struct landlock_hierarchy;
+
+#ifdef CONFIG_TRACEPOINTS
+
+void landlock_trace_free_domain(
+	const struct landlock_hierarchy *const hierarchy);
+
+#else /* CONFIG_TRACEPOINTS */
+
+static inline void
+landlock_trace_free_domain(const struct landlock_hierarchy *const hierarchy)
+{
+}
+
+#endif /* CONFIG_TRACEPOINTS */
+
+#endif /* _SECURITY_LANDLOCK_TRACE_H */
Signature · 1 line
2.54.0
author maintainer
#14 lore raw

PATCH v3 11/20 landlock: Add landlock_enforce_domain tracepoint

In reply to Mickaël Salaün

The landlock_create_domain event records that a domain was created, once, before thread-sync. It cannot tell which threads end up enforcing
it: a successful landlock_restrict_self(2) with LANDLOCK_RESTRICT_SELF_TSYNC applies the domain to the caller and every eligible sibling. Creation (the operation) and enforcement (the per-thread outcome) are distinct.

Add landlock_enforce_domain(domain, complete, process_wide), emitted once per thread the domain is applied to, strictly after that thread's commit_creds(), so it fires only for a thread that is enforcing the domain, never speculatively; an aborted operation emits none. The lifecycle now reads create -> enforce* -> free.

The two booleans name properties, not the implementation:
- complete: marks the single event that concludes the operation. It names the outcome, the set is now enforced, not which thread finishes, which the contract leaves unspecified.
- process_wide: means every eligible thread of the process is covered. It is set race-free by either establishing path, thread-sync or a single-threaded process, so
complete && process_wide is the whole-process-enforced guarantee.

The requesting thread and source ruleset are not repeated here: they are on create_domain (joined via domain->hierarchy->id) and on the immutable domain->hierarchy->details. Source ruleset means the ruleset_id and ruleset_version recorded on create_domain, not the ruleset object, which the caller may close before enforcement.

Cc Günther Noack <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Mathieu Desnoyers <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
- New patch.

---
 include/trace/events/landlock.h | 52 +++++++++++++++++++++++++++++++++
 security/landlock/syscalls.c    | 13 ++++++++-
 security/landlock/tsync.c       | 15 ++++++++++
 3 files changed, 79 insertions(+), 1 deletion(-)
include/trace/events/landlock.h +52 -0
index cb0e21a2fa1f..7f221d8fff38 100644
@@ -289,6 +289,58 @@ TRACE_EVENT(landlock_create_domain,
 		__entry->ruleset_id, __entry->ruleset_version)
 );
 
+/**
+ * landlock_enforce_domain - Domain enforced on a thread
+ *
+ * @domain: Domain now enforced on the current thread (never NULL,
+ *          immutable; read locklessly).  Correlate to
+ *          landlock_create_domain via @domain->hierarchy->id for the
+ *          source ruleset and requesting thread, or read
+ *          @domain->hierarchy->details for the requesting process.
+ * @complete: Set on the single event that concludes the operation, after
+ *            all its other enforcements; filter on it for one event per
+ *            operation.
+ * @process_wide: The enforcement covers every eligible (non-exiting)
+ *                thread of the process: set when the caller used
+ *                %LANDLOCK_RESTRICT_SELF_TSYNC or the process is
+ *                single-threaded.  A lone thread whose group still
+ *                holds a zombie leader is not counted single-threaded,
+ *                so process_wide == 0 never proves the opposite.
+ *
+ * Emitted for each thread sys_landlock_restrict_self() enforces the
+ * domain on, in that thread's own context, right after its
+ * commit_creds(), so it fires only once the thread is irreversibly
+ * enforcing the domain (aborted operations emit none).  Not
+ * balanced; every enforcement falls between the domain's
+ * landlock_create_domain and landlock_free_domain events.
+ *
+ * @complete == 1 && @process_wide == 1 means the whole process is
+ * sandboxed by @domain, durably (Landlock domains are monotonic and
+ * inherited on :manpage:`clone(2)`).
+ */
+TRACE_EVENT(landlock_enforce_domain,
+
+	TP_PROTO(const struct landlock_domain *domain, bool complete,
+		 bool process_wide),
+
+	TP_ARGS(domain, complete, process_wide),
+
+	TP_STRUCT__entry(
+		__field(	__u64,		domain_id	)
+		__field(	bool,		complete	)
+		__field(	bool,		process_wide	)
+	),
+
+	TP_fast_assign(
+		__entry->domain_id	= domain->hierarchy->id;
+		__entry->complete	= complete;
+		__entry->process_wide	= process_wide;
+	),
+
+	TP_printk("domain=%llx complete=%d process_wide=%d",
+		__entry->domain_id, __entry->complete, __entry->process_wide)
+);
+
 /**
  * landlock_free_domain - Domain freed
  *
security/landlock/syscalls.c +12 -1
index 7a1ec140cf14..bf838f65b060 100644
@@ -22,6 +22,7 @@
 #include <linux/mount.h>
 #include <linux/path.h>
 #include <linux/sched.h>
+#include <linux/sched/signal.h>
 #include <linux/security.h>
 #include <linux/stddef.h>
 #include <linux/syscalls.h>
@@ -539,6 +540,7 @@ SYSCALL_DEFINE2(landlock_restrict_self, const int, ruleset_fd, const __u32,
 	struct landlock_domain *new_dom = NULL;
 	struct cred *new_cred;
 	struct landlock_cred_security *new_llcred;
+	bool process_wide;
 	bool __maybe_unused log_same_exec, log_new_exec, log_subdomains,
 		prev_log_subdomains;
 
@@ -677,5 +679,14 @@ SYSCALL_DEFINE2(landlock_restrict_self, const int, ruleset_fd, const __u32,
 		}
 	}
 
-	return commit_creds(new_cred);
+	/* Whole process: thread-sync swept siblings, or single-threaded. */
+	process_wide = (flags & LANDLOCK_RESTRICT_SELF_TSYNC) ||
+		       get_nr_threads(current) == 1;
+	commit_creds(new_cred);
+
+	/* The caller commits last, so its event concludes the operation. */
+	if (ruleset)
+		trace_landlock_enforce_domain(new_dom, true, process_wide);
+
+	return 0;
 }
security/landlock/tsync.c +15 -0
index c5730bbd9ed3..b7de4f9624c7 100644
@@ -21,6 +21,8 @@
 #include "cred.h"
 #include "tsync.h"
 
+#include <trace/events/landlock.h>
+
 /*
  * Shared state between multiple threads which are enforcing Landlock rulesets
  * in lockstep with each other.
@@ -78,6 +80,8 @@ struct tsync_work {
  */
 static void restrict_one_thread(struct tsync_shared_context *ctx)
 {
+	const struct landlock_domain *new_dom =
+		landlock_cred(ctx->new_cred)->domain;
 	int err;
 	struct cred *cred = NULL;
 
@@ -146,6 +150,17 @@ static void restrict_one_thread(struct tsync_shared_context *ctx)
 
 	commit_creds(cred);
 
+	/*
+	 * Emitted strictly after commit_creds() and before the out: label, so
+	 * it fires only for a thread now enforcing new_dom, and every
+	 * non-concluding (complete == false) event happens-before the
+	 * operation's single concluding one.  Skipped on the flags-only path,
+	 * where old_cred and new_cred carry the same domain.  A sibling never
+	 * concludes the operation and its enforcement is always process-wide.
+	 */
+	if (new_dom != landlock_cred(ctx->old_cred)->domain)
+		trace_landlock_enforce_domain(new_dom, false, true);
+
 out:
 	/* Notify the calling thread once all threads are done */
 	if (atomic_dec_return(&ctx->num_unfinished) == 0)
Signature · 1 line
2.54.0
author maintainer
#15 lore raw

PATCH v3 12/20 landlock: Add tracepoints for rule checking

In reply to Mickaël Salaün

Merge landlock_find_rule() into landlock_unmask_layers() so rule pointers stay inside the domain implementation while unmask checking gets the matched rule it needs for the check_rule tracepoint. landlock_unmask_layers() now takes a landlock_id and the domain instead of a rule pointer. A rename or link evaluates the same dentry against both renamed parents, so this path now looks the rule up once per parent; collapsing that back to a single lookup is left to a follow-up.

Emit, via the per-type wrappers unmask_layers_fs() and unmask_layers_net(), the rights each matching rule grants at every domain layer. The events carry this as a dynamic per-layer array (up to LANDLOCK_MAX_NUM_LAYERS entries) reserved from the trace ring buffer, not the caller's stack, and rendered symbolically per layer. A WARN_ON_ONCE() in __trace_landlock_fill_layers() flags a rule whose layer levels fall outside the domain range or are unsorted, a cannot-happen case; the zero-filled slots keep the rendered output and the array bounds safe regardless.

Setting allowed_parent2 to true for non-dom-check requests when get_inode_id() returns false preserves the pre-refactoring behavior: a negative dentry (no backing inode) has no matching rule, so the access is allowed at this path component. Before the refactoring, landlock_unmask_layers() with a NULL rule produced this result as a side effect; now the caller must set it explicitly.

Name the trace-only check_rule fields so each printk label equals its ring-buffer field name and works directly as an ftrace filter: the request field is labelled access_request= and the per-layer array is named grants. Values audit also logs keep audit's label (domain=, ruleset=) so a single filter works across trace and audit.

Cc Günther Noack <[email protected]>
Cc Justin Suess <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Mathieu Desnoyers <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Order the check_rule tracepoint arguments with the common part (domain, rule) before the event-specific access_request and object.
- Reformatted TP_STRUCT__entry and TP_fast_assign to kernel tracing convention (requested by Steven Rostedt).
- Render the request access right as symbolic names with __print_flags(), shared with the audit blocker names.
- Rename the per-layer field label allowed= to grants= and render it symbolically via __print_landlock_layers(), intersected with the request to show the granted requested rights per layer (was a raw hex value).
- Rename struct layer_access_masks to the base's struct layer_masks.
- Rename the check_rule printk label request= to access_request= and the per-layer ring-buffer field layers to grants, so each trace-only field and its printk label share one name (usable directly as an ftrace filter); audit-shared labels (domain=, ruleset=) are unchanged.

Changes since v1:
https://patch.msgid.link/[email protected]
- Merged find-rule consolidation (v1 2/5) into this patch.
- Added check_rule_net tracepoint for network rules.
- Added get_inode_id() helper with rcu_access_pointer().
- Added allowed_parent2 behavioral fix.

---
 include/trace/events/landlock.h | 203 ++++++++++++++++++++++++++++++++
 security/landlock/domain.c      |  32 +++--
 security/landlock/domain.h      |  10 +-
 security/landlock/fs.c          | 149 +++++++++++++++--------
 security/landlock/net.c         |  21 +++-
 5 files changed, 350 insertions(+), 65 deletions(-)
include/trace/events/landlock.h +203 -0
index 7f221d8fff38..c693248afe23 100644
@@ -11,10 +11,13 @@
 #define _TRACE_LANDLOCK_H
 
 #include <linux/landlock.h>
+#include <linux/trace_seq.h>
 #include <linux/tracepoint.h>
 
+struct dentry;
 struct landlock_domain;
 struct landlock_hierarchy;
+struct landlock_rule;
 struct landlock_ruleset;
 struct path;
 
@@ -74,7 +77,110 @@ struct path;
  * (e.g. network ports are __u64 in host endianness, like
  * landlock_net_port_attr.port).  Per-event details, such as where a value
  * is byte-swapped, live in the field's own kdoc.
+ *
+ * Rule-check fields
+ * ~~~~~~~~~~~~~~~~~
+ *
+ * The check_rule events fire during an access check, once per matching
+ * rule, before the final allow-or-deny verdict.  They share domain (the
+ * enforcing domain being evaluated), access_request (the access mask being
+ * checked), and rule (the matching rule, with per-layer access masks).
+ */
+
+#ifdef CREATE_TRACE_POINTS
+
+/*
+ * Fills the dense per-domain-layer array layers (one access mask per layer,
+ * indexed by level - 1) from rule's sparse layer stack, keeping only the
+ * requested rights (access_request).  Layers with no matching rule entry get
+ * a zero mask.  Shared by the check_rule_fs and check_rule_net events.
+ *
+ * rule->layers is sorted by ascending level, with levels in the domain's
+ * [1, num_layers] range (see landlock_merge_ruleset()), so every entry maps
+ * to a slot.  A leftover entry would be a malformed rule; the zero-filled
+ * slots keep the output and the array bounds safe regardless.
  */
+static inline void
+__trace_landlock_fill_layers(access_mask_t *const layers,
+			     const size_t num_layers,
+			     const struct landlock_rule *const rule,
+			     const access_mask_t access_request)
+{
+	size_t i = 0;
+
+	for (size_t level = 1; level <= num_layers; level++) {
+		access_mask_t grants = 0;
+
+		if (i < rule->num_layers && level == rule->layers[i].level) {
+			grants = rule->layers[i].access & access_request;
+			i++;
+		}
+		layers[level - 1] = grants;
+	}
+
+	/* A leftover entry means an out-of-range or unsorted rule level. */
+	WARN_ON_ONCE(i < rule->num_layers);
+}
+
+/*
+ * Renders the dense per-domain-layer access array as symbolic flag names for
+ * the grants field: layers wrapped in "{}", flags within a layer joined by
+ * "|", layers separated by ",", an empty layer rendered as nothing.
+ * Open-codes the flag walk because trace_print_flags_seq() NUL-terminates per
+ * call and so cannot be chained into a single field.  The shared names table
+ * covers every access right, so masked bits are always named.  Returns the
+ * trace_seq position like __print_flags().
+ */
+static inline const char *
+__trace_landlock_print_layers(struct trace_seq *p,
+			      const access_mask_t *const layers,
+			      const size_t num_layers,
+			      const struct trace_print_flags *const names,
+			      const size_t names_size)
+{
+	const char *const ret = trace_seq_buffer_ptr(p);
+
+	trace_seq_putc(p, '{');
+	for (size_t i = 0; i < num_layers; i++) {
+		access_mask_t mask = layers[i];
+		bool first = true;
+
+		if (i)
+			trace_seq_putc(p, ',');
+		for (size_t j = 0; mask && j < names_size; j++) {
+			if ((mask & names[j].mask) != names[j].mask)
+				continue;
+			if (!first)
+				trace_seq_putc(p, '|');
+			trace_seq_puts(p, names[j].name);
+			mask &= ~names[j].mask;
+			first = false;
+		}
+	}
+	trace_seq_putc(p, '}');
+	trace_seq_putc(p, 0);
+	return ret;
+}
+
+#endif /* CREATE_TRACE_POINTS */
+
+/*
+ * Prints a per-layer access mask array (the dynamic array @array) as symbolic
+ * flag names using the shared @flag_names list (a _LANDLOCK_*_NAMES macro).
+ * Stays outside CREATE_TRACE_POINTS: TP_printk is expanded in the print-output
+ * pass where that macro is undefined.
+ */
+#define __print_landlock_layers(array, flag_names...)			\
+	({								\
+		static const struct trace_print_flags __layer_names[] = { \
+			flag_names					\
+		};							\
+		__trace_landlock_print_layers(				\
+			p, __get_dynamic_array(array),			\
+			__get_dynamic_array_len(array) /		\
+				sizeof(access_mask_t),			\
+			__layer_names, ARRAY_SIZE(__layer_names));	\
+	})
 
 /**
  * landlock_create_ruleset - New ruleset created
@@ -374,6 +480,103 @@ TRACE_EVENT(landlock_free_domain,
 		__entry->domain_id, __entry->denials)
 );
 
+/**
+ * landlock_check_rule_fs - Filesystem rule evaluated during access check
+ *
+ * @domain: Enforcing domain (never NULL).
+ * @rule: Matching rule with per-layer access masks (never NULL).
+ * @access_request: Access mask evaluated against the rule (the domain's
+ *                   handled mask during rename/link double-checks).
+ * @dentry: Filesystem dentry being checked (never NULL).
+ *
+ * Emitted for each rule that matches during a filesystem access check.
+ * The grants array shows the requested rights the rule grants at each
+ * domain layer.  See Documentation/trace/events-landlock.rst for how to
+ * interpret it.
+ */
+TRACE_EVENT(landlock_check_rule_fs,
+
+	TP_PROTO(const struct landlock_domain *domain,
+		 const struct landlock_rule *rule,
+		 access_mask_t access_request, const struct dentry *dentry),
+
+	TP_ARGS(domain, rule, access_request, dentry),
+
+	TP_STRUCT__entry(
+		__field(	__u64,		domain_id	)
+		__field(	access_mask_t,	access_request	)
+		__field(	dev_t,		dev		)
+		__field(	ino_t,		ino		)
+		__dynamic_array(access_mask_t,	grants,
+				domain->num_layers)
+	),
+
+	TP_fast_assign(
+		__entry->domain_id	= domain->hierarchy->id;
+		__entry->access_request	= access_request;
+		__entry->dev		= dentry->d_sb->s_dev;
+		__entry->ino		= d_backing_inode(dentry)->i_ino;
+
+		__trace_landlock_fill_layers(__get_dynamic_array(grants),
+					     __get_dynamic_array_len(grants) /
+						     sizeof(access_mask_t),
+					     rule, access_request);
+	),
+
+	TP_printk("domain=%llx access_request=%s dev=%u:%u ino=%lu grants=%s",
+		__entry->domain_id,
+		__print_flags(__entry->access_request, "|", _LANDLOCK_ACCESS_FS_NAMES),
+		MAJOR(__entry->dev), MINOR(__entry->dev), __entry->ino,
+		__print_landlock_layers(grants, _LANDLOCK_ACCESS_FS_NAMES))
+);
+
+/**
+ * landlock_check_rule_net - Network port rule evaluated during access check
+ *
+ * @domain: Enforcing domain (never NULL).
+ * @rule: Matching rule with per-layer access masks (never NULL).
+ * @access_request: Access mask being requested.
+ * @port: Network port being checked (host endianness).
+ *
+ * Emitted for each rule that matches during a network access check.  The
+ * grants array shows the requested rights the rule grants at each domain
+ * layer.  See Documentation/trace/events-landlock.rst for how to
+ * interpret it.
+ */
+TRACE_EVENT(landlock_check_rule_net,
+
+	TP_PROTO(const struct landlock_domain *domain,
+		 const struct landlock_rule *rule,
+		 access_mask_t access_request, __u64 port),
+
+	TP_ARGS(domain, rule, access_request, port),
+
+	TP_STRUCT__entry(
+		__field(	__u64,		domain_id	)
+		__field(	access_mask_t,	access_request	)
+		__field(	__u64,		port		)
+		__dynamic_array(access_mask_t,	grants,
+				domain->num_layers)
+	),
+
+	TP_fast_assign(
+		__entry->domain_id	= domain->hierarchy->id;
+		__entry->access_request	= access_request;
+		__entry->port		= port;
+
+		__trace_landlock_fill_layers(__get_dynamic_array(grants),
+					     __get_dynamic_array_len(grants) /
+						     sizeof(access_mask_t),
+					     rule, access_request);
+	),
+
+	TP_printk("domain=%llx access_request=%s port=%llu grants=%s",
+		__entry->domain_id,
+		__print_flags(__entry->access_request, "|", _LANDLOCK_ACCESS_NET_NAMES),
+		__entry->port,
+		__print_landlock_layers(grants, _LANDLOCK_ACCESS_NET_NAMES))
+);
+
 #undef _LANDLOCK_NAME_ENTRY
 
 #endif /* _TRACE_LANDLOCK_H */
security/landlock/domain.c +22 -10
index 082c4da68536..c20020024de4 100644
@@ -97,9 +97,9 @@ void landlock_put_domain_deferred(struct landlock_domain *const domain)
 }
 
 /* The returned access has the same lifetime as the domain. */
-const struct landlock_rule *
-landlock_find_rule(const struct landlock_domain *const domain,
-		   const struct landlock_id id)
+static const struct landlock_rule *
+find_rule(const struct landlock_domain *const domain,
+	  const struct landlock_id id)
 {
 	const struct rb_root *root;
 	const struct rb_node *node;
@@ -126,26 +126,38 @@ landlock_find_rule(const struct landlock_domain *const domain,
 
 /**
  * landlock_unmask_layers - Remove the access rights in @masks which are
- *                          granted in @rule
+ *                          granted by a matching rule
  *
- * Updates the set of (per-layer) unfulfilled access rights @masks so that all
- * the access rights granted in @rule are removed from it (because they are now
- * fulfilled).
+ * Looks up the rule matching @id in @domain, then updates the set of
+ * (per-layer) unfulfilled access rights @masks so that all the access rights
+ * granted by that rule are removed (because they are now fulfilled).
  *
- * @rule: A rule that grants a set of access rights for each layer.
+ * @domain: The Landlock domain to search for a matching rule.
+ * @id: Identifier for the rule target (e.g. inode, port).
  * @masks: A matrix of unfulfilled access rights for each layer.
+ * @matched_rule: Optional output for the matched rule (for tracing); set to
+ *                the matching rule when non-NULL, unchanged otherwise.
  *
  * Return: True if the request is allowed (i.e. the access rights granted all
  * remaining unfulfilled access rights and masks has no leftover set bits).
  */
-bool landlock_unmask_layers(const struct landlock_rule *const rule,
-			    struct layer_masks *masks)
+bool landlock_unmask_layers(const struct landlock_domain *const domain,
+			    const struct landlock_id id,
+			    struct layer_masks *masks,
+			    const struct landlock_rule **matched_rule)
 {
+	const struct landlock_rule *rule;
+
 	if (!masks)
 		return true;
+
+	rule = find_rule(domain, id);
 	if (!rule)
 		return false;
 
+	if (matched_rule)
+		*matched_rule = rule;
+
 	/*
 	 * An access is granted if, for each policy layer, at least one rule
 	 * encountered on the pathwalk grants the requested access, regardless
security/landlock/domain.h +4 -6
index 8351e22016fe..5baa4a73b446 100644
@@ -305,12 +305,10 @@ struct landlock_domain *
 landlock_merge_ruleset(struct landlock_domain *const parent,
 		       struct landlock_ruleset *const ruleset);
 
-const struct landlock_rule *
-landlock_find_rule(const struct landlock_domain *const domain,
-		   const struct landlock_id id);
-
-bool landlock_unmask_layers(const struct landlock_rule *const rule,
-			    struct layer_masks *masks);
+bool landlock_unmask_layers(const struct landlock_domain *const domain,
+			    const struct landlock_id id,
+			    struct layer_masks *masks,
+			    const struct landlock_rule **matched_rule);
 
 access_mask_t
 landlock_init_layer_masks(const struct landlock_domain *const domain,
security/landlock/fs.c +103 -46

212 lines not on this page · raw message

security/landlock/net.c +18 -3
index ead97fcfdcff..8f2aaac54b33 100644
@@ -53,6 +53,22 @@ int landlock_append_net_rule(struct landlock_ruleset *const ruleset,
 	return err;
 }
 
+static bool unmask_layers_net(const struct landlock_domain *const domain,
+			      const struct landlock_id id,
+			      struct layer_masks *masks,
+			      access_mask_t access_request)
+{
+	const struct landlock_rule *rule = NULL;
+	bool ret;
+
+	ret = landlock_unmask_layers(domain, id, masks, &rule);
+	if (rule)
+		trace_landlock_check_rule_net(
+			domain, rule, access_request,
+			ntohs((__force __be16)id.key.data));
+	return ret;
+}
+
 static int current_check_access_socket(struct socket *const sock,
 				       struct sockaddr *const address,
 				       const int addrlen,
@@ -62,7 +78,6 @@ static int current_check_access_socket(struct socket *const sock,
 	unsigned short sock_family;
 	__be16 port;
 	struct layer_masks layer_masks = {};
-	const struct landlock_rule *rule;
 	struct landlock_id id = {
 		.type = LANDLOCK_KEY_NET_PORT,
 	};
@@ -248,14 +263,14 @@ static int current_check_access_socket(struct socket *const sock,
 	id.key.data = (__force uintptr_t)port;
 	BUILD_BUG_ON(sizeof(port) > sizeof(id.key.data));
 
-	rule = landlock_find_rule(subject->domain, id);
 	access_request = landlock_init_layer_masks(subject->domain,
 						   access_request, &layer_masks,
 						   LANDLOCK_KEY_NET_PORT);
 	if (!access_request)
 		return 0;
 
-	if (landlock_unmask_layers(rule, &layer_masks))
+	if (unmask_layers_net(subject->domain, id, &layer_masks,
+			      access_request))
 		return 0;
 
 	audit_net.family = address->sa_family;
Signature · 1 line
2.54.0
author maintainer
#16 lore raw

PATCH v3 13/20 landlock: Add landlock_deny_access_fs and landlock_deny_access_net

In reply to Mickaël Salaün

Add per-type tracepoints emitted from landlock_log_denial() when an access is denied: landlock_deny_access_fs for filesystem denials and landlock_deny_access_net for network denials. They use the "deny_" prefix (rather than "check_") to mark that they fire only on a denial, and they complement the check_rule events by making the denial-by-absence case explicit (when no rule matches, no check_rule event fires).

Unlike the audit records, these events fire regardless of the audit configuration and the domain's log flags: the user's "disable logging" intent applies to audit records, not to kernel tracing. The logged field records whether the domain's log policy would submit the denial to audit; it is the decision computed once by landlock_log_denial() and passed to both the audit and the tracing emitter, so a stateless ftrace filter can select the audit-visible denials with logged==1.

TP_PROTO passes the denying hierarchy node, not the task's current domain, so domain_id reports the specific node that blocked the access, matching audit record semantics. (check_rule instead passes the current domain, which it needs to size its per-layer array.) same_exec is also passed explicitly because it is computed from the credential bitmask and is not derivable from the hierarchy pointer alone. The denial field is named blockers to match the audit record field.

The filesystem path comes from the request's audit data. Its type selects which union member holds the object, exactly as dump_common_audit_data() selects it (a path, a file's path, an ioctl op's path, or a bare dentry); reading the wrong member would dereference garbage, so every reachable type has an explicit case and an unexpected one is flagged with WARN_ONCE() instead of misread. Path-backed types resolve via d_absolute_path() (as landlock_add_rule_fs does) and the bare-dentry case via dentry_path_raw().

The inode number is read defensively. A filesystem denial can carry a negative dentry (no backing inode), for example a denied creation, so the event mirrors the guard in dump_common_audit_data() and reports inode 0 rather than dereferencing a NULL inode. The sibling fs tracepoints do not need the guard: a dentry that matches a rule during an access check, or one opened to add a rule, always has a backing inode. Landlock tracepoints are reachable by unprivileged sandboxees, so a denial on a negative dentry with the event enabled must not fault the kernel.

Cc Günther Noack <[email protected]>
Cc Justin Suess <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Mathieu Desnoyers <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Guard the deny_access_fs inode read against a negative dentry (no backing inode), mirroring dump_common_audit_data(), so an enabled event cannot NULL-deref on such a denial.
- Reformatted TP_STRUCT__entry, TP_fast_assign, and TP_printk to the kernel tracing convention (requested by Steven Rostedt).
- Replaced the deny events' log_same_exec and log_new_exec fields with a single logged boolean (the domain's audit-logging decision).
- Render blockers as symbolic names with __print_flags(), shared with the audit blocker names, instead of raw hex.
- Move the per-denial logging decision (is_denial_logged() and the logged boolean it feeds to landlock_audit_denial()) and the decoupling of the log state from CONFIG_AUDIT (the domain_exec and log_subdomains_off credential fields and the LANDLOCK_LOG_DISABLED assignment) to the commits that separate the common log framework and the logging decision from audit; this patch consumes the precomputed logged value and emits the events from the dedicated tracing translation unit.
- Select the deny_access_fs path from the request's audit-data type (path, file, ioctl op, or dentry) instead of always reading the path union member, so a truncate or ioctl denial no longer dereferences the wrong member (a crash an unprivileged sandboxee could trigger via ftruncate()/ioctl() with the event enabled).
- Correct the deny_access_net port-field documentation: dport is zero for a UDP send to an AF_UNSPEC address on an IPv6 socket (not a connect), sport is zero for an autobind port, and the bind-vs-connect direction is given by blockers.
- Emit the deny_access_fs event from a single call site and map dentry_path_raw()'s -ENAMETOOLONG to "<too_long>", matching the d_absolute_path() case.
- Give the deny_access_fs audit-data-type switch an explicit case for each reachable type and a WARN_ONCE() default reporting the offending type, so a future FS audit type cannot silently misread the path union.

Changes since v1:
- New patch.

---
 include/trace/events/landlock.h | 128 ++++++++++++++++++++++++++++++++
 security/landlock/log.c         |   2 +
 security/landlock/trace.c       | 119 ++++++++++++++++++++++++++++-
 security/landlock/trace.h       |  16 ++++
 4 files changed, 264 insertions(+), 1 deletion(-)
include/trace/events/landlock.h +128 -0
index c693248afe23..e70dcc9a94b9 100644
@@ -20,6 +20,7 @@ struct landlock_hierarchy;
 struct landlock_rule;
 struct landlock_ruleset;
 struct path;
+struct sock;
 
 /* Maps a shared _LANDLOCK_*_NAMES entry to a __print_flags() pair. */
 #define _LANDLOCK_NAME_ENTRY(mask, name) { mask, name }
@@ -85,6 +86,20 @@ struct path;
  * rule, before the final allow-or-deny verdict.  They share domain (the
  * enforcing domain being evaluated), access_request (the access mask being
  * checked), and rule (the matching rule, with per-layer access masks).
+ *
+ * Denial fields
+ * ~~~~~~~~~~~~~
+ *
+ * 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,
+ * logged, then blockers (deny_access events only), then the type-specific
+ * object fields, then any variable-length field.
  */
 
 #ifdef CREATE_TRACE_POINTS
@@ -577,6 +592,119 @@ TRACE_EVENT(landlock_check_rule_net,
 		__print_landlock_layers(grants, _LANDLOCK_ACCESS_NET_NAMES))
 );
 
+/**
+ * landlock_deny_access_fs - Filesystem access denied
+ *
+ * @hierarchy: Denying domain's hierarchy node (never NULL); its id is the
+ *             domain field.
+ * @same_exec: Whether the current task entered the denying domain itself.
+ * @logged: The domain's audit-logging decision for this denial.
+ * @blockers: Access mask that was blocked (zero for a mount-topology
+ *            change, whose only blocker is the operation itself).
+ * @path: Filesystem path that was denied (never NULL).
+ * @pathname: Resolved path string (never NULL; an error placeholder on
+ *            resolution failure).
+ *
+ * Emitted when a Landlock domain denies a filesystem access.
+ */
+TRACE_EVENT(landlock_deny_access_fs,
+
+	TP_PROTO(const struct landlock_hierarchy *hierarchy, bool same_exec,
+		 bool logged, access_mask_t blockers, const struct path *path,
+		 const char *pathname),
+
+	TP_ARGS(hierarchy, same_exec, logged, blockers, path, pathname),
+
+	TP_STRUCT__entry(
+		__field(	__u64,		domain_id	)
+		__field(	bool,		same_exec	)
+		__field(	bool,		logged		)
+		__field(	access_mask_t,	blockers	)
+		__field(	dev_t,		dev		)
+		__field(	ino_t,		ino		)
+		__string(	pathname,	pathname	)
+	),
+
+	TP_fast_assign(
+		const struct inode *inode = d_backing_inode(path->dentry);
+
+		__entry->domain_id	= hierarchy->id;
+		__entry->same_exec	= same_exec;
+		__entry->logged		= logged;
+		__entry->blockers	= blockers;
+		__entry->dev		= path->dentry->d_sb->s_dev;
+		/*
+		 * A negative dentry has no backing inode, so mirror the
+		 * guard in dump_common_audit_data() and report inode 0.
+		 */
+		__entry->ino		= inode ? inode->i_ino : 0;
+		__assign_str(pathname);
+	),
+
+	TP_printk("domain=%llx same_exec=%d logged=%d blockers=%s dev=%u:%u ino=%lu path=%s",
+		__entry->domain_id, __entry->same_exec, __entry->logged,
+		__print_flags(__entry->blockers, "|", _LANDLOCK_ACCESS_FS_NAMES),
+		MAJOR(__entry->dev), MINOR(__entry->dev), __entry->ino,
+		__print_untrusted_str(pathname))
+);
+
+/**
+ * landlock_deny_access_net - Network access denied
+ *
+ * @hierarchy: Denying domain's hierarchy node (never NULL); its id is the
+ *             domain field.
+ * @same_exec: Whether the current task entered the denying domain itself.
+ * @logged: The domain's audit-logging decision for this denial.
+ * @blockers: Access mask that was blocked.
+ * @sk: Socket object (never NULL), read without a socket lock, so its
+ *      fields are a best-effort snapshot.  The denied endpoint is not
+ *      available: the hook runs before :manpage:`bind(2)` /
+ *      :manpage:`connect(2)` sets the socket addresses.
+ * @sport: Source port in host endianness, set for bind denials (zero for
+ *         an autobind/ephemeral port); zero for connect and send denials.
+ * @dport: Destination port in host endianness, set for connect and send
+ *         denials; zero for bind denials, and also zero for a UDP send to
+ *         an AF_UNSPEC address on an IPv6 socket (indistinguishable from a
+ *         real destination port 0).  The bind-vs-connect direction is
+ *         given by @blockers, not by which port is set.
+ *
+ * Emitted when a Landlock domain denies a network operation.
+ *
+ * The port fields are converted from the socket's network byte order to
+ * host endianness before emitting.
+ */
+TRACE_EVENT(landlock_deny_access_net,
+
+	TP_PROTO(const struct landlock_hierarchy *hierarchy, bool same_exec,
+		 bool logged, access_mask_t blockers, const struct sock *sk,
+		 __u64 sport, __u64 dport),
+
+	TP_ARGS(hierarchy, same_exec, logged, blockers, sk, sport, dport),
+
+	TP_STRUCT__entry(
+		__field(	__u64,		domain_id	)
+		__field(	bool,		same_exec	)
+		__field(	bool,		logged		)
+		__field(	access_mask_t,	blockers	)
+		__field(	__u64,		sport		)
+		__field(	__u64,		dport		)
+	),
+
+	TP_fast_assign(
+		__entry->domain_id	= hierarchy->id;
+		__entry->same_exec	= same_exec;
+		__entry->logged		= logged;
+		__entry->blockers	= blockers;
+		__entry->sport		= sport;
+		__entry->dport		= dport;
+	),
+
+	TP_printk("domain=%llx same_exec=%d logged=%d blockers=%s sport=%llu dport=%llu",
+		__entry->domain_id, __entry->same_exec, __entry->logged,
+		__print_flags(__entry->blockers, "|", _LANDLOCK_ACCESS_NET_NAMES),
+		__entry->sport, __entry->dport)
+);
+
 #undef _LANDLOCK_NAME_ENTRY
 
 #endif /* _TRACE_LANDLOCK_H */
security/landlock/log.c +2 -0
index 13033808bdbd..931d8b4c2c06 100644
@@ -543,6 +543,8 @@ void landlock_log_denial(const struct landlock_cred_security *const subject,
 	 */
 	atomic64_inc(&youngest_denied->num_denials);
 
+	landlock_trace_denial(request, youngest_denied, missing, same_exec,
+			      logged);
 	landlock_audit_denial(request, youngest_denied, missing, logged);
 }
 
security/landlock/trace.c +118 -1

130 lines not on this page · raw message

security/landlock/trace.h +16 -0
index 59c8ea348625..7be98e748855 100644
@@ -9,13 +9,21 @@
 #ifndef _SECURITY_LANDLOCK_TRACE_H
 #define _SECURITY_LANDLOCK_TRACE_H
 
+#include "access.h"
+
 struct landlock_hierarchy;
+struct landlock_request;
 
 #ifdef CONFIG_TRACEPOINTS
 
 void landlock_trace_free_domain(
 	const struct landlock_hierarchy *const hierarchy);
 
+void landlock_trace_denial(
+	const struct landlock_request *const request,
+	const struct landlock_hierarchy *const youngest_denied,
+	const access_mask_t missing, const bool same_exec, const bool logged);
+
 #else /* CONFIG_TRACEPOINTS */
 
 static inline void
@@ -23,6 +31,14 @@ landlock_trace_free_domain(const struct landlock_hierarchy *const hierarchy)
 {
 }
 
+static inline void
+landlock_trace_denial(const struct landlock_request *const request,
+		      const struct landlock_hierarchy *const youngest_denied,
+		      const access_mask_t missing, const bool same_exec,
+		      const bool logged)
+{
+}
+
 #endif /* CONFIG_TRACEPOINTS */
 
 #endif /* _SECURITY_LANDLOCK_TRACE_H */
Signature · 1 line
2.54.0
author maintainer
#17 lore raw

PATCH v3 14/20 landlock: Add tracepoints for ptrace and scope denials

In reply to Mickaël Salaün

Scope and ptrace denials follow a different code path (a domain hierarchy check) than access-right denials, so they need dedicated tracepoints with type-specific TP_PROTO arguments. Complete the denial coverage with:
- landlock_deny_ptrace: ptrace access denied by a domain hierarchy mismatch.
- landlock_deny_scope_signal: signal delivery denied by LANDLOCK_SCOPE_SIGNAL.
- landlock_deny_scope_abstract_unix_socket: abstract unix socket access denied by LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET.

TP_PROTO passes the raw kernel object (struct task_struct or struct sock) for eBPF BTF access; the comm and sun_path string fields use __print_untrusted_str() because they hold untrusted input. Unlike the deny_access events, these omit the blockers field: each maps to exactly one denial type named by the event, so the bitmask would always be zero. Like the deny_access events they carry same_exec and logged.

Audit logs the task-targeted denials with generic field names (opid, ocomm), but a strongly typed trace event can use role-prefixed names (tracee_pid/tracee_comm, target_pid/target_comm) that match the mainline task-name convention (sched_process_fork's parent_comm/child_comm) and say whose name each field holds; a bare comm= would collide across events. The abstract-unix-socket event reports peer_pid instead, a tracepoint-only field with no audit counterpart.

A scope or ptrace verdict compares the subject domain against the other party's domain, so each event also reports that other party's Landlock domain (tracee_domain=, target_domain=, or peer_domain=); the subject domain= alone does not let a consumer redo domain_is_scoped() or domain_ptrace(). It is reported as a scalar ID rather than a domain
pointer: a domain object is immutable, but the other task can replace its credential and free the domain that credential referenced, so a stored foreign pointer could dangle before the event is consumed. The scalar ID also honors the tracepoint no-nullable-pointer rule, since the other party is frequently unsandboxed. Passing the foreign domain hierarchy object so an eBPF consumer could walk the other party's ancestry live would lengthen the RCU section on the shared denial path and needs a deferred refcount put, so it is left as a future enhancement. The relational domain-ID field (tracee_domain, target_domain, or peer_domain) is trace-only and is not added to audit records, so audit's denial format is unchanged by this series.

Cc Günther Noack <[email protected]>
Cc Justin Suess <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Mathieu Desnoyers <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Reformatted TRACE_EVENT bodies to the kernel tracing convention with one field per line and tab-aligned columns (requested by Steven Rostedt).
- Replaced the log_same_exec and log_new_exec fields with the single logged boolean, matching the deny_access events.
- Assert unix_state_lock(peer) in the abstract-unix-socket event (held by the caller) and document why unix_sk(peer)->addr is stable. Document peer_pid as a best-effort READ_ONCE read: its canonical lock is sk->sk_peer_lock, not unix_state_lock, but the target peer's peercred is not updated concurrently in these hooks, and it is 0 for a datagram peer.
- Renamed the deny_ptrace and deny_scope_signal printk label comm= to the role-prefixed tracee_comm= and target_comm=, matching each event's sibling *_pid field and the sched_process_fork task-name convention; label equals field so it works directly as an ftrace filter.
- Record the other party's Landlock domain as a verdict-time scalar ID (tracee_domain=/target_domain=/peer_domain=, 0 when unsandboxed) so a trace consumer can reproduce a relational scope or ptrace verdict; the ID is captured under the RCU read lock or the unix socket lock, and audit records are unchanged.
- Turn the request-type switch default in landlock_trace_denial() into a WARN_ONCE() canary reporting the offending type, now that this patch completes the switch with the ptrace and scope cases (the default is unreachable once every request type is handled).

Changes since v1:
- New patch.

---
 include/trace/events/landlock.h | 195 ++++++++++++++++++++++++++++++++
 security/landlock/log.h         |   9 ++
 security/landlock/task.c        |  52 +++++++--
 security/landlock/trace.c       |  22 ++++
 4 files changed, 271 insertions(+), 7 deletions(-)
include/trace/events/landlock.h +195 -0
index e70dcc9a94b9..94de20fbe908 100644
@@ -13,6 +13,7 @@
 #include <linux/landlock.h>
 #include <linux/trace_seq.h>
 #include <linux/tracepoint.h>
+#include <net/af_unix.h>
 
 struct dentry;
 struct landlock_domain;
@@ -21,6 +22,7 @@ struct landlock_rule;
 struct landlock_ruleset;
 struct path;
 struct sock;
+struct task_struct;
 
 /* Maps a shared _LANDLOCK_*_NAMES entry to a __print_flags() pair. */
 #define _LANDLOCK_NAME_ENTRY(mask, name) { mask, name }
@@ -32,6 +34,18 @@ struct sock;
  * A new tracepoint must uphold them, and an eBPF consumer can rely on
  * them.
  *
+ * Decision context
+ * ~~~~~~~~~~~~~~~~
+ *
+ * A denial event, together with the lifecycle events, exposes the full
+ * set of inputs the verdict consumed, so a consumer that tracked domain
+ * creation (landlock_create_ruleset, landlock_create_domain) can verify
+ * or reproduce the Landlock decision rather than merely observe it
+ * happened.  In who/what/why terms: who is the denying domain (the domain
+ * field, always the subject that enforced the policy, never the current
+ * task), what is the operation and its object, and why is every other
+ * input the verdict weighed.
+ *
  * Lifecycle consistency
  * ~~~~~~~~~~~~~~~~~~~~~~
  *
@@ -100,6 +114,18 @@ struct sock;
  * log flags.  Denial events order their fields as domain, same_exec,
  * logged, then blockers (deny_access events only), then the type-specific
  * object fields, then any variable-length field.
+ *
+ * Relational referents
+ * ~~~~~~~~~~~~~~~~~~~~~
+ *
+ * A scope or ptrace verdict compares two domains, so the other party's
+ * domain is part of the decision context.  It is exposed as a scalar
+ * domain ID (0 when that party is unsandboxed): target_domain (signal),
+ * peer_domain (abstract unix socket), tracee_domain (ptrace).  With both
+ * IDs in the stream, a consumer that tracked domain creation can relate
+ * the two parties without kernel-internal state.  The ID is a scalar
+ * snapshot, not a live domain pointer that could dangle: an optional
+ * relational referent is a scalar (0 sentinel), not a nullable pointer.
  */
 
 #ifdef CREATE_TRACE_POINTS
@@ -705,6 +731,175 @@ TRACE_EVENT(landlock_deny_access_net,
 		__entry->sport, __entry->dport)
 );
 
+/**
+ * landlock_deny_ptrace - Ptrace access denied by a Landlock domain
+ *
+ * @hierarchy: Denying domain's hierarchy node (never NULL); its id is the
+ *             domain field.
+ * @same_exec: Whether the current task entered the denying domain itself.
+ * @logged: The domain's audit-logging decision for this denial.
+ * @tracee_domain_id: The tracee's Landlock domain ID, or 0 if the tracee
+ *                    is unsandboxed.
+ * @tracee: The target task ptrace acted on (never NULL).  tracee_pid is
+ *          the init-namespace TGID (like audit's opid).
+ *
+ * Emitted when a Landlock domain denies a ptrace operation.
+ */
+TRACE_EVENT(landlock_deny_ptrace,
+
+	TP_PROTO(const struct landlock_hierarchy *hierarchy, bool same_exec,
+		 bool logged, u64 tracee_domain_id,
+		 const struct task_struct *tracee),
+
+	TP_ARGS(hierarchy, same_exec, logged, tracee_domain_id, tracee),
+
+	TP_STRUCT__entry(
+		__field(	__u64,		domain_id	)
+		__field(	bool,		same_exec	)
+		__field(	bool,		logged		)
+		__field(	__u64,		tracee_domain_id)
+		__field(	pid_t,		tracee_pid	)
+		__string(	tracee_comm,	tracee->comm	)
+	),
+
+	TP_fast_assign(
+		__entry->domain_id	= hierarchy->id;
+		__entry->same_exec	= same_exec;
+		__entry->logged		= logged;
+		__entry->tracee_domain_id = tracee_domain_id;
+		__entry->tracee_pid	= task_tgid_nr((struct task_struct *)tracee);
+		__assign_str(tracee_comm);
+	),
+
+	TP_printk("domain=%llx same_exec=%d logged=%d tracee_domain=%llx tracee_pid=%d tracee_comm=%s",
+		__entry->domain_id, __entry->same_exec, __entry->logged,
+		__entry->tracee_domain_id, __entry->tracee_pid,
+		__print_untrusted_str(tracee_comm))
+);
+
+/**
+ * landlock_deny_scope_signal - Signal delivery denied by
+ *                               LANDLOCK_SCOPE_SIGNAL
+ *
+ * @hierarchy: Denying domain's hierarchy node (never NULL); its id is the
+ *             domain field.
+ * @same_exec: Whether the current task entered the denying domain itself.
+ * @logged: The domain's audit-logging decision for this denial.
+ * @target_domain_id: The target's Landlock domain ID, or 0 if the target
+ *                    is unsandboxed.
+ * @target: The task the signal was aimed at (never NULL).  target_pid is
+ *          the init-namespace TGID (like audit's opid).
+ *
+ * Emitted when a Landlock domain denies signal delivery to a scoped-out
+ * target.
+ */
+TRACE_EVENT(landlock_deny_scope_signal,
+
+	TP_PROTO(const struct landlock_hierarchy *hierarchy, bool same_exec,
+		 bool logged, u64 target_domain_id,
+		 const struct task_struct *target),
+
+	TP_ARGS(hierarchy, same_exec, logged, target_domain_id, target),
+
+	TP_STRUCT__entry(
+		__field(	__u64,		domain_id	)
+		__field(	bool,		same_exec	)
+		__field(	bool,		logged		)
+		__field(	__u64,		target_domain_id)
+		__field(	pid_t,		target_pid	)
+		__string(	target_comm,	target->comm	)
+	),
+
+	TP_fast_assign(
+		__entry->domain_id	= hierarchy->id;
+		__entry->same_exec	= same_exec;
+		__entry->logged		= logged;
+		__entry->target_domain_id = target_domain_id;
+		__entry->target_pid	= task_tgid_nr((struct task_struct *)target);
+		__assign_str(target_comm);
+	),
+
+	TP_printk("domain=%llx same_exec=%d logged=%d target_domain=%llx target_pid=%d target_comm=%s",
+		__entry->domain_id, __entry->same_exec, __entry->logged,
+		__entry->target_domain_id, __entry->target_pid,
+		__print_untrusted_str(target_comm))
+);
+
+/**
+ * landlock_deny_scope_abstract_unix_socket - Abstract unix socket access
+ *     denied by LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET
+ *
+ * @hierarchy: Denying domain's hierarchy node (never NULL); its id is the
+ *             domain field.
+ * @same_exec: Whether the current task entered the denying domain itself.
+ * @logged: The domain's audit-logging decision for this denial.
+ * @peer_domain_id: The peer's Landlock domain ID, or 0 if the peer is
+ *                  unsandboxed.
+ * @peer: Peer socket (never NULL).  peer_pid is best-effort: it is 0 for
+ *        a datagram peer (no SO_PEERCRED), so sun_path is the reliable
+ *        peer identifier.
+ *
+ * Emitted when a Landlock domain denies access to a scoped-out abstract
+ * unix socket.
+ */
+TRACE_EVENT(landlock_deny_scope_abstract_unix_socket,
+
+	TP_PROTO(const struct landlock_hierarchy *hierarchy, bool same_exec,
+		 bool logged, u64 peer_domain_id, const struct sock *peer),
+
+	TP_ARGS(hierarchy, same_exec, logged, peer_domain_id, peer),
+
+	TP_STRUCT__entry(
+		__field(	__u64,		domain_id	)
+		__field(	bool,		same_exec	)
+		__field(	bool,		logged		)
+		__field(	__u64,		peer_domain_id	)
+		__field(	pid_t,		peer_pid	)
+		/*
+		 * Abstract socket names are untrusted binary data from
+		 * user space.  Use __string_len because abstract names
+		 * are not NUL-terminated; their length is determined by
+		 * addr->len.  unix_sk(peer)->addr is stable here because
+		 * the caller (hook_unix_stream_connect or
+		 * hook_unix_may_send) holds unix_state_lock(peer).
+		 */
+		__string_len(	sun_path,
+				unix_sk(peer)->addr ?
+					unix_sk(peer)->addr->name->sun_path + 1 :
+					"",
+				unix_sk(peer)->addr ?
+					unix_sk(peer)->addr->len -
+						offsetof(struct sockaddr_un,
+							 sun_path) - 1 :
+					0)
+	),
+
+	TP_fast_assign(
+		struct pid *peer_pid;
+
+		lockdep_assert_held(&unix_sk(peer)->lock);
+		__entry->domain_id	= hierarchy->id;
+		__entry->same_exec	= same_exec;
+		__entry->logged		= logged;
+		__entry->peer_domain_id	= peer_domain_id;
+		/*
+		 * Best-effort (0 for a datagram peer).  sk_peer_pid is
+		 * canonically guarded by sk->sk_peer_lock, but the target
+		 * peer's peercred is set once and not updated concurrently in
+		 * these hooks, so this READ_ONCE() is safe; sun_path is the
+		 * reliable identifier.
+		 */
+		peer_pid		= READ_ONCE(peer->sk_peer_pid);
+		__entry->peer_pid	= peer_pid ? pid_nr(peer_pid) : 0;
+		__assign_str(sun_path);
+	),
+
+	TP_printk("domain=%llx same_exec=%d logged=%d peer_domain=%llx peer_pid=%d sun_path=%s",
+		__entry->domain_id, __entry->same_exec, __entry->logged,
+		__entry->peer_domain_id, __entry->peer_pid,
+		__print_untrusted_str(sun_path))
+);
+
 #undef _LANDLOCK_NAME_ENTRY
 
 #endif /* _TRACE_LANDLOCK_H */
security/landlock/log.h +9 -0
index 25afc17cf055..e0a6e44f3ddd 100644
@@ -3,6 +3,7 @@
  * Landlock - Log helpers
  *
  * Copyright © 2023-2025 Microsoft Corporation
+ * Copyright © 2026 Cloudflare, Inc.
  */
 
 #ifndef _SECURITY_LANDLOCK_LOG_H
@@ -50,6 +51,14 @@ struct landlock_request {
 	const access_mask_t all_existing_optional_access;
 	deny_masks_t deny_masks;
 	optional_access_t quiet_optional_accesses;
+
+	/*
+	 * Other-party domain ID for a relational (scope/ptrace) denial, or 0 if
+	 * that party is unsandboxed.  An ID, not a pointer: the other task can
+	 * replace its credential and free the domain it referenced.  Trace path
+	 * only; audit ignores it.
+	 */
+	u64 other_domain_id;
 };
 
 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
security/landlock/task.c +45 -7

174 lines not on this page · raw message

security/landlock/trace.c +22 -0
index 4c4229d4ffdf..2ea7aac8d75d 100644
@@ -157,7 +157,29 @@ void landlock_trace_denial(
 				ntohs(request->audit.u.net->sport),
 				ntohs(request->audit.u.net->dport));
 		break;
+	case LANDLOCK_REQUEST_PTRACE:
+		if (trace_landlock_deny_ptrace_enabled())
+			trace_landlock_deny_ptrace(youngest_denied, same_exec,
+						   logged,
+						   request->other_domain_id,
+						   request->audit.u.tsk);
+		break;
+	case LANDLOCK_REQUEST_SCOPE_SIGNAL:
+		if (trace_landlock_deny_scope_signal_enabled())
+			trace_landlock_deny_scope_signal(
+				youngest_denied, same_exec, logged,
+				request->other_domain_id, request->audit.u.tsk);
+		break;
+	case LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET:
+		if (trace_landlock_deny_scope_abstract_unix_socket_enabled())
+			trace_landlock_deny_scope_abstract_unix_socket(
+				youngest_denied, same_exec, logged,
+				request->other_domain_id,
+				request->audit.u.net->sk);
+		break;
 	default:
+		WARN_ONCE(1, "Unhandled Landlock request type %d",
+			  request->type);
 		break;
 	}
 }
Signature · 1 line
2.54.0
author maintainer
#18 lore raw

PATCH v3 15/20 selftests/landlock: Add trace event test infrastructure and tests

In reply to Mickaël Salaün

Add tracefs test infrastructure in trace.h: helpers for mounting tracefs, enabling/disabling events, reading the trace buffer, counting regex matches, and extracting field values, plus per-event regex patterns. The patterns are anchored with ^ and $, verify every TP_printk field, and use no unescaped dot characters; TRACE_PREFIX matches the ftrace line format with either the expected task name (truncated to TASK_COMM_LEN - 1) or "<...>" for an evicted comm cache entry.

Add trace_test.c with the trace fixture (setup enables all available events with a PID filter, teardown disables and clears) and the lifecycle, API, denial-field, and log-flag tests. Extend the existing true helper to open its working directory before exiting, triggering a read_dir denial inside a sandbox, so the exec-based tests can verify same_exec and the logged decision across an exec. Move regex_escape() from audit.h to common.h for shared use by the audit and trace tests.

Enable CONFIG_ENABLE_DEFAULT_TRACERS alongside CONFIG_FTRACE in the selftest config: CONFIG_FTRACE alone only enables the tracer menu without activating any tracer, while CONFIG_ENABLE_DEFAULT_TRACERS selects TRACING (and thus TRACEPOINTS and event tracing) without depending on architecture-specific syscall tracepoints. When CONFIG_FTRACE is disabled it cannot be set, so TRACEPOINTS is correctly disabled too.

Cc Günther Noack <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Renamed the restrict_self trace matchers (REGEX_RESTRICT_SELF, TRACEFS_RESTRICT_SELF_ENABLE) and the restrict_self tests to create_domain.
- Trim the intentionally-elided-coverage comment: drop the check_rule_net and ptrace-TRACEME notes (both now have dedicated trace tests) and the stale claim that TRACEME routes through hook_ptrace_access_check.
- Updated add_rule_net_fields test expected access mask to include the new UDP access bits (LANDLOCK_ACCESS_NET_BIND_UDP, LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP).
- Assert the symbolic access-right names in the trace field tests instead of hex masks.
- Switched the selftest config from CONFIG_FTRACE_SYSCALLS to CONFIG_ENABLE_DEFAULT_TRACERS, which selects TRACING without an architecture-specific syscall-tracepoint dependency.
- Updated the denial field tests to assert the single logged field instead of log_same_exec and log_new_exec; log_flags_subdomains_off now checks logged==0 (the case the raw flags could not express).
- Follow the check_rule_fs printk label rename request= to access_request= (the trace-only field and its label now share one name): define REGEX_CHECK_RULE_FS with the final access_request= label, since restrict_self already matches check_rule_fs events here and the kernel emits the renamed label.
- Define REGEX_CHECK_RULE_NET with the final access_request= label (same check_rule request= to access_request= rename), so the shared matcher carries its final form from the patch that introduces trace.h rather than being updated in a later test patch.
- Define REGEX_DENY_PTRACE and REGEX_DENY_SCOPE_SIGNAL with the final role-prefixed tracee_comm= and target_comm= labels (deny_ptrace and deny_scope_signal printk label rename comm= to *_comm=, each label now matching its sibling *_pid field), so both matchers carry their final form from the patch that introduces trace.h; the per-layer domain fields and the tests that consume the labels are added later.
- Reuse a shared scope-based ruleset helper (build_enforce_ruleset) in the trace tests: define it here and call it from create_domain_nested and create_domain_invalid, which only need a domain.

Changes since v1:
- New patch.

---
 tools/testing/selftests/landlock/audit.h      |   35 -
 tools/testing/selftests/landlock/common.h     |   47 +
 tools/testing/selftests/landlock/config       |    2 +
 tools/testing/selftests/landlock/trace.h      |  634 ++++++++++
 tools/testing/selftests/landlock/trace_test.c | 1101 +++++++++++++++++
 tools/testing/selftests/landlock/true.c       |   10 +
 6 files changed, 1794 insertions(+), 35 deletions(-)
 create mode 100644 tools/testing/selftests/landlock/trace.h
 create mode 100644 tools/testing/selftests/landlock/trace_test.c
tools/testing/selftests/landlock/audit.h +0 -35
index f45fdef35681..d428ce802f49 100644
@@ -214,41 +214,6 @@ static int audit_set_status(int fd, __u32 key, __u32 val)
 	return audit_request(fd, &msg, NULL);
 }
 
-/* Returns a pointer to the last filled character of @dst, which is `\0`.  */
-static __maybe_unused char *regex_escape(const char *const src, char *dst,
-					 size_t dst_size)
-{
-	char *d = dst;
-
-	for (const char *s = src; *s; s++) {
-		switch (*s) {
-		case '$':
-		case '*':
-		case '.':
-		case '[':
-		case '\\':
-		case ']':
-		case '^':
-			if (d >= dst + dst_size - 2)
-				return (char *)-ENOMEM;
-
-			*d++ = '\\';
-			*d++ = *s;
-			break;
-		default:
-			if (d >= dst + dst_size - 1)
-				return (char *)-ENOMEM;
-
-			*d++ = *s;
-		}
-	}
-	if (d >= dst + dst_size - 1)
-		return (char *)-ENOMEM;
-
-	*d = '\0';
-	return d;
-}
-
 /*
  * @domain_id: The domain ID extracted from the audit message (if the first part
  * of @pattern is REGEX_LANDLOCK_PREFIX).  It is set to 0 if the domain ID is
tools/testing/selftests/landlock/common.h +47 -0

50 lines not on this page · raw message

tools/testing/selftests/landlock/config +2 -0
index 8fe9b461b1fd..d86321936fd8 100644
@@ -2,6 +2,8 @@ CONFIG_AF_UNIX_OOB=y
 CONFIG_AUDIT=y
 CONFIG_CGROUPS=y
 CONFIG_CGROUP_SCHED=y
+CONFIG_ENABLE_DEFAULT_TRACERS=y
+CONFIG_FTRACE=y
 CONFIG_INET=y
 CONFIG_IPV6=y
 CONFIG_KEYS=y
tools/testing/selftests/landlock/trace.h new file +634 -0

634 lines not on this page · raw message

tools/testing/selftests/landlock/trace_test.c new file +1101 -0

1,101 lines not on this page · raw message

tools/testing/selftests/landlock/true.c +10 -0
index 3f9ccbf52783..1e39b664512d 100644
@@ -1,5 +1,15 @@
 // SPDX-License-Identifier: GPL-2.0
+/*
+ * Minimal helper for Landlock selftests.  Opens its own working directory
+ * before exiting, which may trigger access denials depending on the sandbox
+ * configuration.
+ */
+
+#include <fcntl.h>
+#include <unistd.h>
+
 int main(void)
 {
+	close(open(".", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
 	return 0;
 }
Signature · 1 line
2.54.0
author maintainer
#19 lore raw

PATCH v3 16/20 selftests/landlock: Add filesystem tracepoint tests

In reply to Mickaël Salaün

Add filesystem-specific trace tests in a dedicated file, following the audit-test pattern of living alongside each subsystem's functional tests.

trace_fs_test.c verifies that the add_rule_fs, check_rule_fs, and deny_access_fs events fire with the correct fields on matching rules and denied accesses, that check_rule_fs does not fire for unhandled access types, and that no event fires without a sandbox. A denial covered by a quiet rule still emits a deny_access_fs event but with logged=0, the same suppression verdict audit applies; because that verdict must not depend on CONFIG_AUDIT, the test also runs under a tracepoints-only build.

Add trace_layout1 fixture tests in fs_test.c that reuse the layout1 hierarchy to verify the per-layer grants field: field values, multi-rule pathwalk short-circuit, request intersection, the optional truncate right surfacing in the request and grants, and an empty grants set from a rule that grants none of the requested rights.

Cc Günther Noack <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Assert the symbolic access-right names (e.g. read_dir) in the FS trace grants field instead of hex masks, including the optional truncate right and an empty grants set from a matching rule that grants nothing requested.
- Add deny_access_fs_quiet, asserting a quieted filesystem denial emits landlock_deny_access_fs with logged=0, and that quiet suppresses only the logged verdict by anchoring the surviving domain and blockers fields.
- Follow the check_rule_fs printk label rename request= to access_request= (the trace-only field and its label now share one name): parse the access_request field in the FS check_rule assertions (the REGEX_CHECK_RULE_FS matcher carries the renamed label from its first use in the trace lifecycle test).

Changes since v1:
- New patch.

---
 tools/testing/selftests/landlock/fs_test.c    | 483 +++++++++++++++++
 .../selftests/landlock/trace_fs_test.c        | 496 ++++++++++++++++++
 2 files changed, 979 insertions(+)
 create mode 100644 tools/testing/selftests/landlock/trace_fs_test.c
tools/testing/selftests/landlock/fs_test.c +483 -0
index 86e08aa6e0a7..b22df68a2923 100644
@@ -44,6 +44,9 @@
 
 #include "audit.h"
 #include "common.h"
+#include "trace.h"
+
+#define TRACE_TASK "fs_test"
 
 #ifndef renameat2
 int renameat2(int olddirfd, const char *oldpath, int newdirfd,
@@ -10189,4 +10192,484 @@ TEST_F(audit_quiet_rename, quiet_behind_mountpoint_disconnected)
 	ASSERT_EQ(0, records.access);
 }
 
+/* clang-format off */
+FIXTURE(trace_layout1) {
+	/* clang-format on */
+	int tracefs_ok;
+};
+
+FIXTURE_SETUP(trace_layout1)
+{
+	struct stat st;
+
+	/*
+	 * Check tracefs availability before creating the layout, following the
+	 * layout3_fs pattern: skip before any layout creation to avoid leaving
+	 * stale TMP_DIR on skip.
+	 */
+	if (stat(TRACEFS_LANDLOCK_DIR, &st)) {
+		self->tracefs_ok = 0;
+		SKIP(return, "tracefs not available");
+	}
+	self->tracefs_ok = 1;
+
+	/* Isolate tracefs state (PID filter, event enables). */
+	set_cap(_metadata, CAP_SYS_ADMIN);
+	ASSERT_EQ(0, unshare(CLONE_NEWNS));
+	ASSERT_EQ(0, mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL));
+	clear_cap(_metadata, CAP_SYS_ADMIN);
+
+	prepare_layout(_metadata);
+	create_layout1(_metadata);
+
+	set_cap(_metadata, CAP_DAC_OVERRIDE);
+	ASSERT_EQ(0, tracefs_fixture_setup());
+	ASSERT_EQ(0, tracefs_enable_event(TRACEFS_CHECK_RULE_FS_ENABLE, true));
+	ASSERT_EQ(0, tracefs_clear());
+	ASSERT_EQ(0, tracefs_set_pid_filter(getpid()));
+	clear_cap(_metadata, CAP_DAC_OVERRIDE);
+}
+
+FIXTURE_TEARDOWN_PARENT(trace_layout1)
+{
+	if (!self->tracefs_ok)
+		return;
+
+	set_cap(_metadata, CAP_DAC_OVERRIDE);
+	tracefs_enable_event(TRACEFS_CHECK_RULE_FS_ENABLE, false);
+	tracefs_clear_pid_filter();
+	tracefs_fixture_teardown();
+	clear_cap(_metadata, CAP_DAC_OVERRIDE);
+
+	remove_layout1(_metadata);
+	cleanup_layout(_metadata);
+}
+
+/*
+ * Verifies that check_rule_fs events include correct field values: domain, dev,
+ * ino, access_request, and grants.  All values are verified against stat() of
+ * the rule path on a deterministic tmpfs layout.
+ */
+TEST_F(trace_layout1, check_rule_fs_fields)
+{
+	struct stat dir_stat;
+	char expected_dev[32];
+	char expected_ino[32];
+	char *buf;
+	char field[64];
+
+	if (!self->tracefs_ok)
+		SKIP(return, "tracefs not available");
+
+	ASSERT_EQ(0, stat(dir_s1d1, &dir_stat));
+	snprintf(expected_dev, sizeof(expected_dev), "%u:%u",
+		 major(dir_stat.st_dev), minor(dir_stat.st_dev));
+	snprintf(expected_ino, sizeof(expected_ino), "%lu", dir_stat.st_ino);
+
+	set_cap(_metadata, CAP_DAC_OVERRIDE);
+	ASSERT_EQ(0, tracefs_clear());
+	clear_cap(_metadata, CAP_DAC_OVERRIDE);
+
+	sandbox_child_fs_access(_metadata, dir_s1d1,
+				LANDLOCK_ACCESS_FS_READ_DIR,
+				LANDLOCK_ACCESS_FS_READ_DIR, dir_s1d1);
+
+	set_cap(_metadata, CAP_DAC_OVERRIDE);
+	buf = tracefs_read_trace();
+	clear_cap(_metadata, CAP_DAC_OVERRIDE);
+	ASSERT_NE(NULL, buf);
+
+	EXPECT_EQ(1,
+		  tracefs_count_matches(buf, REGEX_CHECK_RULE_FS(TRACE_TASK)))
+	{
+		TH_LOG("Expected 1 check_rule_fs event\n%s", buf);
+	}
+
+	ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CHECK_RULE_FS(TRACE_TASK),
+					   "dev", field, sizeof(field)));
+	EXPECT_STREQ(expected_dev, field)
+	{
+		TH_LOG("Expected dev=%s, got %s", expected_dev, field);
+	}
+
+	ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CHECK_RULE_FS(TRACE_TASK),
+					   "ino", field, sizeof(field)));
+	EXPECT_STREQ(expected_ino, field)
+	{
+		TH_LOG("Expected ino=%s, got %s", expected_ino, field);
+	}
+
+	ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CHECK_RULE_FS(TRACE_TASK),
+					   "access_request", field,
+					   sizeof(field)));
+	EXPECT_STREQ("read_dir", field)
+	{
+		TH_LOG("Expected access_request=read_dir, got %s", field);
+	}
+
+	/*
+	 * The domain handles only READ_DIR, so the rule carries the
+	 * unhandled-rights padding; intersecting with the request leaves just
+	 * the requested read_dir (no padding, no hex).
+	 */
+	ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CHECK_RULE_FS(TRACE_TASK),
+					   "grants", field, sizeof(field)));
+	EXPECT_STREQ("{read_dir}", field)
+	{
+		TH_LOG("Expected grants={read_dir}, got %s", field);
+	}
+
+	free(buf);
+}
+
+/*
+ * Verifies check_rule_fs behavior with multiple rules.  With rules at s1d1 and
+ * s1d2 (a child of s1d1), accessing s1d2 produces only 1 event because the
+ * pathwalk short-circuits after the first rule fully unmasks the single layer.
+ */
+TEST_F(trace_layout1, check_rule_fs_multiple_rules)
+{
+	pid_t pid;
+	int status;
+	char *buf;
+	int count;
+
+	if (!self->tracefs_ok)
+		SKIP(return, "tracefs not available");
+
+	set_cap(_metadata, CAP_DAC_OVERRIDE);
+	ASSERT_EQ(0, tracefs_clear());
+	clear_cap(_metadata, CAP_DAC_OVERRIDE);
+
+	pid = fork();
+	ASSERT_LE(0, pid);
+
+	if (pid == 0) {
+		struct landlock_ruleset_attr attr = {
+			.handled_access_fs = LANDLOCK_ACCESS_FS_READ_DIR,
+		};
+		struct landlock_path_beneath_attr path_beneath = {
+			.allowed_access = LANDLOCK_ACCESS_FS_READ_DIR,
+		};
+		int ruleset_fd, fd;
+
+		ruleset_fd = landlock_create_ruleset(&attr, sizeof(attr), 0);
+		if (ruleset_fd < 0)
+			_exit(1);
+
+		path_beneath.parent_fd =
+			open(dir_s1d1, O_PATH | O_DIRECTORY | O_CLOEXEC);
+		if (path_beneath.parent_fd < 0)
+			_exit(1);
+		if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
+				      &path_beneath, 0))
+			_exit(1);
+		close(path_beneath.parent_fd);
+
+		path_beneath.parent_fd =
+			open(dir_s1d2, O_PATH | O_DIRECTORY | O_CLOEXEC);
+		if (path_beneath.parent_fd < 0)
+			_exit(1);
+		if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
+				      &path_beneath, 0))
+			_exit(1);
+		close(path_beneath.parent_fd);
+
+		prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+		if (landlock_restrict_self(ruleset_fd, 0))
+			_exit(1);
+		close(ruleset_fd);
+
+		fd = open(dir_s1d2, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+		if (fd >= 0)
+			close(fd);
+		_exit(0);
+	}
+
+	ASSERT_EQ(pid, waitpid(pid, &status, 0));
+	ASSERT_TRUE(WIFEXITED(status));
+	EXPECT_EQ(0, WEXITSTATUS(status));
+
+	set_cap(_metadata, CAP_DAC_OVERRIDE);
+	buf = tracefs_read_trace();
+	clear_cap(_metadata, CAP_DAC_OVERRIDE);
+	ASSERT_NE(NULL, buf);
+
+	/*
+	 * Only 1 check_rule_fs event: the rule on dir_s1d2 fully unmasked the
+	 * single layer, so the pathwalk short-circuits before reaching the
+	 * dir_s1d1 rule.
+	 */
+	count = tracefs_count_matches(buf, REGEX_CHECK_RULE_FS(TRACE_TASK));
+	EXPECT_EQ(1, count)
+	{
+		TH_LOG("Expected 1 check_rule_fs event, got %d\n%s", count,
+		       buf);
+	}
+
+	free(buf);
+}
+
+/*
+ * Verifies the grants array is intersected with the request: a handled,
+ * granted, but unrequested right (execute) is filtered out, leaving only the
+ * requested read_dir.
+ */
+TEST_F(trace_layout1, check_rule_fs_request_subset)
+{
+	char *buf;
+	char field[64];
+
+	if (!self->tracefs_ok)
+		SKIP(return, "tracefs not available");
+
+	set_cap(_metadata, CAP_DAC_OVERRIDE);
+	ASSERT_EQ(0, tracefs_clear());
+	clear_cap(_metadata, CAP_DAC_OVERRIDE);
+
+	/*
+	 * Handle and grant READ_DIR|EXECUTE; the open only requests read_dir.
+	 */
+	sandbox_child_fs_access(
+		_metadata, dir_s1d1,
+		LANDLOCK_ACCESS_FS_READ_DIR | LANDLOCK_ACCESS_FS_EXECUTE,
+		LANDLOCK_ACCESS_FS_READ_DIR | LANDLOCK_ACCESS_FS_EXECUTE,
+		dir_s1d1);
+
+	set_cap(_metadata, CAP_DAC_OVERRIDE);
+	buf = tracefs_read_trace();
+	clear_cap(_metadata, CAP_DAC_OVERRIDE);
+	ASSERT_NE(NULL, buf);
+
+	ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CHECK_RULE_FS(TRACE_TASK),
+					   "access_request", field,
+					   sizeof(field)));
+	EXPECT_STREQ("read_dir", field);
+
+	ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CHECK_RULE_FS(TRACE_TASK),
+					   "grants", field, sizeof(field)));
+	EXPECT_STREQ("{read_dir}", field);
+
+	free(buf);
+}
+
+/*
+ * Verifies that the optional TRUNCATE access right, which hook_file_open()
+ * speculatively evaluates on every open, appears in the access_request= and
+ * grants= fields.  Opening file1_s1d1 read-only needs only read_file, but the
+ * open hook also evaluates truncate; the domain handles and the rule grants
+ * both, so the event reports access_request=read_file|truncate and
+ * grants={read_file|truncate}, and the open is allowed.
+ */
+TEST_F(trace_layout1, check_rule_fs_optional_access)
+{
+	pid_t pid;
+	int status;
+	char *buf;
+	char field[64];
+	int count;
+
+	if (!self->tracefs_ok)
+		SKIP(return, "tracefs not available");
+
+	set_cap(_metadata, CAP_DAC_OVERRIDE);
+	ASSERT_EQ(0, tracefs_clear());
+	clear_cap(_metadata, CAP_DAC_OVERRIDE);
+
+	pid = fork();
+	ASSERT_LE(0, pid);
+
+	if (pid == 0) {
+		struct landlock_ruleset_attr attr = {
+			.handled_access_fs = LANDLOCK_ACCESS_FS_READ_FILE |
+					     LANDLOCK_ACCESS_FS_TRUNCATE,
+		};
+		struct landlock_path_beneath_attr path_beneath = {
+			.allowed_access = LANDLOCK_ACCESS_FS_READ_FILE |
+					  LANDLOCK_ACCESS_FS_TRUNCATE,
+		};
+		int ruleset_fd, fd;
+
+		ruleset_fd = landlock_create_ruleset(&attr, sizeof(attr), 0);
+		if (ruleset_fd < 0)
+			_exit(1);
+
+		path_beneath.parent_fd =
+			open(dir_s1d1, O_PATH | O_DIRECTORY | O_CLOEXEC);
+		if (path_beneath.parent_fd < 0)
+			_exit(1);
+		if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
+				      &path_beneath, 0))
+			_exit(1);
+		close(path_beneath.parent_fd);
+
+		prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+		if (landlock_restrict_self(ruleset_fd, 0))
+			_exit(1);
+		close(ruleset_fd);
+
+		/* Read-only open needs only read_file; truncate is optional. */
+		fd = open(file1_s1d1, O_RDONLY | O_CLOEXEC);
+		if (fd < 0)
+			_exit(1);
+		close(fd);
+		_exit(0);
+	}
+
+	ASSERT_EQ(pid, waitpid(pid, &status, 0));
+	ASSERT_TRUE(WIFEXITED(status));
+	/* The open is allowed: the required read_file is granted. */
+	EXPECT_EQ(0, WEXITSTATUS(status));
+
+	set_cap(_metadata, CAP_DAC_OVERRIDE);
+	buf = tracefs_read_trace();
+	clear_cap(_metadata, CAP_DAC_OVERRIDE);
+	ASSERT_NE(NULL, buf);
+
+	/* The rule at dir_s1d1 matches when opening file1_s1d1. */
+	count = tracefs_count_matches(buf, REGEX_CHECK_RULE_FS(TRACE_TASK));
+	EXPECT_EQ(1, count)
+	{
+		TH_LOG("Expected 1 check_rule_fs event, got %d\n%s", count,
+		       buf);
+	}
+
+	/* The open hook adds the optional truncate to the request. */
+	ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CHECK_RULE_FS(TRACE_TASK),
+					   "access_request", field,
+					   sizeof(field)));
+	EXPECT_STREQ("read_file|truncate", field);
+
+	/* The rule grants both, so truncate appears in the grants array. */
+	ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CHECK_RULE_FS(TRACE_TASK),
+					   "grants", field, sizeof(field)));
+	EXPECT_STREQ("{read_file|truncate}", field);
+
+	free(buf);
+}
+
+/*
+ * Verifies that check_rule_fs fires for a rule that matches the inode even when
+ * it grants none of the requested rights, so the grants set is empty.  Landlock
+ * cannot know a rule ignores the request before reading it, so the event is
+ * still emitted (grants={}), which lets a tracer see that the rule matched.
+ * The domain handles READ_DIR|EXECUTE, dir_s1d2 grants only EXECUTE and its
+ * parent dir_s1d1 grants only READ_DIR.  Reading dir_s1d2 (requesting read_dir)
+ * first matches the dir_s1d2 rule, which grants nothing requested (grants={});
+ * walking up to dir_s1d1 then grants read_dir (grants={read_dir}) and allows
+ * the access.
+ */
+TEST_F(trace_layout1, check_rule_fs_empty_grant)
+{
+	pid_t pid;
+	int status;
+	char *buf;
+	int count;
+
+	if (!self->tracefs_ok)
+		SKIP(return, "tracefs not available");
+
+	set_cap(_metadata, CAP_DAC_OVERRIDE);
+	ASSERT_EQ(0, tracefs_clear());
+	clear_cap(_metadata, CAP_DAC_OVERRIDE);
+
+	pid = fork();
+	ASSERT_LE(0, pid);
+
+	if (pid == 0) {
+		struct landlock_ruleset_attr attr = {
+			.handled_access_fs = LANDLOCK_ACCESS_FS_READ_DIR |
+					     LANDLOCK_ACCESS_FS_EXECUTE,
+		};
+		struct landlock_path_beneath_attr path_beneath = {};
+		int ruleset_fd, fd;
+
+		ruleset_fd = landlock_create_ruleset(&attr, sizeof(attr), 0);
+		if (ruleset_fd < 0)
+			_exit(1);
+
+		/* Parent dir_s1d1 grants only READ_DIR. */
+		path_beneath.allowed_access = LANDLOCK_ACCESS_FS_READ_DIR;
+		path_beneath.parent_fd =
+			open(dir_s1d1, O_PATH | O_DIRECTORY | O_CLOEXEC);
+		if (path_beneath.parent_fd < 0)
+			_exit(1);
+		if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
+				      &path_beneath, 0))
+			_exit(1);
+		close(path_beneath.parent_fd);
+
+		/* Child dir_s1d2 grants only EXECUTE. */
+		path_beneath.allowed_access = LANDLOCK_ACCESS_FS_EXECUTE;
+		path_beneath.parent_fd =
+			open(dir_s1d2, O_PATH | O_DIRECTORY | O_CLOEXEC);
+		if (path_beneath.parent_fd < 0)
+			_exit(1);
+		if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
+				      &path_beneath, 0))
+			_exit(1);
+		close(path_beneath.parent_fd);
+
+		prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+		if (landlock_restrict_self(ruleset_fd, 0))
+			_exit(1);
+		close(ruleset_fd);
+
+		fd = open(dir_s1d2, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+		if (fd < 0)
+			_exit(1);
+		close(fd);
+		_exit(0);
+	}
+
+	ASSERT_EQ(pid, waitpid(pid, &status, 0));
+	ASSERT_TRUE(WIFEXITED(status));
+	EXPECT_EQ(0, WEXITSTATUS(status));
+
+	set_cap(_metadata, CAP_DAC_OVERRIDE);
+	buf = tracefs_read_trace();
+	clear_cap(_metadata, CAP_DAC_OVERRIDE);
+	ASSERT_NE(NULL, buf);
+
+	/*
+	 * dir_s1d2 (grants nothing requested) then dir_s1d1 (grants read_dir).
+	 */
+	count = tracefs_count_matches(buf, REGEX_CHECK_RULE_FS(TRACE_TASK));
+	EXPECT_EQ(2, count)
+	{
+		TH_LOG("Expected 2 check_rule_fs events, got %d\n%s", count,
+		       buf);
+	}
+
+	/* The dir_s1d2 rule matches the inode but grants none of read_dir. */
+	EXPECT_EQ(
+		1,
+		tracefs_count_matches(
+			buf,
+			TRACE_PREFIX(
+				TRACE_TASK) "landlock_check_rule_fs: domain=[0-9a-f]\\+ "
+					    "access_request=read_dir "
+					    "dev=[0-9]\\+:[0-9]\\+ ino=[0-9]\\+ "
+					    "grants={}$"))
+	{
+		TH_LOG("Expected a grants={} event\n%s", buf);
+	}
+
+	/* Walking up to dir_s1d1 grants the requested read_dir. */
+	EXPECT_EQ(
+		1,
+		tracefs_count_matches(
+			buf,
+			TRACE_PREFIX(
+				TRACE_TASK) "landlock_check_rule_fs: domain=[0-9a-f]\\+ "
+					    "access_request=read_dir "
+					    "dev=[0-9]\\+:[0-9]\\+ ino=[0-9]\\+ "
+					    "grants={read_dir}$"))
+	{
+		TH_LOG("Expected a grants={read_dir} event\n%s", buf);
+	}
+
+	free(buf);
+}
+
 TEST_HARNESS_MAIN
tools/testing/selftests/landlock/trace_fs_test.c new file +496 -0

496 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#20 lore raw

PATCH v3 17/20 selftests/landlock: Add network tracepoint tests

In reply to Mickaël Salaün

Add network-specific trace tests, co-located with the existing audit fixture so each subsystem's functional, audit, and trace tests live together.

Parameterized fixtures verify the landlock_deny_access_net event: a bind or connect denied outside the ruleset emits exactly one event with the expected sport/dport, an allowed bind or connect emits none, and the unsandboxed baseline emits none. A separate fixture verifies the landlock_check_rule_net event on an allowed bind, anchoring its domain, access_request, port, and grants to exact values; only check_rule_fs had a dedicated field test before.

Port fields are read in host endianness, matching the landlock_net_port_attr.port UAPI convention, so the decimal comparisons also catch byte-order regressions in the tracepoint plumbing. IPv6 trace tests are intentionally elided: IPv6 hook dispatch shares the current_check_access_socket() path with IPv4 (covered by the audit tests), and the trace fields do not depend on address family.

Cc Günther Noack <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Anchor the shared denial fields (non-zero domain, same_exec, logged, non-empty blockers) in the deny_access_net field tests via a common helper, so they prove the whole event stays populated rather than only checking sport/dport.
- Add setup_loopback() to the trace_net and trace_net_connect fixtures (network-namespace isolation matching the rest of net_test.c) so a bound loopback port cannot collide with a concurrent test.
- Tighten the denied-event count assertions from EXPECT_LE to EXPECT_EQ (a single denied operation on a single-layer domain emits exactly one event), matching the scope and ptrace trace tests.
- Add a check_rule_net field test (check_rule_net_fields): an allowed bind matching a net-port rule emits one landlock_check_rule_net event with domain, access_request, port, and grants pinned to exact values; only check_rule_fs had a dedicated field test before.

Changes since v1:
- New patch.

---
 tools/testing/selftests/landlock/net_test.c | 747 +++++++++++++++++++-
 1 file changed, 746 insertions(+), 1 deletion(-)
tools/testing/selftests/landlock/net_test.c +746 -1
index be2eb88092fb..578bb0a64f11 100644
@@ -10,11 +10,12 @@
 #include <arpa/inet.h>
 #include <errno.h>
 #include <fcntl.h>
-#include <linux/landlock.h>
 #include <linux/in.h>
+#include <linux/landlock.h>
 #include <sched.h>
 #include <stdint.h>
 #include <string.h>
+#include <sys/mount.h>
 #include <sys/prctl.h>
 #include <sys/socket.h>
 #include <sys/syscall.h>
@@ -22,6 +23,9 @@
 
 #include "audit.h"
 #include "common.h"
+#include "trace.h"
+
+#define TRACE_TASK "net_test"
 
 const short sock_port_start = (1 << 10);
 
@@ -3285,4 +3289,745 @@ TEST_F(audit, sendmsg)
 	EXPECT_EQ(0, close(sock_fd));
 }
 
+/* Trace tests */
+
+/* clang-format off */
+FIXTURE(trace_net) {
+	/* clang-format on */
+	int tracefs_ok;
+};
+
+FIXTURE_SETUP(trace_net)
+{
+	int ret;
+
+	/* Isolate the network namespace so the bound port cannot collide. */
+	setup_loopback(_metadata);
+
+	set_cap(_metadata, CAP_SYS_ADMIN);
+	ASSERT_EQ(0, unshare(CLONE_NEWNS));
+	ASSERT_EQ(0, mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL));
+
+	ret = tracefs_fixture_setup();
+	if (ret) {
+		clear_cap(_metadata, CAP_SYS_ADMIN);
+		self->tracefs_ok = 0;
+		SKIP(return, "tracefs not available");
+	}
+	self->tracefs_ok = 1;
+
+	ASSERT_EQ(0,
+		  tracefs_enable_event(TRACEFS_DENY_ACCESS_NET_ENABLE, true));
+	ASSERT_EQ(0, tracefs_clear());
+	clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+FIXTURE_TEARDOWN(trace_net)
+{
+	if (!self->tracefs_ok)
+		return;
+
+	set_cap(_metadata, CAP_SYS_ADMIN);
+	tracefs_enable_event(TRACEFS_DENY_ACCESS_NET_ENABLE, false);
+	tracefs_fixture_teardown();
+	clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+/*
+ * Baseline: verifies that without Landlock, the bind succeeds and no
+ * deny_access_net trace event fires.
+ */
+/* clang-format off */
+FIXTURE_VARIANT(trace_net)
+{
+	/* clang-format on */
+	bool sandbox;
+	int bind_port_offset; /* 0 = allowed port, 1 = denied port */
+	int expect_denied;
+};
+
+/* Unsandboxed: no Landlock, bind should succeed with no events. */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_net, unsandboxed) {
+	/* clang-format on */
+	.sandbox = false,
+	.bind_port_offset = 0,
+	.expect_denied = 0,
+};
+
+/* Denied: sandboxed, bind to port not in ruleset. */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_net, bind_denied) {
+	/* clang-format on */
+	.sandbox = true,
+	.bind_port_offset = 1,
+	.expect_denied = 1,
+};
+
+/* Allowed: sandboxed, bind to port in ruleset. */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_net, bind_allowed) {
+	/* clang-format on */
+	.sandbox = true,
+	.bind_port_offset = 0,
+	.expect_denied = 0,
+};
+
+TEST_F(trace_net, deny_access_net_bind)
+{
+	char *buf;
+	int count, status;
+	pid_t child;
+
+	if (!self->tracefs_ok)
+		SKIP(return, "tracefs not available");
+
+	ASSERT_EQ(0, tracefs_clear_buf());
+
+	child = fork();
+	ASSERT_LE(0, child);
+
+	if (child == 0) {
+		struct sockaddr_in addr = {
+			.sin_family = AF_INET,
+			.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
+		};
+		int sock_fd;
+
+		if (variant->sandbox) {
+			struct landlock_ruleset_attr ruleset_attr = {
+				.handled_access_net =
+					LANDLOCK_ACCESS_NET_BIND_TCP,
+			};
+			struct landlock_net_port_attr port_attr = {
+				.allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP,
+				.port = sock_port_start,
+			};
+			int ruleset_fd;
+
+			ruleset_fd = landlock_create_ruleset(
+				&ruleset_attr, sizeof(ruleset_attr), 0);
+			if (ruleset_fd < 0)
+				_exit(1);
+
+			if (landlock_add_rule(ruleset_fd,
+					      LANDLOCK_RULE_NET_PORT,
+					      &port_attr, 0)) {
+				close(ruleset_fd);
+				_exit(1);
+			}
+
+			prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+			if (landlock_restrict_self(ruleset_fd, 0)) {
+				close(ruleset_fd);
+				_exit(1);
+			}
+			close(ruleset_fd);
+		}
+
+		sock_fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
+		if (sock_fd < 0)
+			_exit(1);
+
+		addr.sin_port =
+			htons(sock_port_start + variant->bind_port_offset);
+		if (variant->expect_denied) {
+			/* Bind should be denied. */
+			if (bind(sock_fd, (struct sockaddr *)&addr,
+				 sizeof(addr)) == 0) {
+				close(sock_fd);
+				_exit(2);
+			}
+			if (errno != EACCES) {
+				close(sock_fd);
+				_exit(3);
+			}
+		} else {
+			/* Bind should succeed. */
+			if (bind(sock_fd, (struct sockaddr *)&addr,
+				 sizeof(addr))) {
+				close(sock_fd);
+				_exit(2);
+			}
+		}
+		close(sock_fd);
+		_exit(0);
+	}
+
+	ASSERT_EQ(child, waitpid(child, &status, 0));
+	ASSERT_TRUE(WIFEXITED(status));
+	EXPECT_EQ(0, WEXITSTATUS(status));
+
+	buf = tracefs_read_buf();
+	ASSERT_NE(NULL, buf);
+
+	count = tracefs_count_matches(buf, REGEX_DENY_ACCESS_NET(TRACE_TASK));
+	if (variant->expect_denied) {
+		EXPECT_EQ(variant->expect_denied, count)
+		{
+			TH_LOG("Expected deny_access_net event, got %d\n%s",
+			       count, buf);
+		}
+	} else {
+		EXPECT_EQ(0, count)
+		{
+			TH_LOG("Expected 0 deny_access_net events, "
+			       "got %d\n%s",
+			       count, buf);
+		}
+	}
+
+	free(buf);
+}
+
+/*
+ * Anchors the denial fields shared by every deny_access_net event so a field
+ * test proves more than sport/dport: the denying domain, the same-exec bit, the
+ * audit-logging verdict, and the blocked access all stay populated.
+ */
+static void
+expect_net_deny_common_fields(struct __test_metadata *const _metadata,
+			      const char *const buf)
+{
+	char field[64];
+
+	ASSERT_EQ(0,
+		  tracefs_extract_field(buf, REGEX_DENY_ACCESS_NET(TRACE_TASK),
+					"domain", field, sizeof(field)));
+	EXPECT_STRNE("0", field);
+
+	/* Same exec that restricted itself, no exec in between. */
+	ASSERT_EQ(0,
+		  tracefs_extract_field(buf, REGEX_DENY_ACCESS_NET(TRACE_TASK),
+					"same_exec", field, sizeof(field)));
+	EXPECT_STREQ("1", field);
+
+	/* Default flags, same exec: audit would log this denial. */
+	ASSERT_EQ(0,
+		  tracefs_extract_field(buf, REGEX_DENY_ACCESS_NET(TRACE_TASK),
+					"logged", field, sizeof(field)));
+	EXPECT_STREQ("1", field);
+
+	ASSERT_EQ(0,
+		  tracefs_extract_field(buf, REGEX_DENY_ACCESS_NET(TRACE_TASK),
+					"blockers", field, sizeof(field)));
+	EXPECT_STRNE("", field);
+}
+
+/* Connect and field-check tests use a separate fixture without variants. */
+
+/* clang-format off */
+FIXTURE(trace_net_connect) {
+	/* clang-format on */
+	int tracefs_ok;
+};
+
+FIXTURE_SETUP(trace_net_connect)
+{
+	int ret;
+
+	/* Isolate the network namespace so the bound port cannot collide. */
+	setup_loopback(_metadata);
+
+	set_cap(_metadata, CAP_SYS_ADMIN);
+	ASSERT_EQ(0, unshare(CLONE_NEWNS));
+	ASSERT_EQ(0, mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL));
+
+	ret = tracefs_fixture_setup();
+	if (ret) {
+		clear_cap(_metadata, CAP_SYS_ADMIN);
+		self->tracefs_ok = 0;
+		SKIP(return, "tracefs not available");
+	}
+	self->tracefs_ok = 1;
+
+	ASSERT_EQ(0,
+		  tracefs_enable_event(TRACEFS_DENY_ACCESS_NET_ENABLE, true));
+	ASSERT_EQ(0, tracefs_clear());
+	clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+FIXTURE_TEARDOWN(trace_net_connect)
+{
+	if (!self->tracefs_ok)
+		return;
+
+	set_cap(_metadata, CAP_SYS_ADMIN);
+	tracefs_enable_event(TRACEFS_DENY_ACCESS_NET_ENABLE, false);
+	tracefs_fixture_teardown();
+	clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+/*
+ * Verifies that a denied connect emits a deny_access_net trace event with
+ * sport=0 and dport=<denied_port>.
+ */
+TEST_F(trace_net_connect, deny_access_net_connect_denied)
+{
+	pid_t child;
+	int status;
+	char *buf;
+	char field[64], expected[16];
+
+	if (!self->tracefs_ok)
+		SKIP(return, "tracefs not available");
+
+	child = fork();
+	ASSERT_LE(0, child);
+
+	if (child == 0) {
+		struct landlock_ruleset_attr ruleset_attr = {
+			.handled_access_net = LANDLOCK_ACCESS_NET_CONNECT_TCP,
+		};
+		struct landlock_net_port_attr port_attr = {
+			.allowed_access = LANDLOCK_ACCESS_NET_CONNECT_TCP,
+			.port = sock_port_start,
+		};
+		struct sockaddr_in addr = {
+			.sin_family = AF_INET,
+			.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
+		};
+		int ruleset_fd, sock_fd;
+
+		ruleset_fd = landlock_create_ruleset(&ruleset_attr,
+						     sizeof(ruleset_attr), 0);
+		if (ruleset_fd < 0)
+			_exit(1);
+
+		if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
+				      &port_attr, 0)) {
+			close(ruleset_fd);
+			_exit(1);
+		}
+
+		prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+		if (landlock_restrict_self(ruleset_fd, 0)) {
+			close(ruleset_fd);
+			_exit(1);
+		}
+		close(ruleset_fd);
+
+		/* Connect to denied port. */
+		sock_fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
+		if (sock_fd < 0)
+			_exit(1);
+
+		addr.sin_port = htons(sock_port_start + 1);
+		if (connect(sock_fd, (struct sockaddr *)&addr, sizeof(addr)) ==
+		    0) {
+			close(sock_fd);
+			_exit(2);
+		}
+		if (errno != EACCES) {
+			close(sock_fd);
+			_exit(3);
+		}
+		close(sock_fd);
+		_exit(0);
+	}
+
+	ASSERT_EQ(child, waitpid(child, &status, 0));
+	ASSERT_TRUE(WIFEXITED(status));
+	EXPECT_EQ(0, WEXITSTATUS(status));
+
+	buf = tracefs_read_buf();
+	ASSERT_NE(NULL, buf);
+
+	EXPECT_EQ(1, tracefs_count_matches(buf,
+					   REGEX_DENY_ACCESS_NET(TRACE_TASK)));
+
+	expect_net_deny_common_fields(_metadata, buf);
+
+	/*
+	 * Verify dport is the denied port and sport is 0.  The port value must
+	 * be in host endianness, matching the UAPI convention
+	 * (landlock_net_port_attr.port).  On little-endian,
+	 * htons(sock_port_start + 1) would produce a different decimal value,
+	 * so this comparison also catches byte-order bugs.
+	 */
+	ASSERT_EQ(0,
+		  tracefs_extract_field(buf, REGEX_DENY_ACCESS_NET(TRACE_TASK),
+					"sport", field, sizeof(field)));
+	EXPECT_STREQ("0", field);
+
+	ASSERT_EQ(0,
+		  tracefs_extract_field(buf, REGEX_DENY_ACCESS_NET(TRACE_TASK),
+					"dport", field, sizeof(field)));
+	snprintf(expected, sizeof(expected), "%llu",
+		 (unsigned long long)(sock_port_start + 1));
+	EXPECT_STREQ(expected, field);
+
+	free(buf);
+}
+
+/* Verifies that a denied bind emits sport=<port> dport=0. */
+TEST_F(trace_net_connect, deny_access_net_bind_fields)
+{
+	pid_t child;
+	int status;
+	char *buf;
+	char field[64], expected[16];
+
+	if (!self->tracefs_ok)
+		SKIP(return, "tracefs not available");
+
+	child = fork();
+	ASSERT_LE(0, child);
+
+	if (child == 0) {
+		struct landlock_ruleset_attr ruleset_attr = {
+			.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP,
+		};
+		struct landlock_net_port_attr port_attr = {
+			.allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP,
+			.port = sock_port_start,
+		};
+		struct sockaddr_in addr = {
+			.sin_family = AF_INET,
+			.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
+		};
+		int ruleset_fd, sock_fd;
+
+		ruleset_fd = landlock_create_ruleset(&ruleset_attr,
+						     sizeof(ruleset_attr), 0);
+		if (ruleset_fd < 0)
+			_exit(1);
+
+		if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
+				      &port_attr, 0)) {
+			close(ruleset_fd);
+			_exit(1);
+		}
+
+		prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+		if (landlock_restrict_self(ruleset_fd, 0)) {
+			close(ruleset_fd);
+			_exit(1);
+		}
+		close(ruleset_fd);
+
+		/* Bind to denied port. */
+		sock_fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
+		if (sock_fd < 0)
+			_exit(1);
+
+		addr.sin_port = htons(sock_port_start + 1);
+		if (bind(sock_fd, (struct sockaddr *)&addr, sizeof(addr)) ==
+		    0) {
+			close(sock_fd);
+			_exit(2);
+		}
+		if (errno != EACCES) {
+			close(sock_fd);
+			_exit(3);
+		}
+		close(sock_fd);
+		_exit(0);
+	}
+
+	ASSERT_EQ(child, waitpid(child, &status, 0));
+	ASSERT_TRUE(WIFEXITED(status));
+	EXPECT_EQ(0, WEXITSTATUS(status));
+
+	buf = tracefs_read_buf();
+	ASSERT_NE(NULL, buf);
+
+	EXPECT_EQ(1, tracefs_count_matches(buf,
+					   REGEX_DENY_ACCESS_NET(TRACE_TASK)));
+
+	expect_net_deny_common_fields(_metadata, buf);
+
+	/* Verify sport is the denied port and dport is 0. */
+	ASSERT_EQ(0,
+		  tracefs_extract_field(buf, REGEX_DENY_ACCESS_NET(TRACE_TASK),
+					"dport", field, sizeof(field)));
+	EXPECT_STREQ("0", field);
+
+	ASSERT_EQ(0,
+		  tracefs_extract_field(buf, REGEX_DENY_ACCESS_NET(TRACE_TASK),
+					"sport", field, sizeof(field)));
+	snprintf(expected, sizeof(expected), "%llu",
+		 (unsigned long long)(sock_port_start + 1));
+	EXPECT_STREQ(expected, field);
+
+	free(buf);
+}
+
+/*
+ * Verifies that a denied connect after a successful bind shows sport=0 and
+ * dport=<denied_port>.  The bind succeeds (allowed port), then the connect is
+ * denied.  sport=0 because the denied operation is connect, not bind.
+ */
+TEST_F(trace_net_connect, deny_access_net_connect_after_bind)
+{
+	pid_t child;
+	int status;
+	char *buf;
+	char field[64], expected[16];
+
+	if (!self->tracefs_ok)
+		SKIP(return, "tracefs not available");
+
+	child = fork();
+	ASSERT_LE(0, child);
+
+	if (child == 0) {
+		struct landlock_ruleset_attr ruleset_attr = {
+			.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
+					      LANDLOCK_ACCESS_NET_CONNECT_TCP,
+		};
+		struct landlock_net_port_attr port_attr;
+		struct sockaddr_in bind_addr = {
+			.sin_family = AF_INET,
+			.sin_port = htons(sock_port_start),
+			.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
+		};
+		struct sockaddr_in conn_addr = {
+			.sin_family = AF_INET,
+			.sin_port = htons(sock_port_start + 1),
+			.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
+		};
+		int ruleset_fd, sock_fd, optval = 1;
+
+		ruleset_fd = landlock_create_ruleset(&ruleset_attr,
+						     sizeof(ruleset_attr), 0);
+		if (ruleset_fd < 0)
+			_exit(1);
+
+		/* Allow bind and connect on sock_port_start only. */
+		port_attr.allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP |
+					   LANDLOCK_ACCESS_NET_CONNECT_TCP;
+		port_attr.port = sock_port_start;
+		if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
+				      &port_attr, 0)) {
+			close(ruleset_fd);
+			_exit(1);
+		}
+
+		prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+		if (landlock_restrict_self(ruleset_fd, 0)) {
+			close(ruleset_fd);
+			_exit(1);
+		}
+		close(ruleset_fd);
+
+		sock_fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
+		if (sock_fd < 0)
+			_exit(1);
+		setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &optval,
+			   sizeof(optval));
+
+		/* Bind to allowed port (succeeds, no trace event). */
+		if (bind(sock_fd, (struct sockaddr *)&bind_addr,
+			 sizeof(bind_addr))) {
+			close(sock_fd);
+			_exit(1);
+		}
+
+		/* Connect to denied port (fails, emits trace event). */
+		if (connect(sock_fd, (struct sockaddr *)&conn_addr,
+			    sizeof(conn_addr)) == 0) {
+			close(sock_fd);
+			_exit(2);
+		}
+		if (errno != EACCES) {
+			close(sock_fd);
+			_exit(3);
+		}
+		close(sock_fd);
+		_exit(0);
+	}
+
+	ASSERT_EQ(child, waitpid(child, &status, 0));
+	ASSERT_TRUE(WIFEXITED(status));
+	EXPECT_EQ(0, WEXITSTATUS(status));
+
+	buf = tracefs_read_buf();
+	ASSERT_NE(NULL, buf);
+
+	EXPECT_EQ(1, tracefs_count_matches(buf,
+					   REGEX_DENY_ACCESS_NET(TRACE_TASK)));
+
+	expect_net_deny_common_fields(_metadata, buf);
+
+	/*
+	 * The denied operation is connect, so sport=0 and dport=<denied_port>,
+	 * regardless of the prior bind.
+	 */
+	ASSERT_EQ(0,
+		  tracefs_extract_field(buf, REGEX_DENY_ACCESS_NET(TRACE_TASK),
+					"sport", field, sizeof(field)));
+	EXPECT_STREQ("0", field);
+
+	ASSERT_EQ(0,
+		  tracefs_extract_field(buf, REGEX_DENY_ACCESS_NET(TRACE_TASK),
+					"dport", field, sizeof(field)));
+	snprintf(expected, sizeof(expected), "%llu",
+		 (unsigned long long)(sock_port_start + 1));
+	EXPECT_STREQ(expected, field);
+
+	free(buf);
+}
+
+/* Field verification for the check_rule_net event on an allowed access. */
+
+/* clang-format off */
+FIXTURE(trace_net_check_rule) {
+	/* clang-format on */
+	int tracefs_ok;
+};
+
+FIXTURE_SETUP(trace_net_check_rule)
+{
+	int ret;
+
+	/* Isolate the network namespace so the bound port cannot collide. */
+	setup_loopback(_metadata);
+
+	set_cap(_metadata, CAP_SYS_ADMIN);
+	ASSERT_EQ(0, unshare(CLONE_NEWNS));
+	ASSERT_EQ(0, mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL));
+
+	ret = tracefs_fixture_setup();
+	if (ret) {
+		clear_cap(_metadata, CAP_SYS_ADMIN);
+		self->tracefs_ok = 0;
+		SKIP(return, "tracefs not available");
+	}
+	self->tracefs_ok = 1;
+
+	ASSERT_EQ(0, tracefs_enable_event(TRACEFS_CHECK_RULE_NET_ENABLE, true));
+	ASSERT_EQ(0, tracefs_clear());
+	clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+FIXTURE_TEARDOWN(trace_net_check_rule)
+{
+	if (!self->tracefs_ok)
+		return;
+
+	set_cap(_metadata, CAP_SYS_ADMIN);
+	tracefs_enable_event(TRACEFS_CHECK_RULE_NET_ENABLE, false);
+	tracefs_fixture_teardown();
+	clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+/*
+ * Verifies that an allowed bind matching a net-port rule emits exactly one
+ * landlock_check_rule_net event with the enforcing domain, the requested
+ * access, the checked port (host endianness), and the per-layer grants.  The
+ * whole event is anchored to exact values so a revert of the check_rule_net
+ * emit (or a byte-order or field-plumbing regression) fails the test.
+ */
+TEST_F(trace_net_check_rule, check_rule_net_fields)
+{
+	pid_t child;
+	int status;
+	char *buf;
+	char field[64], expected[16];
+
+	if (!self->tracefs_ok)
+		SKIP(return, "tracefs not available");
+
+	child = fork();
+	ASSERT_LE(0, child);
+
+	if (child == 0) {
+		struct landlock_ruleset_attr ruleset_attr = {
+			.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP,
+		};
+		struct landlock_net_port_attr port_attr = {
+			.allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP,
+			.port = sock_port_start,
+		};
+		struct sockaddr_in addr = {
+			.sin_family = AF_INET,
+			.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
+		};
+		int ruleset_fd, sock_fd;
+
+		ruleset_fd = landlock_create_ruleset(&ruleset_attr,
+						     sizeof(ruleset_attr), 0);
+		if (ruleset_fd < 0)
+			_exit(1);
+
+		if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
+				      &port_attr, 0)) {
+			close(ruleset_fd);
+			_exit(1);
+		}
+
+		prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+		if (landlock_restrict_self(ruleset_fd, 0)) {
+			close(ruleset_fd);
+			_exit(1);
+		}
+		close(ruleset_fd);
+
+		/* Bind to the allowed port: succeeds and matches the rule. */
+		sock_fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
+		if (sock_fd < 0)
+			_exit(1);
+
+		addr.sin_port = htons(sock_port_start);
+		if (bind(sock_fd, (struct sockaddr *)&addr, sizeof(addr))) {
+			close(sock_fd);
+			_exit(2);
+		}
+		close(sock_fd);
+		_exit(0);
+	}
+
+	ASSERT_EQ(child, waitpid(child, &status, 0));
+	ASSERT_TRUE(WIFEXITED(status));
+	EXPECT_EQ(0, WEXITSTATUS(status));
+
+	buf = tracefs_read_buf();
+	ASSERT_NE(NULL, buf);
+
+	/* A single-layer domain matching one port rule emits one event. */
+	EXPECT_EQ(1,
+		  tracefs_count_matches(buf, REGEX_CHECK_RULE_NET(TRACE_TASK)))
+	{
+		TH_LOG("Expected 1 check_rule_net event\n%s", buf);
+	}
+
+	ASSERT_EQ(0,
+		  tracefs_extract_field(buf, REGEX_CHECK_RULE_NET(TRACE_TASK),
+					"domain", field, sizeof(field)));
+	EXPECT_STRNE("0", field);
+
+	ASSERT_EQ(0, tracefs_extract_field(
+			     buf, REGEX_CHECK_RULE_NET(TRACE_TASK),
+			     "access_request", field, sizeof(field)));
+	EXPECT_STREQ("bind_tcp", field);
+
+	/*
+	 * The port is reported in host endianness (UAPI convention), so on
+	 * little-endian htons(sock_port_start) would print a different value:
+	 * the exact match also catches byte-order regressions.
+	 */
+	ASSERT_EQ(0,
+		  tracefs_extract_field(buf, REGEX_CHECK_RULE_NET(TRACE_TASK),
+					"port", field, sizeof(field)));
+	snprintf(expected, sizeof(expected), "%llu",
+		 (unsigned long long)sock_port_start);
+	EXPECT_STREQ(expected, field);
+
+	/* One layer that fully grants the request: grants={bind_tcp}. */
+	ASSERT_EQ(0,
+		  tracefs_extract_field(buf, REGEX_CHECK_RULE_NET(TRACE_TASK),
+					"grants", field, sizeof(field)));
+	EXPECT_STREQ("{bind_tcp}", field);
+
+	free(buf);
+}
+
+/*
+ * IPv6 network trace tests are intentionally elided.  IPv6 hook dispatch uses
+ * the same current_check_access_socket() code path as IPv4, validated by the
+ * audit tests in this file.  The trace events use the same blockers/sport/dport
+ * fields regardless of address family.
+ */
+
 TEST_HARNESS_MAIN
Signature · 1 line
2.54.0
author maintainer
#21 lore raw

PATCH v3 18/20 selftests/landlock: Add scope and ptrace tracepoint tests

In reply to Mickaël Salaün

Add trace tests for the landlock_deny_ptrace, landlock_deny_scope_signal, and landlock_deny_scope_abstract_unix_socket tracepoints, each placed alongside the functional tests for its subsystem, mirroring the audit test layout.

Each tracepoint is exercised by a fixture with three variants that pin both branches of the other-party domain field: denied against an unsandboxed other party (other-party domain ID 0), denied against a sandboxed other party (non-zero ID), and an allowed baseline that records no event. A second fixture per type exercises an alternate LSM hook that reaches the same tracepoint with the same other-party domain ID, since each denial type can be reached through more than one hook.

The datagram abstract-unix variant does not assert peer_pid, which is 0 for a datagram peer (no SO_PEERCRED); sun_path is the reliable peer identifier. The ptrace fixtures install a plain domain-creating ruleset rather than a dedicated flag, since ptrace denial relies on domain ancestry, not on a specific scoped flag. The fixtures unshare the mount namespace and remount / as MS_PRIVATE before mounting tracefs so the helper instance is visible only to the test process.

Cc Günther Noack <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Tighten the denied-variant event-count assertion from EXPECT_LE to EXPECT_EQ (a single denied operation against a single-layer domain emits exactly one event), for the signal, abstract-unix-socket, and ptrace fixtures.
- Follow the deny_ptrace printk label rename comm= to the role-prefixed tracee_comm= (the label now matches its sibling tracee_pid= field) in the parsed field name of the ptrace comm assertion (ptrace_test.c).
- Assert the other party's domain ID in the scope and ptrace trace tests (add the per-layer tracee_domain=/target_domain=/peer_domain= fields to REGEX_DENY_PTRACE, REGEX_DENY_SCOPE_SIGNAL, and REGEX_DENY_SCOPE_ABSTRACT_UNIX_SOCKET, then check them) with three variants per fixture: denied against an unsandboxed other party (domain ID 0),
denied against a sandboxed other party (non-zero ID), and an allowed baseline that records no event.
- Cover the alternate LSM hook that reaches each denial tracepoint and sets the same other-party domain ID: hook_file_send_sigiotask via fcntl(F_SETOWN)+SIGIO (trace_fown), hook_unix_may_send via a datagram sendto (trace_unix_dgram), and a denied hook_ptrace_traceme (trace_ptrace_traceme).

Changes since v1:
- New patch.

---
 .../testing/selftests/landlock/ptrace_test.c  | 402 +++++++++++++++
 .../landlock/scoped_abstract_unix_test.c      | 463 ++++++++++++++++++
 .../selftests/landlock/scoped_signal_test.c   | 404 +++++++++++++++
 tools/testing/selftests/landlock/trace.h      |  17 +-
 4 files changed, 1279 insertions(+), 7 deletions(-)
tools/testing/selftests/landlock/ptrace_test.c +402 -0
index 4f64c90583cd..2644445a9d02 100644
@@ -11,7 +11,9 @@
 #include <errno.h>
 #include <fcntl.h>
 #include <linux/landlock.h>
+#include <sched.h>
 #include <signal.h>
+#include <sys/mount.h>
 #include <sys/prctl.h>
 #include <sys/ptrace.h>
 #include <sys/types.h>
@@ -20,6 +22,7 @@
 
 #include "audit.h"
 #include "common.h"
+#include "trace.h"
 
 /* Copied from security/yama/yama_lsm.c */
 #define YAMA_SCOPE_DISABLED 0
@@ -430,4 +433,403 @@ TEST_F(audit, trace)
 	EXPECT_EQ(0, records.domain);
 }
 
+/* Trace tests */
+
+/* clang-format off */
+FIXTURE(trace_ptrace) {
+	/* clang-format on */
+	int tracefs_ok;
+};
+
+FIXTURE_SETUP(trace_ptrace)
+{
+	int ret;
+
+	set_cap(_metadata, CAP_SYS_ADMIN);
+	ASSERT_EQ(0, unshare(CLONE_NEWNS));
+	ASSERT_EQ(0, mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL));
+
+	ret = tracefs_fixture_setup();
+	if (ret) {
+		clear_cap(_metadata, CAP_SYS_ADMIN);
+		self->tracefs_ok = 0;
+		SKIP(return, "tracefs not available");
+	}
+	self->tracefs_ok = 1;
+
+	ASSERT_EQ(0, tracefs_enable_event(TRACEFS_DENY_PTRACE_ENABLE, true));
+	ASSERT_EQ(0, tracefs_clear());
+	clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+FIXTURE_TEARDOWN(trace_ptrace)
+{
+	if (!self->tracefs_ok)
+		return;
+
+	set_cap(_metadata, CAP_SYS_ADMIN);
+	tracefs_enable_event(TRACEFS_DENY_PTRACE_ENABLE, false);
+	tracefs_fixture_teardown();
+	clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+/* clang-format off */
+FIXTURE_VARIANT(trace_ptrace)
+{
+	/* clang-format on */
+	bool sandbox;
+	bool sandbox_target;
+	int expect_denied;
+};
+
+/* Denied: sandboxed child ptraces unsandboxed parent (tracee_domain=0). */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_ptrace, denied) {
+	/* clang-format on */
+	.sandbox = true,
+	.sandbox_target = false,
+	.expect_denied = 1,
+};
+
+/*
+ * Denied: sandboxed child ptraces a sandboxed parent, so the tracee is in a
+ * domain and tracee_domain= is non-zero.
+ */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_ptrace, denied_scoped_target) {
+	/* clang-format on */
+	.sandbox = true,
+	.sandbox_target = true,
+	.expect_denied = 1,
+};
+
+/* Allowed: unsandboxed child uses PTRACE_TRACEME. */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_ptrace, allowed) {
+	/* clang-format on */
+	.sandbox = false,
+	.sandbox_target = false,
+	.expect_denied = 0,
+};
+
+TEST_F(trace_ptrace, deny_ptrace)
+{
+	char *buf, field[64], expected_pid[16];
+	int count, status;
+	pid_t child, parent;
+
+	if (!self->tracefs_ok)
+		SKIP(return, "tracefs not available");
+
+	parent = getpid();
+
+	/*
+	 * Set a known comm so the denied variant can verify both the trace line
+	 * task name and the tracee_comm= field.
+	 */
+	prctl(PR_SET_NAME, "ll_trace_test");
+
+	/*
+	 * For the non-zero tracee_domain case, sandbox the parent (the tracee)
+	 * before forking.  The child inherits that domain and adds its own
+	 * layer, so the child (tracer) is not an ancestor of the tracee and the
+	 * ptrace is still denied, with tracee_domain= naming the parent's
+	 * domain.
+	 */
+	if (variant->sandbox_target)
+		create_domain(_metadata);
+
+	child = fork();
+	ASSERT_LE(0, child);
+
+	if (child == 0) {
+		if (variant->sandbox) {
+			struct landlock_ruleset_attr ruleset_attr = {
+				.scoped = LANDLOCK_SCOPE_SIGNAL,
+			};
+			int ruleset_fd;
+
+			/*
+			 * Any scope creates a domain.  Ptrace denial checks
+			 * domain ancestry, not specific flags.
+			 */
+			ruleset_fd = landlock_create_ruleset(
+				&ruleset_attr, sizeof(ruleset_attr), 0);
+			if (ruleset_fd < 0)
+				_exit(1);
+
+			prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+			if (landlock_restrict_self(ruleset_fd, 0)) {
+				close(ruleset_fd);
+				_exit(1);
+			}
+			close(ruleset_fd);
+
+			/* PTRACE_ATTACH on unsandboxed parent: denied. */
+			if (ptrace(PTRACE_ATTACH, parent, NULL, NULL) == 0) {
+				ptrace(PTRACE_DETACH, parent, NULL, NULL);
+				_exit(2);
+			}
+			if (errno != EPERM)
+				_exit(3);
+		} else {
+			/* No sandbox: ptrace should succeed. */
+			if (ptrace(PTRACE_TRACEME) != 0)
+				_exit(1);
+		}
+
+		_exit(0);
+	}
+
+	ASSERT_EQ(child, waitpid(child, &status, 0));
+	ASSERT_TRUE(WIFEXITED(status));
+	EXPECT_EQ(0, WEXITSTATUS(status));
+
+	buf = tracefs_read_buf();
+	ASSERT_NE(NULL, buf);
+
+	count = tracefs_count_matches(buf, REGEX_DENY_PTRACE("ll_trace_test"));
+	if (variant->expect_denied) {
+		EXPECT_EQ(variant->expect_denied, count)
+		{
+			TH_LOG("Expected deny_ptrace event, got %d\n%s", count,
+			       buf);
+		}
+
+		/* Verify tracee_pid is the parent's TGID. */
+		snprintf(expected_pid, sizeof(expected_pid), "%d", parent);
+		ASSERT_EQ(0, tracefs_extract_field(
+				     buf, REGEX_DENY_PTRACE("ll_trace_test"),
+				     "tracee_pid", field, sizeof(field)));
+		EXPECT_STREQ(expected_pid, field);
+
+		/* Verify tracee_comm matches prctl(PR_SET_NAME). */
+		ASSERT_EQ(0, tracefs_extract_field(
+				     buf, REGEX_DENY_PTRACE("ll_trace_test"),
+				     "tracee_comm", field, sizeof(field)));
+		EXPECT_STREQ("ll_trace_test", field);
+
+		/*
+		 * Verify tracee_domain: 0 when the tracee is unsandboxed,
+		 * non-zero when the tracee is in a domain.
+		 */
+		ASSERT_EQ(0, tracefs_extract_field(
+				     buf, REGEX_DENY_PTRACE("ll_trace_test"),
+				     "tracee_domain", field, sizeof(field)));
+		EXPECT_EQ(variant->sandbox_target, strcmp("0", field) != 0)
+		{
+			TH_LOG("Unexpected tracee_domain=%s", field);
+		}
+	} else {
+		EXPECT_EQ(0, count)
+		{
+			TH_LOG("Expected 0 deny_ptrace events, got %d\n%s",
+			       count, buf);
+		}
+	}
+
+	free(buf);
+}
+
+/* clang-format off */
+FIXTURE(trace_ptrace_traceme) {
+	/* clang-format on */
+	int tracefs_ok;
+};
+
+FIXTURE_SETUP(trace_ptrace_traceme)
+{
+	int ret;
+
+	set_cap(_metadata, CAP_SYS_ADMIN);
+	ASSERT_EQ(0, unshare(CLONE_NEWNS));
+	ASSERT_EQ(0, mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL));
+
+	ret = tracefs_fixture_setup();
+	if (ret) {
+		clear_cap(_metadata, CAP_SYS_ADMIN);
+		self->tracefs_ok = 0;
+		SKIP(return, "tracefs not available");
+	}
+	self->tracefs_ok = 1;
+
+	ASSERT_EQ(0, tracefs_enable_event(TRACEFS_DENY_PTRACE_ENABLE, true));
+	ASSERT_EQ(0, tracefs_clear());
+	clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+FIXTURE_TEARDOWN(trace_ptrace_traceme)
+{
+	if (!self->tracefs_ok)
+		return;
+
+	set_cap(_metadata, CAP_SYS_ADMIN);
+	tracefs_enable_event(TRACEFS_DENY_PTRACE_ENABLE, false);
+	tracefs_fixture_teardown();
+	clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+/* clang-format off */
+FIXTURE_VARIANT(trace_ptrace_traceme)
+{
+	/* clang-format on */
+	bool sandbox_tracer;
+	bool sandbox_tracee;
+	int expect_denied;
+};
+
+/*
+ * Denied: a sandboxed tracer cannot trace the unsandboxed child that asked to
+ * be traced with PTRACE_TRACEME (tracee_domain=0).
+ */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_ptrace_traceme, denied) {
+	/* clang-format on */
+	.sandbox_tracer = true,
+	.sandbox_tracee = false,
+	.expect_denied = 1,
+};
+
+/*
+ * Denied: a sandboxed child in its own domain asks to be traced by a tracer in
+ * an unrelated domain, so the tracee is in a domain and tracee_domain= is
+ * non-zero.
+ */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_ptrace_traceme, denied_scoped_tracee) {
+	/* clang-format on */
+	.sandbox_tracer = true,
+	.sandbox_tracee = true,
+	.expect_denied = 1,
+};
+
+/* Allowed: unsandboxed child uses PTRACE_TRACEME with an unsandboxed tracer. */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_ptrace_traceme, allowed) {
+	/* clang-format on */
+	.sandbox_tracer = false,
+	.sandbox_tracee = false,
+	.expect_denied = 0,
+};
+
+TEST_F(trace_ptrace_traceme, deny_ptrace)
+{
+	char *buf, field[64], expected_pid[16];
+	int count, status, sync_pipe[2];
+	pid_t child;
+
+	if (!self->tracefs_ok)
+		SKIP(return, "tracefs not available");
+
+	/*
+	 * Set a known comm so the denied variant can verify both the trace line
+	 * task name and the tracee_comm= field.  The tracee is the current
+	 * (child) task for PTRACE_TRACEME, so the child inherits this name.
+	 */
+	prctl(PR_SET_NAME, "ll_trace_test");
+
+	ASSERT_EQ(0, pipe2(sync_pipe, O_CLOEXEC));
+
+	child = fork();
+	ASSERT_LE(0, child);
+
+	if (child == 0) {
+		char c;
+
+		close(sync_pipe[1]);
+
+		/*
+		 * The tracee is the current task; for the non-zero
+		 * tracee_domain case it sandboxes itself in its own domain,
+		 * unrelated to the tracer's domain, so PTRACE_TRACEME is still
+		 * denied and tracee_domain= names the child's own domain.
+		 */
+		if (variant->sandbox_tracee)
+			create_domain(_metadata);
+
+		/* Waits for the tracer (parent) to enter its domain, if any. */
+		if (read(sync_pipe[0], &c, 1) != 1)
+			_exit(1);
+		close(sync_pipe[0]);
+
+		if (variant->expect_denied) {
+			if (ptrace(PTRACE_TRACEME) == 0)
+				_exit(2);
+			if (errno != EPERM)
+				_exit(3);
+		} else {
+			if (ptrace(PTRACE_TRACEME) != 0)
+				_exit(4);
+			/* Lets the tracer reap the trace-stop and detach. */
+			raise(SIGSTOP);
+		}
+
+		_exit(0);
+	}
+
+	close(sync_pipe[0]);
+
+	/*
+	 * For a denial, the proposed tracer must be in a domain that is not an
+	 * ancestor of the tracee's domain.  Sandboxing the parent after the
+	 * fork gives it a domain unrelated to the child.
+	 */
+	if (variant->sandbox_tracer)
+		create_domain(_metadata);
+
+	/* Signals the child that the tracer is in its domain, if any. */
+	ASSERT_EQ(1, write(sync_pipe[1], ".", 1));
+	close(sync_pipe[1]);
+
+	if (!variant->expect_denied) {
+		/* PTRACE_TRACEME succeeded: reap the SIGSTOP and detach. */
+		ASSERT_EQ(child, waitpid(child, &status, WUNTRACED));
+		ASSERT_TRUE(WIFSTOPPED(status));
+		ASSERT_EQ(0, ptrace(PTRACE_DETACH, child, NULL, 0));
+	}
+
+	ASSERT_EQ(child, waitpid(child, &status, 0));
+	ASSERT_TRUE(WIFEXITED(status));
+	EXPECT_EQ(0, WEXITSTATUS(status));
+
+	buf = tracefs_read_buf();
+	ASSERT_NE(NULL, buf);
+
+	count = tracefs_count_matches(buf, REGEX_DENY_PTRACE("ll_trace_test"));
+	if (variant->expect_denied) {
+		EXPECT_EQ(variant->expect_denied, count)
+		{
+			TH_LOG("Expected deny_ptrace event, got %d\n%s", count,
+			       buf);
+		}
+
+		/* Verify tracee_pid is the child's TGID (the traced task). */
+		snprintf(expected_pid, sizeof(expected_pid), "%d", child);
+		ASSERT_EQ(0, tracefs_extract_field(
+				     buf, REGEX_DENY_PTRACE("ll_trace_test"),
+				     "tracee_pid", field, sizeof(field)));
+		EXPECT_STREQ(expected_pid, field);
+
+		/*
+		 * Verify tracee_domain: 0 when the tracee is unsandboxed,
+		 * non-zero when the tracee is in a domain.
+		 */
+		ASSERT_EQ(0, tracefs_extract_field(
+				     buf, REGEX_DENY_PTRACE("ll_trace_test"),
+				     "tracee_domain", field, sizeof(field)));
+		EXPECT_EQ(variant->sandbox_tracee, strcmp("0", field) != 0)
+		{
+			TH_LOG("Unexpected tracee_domain=%s", field);
+		}
+	} else {
+		EXPECT_EQ(0, count)
+		{
+			TH_LOG("Expected 0 deny_ptrace events, got %d\n%s",
+			       count, buf);
+		}
+	}
+
+	free(buf);
+}
+
 TEST_HARNESS_MAIN
tools/testing/selftests/landlock/scoped_abstract_unix_test.c +463 -0

479 lines not on this page · raw message

tools/testing/selftests/landlock/scoped_signal_test.c +404 -0

421 lines not on this page · raw message

tools/testing/selftests/landlock/trace.h +10 -7
index 31f17b43e9f4..e03c689ef398 100644
@@ -146,13 +146,14 @@
 	"sport=[0-9]\\+ "            \
 	"dport=[0-9]\\+$"
 
-#define REGEX_DENY_PTRACE(task)  \
-	TRACE_PREFIX(task)       \
-	"landlock_deny_ptrace: " \
-	"domain=[0-9a-f]\\+ "    \
-	"same_exec=[01] "        \
-	"logged=[01] "           \
-	"tracee_pid=[0-9]\\+ "   \
+#define REGEX_DENY_PTRACE(task)      \
+	TRACE_PREFIX(task)           \
+	"landlock_deny_ptrace: "     \
+	"domain=[0-9a-f]\\+ "        \
+	"same_exec=[01] "            \
+	"logged=[01] "               \
+	"tracee_domain=[0-9a-f]\\+ " \
+	"tracee_pid=[0-9]\\+ "       \
 	"tracee_comm=[^ ]*$"
 
 #define REGEX_DENY_SCOPE_SIGNAL(task)  \
@@ -161,6 +162,7 @@
 	"domain=[0-9a-f]\\+ "          \
 	"same_exec=[01] "              \
 	"logged=[01] "                 \
+	"target_domain=[0-9a-f]\\+ "   \
 	"target_pid=[0-9]\\+ "         \
 	"target_comm=[^ ]*$"
 
@@ -170,6 +172,7 @@
 	"domain=[0-9a-f]\\+ "                        \
 	"same_exec=[01] "                            \
 	"logged=[01] "                               \
+	"peer_domain=[0-9a-f]\\+ "                   \
 	"peer_pid=[0-9]\\+ "                         \
 	"sun_path=[^ ]*$"
 
Signature · 1 line
2.54.0
author maintainer
#22 lore raw

PATCH v3 19/20 selftests/landlock: Add landlock_enforce_domain trace tests

In reply to Mickaël Salaün

Add trace tests for the landlock_enforce_domain event in trace_test.c, asserting field counts after the syscall returns rather than line ordering across per-CPU buffers. They cover single-threaded and TSYNC enforcement (complete and process_wide set), a multi-threaded non-TSYNC process (process_wide clear), the single-threaded non-leader edge case, the flags-only path that creates no domain, and a thread-sync abort that emits create_domain and free_domain but no enforce_domain.

landlock_enforce_domain is added to the fixture enable path and every disable list so its zero-events assertions cannot be tripped by a stray enforcement event.

Test coverage for security/landlock is 91.6% of 2552 lines according to LLVM 22.

Cc Günther Noack <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
- New patch.

---
 tools/testing/selftests/landlock/trace.h      |   9 +
 tools/testing/selftests/landlock/trace_test.c | 522 ++++++++++++++++++
 2 files changed, 531 insertions(+)
tools/testing/selftests/landlock/trace.h +9 -0
index e03c689ef398..9e901823ddaf 100644
@@ -25,6 +25,8 @@
 	TRACEFS_LANDLOCK_DIR "/landlock_create_ruleset/enable"
 #define TRACEFS_CREATE_DOMAIN_ENABLE \
 	TRACEFS_LANDLOCK_DIR "/landlock_create_domain/enable"
+#define TRACEFS_ENFORCE_DOMAIN_ENABLE \
+	TRACEFS_LANDLOCK_DIR "/landlock_enforce_domain/enable"
 #define TRACEFS_ADD_RULE_FS_ENABLE \
 	TRACEFS_LANDLOCK_DIR "/landlock_add_rule_fs/enable"
 #define TRACEFS_ADD_RULE_NET_ENABLE \
@@ -108,6 +110,13 @@
 	"parent=[0-9a-f]\\+ "      \
 	"ruleset=[0-9a-f]\\+\\.[0-9]\\+$"
 
+#define REGEX_ENFORCE_DOMAIN(task)  \
+	TRACE_PREFIX(task)          \
+	"landlock_enforce_domain: " \
+	"domain=[0-9a-f]\\+ "       \
+	"complete=[01] "            \
+	"process_wide=[01]$"
+
 #define REGEX_CHECK_RULE_FS(task)  \
 	TRACE_PREFIX(task)         \
 	"landlock_check_rule_fs: " \
tools/testing/selftests/landlock/trace_test.c +522 -0

552 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#23 lore raw

PATCH v3 20/20 landlock: Document tracepoints

In reply to Mickaël Salaün

Until now, Landlock observability documentation covered only audit records. The tracepoints added by the previous commits introduce a second channel with different semantics (firing regardless of audit configuration and domain log flags, exposing the full ruleset and domain state to eBPF via BTF), which kernel developers, administrators, and userspace tool authors need to discover and compare against audit.

Add a dedicated "Landlock Trace Events" reference covering the event categories, enabling events via tracefs, ruleset versioning, eBPF access through BPF_RAW_TRACEPOINT, and the same_exec and logged denial fields (logged being the kernel's audit-logging decision, so a stateless ftrace filter can select the denials audit would record with logged==1). Cross-reference it from the administrator, kernel-internals, and userspace API documents, contrasting tracepoints with audit: when each channel is preferred, what each guarantees, and how NOAUDIT hooks and audit rate limiting affect them.

Also document the relational other-party domain fields the scope and ptrace denial tracepoints expose (tracee_domain, target_domain, peer_domain; 0 when the other party is unsandboxed), so a consumer can resolve them against the lifecycle events and reproduce the two-domain verdict.

Cc Günther Noack <[email protected]>
Cc Tingmao Wang <[email protected]>

---

Changes since v2:
https://patch.msgid.link/[email protected]
- Renamed the restrict_self event references to create_domain.
- Documented the landlock_enforce_domain event.
- De-duplicate the trace documentation so each fact lives in one place:
keep the shared audit-vs-trace observability material (when to use each, guarantees and limitations, security considerations) in the admin guide, move the worked event samples and the stateful-eBPF recipe to the trace event reference, and replace the admin guide's per-event detail with a pointer to that reference.
- Describe audit and trace field labels behaviorally in the admin guide:
drop the CONFIG_AUDIT symbol and the TP_printk macro name in favor of "built with audit support" and "trace output labels".
- Updated RST dates to July 2026.
- Regenerate the sample trace output with symbolic access-right names and rewrite the hex-mask rationale passage.
- Document that the denial events' logged field is the audit-logging verdict, the same regardless of whether the kernel is built with audit support, and that a quiet rule sets logged=0.
- Add an "Interpreting check_rule events" section explaining the per-layer grants= format.
- Rename "log flags" to "Landlock log flags" with a cross-reference to the userspace-api definition.
- Follow the trace-event label renames: the check_rule label request= becomes access_request= (trace-only field, label equals field) in the interpretation text and the example trace lines, and the ptrace and signal process-name label comm= becomes the role-prefixed tracee_comm= and target_comm= (each matching its sibling *_pid). Audit-shared labels (domain=, ruleset=) and grants= are unchanged.
- Document the relational other-party domain trace fields (tracee_domain=/target_domain=/peer_domain=, 0 when the other party is unsandboxed) in the audit-differences section, framed as the decision context a consumer
resolves against the lifecycle events to verify or reproduce the two-domain scope or ptrace verdict.
- Correct the eBPF-BTF sensitivity note: describe the access as exposing sensitive per-sandbox state to be restricted to trusted users, instead of the inaccurate claim that it is comparable to CAP_SYS_ADMIN.

Changes since v1:
- New patch.

---
 Documentation/admin-guide/LSM/landlock.rst | 105 ++++++-
 Documentation/security/landlock.rst        |  38 ++-
 Documentation/trace/events-landlock.rst    | 313 +++++++++++++++++++++
 Documentation/trace/index.rst              |   1 +
 Documentation/userspace-api/landlock.rst   |  14 +-
 MAINTAINERS                                |   1 +
 6 files changed, 467 insertions(+), 5 deletions(-)
 create mode 100644 Documentation/trace/events-landlock.rst
Documentation/admin-guide/LSM/landlock.rst +104 -1
index 314052bbeb0a..1e4bc9fdc0a0 100644
@@ -1,12 +1,13 @@
 .. SPDX-License-Identifier: GPL-2.0
 .. Copyright © 2025 Microsoft Corporation
+.. Copyright © 2026 Cloudflare, Inc.
 
 ================================
 Landlock: system-wide management
 ================================
 
 :Author: Mickaël Salaün
-:Date: June 2026
+:Date: July 2026
 
 Landlock can leverage the audit framework to log events.
 
@@ -181,11 +182,113 @@ filters to limit noise with two complementary ways:
   programs,
 - or with audit rules (see :manpage:`auditctl(8)`).
 
+Tracepoints
+===========
+
+Landlock also provides tracepoints as an alternative to audit for
+debugging and observability.  Tracepoints fire unconditionally,
+independent of audit configuration, ``audit_enabled``, and domain log
+flags.  This makes them suitable for always-on monitoring with eBPF or
+for ad-hoc debugging with ``trace-pipe``.
+
+See Documentation/trace/events-landlock.rst for the complete event
+reference: the full event list, how to enable events and read their
+output, the field formats, the ``check_rule`` interpretation guide,
+worked event samples, ftrace filtering, and eBPF access.
+
+.. _landlock_observability:
+
+When to use tracing vs audit
+-----------------------------
+
+Audit and tracing both help diagnose Landlock policy issues:
+
+**Audit** records denied accesses with the blockers, domain, and object
+identification (path, port).  Audit is the standard Linux mechanism for
+security events, with a stable record format that is well established
+and already supported by log management systems, SIEM platforms, and EDR
+solutions.  Audit is always active when the kernel is built with audit
+support, filtered by the Landlock log flags to reduce noise in
+production, and designed for long-term security monitoring and
+compliance.
+
+**Tracing** provides deeper introspection for policy debugging.  In
+addition to denied accesses, trace events cover the complete lifecycle
+of Landlock objects (rulesets, domains) and intermediate rule matching
+during access checks.  Trace events are disabled by default (zero
+overhead) and fire unconditionally.  eBPF
+programs attached to trace events can access the full kernel context
+(ruleset rules, domain hierarchy, process credentials) via BTF, enabling
+richer analysis than the flat fields in audit records.  For example, an
+eBPF-based live monitoring tool can correlate creation, rule-addition,
+and denial events to build a real-time view of all active Landlock
+domains and their policies.  However, BTF-based access depends on
+internal kernel struct layouts which have no stability guarantee.  CO-RE
+(Compile Once, Run Everywhere) provides best-effort field relocation.
+The ftrace printk format is also not a stable ABI, but is
+self-describing via the per-event ``format`` file, allowing tools to
+adapt dynamically.
+
+Observability guarantees and limitations
+-----------------------------------------
+
+Both audit records and trace events are emitted for every denied access,
+with these exceptions:
+
+- **Landlock log flags** (audit only): ``LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF``,
+  ``LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON``, and
+  ``LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF`` control which denials
+  generate audit records.  Trace events fire regardless of these flags.
+
+- **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
+  ``denials``.  The denial is still enforced.  This avoids performance
+  overhead and noise from speculative probes that test permissions
+  without performing an actual access.
+
+- **Audit rate limiting**: The audit subsystem may silently drop records
+  when the audit queue is full.  Trace events are not rate-limited.
+
+- **Tracepoint disabled**: When a trace event is disabled (the default
+  state), the tracepoint is a no-op with zero overhead.
+
+When both audit and tracing are active, every denial emits a trace event,
+and a denial that the domain's log policy selects additionally produces an
+audit record (subject to the Landlock log flags).  The ``denials`` count in
+``free_domain`` events is incremented for every denial regardless of the
+log flags, so it can exceed the number of audit records (which the log
+flags and audit-side rate-limiting or exclude rules may suppress).
+
+.. _landlock_observability_security:
+
+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
+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
+trusted users.
+
+eBPF programs attached to Landlock trace events have access to the full
+kernel context of each event (ruleset rules, domain hierarchy, process
+credentials) via BTF, exposing sensitive state about every sandboxed
+process.  Restrict this access to trusted users, as for the audit logs.
+
+Audit logs and kernel trace events require elevated privileges and are
+system-wide; they are not designed for per-sandbox unprivileged
+monitoring.
+
 Additional documentation
 ========================
 
 * `Linux Audit Documentation`_
 * Documentation/userspace-api/landlock.rst
+* Documentation/trace/events-landlock.rst
 * Documentation/security/landlock.rst
 * https://landlock.io
 
Documentation/security/landlock.rst +37 -1
index c5186526e76f..6b5075f4d501 100644
@@ -1,13 +1,14 @@
 .. SPDX-License-Identifier: GPL-2.0
 .. Copyright © 2017-2020 Mickaël Salaün <[email protected]>
 .. Copyright © 2019-2020 ANSSI
+.. Copyright © 2026 Cloudflare, Inc.
 
 ==================================
 Landlock LSM: kernel documentation
 ==================================
 
 :Author: Mickaël Salaün
-:Date: March 2026
+:Date: July 2026
 
 Landlock's goal is to create scoped access-control (i.e. sandboxing).  To
 harden a whole system, this feature should be available to any process,
@@ -177,11 +178,46 @@ makes the reasoning much easier and helps avoid pitfalls.
 .. kernel-doc:: security/landlock/domain.h
     :identifiers:
 
+Denial logging
+==============
+
+Access denials are logged through two independent channels: audit
+records and tracepoints.  Both are managed by the common denial
+framework in ``log.c``, compiled under ``CONFIG_SECURITY_LANDLOCK_LOG``
+(automatically selected by ``CONFIG_AUDIT`` or ``CONFIG_TRACEPOINTS``).
+
+Audit records respect audit configuration, the domain's Landlock log
+flags, and ``LANDLOCK_LOG_DISABLED``.  Tracepoints fire unconditionally,
+independent of these settings.  The denial counter (``num_denials``) is
+always incremented regardless of logging configuration.
+
+Each denial tracepoint carries a ``logged`` field reporting the
+audit-logging verdict: whether the denial would be written to the audit
+log if audit were configured and active.  This verdict is the same
+whether or not the kernel is built with audit support, so a
+tracepoints-only build reports the selection audit would make.  A quiet
+rule (``LANDLOCK_ADD_RULE_QUIET`` with the access in the ``quiet_*``
+fields of ``struct landlock_ruleset_attr``) suppresses logging by
+setting ``logged=0`` the same way.
+
+See Documentation/admin-guide/LSM/landlock.rst for audit record format,
+tracepoint usage, and filtering examples.
+
+.. kernel-doc:: security/landlock/log.h
+    :identifiers:
+
+Trace events
+------------
+
+See Documentation/trace/events-landlock.rst for trace event usage and format
+details; the full event reference lives there and is not duplicated here.
+
 Additional documentation
 ========================
 
 * Documentation/userspace-api/landlock.rst
 * Documentation/admin-guide/LSM/landlock.rst
+* Documentation/trace/events-landlock.rst
 * https://landlock.io
 
 .. Links
Documentation/trace/events-landlock.rst new file +313 -0

313 lines not on this page · raw message

Documentation/trace/index.rst +1 -0
index 5d9bf4694d5d..f4058e8e92e3 100644
@@ -54,6 +54,7 @@ applications.
    events-power
    events-nmi
    events-msr
+   events-landlock
    events-pci
    events-pci-controller
    boottime-trace
Documentation/userspace-api/landlock.rst +11 -3
index 5a63d4476c1c..af625b7becf9 100644
@@ -8,7 +8,7 @@ Landlock: unprivileged access control
 =====================================
 
 :Author: Mickaël Salaün
-:Date: June 2026
+:Date: July 2026
 
 The goal of Landlock is to enable restriction of ambient rights (e.g. global
 filesystem or network access) for a set of processes.  Because Landlock
@@ -737,6 +737,8 @@ Starting with the Landlock ABI version 6, it is possible to restrict
 :manpage:`signal(7)` sending by setting ``LANDLOCK_SCOPE_SIGNAL`` to the
 ``scoped`` ruleset attribute.
 
+.. _landlock_log_flags:
+
 Logging (ABI < 7)
 -----------------
 
@@ -744,8 +746,13 @@ Starting with the Landlock ABI version 7, it is possible to control logging of
 Landlock audit events with the ``LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF``,
 ``LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON``, and
 ``LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF`` flags passed to
-sys_landlock_restrict_self().  See Documentation/admin-guide/LSM/landlock.rst
-for more details on audit.
+sys_landlock_restrict_self().  These flags control audit record generation.
+Landlock tracepoints are not affected by these flags and always fire when
+enabled, providing an alternative observability channel for debugging and
+monitoring.  See Documentation/admin-guide/LSM/landlock.rst for more
+details on audit and tracepoints, and
+Documentation/trace/events-landlock.rst for the complete trace event
+reference.
 
 Thread synchronization (ABI < 8)
 --------------------------------
@@ -887,6 +894,7 @@ Additional documentation
 ========================
 
 * Documentation/admin-guide/LSM/landlock.rst
+* Documentation/trace/events-landlock.rst
 * Documentation/security/landlock.rst
 * https://landlock.io
 
MAINTAINERS +1 -0
index ca41aec9993c..866763cab9b7 100644
@@ -14596,6 +14596,7 @@ W:	https://landlock.io
 T:	git https://git.kernel.org/pub/scm/linux/kernel/git/mic/linux.git
 F:	Documentation/admin-guide/LSM/landlock.rst
 F:	Documentation/security/landlock.rst
+F:	Documentation/trace/events-landlock.rst
 F:	Documentation/userspace-api/landlock.rst
 F:	fs/ioctl.c
 F:	include/linux/landlock.h
Signature · 1 line
2.54.0